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