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