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