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