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