1 /*
   2  * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classLoader.hpp"
  27 #include "classfile/javaAssertions.hpp"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "code/codeCacheExtensions.hpp"
  31 #include "gc/shared/cardTableRS.hpp"
  32 #include "gc/shared/genCollectedHeap.hpp"
  33 #include "gc/shared/referenceProcessor.hpp"
  34 #include "gc/shared/taskqueue.hpp"
  35 #include "logging/log.hpp"
  36 #include "logging/logConfiguration.hpp"
  37 #include "logging/logStream.hpp"
  38 #include "logging/logTag.hpp"
  39 #include "memory/allocation.inline.hpp"
  40 #include "memory/universe.inline.hpp"
  41 #include "oops/oop.inline.hpp"
  42 #include "prims/jvmtiExport.hpp"
  43 #include "runtime/arguments.hpp"
  44 #include "runtime/arguments_ext.hpp"
  45 #include "runtime/commandLineFlagConstraintList.hpp"
  46 #include "runtime/commandLineFlagWriteableList.hpp"
  47 #include "runtime/commandLineFlagRangeList.hpp"
  48 #include "runtime/globals.hpp"
  49 #include "runtime/globals_extension.hpp"
  50 #include "runtime/java.hpp"
  51 #include "runtime/os.hpp"
  52 #include "runtime/vm_version.hpp"
  53 #include "services/management.hpp"
  54 #include "services/memTracker.hpp"
  55 #include "utilities/defaultStream.hpp"
  56 #include "utilities/macros.hpp"
  57 #include "utilities/stringUtils.hpp"
  58 #if INCLUDE_JVMCI
  59 #include "jvmci/jvmciRuntime.hpp"
  60 #endif
  61 #if INCLUDE_ALL_GCS
  62 #include "gc/cms/compactibleFreeListSpace.hpp"
  63 #include "gc/g1/g1CollectedHeap.inline.hpp"
  64 #include "gc/parallel/parallelScavengeHeap.hpp"
  65 #endif // INCLUDE_ALL_GCS
  66 
  67 // Note: This is a special bug reporting site for the JVM
  68 #define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
  69 #define DEFAULT_JAVA_LAUNCHER  "generic"
  70 
  71 char*  Arguments::_jvm_flags_file               = NULL;
  72 char** Arguments::_jvm_flags_array              = NULL;
  73 int    Arguments::_num_jvm_flags                = 0;
  74 char** Arguments::_jvm_args_array               = NULL;
  75 int    Arguments::_num_jvm_args                 = 0;
  76 char*  Arguments::_java_command                 = NULL;
  77 SystemProperty* Arguments::_system_properties   = NULL;
  78 const char*  Arguments::_gc_log_filename        = NULL;
  79 bool   Arguments::_has_profile                  = false;
  80 size_t Arguments::_conservative_max_heap_alignment = 0;
  81 size_t Arguments::_min_heap_size                = 0;
  82 Arguments::Mode Arguments::_mode                = _mixed;
  83 bool   Arguments::_java_compiler                = false;
  84 bool   Arguments::_xdebug_mode                  = false;
  85 const char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
  86 const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
  87 int    Arguments::_sun_java_launcher_pid        = -1;
  88 bool   Arguments::_sun_java_launcher_is_altjvm  = false;
  89 
  90 // These parameters are reset in method parse_vm_init_args()
  91 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
  92 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
  93 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
  94 bool   Arguments::_ClipInlining                 = ClipInlining;
  95 intx   Arguments::_Tier3InvokeNotifyFreqLog     = Tier3InvokeNotifyFreqLog;
  96 intx   Arguments::_Tier4InvocationThreshold     = Tier4InvocationThreshold;
  97 
  98 char*  Arguments::SharedArchivePath             = NULL;
  99 
 100 AgentLibraryList Arguments::_libraryList;
 101 AgentLibraryList Arguments::_agentList;
 102 
 103 abort_hook_t     Arguments::_abort_hook         = NULL;
 104 exit_hook_t      Arguments::_exit_hook          = NULL;
 105 vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
 106 
 107 
 108 SystemProperty *Arguments::_sun_boot_library_path = NULL;
 109 SystemProperty *Arguments::_java_library_path = NULL;
 110 SystemProperty *Arguments::_java_home = NULL;
 111 SystemProperty *Arguments::_java_class_path = NULL;
 112 SystemProperty *Arguments::_jdk_boot_class_path_append = NULL;
 113 
 114 GrowableArray<ModulePatchPath*> *Arguments::_patch_mod_prefix = NULL;
 115 PathString *Arguments::_system_boot_class_path = NULL;
 116 bool Arguments::_has_jimage = false;
 117 
 118 char* Arguments::_ext_dirs = NULL;
 119 
 120 // Check if head of 'option' matches 'name', and sets 'tail' to the remaining
 121 // part of the option string.
 122 static bool match_option(const JavaVMOption *option, const char* name,
 123                          const char** tail) {
 124   size_t len = strlen(name);
 125   if (strncmp(option->optionString, name, len) == 0) {
 126     *tail = option->optionString + len;
 127     return true;
 128   } else {
 129     return false;
 130   }
 131 }
 132 
 133 // Check if 'option' matches 'name'. No "tail" is allowed.
 134 static bool match_option(const JavaVMOption *option, const char* name) {
 135   const char* tail = NULL;
 136   bool result = match_option(option, name, &tail);
 137   if (tail != NULL && *tail == '\0') {
 138     return result;
 139   } else {
 140     return false;
 141   }
 142 }
 143 
 144 // Return true if any of the strings in null-terminated array 'names' matches.
 145 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
 146 // the option must match exactly.
 147 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
 148   bool tail_allowed) {
 149   for (/* empty */; *names != NULL; ++names) {
 150     if (match_option(option, *names, tail)) {
 151       if (**tail == '\0' || tail_allowed && **tail == ':') {
 152         return true;
 153       }
 154     }
 155   }
 156   return false;
 157 }
 158 
 159 static void logOption(const char* opt) {
 160   if (PrintVMOptions) {
 161     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
 162   }
 163 }
 164 
 165 bool needs_module_property_warning = false;
 166 
 167 #define MODULE_PROPERTY_PREFIX "jdk.module."
 168 #define MODULE_PROPERTY_PREFIX_LEN 11
 169 #define ADDEXPORTS "addexports"
 170 #define ADDEXPORTS_LEN 10
 171 #define ADDREADS "addreads"
 172 #define ADDREADS_LEN 8
 173 #define PATCH "patch"
 174 #define PATCH_LEN 5
 175 #define ADDMODS "addmods"
 176 #define ADDMODS_LEN 7
 177 #define LIMITMODS "limitmods"
 178 #define LIMITMODS_LEN 9
 179 #define PATH "path"
 180 #define PATH_LEN 4
 181 #define UPGRADE_PATH "upgrade.path"
 182 #define UPGRADE_PATH_LEN 12
 183 
 184 // Return TRUE if option matches 'property', or 'property=', or 'property.'.
 185 static bool matches_property_suffix(const char* option, const char* property, size_t len) {
 186   return ((strncmp(option, property, len) == 0) &&
 187           (option[len] == '=' || option[len] == '.' || option[len] == '\0'));
 188 }
 189 
 190 // Return true if property starts with "jdk.module." and its ensuing chars match
 191 // any of the reserved module properties.
 192 // property should be passed without the leading "-D".
 193 bool Arguments::is_internal_module_property(const char* property) {
 194   assert((strncmp(property, "-D", 2) != 0), "Unexpected leading -D");
 195   if  (strncmp(property, MODULE_PROPERTY_PREFIX, MODULE_PROPERTY_PREFIX_LEN) == 0) {
 196     const char* property_suffix = property + MODULE_PROPERTY_PREFIX_LEN;
 197     if (matches_property_suffix(property_suffix, ADDEXPORTS, ADDEXPORTS_LEN) ||
 198         matches_property_suffix(property_suffix, ADDREADS, ADDREADS_LEN) ||
 199         matches_property_suffix(property_suffix, PATCH, PATCH_LEN) ||
 200         matches_property_suffix(property_suffix, ADDMODS, ADDMODS_LEN) ||
 201         matches_property_suffix(property_suffix, LIMITMODS, LIMITMODS_LEN) ||
 202         matches_property_suffix(property_suffix, PATH, PATH_LEN) ||
 203         matches_property_suffix(property_suffix, UPGRADE_PATH, UPGRADE_PATH_LEN)) {
 204       return true;
 205     }
 206   }
 207   return false;
 208 }
 209 
 210 // Process java launcher properties.
 211 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
 212   // See if sun.java.launcher, sun.java.launcher.is_altjvm or
 213   // sun.java.launcher.pid is defined.
 214   // Must do this before setting up other system properties,
 215   // as some of them may depend on launcher type.
 216   for (int index = 0; index < args->nOptions; index++) {
 217     const JavaVMOption* option = args->options + index;
 218     const char* tail;
 219 
 220     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
 221       process_java_launcher_argument(tail, option->extraInfo);
 222       continue;
 223     }
 224     if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
 225       if (strcmp(tail, "true") == 0) {
 226         _sun_java_launcher_is_altjvm = true;
 227       }
 228       continue;
 229     }
 230     if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
 231       _sun_java_launcher_pid = atoi(tail);
 232       continue;
 233     }
 234   }
 235 }
 236 
 237 // Initialize system properties key and value.
 238 void Arguments::init_system_properties() {
 239 
 240   // Set up _system_boot_class_path which is not a property but
 241   // relies heavily on argument processing and the jdk.boot.class.path.append
 242   // property. It is used to store the underlying system boot class path.
 243   _system_boot_class_path = new PathString(NULL);
 244 
 245   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
 246                                                            "Java Virtual Machine Specification",  false));
 247   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
 248   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
 249   PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
 250   PropertyList_add(&_system_properties, new SystemProperty("jdk.debug", VM_Version::jdk_debug_level(),  false));
 251 
 252   // Following are JVMTI agent writable properties.
 253   // Properties values are set to NULL and they are
 254   // os specific they are initialized in os::init_system_properties_values().
 255   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
 256   _java_library_path = new SystemProperty("java.library.path", NULL,  true);
 257   _java_home =  new SystemProperty("java.home", NULL,  true);
 258   _java_class_path = new SystemProperty("java.class.path", "",  true);
 259   // jdk.boot.class.path.append is a non-writeable, internal property.
 260   // It can only be set by either:
 261   //    - -Xbootclasspath/a:
 262   //    - AddToBootstrapClassLoaderSearch during JVMTI OnLoad phase
 263   _jdk_boot_class_path_append = new SystemProperty("jdk.boot.class.path.append", "", false, true);
 264 
 265   // Add to System Property list.
 266   PropertyList_add(&_system_properties, _sun_boot_library_path);
 267   PropertyList_add(&_system_properties, _java_library_path);
 268   PropertyList_add(&_system_properties, _java_home);
 269   PropertyList_add(&_system_properties, _java_class_path);
 270   PropertyList_add(&_system_properties, _jdk_boot_class_path_append);
 271 
 272   // Set OS specific system properties values
 273   os::init_system_properties_values();
 274 }
 275 
 276 // Update/Initialize System properties after JDK version number is known
 277 void Arguments::init_version_specific_system_properties() {
 278   enum { bufsz = 16 };
 279   char buffer[bufsz];
 280   const char* spec_vendor = "Oracle Corporation";
 281   uint32_t spec_version = JDK_Version::current().major_version();
 282 
 283   jio_snprintf(buffer, bufsz, UINT32_FORMAT, spec_version);
 284 
 285   PropertyList_add(&_system_properties,
 286       new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
 287   PropertyList_add(&_system_properties,
 288       new SystemProperty("java.vm.specification.version", buffer, false));
 289   PropertyList_add(&_system_properties,
 290       new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
 291 }
 292 
 293 /*
 294  *  -XX argument processing:
 295  *
 296  *  -XX arguments are defined in several places, such as:
 297  *      globals.hpp, globals_<cpu>.hpp, globals_<os>.hpp, <compiler>_globals.hpp, or <gc>_globals.hpp.
 298  *  -XX arguments are parsed in parse_argument().
 299  *  -XX argument bounds checking is done in check_vm_args_consistency().
 300  *
 301  * Over time -XX arguments may change. There are mechanisms to handle common cases:
 302  *
 303  *      ALIASED: An option that is simply another name for another option. This is often
 304  *               part of the process of deprecating a flag, but not all aliases need
 305  *               to be deprecated.
 306  *
 307  *               Create an alias for an option by adding the old and new option names to the
 308  *               "aliased_jvm_flags" table. Delete the old variable from globals.hpp (etc).
 309  *
 310  *   DEPRECATED: An option that is supported, but a warning is printed to let the user know that
 311  *               support may be removed in the future. Both regular and aliased options may be
 312  *               deprecated.
 313  *
 314  *               Add a deprecation warning for an option (or alias) by adding an entry in the
 315  *               "special_jvm_flags" table and setting the "deprecated_in" field.
 316  *               Often an option "deprecated" in one major release will
 317  *               be made "obsolete" in the next. In this case the entry should also have it's
 318  *               "obsolete_in" field set.
 319  *
 320  *     OBSOLETE: An option that has been removed (and deleted from globals.hpp), but is still accepted
 321  *               on the command line. A warning is printed to let the user know that option might not
 322  *               be accepted in the future.
 323  *
 324  *               Add an obsolete warning for an option by adding an entry in the "special_jvm_flags"
 325  *               table and setting the "obsolete_in" field.
 326  *
 327  *      EXPIRED: A deprecated or obsolete option that has an "accept_until" version less than or equal
 328  *               to the current JDK version. The system will flatly refuse to admit the existence of
 329  *               the flag. This allows a flag to die automatically over JDK releases.
 330  *
 331  *               Note that manual cleanup of expired options should be done at major JDK version upgrades:
 332  *                  - Newly expired options should be removed from the special_jvm_flags and aliased_jvm_flags tables.
 333  *                  - Newly obsolete or expired deprecated options should have their global variable
 334  *                    definitions removed (from globals.hpp, etc) and related implementations removed.
 335  *
 336  * Recommended approach for removing options:
 337  *
 338  * To remove options commonly used by customers (e.g. product, commercial -XX options), use
 339  * the 3-step model adding major release numbers to the deprecate, obsolete and expire columns.
 340  *
 341  * To remove internal options (e.g. diagnostic, experimental, develop options), use
 342  * a 2-step model adding major release numbers to the obsolete and expire columns.
 343  *
 344  * To change the name of an option, use the alias table as well as a 2-step
 345  * model adding major release numbers to the deprecate and expire columns.
 346  * Think twice about aliasing commonly used customer options.
 347  *
 348  * There are times when it is appropriate to leave a future release number as undefined.
 349  *
 350  * Tests:  Aliases should be tested in VMAliasOptions.java.
 351  *         Deprecated options should be tested in VMDeprecatedOptions.java.
 352  */
 353 
 354 // The special_jvm_flags table declares options that are being deprecated and/or obsoleted. The
 355 // "deprecated_in" or "obsolete_in" fields may be set to "undefined", but not both.
 356 // When the JDK version reaches 'deprecated_in' limit, the JVM will process this flag on
 357 // the command-line as usual, but will issue a warning.
 358 // When the JDK version reaches 'obsolete_in' limit, the JVM will continue accepting this flag on
 359 // the command-line, while issuing a warning and ignoring the flag value.
 360 // Once the JDK version reaches 'expired_in' limit, the JVM will flatly refuse to admit the
 361 // existence of the flag.
 362 //
 363 // MANUAL CLEANUP ON JDK VERSION UPDATES:
 364 // This table ensures that the handling of options will update automatically when the JDK
 365 // version is incremented, but the source code needs to be cleanup up manually:
 366 // - As "deprecated" options age into "obsolete" or "expired" options, the associated "globals"
 367 //   variable should be removed, as well as users of the variable.
 368 // - As "deprecated" options age into "obsolete" options, move the entry into the
 369 //   "Obsolete Flags" section of the table.
 370 // - All expired options should be removed from the table.
 371 static SpecialFlag const special_jvm_flags[] = {
 372   // -------------- Deprecated Flags --------------
 373   // --- Non-alias flags - sorted by obsolete_in then expired_in:
 374   { "MaxGCMinorPauseMillis",        JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
 375   { "AutoGCSelectPauseMillis",      JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 376   { "UseAutoGCSelectPolicy",        JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 377   { "UseParNewGC",                  JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 378   { "ConvertSleepToYield",          JDK_Version::jdk(9), JDK_Version::jdk(10),     JDK_Version::jdk(11) },
 379   { "ConvertYieldToSleep",          JDK_Version::jdk(9), JDK_Version::jdk(10),     JDK_Version::jdk(11) },
 380 
 381   // --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in:
 382   { "DefaultMaxRAMFraction",        JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
 383   { "CreateMinidumpOnCrash",        JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 384   { "CMSMarkStackSizeMax",          JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 385   { "CMSMarkStackSize",             JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 386   { "G1MarkStackSize",              JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 387   { "ParallelMarkingThreads",       JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 388   { "ParallelCMSThreads",           JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 389 
 390   // -------------- Obsolete Flags - sorted by expired_in --------------
 391   { "UseOldInlining",                JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 392   { "SafepointPollOffset",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 393   { "UseBoundThreads",               JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 394   { "DefaultThreadPriority",         JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 395   { "NoYieldsInMicrolock",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 396   { "BackEdgeThreshold",             JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 397   { "UseNewReflection",              JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 398   { "ReflectionWrapResolutionErrors",JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 399   { "VerifyReflectionBytecodes",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 400   { "AutoShutdownNMT",               JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 401   { "NmethodSweepFraction",          JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 402   { "NmethodSweepCheckInterval",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 403   { "CodeCacheMinimumFreeSpace",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 404 #ifndef ZERO
 405   { "UseFastAccessorMethods",        JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 406   { "UseFastEmptyMethods",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 407 #endif // ZERO
 408   { "UseCompilerSafepoints",         JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 409   { "AdaptiveSizePausePolicy",       JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 410   { "ParallelGCRetainPLAB",          JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 411   { "ThreadSafetyMargin",            JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 412   { "LazyBootClassLoader",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 413   { "StarvationMonitorInterval",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 414   { "PreInflateSpin",                JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 415   { "JNIDetachReleasesMonitors",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 416   { "UseAltSigs",                    JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 417   { "SegmentedHeapDumpThreshold",    JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 418   { "PrintOopAddress",               JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 419   { "PermSize",                      JDK_Version::undefined(), JDK_Version::jdk(8), JDK_Version::jdk(10) },
 420   { "MaxPermSize",                   JDK_Version::undefined(), JDK_Version::jdk(8), JDK_Version::jdk(10) },
 421 
 422 #ifdef TEST_VERIFY_SPECIAL_JVM_FLAGS
 423   { "dep > obs",                    JDK_Version::jdk(9), JDK_Version::jdk(8), JDK_Version::undefined() },
 424   { "dep > exp ",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(8) },
 425   { "obs > exp ",                   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(8) },
 426   { "not deprecated or obsolete",   JDK_Version::undefined(), JDK_Version::undefined(), JDK_Version::jdk(9) },
 427   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 428   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 429   { "BytecodeVerificationRemote",   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::undefined() },
 430 #endif
 431 
 432   { NULL, JDK_Version(0), JDK_Version(0) }
 433 };
 434 
 435 // Flags that are aliases for other flags.
 436 typedef struct {
 437   const char* alias_name;
 438   const char* real_name;
 439 } AliasedFlag;
 440 
 441 static AliasedFlag const aliased_jvm_flags[] = {
 442   { "DefaultMaxRAMFraction",    "MaxRAMFraction"    },
 443   { "CMSMarkStackSizeMax",      "MarkStackSizeMax"  },
 444   { "CMSMarkStackSize",         "MarkStackSize"     },
 445   { "G1MarkStackSize",          "MarkStackSize"     },
 446   { "ParallelMarkingThreads",   "ConcGCThreads"     },
 447   { "ParallelCMSThreads",       "ConcGCThreads"     },
 448   { "CreateMinidumpOnCrash",    "CreateCoredumpOnCrash" },
 449   { NULL, NULL}
 450 };
 451 
 452 // NOTE: A compatibility request will be necessary for each alias to be removed.
 453 static AliasedLoggingFlag const aliased_logging_flags[] = {
 454   { "PrintCompressedOopsMode",   LogLevel::Info,  true,  LOG_TAGS(gc, heap, coops) },
 455   { "TraceBiasedLocking",        LogLevel::Info,  true,  LOG_TAGS(biasedlocking) },
 456   { "TraceClassLoading",         LogLevel::Info,  true,  LOG_TAGS(class, load) },
 457   { "TraceClassLoadingPreorder", LogLevel::Debug, true,  LOG_TAGS(class, preorder) },
 458   { "TraceClassPaths",           LogLevel::Info,  true,  LOG_TAGS(class, path) },
 459   { "TraceClassResolution",      LogLevel::Debug, true,  LOG_TAGS(class, resolve) },
 460   { "TraceClassUnloading",       LogLevel::Info,  true,  LOG_TAGS(class, unload) },
 461   { "TraceExceptions",           LogLevel::Info,  true,  LOG_TAGS(exceptions) },
 462   { "TraceLoaderConstraints",    LogLevel::Info,  true,  LOG_TAGS(class, loader, constraints) },
 463   { "TraceMonitorInflation",     LogLevel::Debug, true,  LOG_TAGS(monitorinflation) },
 464   { "TraceSafepointCleanupTime", LogLevel::Info,  true,  LOG_TAGS(safepoint, cleanup) },
 465   { "TraceJVMTIObjectTagging",   LogLevel::Debug, true,  LOG_TAGS(jvmti, objecttagging) },
 466   { "TraceRedefineClasses",      LogLevel::Info,  false, LOG_TAGS(redefine, class) },
 467   { NULL,                        LogLevel::Off,   false, LOG_TAGS(_NO_TAG) }
 468 };
 469 
 470 #ifndef PRODUCT
 471 // These options are removed in jdk9. Remove this code for jdk10.
 472 static AliasedFlag const removed_develop_logging_flags[] = {
 473   { "TraceClassInitialization",   "-Xlog:class+init" },
 474   { "TraceClassLoaderData",       "-Xlog:class+loader+data" },
 475   { "TraceDefaultMethods",        "-Xlog:defaultmethods=debug" },
 476   { "TraceItables",               "-Xlog:itables=debug" },
 477   { "TraceMonitorMismatch",       "-Xlog:monitormismatch=info" },
 478   { "TraceSafepoint",             "-Xlog:safepoint=debug" },
 479   { "TraceStartupTime",           "-Xlog:startuptime" },
 480   { "TraceVMOperation",           "-Xlog:vmoperation=debug" },
 481   { "PrintVtables",               "-Xlog:vtables=debug" },
 482   { "VerboseVerification",        "-Xlog:verification" },
 483   { NULL, NULL }
 484 };
 485 #endif //PRODUCT
 486 
 487 // Return true if "v" is less than "other", where "other" may be "undefined".
 488 static bool version_less_than(JDK_Version v, JDK_Version other) {
 489   assert(!v.is_undefined(), "must be defined");
 490   if (!other.is_undefined() && v.compare(other) >= 0) {
 491     return false;
 492   } else {
 493     return true;
 494   }
 495 }
 496 
 497 extern bool lookup_special_flag_ext(const char *flag_name, SpecialFlag& flag);
 498 
 499 static bool lookup_special_flag(const char *flag_name, SpecialFlag& flag) {
 500   // Allow extensions to have priority
 501   if (lookup_special_flag_ext(flag_name, flag)) {
 502     return true;
 503   }
 504 
 505   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 506     if ((strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 507       flag = special_jvm_flags[i];
 508       return true;
 509     }
 510   }
 511   return false;
 512 }
 513 
 514 bool Arguments::is_obsolete_flag(const char *flag_name, JDK_Version* version) {
 515   assert(version != NULL, "Must provide a version buffer");
 516   SpecialFlag flag;
 517   if (lookup_special_flag(flag_name, flag)) {
 518     if (!flag.obsolete_in.is_undefined()) {
 519       if (version_less_than(JDK_Version::current(), flag.expired_in)) {
 520         *version = flag.obsolete_in;
 521         return true;
 522       }
 523     }
 524   }
 525   return false;
 526 }
 527 
 528 int Arguments::is_deprecated_flag(const char *flag_name, JDK_Version* version) {
 529   assert(version != NULL, "Must provide a version buffer");
 530   SpecialFlag flag;
 531   if (lookup_special_flag(flag_name, flag)) {
 532     if (!flag.deprecated_in.is_undefined()) {
 533       if (version_less_than(JDK_Version::current(), flag.obsolete_in) &&
 534           version_less_than(JDK_Version::current(), flag.expired_in)) {
 535         *version = flag.deprecated_in;
 536         return 1;
 537       } else {
 538         return -1;
 539       }
 540     }
 541   }
 542   return 0;
 543 }
 544 
 545 #ifndef PRODUCT
 546 const char* Arguments::removed_develop_logging_flag_name(const char* name){
 547   for (size_t i = 0; removed_develop_logging_flags[i].alias_name != NULL; i++) {
 548     const AliasedFlag& flag = removed_develop_logging_flags[i];
 549     if (strcmp(flag.alias_name, name) == 0) {
 550       return flag.real_name;
 551     }
 552   }
 553   return NULL;
 554 }
 555 #endif // PRODUCT
 556 
 557 const char* Arguments::real_flag_name(const char *flag_name) {
 558   for (size_t i = 0; aliased_jvm_flags[i].alias_name != NULL; i++) {
 559     const AliasedFlag& flag_status = aliased_jvm_flags[i];
 560     if (strcmp(flag_status.alias_name, flag_name) == 0) {
 561         return flag_status.real_name;
 562     }
 563   }
 564   return flag_name;
 565 }
 566 
 567 #ifdef ASSERT
 568 static bool lookup_special_flag(const char *flag_name, size_t skip_index) {
 569   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 570     if ((i != skip_index) && (strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 571       return true;
 572     }
 573   }
 574   return false;
 575 }
 576 
 577 static bool verify_special_jvm_flags() {
 578   bool success = true;
 579   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 580     const SpecialFlag& flag = special_jvm_flags[i];
 581     if (lookup_special_flag(flag.name, i)) {
 582       warning("Duplicate special flag declaration \"%s\"", flag.name);
 583       success = false;
 584     }
 585     if (flag.deprecated_in.is_undefined() &&
 586         flag.obsolete_in.is_undefined()) {
 587       warning("Special flag entry \"%s\" must declare version deprecated and/or obsoleted in.", flag.name);
 588       success = false;
 589     }
 590 
 591     if (!flag.deprecated_in.is_undefined()) {
 592       if (!version_less_than(flag.deprecated_in, flag.obsolete_in)) {
 593         warning("Special flag entry \"%s\" must be deprecated before obsoleted.", flag.name);
 594         success = false;
 595       }
 596 
 597       if (!version_less_than(flag.deprecated_in, flag.expired_in)) {
 598         warning("Special flag entry \"%s\" must be deprecated before expired.", flag.name);
 599         success = false;
 600       }
 601     }
 602 
 603     if (!flag.obsolete_in.is_undefined()) {
 604       if (!version_less_than(flag.obsolete_in, flag.expired_in)) {
 605         warning("Special flag entry \"%s\" must be obsoleted before expired.", flag.name);
 606         success = false;
 607       }
 608 
 609       // if flag has become obsolete it should not have a "globals" flag defined anymore.
 610       if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 611         if (Flag::find_flag(flag.name) != NULL) {
 612           warning("Global variable for obsolete special flag entry \"%s\" should be removed", flag.name);
 613           success = false;
 614         }
 615       }
 616     }
 617 
 618     if (!flag.expired_in.is_undefined()) {
 619       // if flag has become expired it should not have a "globals" flag defined anymore.
 620       if (!version_less_than(JDK_Version::current(), flag.expired_in)) {
 621         if (Flag::find_flag(flag.name) != NULL) {
 622           warning("Global variable for expired flag entry \"%s\" should be removed", flag.name);
 623           success = false;
 624         }
 625       }
 626     }
 627 
 628   }
 629   return success;
 630 }
 631 #endif
 632 
 633 // Parses a size specification string.
 634 bool Arguments::atojulong(const char *s, julong* result) {
 635   julong n = 0;
 636 
 637   // First char must be a digit. Don't allow negative numbers or leading spaces.
 638   if (!isdigit(*s)) {
 639     return false;
 640   }
 641 
 642   bool is_hex = (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'));
 643   char* remainder;
 644   errno = 0;
 645   n = strtoull(s, &remainder, (is_hex ? 16 : 10));
 646   if (errno != 0) {
 647     return false;
 648   }
 649 
 650   // Fail if no number was read at all or if the remainder contains more than a single non-digit character.
 651   if (remainder == s || strlen(remainder) > 1) {
 652     return false;
 653   }
 654 
 655   switch (*remainder) {
 656     case 'T': case 't':
 657       *result = n * G * K;
 658       // Check for overflow.
 659       if (*result/((julong)G * K) != n) return false;
 660       return true;
 661     case 'G': case 'g':
 662       *result = n * G;
 663       if (*result/G != n) return false;
 664       return true;
 665     case 'M': case 'm':
 666       *result = n * M;
 667       if (*result/M != n) return false;
 668       return true;
 669     case 'K': case 'k':
 670       *result = n * K;
 671       if (*result/K != n) return false;
 672       return true;
 673     case '\0':
 674       *result = n;
 675       return true;
 676     default:
 677       return false;
 678   }
 679 }
 680 
 681 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
 682   if (size < min_size) return arg_too_small;
 683   // Check that size will fit in a size_t (only relevant on 32-bit)
 684   if (size > max_uintx) return arg_too_big;
 685   return arg_in_range;
 686 }
 687 
 688 // Describe an argument out of range error
 689 void Arguments::describe_range_error(ArgsRange errcode) {
 690   switch(errcode) {
 691   case arg_too_big:
 692     jio_fprintf(defaultStream::error_stream(),
 693                 "The specified size exceeds the maximum "
 694                 "representable size.\n");
 695     break;
 696   case arg_too_small:
 697   case arg_unreadable:
 698   case arg_in_range:
 699     // do nothing for now
 700     break;
 701   default:
 702     ShouldNotReachHere();
 703   }
 704 }
 705 
 706 static bool set_bool_flag(const char* name, bool value, Flag::Flags origin) {
 707   if (CommandLineFlags::boolAtPut(name, &value, origin) == Flag::SUCCESS) {
 708     return true;
 709   } else {
 710     return false;
 711   }
 712 }
 713 
 714 static bool set_fp_numeric_flag(const char* name, char* value, Flag::Flags origin) {
 715   char* end;
 716   errno = 0;
 717   double v = strtod(value, &end);
 718   if ((errno != 0) || (*end != 0)) {
 719     return false;
 720   }
 721 
 722   if (CommandLineFlags::doubleAtPut(name, &v, origin) == Flag::SUCCESS) {
 723     return true;
 724   }
 725   return false;
 726 }
 727 
 728 static bool set_numeric_flag(const char* name, char* value, Flag::Flags origin) {
 729   julong v;
 730   int int_v;
 731   intx intx_v;
 732   bool is_neg = false;
 733   Flag* result = Flag::find_flag(name, strlen(name));
 734 
 735   if (result == NULL) {
 736     return false;
 737   }
 738 
 739   // Check the sign first since atojulong() parses only unsigned values.
 740   if (*value == '-') {
 741     if (!result->is_intx() && !result->is_int()) {
 742       return false;
 743     }
 744     value++;
 745     is_neg = true;
 746   }
 747   if (!Arguments::atojulong(value, &v)) {
 748     return false;
 749   }
 750   if (result->is_int()) {
 751     int_v = (int) v;
 752     if (is_neg) {
 753       int_v = -int_v;
 754     }
 755     return CommandLineFlags::intAtPut(result, &int_v, origin) == Flag::SUCCESS;
 756   } else if (result->is_uint()) {
 757     uint uint_v = (uint) v;
 758     return CommandLineFlags::uintAtPut(result, &uint_v, origin) == Flag::SUCCESS;
 759   } else if (result->is_intx()) {
 760     intx_v = (intx) v;
 761     if (is_neg) {
 762       intx_v = -intx_v;
 763     }
 764     return CommandLineFlags::intxAtPut(result, &intx_v, origin) == Flag::SUCCESS;
 765   } else if (result->is_uintx()) {
 766     uintx uintx_v = (uintx) v;
 767     return CommandLineFlags::uintxAtPut(result, &uintx_v, origin) == Flag::SUCCESS;
 768   } else if (result->is_uint64_t()) {
 769     uint64_t uint64_t_v = (uint64_t) v;
 770     return CommandLineFlags::uint64_tAtPut(result, &uint64_t_v, origin) == Flag::SUCCESS;
 771   } else if (result->is_size_t()) {
 772     size_t size_t_v = (size_t) v;
 773     return CommandLineFlags::size_tAtPut(result, &size_t_v, origin) == Flag::SUCCESS;
 774   } else {
 775     return false;
 776   }
 777 }
 778 
 779 static bool set_string_flag(const char* name, const char* value, Flag::Flags origin) {
 780   if (CommandLineFlags::ccstrAtPut(name, &value, origin) != Flag::SUCCESS) return false;
 781   // Contract:  CommandLineFlags always returns a pointer that needs freeing.
 782   FREE_C_HEAP_ARRAY(char, value);
 783   return true;
 784 }
 785 
 786 static bool append_to_string_flag(const char* name, const char* new_value, Flag::Flags origin) {
 787   const char* old_value = "";
 788   if (CommandLineFlags::ccstrAt(name, &old_value) != Flag::SUCCESS) return false;
 789   size_t old_len = old_value != NULL ? strlen(old_value) : 0;
 790   size_t new_len = strlen(new_value);
 791   const char* value;
 792   char* free_this_too = NULL;
 793   if (old_len == 0) {
 794     value = new_value;
 795   } else if (new_len == 0) {
 796     value = old_value;
 797   } else {
 798      size_t length = old_len + 1 + new_len + 1;
 799      char* buf = NEW_C_HEAP_ARRAY(char, length, mtArguments);
 800     // each new setting adds another LINE to the switch:
 801     jio_snprintf(buf, length, "%s\n%s", old_value, new_value);
 802     value = buf;
 803     free_this_too = buf;
 804   }
 805   (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
 806   // CommandLineFlags always returns a pointer that needs freeing.
 807   FREE_C_HEAP_ARRAY(char, value);
 808   if (free_this_too != NULL) {
 809     // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
 810     FREE_C_HEAP_ARRAY(char, free_this_too);
 811   }
 812   return true;
 813 }
 814 
 815 const char* Arguments::handle_aliases_and_deprecation(const char* arg, bool warn) {
 816   const char* real_name = real_flag_name(arg);
 817   JDK_Version since = JDK_Version();
 818   switch (is_deprecated_flag(arg, &since)) {
 819     case -1:
 820       return NULL; // obsolete or expired, don't process normally
 821     case 0:
 822       return real_name;
 823     case 1: {
 824       if (warn) {
 825         char version[256];
 826         since.to_string(version, sizeof(version));
 827         if (real_name != arg) {
 828           warning("Option %s was deprecated in version %s and will likely be removed in a future release. Use option %s instead.",
 829                   arg, version, real_name);
 830         } else {
 831           warning("Option %s was deprecated in version %s and will likely be removed in a future release.",
 832                   arg, version);
 833         }
 834       }
 835       return real_name;
 836     }
 837   }
 838   ShouldNotReachHere();
 839   return NULL;
 840 }
 841 
 842 void log_deprecated_flag(const char* name, bool on, AliasedLoggingFlag alf) {
 843   LogTagType tagSet[] = {alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5};
 844   // Set tagset string buffer at max size of 256, large enough for any alias tagset
 845   const int max_tagset_size = 256;
 846   int max_tagset_len = max_tagset_size - 1;
 847   char tagset_buffer[max_tagset_size];
 848   tagset_buffer[0] = '\0';
 849 
 850   // Write tag-set for aliased logging option, in string list form
 851   int max_tags = sizeof(tagSet)/sizeof(tagSet[0]);
 852   for (int i = 0; i < max_tags && tagSet[i] != LogTag::__NO_TAG; i++) {
 853     if (i > 0) {
 854       strncat(tagset_buffer, "+", max_tagset_len - strlen(tagset_buffer));
 855     }
 856     strncat(tagset_buffer, LogTag::name(tagSet[i]), max_tagset_len - strlen(tagset_buffer));
 857   }
 858   if (!alf.exactMatch) {
 859       strncat(tagset_buffer, "*", max_tagset_len - strlen(tagset_buffer));
 860   }
 861   log_warning(arguments)("-XX:%s%s is deprecated. Will use -Xlog:%s=%s instead.",
 862                          (on) ? "+" : "-",
 863                          name,
 864                          tagset_buffer,
 865                          (on) ? LogLevel::name(alf.level) : "off");
 866 }
 867 
 868 AliasedLoggingFlag Arguments::catch_logging_aliases(const char* name, bool on){
 869   for (size_t i = 0; aliased_logging_flags[i].alias_name != NULL; i++) {
 870     const AliasedLoggingFlag& alf = aliased_logging_flags[i];
 871     if (strcmp(alf.alias_name, name) == 0) {
 872       log_deprecated_flag(name, on, alf);
 873       return alf;
 874     }
 875   }
 876   AliasedLoggingFlag a = {NULL, LogLevel::Off, false, LOG_TAGS(_NO_TAG)};
 877   return a;
 878 }
 879 
 880 bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
 881 
 882   // range of acceptable characters spelled out for portability reasons
 883 #define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
 884 #define BUFLEN 255
 885   char name[BUFLEN+1];
 886   char dummy;
 887   const char* real_name;
 888   bool warn_if_deprecated = true;
 889 
 890   if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
 891     AliasedLoggingFlag alf = catch_logging_aliases(name, false);
 892     if (alf.alias_name != NULL){
 893       LogConfiguration::configure_stdout(LogLevel::Off, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
 894       return true;
 895     }
 896     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
 897     if (real_name == NULL) {
 898       return false;
 899     }
 900     return set_bool_flag(real_name, false, origin);
 901   }
 902   if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
 903     AliasedLoggingFlag alf = catch_logging_aliases(name, true);
 904     if (alf.alias_name != NULL){
 905       LogConfiguration::configure_stdout(alf.level, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
 906       return true;
 907     }
 908     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
 909     if (real_name == NULL) {
 910       return false;
 911     }
 912     return set_bool_flag(real_name, true, origin);
 913   }
 914 
 915   char punct;
 916   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
 917     const char* value = strchr(arg, '=') + 1;
 918     Flag* flag;
 919 
 920     // this scanf pattern matches both strings (handled here) and numbers (handled later))
 921     AliasedLoggingFlag alf = catch_logging_aliases(name, true);
 922     if (alf.alias_name != NULL) {
 923       LogConfiguration::configure_stdout(alf.level, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
 924       return true;
 925     }
 926     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
 927     if (real_name == NULL) {
 928       return false;
 929     }
 930     flag = Flag::find_flag(real_name);
 931     if (flag != NULL && flag->is_ccstr()) {
 932       if (flag->ccstr_accumulates()) {
 933         return append_to_string_flag(real_name, value, origin);
 934       } else {
 935         if (value[0] == '\0') {
 936           value = NULL;
 937         }
 938         return set_string_flag(real_name, value, origin);
 939       }
 940     } else {
 941       warn_if_deprecated = false; // if arg is deprecated, we've already done warning...
 942     }
 943   }
 944 
 945   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
 946     const char* value = strchr(arg, '=') + 1;
 947     // -XX:Foo:=xxx will reset the string flag to the given value.
 948     if (value[0] == '\0') {
 949       value = NULL;
 950     }
 951     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
 952     if (real_name == NULL) {
 953       return false;
 954     }
 955     return set_string_flag(real_name, value, origin);
 956   }
 957 
 958 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.eE+]"
 959 #define SIGNED_NUMBER_RANGE    "[-0123456789]"
 960 #define        NUMBER_RANGE    "[0123456789eE+-]"
 961   char value[BUFLEN + 1];
 962   char value2[BUFLEN + 1];
 963   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
 964     // Looks like a floating-point number -- try again with more lenient format string
 965     if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
 966       real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
 967       if (real_name == NULL) {
 968         return false;
 969       }
 970       return set_fp_numeric_flag(real_name, value, origin);
 971     }
 972   }
 973 
 974 #define VALUE_RANGE "[-kmgtxKMGTX0123456789abcdefABCDEF]"
 975   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
 976     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
 977     if (real_name == NULL) {
 978       return false;
 979     }
 980     return set_numeric_flag(real_name, value, origin);
 981   }
 982 
 983   return false;
 984 }
 985 
 986 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
 987   assert(bldarray != NULL, "illegal argument");
 988 
 989   if (arg == NULL) {
 990     return;
 991   }
 992 
 993   int new_count = *count + 1;
 994 
 995   // expand the array and add arg to the last element
 996   if (*bldarray == NULL) {
 997     *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtArguments);
 998   } else {
 999     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtArguments);
1000   }
1001   (*bldarray)[*count] = os::strdup_check_oom(arg);
1002   *count = new_count;
1003 }
1004 
1005 void Arguments::build_jvm_args(const char* arg) {
1006   add_string(&_jvm_args_array, &_num_jvm_args, arg);
1007 }
1008 
1009 void Arguments::build_jvm_flags(const char* arg) {
1010   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
1011 }
1012 
1013 // utility function to return a string that concatenates all
1014 // strings in a given char** array
1015 const char* Arguments::build_resource_string(char** args, int count) {
1016   if (args == NULL || count == 0) {
1017     return NULL;
1018   }
1019   size_t length = 0;
1020   for (int i = 0; i < count; i++) {
1021     length += strlen(args[i]) + 1; // add 1 for a space or NULL terminating character
1022   }
1023   char* s = NEW_RESOURCE_ARRAY(char, length);
1024   char* dst = s;
1025   for (int j = 0; j < count; j++) {
1026     size_t offset = strlen(args[j]) + 1; // add 1 for a space or NULL terminating character
1027     jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with NULL character
1028     dst += offset;
1029     length -= offset;
1030   }
1031   return (const char*) s;
1032 }
1033 
1034 void Arguments::print_on(outputStream* st) {
1035   st->print_cr("VM Arguments:");
1036   if (num_jvm_flags() > 0) {
1037     st->print("jvm_flags: "); print_jvm_flags_on(st);
1038     st->cr();
1039   }
1040   if (num_jvm_args() > 0) {
1041     st->print("jvm_args: "); print_jvm_args_on(st);
1042     st->cr();
1043   }
1044   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
1045   if (_java_class_path != NULL) {
1046     char* path = _java_class_path->value();
1047     st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
1048   }
1049   st->print_cr("Launcher Type: %s", _sun_java_launcher);
1050 }
1051 
1052 void Arguments::print_summary_on(outputStream* st) {
1053   // Print the command line.  Environment variables that are helpful for
1054   // reproducing the problem are written later in the hs_err file.
1055   // flags are from setting file
1056   if (num_jvm_flags() > 0) {
1057     st->print_raw("Settings File: ");
1058     print_jvm_flags_on(st);
1059     st->cr();
1060   }
1061   // args are the command line and environment variable arguments.
1062   st->print_raw("Command Line: ");
1063   if (num_jvm_args() > 0) {
1064     print_jvm_args_on(st);
1065   }
1066   // this is the classfile and any arguments to the java program
1067   if (java_command() != NULL) {
1068     st->print("%s", java_command());
1069   }
1070   st->cr();
1071 }
1072 
1073 void Arguments::print_jvm_flags_on(outputStream* st) {
1074   if (_num_jvm_flags > 0) {
1075     for (int i=0; i < _num_jvm_flags; i++) {
1076       st->print("%s ", _jvm_flags_array[i]);
1077     }
1078   }
1079 }
1080 
1081 void Arguments::print_jvm_args_on(outputStream* st) {
1082   if (_num_jvm_args > 0) {
1083     for (int i=0; i < _num_jvm_args; i++) {
1084       st->print("%s ", _jvm_args_array[i]);
1085     }
1086   }
1087 }
1088 
1089 bool Arguments::process_argument(const char* arg,
1090                                  jboolean ignore_unrecognized,
1091                                  Flag::Flags origin) {
1092   JDK_Version since = JDK_Version();
1093 
1094   if (parse_argument(arg, origin)) {
1095     return true;
1096   }
1097 
1098   // Determine if the flag has '+', '-', or '=' characters.
1099   bool has_plus_minus = (*arg == '+' || *arg == '-');
1100   const char* const argname = has_plus_minus ? arg + 1 : arg;
1101 
1102   size_t arg_len;
1103   const char* equal_sign = strchr(argname, '=');
1104   if (equal_sign == NULL) {
1105     arg_len = strlen(argname);
1106   } else {
1107     arg_len = equal_sign - argname;
1108   }
1109 
1110   // Only make the obsolete check for valid arguments.
1111   if (arg_len <= BUFLEN) {
1112     // Construct a string which consists only of the argument name without '+', '-', or '='.
1113     char stripped_argname[BUFLEN+1]; // +1 for '\0'
1114     jio_snprintf(stripped_argname, arg_len+1, "%s", argname); // +1 for '\0'
1115     if (is_obsolete_flag(stripped_argname, &since)) {
1116       char version[256];
1117       since.to_string(version, sizeof(version));
1118       warning("Ignoring option %s; support was removed in %s", stripped_argname, version);
1119       return true;
1120     }
1121 #ifndef PRODUCT
1122     else {
1123       const char* replacement;
1124       if ((replacement = removed_develop_logging_flag_name(stripped_argname)) != NULL){
1125         log_warning(arguments)("%s has been removed. Please use %s instead.",
1126                                stripped_argname,
1127                                replacement);
1128         return false;
1129       }
1130     }
1131 #endif //PRODUCT
1132   }
1133 
1134   // For locked flags, report a custom error message if available.
1135   // Otherwise, report the standard unrecognized VM option.
1136   Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
1137   if (found_flag != NULL) {
1138     char locked_message_buf[BUFLEN];
1139     Flag::MsgType msg_type = found_flag->get_locked_message(locked_message_buf, BUFLEN);
1140     if (strlen(locked_message_buf) == 0) {
1141       if (found_flag->is_bool() && !has_plus_minus) {
1142         jio_fprintf(defaultStream::error_stream(),
1143           "Missing +/- setting for VM option '%s'\n", argname);
1144       } else if (!found_flag->is_bool() && has_plus_minus) {
1145         jio_fprintf(defaultStream::error_stream(),
1146           "Unexpected +/- setting in VM option '%s'\n", argname);
1147       } else {
1148         jio_fprintf(defaultStream::error_stream(),
1149           "Improperly specified VM option '%s'\n", argname);
1150       }
1151     } else {
1152 #ifdef PRODUCT
1153       bool mismatched = ((msg_type == Flag::NOTPRODUCT_FLAG_BUT_PRODUCT_BUILD) ||
1154                          (msg_type == Flag::DEVELOPER_FLAG_BUT_PRODUCT_BUILD));
1155       if (ignore_unrecognized && mismatched) {
1156         return true;
1157       }
1158 #endif
1159       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
1160     }
1161   } else {
1162     if (ignore_unrecognized) {
1163       return true;
1164     }
1165     jio_fprintf(defaultStream::error_stream(),
1166                 "Unrecognized VM option '%s'\n", argname);
1167     Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
1168     if (fuzzy_matched != NULL) {
1169       jio_fprintf(defaultStream::error_stream(),
1170                   "Did you mean '%s%s%s'? ",
1171                   (fuzzy_matched->is_bool()) ? "(+/-)" : "",
1172                   fuzzy_matched->_name,
1173                   (fuzzy_matched->is_bool()) ? "" : "=<value>");
1174     }
1175   }
1176 
1177   // allow for commandline "commenting out" options like -XX:#+Verbose
1178   return arg[0] == '#';
1179 }
1180 
1181 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
1182   FILE* stream = fopen(file_name, "rb");
1183   if (stream == NULL) {
1184     if (should_exist) {
1185       jio_fprintf(defaultStream::error_stream(),
1186                   "Could not open settings file %s\n", file_name);
1187       return false;
1188     } else {
1189       return true;
1190     }
1191   }
1192 
1193   char token[1024];
1194   int  pos = 0;
1195 
1196   bool in_white_space = true;
1197   bool in_comment     = false;
1198   bool in_quote       = false;
1199   char quote_c        = 0;
1200   bool result         = true;
1201 
1202   int c = getc(stream);
1203   while(c != EOF && pos < (int)(sizeof(token)-1)) {
1204     if (in_white_space) {
1205       if (in_comment) {
1206         if (c == '\n') in_comment = false;
1207       } else {
1208         if (c == '#') in_comment = true;
1209         else if (!isspace(c)) {
1210           in_white_space = false;
1211           token[pos++] = c;
1212         }
1213       }
1214     } else {
1215       if (c == '\n' || (!in_quote && isspace(c))) {
1216         // token ends at newline, or at unquoted whitespace
1217         // this allows a way to include spaces in string-valued options
1218         token[pos] = '\0';
1219         logOption(token);
1220         result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
1221         build_jvm_flags(token);
1222         pos = 0;
1223         in_white_space = true;
1224         in_quote = false;
1225       } else if (!in_quote && (c == '\'' || c == '"')) {
1226         in_quote = true;
1227         quote_c = c;
1228       } else if (in_quote && (c == quote_c)) {
1229         in_quote = false;
1230       } else {
1231         token[pos++] = c;
1232       }
1233     }
1234     c = getc(stream);
1235   }
1236   if (pos > 0) {
1237     token[pos] = '\0';
1238     result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
1239     build_jvm_flags(token);
1240   }
1241   fclose(stream);
1242   return result;
1243 }
1244 
1245 //=============================================================================================================
1246 // Parsing of properties (-D)
1247 
1248 const char* Arguments::get_property(const char* key) {
1249   return PropertyList_get_value(system_properties(), key);
1250 }
1251 
1252 bool Arguments::add_property(const char* prop, PropertyWriteable writeable, PropertyInternal internal) {
1253   const char* eq = strchr(prop, '=');
1254   const char* key;
1255   const char* value = "";
1256 
1257   if (eq == NULL) {
1258     // property doesn't have a value, thus use passed string
1259     key = prop;
1260   } else {
1261     // property have a value, thus extract it and save to the
1262     // allocated string
1263     size_t key_len = eq - prop;
1264     char* tmp_key = AllocateHeap(key_len + 1, mtArguments);
1265 
1266     jio_snprintf(tmp_key, key_len + 1, "%s", prop);
1267     key = tmp_key;
1268 
1269     value = &prop[key_len + 1];
1270   }
1271 
1272   if (strcmp(key, "java.compiler") == 0) {
1273     process_java_compiler_argument(value);
1274     // Record value in Arguments, but let it get passed to Java.
1275   } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0 ||
1276              strcmp(key, "sun.java.launcher.pid") == 0) {
1277     // sun.java.launcher.is_altjvm and sun.java.launcher.pid property are
1278     // private and are processed in process_sun_java_launcher_properties();
1279     // the sun.java.launcher property is passed on to the java application
1280   } else if (strcmp(key, "sun.boot.library.path") == 0) {
1281     // append is true, writable is true, internal is false
1282     PropertyList_unique_add(&_system_properties, key, value, AppendProperty,
1283                             WriteableProperty, ExternalProperty);
1284   } else {
1285     if (strcmp(key, "sun.java.command") == 0) {
1286       char *old_java_command = _java_command;
1287       _java_command = os::strdup_check_oom(value, mtArguments);
1288       if (old_java_command != NULL) {
1289         os::free(old_java_command);
1290       }
1291     } else if (strcmp(key, "java.vendor.url.bug") == 0) {
1292       const char* old_java_vendor_url_bug = _java_vendor_url_bug;
1293       // save it in _java_vendor_url_bug, so JVM fatal error handler can access
1294       // its value without going through the property list or making a Java call.
1295       _java_vendor_url_bug = os::strdup_check_oom(value, mtArguments);
1296       if (old_java_vendor_url_bug != DEFAULT_VENDOR_URL_BUG) {
1297         assert(old_java_vendor_url_bug != NULL, "_java_vendor_url_bug is NULL");
1298         os::free((void *)old_java_vendor_url_bug);
1299       }
1300     }
1301 
1302     // Create new property and add at the end of the list
1303     PropertyList_unique_add(&_system_properties, key, value, AddProperty, writeable, internal);
1304   }
1305 
1306   if (key != prop) {
1307     // SystemProperty copy passed value, thus free previously allocated
1308     // memory
1309     FreeHeap((void *)key);
1310   }
1311 
1312   return true;
1313 }
1314 
1315 #if INCLUDE_CDS
1316 void Arguments::check_unsupported_dumping_properties() {
1317   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
1318   const char* unsupported_properties[] = { "jdk.module.main",
1319                                            "jdk.module.limitmods",
1320                                            "jdk.module.path",
1321                                            "jdk.module.upgrade.path",
1322                                            "jdk.module.addmods.0" };
1323   const char* unsupported_options[] = { "-m",
1324                                         "--limit-modules",
1325                                         "--module-path",
1326                                         "--upgrade-module-path",
1327                                         "--add-modules" };
1328   assert(ARRAY_SIZE(unsupported_properties) == ARRAY_SIZE(unsupported_options), "must be");
1329   // If a vm option is found in the unsupported_options array with index less than the warning_idx,
1330   // vm will exit with an error message. Otherwise, it will result in a warning message.
1331   uint warning_idx = 2;
1332   SystemProperty* sp = system_properties();
1333   while (sp != NULL) {
1334     for (uint i = 0; i < ARRAY_SIZE(unsupported_properties); i++) {
1335       if (strcmp(sp->key(), unsupported_properties[i]) == 0) {
1336         if (i < warning_idx) {
1337           vm_exit_during_initialization(
1338             "Cannot use the following option when dumping the shared archive", unsupported_options[i]);
1339         } else {
1340           warning(
1341             "the %s option is ignored when dumping the shared archive", unsupported_options[i]);
1342         }
1343       }
1344     }
1345     sp = sp->next();
1346   }
1347 
1348   // Check for an exploded module build in use with -Xshare:dump.
1349   if (!has_jimage()) {
1350     vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
1351   }
1352 }
1353 #endif
1354 
1355 //===========================================================================================================
1356 // Setting int/mixed/comp mode flags
1357 
1358 void Arguments::set_mode_flags(Mode mode) {
1359   // Set up default values for all flags.
1360   // If you add a flag to any of the branches below,
1361   // add a default value for it here.
1362   set_java_compiler(false);
1363   _mode                      = mode;
1364 
1365   // Ensure Agent_OnLoad has the correct initial values.
1366   // This may not be the final mode; mode may change later in onload phase.
1367   PropertyList_unique_add(&_system_properties, "java.vm.info",
1368                           VM_Version::vm_info_string(), AddProperty, UnwriteableProperty, ExternalProperty);
1369 
1370   UseInterpreter             = true;
1371   UseCompiler                = true;
1372   UseLoopCounter             = true;
1373 
1374   // Default values may be platform/compiler dependent -
1375   // use the saved values
1376   ClipInlining               = Arguments::_ClipInlining;
1377   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1378   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1379   BackgroundCompilation      = Arguments::_BackgroundCompilation;
1380   if (TieredCompilation) {
1381     if (FLAG_IS_DEFAULT(Tier3InvokeNotifyFreqLog)) {
1382       Tier3InvokeNotifyFreqLog = Arguments::_Tier3InvokeNotifyFreqLog;
1383     }
1384     if (FLAG_IS_DEFAULT(Tier4InvocationThreshold)) {
1385       Tier4InvocationThreshold = Arguments::_Tier4InvocationThreshold;
1386     }
1387   }
1388 
1389   // Change from defaults based on mode
1390   switch (mode) {
1391   default:
1392     ShouldNotReachHere();
1393     break;
1394   case _int:
1395     UseCompiler              = false;
1396     UseLoopCounter           = false;
1397     AlwaysCompileLoopMethods = false;
1398     UseOnStackReplacement    = false;
1399     break;
1400   case _mixed:
1401     // same as default
1402     break;
1403   case _comp:
1404     UseInterpreter           = false;
1405     BackgroundCompilation    = false;
1406     ClipInlining             = false;
1407     // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1408     // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1409     // compile a level 4 (C2) and then continue executing it.
1410     if (TieredCompilation) {
1411       Tier3InvokeNotifyFreqLog = 0;
1412       Tier4InvocationThreshold = 0;
1413     }
1414     break;
1415   }
1416 }
1417 
1418 #if defined(COMPILER2) || INCLUDE_JVMCI || defined(_LP64) || !INCLUDE_CDS
1419 // Conflict: required to use shared spaces (-Xshare:on), but
1420 // incompatible command line options were chosen.
1421 
1422 static void no_shared_spaces(const char* message) {
1423   if (RequireSharedSpaces) {
1424     jio_fprintf(defaultStream::error_stream(),
1425       "Class data sharing is inconsistent with other specified options.\n");
1426     vm_exit_during_initialization("Unable to use shared archive.", message);
1427   } else {
1428     FLAG_SET_DEFAULT(UseSharedSpaces, false);
1429   }
1430 }
1431 #endif
1432 
1433 // Returns threshold scaled with the value of scale.
1434 // If scale < 0.0, threshold is returned without scaling.
1435 intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
1436   if (scale == 1.0 || scale < 0.0) {
1437     return threshold;
1438   } else {
1439     return (intx)(threshold * scale);
1440   }
1441 }
1442 
1443 // Returns freq_log scaled with the value of scale.
1444 // Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
1445 // If scale < 0.0, freq_log is returned without scaling.
1446 intx Arguments::scaled_freq_log(intx freq_log, double scale) {
1447   // Check if scaling is necessary or if negative value was specified.
1448   if (scale == 1.0 || scale < 0.0) {
1449     return freq_log;
1450   }
1451   // Check values to avoid calculating log2 of 0.
1452   if (scale == 0.0 || freq_log == 0) {
1453     return 0;
1454   }
1455   // Determine the maximum notification frequency value currently supported.
1456   // The largest mask value that the interpreter/C1 can handle is
1457   // of length InvocationCounter::number_of_count_bits. Mask values are always
1458   // one bit shorter then the value of the notification frequency. Set
1459   // max_freq_bits accordingly.
1460   intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
1461   intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
1462   if (scaled_freq == 0) {
1463     // Return 0 right away to avoid calculating log2 of 0.
1464     return 0;
1465   } else if (scaled_freq > nth_bit(max_freq_bits)) {
1466     return max_freq_bits;
1467   } else {
1468     return log2_intptr(scaled_freq);
1469   }
1470 }
1471 
1472 void Arguments::set_tiered_flags() {
1473   // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1474   if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1475     FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1476   }
1477   if (CompilationPolicyChoice < 2) {
1478     vm_exit_during_initialization(
1479       "Incompatible compilation policy selected", NULL);
1480   }
1481   // Increase the code cache size - tiered compiles a lot more.
1482   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1483     FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
1484                   MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1485   }
1486   // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
1487   if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
1488     FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
1489   }
1490   if (!UseInterpreter) { // -Xcomp
1491     Tier3InvokeNotifyFreqLog = 0;
1492     Tier4InvocationThreshold = 0;
1493   }
1494 
1495   if (CompileThresholdScaling < 0) {
1496     vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
1497   }
1498 
1499   // Scale tiered compilation thresholds.
1500   // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
1501   if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
1502     FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
1503     FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
1504 
1505     FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
1506     FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
1507     FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
1508     FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
1509 
1510     // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
1511     // once these thresholds become supported.
1512 
1513     FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
1514     FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
1515 
1516     FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
1517     FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
1518 
1519     FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
1520 
1521     FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
1522     FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
1523     FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
1524     FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
1525   }
1526 }
1527 
1528 #if INCLUDE_ALL_GCS
1529 static void disable_adaptive_size_policy(const char* collector_name) {
1530   if (UseAdaptiveSizePolicy) {
1531     if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
1532       warning("Disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
1533               collector_name);
1534     }
1535     FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
1536   }
1537 }
1538 
1539 void Arguments::set_parnew_gc_flags() {
1540   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
1541          "control point invariant");
1542   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1543   assert(UseParNewGC, "ParNew should always be used with CMS");
1544 
1545   if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
1546     FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1547     assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
1548   } else if (ParallelGCThreads == 0) {
1549     jio_fprintf(defaultStream::error_stream(),
1550         "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
1551     vm_exit(1);
1552   }
1553 
1554   // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
1555   // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
1556   // we set them to 1024 and 1024.
1557   // See CR 6362902.
1558   if (FLAG_IS_DEFAULT(YoungPLABSize)) {
1559     FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
1560   }
1561   if (FLAG_IS_DEFAULT(OldPLABSize)) {
1562     FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
1563   }
1564 
1565   // When using compressed oops, we use local overflow stacks,
1566   // rather than using a global overflow list chained through
1567   // the klass word of the object's pre-image.
1568   if (UseCompressedOops && !ParGCUseLocalOverflow) {
1569     if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
1570       warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
1571     }
1572     FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
1573   }
1574   assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
1575 }
1576 
1577 // Adjust some sizes to suit CMS and/or ParNew needs; these work well on
1578 // sparc/solaris for certain applications, but would gain from
1579 // further optimization and tuning efforts, and would almost
1580 // certainly gain from analysis of platform and environment.
1581 void Arguments::set_cms_and_parnew_gc_flags() {
1582   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
1583   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1584   assert(UseParNewGC, "ParNew should always be used with CMS");
1585 
1586   // Turn off AdaptiveSizePolicy by default for cms until it is complete.
1587   disable_adaptive_size_policy("UseConcMarkSweepGC");
1588 
1589   set_parnew_gc_flags();
1590 
1591   size_t max_heap = align_size_down(MaxHeapSize,
1592                                     CardTableRS::ct_max_alignment_constraint());
1593 
1594   // Now make adjustments for CMS
1595   intx   tenuring_default = (intx)6;
1596   size_t young_gen_per_worker = CMSYoungGenPerWorker;
1597 
1598   // Preferred young gen size for "short" pauses:
1599   // upper bound depends on # of threads and NewRatio.
1600   const size_t preferred_max_new_size_unaligned =
1601     MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * ParallelGCThreads));
1602   size_t preferred_max_new_size =
1603     align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
1604 
1605   // Unless explicitly requested otherwise, size young gen
1606   // for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
1607 
1608   // If either MaxNewSize or NewRatio is set on the command line,
1609   // assume the user is trying to set the size of the young gen.
1610   if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
1611 
1612     // Set MaxNewSize to our calculated preferred_max_new_size unless
1613     // NewSize was set on the command line and it is larger than
1614     // preferred_max_new_size.
1615     if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
1616       FLAG_SET_ERGO(size_t, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
1617     } else {
1618       FLAG_SET_ERGO(size_t, MaxNewSize, preferred_max_new_size);
1619     }
1620     log_trace(gc, heap)("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
1621 
1622     // Code along this path potentially sets NewSize and OldSize
1623     log_trace(gc, heap)("CMS set min_heap_size: " SIZE_FORMAT " initial_heap_size:  " SIZE_FORMAT " max_heap: " SIZE_FORMAT,
1624                         min_heap_size(), InitialHeapSize, max_heap);
1625     size_t min_new = preferred_max_new_size;
1626     if (FLAG_IS_CMDLINE(NewSize)) {
1627       min_new = NewSize;
1628     }
1629     if (max_heap > min_new && min_heap_size() > min_new) {
1630       // Unless explicitly requested otherwise, make young gen
1631       // at least min_new, and at most preferred_max_new_size.
1632       if (FLAG_IS_DEFAULT(NewSize)) {
1633         FLAG_SET_ERGO(size_t, NewSize, MAX2(NewSize, min_new));
1634         FLAG_SET_ERGO(size_t, NewSize, MIN2(preferred_max_new_size, NewSize));
1635         log_trace(gc, heap)("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
1636       }
1637       // Unless explicitly requested otherwise, size old gen
1638       // so it's NewRatio x of NewSize.
1639       if (FLAG_IS_DEFAULT(OldSize)) {
1640         if (max_heap > NewSize) {
1641           FLAG_SET_ERGO(size_t, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
1642           log_trace(gc, heap)("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
1643         }
1644       }
1645     }
1646   }
1647   // Unless explicitly requested otherwise, definitely
1648   // promote all objects surviving "tenuring_default" scavenges.
1649   if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
1650       FLAG_IS_DEFAULT(SurvivorRatio)) {
1651     FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
1652   }
1653   // If we decided above (or user explicitly requested)
1654   // `promote all' (via MaxTenuringThreshold := 0),
1655   // prefer minuscule survivor spaces so as not to waste
1656   // space for (non-existent) survivors
1657   if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
1658     FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
1659   }
1660 
1661   // OldPLABSize is interpreted in CMS as not the size of the PLAB in words,
1662   // but rather the number of free blocks of a given size that are used when
1663   // replenishing the local per-worker free list caches.
1664   if (FLAG_IS_DEFAULT(OldPLABSize)) {
1665     if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
1666       // OldPLAB sizing manually turned off: Use a larger default setting,
1667       // unless it was manually specified. This is because a too-low value
1668       // will slow down scavenges.
1669       FLAG_SET_ERGO(size_t, OldPLABSize, CompactibleFreeListSpaceLAB::_default_static_old_plab_size); // default value before 6631166
1670     } else {
1671       FLAG_SET_DEFAULT(OldPLABSize, CompactibleFreeListSpaceLAB::_default_dynamic_old_plab_size); // old CMSParPromoteBlocksToClaim default
1672     }
1673   }
1674 
1675   // If either of the static initialization defaults have changed, note this
1676   // modification.
1677   if (!FLAG_IS_DEFAULT(OldPLABSize) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
1678     CompactibleFreeListSpaceLAB::modify_initialization(OldPLABSize, OldPLABWeight);
1679   }
1680 
1681   log_trace(gc)("MarkStackSize: %uk  MarkStackSizeMax: %uk", (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1682 }
1683 #endif // INCLUDE_ALL_GCS
1684 
1685 void set_object_alignment() {
1686   // Object alignment.
1687   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1688   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1689   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1690   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1691   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1692   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1693 
1694   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1695   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1696 
1697   // Oop encoding heap max
1698   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1699 
1700   if (SurvivorAlignmentInBytes == 0) {
1701     SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1702   }
1703 
1704 #if INCLUDE_ALL_GCS
1705   // Set CMS global values
1706   CompactibleFreeListSpace::set_cms_values();
1707 #endif // INCLUDE_ALL_GCS
1708 }
1709 
1710 size_t Arguments::max_heap_for_compressed_oops() {
1711   // Avoid sign flip.
1712   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1713   // We need to fit both the NULL page and the heap into the memory budget, while
1714   // keeping alignment constraints of the heap. To guarantee the latter, as the
1715   // NULL page is located before the heap, we pad the NULL page to the conservative
1716   // maximum alignment that the GC may ever impose upon the heap.
1717   size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
1718                                                         _conservative_max_heap_alignment);
1719 
1720   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1721   NOT_LP64(ShouldNotReachHere(); return 0);
1722 }
1723 
1724 bool Arguments::should_auto_select_low_pause_collector() {
1725   if (UseAutoGCSelectPolicy &&
1726       !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
1727       (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
1728     log_trace(gc)("Automatic selection of the low pause collector based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
1729     return true;
1730   }
1731   return false;
1732 }
1733 
1734 void Arguments::set_use_compressed_oops() {
1735 #ifndef ZERO
1736 #ifdef _LP64
1737   // MaxHeapSize is not set up properly at this point, but
1738   // the only value that can override MaxHeapSize if we are
1739   // to use UseCompressedOops is InitialHeapSize.
1740   size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1741 
1742   if (max_heap_size <= max_heap_for_compressed_oops()) {
1743 #if !defined(COMPILER1) || defined(TIERED)
1744     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1745       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1746     }
1747 #endif
1748   } else {
1749     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1750       warning("Max heap size too large for Compressed Oops");
1751       FLAG_SET_DEFAULT(UseCompressedOops, false);
1752       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1753     }
1754   }
1755 #endif // _LP64
1756 #endif // ZERO
1757 }
1758 
1759 
1760 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1761 // set_use_compressed_oops().
1762 void Arguments::set_use_compressed_klass_ptrs() {
1763 #ifndef ZERO
1764 #ifdef _LP64
1765   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1766   if (!UseCompressedOops) {
1767     if (UseCompressedClassPointers) {
1768       warning("UseCompressedClassPointers requires UseCompressedOops");
1769     }
1770     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1771   } else {
1772     // Turn on UseCompressedClassPointers too
1773     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1774       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1775     }
1776     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1777     if (UseCompressedClassPointers) {
1778       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1779         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1780         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1781       }
1782     }
1783   }
1784 #endif // _LP64
1785 #endif // !ZERO
1786 }
1787 
1788 void Arguments::set_conservative_max_heap_alignment() {
1789   // The conservative maximum required alignment for the heap is the maximum of
1790   // the alignments imposed by several sources: any requirements from the heap
1791   // itself, the collector policy and the maximum page size we may run the VM
1792   // with.
1793   size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
1794 #if INCLUDE_ALL_GCS
1795   if (UseParallelGC) {
1796     heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
1797   } else if (UseG1GC) {
1798     heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
1799   }
1800 #endif // INCLUDE_ALL_GCS
1801   _conservative_max_heap_alignment = MAX4(heap_alignment,
1802                                           (size_t)os::vm_allocation_granularity(),
1803                                           os::max_page_size(),
1804                                           CollectorPolicy::compute_heap_alignment());
1805 }
1806 
1807 bool Arguments::gc_selected() {
1808 #if INCLUDE_ALL_GCS
1809   return UseSerialGC || UseParallelGC || UseParallelOldGC || UseConcMarkSweepGC || UseG1GC;
1810 #else
1811   return UseSerialGC;
1812 #endif // INCLUDE_ALL_GCS
1813 }
1814 
1815 void Arguments::select_gc_ergonomically() {
1816 #if INCLUDE_ALL_GCS
1817   if (os::is_server_class_machine()) {
1818     if (!UseAutoGCSelectPolicy) {
1819        FLAG_SET_ERGO_IF_DEFAULT(bool, UseG1GC, true);
1820     } else {
1821       if (should_auto_select_low_pause_collector()) {
1822         FLAG_SET_ERGO_IF_DEFAULT(bool, UseConcMarkSweepGC, true);
1823         FLAG_SET_ERGO_IF_DEFAULT(bool, UseParNewGC, true);
1824       } else {
1825         FLAG_SET_ERGO_IF_DEFAULT(bool, UseParallelGC, true);
1826       }
1827     }
1828   } else {
1829     FLAG_SET_ERGO_IF_DEFAULT(bool, UseSerialGC, true);
1830   }
1831 #else
1832   UNSUPPORTED_OPTION(UseG1GC);
1833   UNSUPPORTED_OPTION(UseParallelGC);
1834   UNSUPPORTED_OPTION(UseParallelOldGC);
1835   UNSUPPORTED_OPTION(UseConcMarkSweepGC);
1836   UNSUPPORTED_OPTION(UseParNewGC);
1837   FLAG_SET_ERGO_IF_DEFAULT(bool, UseSerialGC, true);
1838 #endif // INCLUDE_ALL_GCS
1839 }
1840 
1841 void Arguments::select_gc() {
1842   if (!gc_selected()) {
1843     select_gc_ergonomically();
1844     if (!gc_selected()) {
1845       vm_exit_during_initialization("Garbage collector not selected (default collector explicitly disabled)", NULL);
1846     }
1847   }
1848 }
1849 
1850 void Arguments::set_ergonomics_flags() {
1851   select_gc();
1852 
1853 #if defined(COMPILER2) || INCLUDE_JVMCI
1854   // Shared spaces work fine with other GCs but causes bytecode rewriting
1855   // to be disabled, which hurts interpreter performance and decreases
1856   // server performance.  When -server is specified, keep the default off
1857   // unless it is asked for.  Future work: either add bytecode rewriting
1858   // at link time, or rewrite bytecodes in non-shared methods.
1859   if (!DumpSharedSpaces && !RequireSharedSpaces &&
1860       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1861     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1862   }
1863 #endif
1864 
1865   set_conservative_max_heap_alignment();
1866 
1867 #ifndef ZERO
1868 #ifdef _LP64
1869   set_use_compressed_oops();
1870 
1871   // set_use_compressed_klass_ptrs() must be called after calling
1872   // set_use_compressed_oops().
1873   set_use_compressed_klass_ptrs();
1874 
1875   // Also checks that certain machines are slower with compressed oops
1876   // in vm_version initialization code.
1877 #endif // _LP64
1878 #endif // !ZERO
1879 
1880   CodeCacheExtensions::set_ergonomics_flags();
1881 }
1882 
1883 void Arguments::set_parallel_gc_flags() {
1884   assert(UseParallelGC || UseParallelOldGC, "Error");
1885   // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1886   if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1887     FLAG_SET_DEFAULT(UseParallelOldGC, true);
1888   }
1889   FLAG_SET_DEFAULT(UseParallelGC, true);
1890 
1891   // If no heap maximum was requested explicitly, use some reasonable fraction
1892   // of the physical memory, up to a maximum of 1GB.
1893   FLAG_SET_DEFAULT(ParallelGCThreads,
1894                    Abstract_VM_Version::parallel_worker_threads());
1895   if (ParallelGCThreads == 0) {
1896     jio_fprintf(defaultStream::error_stream(),
1897         "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1898     vm_exit(1);
1899   }
1900 
1901   if (UseAdaptiveSizePolicy) {
1902     // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1903     // unless the user actually sets these flags.
1904     if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1905       FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1906     }
1907     if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1908       FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1909     }
1910   }
1911 
1912   // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1913   // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1914   // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1915   // See CR 6362902 for details.
1916   if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1917     if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1918        FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1919     }
1920     if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1921       FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1922     }
1923   }
1924 
1925   if (UseParallelOldGC) {
1926     // Par compact uses lower default values since they are treated as
1927     // minimums.  These are different defaults because of the different
1928     // interpretation and are not ergonomically set.
1929     if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1930       FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1931     }
1932   }
1933 }
1934 
1935 void Arguments::set_g1_gc_flags() {
1936   assert(UseG1GC, "Error");
1937 #if defined(COMPILER1) || INCLUDE_JVMCI
1938   FastTLABRefill = false;
1939 #endif
1940   FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1941   if (ParallelGCThreads == 0) {
1942     assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
1943     vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1944   }
1945 
1946 #if INCLUDE_ALL_GCS
1947   if (FLAG_IS_DEFAULT(G1ConcRefinementThreads)) {
1948     FLAG_SET_ERGO(uint, G1ConcRefinementThreads, ParallelGCThreads);
1949   }
1950 #endif
1951 
1952   // MarkStackSize will be set (if it hasn't been set by the user)
1953   // when concurrent marking is initialized.
1954   // Its value will be based upon the number of parallel marking threads.
1955   // But we do set the maximum mark stack size here.
1956   if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1957     FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1958   }
1959 
1960   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1961     // In G1, we want the default GC overhead goal to be higher than
1962     // it is for PS, or the heap might be expanded too aggressively.
1963     // We set it here to ~8%.
1964     FLAG_SET_DEFAULT(GCTimeRatio, 12);
1965   }
1966 
1967   // Below, we might need to calculate the pause time interval based on
1968   // the pause target. When we do so we are going to give G1 maximum
1969   // flexibility and allow it to do pauses when it needs to. So, we'll
1970   // arrange that the pause interval to be pause time target + 1 to
1971   // ensure that a) the pause time target is maximized with respect to
1972   // the pause interval and b) we maintain the invariant that pause
1973   // time target < pause interval. If the user does not want this
1974   // maximum flexibility, they will have to set the pause interval
1975   // explicitly.
1976 
1977   if (FLAG_IS_DEFAULT(MaxGCPauseMillis)) {
1978     // The default pause time target in G1 is 200ms
1979     FLAG_SET_DEFAULT(MaxGCPauseMillis, 200);
1980   }
1981 
1982   // Then, if the interval parameter was not set, set it according to
1983   // the pause time target (this will also deal with the case when the
1984   // pause time target is the default value).
1985   if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
1986     FLAG_SET_DEFAULT(GCPauseIntervalMillis, MaxGCPauseMillis + 1);
1987   }
1988 
1989   log_trace(gc)("MarkStackSize: %uk  MarkStackSizeMax: %uk", (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1990 }
1991 
1992 void Arguments::set_gc_specific_flags() {
1993 #if INCLUDE_ALL_GCS
1994   // Set per-collector flags
1995   if (UseParallelGC || UseParallelOldGC) {
1996     set_parallel_gc_flags();
1997   } else if (UseConcMarkSweepGC) {
1998     set_cms_and_parnew_gc_flags();
1999   } else if (UseG1GC) {
2000     set_g1_gc_flags();
2001   }
2002   if (AssumeMP && !UseSerialGC) {
2003     if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
2004       warning("If the number of processors is expected to increase from one, then"
2005               " you should configure the number of parallel GC threads appropriately"
2006               " using -XX:ParallelGCThreads=N");
2007     }
2008   }
2009   if (MinHeapFreeRatio == 100) {
2010     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
2011     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
2012   }
2013 
2014   // If class unloading is disabled, also disable concurrent class unloading.
2015   if (!ClassUnloading) {
2016     FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
2017     FLAG_SET_CMDLINE(bool, ClassUnloadingWithConcurrentMark, false);
2018     FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
2019   }
2020 #endif // INCLUDE_ALL_GCS
2021 }
2022 
2023 julong Arguments::limit_by_allocatable_memory(julong limit) {
2024   julong max_allocatable;
2025   julong result = limit;
2026   if (os::has_allocatable_memory_limit(&max_allocatable)) {
2027     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
2028   }
2029   return result;
2030 }
2031 
2032 // Use static initialization to get the default before parsing
2033 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
2034 
2035 void Arguments::set_heap_size() {
2036   const julong phys_mem =
2037     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
2038                             : (julong)MaxRAM;
2039 
2040   // If the maximum heap size has not been set with -Xmx,
2041   // then set it as fraction of the size of physical memory,
2042   // respecting the maximum and minimum sizes of the heap.
2043   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2044     julong reasonable_max = phys_mem / MaxRAMFraction;
2045 
2046     if (phys_mem <= MaxHeapSize * MinRAMFraction) {
2047       // Small physical memory, so use a minimum fraction of it for the heap
2048       reasonable_max = phys_mem / MinRAMFraction;
2049     } else {
2050       // Not-small physical memory, so require a heap at least
2051       // as large as MaxHeapSize
2052       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
2053     }
2054     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
2055       // Limit the heap size to ErgoHeapSizeLimit
2056       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
2057     }
2058     if (UseCompressedOops) {
2059       // Limit the heap size to the maximum possible when using compressed oops
2060       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
2061 
2062       // HeapBaseMinAddress can be greater than default but not less than.
2063       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
2064         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
2065           // matches compressed oops printing flags
2066           log_debug(gc, heap, coops)("HeapBaseMinAddress must be at least " SIZE_FORMAT
2067                                      " (" SIZE_FORMAT "G) which is greater than value given " SIZE_FORMAT,
2068                                      DefaultHeapBaseMinAddress,
2069                                      DefaultHeapBaseMinAddress/G,
2070                                      HeapBaseMinAddress);
2071           FLAG_SET_ERGO(size_t, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
2072         }
2073       }
2074 
2075       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
2076         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
2077         // but it should be not less than default MaxHeapSize.
2078         max_coop_heap -= HeapBaseMinAddress;
2079       }
2080       reasonable_max = MIN2(reasonable_max, max_coop_heap);
2081     }
2082     reasonable_max = limit_by_allocatable_memory(reasonable_max);
2083 
2084     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
2085       // An initial heap size was specified on the command line,
2086       // so be sure that the maximum size is consistent.  Done
2087       // after call to limit_by_allocatable_memory because that
2088       // method might reduce the allocation size.
2089       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
2090     }
2091 
2092     log_trace(gc, heap)("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
2093     FLAG_SET_ERGO(size_t, MaxHeapSize, (size_t)reasonable_max);
2094   }
2095 
2096   // If the minimum or initial heap_size have not been set or requested to be set
2097   // ergonomically, set them accordingly.
2098   if (InitialHeapSize == 0 || min_heap_size() == 0) {
2099     julong reasonable_minimum = (julong)(OldSize + NewSize);
2100 
2101     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
2102 
2103     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
2104 
2105     if (InitialHeapSize == 0) {
2106       julong reasonable_initial = phys_mem / InitialRAMFraction;
2107 
2108       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
2109       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
2110 
2111       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
2112 
2113       log_trace(gc, heap)("  Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
2114       FLAG_SET_ERGO(size_t, InitialHeapSize, (size_t)reasonable_initial);
2115     }
2116     // If the minimum heap size has not been set (via -Xms),
2117     // synchronize with InitialHeapSize to avoid errors with the default value.
2118     if (min_heap_size() == 0) {
2119       set_min_heap_size(MIN2((size_t)reasonable_minimum, InitialHeapSize));
2120       log_trace(gc, heap)("  Minimum heap size " SIZE_FORMAT, min_heap_size());
2121     }
2122   }
2123 }
2124 
2125 // This option inspects the machine and attempts to set various
2126 // parameters to be optimal for long-running, memory allocation
2127 // intensive jobs.  It is intended for machines with large
2128 // amounts of cpu and memory.
2129 jint Arguments::set_aggressive_heap_flags() {
2130   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
2131   // VM, but we may not be able to represent the total physical memory
2132   // available (like having 8gb of memory on a box but using a 32bit VM).
2133   // Thus, we need to make sure we're using a julong for intermediate
2134   // calculations.
2135   julong initHeapSize;
2136   julong total_memory = os::physical_memory();
2137 
2138   if (total_memory < (julong) 256 * M) {
2139     jio_fprintf(defaultStream::error_stream(),
2140             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
2141     vm_exit(1);
2142   }
2143 
2144   // The heap size is half of available memory, or (at most)
2145   // all of possible memory less 160mb (leaving room for the OS
2146   // when using ISM).  This is the maximum; because adaptive sizing
2147   // is turned on below, the actual space used may be smaller.
2148 
2149   initHeapSize = MIN2(total_memory / (julong) 2,
2150           total_memory - (julong) 160 * M);
2151 
2152   initHeapSize = limit_by_allocatable_memory(initHeapSize);
2153 
2154   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2155     if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, initHeapSize) != Flag::SUCCESS) {
2156       return JNI_EINVAL;
2157     }
2158     if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, initHeapSize) != Flag::SUCCESS) {
2159       return JNI_EINVAL;
2160     }
2161     // Currently the minimum size and the initial heap sizes are the same.
2162     set_min_heap_size(initHeapSize);
2163   }
2164   if (FLAG_IS_DEFAULT(NewSize)) {
2165     // Make the young generation 3/8ths of the total heap.
2166     if (FLAG_SET_CMDLINE(size_t, NewSize,
2167             ((julong) MaxHeapSize / (julong) 8) * (julong) 3) != Flag::SUCCESS) {
2168       return JNI_EINVAL;
2169     }
2170     if (FLAG_SET_CMDLINE(size_t, MaxNewSize, NewSize) != Flag::SUCCESS) {
2171       return JNI_EINVAL;
2172     }
2173   }
2174 
2175 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
2176   FLAG_SET_DEFAULT(UseLargePages, true);
2177 #endif
2178 
2179   // Increase some data structure sizes for efficiency
2180   if (FLAG_SET_CMDLINE(size_t, BaseFootPrintEstimate, MaxHeapSize) != Flag::SUCCESS) {
2181     return JNI_EINVAL;
2182   }
2183   if (FLAG_SET_CMDLINE(bool, ResizeTLAB, false) != Flag::SUCCESS) {
2184     return JNI_EINVAL;
2185   }
2186   if (FLAG_SET_CMDLINE(size_t, TLABSize, 256 * K) != Flag::SUCCESS) {
2187     return JNI_EINVAL;
2188   }
2189 
2190   // See the OldPLABSize comment below, but replace 'after promotion'
2191   // with 'after copying'.  YoungPLABSize is the size of the survivor
2192   // space per-gc-thread buffers.  The default is 4kw.
2193   if (FLAG_SET_CMDLINE(size_t, YoungPLABSize, 256 * K) != Flag::SUCCESS) { // Note: this is in words
2194     return JNI_EINVAL;
2195   }
2196 
2197   // OldPLABSize is the size of the buffers in the old gen that
2198   // UseParallelGC uses to promote live data that doesn't fit in the
2199   // survivor spaces.  At any given time, there's one for each gc thread.
2200   // The default size is 1kw. These buffers are rarely used, since the
2201   // survivor spaces are usually big enough.  For specjbb, however, there
2202   // are occasions when there's lots of live data in the young gen
2203   // and we end up promoting some of it.  We don't have a definite
2204   // explanation for why bumping OldPLABSize helps, but the theory
2205   // is that a bigger PLAB results in retaining something like the
2206   // original allocation order after promotion, which improves mutator
2207   // locality.  A minor effect may be that larger PLABs reduce the
2208   // number of PLAB allocation events during gc.  The value of 8kw
2209   // was arrived at by experimenting with specjbb.
2210   if (FLAG_SET_CMDLINE(size_t, OldPLABSize, 8 * K) != Flag::SUCCESS) { // Note: this is in words
2211     return JNI_EINVAL;
2212   }
2213 
2214   // Enable parallel GC and adaptive generation sizing
2215   if (FLAG_SET_CMDLINE(bool, UseParallelGC, true) != Flag::SUCCESS) {
2216     return JNI_EINVAL;
2217   }
2218   FLAG_SET_DEFAULT(ParallelGCThreads,
2219           Abstract_VM_Version::parallel_worker_threads());
2220 
2221   // Encourage steady state memory management
2222   if (FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100) != Flag::SUCCESS) {
2223     return JNI_EINVAL;
2224   }
2225 
2226   // This appears to improve mutator locality
2227   if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2228     return JNI_EINVAL;
2229   }
2230 
2231   // Get around early Solaris scheduling bug
2232   // (affinity vs other jobs on system)
2233   // but disallow DR and offlining (5008695).
2234   if (FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true) != Flag::SUCCESS) {
2235     return JNI_EINVAL;
2236   }
2237 
2238   return JNI_OK;
2239 }
2240 
2241 // This must be called after ergonomics.
2242 void Arguments::set_bytecode_flags() {
2243   if (!RewriteBytecodes) {
2244     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
2245   }
2246 }
2247 
2248 // Aggressive optimization flags  -XX:+AggressiveOpts
2249 jint Arguments::set_aggressive_opts_flags() {
2250 #ifdef COMPILER2
2251   if (AggressiveUnboxing) {
2252     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2253       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2254     } else if (!EliminateAutoBox) {
2255       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
2256       AggressiveUnboxing = false;
2257     }
2258     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
2259       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
2260     } else if (!DoEscapeAnalysis) {
2261       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
2262       AggressiveUnboxing = false;
2263     }
2264   }
2265   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2266     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2267       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2268     }
2269     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2270       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
2271     }
2272 
2273     // Feed the cache size setting into the JDK
2274     char buffer[1024];
2275     jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
2276     if (!add_property(buffer)) {
2277       return JNI_ENOMEM;
2278     }
2279   }
2280   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
2281     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
2282   }
2283 #endif
2284 
2285   if (AggressiveOpts) {
2286 // Sample flag setting code
2287 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
2288 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
2289 //    }
2290   }
2291 
2292   return JNI_OK;
2293 }
2294 
2295 //===========================================================================================================
2296 // Parsing of java.compiler property
2297 
2298 void Arguments::process_java_compiler_argument(const char* arg) {
2299   // For backwards compatibility, Djava.compiler=NONE or ""
2300   // causes us to switch to -Xint mode UNLESS -Xdebug
2301   // is also specified.
2302   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
2303     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
2304   }
2305 }
2306 
2307 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
2308   _sun_java_launcher = os::strdup_check_oom(launcher);
2309 }
2310 
2311 bool Arguments::created_by_java_launcher() {
2312   assert(_sun_java_launcher != NULL, "property must have value");
2313   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
2314 }
2315 
2316 bool Arguments::sun_java_launcher_is_altjvm() {
2317   return _sun_java_launcher_is_altjvm;
2318 }
2319 
2320 //===========================================================================================================
2321 // Parsing of main arguments
2322 
2323 #if INCLUDE_JVMCI
2324 // Check consistency of jvmci vm argument settings.
2325 bool Arguments::check_jvmci_args_consistency() {
2326    return JVMCIGlobals::check_jvmci_flags_are_consistent();
2327 }
2328 #endif //INCLUDE_JVMCI
2329 
2330 // Check consistency of GC selection
2331 bool Arguments::check_gc_consistency() {
2332   // Ensure that the user has not selected conflicting sets
2333   // of collectors.
2334   uint i = 0;
2335   if (UseSerialGC)                       i++;
2336   if (UseConcMarkSweepGC)                i++;
2337   if (UseParallelGC || UseParallelOldGC) i++;
2338   if (UseG1GC)                           i++;
2339   if (i > 1) {
2340     jio_fprintf(defaultStream::error_stream(),
2341                 "Conflicting collector combinations in option list; "
2342                 "please refer to the release notes for the combinations "
2343                 "allowed\n");
2344     return false;
2345   }
2346 
2347   if (UseConcMarkSweepGC && !UseParNewGC) {
2348     jio_fprintf(defaultStream::error_stream(),
2349         "It is not possible to combine the DefNew young collector with the CMS collector.\n");
2350     return false;
2351   }
2352 
2353   if (UseParNewGC && !UseConcMarkSweepGC) {
2354     jio_fprintf(defaultStream::error_stream(),
2355         "It is not possible to combine the ParNew young collector with any collector other than CMS.\n");
2356     return false;
2357   }
2358 
2359   return true;
2360 }
2361 
2362 // Check the consistency of vm_init_args
2363 bool Arguments::check_vm_args_consistency() {
2364   // Method for adding checks for flag consistency.
2365   // The intent is to warn the user of all possible conflicts,
2366   // before returning an error.
2367   // Note: Needs platform-dependent factoring.
2368   bool status = true;
2369 
2370   if (TLABRefillWasteFraction == 0) {
2371     jio_fprintf(defaultStream::error_stream(),
2372                 "TLABRefillWasteFraction should be a denominator, "
2373                 "not " SIZE_FORMAT "\n",
2374                 TLABRefillWasteFraction);
2375     status = false;
2376   }
2377 
2378   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2379     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
2380   }
2381 
2382   if (!(UseParallelGC || UseParallelOldGC) && FLAG_IS_DEFAULT(ScavengeBeforeFullGC)) {
2383     FLAG_SET_DEFAULT(ScavengeBeforeFullGC, false);
2384   }
2385 
2386   if (GCTimeLimit == 100) {
2387     // Turn off gc-overhead-limit-exceeded checks
2388     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2389   }
2390 
2391   status = status && check_gc_consistency();
2392 
2393   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2394   // insists that we hold the requisite locks so that the iteration is
2395   // MT-safe. For the verification at start-up and shut-down, we don't
2396   // yet have a good way of acquiring and releasing these locks,
2397   // which are not visible at the CollectedHeap level. We want to
2398   // be able to acquire these locks and then do the iteration rather
2399   // than just disable the lock verification. This will be fixed under
2400   // bug 4788986.
2401   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2402     if (VerifyDuringStartup) {
2403       warning("Heap verification at start-up disabled "
2404               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2405       VerifyDuringStartup = false; // Disable verification at start-up
2406     }
2407 
2408     if (VerifyBeforeExit) {
2409       warning("Heap verification at shutdown disabled "
2410               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2411       VerifyBeforeExit = false; // Disable verification at shutdown
2412     }
2413   }
2414 
2415   if (PrintNMTStatistics) {
2416 #if INCLUDE_NMT
2417     if (MemTracker::tracking_level() == NMT_off) {
2418 #endif // INCLUDE_NMT
2419       warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2420       PrintNMTStatistics = false;
2421 #if INCLUDE_NMT
2422     }
2423 #endif
2424   }
2425 #if INCLUDE_JVMCI
2426 
2427   status = status && check_jvmci_args_consistency();
2428 
2429   if (EnableJVMCI) {
2430     if (!ScavengeRootsInCode) {
2431       warning("forcing ScavengeRootsInCode non-zero because JVMCI is enabled");
2432       ScavengeRootsInCode = 1;
2433     }
2434     if (FLAG_IS_DEFAULT(TypeProfileLevel)) {
2435       TypeProfileLevel = 0;
2436     }
2437     if (UseJVMCICompiler) {
2438       if (FLAG_IS_DEFAULT(TypeProfileWidth)) {
2439         TypeProfileWidth = 8;
2440       }
2441     }
2442   }
2443 #endif
2444 
2445   // Check lower bounds of the code cache
2446   // Template Interpreter code is approximately 3X larger in debug builds.
2447   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2448   if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2449     jio_fprintf(defaultStream::error_stream(),
2450                 "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
2451                 os::vm_page_size()/K);
2452     status = false;
2453   } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2454     jio_fprintf(defaultStream::error_stream(),
2455                 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2456                 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2457     status = false;
2458   } else if (ReservedCodeCacheSize < min_code_cache_size) {
2459     jio_fprintf(defaultStream::error_stream(),
2460                 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2461                 min_code_cache_size/K);
2462     status = false;
2463   } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2464     // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2465     jio_fprintf(defaultStream::error_stream(),
2466                 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2467                 CODE_CACHE_SIZE_LIMIT/M);
2468     status = false;
2469   } else if (NonNMethodCodeHeapSize < min_code_cache_size) {
2470     jio_fprintf(defaultStream::error_stream(),
2471                 "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2472                 min_code_cache_size/K);
2473     status = false;
2474   }
2475 
2476 #ifdef _LP64
2477   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2478     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2479   }
2480 #endif
2481 
2482 #ifndef SUPPORT_RESERVED_STACK_AREA
2483   if (StackReservedPages != 0) {
2484     FLAG_SET_CMDLINE(intx, StackReservedPages, 0);
2485     warning("Reserved Stack Area not supported on this platform");
2486   }
2487 #endif
2488 
2489   if (BackgroundCompilation && (CompileTheWorld || ReplayCompiles)) {
2490     if (!FLAG_IS_DEFAULT(BackgroundCompilation)) {
2491       warning("BackgroundCompilation disabled due to CompileTheWorld or ReplayCompiles options.");
2492     }
2493     FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2494   }
2495   if (UseCompiler && is_interpreter_only()) {
2496     if (!FLAG_IS_DEFAULT(UseCompiler)) {
2497       warning("UseCompiler disabled due to -Xint.");
2498     }
2499     FLAG_SET_CMDLINE(bool, UseCompiler, false);
2500   }
2501 #ifdef COMPILER2
2502   if (PostLoopMultiversioning && !RangeCheckElimination) {
2503     if (!FLAG_IS_DEFAULT(PostLoopMultiversioning)) {
2504       warning("PostLoopMultiversioning disabled because RangeCheckElimination is disabled.");
2505     }
2506     FLAG_SET_CMDLINE(bool, PostLoopMultiversioning, false);
2507   }
2508 #endif
2509   return status;
2510 }
2511 
2512 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2513   const char* option_type) {
2514   if (ignore) return false;
2515 
2516   const char* spacer = " ";
2517   if (option_type == NULL) {
2518     option_type = ++spacer; // Set both to the empty string.
2519   }
2520 
2521   if (os::obsolete_option(option)) {
2522     jio_fprintf(defaultStream::error_stream(),
2523                 "Obsolete %s%soption: %s\n", option_type, spacer,
2524       option->optionString);
2525     return false;
2526   } else {
2527     jio_fprintf(defaultStream::error_stream(),
2528                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2529       option->optionString);
2530     return true;
2531   }
2532 }
2533 
2534 static const char* user_assertion_options[] = {
2535   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2536 };
2537 
2538 static const char* system_assertion_options[] = {
2539   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2540 };
2541 
2542 bool Arguments::parse_uintx(const char* value,
2543                             uintx* uintx_arg,
2544                             uintx min_size) {
2545 
2546   // Check the sign first since atojulong() parses only unsigned values.
2547   bool value_is_positive = !(*value == '-');
2548 
2549   if (value_is_positive) {
2550     julong n;
2551     bool good_return = atojulong(value, &n);
2552     if (good_return) {
2553       bool above_minimum = n >= min_size;
2554       bool value_is_too_large = n > max_uintx;
2555 
2556       if (above_minimum && !value_is_too_large) {
2557         *uintx_arg = n;
2558         return true;
2559       }
2560     }
2561   }
2562   return false;
2563 }
2564 
2565 unsigned int addreads_count = 0;
2566 unsigned int addexports_count = 0;
2567 unsigned int addmods_count = 0;
2568 unsigned int patch_mod_count = 0;
2569 
2570 bool Arguments::create_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
2571   size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
2572   char* property = AllocateHeap(prop_len, mtArguments);
2573   int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);
2574   if (ret < 0 || ret >= (int)prop_len) {
2575     FreeHeap(property);
2576     return false;
2577   }
2578   bool added = add_property(property, UnwriteableProperty, internal);
2579   FreeHeap(property);
2580   return added;
2581 }
2582 
2583 bool Arguments::create_numbered_property(const char* prop_base_name, const char* prop_value, unsigned int count) {
2584   // Make sure count is < 1,000. Otherwise, memory allocation will be too small.
2585   if (count < 1000) {
2586     size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + 5;
2587     char* property = AllocateHeap(prop_len, mtArguments);
2588     int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);
2589     if (ret < 0 || ret >= (int)prop_len) {
2590       FreeHeap(property);
2591       return false;
2592     }
2593     bool added = add_property(property, UnwriteableProperty, InternalProperty);
2594     FreeHeap(property);
2595     return added;
2596   }
2597   return false;
2598 }
2599 
2600 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2601                                                   julong* long_arg,
2602                                                   julong min_size) {
2603   if (!atojulong(s, long_arg)) return arg_unreadable;
2604   return check_memory_size(*long_arg, min_size);
2605 }
2606 
2607 // Parse JavaVMInitArgs structure
2608 
2609 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *java_tool_options_args,
2610                                    const JavaVMInitArgs *java_options_args,
2611                                    const JavaVMInitArgs *cmd_line_args) {
2612   bool patch_mod_javabase = false;
2613 
2614   // Save default settings for some mode flags
2615   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2616   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2617   Arguments::_ClipInlining             = ClipInlining;
2618   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2619   if (TieredCompilation) {
2620     Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2621     Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2622   }
2623 
2624   // Setup flags for mixed which is the default
2625   set_mode_flags(_mixed);
2626 
2627   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2628   // variable (if present).
2629   jint result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
2630   if (result != JNI_OK) {
2631     return result;
2632   }
2633 
2634   // Parse args structure generated from the command line flags.
2635   result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, Flag::COMMAND_LINE);
2636   if (result != JNI_OK) {
2637     return result;
2638   }
2639 
2640   // Parse args structure generated from the _JAVA_OPTIONS environment
2641   // variable (if present) (mimics classic VM)
2642   result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
2643   if (result != JNI_OK) {
2644     return result;
2645   }
2646 
2647   // Do final processing now that all arguments have been parsed
2648   result = finalize_vm_init_args();
2649   if (result != JNI_OK) {
2650     return result;
2651   }
2652 
2653   return JNI_OK;
2654 }
2655 
2656 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2657 // represents a valid JDWP agent.  is_path==true denotes that we
2658 // are dealing with -agentpath (case where name is a path), otherwise with
2659 // -agentlib
2660 bool valid_jdwp_agent(char *name, bool is_path) {
2661   char *_name;
2662   const char *_jdwp = "jdwp";
2663   size_t _len_jdwp, _len_prefix;
2664 
2665   if (is_path) {
2666     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2667       return false;
2668     }
2669 
2670     _name++;  // skip past last path separator
2671     _len_prefix = strlen(JNI_LIB_PREFIX);
2672 
2673     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2674       return false;
2675     }
2676 
2677     _name += _len_prefix;
2678     _len_jdwp = strlen(_jdwp);
2679 
2680     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2681       _name += _len_jdwp;
2682     }
2683     else {
2684       return false;
2685     }
2686 
2687     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2688       return false;
2689     }
2690 
2691     return true;
2692   }
2693 
2694   if (strcmp(name, _jdwp) == 0) {
2695     return true;
2696   }
2697 
2698   return false;
2699 }
2700 
2701 int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {
2702   // --patch-module=<module>=<file>(<pathsep><file>)*
2703   assert(patch_mod_tail != NULL, "Unexpected NULL patch-module value");
2704   // Find the equal sign between the module name and the path specification
2705   const char* module_equal = strchr(patch_mod_tail, '=');
2706   if (module_equal == NULL) {
2707     jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");
2708     return JNI_ERR;
2709   } else {
2710     // Pick out the module name
2711     size_t module_len = module_equal - patch_mod_tail;
2712     char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);
2713     if (module_name != NULL) {
2714       memcpy(module_name, patch_mod_tail, module_len);
2715       *(module_name + module_len) = '\0';
2716       // The path piece begins one past the module_equal sign
2717       add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);
2718       FREE_C_HEAP_ARRAY(char, module_name);
2719       if (!create_numbered_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {
2720         return JNI_ENOMEM;
2721       }
2722     } else {
2723       return JNI_ENOMEM;
2724     }
2725   }
2726   return JNI_OK;
2727 }
2728 
2729 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, Flag::Flags origin) {
2730   // For match_option to return remaining or value part of option string
2731   const char* tail;
2732 
2733   // iterate over arguments
2734   for (int index = 0; index < args->nOptions; index++) {
2735     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2736 
2737     const JavaVMOption* option = args->options + index;
2738 
2739     if (!match_option(option, "-Djava.class.path", &tail) &&
2740         !match_option(option, "-Dsun.java.command", &tail) &&
2741         !match_option(option, "-Dsun.java.launcher", &tail)) {
2742 
2743         // add all jvm options to the jvm_args string. This string
2744         // is used later to set the java.vm.args PerfData string constant.
2745         // the -Djava.class.path and the -Dsun.java.command options are
2746         // omitted from jvm_args string as each have their own PerfData
2747         // string constant object.
2748         build_jvm_args(option->optionString);
2749     }
2750 
2751     // -verbose:[class/gc/jni]
2752     if (match_option(option, "-verbose", &tail)) {
2753       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2754         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));
2755         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));
2756       } else if (!strcmp(tail, ":gc")) {
2757         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(gc));
2758       } else if (!strcmp(tail, ":jni")) {
2759         if (FLAG_SET_CMDLINE(bool, PrintJNIResolving, true) != Flag::SUCCESS) {
2760           return JNI_EINVAL;
2761         }
2762       }
2763     // -da / -ea / -disableassertions / -enableassertions
2764     // These accept an optional class/package name separated by a colon, e.g.,
2765     // -da:java.lang.Thread.
2766     } else if (match_option(option, user_assertion_options, &tail, true)) {
2767       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2768       if (*tail == '\0') {
2769         JavaAssertions::setUserClassDefault(enable);
2770       } else {
2771         assert(*tail == ':', "bogus match by match_option()");
2772         JavaAssertions::addOption(tail + 1, enable);
2773       }
2774     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2775     } else if (match_option(option, system_assertion_options, &tail, false)) {
2776       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2777       JavaAssertions::setSystemClassDefault(enable);
2778     // -bootclasspath:
2779     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2780         jio_fprintf(defaultStream::output_stream(),
2781           "-Xbootclasspath is no longer a supported option.\n");
2782         return JNI_EINVAL;
2783     // -bootclasspath/a:
2784     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2785       Arguments::append_sysclasspath(tail);
2786     // -bootclasspath/p:
2787     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2788         jio_fprintf(defaultStream::output_stream(),
2789           "-Xbootclasspath/p is no longer a supported option.\n");
2790         return JNI_EINVAL;
2791     // -Xrun
2792     } else if (match_option(option, "-Xrun", &tail)) {
2793       if (tail != NULL) {
2794         const char* pos = strchr(tail, ':');
2795         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2796         char* name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2797         jio_snprintf(name, len + 1, "%s", tail);
2798 
2799         char *options = NULL;
2800         if(pos != NULL) {
2801           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2802           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);
2803         }
2804 #if !INCLUDE_JVMTI
2805         if (strcmp(name, "jdwp") == 0) {
2806           jio_fprintf(defaultStream::error_stream(),
2807             "Debugging agents are not supported in this VM\n");
2808           return JNI_ERR;
2809         }
2810 #endif // !INCLUDE_JVMTI
2811         add_init_library(name, options);
2812       }
2813     } else if (match_option(option, "--add-reads=", &tail)) {
2814       if (!create_numbered_property("jdk.module.addreads", tail, addreads_count++)) {
2815         return JNI_ENOMEM;
2816       }
2817     } else if (match_option(option, "--add-exports=", &tail)) {
2818       if (!create_numbered_property("jdk.module.addexports", tail, addexports_count++)) {
2819         return JNI_ENOMEM;
2820       }
2821     } else if (match_option(option, "--add-modules=", &tail)) {
2822       if (!create_numbered_property("jdk.module.addmods", tail, addmods_count++)) {
2823         return JNI_ENOMEM;
2824       }
2825     } else if (match_option(option, "--limit-modules=", &tail)) {
2826       if (!create_property("jdk.module.limitmods", tail, InternalProperty)) {
2827         return JNI_ENOMEM;
2828       }
2829     } else if (match_option(option, "--module-path=", &tail)) {
2830       if (!create_property("jdk.module.path", tail, ExternalProperty)) {
2831         return JNI_ENOMEM;
2832       }
2833     } else if (match_option(option, "--upgrade-module-path=", &tail)) {
2834       if (!create_property("jdk.module.upgrade.path", tail, ExternalProperty)) {
2835         return JNI_ENOMEM;
2836       }
2837     } else if (match_option(option, "--patch-module=", &tail)) {
2838       // --patch-module=<module>=<file>(<pathsep><file>)*
2839       int res = process_patch_mod_option(tail, patch_mod_javabase);
2840       if (res != JNI_OK) {
2841         return res;
2842       }
2843     // -agentlib and -agentpath
2844     } else if (match_option(option, "-agentlib:", &tail) ||
2845           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2846       if(tail != NULL) {
2847         const char* pos = strchr(tail, '=');
2848         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2849         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtArguments), tail, len);
2850         name[len] = '\0';
2851 
2852         char *options = NULL;
2853         if(pos != NULL) {
2854           options = os::strdup_check_oom(pos + 1, mtArguments);
2855         }
2856 #if !INCLUDE_JVMTI
2857         if (valid_jdwp_agent(name, is_absolute_path)) {
2858           jio_fprintf(defaultStream::error_stream(),
2859             "Debugging agents are not supported in this VM\n");
2860           return JNI_ERR;
2861         }
2862 #endif // !INCLUDE_JVMTI
2863         add_init_agent(name, options, is_absolute_path);
2864       }
2865     // -javaagent
2866     } else if (match_option(option, "-javaagent:", &tail)) {
2867 #if !INCLUDE_JVMTI
2868       jio_fprintf(defaultStream::error_stream(),
2869         "Instrumentation agents are not supported in this VM\n");
2870       return JNI_ERR;
2871 #else
2872       if (tail != NULL) {
2873         size_t length = strlen(tail) + 1;
2874         char *options = NEW_C_HEAP_ARRAY(char, length, mtArguments);
2875         jio_snprintf(options, length, "%s", tail);
2876         add_init_agent("instrument", options, false);
2877         // java agents need module java.instrument
2878         if (!create_numbered_property("jdk.module.addmods", "java.instrument", addmods_count++)) {
2879           return JNI_ENOMEM;
2880         }
2881       }
2882 #endif // !INCLUDE_JVMTI
2883     // -Xnoclassgc
2884     } else if (match_option(option, "-Xnoclassgc")) {
2885       if (FLAG_SET_CMDLINE(bool, ClassUnloading, false) != Flag::SUCCESS) {
2886         return JNI_EINVAL;
2887       }
2888     // -Xconcgc
2889     } else if (match_option(option, "-Xconcgc")) {
2890       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true) != Flag::SUCCESS) {
2891         return JNI_EINVAL;
2892       }
2893       handle_extra_cms_flags("-Xconcgc uses UseConcMarkSweepGC");
2894     // -Xnoconcgc
2895     } else if (match_option(option, "-Xnoconcgc")) {
2896       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false) != Flag::SUCCESS) {
2897         return JNI_EINVAL;
2898       }
2899       handle_extra_cms_flags("-Xnoconcgc uses UseConcMarkSweepGC");
2900     // -Xbatch
2901     } else if (match_option(option, "-Xbatch")) {
2902       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2903         return JNI_EINVAL;
2904       }
2905     // -Xmn for compatibility with other JVM vendors
2906     } else if (match_option(option, "-Xmn", &tail)) {
2907       julong long_initial_young_size = 0;
2908       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2909       if (errcode != arg_in_range) {
2910         jio_fprintf(defaultStream::error_stream(),
2911                     "Invalid initial young generation size: %s\n", option->optionString);
2912         describe_range_error(errcode);
2913         return JNI_EINVAL;
2914       }
2915       if (FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2916         return JNI_EINVAL;
2917       }
2918       if (FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2919         return JNI_EINVAL;
2920       }
2921     // -Xms
2922     } else if (match_option(option, "-Xms", &tail)) {
2923       julong long_initial_heap_size = 0;
2924       // an initial heap size of 0 means automatically determine
2925       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2926       if (errcode != arg_in_range) {
2927         jio_fprintf(defaultStream::error_stream(),
2928                     "Invalid initial heap size: %s\n", option->optionString);
2929         describe_range_error(errcode);
2930         return JNI_EINVAL;
2931       }
2932       set_min_heap_size((size_t)long_initial_heap_size);
2933       // Currently the minimum size and the initial heap sizes are the same.
2934       // Can be overridden with -XX:InitialHeapSize.
2935       if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size) != Flag::SUCCESS) {
2936         return JNI_EINVAL;
2937       }
2938     // -Xmx
2939     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2940       julong long_max_heap_size = 0;
2941       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2942       if (errcode != arg_in_range) {
2943         jio_fprintf(defaultStream::error_stream(),
2944                     "Invalid maximum heap size: %s\n", option->optionString);
2945         describe_range_error(errcode);
2946         return JNI_EINVAL;
2947       }
2948       if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size) != Flag::SUCCESS) {
2949         return JNI_EINVAL;
2950       }
2951     // Xmaxf
2952     } else if (match_option(option, "-Xmaxf", &tail)) {
2953       char* err;
2954       int maxf = (int)(strtod(tail, &err) * 100);
2955       if (*err != '\0' || *tail == '\0') {
2956         jio_fprintf(defaultStream::error_stream(),
2957                     "Bad max heap free percentage size: %s\n",
2958                     option->optionString);
2959         return JNI_EINVAL;
2960       } else {
2961         if (FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf) != Flag::SUCCESS) {
2962             return JNI_EINVAL;
2963         }
2964       }
2965     // Xminf
2966     } else if (match_option(option, "-Xminf", &tail)) {
2967       char* err;
2968       int minf = (int)(strtod(tail, &err) * 100);
2969       if (*err != '\0' || *tail == '\0') {
2970         jio_fprintf(defaultStream::error_stream(),
2971                     "Bad min heap free percentage size: %s\n",
2972                     option->optionString);
2973         return JNI_EINVAL;
2974       } else {
2975         if (FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf) != Flag::SUCCESS) {
2976           return JNI_EINVAL;
2977         }
2978       }
2979     // -Xss
2980     } else if (match_option(option, "-Xss", &tail)) {
2981       julong long_ThreadStackSize = 0;
2982       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2983       if (errcode != arg_in_range) {
2984         jio_fprintf(defaultStream::error_stream(),
2985                     "Invalid thread stack size: %s\n", option->optionString);
2986         describe_range_error(errcode);
2987         return JNI_EINVAL;
2988       }
2989       // Internally track ThreadStackSize in units of 1024 bytes.
2990       if (FLAG_SET_CMDLINE(intx, ThreadStackSize,
2991                        round_to((int)long_ThreadStackSize, K) / K) != Flag::SUCCESS) {
2992         return JNI_EINVAL;
2993       }
2994     // -Xoss, -Xsqnopause, -Xoptimize, -Xboundthreads, -Xusealtsigs
2995     } else if (match_option(option, "-Xoss", &tail) ||
2996                match_option(option, "-Xsqnopause") ||
2997                match_option(option, "-Xoptimize") ||
2998                match_option(option, "-Xboundthreads") ||
2999                match_option(option, "-Xusealtsigs")) {
3000       // All these options are deprecated in JDK 9 and will be removed in a future release
3001       char version[256];
3002       JDK_Version::jdk(9).to_string(version, sizeof(version));
3003       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
3004     } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
3005       julong long_CodeCacheExpansionSize = 0;
3006       ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
3007       if (errcode != arg_in_range) {
3008         jio_fprintf(defaultStream::error_stream(),
3009                    "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
3010                    os::vm_page_size()/K);
3011         return JNI_EINVAL;
3012       }
3013       if (FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize) != Flag::SUCCESS) {
3014         return JNI_EINVAL;
3015       }
3016     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
3017                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
3018       julong long_ReservedCodeCacheSize = 0;
3019 
3020       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
3021       if (errcode != arg_in_range) {
3022         jio_fprintf(defaultStream::error_stream(),
3023                     "Invalid maximum code cache size: %s.\n", option->optionString);
3024         return JNI_EINVAL;
3025       }
3026       if (FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != Flag::SUCCESS) {
3027         return JNI_EINVAL;
3028       }
3029       // -XX:NonNMethodCodeHeapSize=
3030     } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
3031       julong long_NonNMethodCodeHeapSize = 0;
3032 
3033       ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
3034       if (errcode != arg_in_range) {
3035         jio_fprintf(defaultStream::error_stream(),
3036                     "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
3037         return JNI_EINVAL;
3038       }
3039       if (FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize) != Flag::SUCCESS) {
3040         return JNI_EINVAL;
3041       }
3042       // -XX:ProfiledCodeHeapSize=
3043     } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
3044       julong long_ProfiledCodeHeapSize = 0;
3045 
3046       ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
3047       if (errcode != arg_in_range) {
3048         jio_fprintf(defaultStream::error_stream(),
3049                     "Invalid maximum profiled code heap size: %s.\n", option->optionString);
3050         return JNI_EINVAL;
3051       }
3052       if (FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize) != Flag::SUCCESS) {
3053         return JNI_EINVAL;
3054       }
3055       // -XX:NonProfiledCodeHeapSizee=
3056     } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
3057       julong long_NonProfiledCodeHeapSize = 0;
3058 
3059       ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
3060       if (errcode != arg_in_range) {
3061         jio_fprintf(defaultStream::error_stream(),
3062                     "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
3063         return JNI_EINVAL;
3064       }
3065       if (FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize) != Flag::SUCCESS) {
3066         return JNI_EINVAL;
3067       }
3068     // -green
3069     } else if (match_option(option, "-green")) {
3070       jio_fprintf(defaultStream::error_stream(),
3071                   "Green threads support not available\n");
3072           return JNI_EINVAL;
3073     // -native
3074     } else if (match_option(option, "-native")) {
3075           // HotSpot always uses native threads, ignore silently for compatibility
3076     // -Xrs
3077     } else if (match_option(option, "-Xrs")) {
3078           // Classic/EVM option, new functionality
3079       if (FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true) != Flag::SUCCESS) {
3080         return JNI_EINVAL;
3081       }
3082     // -Xprof
3083     } else if (match_option(option, "-Xprof")) {
3084 #if INCLUDE_FPROF
3085       _has_profile = true;
3086 #else // INCLUDE_FPROF
3087       jio_fprintf(defaultStream::error_stream(),
3088         "Flat profiling is not supported in this VM.\n");
3089       return JNI_ERR;
3090 #endif // INCLUDE_FPROF
3091     // -Xconcurrentio
3092     } else if (match_option(option, "-Xconcurrentio")) {
3093       if (FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true) != Flag::SUCCESS) {
3094         return JNI_EINVAL;
3095       }
3096       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
3097         return JNI_EINVAL;
3098       }
3099       if (FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1) != Flag::SUCCESS) {
3100         return JNI_EINVAL;
3101       }
3102       if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
3103         return JNI_EINVAL;
3104       }
3105       if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
3106         return JNI_EINVAL;
3107       }
3108 
3109       // -Xinternalversion
3110     } else if (match_option(option, "-Xinternalversion")) {
3111       jio_fprintf(defaultStream::output_stream(), "%s\n",
3112                   VM_Version::internal_vm_info_string());
3113       vm_exit(0);
3114 #ifndef PRODUCT
3115     // -Xprintflags
3116     } else if (match_option(option, "-Xprintflags")) {
3117       CommandLineFlags::printFlags(tty, false);
3118       vm_exit(0);
3119 #endif
3120     // -D
3121     } else if (match_option(option, "-D", &tail)) {
3122       const char* value;
3123       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
3124             *value!= '\0' && strcmp(value, "\"\"") != 0) {
3125         // abort if -Djava.endorsed.dirs is set
3126         jio_fprintf(defaultStream::output_stream(),
3127           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
3128           "in modular form will be supported via the concept of upgradeable modules.\n", value);
3129         return JNI_EINVAL;
3130       }
3131       if (match_option(option, "-Djava.ext.dirs=", &value) &&
3132             *value != '\0' && strcmp(value, "\"\"") != 0) {
3133         // abort if -Djava.ext.dirs is set
3134         jio_fprintf(defaultStream::output_stream(),
3135           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
3136         return JNI_EINVAL;
3137       }
3138       // Check for module related properties.  They must be set using the modules
3139       // options. For example: use "--add-modules=java.sql", not
3140       // "-Djdk.module.addmods=java.sql"
3141       if (is_internal_module_property(option->optionString + 2)) {
3142         needs_module_property_warning = true;
3143         continue;
3144       }
3145 
3146       if (!add_property(tail)) {
3147         return JNI_ENOMEM;
3148       }
3149       // Out of the box management support
3150       if (match_option(option, "-Dcom.sun.management", &tail)) {
3151 #if INCLUDE_MANAGEMENT
3152         if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
3153           return JNI_EINVAL;
3154         }
3155         // management agent in module java.management
3156         if (!create_numbered_property("jdk.module.addmods", "java.management", addmods_count++)) {
3157           return JNI_ENOMEM;
3158         }
3159 #else
3160         jio_fprintf(defaultStream::output_stream(),
3161           "-Dcom.sun.management is not supported in this VM.\n");
3162         return JNI_ERR;
3163 #endif
3164       }
3165     // -Xint
3166     } else if (match_option(option, "-Xint")) {
3167           set_mode_flags(_int);
3168     // -Xmixed
3169     } else if (match_option(option, "-Xmixed")) {
3170           set_mode_flags(_mixed);
3171     // -Xcomp
3172     } else if (match_option(option, "-Xcomp")) {
3173       // for testing the compiler; turn off all flags that inhibit compilation
3174           set_mode_flags(_comp);
3175     // -Xshare:dump
3176     } else if (match_option(option, "-Xshare:dump")) {
3177       if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
3178         return JNI_EINVAL;
3179       }
3180       set_mode_flags(_int);     // Prevent compilation, which creates objects
3181     // -Xshare:on
3182     } else if (match_option(option, "-Xshare:on")) {
3183       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3184         return JNI_EINVAL;
3185       }
3186       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3187         return JNI_EINVAL;
3188       }
3189     // -Xshare:auto
3190     } else if (match_option(option, "-Xshare:auto")) {
3191       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3192         return JNI_EINVAL;
3193       }
3194       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3195         return JNI_EINVAL;
3196       }
3197     // -Xshare:off
3198     } else if (match_option(option, "-Xshare:off")) {
3199       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
3200         return JNI_EINVAL;
3201       }
3202       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3203         return JNI_EINVAL;
3204       }
3205     // -Xverify
3206     } else if (match_option(option, "-Xverify", &tail)) {
3207       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
3208         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
3209           return JNI_EINVAL;
3210         }
3211         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3212           return JNI_EINVAL;
3213         }
3214       } else if (strcmp(tail, ":remote") == 0) {
3215         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3216           return JNI_EINVAL;
3217         }
3218         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3219           return JNI_EINVAL;
3220         }
3221       } else if (strcmp(tail, ":none") == 0) {
3222         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3223           return JNI_EINVAL;
3224         }
3225         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
3226           return JNI_EINVAL;
3227         }
3228       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3229         return JNI_EINVAL;
3230       }
3231     // -Xdebug
3232     } else if (match_option(option, "-Xdebug")) {
3233       // note this flag has been used, then ignore
3234       set_xdebug_mode(true);
3235     // -Xnoagent
3236     } else if (match_option(option, "-Xnoagent")) {
3237       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3238     } else if (match_option(option, "-Xloggc:", &tail)) {
3239       // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
3240       log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
3241       _gc_log_filename = os::strdup_check_oom(tail);
3242     } else if (match_option(option, "-Xlog", &tail)) {
3243       bool ret = false;
3244       if (strcmp(tail, ":help") == 0) {
3245         LogConfiguration::print_command_line_help(defaultStream::output_stream());
3246         vm_exit(0);
3247       } else if (strcmp(tail, ":disable") == 0) {
3248         LogConfiguration::disable_logging();
3249         ret = true;
3250       } else if (*tail == '\0') {
3251         ret = LogConfiguration::parse_command_line_arguments();
3252         assert(ret, "-Xlog without arguments should never fail to parse");
3253       } else if (*tail == ':') {
3254         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
3255       }
3256       if (ret == false) {
3257         jio_fprintf(defaultStream::error_stream(),
3258                     "Invalid -Xlog option '-Xlog%s'\n",
3259                     tail);
3260         return JNI_EINVAL;
3261       }
3262     // JNI hooks
3263     } else if (match_option(option, "-Xcheck", &tail)) {
3264       if (!strcmp(tail, ":jni")) {
3265 #if !INCLUDE_JNI_CHECK
3266         warning("JNI CHECKING is not supported in this VM");
3267 #else
3268         CheckJNICalls = true;
3269 #endif // INCLUDE_JNI_CHECK
3270       } else if (is_bad_option(option, args->ignoreUnrecognized,
3271                                      "check")) {
3272         return JNI_EINVAL;
3273       }
3274     } else if (match_option(option, "vfprintf")) {
3275       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3276     } else if (match_option(option, "exit")) {
3277       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3278     } else if (match_option(option, "abort")) {
3279       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3280     // -XX:+AggressiveHeap
3281     } else if (match_option(option, "-XX:+AggressiveHeap")) {
3282       jint result = set_aggressive_heap_flags();
3283       if (result != JNI_OK) {
3284           return result;
3285       }
3286     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
3287     // and the last option wins.
3288     } else if (match_option(option, "-XX:+NeverTenure")) {
3289       if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
3290         return JNI_EINVAL;
3291       }
3292       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3293         return JNI_EINVAL;
3294       }
3295       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
3296         return JNI_EINVAL;
3297       }
3298     } else if (match_option(option, "-XX:+AlwaysTenure")) {
3299       if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3300         return JNI_EINVAL;
3301       }
3302       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3303         return JNI_EINVAL;
3304       }
3305       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
3306         return JNI_EINVAL;
3307       }
3308     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
3309       uintx max_tenuring_thresh = 0;
3310       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
3311         jio_fprintf(defaultStream::error_stream(),
3312                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
3313         return JNI_EINVAL;
3314       }
3315 
3316       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
3317         return JNI_EINVAL;
3318       }
3319 
3320       if (MaxTenuringThreshold == 0) {
3321         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3322           return JNI_EINVAL;
3323         }
3324         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3325           return JNI_EINVAL;
3326         }
3327       } else {
3328         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3329           return JNI_EINVAL;
3330         }
3331         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3332           return JNI_EINVAL;
3333         }
3334       }
3335     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3336       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
3337         return JNI_EINVAL;
3338       }
3339       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
3340         return JNI_EINVAL;
3341       }
3342     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3343       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
3344         return JNI_EINVAL;
3345       }
3346       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3347         return JNI_EINVAL;
3348       }
3349     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3350 #if defined(DTRACE_ENABLED)
3351       if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3352         return JNI_EINVAL;
3353       }
3354       if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3355         return JNI_EINVAL;
3356       }
3357       if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3358         return JNI_EINVAL;
3359       }
3360       if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3361         return JNI_EINVAL;
3362       }
3363 #else // defined(DTRACE_ENABLED)
3364       jio_fprintf(defaultStream::error_stream(),
3365                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3366       return JNI_EINVAL;
3367 #endif // defined(DTRACE_ENABLED)
3368 #ifdef ASSERT
3369     } else if (match_option(option, "-XX:+FullGCALot")) {
3370       if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3371         return JNI_EINVAL;
3372       }
3373       // disable scavenge before parallel mark-compact
3374       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3375         return JNI_EINVAL;
3376       }
3377 #endif
3378 #if !INCLUDE_MANAGEMENT
3379     } else if (match_option(option, "-XX:+ManagementServer")) {
3380         jio_fprintf(defaultStream::error_stream(),
3381           "ManagementServer is not supported in this VM.\n");
3382         return JNI_ERR;
3383 #endif // INCLUDE_MANAGEMENT
3384     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3385       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
3386       // already been handled
3387       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
3388           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
3389         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3390           return JNI_EINVAL;
3391         }
3392       }
3393     // Unknown option
3394     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3395       return JNI_ERR;
3396     }
3397   }
3398 
3399   // PrintSharedArchiveAndExit will turn on
3400   //   -Xshare:on
3401   //   -Xlog:class+path=info
3402   if (PrintSharedArchiveAndExit) {
3403     if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3404       return JNI_EINVAL;
3405     }
3406     if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3407       return JNI_EINVAL;
3408     }
3409     LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));
3410   }
3411 
3412   // Change the default value for flags  which have different default values
3413   // when working with older JDKs.
3414 #ifdef LINUX
3415  if (JDK_Version::current().compare_major(6) <= 0 &&
3416       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3417     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3418   }
3419 #endif // LINUX
3420   fix_appclasspath();
3421   return JNI_OK;
3422 }
3423 
3424 void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {
3425   // For java.base check for duplicate --patch-module options being specified on the command line.
3426   // This check is only required for java.base, all other duplicate module specifications
3427   // will be checked during module system initialization.  The module system initialization
3428   // will throw an ExceptionInInitializerError if this situation occurs.
3429   if (strcmp(module_name, "java.base") == 0) {
3430     if (*patch_mod_javabase) {
3431       vm_exit_during_initialization("Cannot specify java.base more than once to --patch-module");
3432     } else {
3433       *patch_mod_javabase = true;
3434     }
3435   }
3436 
3437   // Create GrowableArray lazily, only if --patch-module has been specified
3438   if (_patch_mod_prefix == NULL) {
3439     _patch_mod_prefix = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<ModulePatchPath*>(10, true);
3440   }
3441 
3442   _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
3443 }
3444 
3445 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3446 //
3447 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3448 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3449 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3450 // path is treated as the current directory.
3451 //
3452 // This causes problems with CDS, which requires that all directories specified in the classpath
3453 // must be empty. In most cases, applications do NOT want to load classes from the current
3454 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3455 // scripts compatible with CDS.
3456 void Arguments::fix_appclasspath() {
3457   if (IgnoreEmptyClassPaths) {
3458     const char separator = *os::path_separator();
3459     const char* src = _java_class_path->value();
3460 
3461     // skip over all the leading empty paths
3462     while (*src == separator) {
3463       src ++;
3464     }
3465 
3466     char* copy = os::strdup_check_oom(src, mtArguments);
3467 
3468     // trim all trailing empty paths
3469     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3470       *tail = '\0';
3471     }
3472 
3473     char from[3] = {separator, separator, '\0'};
3474     char to  [2] = {separator, '\0'};
3475     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3476       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3477       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3478     }
3479 
3480     _java_class_path->set_writeable_value(copy);
3481     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3482   }
3483 }
3484 
3485 static bool has_jar_files(const char* directory) {
3486   DIR* dir = os::opendir(directory);
3487   if (dir == NULL) return false;
3488 
3489   struct dirent *entry;
3490   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtArguments);
3491   bool hasJarFile = false;
3492   while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3493     const char* name = entry->d_name;
3494     const char* ext = name + strlen(name) - 4;
3495     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3496   }
3497   FREE_C_HEAP_ARRAY(char, dbuf);
3498   os::closedir(dir);
3499   return hasJarFile ;
3500 }
3501 
3502 static int check_non_empty_dirs(const char* path) {
3503   const char separator = *os::path_separator();
3504   const char* const end = path + strlen(path);
3505   int nonEmptyDirs = 0;
3506   while (path < end) {
3507     const char* tmp_end = strchr(path, separator);
3508     if (tmp_end == NULL) {
3509       if (has_jar_files(path)) {
3510         nonEmptyDirs++;
3511         jio_fprintf(defaultStream::output_stream(),
3512           "Non-empty directory: %s\n", path);
3513       }
3514       path = end;
3515     } else {
3516       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtArguments);
3517       memcpy(dirpath, path, tmp_end - path);
3518       dirpath[tmp_end - path] = '\0';
3519       if (has_jar_files(dirpath)) {
3520         nonEmptyDirs++;
3521         jio_fprintf(defaultStream::output_stream(),
3522           "Non-empty directory: %s\n", dirpath);
3523       }
3524       FREE_C_HEAP_ARRAY(char, dirpath);
3525       path = tmp_end + 1;
3526     }
3527   }
3528   return nonEmptyDirs;
3529 }
3530 
3531 jint Arguments::finalize_vm_init_args() {
3532   // check if the default lib/endorsed directory exists; if so, error
3533   char path[JVM_MAXPATHLEN];
3534   const char* fileSep = os::file_separator();
3535   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3536 
3537   if (CheckEndorsedAndExtDirs) {
3538     int nonEmptyDirs = 0;
3539     // check endorsed directory
3540     nonEmptyDirs += check_non_empty_dirs(path);
3541     // check the extension directories
3542     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3543     if (nonEmptyDirs > 0) {
3544       return JNI_ERR;
3545     }
3546   }
3547 
3548   DIR* dir = os::opendir(path);
3549   if (dir != NULL) {
3550     jio_fprintf(defaultStream::output_stream(),
3551       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3552       "in modular form will be supported via the concept of upgradeable modules.\n");
3553     os::closedir(dir);
3554     return JNI_ERR;
3555   }
3556 
3557   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3558   dir = os::opendir(path);
3559   if (dir != NULL) {
3560     jio_fprintf(defaultStream::output_stream(),
3561       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3562       "Use -classpath instead.\n.");
3563     os::closedir(dir);
3564     return JNI_ERR;
3565   }
3566 
3567   // This must be done after all arguments have been processed.
3568   // java_compiler() true means set to "NONE" or empty.
3569   if (java_compiler() && !xdebug_mode()) {
3570     // For backwards compatibility, we switch to interpreted mode if
3571     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3572     // not specified.
3573     set_mode_flags(_int);
3574   }
3575 
3576   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3577   // but like -Xint, leave compilation thresholds unaffected.
3578   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3579   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3580     set_mode_flags(_int);
3581   }
3582 
3583   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3584   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3585     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3586   }
3587 
3588 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3589   // Don't degrade server performance for footprint
3590   if (FLAG_IS_DEFAULT(UseLargePages) &&
3591       MaxHeapSize < LargePageHeapSizeThreshold) {
3592     // No need for large granularity pages w/small heaps.
3593     // Note that large pages are enabled/disabled for both the
3594     // Java heap and the code cache.
3595     FLAG_SET_DEFAULT(UseLargePages, false);
3596   }
3597 
3598 #elif defined(COMPILER2)
3599   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3600     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3601   }
3602 #endif
3603 
3604 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3605   UNSUPPORTED_OPTION(ProfileInterpreter);
3606   NOT_PRODUCT(UNSUPPORTED_OPTION(TraceProfileInterpreter));
3607 #endif
3608 
3609 #ifndef TIERED
3610   // Tiered compilation is undefined.
3611   UNSUPPORTED_OPTION(TieredCompilation);
3612 #endif
3613 
3614 #if INCLUDE_JVMCI
3615   if (EnableJVMCI &&
3616       !create_numbered_property("jdk.module.addmods", "jdk.vm.ci", addmods_count++)) {
3617     return JNI_ENOMEM;
3618   }
3619 #endif
3620 
3621   // If we are running in a headless jre, force java.awt.headless property
3622   // to be true unless the property has already been set.
3623   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3624   if (os::is_headless_jre()) {
3625     const char* headless = Arguments::get_property("java.awt.headless");
3626     if (headless == NULL) {
3627       const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3628       if (headless_env == NULL) {
3629         if (!add_property("java.awt.headless=true")) {
3630           return JNI_ENOMEM;
3631         }
3632       } else {
3633         char buffer[256];
3634         jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3635         if (!add_property(buffer)) {
3636           return JNI_ENOMEM;
3637         }
3638       }
3639     }
3640   }
3641 
3642   if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3643     // CMS can only be used with ParNew
3644     FLAG_SET_ERGO(bool, UseParNewGC, true);
3645   }
3646 
3647   if (!check_vm_args_consistency()) {
3648     return JNI_ERR;
3649   }
3650 
3651   return JNI_OK;
3652 }
3653 
3654 // Helper class for controlling the lifetime of JavaVMInitArgs
3655 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3656 // deleted on the destruction of the ScopedVMInitArgs object.
3657 class ScopedVMInitArgs : public StackObj {
3658  private:
3659   JavaVMInitArgs _args;
3660   char*          _container_name;
3661   bool           _is_set;
3662   char*          _vm_options_file_arg;
3663 
3664  public:
3665   ScopedVMInitArgs(const char *container_name) {
3666     _args.version = JNI_VERSION_1_2;
3667     _args.nOptions = 0;
3668     _args.options = NULL;
3669     _args.ignoreUnrecognized = false;
3670     _container_name = (char *)container_name;
3671     _is_set = false;
3672     _vm_options_file_arg = NULL;
3673   }
3674 
3675   // Populates the JavaVMInitArgs object represented by this
3676   // ScopedVMInitArgs object with the arguments in options.  The
3677   // allocated memory is deleted by the destructor.  If this method
3678   // returns anything other than JNI_OK, then this object is in a
3679   // partially constructed state, and should be abandoned.
3680   jint set_args(GrowableArray<JavaVMOption>* options) {
3681     _is_set = true;
3682     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3683         JavaVMOption, options->length(), mtArguments);
3684     if (options_arr == NULL) {
3685       return JNI_ENOMEM;
3686     }
3687     _args.options = options_arr;
3688 
3689     for (int i = 0; i < options->length(); i++) {
3690       options_arr[i] = options->at(i);
3691       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3692       if (options_arr[i].optionString == NULL) {
3693         // Rely on the destructor to do cleanup.
3694         _args.nOptions = i;
3695         return JNI_ENOMEM;
3696       }
3697     }
3698 
3699     _args.nOptions = options->length();
3700     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3701     return JNI_OK;
3702   }
3703 
3704   JavaVMInitArgs* get()             { return &_args; }
3705   char* container_name()            { return _container_name; }
3706   bool  is_set()                    { return _is_set; }
3707   bool  found_vm_options_file_arg() { return _vm_options_file_arg != NULL; }
3708   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3709 
3710   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3711     if (_vm_options_file_arg != NULL) {
3712       os::free(_vm_options_file_arg);
3713     }
3714     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3715   }
3716 
3717   ~ScopedVMInitArgs() {
3718     if (_vm_options_file_arg != NULL) {
3719       os::free(_vm_options_file_arg);
3720     }
3721     if (_args.options == NULL) return;
3722     for (int i = 0; i < _args.nOptions; i++) {
3723       os::free(_args.options[i].optionString);
3724     }
3725     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3726   }
3727 
3728   // Insert options into this option list, to replace option at
3729   // vm_options_file_pos (-XX:VMOptionsFile)
3730   jint insert(const JavaVMInitArgs* args,
3731               const JavaVMInitArgs* args_to_insert,
3732               const int vm_options_file_pos) {
3733     assert(_args.options == NULL, "shouldn't be set yet");
3734     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3735     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3736 
3737     int length = args->nOptions + args_to_insert->nOptions - 1;
3738     GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments)
3739               GrowableArray<JavaVMOption>(length, true);    // Construct new option array
3740     for (int i = 0; i < args->nOptions; i++) {
3741       if (i == vm_options_file_pos) {
3742         // insert the new options starting at the same place as the
3743         // -XX:VMOptionsFile option
3744         for (int j = 0; j < args_to_insert->nOptions; j++) {
3745           options->push(args_to_insert->options[j]);
3746         }
3747       } else {
3748         options->push(args->options[i]);
3749       }
3750     }
3751     // make into options array
3752     jint result = set_args(options);
3753     delete options;
3754     return result;
3755   }
3756 };
3757 
3758 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3759   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3760 }
3761 
3762 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3763   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3764 }
3765 
3766 jint Arguments::parse_options_environment_variable(const char* name,
3767                                                    ScopedVMInitArgs* vm_args) {
3768   char *buffer = ::getenv(name);
3769 
3770   // Don't check this environment variable if user has special privileges
3771   // (e.g. unix su command).
3772   if (buffer == NULL || os::have_special_privileges()) {
3773     return JNI_OK;
3774   }
3775 
3776   if ((buffer = os::strdup(buffer)) == NULL) {
3777     return JNI_ENOMEM;
3778   }
3779 
3780   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3781 
3782   os::free(buffer);
3783   return retcode;
3784 }
3785 
3786 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3787   // read file into buffer
3788   int fd = ::open(file_name, O_RDONLY);
3789   if (fd < 0) {
3790     jio_fprintf(defaultStream::error_stream(),
3791                 "Could not open options file '%s'\n",
3792                 file_name);
3793     return JNI_ERR;
3794   }
3795 
3796   struct stat stbuf;
3797   int retcode = os::stat(file_name, &stbuf);
3798   if (retcode != 0) {
3799     jio_fprintf(defaultStream::error_stream(),
3800                 "Could not stat options file '%s'\n",
3801                 file_name);
3802     os::close(fd);
3803     return JNI_ERR;
3804   }
3805 
3806   if (stbuf.st_size == 0) {
3807     // tell caller there is no option data and that is ok
3808     os::close(fd);
3809     return JNI_OK;
3810   }
3811 
3812   // '+ 1' for NULL termination even with max bytes
3813   size_t bytes_alloc = stbuf.st_size + 1;
3814 
3815   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3816   if (NULL == buf) {
3817     jio_fprintf(defaultStream::error_stream(),
3818                 "Could not allocate read buffer for options file parse\n");
3819     os::close(fd);
3820     return JNI_ENOMEM;
3821   }
3822 
3823   memset(buf, 0, bytes_alloc);
3824 
3825   // Fill buffer
3826   // Use ::read() instead of os::read because os::read()
3827   // might do a thread state transition
3828   // and it is too early for that here
3829 
3830   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3831   os::close(fd);
3832   if (bytes_read < 0) {
3833     FREE_C_HEAP_ARRAY(char, buf);
3834     jio_fprintf(defaultStream::error_stream(),
3835                 "Could not read options file '%s'\n", file_name);
3836     return JNI_ERR;
3837   }
3838 
3839   if (bytes_read == 0) {
3840     // tell caller there is no option data and that is ok
3841     FREE_C_HEAP_ARRAY(char, buf);
3842     return JNI_OK;
3843   }
3844 
3845   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3846 
3847   FREE_C_HEAP_ARRAY(char, buf);
3848   return retcode;
3849 }
3850 
3851 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3852   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3853 
3854   // some pointers to help with parsing
3855   char *buffer_end = buffer + buf_len;
3856   char *opt_hd = buffer;
3857   char *wrt = buffer;
3858   char *rd = buffer;
3859 
3860   // parse all options
3861   while (rd < buffer_end) {
3862     // skip leading white space from the input string
3863     while (rd < buffer_end && isspace(*rd)) {
3864       rd++;
3865     }
3866 
3867     if (rd >= buffer_end) {
3868       break;
3869     }
3870 
3871     // Remember this is where we found the head of the token.
3872     opt_hd = wrt;
3873 
3874     // Tokens are strings of non white space characters separated
3875     // by one or more white spaces.
3876     while (rd < buffer_end && !isspace(*rd)) {
3877       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3878         int quote = *rd;                    // matching quote to look for
3879         rd++;                               // don't copy open quote
3880         while (rd < buffer_end && *rd != quote) {
3881                                             // include everything (even spaces)
3882                                             // up until the close quote
3883           *wrt++ = *rd++;                   // copy to option string
3884         }
3885 
3886         if (rd < buffer_end) {
3887           rd++;                             // don't copy close quote
3888         } else {
3889                                             // did not see closing quote
3890           jio_fprintf(defaultStream::error_stream(),
3891                       "Unmatched quote in %s\n", name);
3892           delete options;
3893           return JNI_ERR;
3894         }
3895       } else {
3896         *wrt++ = *rd++;                     // copy to option string
3897       }
3898     }
3899 
3900     // steal a white space character and set it to NULL
3901     *wrt++ = '\0';
3902     // We now have a complete token
3903 
3904     JavaVMOption option;
3905     option.optionString = opt_hd;
3906     option.extraInfo = NULL;
3907 
3908     options->append(option);                // Fill in option
3909 
3910     rd++;  // Advance to next character
3911   }
3912 
3913   // Fill out JavaVMInitArgs structure.
3914   jint status = vm_args->set_args(options);
3915 
3916   delete options;
3917   return status;
3918 }
3919 
3920 void Arguments::set_shared_spaces_flags() {
3921   if (DumpSharedSpaces) {
3922     if (FailOverToOldVerifier) {
3923       // Don't fall back to the old verifier on verification failure. If a
3924       // class fails verification with the split verifier, it might fail the
3925       // CDS runtime verifier constraint check. In that case, we don't want
3926       // to share the class. We only archive classes that pass the split verifier.
3927       FLAG_SET_DEFAULT(FailOverToOldVerifier, false);
3928     }
3929 
3930     if (RequireSharedSpaces) {
3931       warning("Cannot dump shared archive while using shared archive");
3932     }
3933     UseSharedSpaces = false;
3934 #ifdef _LP64
3935     if (!UseCompressedOops || !UseCompressedClassPointers) {
3936       vm_exit_during_initialization(
3937         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3938     }
3939   } else {
3940     if (!UseCompressedOops || !UseCompressedClassPointers) {
3941       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3942     }
3943 #endif
3944   }
3945 }
3946 
3947 // Sharing support
3948 // Construct the path to the archive
3949 static char* get_shared_archive_path() {
3950   char *shared_archive_path;
3951   if (SharedArchiveFile == NULL) {
3952     char jvm_path[JVM_MAXPATHLEN];
3953     os::jvm_path(jvm_path, sizeof(jvm_path));
3954     char *end = strrchr(jvm_path, *os::file_separator());
3955     if (end != NULL) *end = '\0';
3956     size_t jvm_path_len = strlen(jvm_path);
3957     size_t file_sep_len = strlen(os::file_separator());
3958     const size_t len = jvm_path_len + file_sep_len + 20;
3959     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);
3960     if (shared_archive_path != NULL) {
3961       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3962         jvm_path, os::file_separator());
3963     }
3964   } else {
3965     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);
3966   }
3967   return shared_archive_path;
3968 }
3969 
3970 #ifndef PRODUCT
3971 // Determine whether LogVMOutput should be implicitly turned on.
3972 static bool use_vm_log() {
3973   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3974       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3975       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3976       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3977       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3978     return true;
3979   }
3980 
3981 #ifdef COMPILER1
3982   if (PrintC1Statistics) {
3983     return true;
3984   }
3985 #endif // COMPILER1
3986 
3987 #ifdef COMPILER2
3988   if (PrintOptoAssembly || PrintOptoStatistics) {
3989     return true;
3990   }
3991 #endif // COMPILER2
3992 
3993   return false;
3994 }
3995 
3996 #endif // PRODUCT
3997 
3998 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3999   for (int index = 0; index < args->nOptions; index++) {
4000     const JavaVMOption* option = args->options + index;
4001     const char* tail;
4002     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
4003       return true;
4004     }
4005   }
4006   return false;
4007 }
4008 
4009 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
4010                                        const char* vm_options_file,
4011                                        const int vm_options_file_pos,
4012                                        ScopedVMInitArgs* vm_options_file_args,
4013                                        ScopedVMInitArgs* args_out) {
4014   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
4015   if (code != JNI_OK) {
4016     return code;
4017   }
4018 
4019   if (vm_options_file_args->get()->nOptions < 1) {
4020     return JNI_OK;
4021   }
4022 
4023   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
4024     jio_fprintf(defaultStream::error_stream(),
4025                 "A VM options file may not refer to a VM options file. "
4026                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
4027                 "options file '%s' in options container '%s' is an error.\n",
4028                 vm_options_file_args->vm_options_file_arg(),
4029                 vm_options_file_args->container_name());
4030     return JNI_EINVAL;
4031   }
4032 
4033   return args_out->insert(args, vm_options_file_args->get(),
4034                           vm_options_file_pos);
4035 }
4036 
4037 // Expand -XX:VMOptionsFile found in args_in as needed.
4038 // mod_args and args_out parameters may return values as needed.
4039 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
4040                                             ScopedVMInitArgs* mod_args,
4041                                             JavaVMInitArgs** args_out) {
4042   jint code = match_special_option_and_act(args_in, mod_args);
4043   if (code != JNI_OK) {
4044     return code;
4045   }
4046 
4047   if (mod_args->is_set()) {
4048     // args_in contains -XX:VMOptionsFile and mod_args contains the
4049     // original options from args_in along with the options expanded
4050     // from the VMOptionsFile. Return a short-hand to the caller.
4051     *args_out = mod_args->get();
4052   } else {
4053     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
4054   }
4055   return JNI_OK;
4056 }
4057 
4058 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
4059                                              ScopedVMInitArgs* args_out) {
4060   // Remaining part of option string
4061   const char* tail;
4062   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
4063 
4064   for (int index = 0; index < args->nOptions; index++) {
4065     const JavaVMOption* option = args->options + index;
4066     if (ArgumentsExt::process_options(option)) {
4067       continue;
4068     }
4069     if (match_option(option, "-XX:Flags=", &tail)) {
4070       Arguments::set_jvm_flags_file(tail);
4071       continue;
4072     }
4073     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
4074       if (vm_options_file_args.found_vm_options_file_arg()) {
4075         jio_fprintf(defaultStream::error_stream(),
4076                     "The option '%s' is already specified in the options "
4077                     "container '%s' so the specification of '%s' in the "
4078                     "same options container is an error.\n",
4079                     vm_options_file_args.vm_options_file_arg(),
4080                     vm_options_file_args.container_name(),
4081                     option->optionString);
4082         return JNI_EINVAL;
4083       }
4084       vm_options_file_args.set_vm_options_file_arg(option->optionString);
4085       // If there's a VMOptionsFile, parse that
4086       jint code = insert_vm_options_file(args, tail, index,
4087                                          &vm_options_file_args, args_out);
4088       if (code != JNI_OK) {
4089         return code;
4090       }
4091       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
4092       if (args_out->is_set()) {
4093         // The VMOptions file inserted some options so switch 'args'
4094         // to the new set of options, and continue processing which
4095         // preserves "last option wins" semantics.
4096         args = args_out->get();
4097         // The first option from the VMOptionsFile replaces the
4098         // current option.  So we back track to process the
4099         // replacement option.
4100         index--;
4101       }
4102       continue;
4103     }
4104     if (match_option(option, "-XX:+PrintVMOptions")) {
4105       PrintVMOptions = true;
4106       continue;
4107     }
4108     if (match_option(option, "-XX:-PrintVMOptions")) {
4109       PrintVMOptions = false;
4110       continue;
4111     }
4112     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
4113       IgnoreUnrecognizedVMOptions = true;
4114       continue;
4115     }
4116     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
4117       IgnoreUnrecognizedVMOptions = false;
4118       continue;
4119     }
4120     if (match_option(option, "-XX:+PrintFlagsInitial")) {
4121       CommandLineFlags::printFlags(tty, false);
4122       vm_exit(0);
4123     }
4124     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
4125 #if INCLUDE_NMT
4126       // The launcher did not setup nmt environment variable properly.
4127       if (!MemTracker::check_launcher_nmt_support(tail)) {
4128         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
4129       }
4130 
4131       // Verify if nmt option is valid.
4132       if (MemTracker::verify_nmt_option()) {
4133         // Late initialization, still in single-threaded mode.
4134         if (MemTracker::tracking_level() >= NMT_summary) {
4135           MemTracker::init();
4136         }
4137       } else {
4138         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
4139       }
4140       continue;
4141 #else
4142       jio_fprintf(defaultStream::error_stream(),
4143         "Native Memory Tracking is not supported in this VM\n");
4144       return JNI_ERR;
4145 #endif
4146     }
4147 
4148 #ifndef PRODUCT
4149     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
4150       CommandLineFlags::printFlags(tty, true);
4151       vm_exit(0);
4152     }
4153 #endif
4154   }
4155   return JNI_OK;
4156 }
4157 
4158 static void print_options(const JavaVMInitArgs *args) {
4159   const char* tail;
4160   for (int index = 0; index < args->nOptions; index++) {
4161     const JavaVMOption *option = args->options + index;
4162     if (match_option(option, "-XX:", &tail)) {
4163       logOption(tail);
4164     }
4165   }
4166 }
4167 
4168 bool Arguments::handle_deprecated_print_gc_flags() {
4169   if (PrintGC) {
4170     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
4171   }
4172   if (PrintGCDetails) {
4173     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
4174   }
4175 
4176   if (_gc_log_filename != NULL) {
4177     // -Xloggc was used to specify a filename
4178     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
4179 
4180     LogTarget(Error, logging) target;
4181     LogStreamCHeap errstream(target);
4182     return LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, &errstream);
4183   } else if (PrintGC || PrintGCDetails) {
4184     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
4185   }
4186   return true;
4187 }
4188 
4189 void Arguments::handle_extra_cms_flags(const char* msg) {
4190   SpecialFlag flag;
4191   const char *flag_name = "UseConcMarkSweepGC";
4192   if (lookup_special_flag(flag_name, flag)) {
4193     handle_aliases_and_deprecation(flag_name, /* print warning */ true);
4194     warning("%s", msg);
4195   }
4196 }
4197 
4198 // Parse entry point called from JNI_CreateJavaVM
4199 
4200 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
4201   assert(verify_special_jvm_flags(), "deprecated and obsolete flag table inconsistent");
4202 
4203   // Initialize ranges, constraints and writeables
4204   CommandLineFlagRangeList::init();
4205   CommandLineFlagConstraintList::init();
4206   CommandLineFlagWriteableList::init();
4207 
4208   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
4209   const char* hotspotrc = ".hotspotrc";
4210   bool settings_file_specified = false;
4211   bool needs_hotspotrc_warning = false;
4212   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4213   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
4214 
4215   // Pointers to current working set of containers
4216   JavaVMInitArgs* cur_cmd_args;
4217   JavaVMInitArgs* cur_java_options_args;
4218   JavaVMInitArgs* cur_java_tool_options_args;
4219 
4220   // Containers for modified/expanded options
4221   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
4222   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4223   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
4224 
4225 
4226   jint code =
4227       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
4228   if (code != JNI_OK) {
4229     return code;
4230   }
4231 
4232   code = parse_java_options_environment_variable(&initial_java_options_args);
4233   if (code != JNI_OK) {
4234     return code;
4235   }
4236 
4237   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
4238                                      &mod_java_tool_options_args,
4239                                      &cur_java_tool_options_args);
4240   if (code != JNI_OK) {
4241     return code;
4242   }
4243 
4244   code = expand_vm_options_as_needed(initial_cmd_args,
4245                                      &mod_cmd_args,
4246                                      &cur_cmd_args);
4247   if (code != JNI_OK) {
4248     return code;
4249   }
4250 
4251   code = expand_vm_options_as_needed(initial_java_options_args.get(),
4252                                      &mod_java_options_args,
4253                                      &cur_java_options_args);
4254   if (code != JNI_OK) {
4255     return code;
4256   }
4257 
4258   const char* flags_file = Arguments::get_jvm_flags_file();
4259   settings_file_specified = (flags_file != NULL);
4260 
4261   if (IgnoreUnrecognizedVMOptions) {
4262     cur_cmd_args->ignoreUnrecognized = true;
4263     cur_java_tool_options_args->ignoreUnrecognized = true;
4264     cur_java_options_args->ignoreUnrecognized = true;
4265   }
4266 
4267   // Parse specified settings file
4268   if (settings_file_specified) {
4269     if (!process_settings_file(flags_file, true,
4270                                cur_cmd_args->ignoreUnrecognized)) {
4271       return JNI_EINVAL;
4272     }
4273   } else {
4274 #ifdef ASSERT
4275     // Parse default .hotspotrc settings file
4276     if (!process_settings_file(".hotspotrc", false,
4277                                cur_cmd_args->ignoreUnrecognized)) {
4278       return JNI_EINVAL;
4279     }
4280 #else
4281     struct stat buf;
4282     if (os::stat(hotspotrc, &buf) == 0) {
4283       needs_hotspotrc_warning = true;
4284     }
4285 #endif
4286   }
4287 
4288   if (PrintVMOptions) {
4289     print_options(cur_java_tool_options_args);
4290     print_options(cur_cmd_args);
4291     print_options(cur_java_options_args);
4292   }
4293 
4294   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
4295   jint result = parse_vm_init_args(cur_java_tool_options_args,
4296                                    cur_java_options_args,
4297                                    cur_cmd_args);
4298 
4299   if (result != JNI_OK) {
4300     return result;
4301   }
4302 
4303   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
4304   SharedArchivePath = get_shared_archive_path();
4305   if (SharedArchivePath == NULL) {
4306     return JNI_ENOMEM;
4307   }
4308 
4309   // Set up VerifySharedSpaces
4310   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
4311     VerifySharedSpaces = true;
4312   }
4313 
4314   // Delay warning until here so that we've had a chance to process
4315   // the -XX:-PrintWarnings flag
4316   if (needs_hotspotrc_warning) {
4317     warning("%s file is present but has been ignored.  "
4318             "Run with -XX:Flags=%s to load the file.",
4319             hotspotrc, hotspotrc);
4320   }
4321 
4322   if (needs_module_property_warning) {
4323     warning("Ignoring system property options whose names match the '-Djdk.module.*'."
4324             " names that are reserved for internal use.");
4325   }
4326 
4327 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
4328   UNSUPPORTED_OPTION(UseLargePages);
4329 #endif
4330 
4331   ArgumentsExt::report_unsupported_options();
4332 
4333 #ifndef PRODUCT
4334   if (TraceBytecodesAt != 0) {
4335     TraceBytecodes = true;
4336   }
4337   if (CountCompiledCalls) {
4338     if (UseCounterDecay) {
4339       warning("UseCounterDecay disabled because CountCalls is set");
4340       UseCounterDecay = false;
4341     }
4342   }
4343 #endif // PRODUCT
4344 
4345   if (ScavengeRootsInCode == 0) {
4346     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4347       warning("Forcing ScavengeRootsInCode non-zero");
4348     }
4349     ScavengeRootsInCode = 1;
4350   }
4351 
4352   if (!handle_deprecated_print_gc_flags()) {
4353     return JNI_EINVAL;
4354   }
4355 
4356   // Set object alignment values.
4357   set_object_alignment();
4358 
4359 #if !INCLUDE_CDS
4360   if (DumpSharedSpaces || RequireSharedSpaces) {
4361     jio_fprintf(defaultStream::error_stream(),
4362       "Shared spaces are not supported in this VM\n");
4363     return JNI_ERR;
4364   }
4365   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
4366     warning("Shared spaces are not supported in this VM");
4367     FLAG_SET_DEFAULT(UseSharedSpaces, false);
4368     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
4369   }
4370   no_shared_spaces("CDS Disabled");
4371 #endif // INCLUDE_CDS
4372 
4373   return JNI_OK;
4374 }
4375 
4376 jint Arguments::apply_ergo() {
4377 
4378   // Set flags based on ergonomics.
4379   set_ergonomics_flags();
4380 
4381   set_shared_spaces_flags();
4382 
4383   // Check the GC selections again.
4384   if (!check_gc_consistency()) {
4385     return JNI_EINVAL;
4386   }
4387 
4388   if (TieredCompilation) {
4389     set_tiered_flags();
4390   } else {
4391     int max_compilation_policy_choice = 1;
4392 #ifdef COMPILER2
4393     max_compilation_policy_choice = 2;
4394 #endif
4395     // Check if the policy is valid.
4396     if (CompilationPolicyChoice >= max_compilation_policy_choice) {
4397       vm_exit_during_initialization(
4398         "Incompatible compilation policy selected", NULL);
4399     }
4400     // Scale CompileThreshold
4401     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
4402     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
4403       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
4404     }
4405   }
4406 
4407 #ifdef COMPILER2
4408 #ifndef PRODUCT
4409   if (PrintIdealGraphLevel > 0) {
4410     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
4411   }
4412 #endif
4413 #endif
4414 
4415   // Set heap size based on available physical memory
4416   set_heap_size();
4417 
4418   ArgumentsExt::set_gc_specific_flags();
4419 
4420   // Initialize Metaspace flags and alignments
4421   Metaspace::ergo_initialize();
4422 
4423   // Set bytecode rewriting flags
4424   set_bytecode_flags();
4425 
4426   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
4427   jint code = set_aggressive_opts_flags();
4428   if (code != JNI_OK) {
4429     return code;
4430   }
4431 
4432   // Turn off biased locking for locking debug mode flags,
4433   // which are subtly different from each other but neither works with
4434   // biased locking
4435   if (UseHeavyMonitors
4436 #ifdef COMPILER1
4437       || !UseFastLocking
4438 #endif // COMPILER1
4439 #if INCLUDE_JVMCI
4440       || !JVMCIUseFastLocking
4441 #endif
4442     ) {
4443     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4444       // flag set to true on command line; warn the user that they
4445       // can't enable biased locking here
4446       warning("Biased Locking is not supported with locking debug flags"
4447               "; ignoring UseBiasedLocking flag." );
4448     }
4449     UseBiasedLocking = false;
4450   }
4451 
4452 #ifdef CC_INTERP
4453   // Clear flags not supported on zero.
4454   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4455   FLAG_SET_DEFAULT(UseBiasedLocking, false);
4456   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4457   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4458 #endif // CC_INTERP
4459 
4460 #ifdef COMPILER2
4461   if (!EliminateLocks) {
4462     EliminateNestedLocks = false;
4463   }
4464   if (!Inline) {
4465     IncrementalInline = false;
4466   }
4467 #ifndef PRODUCT
4468   if (!IncrementalInline) {
4469     AlwaysIncrementalInline = false;
4470   }
4471 #endif
4472   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
4473     // nothing to use the profiling, turn if off
4474     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
4475   }
4476 #endif
4477 
4478   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4479     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4480     DebugNonSafepoints = true;
4481   }
4482 
4483   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4484     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4485   }
4486 
4487   if (UseOnStackReplacement && !UseLoopCounter) {
4488     warning("On-stack-replacement requires loop counters; enabling loop counters");
4489     FLAG_SET_DEFAULT(UseLoopCounter, true);
4490   }
4491 
4492 #ifndef PRODUCT
4493   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4494     if (use_vm_log()) {
4495       LogVMOutput = true;
4496     }
4497   }
4498 #endif // PRODUCT
4499 
4500   if (PrintCommandLineFlags) {
4501     CommandLineFlags::printSetFlags(tty);
4502   }
4503 
4504   // Apply CPU specific policy for the BiasedLocking
4505   if (UseBiasedLocking) {
4506     if (!VM_Version::use_biased_locking() &&
4507         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4508       UseBiasedLocking = false;
4509     }
4510   }
4511 #ifdef COMPILER2
4512   if (!UseBiasedLocking || EmitSync != 0) {
4513     UseOptoBiasInlining = false;
4514   }
4515 #endif
4516 
4517   return JNI_OK;
4518 }
4519 
4520 jint Arguments::adjust_after_os() {
4521   if (UseNUMA) {
4522     if (UseParallelGC || UseParallelOldGC) {
4523       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4524          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4525       }
4526     }
4527     // UseNUMAInterleaving is set to ON for all collectors and
4528     // platforms when UseNUMA is set to ON. NUMA-aware collectors
4529     // such as the parallel collector for Linux and Solaris will
4530     // interleave old gen and survivor spaces on top of NUMA
4531     // allocation policy for the eden space.
4532     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4533     // all platforms and ParallelGC on Windows will interleave all
4534     // of the heap spaces across NUMA nodes.
4535     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4536       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4537     }
4538   }
4539   return JNI_OK;
4540 }
4541 
4542 int Arguments::PropertyList_count(SystemProperty* pl) {
4543   int count = 0;
4544   while(pl != NULL) {
4545     count++;
4546     pl = pl->next();
4547   }
4548   return count;
4549 }
4550 
4551 // Return the number of readable properties.
4552 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
4553   int count = 0;
4554   while(pl != NULL) {
4555     if (pl->is_readable()) {
4556       count++;
4557     }
4558     pl = pl->next();
4559   }
4560   return count;
4561 }
4562 
4563 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4564   assert(key != NULL, "just checking");
4565   SystemProperty* prop;
4566   for (prop = pl; prop != NULL; prop = prop->next()) {
4567     if (strcmp(key, prop->key()) == 0) return prop->value();
4568   }
4569   return NULL;
4570 }
4571 
4572 // Return the value of the requested property provided that it is a readable property.
4573 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4574   assert(key != NULL, "just checking");
4575   SystemProperty* prop;
4576   // Return the property value if the keys match and the property is not internal or
4577   // it's the special internal property "jdk.boot.class.path.append".
4578   for (prop = pl; prop != NULL; prop = prop->next()) {
4579     if (strcmp(key, prop->key()) == 0) {
4580       if (!prop->internal()) {
4581         return prop->value();
4582       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4583         return prop->value();
4584       } else {
4585         // Property is internal and not jdk.boot.class.path.append so return NULL.
4586         return NULL;
4587       }
4588     }
4589   }
4590   return NULL;
4591 }
4592 
4593 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4594   int count = 0;
4595   const char* ret_val = NULL;
4596 
4597   while(pl != NULL) {
4598     if(count >= index) {
4599       ret_val = pl->key();
4600       break;
4601     }
4602     count++;
4603     pl = pl->next();
4604   }
4605 
4606   return ret_val;
4607 }
4608 
4609 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4610   int count = 0;
4611   char* ret_val = NULL;
4612 
4613   while(pl != NULL) {
4614     if(count >= index) {
4615       ret_val = pl->value();
4616       break;
4617     }
4618     count++;
4619     pl = pl->next();
4620   }
4621 
4622   return ret_val;
4623 }
4624 
4625 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4626   SystemProperty* p = *plist;
4627   if (p == NULL) {
4628     *plist = new_p;
4629   } else {
4630     while (p->next() != NULL) {
4631       p = p->next();
4632     }
4633     p->set_next(new_p);
4634   }
4635 }
4636 
4637 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4638                                  bool writeable, bool internal) {
4639   if (plist == NULL)
4640     return;
4641 
4642   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4643   PropertyList_add(plist, new_p);
4644 }
4645 
4646 void Arguments::PropertyList_add(SystemProperty *element) {
4647   PropertyList_add(&_system_properties, element);
4648 }
4649 
4650 // This add maintains unique property key in the list.
4651 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4652                                         PropertyAppendable append, PropertyWriteable writeable,
4653                                         PropertyInternal internal) {
4654   if (plist == NULL)
4655     return;
4656 
4657   // If property key exist then update with new value.
4658   SystemProperty* prop;
4659   for (prop = *plist; prop != NULL; prop = prop->next()) {
4660     if (strcmp(k, prop->key()) == 0) {
4661       if (append == AppendProperty) {
4662         prop->append_value(v);
4663       } else {
4664         prop->set_value(v);
4665       }
4666       return;
4667     }
4668   }
4669 
4670   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4671 }
4672 
4673 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4674 // Returns true if all of the source pointed by src has been copied over to
4675 // the destination buffer pointed by buf. Otherwise, returns false.
4676 // Notes:
4677 // 1. If the length (buflen) of the destination buffer excluding the
4678 // NULL terminator character is not long enough for holding the expanded
4679 // pid characters, it also returns false instead of returning the partially
4680 // expanded one.
4681 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4682 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4683                                 char* buf, size_t buflen) {
4684   const char* p = src;
4685   char* b = buf;
4686   const char* src_end = &src[srclen];
4687   char* buf_end = &buf[buflen - 1];
4688 
4689   while (p < src_end && b < buf_end) {
4690     if (*p == '%') {
4691       switch (*(++p)) {
4692       case '%':         // "%%" ==> "%"
4693         *b++ = *p++;
4694         break;
4695       case 'p':  {       //  "%p" ==> current process id
4696         // buf_end points to the character before the last character so
4697         // that we could write '\0' to the end of the buffer.
4698         size_t buf_sz = buf_end - b + 1;
4699         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4700 
4701         // if jio_snprintf fails or the buffer is not long enough to hold
4702         // the expanded pid, returns false.
4703         if (ret < 0 || ret >= (int)buf_sz) {
4704           return false;
4705         } else {
4706           b += ret;
4707           assert(*b == '\0', "fail in copy_expand_pid");
4708           if (p == src_end && b == buf_end + 1) {
4709             // reach the end of the buffer.
4710             return true;
4711           }
4712         }
4713         p++;
4714         break;
4715       }
4716       default :
4717         *b++ = '%';
4718       }
4719     } else {
4720       *b++ = *p++;
4721     }
4722   }
4723   *b = '\0';
4724   return (p == src_end); // return false if not all of the source was copied
4725 }