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