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