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