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