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