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