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