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