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