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 int    Arguments::_bootclassloader_append_index = -1;
  89 
  90 // These parameters are reset in method parse_vm_init_args()
  91 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
  92 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
  93 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
  94 bool   Arguments::_ClipInlining                 = ClipInlining;
  95 intx   Arguments::_Tier3InvokeNotifyFreqLog     = Tier3InvokeNotifyFreqLog;
  96 intx   Arguments::_Tier4InvocationThreshold     = Tier4InvocationThreshold;
  97 
  98 char*  Arguments::SharedArchivePath             = NULL;
  99 
 100 AgentLibraryList Arguments::_libraryList;
 101 AgentLibraryList Arguments::_agentList;
 102 
 103 abort_hook_t     Arguments::_abort_hook         = NULL;
 104 exit_hook_t      Arguments::_exit_hook          = NULL;
 105 vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
 106 
 107 
 108 SystemProperty *Arguments::_sun_boot_library_path = NULL;
 109 SystemProperty *Arguments::_java_library_path = NULL;
 110 SystemProperty *Arguments::_java_home = NULL;
 111 SystemProperty *Arguments::_java_class_path = NULL;
 112 SystemProperty *Arguments::_jdk_boot_class_path_append = NULL;
 113 
 114 GrowableArray<ModulePatchPath*> *Arguments::_patch_mod_prefix = NULL;
 115 PathString *Arguments::_system_boot_class_path = NULL;
 116 
 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 #endif
1336 
1337 //===========================================================================================================
1338 // Setting int/mixed/comp mode flags
1339 
1340 void Arguments::set_mode_flags(Mode mode) {
1341   // Set up default values for all flags.
1342   // If you add a flag to any of the branches below,
1343   // add a default value for it here.
1344   set_java_compiler(false);
1345   _mode                      = mode;
1346 
1347   // Ensure Agent_OnLoad has the correct initial values.
1348   // This may not be the final mode; mode may change later in onload phase.
1349   PropertyList_unique_add(&_system_properties, "java.vm.info",
1350                           VM_Version::vm_info_string(), AddProperty, UnwriteableProperty, ExternalProperty);
1351 
1352   UseInterpreter             = true;
1353   UseCompiler                = true;
1354   UseLoopCounter             = true;
1355 
1356   // Default values may be platform/compiler dependent -
1357   // use the saved values
1358   ClipInlining               = Arguments::_ClipInlining;
1359   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1360   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1361   BackgroundCompilation      = Arguments::_BackgroundCompilation;
1362   if (TieredCompilation) {
1363     if (FLAG_IS_DEFAULT(Tier3InvokeNotifyFreqLog)) {
1364       Tier3InvokeNotifyFreqLog = Arguments::_Tier3InvokeNotifyFreqLog;
1365     }
1366     if (FLAG_IS_DEFAULT(Tier4InvocationThreshold)) {
1367       Tier4InvocationThreshold = Arguments::_Tier4InvocationThreshold;
1368     }
1369   }
1370 
1371   // Change from defaults based on mode
1372   switch (mode) {
1373   default:
1374     ShouldNotReachHere();
1375     break;
1376   case _int:
1377     UseCompiler              = false;
1378     UseLoopCounter           = false;
1379     AlwaysCompileLoopMethods = false;
1380     UseOnStackReplacement    = false;
1381     break;
1382   case _mixed:
1383     // same as default
1384     break;
1385   case _comp:
1386     UseInterpreter           = false;
1387     BackgroundCompilation    = false;
1388     ClipInlining             = false;
1389     // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1390     // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1391     // compile a level 4 (C2) and then continue executing it.
1392     if (TieredCompilation) {
1393       Tier3InvokeNotifyFreqLog = 0;
1394       Tier4InvocationThreshold = 0;
1395     }
1396     break;
1397   }
1398 }
1399 
1400 #if defined(COMPILER2) || INCLUDE_JVMCI || defined(_LP64) || !INCLUDE_CDS
1401 // Conflict: required to use shared spaces (-Xshare:on), but
1402 // incompatible command line options were chosen.
1403 
1404 static void no_shared_spaces(const char* message) {
1405   if (RequireSharedSpaces) {
1406     jio_fprintf(defaultStream::error_stream(),
1407       "Class data sharing is inconsistent with other specified options.\n");
1408     vm_exit_during_initialization("Unable to use shared archive.", message);
1409   } else {
1410     FLAG_SET_DEFAULT(UseSharedSpaces, false);
1411   }
1412 }
1413 #endif
1414 
1415 // Returns threshold scaled with the value of scale.
1416 // If scale < 0.0, threshold is returned without scaling.
1417 intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
1418   if (scale == 1.0 || scale < 0.0) {
1419     return threshold;
1420   } else {
1421     return (intx)(threshold * scale);
1422   }
1423 }
1424 
1425 // Returns freq_log scaled with the value of scale.
1426 // Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
1427 // If scale < 0.0, freq_log is returned without scaling.
1428 intx Arguments::scaled_freq_log(intx freq_log, double scale) {
1429   // Check if scaling is necessary or if negative value was specified.
1430   if (scale == 1.0 || scale < 0.0) {
1431     return freq_log;
1432   }
1433   // Check values to avoid calculating log2 of 0.
1434   if (scale == 0.0 || freq_log == 0) {
1435     return 0;
1436   }
1437   // Determine the maximum notification frequency value currently supported.
1438   // The largest mask value that the interpreter/C1 can handle is
1439   // of length InvocationCounter::number_of_count_bits. Mask values are always
1440   // one bit shorter then the value of the notification frequency. Set
1441   // max_freq_bits accordingly.
1442   intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
1443   intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
1444   if (scaled_freq == 0) {
1445     // Return 0 right away to avoid calculating log2 of 0.
1446     return 0;
1447   } else if (scaled_freq > nth_bit(max_freq_bits)) {
1448     return max_freq_bits;
1449   } else {
1450     return log2_intptr(scaled_freq);
1451   }
1452 }
1453 
1454 void Arguments::set_tiered_flags() {
1455   // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1456   if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1457     FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1458   }
1459   if (CompilationPolicyChoice < 2) {
1460     vm_exit_during_initialization(
1461       "Incompatible compilation policy selected", NULL);
1462   }
1463   // Increase the code cache size - tiered compiles a lot more.
1464   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1465     FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
1466                   MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1467   }
1468   // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
1469   if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
1470     FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
1471   }
1472   if (!UseInterpreter) { // -Xcomp
1473     Tier3InvokeNotifyFreqLog = 0;
1474     Tier4InvocationThreshold = 0;
1475   }
1476 
1477   if (CompileThresholdScaling < 0) {
1478     vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
1479   }
1480 
1481   // Scale tiered compilation thresholds.
1482   // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
1483   if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
1484     FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
1485     FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
1486 
1487     FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
1488     FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
1489     FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
1490     FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
1491 
1492     // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
1493     // once these thresholds become supported.
1494 
1495     FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
1496     FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
1497 
1498     FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
1499     FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
1500 
1501     FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
1502 
1503     FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
1504     FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
1505     FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
1506     FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
1507   }
1508 }
1509 
1510 #if INCLUDE_ALL_GCS
1511 static void disable_adaptive_size_policy(const char* collector_name) {
1512   if (UseAdaptiveSizePolicy) {
1513     if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
1514       warning("Disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
1515               collector_name);
1516     }
1517     FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
1518   }
1519 }
1520 
1521 void Arguments::set_parnew_gc_flags() {
1522   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
1523          "control point invariant");
1524   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1525   assert(UseParNewGC, "ParNew should always be used with CMS");
1526 
1527   if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
1528     FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1529     assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
1530   } else if (ParallelGCThreads == 0) {
1531     jio_fprintf(defaultStream::error_stream(),
1532         "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
1533     vm_exit(1);
1534   }
1535 
1536   // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
1537   // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
1538   // we set them to 1024 and 1024.
1539   // See CR 6362902.
1540   if (FLAG_IS_DEFAULT(YoungPLABSize)) {
1541     FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
1542   }
1543   if (FLAG_IS_DEFAULT(OldPLABSize)) {
1544     FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
1545   }
1546 
1547   // When using compressed oops, we use local overflow stacks,
1548   // rather than using a global overflow list chained through
1549   // the klass word of the object's pre-image.
1550   if (UseCompressedOops && !ParGCUseLocalOverflow) {
1551     if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
1552       warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
1553     }
1554     FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
1555   }
1556   assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
1557 }
1558 
1559 // Adjust some sizes to suit CMS and/or ParNew needs; these work well on
1560 // sparc/solaris for certain applications, but would gain from
1561 // further optimization and tuning efforts, and would almost
1562 // certainly gain from analysis of platform and environment.
1563 void Arguments::set_cms_and_parnew_gc_flags() {
1564   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
1565   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1566   assert(UseParNewGC, "ParNew should always be used with CMS");
1567 
1568   // Turn off AdaptiveSizePolicy by default for cms until it is complete.
1569   disable_adaptive_size_policy("UseConcMarkSweepGC");
1570 
1571   set_parnew_gc_flags();
1572 
1573   size_t max_heap = align_size_down(MaxHeapSize,
1574                                     CardTableRS::ct_max_alignment_constraint());
1575 
1576   // Now make adjustments for CMS
1577   intx   tenuring_default = (intx)6;
1578   size_t young_gen_per_worker = CMSYoungGenPerWorker;
1579 
1580   // Preferred young gen size for "short" pauses:
1581   // upper bound depends on # of threads and NewRatio.
1582   const size_t preferred_max_new_size_unaligned =
1583     MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * ParallelGCThreads));
1584   size_t preferred_max_new_size =
1585     align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
1586 
1587   // Unless explicitly requested otherwise, size young gen
1588   // for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
1589 
1590   // If either MaxNewSize or NewRatio is set on the command line,
1591   // assume the user is trying to set the size of the young gen.
1592   if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
1593 
1594     // Set MaxNewSize to our calculated preferred_max_new_size unless
1595     // NewSize was set on the command line and it is larger than
1596     // preferred_max_new_size.
1597     if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
1598       FLAG_SET_ERGO(size_t, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
1599     } else {
1600       FLAG_SET_ERGO(size_t, MaxNewSize, preferred_max_new_size);
1601     }
1602     log_trace(gc, heap)("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
1603 
1604     // Code along this path potentially sets NewSize and OldSize
1605     log_trace(gc, heap)("CMS set min_heap_size: " SIZE_FORMAT " initial_heap_size:  " SIZE_FORMAT " max_heap: " SIZE_FORMAT,
1606                         min_heap_size(), InitialHeapSize, max_heap);
1607     size_t min_new = preferred_max_new_size;
1608     if (FLAG_IS_CMDLINE(NewSize)) {
1609       min_new = NewSize;
1610     }
1611     if (max_heap > min_new && min_heap_size() > min_new) {
1612       // Unless explicitly requested otherwise, make young gen
1613       // at least min_new, and at most preferred_max_new_size.
1614       if (FLAG_IS_DEFAULT(NewSize)) {
1615         FLAG_SET_ERGO(size_t, NewSize, MAX2(NewSize, min_new));
1616         FLAG_SET_ERGO(size_t, NewSize, MIN2(preferred_max_new_size, NewSize));
1617         log_trace(gc, heap)("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
1618       }
1619       // Unless explicitly requested otherwise, size old gen
1620       // so it's NewRatio x of NewSize.
1621       if (FLAG_IS_DEFAULT(OldSize)) {
1622         if (max_heap > NewSize) {
1623           FLAG_SET_ERGO(size_t, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
1624           log_trace(gc, heap)("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
1625         }
1626       }
1627     }
1628   }
1629   // Unless explicitly requested otherwise, definitely
1630   // promote all objects surviving "tenuring_default" scavenges.
1631   if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
1632       FLAG_IS_DEFAULT(SurvivorRatio)) {
1633     FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
1634   }
1635   // If we decided above (or user explicitly requested)
1636   // `promote all' (via MaxTenuringThreshold := 0),
1637   // prefer minuscule survivor spaces so as not to waste
1638   // space for (non-existent) survivors
1639   if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
1640     FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
1641   }
1642 
1643   // OldPLABSize is interpreted in CMS as not the size of the PLAB in words,
1644   // but rather the number of free blocks of a given size that are used when
1645   // replenishing the local per-worker free list caches.
1646   if (FLAG_IS_DEFAULT(OldPLABSize)) {
1647     if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
1648       // OldPLAB sizing manually turned off: Use a larger default setting,
1649       // unless it was manually specified. This is because a too-low value
1650       // will slow down scavenges.
1651       FLAG_SET_ERGO(size_t, OldPLABSize, CompactibleFreeListSpaceLAB::_default_static_old_plab_size); // default value before 6631166
1652     } else {
1653       FLAG_SET_DEFAULT(OldPLABSize, CompactibleFreeListSpaceLAB::_default_dynamic_old_plab_size); // old CMSParPromoteBlocksToClaim default
1654     }
1655   }
1656 
1657   // If either of the static initialization defaults have changed, note this
1658   // modification.
1659   if (!FLAG_IS_DEFAULT(OldPLABSize) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
1660     CompactibleFreeListSpaceLAB::modify_initialization(OldPLABSize, OldPLABWeight);
1661   }
1662 
1663   if (!ClassUnloading) {
1664     FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
1665     FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
1666   }
1667 
1668   log_trace(gc)("MarkStackSize: %uk  MarkStackSizeMax: %uk", (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1669 }
1670 #endif // INCLUDE_ALL_GCS
1671 
1672 void set_object_alignment() {
1673   // Object alignment.
1674   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1675   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1676   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1677   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1678   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1679   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1680 
1681   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1682   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1683 
1684   // Oop encoding heap max
1685   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1686 
1687   if (SurvivorAlignmentInBytes == 0) {
1688     SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1689   }
1690 
1691 #if INCLUDE_ALL_GCS
1692   // Set CMS global values
1693   CompactibleFreeListSpace::set_cms_values();
1694 #endif // INCLUDE_ALL_GCS
1695 }
1696 
1697 size_t Arguments::max_heap_for_compressed_oops() {
1698   // Avoid sign flip.
1699   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1700   // We need to fit both the NULL page and the heap into the memory budget, while
1701   // keeping alignment constraints of the heap. To guarantee the latter, as the
1702   // NULL page is located before the heap, we pad the NULL page to the conservative
1703   // maximum alignment that the GC may ever impose upon the heap.
1704   size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
1705                                                         _conservative_max_heap_alignment);
1706 
1707   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1708   NOT_LP64(ShouldNotReachHere(); return 0);
1709 }
1710 
1711 bool Arguments::should_auto_select_low_pause_collector() {
1712   if (UseAutoGCSelectPolicy &&
1713       !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
1714       (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
1715     log_trace(gc)("Automatic selection of the low pause collector based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
1716     return true;
1717   }
1718   return false;
1719 }
1720 
1721 void Arguments::set_use_compressed_oops() {
1722 #ifndef ZERO
1723 #ifdef _LP64
1724   // MaxHeapSize is not set up properly at this point, but
1725   // the only value that can override MaxHeapSize if we are
1726   // to use UseCompressedOops is InitialHeapSize.
1727   size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1728 
1729   if (max_heap_size <= max_heap_for_compressed_oops()) {
1730 #if !defined(COMPILER1) || defined(TIERED)
1731     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1732       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1733     }
1734 #endif
1735   } else {
1736     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1737       warning("Max heap size too large for Compressed Oops");
1738       FLAG_SET_DEFAULT(UseCompressedOops, false);
1739       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1740     }
1741   }
1742 #endif // _LP64
1743 #endif // ZERO
1744 }
1745 
1746 
1747 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1748 // set_use_compressed_oops().
1749 void Arguments::set_use_compressed_klass_ptrs() {
1750 #ifndef ZERO
1751 #ifdef _LP64
1752   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1753   if (!UseCompressedOops) {
1754     if (UseCompressedClassPointers) {
1755       warning("UseCompressedClassPointers requires UseCompressedOops");
1756     }
1757     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1758   } else {
1759     // Turn on UseCompressedClassPointers too
1760     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1761       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1762     }
1763     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1764     if (UseCompressedClassPointers) {
1765       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1766         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1767         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1768       }
1769     }
1770   }
1771 #endif // _LP64
1772 #endif // !ZERO
1773 }
1774 
1775 void Arguments::set_conservative_max_heap_alignment() {
1776   // The conservative maximum required alignment for the heap is the maximum of
1777   // the alignments imposed by several sources: any requirements from the heap
1778   // itself, the collector policy and the maximum page size we may run the VM
1779   // with.
1780   size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
1781 #if INCLUDE_ALL_GCS
1782   if (UseParallelGC) {
1783     heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
1784   } else if (UseG1GC) {
1785     heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
1786   }
1787 #endif // INCLUDE_ALL_GCS
1788   _conservative_max_heap_alignment = MAX4(heap_alignment,
1789                                           (size_t)os::vm_allocation_granularity(),
1790                                           os::max_page_size(),
1791                                           CollectorPolicy::compute_heap_alignment());
1792 }
1793 
1794 bool Arguments::gc_selected() {
1795 #if INCLUDE_ALL_GCS
1796   return UseSerialGC || UseParallelGC || UseParallelOldGC || UseConcMarkSweepGC || UseG1GC;
1797 #else
1798   return UseSerialGC;
1799 #endif // INCLUDE_ALL_GCS
1800 }
1801 
1802 void Arguments::select_gc_ergonomically() {
1803 #if INCLUDE_ALL_GCS
1804   if (os::is_server_class_machine()) {
1805     if (should_auto_select_low_pause_collector()) {
1806       FLAG_SET_ERGO_IF_DEFAULT(bool, UseConcMarkSweepGC, true);
1807     } else {
1808 #if defined(JAVASE_EMBEDDED)
1809       FLAG_SET_ERGO_IF_DEFAULT(bool, UseParallelGC, true);
1810 #else
1811       FLAG_SET_ERGO_IF_DEFAULT(bool, UseG1GC, true);
1812 #endif
1813     }
1814   } else {
1815     FLAG_SET_ERGO_IF_DEFAULT(bool, UseSerialGC, true);
1816   }
1817 #else
1818   UNSUPPORTED_OPTION(UseG1GC);
1819   UNSUPPORTED_OPTION(UseParallelGC);
1820   UNSUPPORTED_OPTION(UseParallelOldGC);
1821   UNSUPPORTED_OPTION(UseConcMarkSweepGC);
1822   UNSUPPORTED_OPTION(UseParNewGC);
1823   FLAG_SET_ERGO_IF_DEFAULT(bool, UseSerialGC, true);
1824 #endif // INCLUDE_ALL_GCS
1825 }
1826 
1827 void Arguments::select_gc() {
1828   if (!gc_selected()) {
1829     select_gc_ergonomically();
1830     if (!gc_selected()) {
1831       vm_exit_during_initialization("Garbage collector not selected (default collector explicitly disabled)", NULL);
1832     }
1833   }
1834 }
1835 
1836 void Arguments::set_ergonomics_flags() {
1837   select_gc();
1838 
1839 #if defined(COMPILER2) || INCLUDE_JVMCI
1840   // Shared spaces work fine with other GCs but causes bytecode rewriting
1841   // to be disabled, which hurts interpreter performance and decreases
1842   // server performance.  When -server is specified, keep the default off
1843   // unless it is asked for.  Future work: either add bytecode rewriting
1844   // at link time, or rewrite bytecodes in non-shared methods.
1845   if (!DumpSharedSpaces && !RequireSharedSpaces &&
1846       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1847     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1848   }
1849 #endif
1850 
1851   set_conservative_max_heap_alignment();
1852 
1853 #ifndef ZERO
1854 #ifdef _LP64
1855   set_use_compressed_oops();
1856 
1857   // set_use_compressed_klass_ptrs() must be called after calling
1858   // set_use_compressed_oops().
1859   set_use_compressed_klass_ptrs();
1860 
1861   // Also checks that certain machines are slower with compressed oops
1862   // in vm_version initialization code.
1863 #endif // _LP64
1864 #endif // !ZERO
1865 
1866   CodeCacheExtensions::set_ergonomics_flags();
1867 }
1868 
1869 void Arguments::set_parallel_gc_flags() {
1870   assert(UseParallelGC || UseParallelOldGC, "Error");
1871   // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1872   if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1873     FLAG_SET_DEFAULT(UseParallelOldGC, true);
1874   }
1875   FLAG_SET_DEFAULT(UseParallelGC, true);
1876 
1877   // If no heap maximum was requested explicitly, use some reasonable fraction
1878   // of the physical memory, up to a maximum of 1GB.
1879   FLAG_SET_DEFAULT(ParallelGCThreads,
1880                    Abstract_VM_Version::parallel_worker_threads());
1881   if (ParallelGCThreads == 0) {
1882     jio_fprintf(defaultStream::error_stream(),
1883         "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1884     vm_exit(1);
1885   }
1886 
1887   if (UseAdaptiveSizePolicy) {
1888     // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1889     // unless the user actually sets these flags.
1890     if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1891       FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1892     }
1893     if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1894       FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1895     }
1896   }
1897 
1898   // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1899   // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1900   // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1901   // See CR 6362902 for details.
1902   if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1903     if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1904        FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1905     }
1906     if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1907       FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1908     }
1909   }
1910 
1911   if (UseParallelOldGC) {
1912     // Par compact uses lower default values since they are treated as
1913     // minimums.  These are different defaults because of the different
1914     // interpretation and are not ergonomically set.
1915     if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1916       FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1917     }
1918   }
1919 }
1920 
1921 void Arguments::set_g1_gc_flags() {
1922   assert(UseG1GC, "Error");
1923 #if defined(COMPILER1) || INCLUDE_JVMCI
1924   FastTLABRefill = false;
1925 #endif
1926   FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1927   if (ParallelGCThreads == 0) {
1928     assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
1929     vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1930   }
1931 
1932 #if INCLUDE_ALL_GCS
1933   if (FLAG_IS_DEFAULT(G1ConcRefinementThreads)) {
1934     FLAG_SET_ERGO(uint, G1ConcRefinementThreads, ParallelGCThreads);
1935   }
1936 #endif
1937 
1938   // MarkStackSize will be set (if it hasn't been set by the user)
1939   // when concurrent marking is initialized.
1940   // Its value will be based upon the number of parallel marking threads.
1941   // But we do set the maximum mark stack size here.
1942   if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1943     FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1944   }
1945 
1946   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1947     // In G1, we want the default GC overhead goal to be higher than
1948     // it is for PS, or the heap might be expanded too aggressively.
1949     // We set it here to ~8%.
1950     FLAG_SET_DEFAULT(GCTimeRatio, 12);
1951   }
1952 
1953   // Below, we might need to calculate the pause time interval based on
1954   // the pause target. When we do so we are going to give G1 maximum
1955   // flexibility and allow it to do pauses when it needs to. So, we'll
1956   // arrange that the pause interval to be pause time target + 1 to
1957   // ensure that a) the pause time target is maximized with respect to
1958   // the pause interval and b) we maintain the invariant that pause
1959   // time target < pause interval. If the user does not want this
1960   // maximum flexibility, they will have to set the pause interval
1961   // explicitly.
1962 
1963   if (FLAG_IS_DEFAULT(MaxGCPauseMillis)) {
1964     // The default pause time target in G1 is 200ms
1965     FLAG_SET_DEFAULT(MaxGCPauseMillis, 200);
1966   }
1967 
1968   // Then, if the interval parameter was not set, set it according to
1969   // the pause time target (this will also deal with the case when the
1970   // pause time target is the default value).
1971   if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
1972     FLAG_SET_DEFAULT(GCPauseIntervalMillis, MaxGCPauseMillis + 1);
1973   }
1974 
1975   log_trace(gc)("MarkStackSize: %uk  MarkStackSizeMax: %uk", (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1976 }
1977 
1978 void Arguments::set_gc_specific_flags() {
1979 #if INCLUDE_ALL_GCS
1980   // Set per-collector flags
1981   if (UseParallelGC || UseParallelOldGC) {
1982     set_parallel_gc_flags();
1983   } else if (UseConcMarkSweepGC) {
1984     set_cms_and_parnew_gc_flags();
1985   } else if (UseG1GC) {
1986     set_g1_gc_flags();
1987   }
1988   if (AssumeMP && !UseSerialGC) {
1989     if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
1990       warning("If the number of processors is expected to increase from one, then"
1991               " you should configure the number of parallel GC threads appropriately"
1992               " using -XX:ParallelGCThreads=N");
1993     }
1994   }
1995   if (MinHeapFreeRatio == 100) {
1996     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
1997     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
1998   }
1999 #endif // INCLUDE_ALL_GCS
2000 }
2001 
2002 julong Arguments::limit_by_allocatable_memory(julong limit) {
2003   julong max_allocatable;
2004   julong result = limit;
2005   if (os::has_allocatable_memory_limit(&max_allocatable)) {
2006     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
2007   }
2008   return result;
2009 }
2010 
2011 // Use static initialization to get the default before parsing
2012 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
2013 
2014 void Arguments::set_heap_size() {
2015   const julong phys_mem =
2016     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
2017                             : (julong)MaxRAM;
2018 
2019   // If the maximum heap size has not been set with -Xmx,
2020   // then set it as fraction of the size of physical memory,
2021   // respecting the maximum and minimum sizes of the heap.
2022   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2023     julong reasonable_max = phys_mem / MaxRAMFraction;
2024 
2025     if (phys_mem <= MaxHeapSize * MinRAMFraction) {
2026       // Small physical memory, so use a minimum fraction of it for the heap
2027       reasonable_max = phys_mem / MinRAMFraction;
2028     } else {
2029       // Not-small physical memory, so require a heap at least
2030       // as large as MaxHeapSize
2031       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
2032     }
2033     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
2034       // Limit the heap size to ErgoHeapSizeLimit
2035       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
2036     }
2037     if (UseCompressedOops) {
2038       // Limit the heap size to the maximum possible when using compressed oops
2039       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
2040 
2041       // HeapBaseMinAddress can be greater than default but not less than.
2042       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
2043         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
2044           // matches compressed oops printing flags
2045           log_debug(gc, heap, coops)("HeapBaseMinAddress must be at least " SIZE_FORMAT
2046                                      " (" SIZE_FORMAT "G) which is greater than value given " SIZE_FORMAT,
2047                                      DefaultHeapBaseMinAddress,
2048                                      DefaultHeapBaseMinAddress/G,
2049                                      HeapBaseMinAddress);
2050           FLAG_SET_ERGO(size_t, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
2051         }
2052       }
2053 
2054       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
2055         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
2056         // but it should be not less than default MaxHeapSize.
2057         max_coop_heap -= HeapBaseMinAddress;
2058       }
2059       reasonable_max = MIN2(reasonable_max, max_coop_heap);
2060     }
2061     reasonable_max = limit_by_allocatable_memory(reasonable_max);
2062 
2063     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
2064       // An initial heap size was specified on the command line,
2065       // so be sure that the maximum size is consistent.  Done
2066       // after call to limit_by_allocatable_memory because that
2067       // method might reduce the allocation size.
2068       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
2069     }
2070 
2071     log_trace(gc, heap)("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
2072     FLAG_SET_ERGO(size_t, MaxHeapSize, (size_t)reasonable_max);
2073   }
2074 
2075   // If the minimum or initial heap_size have not been set or requested to be set
2076   // ergonomically, set them accordingly.
2077   if (InitialHeapSize == 0 || min_heap_size() == 0) {
2078     julong reasonable_minimum = (julong)(OldSize + NewSize);
2079 
2080     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
2081 
2082     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
2083 
2084     if (InitialHeapSize == 0) {
2085       julong reasonable_initial = phys_mem / InitialRAMFraction;
2086 
2087       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
2088       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
2089 
2090       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
2091 
2092       log_trace(gc, heap)("  Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
2093       FLAG_SET_ERGO(size_t, InitialHeapSize, (size_t)reasonable_initial);
2094     }
2095     // If the minimum heap size has not been set (via -Xms),
2096     // synchronize with InitialHeapSize to avoid errors with the default value.
2097     if (min_heap_size() == 0) {
2098       set_min_heap_size(MIN2((size_t)reasonable_minimum, InitialHeapSize));
2099       log_trace(gc, heap)("  Minimum heap size " SIZE_FORMAT, min_heap_size());
2100     }
2101   }
2102 }
2103 
2104 // This option inspects the machine and attempts to set various
2105 // parameters to be optimal for long-running, memory allocation
2106 // intensive jobs.  It is intended for machines with large
2107 // amounts of cpu and memory.
2108 jint Arguments::set_aggressive_heap_flags() {
2109   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
2110   // VM, but we may not be able to represent the total physical memory
2111   // available (like having 8gb of memory on a box but using a 32bit VM).
2112   // Thus, we need to make sure we're using a julong for intermediate
2113   // calculations.
2114   julong initHeapSize;
2115   julong total_memory = os::physical_memory();
2116 
2117   if (total_memory < (julong) 256 * M) {
2118     jio_fprintf(defaultStream::error_stream(),
2119             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
2120     vm_exit(1);
2121   }
2122 
2123   // The heap size is half of available memory, or (at most)
2124   // all of possible memory less 160mb (leaving room for the OS
2125   // when using ISM).  This is the maximum; because adaptive sizing
2126   // is turned on below, the actual space used may be smaller.
2127 
2128   initHeapSize = MIN2(total_memory / (julong) 2,
2129           total_memory - (julong) 160 * M);
2130 
2131   initHeapSize = limit_by_allocatable_memory(initHeapSize);
2132 
2133   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2134     if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, initHeapSize) != Flag::SUCCESS) {
2135       return JNI_EINVAL;
2136     }
2137     if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, initHeapSize) != Flag::SUCCESS) {
2138       return JNI_EINVAL;
2139     }
2140     // Currently the minimum size and the initial heap sizes are the same.
2141     set_min_heap_size(initHeapSize);
2142   }
2143   if (FLAG_IS_DEFAULT(NewSize)) {
2144     // Make the young generation 3/8ths of the total heap.
2145     if (FLAG_SET_CMDLINE(size_t, NewSize,
2146             ((julong) MaxHeapSize / (julong) 8) * (julong) 3) != Flag::SUCCESS) {
2147       return JNI_EINVAL;
2148     }
2149     if (FLAG_SET_CMDLINE(size_t, MaxNewSize, NewSize) != Flag::SUCCESS) {
2150       return JNI_EINVAL;
2151     }
2152   }
2153 
2154 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
2155   FLAG_SET_DEFAULT(UseLargePages, true);
2156 #endif
2157 
2158   // Increase some data structure sizes for efficiency
2159   if (FLAG_SET_CMDLINE(size_t, BaseFootPrintEstimate, MaxHeapSize) != Flag::SUCCESS) {
2160     return JNI_EINVAL;
2161   }
2162   if (FLAG_SET_CMDLINE(bool, ResizeTLAB, false) != Flag::SUCCESS) {
2163     return JNI_EINVAL;
2164   }
2165   if (FLAG_SET_CMDLINE(size_t, TLABSize, 256 * K) != Flag::SUCCESS) {
2166     return JNI_EINVAL;
2167   }
2168 
2169   // See the OldPLABSize comment below, but replace 'after promotion'
2170   // with 'after copying'.  YoungPLABSize is the size of the survivor
2171   // space per-gc-thread buffers.  The default is 4kw.
2172   if (FLAG_SET_CMDLINE(size_t, YoungPLABSize, 256 * K) != Flag::SUCCESS) { // Note: this is in words
2173     return JNI_EINVAL;
2174   }
2175 
2176   // OldPLABSize is the size of the buffers in the old gen that
2177   // UseParallelGC uses to promote live data that doesn't fit in the
2178   // survivor spaces.  At any given time, there's one for each gc thread.
2179   // The default size is 1kw. These buffers are rarely used, since the
2180   // survivor spaces are usually big enough.  For specjbb, however, there
2181   // are occasions when there's lots of live data in the young gen
2182   // and we end up promoting some of it.  We don't have a definite
2183   // explanation for why bumping OldPLABSize helps, but the theory
2184   // is that a bigger PLAB results in retaining something like the
2185   // original allocation order after promotion, which improves mutator
2186   // locality.  A minor effect may be that larger PLABs reduce the
2187   // number of PLAB allocation events during gc.  The value of 8kw
2188   // was arrived at by experimenting with specjbb.
2189   if (FLAG_SET_CMDLINE(size_t, OldPLABSize, 8 * K) != Flag::SUCCESS) { // Note: this is in words
2190     return JNI_EINVAL;
2191   }
2192 
2193   // Enable parallel GC and adaptive generation sizing
2194   if (FLAG_SET_CMDLINE(bool, UseParallelGC, true) != Flag::SUCCESS) {
2195     return JNI_EINVAL;
2196   }
2197   FLAG_SET_DEFAULT(ParallelGCThreads,
2198           Abstract_VM_Version::parallel_worker_threads());
2199 
2200   // Encourage steady state memory management
2201   if (FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100) != Flag::SUCCESS) {
2202     return JNI_EINVAL;
2203   }
2204 
2205   // This appears to improve mutator locality
2206   if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2207     return JNI_EINVAL;
2208   }
2209 
2210   // Get around early Solaris scheduling bug
2211   // (affinity vs other jobs on system)
2212   // but disallow DR and offlining (5008695).
2213   if (FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true) != Flag::SUCCESS) {
2214     return JNI_EINVAL;
2215   }
2216 
2217   return JNI_OK;
2218 }
2219 
2220 // This must be called after ergonomics.
2221 void Arguments::set_bytecode_flags() {
2222   if (!RewriteBytecodes) {
2223     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
2224   }
2225 }
2226 
2227 // Aggressive optimization flags  -XX:+AggressiveOpts
2228 jint Arguments::set_aggressive_opts_flags() {
2229 #ifdef COMPILER2
2230   if (AggressiveUnboxing) {
2231     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2232       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2233     } else if (!EliminateAutoBox) {
2234       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
2235       AggressiveUnboxing = false;
2236     }
2237     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
2238       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
2239     } else if (!DoEscapeAnalysis) {
2240       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
2241       AggressiveUnboxing = false;
2242     }
2243   }
2244   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2245     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2246       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2247     }
2248     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2249       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
2250     }
2251 
2252     // Feed the cache size setting into the JDK
2253     char buffer[1024];
2254     sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
2255     if (!add_property(buffer)) {
2256       return JNI_ENOMEM;
2257     }
2258   }
2259   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
2260     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
2261   }
2262 #endif
2263 
2264   if (AggressiveOpts) {
2265 // Sample flag setting code
2266 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
2267 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
2268 //    }
2269   }
2270 
2271   return JNI_OK;
2272 }
2273 
2274 //===========================================================================================================
2275 // Parsing of java.compiler property
2276 
2277 void Arguments::process_java_compiler_argument(const char* arg) {
2278   // For backwards compatibility, Djava.compiler=NONE or ""
2279   // causes us to switch to -Xint mode UNLESS -Xdebug
2280   // is also specified.
2281   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
2282     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
2283   }
2284 }
2285 
2286 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
2287   _sun_java_launcher = os::strdup_check_oom(launcher);
2288 }
2289 
2290 bool Arguments::created_by_java_launcher() {
2291   assert(_sun_java_launcher != NULL, "property must have value");
2292   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
2293 }
2294 
2295 bool Arguments::sun_java_launcher_is_altjvm() {
2296   return _sun_java_launcher_is_altjvm;
2297 }
2298 
2299 //===========================================================================================================
2300 // Parsing of main arguments
2301 
2302 #if INCLUDE_JVMCI
2303 // Check consistency of jvmci vm argument settings.
2304 bool Arguments::check_jvmci_args_consistency() {
2305   if (!EnableJVMCI && !JVMCIGlobals::check_jvmci_flags_are_consistent()) {
2306     JVMCIGlobals::print_jvmci_args_inconsistency_error_message();
2307     return false;
2308   }
2309   return true;
2310 }
2311 #endif //INCLUDE_JVMCI
2312 
2313 // Check consistency of GC selection
2314 bool Arguments::check_gc_consistency() {
2315   // Ensure that the user has not selected conflicting sets
2316   // of collectors.
2317   uint i = 0;
2318   if (UseSerialGC)                       i++;
2319   if (UseConcMarkSweepGC)                i++;
2320   if (UseParallelGC || UseParallelOldGC) i++;
2321   if (UseG1GC)                           i++;
2322   if (i > 1) {
2323     jio_fprintf(defaultStream::error_stream(),
2324                 "Conflicting collector combinations in option list; "
2325                 "please refer to the release notes for the combinations "
2326                 "allowed\n");
2327     return false;
2328   }
2329 
2330   if (UseConcMarkSweepGC && !UseParNewGC) {
2331     jio_fprintf(defaultStream::error_stream(),
2332         "It is not possible to combine the DefNew young collector with the CMS collector.\n");
2333     return false;
2334   }
2335 
2336   if (UseParNewGC && !UseConcMarkSweepGC) {
2337     jio_fprintf(defaultStream::error_stream(),
2338         "It is not possible to combine the ParNew young collector with any collector other than CMS.\n");
2339     return false;
2340   }
2341 
2342   return true;
2343 }
2344 
2345 // Check the consistency of vm_init_args
2346 bool Arguments::check_vm_args_consistency() {
2347   // Method for adding checks for flag consistency.
2348   // The intent is to warn the user of all possible conflicts,
2349   // before returning an error.
2350   // Note: Needs platform-dependent factoring.
2351   bool status = true;
2352 
2353   if (TLABRefillWasteFraction == 0) {
2354     jio_fprintf(defaultStream::error_stream(),
2355                 "TLABRefillWasteFraction should be a denominator, "
2356                 "not " SIZE_FORMAT "\n",
2357                 TLABRefillWasteFraction);
2358     status = false;
2359   }
2360 
2361   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2362     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
2363   }
2364 
2365   if (!(UseParallelGC || UseParallelOldGC) && FLAG_IS_DEFAULT(ScavengeBeforeFullGC)) {
2366     FLAG_SET_DEFAULT(ScavengeBeforeFullGC, false);
2367   }
2368 
2369   if (GCTimeLimit == 100) {
2370     // Turn off gc-overhead-limit-exceeded checks
2371     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2372   }
2373 
2374   status = status && check_gc_consistency();
2375 
2376   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2377   // insists that we hold the requisite locks so that the iteration is
2378   // MT-safe. For the verification at start-up and shut-down, we don't
2379   // yet have a good way of acquiring and releasing these locks,
2380   // which are not visible at the CollectedHeap level. We want to
2381   // be able to acquire these locks and then do the iteration rather
2382   // than just disable the lock verification. This will be fixed under
2383   // bug 4788986.
2384   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2385     if (VerifyDuringStartup) {
2386       warning("Heap verification at start-up disabled "
2387               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2388       VerifyDuringStartup = false; // Disable verification at start-up
2389     }
2390 
2391     if (VerifyBeforeExit) {
2392       warning("Heap verification at shutdown disabled "
2393               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2394       VerifyBeforeExit = false; // Disable verification at shutdown
2395     }
2396   }
2397 
2398   if (PrintNMTStatistics) {
2399 #if INCLUDE_NMT
2400     if (MemTracker::tracking_level() == NMT_off) {
2401 #endif // INCLUDE_NMT
2402       warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2403       PrintNMTStatistics = false;
2404 #if INCLUDE_NMT
2405     }
2406 #endif
2407   }
2408 #if INCLUDE_JVMCI
2409 
2410   status = status && check_jvmci_args_consistency();
2411 
2412   if (EnableJVMCI) {
2413     if (!ScavengeRootsInCode) {
2414       warning("forcing ScavengeRootsInCode non-zero because JVMCI is enabled");
2415       ScavengeRootsInCode = 1;
2416     }
2417     if (FLAG_IS_DEFAULT(TypeProfileLevel)) {
2418       TypeProfileLevel = 0;
2419     }
2420     if (UseJVMCICompiler) {
2421       if (FLAG_IS_DEFAULT(TypeProfileWidth)) {
2422         TypeProfileWidth = 8;
2423       }
2424     }
2425   }
2426 #endif
2427 
2428   // Check lower bounds of the code cache
2429   // Template Interpreter code is approximately 3X larger in debug builds.
2430   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2431   if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2432     jio_fprintf(defaultStream::error_stream(),
2433                 "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
2434                 os::vm_page_size()/K);
2435     status = false;
2436   } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2437     jio_fprintf(defaultStream::error_stream(),
2438                 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2439                 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2440     status = false;
2441   } else if (ReservedCodeCacheSize < min_code_cache_size) {
2442     jio_fprintf(defaultStream::error_stream(),
2443                 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2444                 min_code_cache_size/K);
2445     status = false;
2446   } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2447     // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2448     jio_fprintf(defaultStream::error_stream(),
2449                 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2450                 CODE_CACHE_SIZE_LIMIT/M);
2451     status = false;
2452   } else if (NonNMethodCodeHeapSize < min_code_cache_size) {
2453     jio_fprintf(defaultStream::error_stream(),
2454                 "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2455                 min_code_cache_size/K);
2456     status = false;
2457   }
2458 
2459 #ifdef _LP64
2460   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2461     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2462   }
2463 #endif
2464 
2465 #ifndef SUPPORT_RESERVED_STACK_AREA
2466   if (StackReservedPages != 0) {
2467     FLAG_SET_CMDLINE(intx, StackReservedPages, 0);
2468     warning("Reserved Stack Area not supported on this platform");
2469   }
2470 #endif
2471 
2472   if (BackgroundCompilation && (CompileTheWorld || ReplayCompiles)) {
2473     if (!FLAG_IS_DEFAULT(BackgroundCompilation)) {
2474       warning("BackgroundCompilation disabled due to CompileTheWorld or ReplayCompiles options.");
2475     }
2476     FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2477   }
2478   if (UseCompiler && is_interpreter_only()) {
2479     if (!FLAG_IS_DEFAULT(UseCompiler)) {
2480       warning("UseCompiler disabled due to -Xint.");
2481     }
2482     FLAG_SET_CMDLINE(bool, UseCompiler, false);
2483   }
2484 #ifdef COMPILER2
2485   if (PostLoopMultiversioning && !RangeCheckElimination) {
2486     if (!FLAG_IS_DEFAULT(PostLoopMultiversioning)) {
2487       warning("PostLoopMultiversioning disabled because RangeCheckElimination is disabled.");
2488     }
2489     FLAG_SET_CMDLINE(bool, PostLoopMultiversioning, false);
2490   }
2491 #endif
2492   return status;
2493 }
2494 
2495 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2496   const char* option_type) {
2497   if (ignore) return false;
2498 
2499   const char* spacer = " ";
2500   if (option_type == NULL) {
2501     option_type = ++spacer; // Set both to the empty string.
2502   }
2503 
2504   if (os::obsolete_option(option)) {
2505     jio_fprintf(defaultStream::error_stream(),
2506                 "Obsolete %s%soption: %s\n", option_type, spacer,
2507       option->optionString);
2508     return false;
2509   } else {
2510     jio_fprintf(defaultStream::error_stream(),
2511                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2512       option->optionString);
2513     return true;
2514   }
2515 }
2516 
2517 static const char* user_assertion_options[] = {
2518   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2519 };
2520 
2521 static const char* system_assertion_options[] = {
2522   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2523 };
2524 
2525 bool Arguments::parse_uintx(const char* value,
2526                             uintx* uintx_arg,
2527                             uintx min_size) {
2528 
2529   // Check the sign first since atojulong() parses only unsigned values.
2530   bool value_is_positive = !(*value == '-');
2531 
2532   if (value_is_positive) {
2533     julong n;
2534     bool good_return = atojulong(value, &n);
2535     if (good_return) {
2536       bool above_minimum = n >= min_size;
2537       bool value_is_too_large = n > max_uintx;
2538 
2539       if (above_minimum && !value_is_too_large) {
2540         *uintx_arg = n;
2541         return true;
2542       }
2543     }
2544   }
2545   return false;
2546 }
2547 
2548 unsigned int addreads_count = 0;
2549 unsigned int addexports_count = 0;
2550 unsigned int patch_mod_count = 0;
2551 const char* add_modules_value = NULL;
2552 
2553 bool Arguments::create_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
2554   size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
2555   char* property = AllocateHeap(prop_len, mtArguments);
2556   int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);
2557   if (ret < 0 || ret >= (int)prop_len) {
2558     FreeHeap(property);
2559     return false;
2560   }
2561   bool added = add_property(property, UnwriteableProperty, internal);
2562   FreeHeap(property);
2563   return added;
2564 }
2565 
2566 bool Arguments::create_numbered_property(const char* prop_base_name, const char* prop_value, unsigned int count) {
2567   // Make sure count is < 1,000. Otherwise, memory allocation will be too small.
2568   if (count < 1000) {
2569     size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + 5;
2570     char* property = AllocateHeap(prop_len, mtArguments);
2571     int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);
2572     if (ret < 0 || ret >= (int)prop_len) {
2573       FreeHeap(property);
2574       return false;
2575     }
2576     bool added = add_property(property, UnwriteableProperty, InternalProperty);
2577     FreeHeap(property);
2578     return added;
2579   }
2580   return false;
2581 }
2582 
2583 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2584                                                   julong* long_arg,
2585                                                   julong min_size) {
2586   if (!atojulong(s, long_arg)) return arg_unreadable;
2587   return check_memory_size(*long_arg, min_size);
2588 }
2589 
2590 // Parse JavaVMInitArgs structure
2591 
2592 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *java_tool_options_args,
2593                                    const JavaVMInitArgs *java_options_args,
2594                                    const JavaVMInitArgs *cmd_line_args) {
2595   bool patch_mod_javabase = false;
2596 
2597   // Save default settings for some mode flags
2598   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2599   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2600   Arguments::_ClipInlining             = ClipInlining;
2601   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2602   if (TieredCompilation) {
2603     Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2604     Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2605   }
2606 
2607   // Setup flags for mixed which is the default
2608   set_mode_flags(_mixed);
2609 
2610   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2611   // variable (if present).
2612   jint result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
2613   if (result != JNI_OK) {
2614     return result;
2615   }
2616 
2617   // Parse args structure generated from the command line flags.
2618   result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, Flag::COMMAND_LINE);
2619   if (result != JNI_OK) {
2620     return result;
2621   }
2622 
2623   // Parse args structure generated from the _JAVA_OPTIONS environment
2624   // variable (if present) (mimics classic VM)
2625   result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
2626   if (result != JNI_OK) {
2627     return result;
2628   }
2629 
2630   // Do final processing now that all arguments have been parsed
2631   result = finalize_vm_init_args();
2632   if (result != JNI_OK) {
2633     return result;
2634   }
2635 
2636   return JNI_OK;
2637 }
2638 
2639 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2640 // represents a valid JDWP agent.  is_path==true denotes that we
2641 // are dealing with -agentpath (case where name is a path), otherwise with
2642 // -agentlib
2643 bool valid_jdwp_agent(char *name, bool is_path) {
2644   char *_name;
2645   const char *_jdwp = "jdwp";
2646   size_t _len_jdwp, _len_prefix;
2647 
2648   if (is_path) {
2649     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2650       return false;
2651     }
2652 
2653     _name++;  // skip past last path separator
2654     _len_prefix = strlen(JNI_LIB_PREFIX);
2655 
2656     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2657       return false;
2658     }
2659 
2660     _name += _len_prefix;
2661     _len_jdwp = strlen(_jdwp);
2662 
2663     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2664       _name += _len_jdwp;
2665     }
2666     else {
2667       return false;
2668     }
2669 
2670     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2671       return false;
2672     }
2673 
2674     return true;
2675   }
2676 
2677   if (strcmp(name, _jdwp) == 0) {
2678     return true;
2679   }
2680 
2681   return false;
2682 }
2683 
2684 int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {
2685   // --patch-module=<module>=<file>(<pathsep><file>)*
2686   assert(patch_mod_tail != NULL, "Unexpected NULL patch-module value");
2687   // Find the equal sign between the module name and the path specification
2688   const char* module_equal = strchr(patch_mod_tail, '=');
2689   if (module_equal == NULL) {
2690     jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");
2691     return JNI_ERR;
2692   } else {
2693     // Pick out the module name
2694     size_t module_len = module_equal - patch_mod_tail;
2695     char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);
2696     if (module_name != NULL) {
2697       memcpy(module_name, patch_mod_tail, module_len);
2698       *(module_name + module_len) = '\0';
2699       // The path piece begins one past the module_equal sign
2700       add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);
2701       FREE_C_HEAP_ARRAY(char, module_name);
2702       if (!create_numbered_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {
2703         return JNI_ENOMEM;
2704       }
2705     } else {
2706       return JNI_ENOMEM;
2707     }
2708   }
2709   return JNI_OK;
2710 }
2711 
2712 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, Flag::Flags origin) {
2713   // For match_option to return remaining or value part of option string
2714   const char* tail;
2715 
2716   // iterate over arguments
2717   for (int index = 0; index < args->nOptions; index++) {
2718     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2719 
2720     const JavaVMOption* option = args->options + index;
2721 
2722     if (!match_option(option, "-Djava.class.path", &tail) &&
2723         !match_option(option, "-Dsun.java.command", &tail) &&
2724         !match_option(option, "-Dsun.java.launcher", &tail)) {
2725 
2726         // add all jvm options to the jvm_args string. This string
2727         // is used later to set the java.vm.args PerfData string constant.
2728         // the -Djava.class.path and the -Dsun.java.command options are
2729         // omitted from jvm_args string as each have their own PerfData
2730         // string constant object.
2731         build_jvm_args(option->optionString);
2732     }
2733 
2734     // -verbose:[class/gc/jni]
2735     if (match_option(option, "-verbose", &tail)) {
2736       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2737         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));
2738         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));
2739       } else if (!strcmp(tail, ":gc")) {
2740         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(gc));
2741       } else if (!strcmp(tail, ":jni")) {
2742         if (FLAG_SET_CMDLINE(bool, PrintJNIResolving, true) != Flag::SUCCESS) {
2743           return JNI_EINVAL;
2744         }
2745       }
2746     // -da / -ea / -disableassertions / -enableassertions
2747     // These accept an optional class/package name separated by a colon, e.g.,
2748     // -da:java.lang.Thread.
2749     } else if (match_option(option, user_assertion_options, &tail, true)) {
2750       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2751       if (*tail == '\0') {
2752         JavaAssertions::setUserClassDefault(enable);
2753       } else {
2754         assert(*tail == ':', "bogus match by match_option()");
2755         JavaAssertions::addOption(tail + 1, enable);
2756       }
2757     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2758     } else if (match_option(option, system_assertion_options, &tail, false)) {
2759       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2760       JavaAssertions::setSystemClassDefault(enable);
2761     // -bootclasspath:
2762     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2763         jio_fprintf(defaultStream::output_stream(),
2764           "-Xbootclasspath is no longer a supported option.\n");
2765         return JNI_EINVAL;
2766     // -bootclasspath/a:
2767     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2768       Arguments::set_bootclassloader_append_index((int)strlen(Arguments::get_sysclasspath())+1);
2769       Arguments::append_sysclasspath(tail);
2770     // -bootclasspath/p:
2771     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2772         jio_fprintf(defaultStream::output_stream(),
2773           "-Xbootclasspath/p is no longer a supported option.\n");
2774         return JNI_EINVAL;
2775     // -Xrun
2776     } else if (match_option(option, "-Xrun", &tail)) {
2777       if (tail != NULL) {
2778         const char* pos = strchr(tail, ':');
2779         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2780         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtArguments), tail, len);
2781         name[len] = '\0';
2782 
2783         char *options = NULL;
2784         if(pos != NULL) {
2785           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2786           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);
2787         }
2788 #if !INCLUDE_JVMTI
2789         if (strcmp(name, "jdwp") == 0) {
2790           jio_fprintf(defaultStream::error_stream(),
2791             "Debugging agents are not supported in this VM\n");
2792           return JNI_ERR;
2793         }
2794 #endif // !INCLUDE_JVMTI
2795         add_init_library(name, options);
2796       }
2797     } else if (match_option(option, "--add-reads=", &tail)) {
2798       if (!create_numbered_property("jdk.module.addreads", tail, addreads_count++)) {
2799         return JNI_ENOMEM;
2800       }
2801     } else if (match_option(option, "--add-exports=", &tail)) {
2802       if (!create_numbered_property("jdk.module.addexports", tail, addexports_count++)) {
2803         return JNI_ENOMEM;
2804       }
2805     } else if (match_option(option, "--add-modules=", &tail)) {
2806       add_modules_value = tail;
2807     } else if (match_option(option, "--limit-modules=", &tail)) {
2808       if (!create_property("jdk.module.limitmods", tail, InternalProperty)) {
2809         return JNI_ENOMEM;
2810       }
2811     } else if (match_option(option, "--module-path=", &tail)) {
2812       if (!create_property("jdk.module.path", tail, ExternalProperty)) {
2813         return JNI_ENOMEM;
2814       }
2815     } else if (match_option(option, "--upgrade-module-path=", &tail)) {
2816       if (!create_property("jdk.module.upgrade.path", tail, ExternalProperty)) {
2817         return JNI_ENOMEM;
2818       }
2819     } else if (match_option(option, "--patch-module=", &tail)) {
2820       // --patch-module=<module>=<file>(<pathsep><file>)*
2821       int res = process_patch_mod_option(tail, patch_mod_javabase);
2822       if (res != JNI_OK) {
2823         return res;
2824       }
2825     // -agentlib and -agentpath
2826     } else if (match_option(option, "-agentlib:", &tail) ||
2827           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2828       if(tail != NULL) {
2829         const char* pos = strchr(tail, '=');
2830         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2831         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtArguments), tail, len);
2832         name[len] = '\0';
2833 
2834         char *options = NULL;
2835         if(pos != NULL) {
2836           options = os::strdup_check_oom(pos + 1, mtArguments);
2837         }
2838 #if !INCLUDE_JVMTI
2839         if (valid_jdwp_agent(name, is_absolute_path)) {
2840           jio_fprintf(defaultStream::error_stream(),
2841             "Debugging agents are not supported in this VM\n");
2842           return JNI_ERR;
2843         }
2844 #endif // !INCLUDE_JVMTI
2845         add_init_agent(name, options, is_absolute_path);
2846       }
2847     // -javaagent
2848     } else if (match_option(option, "-javaagent:", &tail)) {
2849 #if !INCLUDE_JVMTI
2850       jio_fprintf(defaultStream::error_stream(),
2851         "Instrumentation agents are not supported in this VM\n");
2852       return JNI_ERR;
2853 #else
2854       if (tail != NULL) {
2855         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtArguments), tail);
2856         add_init_agent("instrument", options, false);
2857         // java agents need module java.instrument
2858         if (!Arguments::append_to_addmods_property("java.instrument")) {
2859           return JNI_ENOMEM;
2860         }
2861       }
2862 #endif // !INCLUDE_JVMTI
2863     // -Xnoclassgc
2864     } else if (match_option(option, "-Xnoclassgc")) {
2865       if (FLAG_SET_CMDLINE(bool, ClassUnloading, false) != Flag::SUCCESS) {
2866         return JNI_EINVAL;
2867       }
2868     // -Xconcgc
2869     } else if (match_option(option, "-Xconcgc")) {
2870       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true) != Flag::SUCCESS) {
2871         return JNI_EINVAL;
2872       }
2873     // -Xnoconcgc
2874     } else if (match_option(option, "-Xnoconcgc")) {
2875       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false) != Flag::SUCCESS) {
2876         return JNI_EINVAL;
2877       }
2878     // -Xbatch
2879     } else if (match_option(option, "-Xbatch")) {
2880       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2881         return JNI_EINVAL;
2882       }
2883     // -Xmn for compatibility with other JVM vendors
2884     } else if (match_option(option, "-Xmn", &tail)) {
2885       julong long_initial_young_size = 0;
2886       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2887       if (errcode != arg_in_range) {
2888         jio_fprintf(defaultStream::error_stream(),
2889                     "Invalid initial young generation size: %s\n", option->optionString);
2890         describe_range_error(errcode);
2891         return JNI_EINVAL;
2892       }
2893       if (FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2894         return JNI_EINVAL;
2895       }
2896       if (FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2897         return JNI_EINVAL;
2898       }
2899     // -Xms
2900     } else if (match_option(option, "-Xms", &tail)) {
2901       julong long_initial_heap_size = 0;
2902       // an initial heap size of 0 means automatically determine
2903       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2904       if (errcode != arg_in_range) {
2905         jio_fprintf(defaultStream::error_stream(),
2906                     "Invalid initial heap size: %s\n", option->optionString);
2907         describe_range_error(errcode);
2908         return JNI_EINVAL;
2909       }
2910       set_min_heap_size((size_t)long_initial_heap_size);
2911       // Currently the minimum size and the initial heap sizes are the same.
2912       // Can be overridden with -XX:InitialHeapSize.
2913       if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size) != Flag::SUCCESS) {
2914         return JNI_EINVAL;
2915       }
2916     // -Xmx
2917     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2918       julong long_max_heap_size = 0;
2919       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2920       if (errcode != arg_in_range) {
2921         jio_fprintf(defaultStream::error_stream(),
2922                     "Invalid maximum heap size: %s\n", option->optionString);
2923         describe_range_error(errcode);
2924         return JNI_EINVAL;
2925       }
2926       if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size) != Flag::SUCCESS) {
2927         return JNI_EINVAL;
2928       }
2929     // Xmaxf
2930     } else if (match_option(option, "-Xmaxf", &tail)) {
2931       char* err;
2932       int maxf = (int)(strtod(tail, &err) * 100);
2933       if (*err != '\0' || *tail == '\0') {
2934         jio_fprintf(defaultStream::error_stream(),
2935                     "Bad max heap free percentage size: %s\n",
2936                     option->optionString);
2937         return JNI_EINVAL;
2938       } else {
2939         if (FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf) != Flag::SUCCESS) {
2940             return JNI_EINVAL;
2941         }
2942       }
2943     // Xminf
2944     } else if (match_option(option, "-Xminf", &tail)) {
2945       char* err;
2946       int minf = (int)(strtod(tail, &err) * 100);
2947       if (*err != '\0' || *tail == '\0') {
2948         jio_fprintf(defaultStream::error_stream(),
2949                     "Bad min heap free percentage size: %s\n",
2950                     option->optionString);
2951         return JNI_EINVAL;
2952       } else {
2953         if (FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf) != Flag::SUCCESS) {
2954           return JNI_EINVAL;
2955         }
2956       }
2957     // -Xss
2958     } else if (match_option(option, "-Xss", &tail)) {
2959       julong long_ThreadStackSize = 0;
2960       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2961       if (errcode != arg_in_range) {
2962         jio_fprintf(defaultStream::error_stream(),
2963                     "Invalid thread stack size: %s\n", option->optionString);
2964         describe_range_error(errcode);
2965         return JNI_EINVAL;
2966       }
2967       // Internally track ThreadStackSize in units of 1024 bytes.
2968       if (FLAG_SET_CMDLINE(intx, ThreadStackSize,
2969                        round_to((int)long_ThreadStackSize, K) / K) != Flag::SUCCESS) {
2970         return JNI_EINVAL;
2971       }
2972     // -Xoss, -Xsqnopause, -Xoptimize, -Xboundthreads, -Xusealtsigs
2973     } else if (match_option(option, "-Xoss", &tail) ||
2974                match_option(option, "-Xsqnopause") ||
2975                match_option(option, "-Xoptimize") ||
2976                match_option(option, "-Xboundthreads") ||
2977                match_option(option, "-Xusealtsigs")) {
2978       // All these options are deprecated in JDK 9 and will be removed in a future release
2979       char version[256];
2980       JDK_Version::jdk(9).to_string(version, sizeof(version));
2981       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2982     } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
2983       julong long_CodeCacheExpansionSize = 0;
2984       ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
2985       if (errcode != arg_in_range) {
2986         jio_fprintf(defaultStream::error_stream(),
2987                    "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
2988                    os::vm_page_size()/K);
2989         return JNI_EINVAL;
2990       }
2991       if (FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize) != Flag::SUCCESS) {
2992         return JNI_EINVAL;
2993       }
2994     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2995                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2996       julong long_ReservedCodeCacheSize = 0;
2997 
2998       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2999       if (errcode != arg_in_range) {
3000         jio_fprintf(defaultStream::error_stream(),
3001                     "Invalid maximum code cache size: %s.\n", option->optionString);
3002         return JNI_EINVAL;
3003       }
3004       if (FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != Flag::SUCCESS) {
3005         return JNI_EINVAL;
3006       }
3007       // -XX:NonNMethodCodeHeapSize=
3008     } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
3009       julong long_NonNMethodCodeHeapSize = 0;
3010 
3011       ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
3012       if (errcode != arg_in_range) {
3013         jio_fprintf(defaultStream::error_stream(),
3014                     "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
3015         return JNI_EINVAL;
3016       }
3017       if (FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize) != Flag::SUCCESS) {
3018         return JNI_EINVAL;
3019       }
3020       // -XX:ProfiledCodeHeapSize=
3021     } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
3022       julong long_ProfiledCodeHeapSize = 0;
3023 
3024       ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
3025       if (errcode != arg_in_range) {
3026         jio_fprintf(defaultStream::error_stream(),
3027                     "Invalid maximum profiled code heap size: %s.\n", option->optionString);
3028         return JNI_EINVAL;
3029       }
3030       if (FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize) != Flag::SUCCESS) {
3031         return JNI_EINVAL;
3032       }
3033       // -XX:NonProfiledCodeHeapSizee=
3034     } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
3035       julong long_NonProfiledCodeHeapSize = 0;
3036 
3037       ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
3038       if (errcode != arg_in_range) {
3039         jio_fprintf(defaultStream::error_stream(),
3040                     "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
3041         return JNI_EINVAL;
3042       }
3043       if (FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize) != Flag::SUCCESS) {
3044         return JNI_EINVAL;
3045       }
3046     // -green
3047     } else if (match_option(option, "-green")) {
3048       jio_fprintf(defaultStream::error_stream(),
3049                   "Green threads support not available\n");
3050           return JNI_EINVAL;
3051     // -native
3052     } else if (match_option(option, "-native")) {
3053           // HotSpot always uses native threads, ignore silently for compatibility
3054     // -Xrs
3055     } else if (match_option(option, "-Xrs")) {
3056           // Classic/EVM option, new functionality
3057       if (FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true) != Flag::SUCCESS) {
3058         return JNI_EINVAL;
3059       }
3060     // -Xprof
3061     } else if (match_option(option, "-Xprof")) {
3062 #if INCLUDE_FPROF
3063       _has_profile = true;
3064 #else // INCLUDE_FPROF
3065       jio_fprintf(defaultStream::error_stream(),
3066         "Flat profiling is not supported in this VM.\n");
3067       return JNI_ERR;
3068 #endif // INCLUDE_FPROF
3069     // -Xconcurrentio
3070     } else if (match_option(option, "-Xconcurrentio")) {
3071       if (FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true) != Flag::SUCCESS) {
3072         return JNI_EINVAL;
3073       }
3074       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
3075         return JNI_EINVAL;
3076       }
3077       if (FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1) != Flag::SUCCESS) {
3078         return JNI_EINVAL;
3079       }
3080       if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
3081         return JNI_EINVAL;
3082       }
3083       if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
3084         return JNI_EINVAL;
3085       }
3086 
3087       // -Xinternalversion
3088     } else if (match_option(option, "-Xinternalversion")) {
3089       jio_fprintf(defaultStream::output_stream(), "%s\n",
3090                   VM_Version::internal_vm_info_string());
3091       vm_exit(0);
3092 #ifndef PRODUCT
3093     // -Xprintflags
3094     } else if (match_option(option, "-Xprintflags")) {
3095       CommandLineFlags::printFlags(tty, false);
3096       vm_exit(0);
3097 #endif
3098     // -D
3099     } else if (match_option(option, "-D", &tail)) {
3100       const char* value;
3101       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
3102             *value!= '\0' && strcmp(value, "\"\"") != 0) {
3103         // abort if -Djava.endorsed.dirs is set
3104         jio_fprintf(defaultStream::output_stream(),
3105           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
3106           "in modular form will be supported via the concept of upgradeable modules.\n", value);
3107         return JNI_EINVAL;
3108       }
3109       if (match_option(option, "-Djava.ext.dirs=", &value) &&
3110             *value != '\0' && strcmp(value, "\"\"") != 0) {
3111         // abort if -Djava.ext.dirs is set
3112         jio_fprintf(defaultStream::output_stream(),
3113           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
3114         return JNI_EINVAL;
3115       }
3116       // Check for module related properties.  They must be set using the modules
3117       // options. For example: use "--add-modules=java.sql", not
3118       // "-Djdk.module.addmods=java.sql"
3119       if (is_internal_module_property(option->optionString + 2)) {
3120         needs_module_property_warning = true;
3121         continue;
3122       }
3123 
3124       if (!add_property(tail)) {
3125         return JNI_ENOMEM;
3126       }
3127       // Out of the box management support
3128       if (match_option(option, "-Dcom.sun.management", &tail)) {
3129 #if INCLUDE_MANAGEMENT
3130         if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
3131           return JNI_EINVAL;
3132         }
3133         // management agent in module java.management
3134         if (!Arguments::append_to_addmods_property("java.management")) {
3135           return JNI_ENOMEM;
3136         }
3137 #else
3138         jio_fprintf(defaultStream::output_stream(),
3139           "-Dcom.sun.management is not supported in this VM.\n");
3140         return JNI_ERR;
3141 #endif
3142       }
3143     // -Xint
3144     } else if (match_option(option, "-Xint")) {
3145           set_mode_flags(_int);
3146     // -Xmixed
3147     } else if (match_option(option, "-Xmixed")) {
3148           set_mode_flags(_mixed);
3149     // -Xcomp
3150     } else if (match_option(option, "-Xcomp")) {
3151       // for testing the compiler; turn off all flags that inhibit compilation
3152           set_mode_flags(_comp);
3153     // -Xshare:dump
3154     } else if (match_option(option, "-Xshare:dump")) {
3155       if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
3156         return JNI_EINVAL;
3157       }
3158       set_mode_flags(_int);     // Prevent compilation, which creates objects
3159     // -Xshare:on
3160     } else if (match_option(option, "-Xshare:on")) {
3161       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3162         return JNI_EINVAL;
3163       }
3164       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3165         return JNI_EINVAL;
3166       }
3167     // -Xshare:auto
3168     } else if (match_option(option, "-Xshare:auto")) {
3169       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3170         return JNI_EINVAL;
3171       }
3172       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3173         return JNI_EINVAL;
3174       }
3175     // -Xshare:off
3176     } else if (match_option(option, "-Xshare:off")) {
3177       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
3178         return JNI_EINVAL;
3179       }
3180       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3181         return JNI_EINVAL;
3182       }
3183     // -Xverify
3184     } else if (match_option(option, "-Xverify", &tail)) {
3185       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
3186         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
3187           return JNI_EINVAL;
3188         }
3189         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3190           return JNI_EINVAL;
3191         }
3192       } else if (strcmp(tail, ":remote") == 0) {
3193         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3194           return JNI_EINVAL;
3195         }
3196         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3197           return JNI_EINVAL;
3198         }
3199       } else if (strcmp(tail, ":none") == 0) {
3200         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3201           return JNI_EINVAL;
3202         }
3203         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
3204           return JNI_EINVAL;
3205         }
3206       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3207         return JNI_EINVAL;
3208       }
3209     // -Xdebug
3210     } else if (match_option(option, "-Xdebug")) {
3211       // note this flag has been used, then ignore
3212       set_xdebug_mode(true);
3213     // -Xnoagent
3214     } else if (match_option(option, "-Xnoagent")) {
3215       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3216     } else if (match_option(option, "-Xloggc:", &tail)) {
3217       // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
3218       log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
3219       _gc_log_filename = os::strdup_check_oom(tail);
3220     } else if (match_option(option, "-Xlog", &tail)) {
3221       bool ret = false;
3222       if (strcmp(tail, ":help") == 0) {
3223         LogConfiguration::print_command_line_help(defaultStream::output_stream());
3224         vm_exit(0);
3225       } else if (strcmp(tail, ":disable") == 0) {
3226         LogConfiguration::disable_logging();
3227         ret = true;
3228       } else if (*tail == '\0') {
3229         ret = LogConfiguration::parse_command_line_arguments();
3230         assert(ret, "-Xlog without arguments should never fail to parse");
3231       } else if (*tail == ':') {
3232         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
3233       }
3234       if (ret == false) {
3235         jio_fprintf(defaultStream::error_stream(),
3236                     "Invalid -Xlog option '-Xlog%s'\n",
3237                     tail);
3238         return JNI_EINVAL;
3239       }
3240     // JNI hooks
3241     } else if (match_option(option, "-Xcheck", &tail)) {
3242       if (!strcmp(tail, ":jni")) {
3243 #if !INCLUDE_JNI_CHECK
3244         warning("JNI CHECKING is not supported in this VM");
3245 #else
3246         CheckJNICalls = true;
3247 #endif // INCLUDE_JNI_CHECK
3248       } else if (is_bad_option(option, args->ignoreUnrecognized,
3249                                      "check")) {
3250         return JNI_EINVAL;
3251       }
3252     } else if (match_option(option, "vfprintf")) {
3253       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3254     } else if (match_option(option, "exit")) {
3255       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3256     } else if (match_option(option, "abort")) {
3257       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3258     // -XX:+AggressiveHeap
3259     } else if (match_option(option, "-XX:+AggressiveHeap")) {
3260       jint result = set_aggressive_heap_flags();
3261       if (result != JNI_OK) {
3262           return result;
3263       }
3264     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
3265     // and the last option wins.
3266     } else if (match_option(option, "-XX:+NeverTenure")) {
3267       if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
3268         return JNI_EINVAL;
3269       }
3270       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3271         return JNI_EINVAL;
3272       }
3273       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
3274         return JNI_EINVAL;
3275       }
3276     } else if (match_option(option, "-XX:+AlwaysTenure")) {
3277       if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3278         return JNI_EINVAL;
3279       }
3280       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3281         return JNI_EINVAL;
3282       }
3283       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
3284         return JNI_EINVAL;
3285       }
3286     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
3287       uintx max_tenuring_thresh = 0;
3288       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
3289         jio_fprintf(defaultStream::error_stream(),
3290                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
3291         return JNI_EINVAL;
3292       }
3293 
3294       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
3295         return JNI_EINVAL;
3296       }
3297 
3298       if (MaxTenuringThreshold == 0) {
3299         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3300           return JNI_EINVAL;
3301         }
3302         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3303           return JNI_EINVAL;
3304         }
3305       } else {
3306         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3307           return JNI_EINVAL;
3308         }
3309         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3310           return JNI_EINVAL;
3311         }
3312       }
3313     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3314       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
3315         return JNI_EINVAL;
3316       }
3317       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
3318         return JNI_EINVAL;
3319       }
3320     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3321       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
3322         return JNI_EINVAL;
3323       }
3324       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3325         return JNI_EINVAL;
3326       }
3327     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3328 #if defined(DTRACE_ENABLED)
3329       if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3330         return JNI_EINVAL;
3331       }
3332       if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3333         return JNI_EINVAL;
3334       }
3335       if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3336         return JNI_EINVAL;
3337       }
3338       if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3339         return JNI_EINVAL;
3340       }
3341 #else // defined(DTRACE_ENABLED)
3342       jio_fprintf(defaultStream::error_stream(),
3343                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3344       return JNI_EINVAL;
3345 #endif // defined(DTRACE_ENABLED)
3346 #ifdef ASSERT
3347     } else if (match_option(option, "-XX:+FullGCALot")) {
3348       if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3349         return JNI_EINVAL;
3350       }
3351       // disable scavenge before parallel mark-compact
3352       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3353         return JNI_EINVAL;
3354       }
3355 #endif
3356 #if !INCLUDE_MANAGEMENT
3357     } else if (match_option(option, "-XX:+ManagementServer")) {
3358         jio_fprintf(defaultStream::error_stream(),
3359           "ManagementServer is not supported in this VM.\n");
3360         return JNI_ERR;
3361 #endif // INCLUDE_MANAGEMENT
3362     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3363       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
3364       // already been handled
3365       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
3366           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
3367         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3368           return JNI_EINVAL;
3369         }
3370       }
3371     // Unknown option
3372     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3373       return JNI_ERR;
3374     }
3375   }
3376 
3377   // PrintSharedArchiveAndExit will turn on
3378   //   -Xshare:on
3379   //   -Xlog:class+path=info
3380   if (PrintSharedArchiveAndExit) {
3381     if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3382       return JNI_EINVAL;
3383     }
3384     if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3385       return JNI_EINVAL;
3386     }
3387     LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));
3388   }
3389 
3390   // Change the default value for flags  which have different default values
3391   // when working with older JDKs.
3392 #ifdef LINUX
3393  if (JDK_Version::current().compare_major(6) <= 0 &&
3394       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3395     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3396   }
3397 #endif // LINUX
3398   fix_appclasspath();
3399   return JNI_OK;
3400 }
3401 
3402 void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {
3403   // For java.base check for duplicate --patch-module options being specified on the command line.
3404   // This check is only required for java.base, all other duplicate module specifications
3405   // will be checked during module system initialization.  The module system initialization
3406   // will throw an ExceptionInInitializerError if this situation occurs.
3407   if (strcmp(module_name, "java.base") == 0) {
3408     if (*patch_mod_javabase) {
3409       vm_exit_during_initialization("Cannot specify java.base more than once to --patch-module");
3410     } else {
3411       *patch_mod_javabase = true;
3412     }
3413   }
3414 
3415   // Create GrowableArray lazily, only if --patch-module has been specified
3416   if (_patch_mod_prefix == NULL) {
3417     _patch_mod_prefix = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<ModulePatchPath*>(10, true);
3418   }
3419 
3420   _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
3421 }
3422 
3423 // Set property jdk.boot.class.path.append to the contents of the bootclasspath
3424 // that follows either the jimage file or exploded module directories.  The
3425 // property will contain -Xbootclasspath/a and/or jvmti appended additions.
3426 void Arguments::set_jdkbootclasspath_append() {
3427   char *sysclasspath = get_sysclasspath();
3428   assert(sysclasspath != NULL, "NULL sysclasspath");
3429   int bcp_a_idx = bootclassloader_append_index();
3430   if (bcp_a_idx != -1 && bcp_a_idx < (int)strlen(sysclasspath)) {
3431     _jdk_boot_class_path_append->set_value(sysclasspath + bcp_a_idx);
3432   }
3433 }
3434 
3435 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3436 //
3437 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3438 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3439 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3440 // path is treated as the current directory.
3441 //
3442 // This causes problems with CDS, which requires that all directories specified in the classpath
3443 // must be empty. In most cases, applications do NOT want to load classes from the current
3444 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3445 // scripts compatible with CDS.
3446 void Arguments::fix_appclasspath() {
3447   if (IgnoreEmptyClassPaths) {
3448     const char separator = *os::path_separator();
3449     const char* src = _java_class_path->value();
3450 
3451     // skip over all the leading empty paths
3452     while (*src == separator) {
3453       src ++;
3454     }
3455 
3456     char* copy = os::strdup_check_oom(src, mtArguments);
3457 
3458     // trim all trailing empty paths
3459     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3460       *tail = '\0';
3461     }
3462 
3463     char from[3] = {separator, separator, '\0'};
3464     char to  [2] = {separator, '\0'};
3465     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3466       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3467       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3468     }
3469 
3470     _java_class_path->set_writeable_value(copy);
3471     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3472   }
3473 }
3474 
3475 static bool has_jar_files(const char* directory) {
3476   DIR* dir = os::opendir(directory);
3477   if (dir == NULL) return false;
3478 
3479   struct dirent *entry;
3480   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtArguments);
3481   bool hasJarFile = false;
3482   while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3483     const char* name = entry->d_name;
3484     const char* ext = name + strlen(name) - 4;
3485     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3486   }
3487   FREE_C_HEAP_ARRAY(char, dbuf);
3488   os::closedir(dir);
3489   return hasJarFile ;
3490 }
3491 
3492 static int check_non_empty_dirs(const char* path) {
3493   const char separator = *os::path_separator();
3494   const char* const end = path + strlen(path);
3495   int nonEmptyDirs = 0;
3496   while (path < end) {
3497     const char* tmp_end = strchr(path, separator);
3498     if (tmp_end == NULL) {
3499       if (has_jar_files(path)) {
3500         nonEmptyDirs++;
3501         jio_fprintf(defaultStream::output_stream(),
3502           "Non-empty directory: %s\n", path);
3503       }
3504       path = end;
3505     } else {
3506       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtArguments);
3507       memcpy(dirpath, path, tmp_end - path);
3508       dirpath[tmp_end - path] = '\0';
3509       if (has_jar_files(dirpath)) {
3510         nonEmptyDirs++;
3511         jio_fprintf(defaultStream::output_stream(),
3512           "Non-empty directory: %s\n", dirpath);
3513       }
3514       FREE_C_HEAP_ARRAY(char, dirpath);
3515       path = tmp_end + 1;
3516     }
3517   }
3518   return nonEmptyDirs;
3519 }
3520 
3521 jint Arguments::finalize_vm_init_args() {
3522   // check if the default lib/endorsed directory exists; if so, error
3523   char path[JVM_MAXPATHLEN];
3524   const char* fileSep = os::file_separator();
3525   sprintf(path, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3526 
3527   if (CheckEndorsedAndExtDirs) {
3528     int nonEmptyDirs = 0;
3529     // check endorsed directory
3530     nonEmptyDirs += check_non_empty_dirs(path);
3531     // check the extension directories
3532     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3533     if (nonEmptyDirs > 0) {
3534       return JNI_ERR;
3535     }
3536   }
3537 
3538   DIR* dir = os::opendir(path);
3539   if (dir != NULL) {
3540     jio_fprintf(defaultStream::output_stream(),
3541       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3542       "in modular form will be supported via the concept of upgradeable modules.\n");
3543     os::closedir(dir);
3544     return JNI_ERR;
3545   }
3546 
3547   sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3548   dir = os::opendir(path);
3549   if (dir != NULL) {
3550     jio_fprintf(defaultStream::output_stream(),
3551       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3552       "Use -classpath instead.\n.");
3553     os::closedir(dir);
3554     return JNI_ERR;
3555   }
3556 
3557   // Append the value of the last --add-modules option specified on the command line.
3558   // This needs to be done here, to prevent overwriting possible values written
3559   // to the jdk.module.addmods property by -javaagent and other options.
3560   if (add_modules_value != NULL) {
3561     if (!append_to_addmods_property(add_modules_value)) {
3562       return JNI_ENOMEM;
3563     }
3564   }
3565 
3566   Arguments::set_bootclassloader_append_index(((int)strlen(Arguments::get_sysclasspath()))+1);
3567 
3568   // This must be done after all arguments have been processed.
3569   // java_compiler() true means set to "NONE" or empty.
3570   if (java_compiler() && !xdebug_mode()) {
3571     // For backwards compatibility, we switch to interpreted mode if
3572     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3573     // not specified.
3574     set_mode_flags(_int);
3575   }
3576 
3577   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3578   // but like -Xint, leave compilation thresholds unaffected.
3579   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3580   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3581     set_mode_flags(_int);
3582   }
3583 
3584   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3585   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3586     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3587   }
3588 
3589 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3590   // Don't degrade server performance for footprint
3591   if (FLAG_IS_DEFAULT(UseLargePages) &&
3592       MaxHeapSize < LargePageHeapSizeThreshold) {
3593     // No need for large granularity pages w/small heaps.
3594     // Note that large pages are enabled/disabled for both the
3595     // Java heap and the code cache.
3596     FLAG_SET_DEFAULT(UseLargePages, false);
3597   }
3598 
3599 #elif defined(COMPILER2)
3600   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3601     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3602   }
3603 #endif
3604 
3605 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3606   UNSUPPORTED_OPTION(ProfileInterpreter);
3607   NOT_PRODUCT(UNSUPPORTED_OPTION(TraceProfileInterpreter));
3608 #endif
3609 
3610 #ifndef TIERED
3611   // Tiered compilation is undefined.
3612   UNSUPPORTED_OPTION(TieredCompilation);
3613 #endif
3614 
3615 #if INCLUDE_JVMCI
3616   if (EnableJVMCI && !append_to_addmods_property("jdk.vm.ci")) {
3617     return JNI_ENOMEM;
3618   }
3619 #endif
3620 
3621   // If we are running in a headless jre, force java.awt.headless property
3622   // to be true unless the property has already been set.
3623   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3624   if (os::is_headless_jre()) {
3625     const char* headless = Arguments::get_property("java.awt.headless");
3626     if (headless == NULL) {
3627       const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3628       if (headless_env == NULL) {
3629         if (!add_property("java.awt.headless=true")) {
3630           return JNI_ENOMEM;
3631         }
3632       } else {
3633         char buffer[256];
3634         jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3635         if (!add_property(buffer)) {
3636           return JNI_ENOMEM;
3637         }
3638       }
3639     }
3640   }
3641 
3642   if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3643     // CMS can only be used with ParNew
3644     FLAG_SET_ERGO(bool, UseParNewGC, true);
3645   }
3646 
3647   if (!check_vm_args_consistency()) {
3648     return JNI_ERR;
3649   }
3650 
3651   return JNI_OK;
3652 }
3653 
3654 // Helper class for controlling the lifetime of JavaVMInitArgs
3655 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3656 // deleted on the destruction of the ScopedVMInitArgs object.
3657 class ScopedVMInitArgs : public StackObj {
3658  private:
3659   JavaVMInitArgs _args;
3660   char*          _container_name;
3661   bool           _is_set;
3662   char*          _vm_options_file_arg;
3663 
3664  public:
3665   ScopedVMInitArgs(const char *container_name) {
3666     _args.version = JNI_VERSION_1_2;
3667     _args.nOptions = 0;
3668     _args.options = NULL;
3669     _args.ignoreUnrecognized = false;
3670     _container_name = (char *)container_name;
3671     _is_set = false;
3672     _vm_options_file_arg = NULL;
3673   }
3674 
3675   // Populates the JavaVMInitArgs object represented by this
3676   // ScopedVMInitArgs object with the arguments in options.  The
3677   // allocated memory is deleted by the destructor.  If this method
3678   // returns anything other than JNI_OK, then this object is in a
3679   // partially constructed state, and should be abandoned.
3680   jint set_args(GrowableArray<JavaVMOption>* options) {
3681     _is_set = true;
3682     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3683         JavaVMOption, options->length(), mtArguments);
3684     if (options_arr == NULL) {
3685       return JNI_ENOMEM;
3686     }
3687     _args.options = options_arr;
3688 
3689     for (int i = 0; i < options->length(); i++) {
3690       options_arr[i] = options->at(i);
3691       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3692       if (options_arr[i].optionString == NULL) {
3693         // Rely on the destructor to do cleanup.
3694         _args.nOptions = i;
3695         return JNI_ENOMEM;
3696       }
3697     }
3698 
3699     _args.nOptions = options->length();
3700     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3701     return JNI_OK;
3702   }
3703 
3704   JavaVMInitArgs* get()             { return &_args; }
3705   char* container_name()            { return _container_name; }
3706   bool  is_set()                    { return _is_set; }
3707   bool  found_vm_options_file_arg() { return _vm_options_file_arg != NULL; }
3708   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3709 
3710   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3711     if (_vm_options_file_arg != NULL) {
3712       os::free(_vm_options_file_arg);
3713     }
3714     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3715   }
3716 
3717   ~ScopedVMInitArgs() {
3718     if (_vm_options_file_arg != NULL) {
3719       os::free(_vm_options_file_arg);
3720     }
3721     if (_args.options == NULL) return;
3722     for (int i = 0; i < _args.nOptions; i++) {
3723       os::free(_args.options[i].optionString);
3724     }
3725     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3726   }
3727 
3728   // Insert options into this option list, to replace option at
3729   // vm_options_file_pos (-XX:VMOptionsFile)
3730   jint insert(const JavaVMInitArgs* args,
3731               const JavaVMInitArgs* args_to_insert,
3732               const int vm_options_file_pos) {
3733     assert(_args.options == NULL, "shouldn't be set yet");
3734     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3735     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3736 
3737     int length = args->nOptions + args_to_insert->nOptions - 1;
3738     GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments)
3739               GrowableArray<JavaVMOption>(length, true);    // Construct new option array
3740     for (int i = 0; i < args->nOptions; i++) {
3741       if (i == vm_options_file_pos) {
3742         // insert the new options starting at the same place as the
3743         // -XX:VMOptionsFile option
3744         for (int j = 0; j < args_to_insert->nOptions; j++) {
3745           options->push(args_to_insert->options[j]);
3746         }
3747       } else {
3748         options->push(args->options[i]);
3749       }
3750     }
3751     // make into options array
3752     jint result = set_args(options);
3753     delete options;
3754     return result;
3755   }
3756 };
3757 
3758 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3759   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3760 }
3761 
3762 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3763   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3764 }
3765 
3766 jint Arguments::parse_options_environment_variable(const char* name,
3767                                                    ScopedVMInitArgs* vm_args) {
3768   char *buffer = ::getenv(name);
3769 
3770   // Don't check this environment variable if user has special privileges
3771   // (e.g. unix su command).
3772   if (buffer == NULL || os::have_special_privileges()) {
3773     return JNI_OK;
3774   }
3775 
3776   if ((buffer = os::strdup(buffer)) == NULL) {
3777     return JNI_ENOMEM;
3778   }
3779 
3780   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3781 
3782   os::free(buffer);
3783   return retcode;
3784 }
3785 
3786 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3787   // read file into buffer
3788   int fd = ::open(file_name, O_RDONLY);
3789   if (fd < 0) {
3790     jio_fprintf(defaultStream::error_stream(),
3791                 "Could not open options file '%s'\n",
3792                 file_name);
3793     return JNI_ERR;
3794   }
3795 
3796   struct stat stbuf;
3797   int retcode = os::stat(file_name, &stbuf);
3798   if (retcode != 0) {
3799     jio_fprintf(defaultStream::error_stream(),
3800                 "Could not stat options file '%s'\n",
3801                 file_name);
3802     os::close(fd);
3803     return JNI_ERR;
3804   }
3805 
3806   if (stbuf.st_size == 0) {
3807     // tell caller there is no option data and that is ok
3808     os::close(fd);
3809     return JNI_OK;
3810   }
3811 
3812   // '+ 1' for NULL termination even with max bytes
3813   size_t bytes_alloc = stbuf.st_size + 1;
3814 
3815   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3816   if (NULL == buf) {
3817     jio_fprintf(defaultStream::error_stream(),
3818                 "Could not allocate read buffer for options file parse\n");
3819     os::close(fd);
3820     return JNI_ENOMEM;
3821   }
3822 
3823   memset(buf, 0, bytes_alloc);
3824 
3825   // Fill buffer
3826   // Use ::read() instead of os::read because os::read()
3827   // might do a thread state transition
3828   // and it is too early for that here
3829 
3830   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3831   os::close(fd);
3832   if (bytes_read < 0) {
3833     FREE_C_HEAP_ARRAY(char, buf);
3834     jio_fprintf(defaultStream::error_stream(),
3835                 "Could not read options file '%s'\n", file_name);
3836     return JNI_ERR;
3837   }
3838 
3839   if (bytes_read == 0) {
3840     // tell caller there is no option data and that is ok
3841     FREE_C_HEAP_ARRAY(char, buf);
3842     return JNI_OK;
3843   }
3844 
3845   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3846 
3847   FREE_C_HEAP_ARRAY(char, buf);
3848   return retcode;
3849 }
3850 
3851 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3852   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3853 
3854   // some pointers to help with parsing
3855   char *buffer_end = buffer + buf_len;
3856   char *opt_hd = buffer;
3857   char *wrt = buffer;
3858   char *rd = buffer;
3859 
3860   // parse all options
3861   while (rd < buffer_end) {
3862     // skip leading white space from the input string
3863     while (rd < buffer_end && isspace(*rd)) {
3864       rd++;
3865     }
3866 
3867     if (rd >= buffer_end) {
3868       break;
3869     }
3870 
3871     // Remember this is where we found the head of the token.
3872     opt_hd = wrt;
3873 
3874     // Tokens are strings of non white space characters separated
3875     // by one or more white spaces.
3876     while (rd < buffer_end && !isspace(*rd)) {
3877       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3878         int quote = *rd;                    // matching quote to look for
3879         rd++;                               // don't copy open quote
3880         while (rd < buffer_end && *rd != quote) {
3881                                             // include everything (even spaces)
3882                                             // up until the close quote
3883           *wrt++ = *rd++;                   // copy to option string
3884         }
3885 
3886         if (rd < buffer_end) {
3887           rd++;                             // don't copy close quote
3888         } else {
3889                                             // did not see closing quote
3890           jio_fprintf(defaultStream::error_stream(),
3891                       "Unmatched quote in %s\n", name);
3892           delete options;
3893           return JNI_ERR;
3894         }
3895       } else {
3896         *wrt++ = *rd++;                     // copy to option string
3897       }
3898     }
3899 
3900     // steal a white space character and set it to NULL
3901     *wrt++ = '\0';
3902     // We now have a complete token
3903 
3904     JavaVMOption option;
3905     option.optionString = opt_hd;
3906     option.extraInfo = NULL;
3907 
3908     options->append(option);                // Fill in option
3909 
3910     rd++;  // Advance to next character
3911   }
3912 
3913   // Fill out JavaVMInitArgs structure.
3914   jint status = vm_args->set_args(options);
3915 
3916   delete options;
3917   return status;
3918 }
3919 
3920 void Arguments::set_shared_spaces_flags() {
3921   if (DumpSharedSpaces) {
3922     if (Arguments::get_patch_mod_prefix() != NULL) {
3923       vm_exit_during_initialization(
3924         "Cannot use the following option when dumping the shared archive: --patch-module");
3925     }
3926 
3927     if (RequireSharedSpaces) {
3928       warning("Cannot dump shared archive while using shared archive");
3929     }
3930     UseSharedSpaces = false;
3931 #ifdef _LP64
3932     if (!UseCompressedOops || !UseCompressedClassPointers) {
3933       vm_exit_during_initialization(
3934         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3935     }
3936   } else {
3937     if (!UseCompressedOops || !UseCompressedClassPointers) {
3938       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3939     }
3940 #endif
3941   }
3942 }
3943 
3944 // Sharing support
3945 // Construct the path to the archive
3946 static char* get_shared_archive_path() {
3947   char *shared_archive_path;
3948   if (SharedArchiveFile == NULL) {
3949     char jvm_path[JVM_MAXPATHLEN];
3950     os::jvm_path(jvm_path, sizeof(jvm_path));
3951     char *end = strrchr(jvm_path, *os::file_separator());
3952     if (end != NULL) *end = '\0';
3953     size_t jvm_path_len = strlen(jvm_path);
3954     size_t file_sep_len = strlen(os::file_separator());
3955     const size_t len = jvm_path_len + file_sep_len + 20;
3956     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);
3957     if (shared_archive_path != NULL) {
3958       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3959         jvm_path, os::file_separator());
3960     }
3961   } else {
3962     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);
3963   }
3964   return shared_archive_path;
3965 }
3966 
3967 #ifndef PRODUCT
3968 // Determine whether LogVMOutput should be implicitly turned on.
3969 static bool use_vm_log() {
3970   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3971       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3972       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3973       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3974       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3975     return true;
3976   }
3977 
3978 #ifdef COMPILER1
3979   if (PrintC1Statistics) {
3980     return true;
3981   }
3982 #endif // COMPILER1
3983 
3984 #ifdef COMPILER2
3985   if (PrintOptoAssembly || PrintOptoStatistics) {
3986     return true;
3987   }
3988 #endif // COMPILER2
3989 
3990   return false;
3991 }
3992 
3993 #endif // PRODUCT
3994 
3995 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3996   for (int index = 0; index < args->nOptions; index++) {
3997     const JavaVMOption* option = args->options + index;
3998     const char* tail;
3999     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
4000       return true;
4001     }
4002   }
4003   return false;
4004 }
4005 
4006 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
4007                                        const char* vm_options_file,
4008                                        const int vm_options_file_pos,
4009                                        ScopedVMInitArgs* vm_options_file_args,
4010                                        ScopedVMInitArgs* args_out) {
4011   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
4012   if (code != JNI_OK) {
4013     return code;
4014   }
4015 
4016   if (vm_options_file_args->get()->nOptions < 1) {
4017     return JNI_OK;
4018   }
4019 
4020   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
4021     jio_fprintf(defaultStream::error_stream(),
4022                 "A VM options file may not refer to a VM options file. "
4023                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
4024                 "options file '%s' in options container '%s' is an error.\n",
4025                 vm_options_file_args->vm_options_file_arg(),
4026                 vm_options_file_args->container_name());
4027     return JNI_EINVAL;
4028   }
4029 
4030   return args_out->insert(args, vm_options_file_args->get(),
4031                           vm_options_file_pos);
4032 }
4033 
4034 // Expand -XX:VMOptionsFile found in args_in as needed.
4035 // mod_args and args_out parameters may return values as needed.
4036 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
4037                                             ScopedVMInitArgs* mod_args,
4038                                             JavaVMInitArgs** args_out) {
4039   jint code = match_special_option_and_act(args_in, mod_args);
4040   if (code != JNI_OK) {
4041     return code;
4042   }
4043 
4044   if (mod_args->is_set()) {
4045     // args_in contains -XX:VMOptionsFile and mod_args contains the
4046     // original options from args_in along with the options expanded
4047     // from the VMOptionsFile. Return a short-hand to the caller.
4048     *args_out = mod_args->get();
4049   } else {
4050     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
4051   }
4052   return JNI_OK;
4053 }
4054 
4055 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
4056                                              ScopedVMInitArgs* args_out) {
4057   // Remaining part of option string
4058   const char* tail;
4059   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
4060 
4061   for (int index = 0; index < args->nOptions; index++) {
4062     const JavaVMOption* option = args->options + index;
4063     if (ArgumentsExt::process_options(option)) {
4064       continue;
4065     }
4066     if (match_option(option, "-XX:Flags=", &tail)) {
4067       Arguments::set_jvm_flags_file(tail);
4068       continue;
4069     }
4070     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
4071       if (vm_options_file_args.found_vm_options_file_arg()) {
4072         jio_fprintf(defaultStream::error_stream(),
4073                     "The option '%s' is already specified in the options "
4074                     "container '%s' so the specification of '%s' in the "
4075                     "same options container is an error.\n",
4076                     vm_options_file_args.vm_options_file_arg(),
4077                     vm_options_file_args.container_name(),
4078                     option->optionString);
4079         return JNI_EINVAL;
4080       }
4081       vm_options_file_args.set_vm_options_file_arg(option->optionString);
4082       // If there's a VMOptionsFile, parse that
4083       jint code = insert_vm_options_file(args, tail, index,
4084                                          &vm_options_file_args, args_out);
4085       if (code != JNI_OK) {
4086         return code;
4087       }
4088       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
4089       if (args_out->is_set()) {
4090         // The VMOptions file inserted some options so switch 'args'
4091         // to the new set of options, and continue processing which
4092         // preserves "last option wins" semantics.
4093         args = args_out->get();
4094         // The first option from the VMOptionsFile replaces the
4095         // current option.  So we back track to process the
4096         // replacement option.
4097         index--;
4098       }
4099       continue;
4100     }
4101     if (match_option(option, "-XX:+PrintVMOptions")) {
4102       PrintVMOptions = true;
4103       continue;
4104     }
4105     if (match_option(option, "-XX:-PrintVMOptions")) {
4106       PrintVMOptions = false;
4107       continue;
4108     }
4109     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
4110       IgnoreUnrecognizedVMOptions = true;
4111       continue;
4112     }
4113     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
4114       IgnoreUnrecognizedVMOptions = false;
4115       continue;
4116     }
4117     if (match_option(option, "-XX:+PrintFlagsInitial")) {
4118       CommandLineFlags::printFlags(tty, false);
4119       vm_exit(0);
4120     }
4121     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
4122 #if INCLUDE_NMT
4123       // The launcher did not setup nmt environment variable properly.
4124       if (!MemTracker::check_launcher_nmt_support(tail)) {
4125         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
4126       }
4127 
4128       // Verify if nmt option is valid.
4129       if (MemTracker::verify_nmt_option()) {
4130         // Late initialization, still in single-threaded mode.
4131         if (MemTracker::tracking_level() >= NMT_summary) {
4132           MemTracker::init();
4133         }
4134       } else {
4135         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
4136       }
4137       continue;
4138 #else
4139       jio_fprintf(defaultStream::error_stream(),
4140         "Native Memory Tracking is not supported in this VM\n");
4141       return JNI_ERR;
4142 #endif
4143     }
4144 
4145 #ifndef PRODUCT
4146     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
4147       CommandLineFlags::printFlags(tty, true);
4148       vm_exit(0);
4149     }
4150 #endif
4151   }
4152   return JNI_OK;
4153 }
4154 
4155 static void print_options(const JavaVMInitArgs *args) {
4156   const char* tail;
4157   for (int index = 0; index < args->nOptions; index++) {
4158     const JavaVMOption *option = args->options + index;
4159     if (match_option(option, "-XX:", &tail)) {
4160       logOption(tail);
4161     }
4162   }
4163 }
4164 
4165 bool Arguments::handle_deprecated_print_gc_flags() {
4166   if (PrintGC) {
4167     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
4168   }
4169   if (PrintGCDetails) {
4170     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
4171   }
4172 
4173   if (_gc_log_filename != NULL) {
4174     // -Xloggc was used to specify a filename
4175     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
4176     return  LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, NULL);
4177   } else if (PrintGC || PrintGCDetails) {
4178     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
4179   }
4180   return true;
4181 }
4182 
4183 // Parse entry point called from JNI_CreateJavaVM
4184 
4185 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
4186   assert(verify_special_jvm_flags(), "deprecated and obsolete flag table inconsistent");
4187 
4188   // Initialize ranges, constraints and writeables
4189   CommandLineFlagRangeList::init();
4190   CommandLineFlagConstraintList::init();
4191   CommandLineFlagWriteableList::init();
4192 
4193   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
4194   const char* hotspotrc = ".hotspotrc";
4195   bool settings_file_specified = false;
4196   bool needs_hotspotrc_warning = false;
4197   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4198   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
4199 
4200   // Pointers to current working set of containers
4201   JavaVMInitArgs* cur_cmd_args;
4202   JavaVMInitArgs* cur_java_options_args;
4203   JavaVMInitArgs* cur_java_tool_options_args;
4204 
4205   // Containers for modified/expanded options
4206   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
4207   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4208   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
4209 
4210 
4211   jint code =
4212       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
4213   if (code != JNI_OK) {
4214     return code;
4215   }
4216 
4217   code = parse_java_options_environment_variable(&initial_java_options_args);
4218   if (code != JNI_OK) {
4219     return code;
4220   }
4221 
4222   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
4223                                      &mod_java_tool_options_args,
4224                                      &cur_java_tool_options_args);
4225   if (code != JNI_OK) {
4226     return code;
4227   }
4228 
4229   code = expand_vm_options_as_needed(initial_cmd_args,
4230                                      &mod_cmd_args,
4231                                      &cur_cmd_args);
4232   if (code != JNI_OK) {
4233     return code;
4234   }
4235 
4236   code = expand_vm_options_as_needed(initial_java_options_args.get(),
4237                                      &mod_java_options_args,
4238                                      &cur_java_options_args);
4239   if (code != JNI_OK) {
4240     return code;
4241   }
4242 
4243   const char* flags_file = Arguments::get_jvm_flags_file();
4244   settings_file_specified = (flags_file != NULL);
4245 
4246   if (IgnoreUnrecognizedVMOptions) {
4247     cur_cmd_args->ignoreUnrecognized = true;
4248     cur_java_tool_options_args->ignoreUnrecognized = true;
4249     cur_java_options_args->ignoreUnrecognized = true;
4250   }
4251 
4252   // Parse specified settings file
4253   if (settings_file_specified) {
4254     if (!process_settings_file(flags_file, true,
4255                                cur_cmd_args->ignoreUnrecognized)) {
4256       return JNI_EINVAL;
4257     }
4258   } else {
4259 #ifdef ASSERT
4260     // Parse default .hotspotrc settings file
4261     if (!process_settings_file(".hotspotrc", false,
4262                                cur_cmd_args->ignoreUnrecognized)) {
4263       return JNI_EINVAL;
4264     }
4265 #else
4266     struct stat buf;
4267     if (os::stat(hotspotrc, &buf) == 0) {
4268       needs_hotspotrc_warning = true;
4269     }
4270 #endif
4271   }
4272 
4273   if (PrintVMOptions) {
4274     print_options(cur_java_tool_options_args);
4275     print_options(cur_cmd_args);
4276     print_options(cur_java_options_args);
4277   }
4278 
4279   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
4280   jint result = parse_vm_init_args(cur_java_tool_options_args,
4281                                    cur_java_options_args,
4282                                    cur_cmd_args);
4283 
4284   if (result != JNI_OK) {
4285     return result;
4286   }
4287 
4288   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
4289   SharedArchivePath = get_shared_archive_path();
4290   if (SharedArchivePath == NULL) {
4291     return JNI_ENOMEM;
4292   }
4293 
4294   // Set up VerifySharedSpaces
4295   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
4296     VerifySharedSpaces = true;
4297   }
4298 
4299   // Delay warning until here so that we've had a chance to process
4300   // the -XX:-PrintWarnings flag
4301   if (needs_hotspotrc_warning) {
4302     warning("%s file is present but has been ignored.  "
4303             "Run with -XX:Flags=%s to load the file.",
4304             hotspotrc, hotspotrc);
4305   }
4306 
4307   if (needs_module_property_warning) {
4308     warning("Ignoring system property options whose names start with '-Djdk.module'."
4309             "  They are reserved for internal use.");
4310   }
4311 
4312 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
4313   UNSUPPORTED_OPTION(UseLargePages);
4314 #endif
4315 
4316   ArgumentsExt::report_unsupported_options();
4317 
4318 #ifndef PRODUCT
4319   if (TraceBytecodesAt != 0) {
4320     TraceBytecodes = true;
4321   }
4322   if (CountCompiledCalls) {
4323     if (UseCounterDecay) {
4324       warning("UseCounterDecay disabled because CountCalls is set");
4325       UseCounterDecay = false;
4326     }
4327   }
4328 #endif // PRODUCT
4329 
4330   if (ScavengeRootsInCode == 0) {
4331     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4332       warning("Forcing ScavengeRootsInCode non-zero");
4333     }
4334     ScavengeRootsInCode = 1;
4335   }
4336 
4337   if (!handle_deprecated_print_gc_flags()) {
4338     return JNI_EINVAL;
4339   }
4340 
4341   // Set object alignment values.
4342   set_object_alignment();
4343 
4344 #if !INCLUDE_CDS
4345   if (DumpSharedSpaces || RequireSharedSpaces) {
4346     jio_fprintf(defaultStream::error_stream(),
4347       "Shared spaces are not supported in this VM\n");
4348     return JNI_ERR;
4349   }
4350   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
4351     warning("Shared spaces are not supported in this VM");
4352     FLAG_SET_DEFAULT(UseSharedSpaces, false);
4353     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
4354   }
4355   no_shared_spaces("CDS Disabled");
4356 #endif // INCLUDE_CDS
4357 
4358   return JNI_OK;
4359 }
4360 
4361 jint Arguments::apply_ergo() {
4362 
4363   // Set flags based on ergonomics.
4364   set_ergonomics_flags();
4365 
4366   set_shared_spaces_flags();
4367 
4368   // Check the GC selections again.
4369   if (!check_gc_consistency()) {
4370     return JNI_EINVAL;
4371   }
4372 
4373   if (TieredCompilation) {
4374     set_tiered_flags();
4375   } else {
4376     int max_compilation_policy_choice = 1;
4377 #ifdef COMPILER2
4378     max_compilation_policy_choice = 2;
4379 #endif
4380     // Check if the policy is valid.
4381     if (CompilationPolicyChoice >= max_compilation_policy_choice) {
4382       vm_exit_during_initialization(
4383         "Incompatible compilation policy selected", NULL);
4384     }
4385     // Scale CompileThreshold
4386     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
4387     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
4388       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
4389     }
4390   }
4391 
4392 #ifdef COMPILER2
4393 #ifndef PRODUCT
4394   if (PrintIdealGraphLevel > 0) {
4395     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
4396   }
4397 #endif
4398 #endif
4399 
4400   // Set heap size based on available physical memory
4401   set_heap_size();
4402 
4403   ArgumentsExt::set_gc_specific_flags();
4404 
4405   // Initialize Metaspace flags and alignments
4406   Metaspace::ergo_initialize();
4407 
4408   // Set bytecode rewriting flags
4409   set_bytecode_flags();
4410 
4411   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
4412   jint code = set_aggressive_opts_flags();
4413   if (code != JNI_OK) {
4414     return code;
4415   }
4416 
4417   // Turn off biased locking for locking debug mode flags,
4418   // which are subtly different from each other but neither works with
4419   // biased locking
4420   if (UseHeavyMonitors
4421 #ifdef COMPILER1
4422       || !UseFastLocking
4423 #endif // COMPILER1
4424 #if INCLUDE_JVMCI
4425       || !JVMCIUseFastLocking
4426 #endif
4427     ) {
4428     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4429       // flag set to true on command line; warn the user that they
4430       // can't enable biased locking here
4431       warning("Biased Locking is not supported with locking debug flags"
4432               "; ignoring UseBiasedLocking flag." );
4433     }
4434     UseBiasedLocking = false;
4435   }
4436 
4437 #ifdef CC_INTERP
4438   // Clear flags not supported on zero.
4439   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4440   FLAG_SET_DEFAULT(UseBiasedLocking, false);
4441   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4442   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4443 #endif // CC_INTERP
4444 
4445 #ifdef COMPILER2
4446   if (!EliminateLocks) {
4447     EliminateNestedLocks = false;
4448   }
4449   if (!Inline) {
4450     IncrementalInline = false;
4451   }
4452 #ifndef PRODUCT
4453   if (!IncrementalInline) {
4454     AlwaysIncrementalInline = false;
4455   }
4456 #endif
4457   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
4458     // nothing to use the profiling, turn if off
4459     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
4460   }
4461 #endif
4462 
4463   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4464     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4465     DebugNonSafepoints = true;
4466   }
4467 
4468   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4469     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4470   }
4471 
4472   if (UseOnStackReplacement && !UseLoopCounter) {
4473     warning("On-stack-replacement requires loop counters; enabling loop counters");
4474     FLAG_SET_DEFAULT(UseLoopCounter, true);
4475   }
4476 
4477 #ifndef PRODUCT
4478   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4479     if (use_vm_log()) {
4480       LogVMOutput = true;
4481     }
4482   }
4483 #endif // PRODUCT
4484 
4485   if (PrintCommandLineFlags) {
4486     CommandLineFlags::printSetFlags(tty);
4487   }
4488 
4489   // Apply CPU specific policy for the BiasedLocking
4490   if (UseBiasedLocking) {
4491     if (!VM_Version::use_biased_locking() &&
4492         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4493       UseBiasedLocking = false;
4494     }
4495   }
4496 #ifdef COMPILER2
4497   if (!UseBiasedLocking || EmitSync != 0) {
4498     UseOptoBiasInlining = false;
4499   }
4500 #endif
4501 
4502   return JNI_OK;
4503 }
4504 
4505 jint Arguments::adjust_after_os() {
4506   if (UseNUMA) {
4507     if (UseParallelGC || UseParallelOldGC) {
4508       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4509          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4510       }
4511     }
4512     // UseNUMAInterleaving is set to ON for all collectors and
4513     // platforms when UseNUMA is set to ON. NUMA-aware collectors
4514     // such as the parallel collector for Linux and Solaris will
4515     // interleave old gen and survivor spaces on top of NUMA
4516     // allocation policy for the eden space.
4517     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4518     // all platforms and ParallelGC on Windows will interleave all
4519     // of the heap spaces across NUMA nodes.
4520     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4521       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4522     }
4523   }
4524   return JNI_OK;
4525 }
4526 
4527 int Arguments::PropertyList_count(SystemProperty* pl) {
4528   int count = 0;
4529   while(pl != NULL) {
4530     count++;
4531     pl = pl->next();
4532   }
4533   return count;
4534 }
4535 
4536 // Return the number of readable properties.
4537 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
4538   int count = 0;
4539   while(pl != NULL) {
4540     if (pl->is_readable()) {
4541       count++;
4542     }
4543     pl = pl->next();
4544   }
4545   return count;
4546 }
4547 
4548 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4549   assert(key != NULL, "just checking");
4550   SystemProperty* prop;
4551   for (prop = pl; prop != NULL; prop = prop->next()) {
4552     if (strcmp(key, prop->key()) == 0) return prop->value();
4553   }
4554   return NULL;
4555 }
4556 
4557 // Return the value of the requested property provided that it is a readable property.
4558 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4559   assert(key != NULL, "just checking");
4560   SystemProperty* prop;
4561   // Return the property value if the keys match and the property is not internal or
4562   // it's the special internal property "jdk.boot.class.path.append".
4563   for (prop = pl; prop != NULL; prop = prop->next()) {
4564     if (strcmp(key, prop->key()) == 0) {
4565       if (!prop->internal()) {
4566         return prop->value();
4567       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4568         return prop->value();
4569       } else {
4570         // Property is internal and not jdk.boot.class.path.append so return NULL.
4571         return NULL;
4572       }
4573     }
4574   }
4575   return NULL;
4576 }
4577 
4578 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4579   int count = 0;
4580   const char* ret_val = NULL;
4581 
4582   while(pl != NULL) {
4583     if(count >= index) {
4584       ret_val = pl->key();
4585       break;
4586     }
4587     count++;
4588     pl = pl->next();
4589   }
4590 
4591   return ret_val;
4592 }
4593 
4594 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4595   int count = 0;
4596   char* ret_val = NULL;
4597 
4598   while(pl != NULL) {
4599     if(count >= index) {
4600       ret_val = pl->value();
4601       break;
4602     }
4603     count++;
4604     pl = pl->next();
4605   }
4606 
4607   return ret_val;
4608 }
4609 
4610 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4611   SystemProperty* p = *plist;
4612   if (p == NULL) {
4613     *plist = new_p;
4614   } else {
4615     while (p->next() != NULL) {
4616       p = p->next();
4617     }
4618     p->set_next(new_p);
4619   }
4620 }
4621 
4622 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4623                                  bool writeable, bool internal) {
4624   if (plist == NULL)
4625     return;
4626 
4627   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4628   PropertyList_add(plist, new_p);
4629 }
4630 
4631 void Arguments::PropertyList_add(SystemProperty *element) {
4632   PropertyList_add(&_system_properties, element);
4633 }
4634 
4635 // This add maintains unique property key in the list.
4636 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4637                                         PropertyAppendable append, PropertyWriteable writeable,
4638                                         PropertyInternal internal) {
4639   if (plist == NULL)
4640     return;
4641 
4642   // If property key exist then update with new value.
4643   SystemProperty* prop;
4644   for (prop = *plist; prop != NULL; prop = prop->next()) {
4645     if (strcmp(k, prop->key()) == 0) {
4646       if (append == AppendProperty) {
4647         prop->append_value(v);
4648       } else {
4649         prop->set_value(v);
4650       }
4651       return;
4652     }
4653   }
4654 
4655   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4656 }
4657 
4658 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4659 // Returns true if all of the source pointed by src has been copied over to
4660 // the destination buffer pointed by buf. Otherwise, returns false.
4661 // Notes:
4662 // 1. If the length (buflen) of the destination buffer excluding the
4663 // NULL terminator character is not long enough for holding the expanded
4664 // pid characters, it also returns false instead of returning the partially
4665 // expanded one.
4666 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4667 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4668                                 char* buf, size_t buflen) {
4669   const char* p = src;
4670   char* b = buf;
4671   const char* src_end = &src[srclen];
4672   char* buf_end = &buf[buflen - 1];
4673 
4674   while (p < src_end && b < buf_end) {
4675     if (*p == '%') {
4676       switch (*(++p)) {
4677       case '%':         // "%%" ==> "%"
4678         *b++ = *p++;
4679         break;
4680       case 'p':  {       //  "%p" ==> current process id
4681         // buf_end points to the character before the last character so
4682         // that we could write '\0' to the end of the buffer.
4683         size_t buf_sz = buf_end - b + 1;
4684         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4685 
4686         // if jio_snprintf fails or the buffer is not long enough to hold
4687         // the expanded pid, returns false.
4688         if (ret < 0 || ret >= (int)buf_sz) {
4689           return false;
4690         } else {
4691           b += ret;
4692           assert(*b == '\0', "fail in copy_expand_pid");
4693           if (p == src_end && b == buf_end + 1) {
4694             // reach the end of the buffer.
4695             return true;
4696           }
4697         }
4698         p++;
4699         break;
4700       }
4701       default :
4702         *b++ = '%';
4703       }
4704     } else {
4705       *b++ = *p++;
4706     }
4707   }
4708   *b = '\0';
4709   return (p == src_end); // return false if not all of the source was copied
4710 }