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