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