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