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