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