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