1 /*
   2  * Copyright (c) 1997, 2023, 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 "cds/cds_globals.hpp"
  27 #include "cds/filemap.hpp"
  28 #include "classfile/classLoader.hpp"
  29 #include "classfile/javaAssertions.hpp"
  30 #include "classfile/moduleEntry.hpp"
  31 #include "classfile/stringTable.hpp"
  32 #include "classfile/symbolTable.hpp"
  33 #include "compiler/compilerDefinitions.hpp"
  34 #include "gc/shared/gcArguments.hpp"
  35 #include "gc/shared/gcConfig.hpp"
  36 #include "gc/shared/stringdedup/stringDedup.hpp"
  37 #include "gc/shared/tlab_globals.hpp"
  38 #include "jvm.h"
  39 #include "logging/log.hpp"
  40 #include "logging/logConfiguration.hpp"
  41 #include "logging/logStream.hpp"
  42 #include "logging/logTag.hpp"
  43 #include "memory/allocation.inline.hpp"
  44 #include "oops/instanceKlass.hpp"
  45 #include "oops/oop.inline.hpp"
  46 #include "prims/jvmtiAgentList.hpp"
  47 #include "prims/jvmtiExport.hpp"
  48 #include "runtime/arguments.hpp"
  49 #include "runtime/flags/jvmFlag.hpp"
  50 #include "runtime/flags/jvmFlagAccess.hpp"
  51 #include "runtime/flags/jvmFlagLimit.hpp"
  52 #include "runtime/globals_extension.hpp"
  53 #include "runtime/java.hpp"
  54 #include "runtime/os.hpp"
  55 #include "runtime/safepoint.hpp"
  56 #include "runtime/safepointMechanism.hpp"
  57 #include "runtime/synchronizer.hpp"
  58 #include "runtime/vm_version.hpp"
  59 #include "services/management.hpp"
  60 #include "services/nmtCommon.hpp"
  61 #include "utilities/align.hpp"
  62 #include "utilities/debug.hpp"
  63 #include "utilities/defaultStream.hpp"
  64 #include "utilities/macros.hpp"
  65 #include "utilities/parseInteger.hpp"
  66 #include "utilities/powerOfTwo.hpp"
  67 #include "utilities/stringUtils.hpp"
  68 #include "utilities/systemMemoryBarrier.hpp"
  69 #if INCLUDE_JFR
  70 #include "jfr/jfr.hpp"
  71 #endif
  72 
  73 #include <limits>
  74 
  75 static const char _default_java_launcher[] = "generic";
  76 
  77 #define DEFAULT_JAVA_LAUNCHER _default_java_launcher
  78 
  79 char*  Arguments::_jvm_flags_file               = nullptr;
  80 char** Arguments::_jvm_flags_array              = nullptr;
  81 int    Arguments::_num_jvm_flags                = 0;
  82 char** Arguments::_jvm_args_array               = nullptr;
  83 int    Arguments::_num_jvm_args                 = 0;
  84 char*  Arguments::_java_command                 = nullptr;
  85 SystemProperty* Arguments::_system_properties   = nullptr;
  86 size_t Arguments::_conservative_max_heap_alignment = 0;
  87 Arguments::Mode Arguments::_mode                = _mixed;
  88 bool   Arguments::_xdebug_mode                  = false;
  89 const char*  Arguments::_java_vendor_url_bug    = nullptr;
  90 const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
  91 bool   Arguments::_sun_java_launcher_is_altjvm  = false;
  92 
  93 // These parameters are reset in method parse_vm_init_args()
  94 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
  95 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
  96 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
  97 bool   Arguments::_ClipInlining                 = ClipInlining;
  98 size_t Arguments::_default_SharedBaseAddress    = SharedBaseAddress;
  99 
 100 bool   Arguments::_enable_preview               = false;
 101 
 102 char*  Arguments::_default_shared_archive_path  = nullptr;
 103 char*  Arguments::SharedArchivePath             = nullptr;
 104 char*  Arguments::SharedDynamicArchivePath      = nullptr;
 105 
 106 LegacyGCLogging Arguments::_legacyGCLogging     = { 0, 0 };
 107 
 108 // These are not set by the JDK's built-in launchers, but they can be set by
 109 // programs that embed the JVM using JNI_CreateJavaVM. See comments around
 110 // JavaVMOption in jni.h.
 111 abort_hook_t     Arguments::_abort_hook         = nullptr;
 112 exit_hook_t      Arguments::_exit_hook          = nullptr;
 113 vfprintf_hook_t  Arguments::_vfprintf_hook      = nullptr;
 114 
 115 
 116 SystemProperty *Arguments::_sun_boot_library_path = nullptr;
 117 SystemProperty *Arguments::_java_library_path = nullptr;
 118 SystemProperty *Arguments::_java_home = nullptr;
 119 SystemProperty *Arguments::_java_class_path = nullptr;
 120 SystemProperty *Arguments::_jdk_boot_class_path_append = nullptr;
 121 SystemProperty *Arguments::_vm_info = nullptr;
 122 
 123 GrowableArray<ModulePatchPath*> *Arguments::_patch_mod_prefix = nullptr;
 124 PathString *Arguments::_boot_class_path = nullptr;
 125 bool Arguments::_has_jimage = false;
 126 
 127 char* Arguments::_ext_dirs = nullptr;
 128 
 129 // True if -Xshare:auto option was specified.
 130 static bool xshare_auto_cmd_line = false;
 131 
 132 bool PathString::set_value(const char *value, AllocFailType alloc_failmode) {
 133   char* new_value = AllocateHeap(strlen(value)+1, mtArguments, alloc_failmode);
 134   if (new_value == nullptr) {
 135     assert(alloc_failmode == AllocFailStrategy::RETURN_NULL, "must be");
 136     return false;
 137   }
 138   if (_value != nullptr) {
 139     FreeHeap(_value);
 140   }
 141   _value = new_value;
 142   strcpy(_value, value);
 143   return true;
 144 }
 145 
 146 void PathString::append_value(const char *value) {
 147   char *sp;
 148   size_t len = 0;
 149   if (value != nullptr) {
 150     len = strlen(value);
 151     if (_value != nullptr) {
 152       len += strlen(_value);
 153     }
 154     sp = AllocateHeap(len+2, mtArguments);
 155     assert(sp != nullptr, "Unable to allocate space for new append path value");
 156     if (sp != nullptr) {
 157       if (_value != nullptr) {
 158         strcpy(sp, _value);
 159         strcat(sp, os::path_separator());
 160         strcat(sp, value);
 161         FreeHeap(_value);
 162       } else {
 163         strcpy(sp, value);
 164       }
 165       _value = sp;
 166     }
 167   }
 168 }
 169 
 170 PathString::PathString(const char* value) {
 171   if (value == nullptr) {
 172     _value = nullptr;
 173   } else {
 174     _value = AllocateHeap(strlen(value)+1, mtArguments);
 175     strcpy(_value, value);
 176   }
 177 }
 178 
 179 PathString::~PathString() {
 180   if (_value != nullptr) {
 181     FreeHeap(_value);
 182     _value = nullptr;
 183   }
 184 }
 185 
 186 ModulePatchPath::ModulePatchPath(const char* module_name, const char* path) {
 187   assert(module_name != nullptr && path != nullptr, "Invalid module name or path value");
 188   size_t len = strlen(module_name) + 1;
 189   _module_name = AllocateHeap(len, mtInternal);
 190   strncpy(_module_name, module_name, len); // copy the trailing null
 191   _path =  new PathString(path);
 192 }
 193 
 194 ModulePatchPath::~ModulePatchPath() {
 195   if (_module_name != nullptr) {
 196     FreeHeap(_module_name);
 197     _module_name = nullptr;
 198   }
 199   if (_path != nullptr) {
 200     delete _path;
 201     _path = nullptr;
 202   }
 203 }
 204 
 205 SystemProperty::SystemProperty(const char* key, const char* value, bool writeable, bool internal) : PathString(value) {
 206   if (key == nullptr) {
 207     _key = nullptr;
 208   } else {
 209     _key = AllocateHeap(strlen(key)+1, mtArguments);
 210     strcpy(_key, key);
 211   }
 212   _next = nullptr;
 213   _internal = internal;
 214   _writeable = writeable;
 215 }
 216 
 217 // Check if head of 'option' matches 'name', and sets 'tail' to the remaining
 218 // part of the option string.
 219 static bool match_option(const JavaVMOption *option, const char* name,
 220                          const char** tail) {
 221   size_t len = strlen(name);
 222   if (strncmp(option->optionString, name, len) == 0) {
 223     *tail = option->optionString + len;
 224     return true;
 225   } else {
 226     return false;
 227   }
 228 }
 229 
 230 // Check if 'option' matches 'name'. No "tail" is allowed.
 231 static bool match_option(const JavaVMOption *option, const char* name) {
 232   const char* tail = nullptr;
 233   bool result = match_option(option, name, &tail);
 234   if (tail != nullptr && *tail == '\0') {
 235     return result;
 236   } else {
 237     return false;
 238   }
 239 }
 240 
 241 // Return true if any of the strings in null-terminated array 'names' matches.
 242 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
 243 // the option must match exactly.
 244 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
 245   bool tail_allowed) {
 246   for (/* empty */; *names != nullptr; ++names) {
 247   if (match_option(option, *names, tail)) {
 248       if (**tail == '\0' || (tail_allowed && **tail == ':')) {
 249         return true;
 250       }
 251     }
 252   }
 253   return false;
 254 }
 255 
 256 #if INCLUDE_JFR
 257 static bool _has_jfr_option = false;  // is using JFR
 258 
 259 // return true on failure
 260 static bool match_jfr_option(const JavaVMOption** option) {
 261   assert((*option)->optionString != nullptr, "invariant");
 262   char* tail = nullptr;
 263   if (match_option(*option, "-XX:StartFlightRecording", (const char**)&tail)) {
 264     _has_jfr_option = true;
 265     return Jfr::on_start_flight_recording_option(option, tail);
 266   } else if (match_option(*option, "-XX:FlightRecorderOptions", (const char**)&tail)) {
 267     _has_jfr_option = true;
 268     return Jfr::on_flight_recorder_option(option, tail);
 269   }
 270   return false;
 271 }
 272 
 273 bool Arguments::has_jfr_option() {
 274   return _has_jfr_option;
 275 }
 276 #endif
 277 
 278 static void logOption(const char* opt) {
 279   if (PrintVMOptions) {
 280     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
 281   }
 282 }
 283 
 284 bool needs_module_property_warning = false;
 285 
 286 #define MODULE_PROPERTY_PREFIX "jdk.module."
 287 #define MODULE_PROPERTY_PREFIX_LEN 11
 288 #define ADDEXPORTS "addexports"
 289 #define ADDEXPORTS_LEN 10
 290 #define ADDREADS "addreads"
 291 #define ADDREADS_LEN 8
 292 #define ADDOPENS "addopens"
 293 #define ADDOPENS_LEN 8
 294 #define PATCH "patch"
 295 #define PATCH_LEN 5
 296 #define ADDMODS "addmods"
 297 #define ADDMODS_LEN 7
 298 #define LIMITMODS "limitmods"
 299 #define LIMITMODS_LEN 9
 300 #define PATH "path"
 301 #define PATH_LEN 4
 302 #define UPGRADE_PATH "upgrade.path"
 303 #define UPGRADE_PATH_LEN 12
 304 #define ENABLE_NATIVE_ACCESS "enable.native.access"
 305 #define ENABLE_NATIVE_ACCESS_LEN 20
 306 
 307 // Return TRUE if option matches 'property', or 'property=', or 'property.'.
 308 static bool matches_property_suffix(const char* option, const char* property, size_t len) {
 309   return ((strncmp(option, property, len) == 0) &&
 310           (option[len] == '=' || option[len] == '.' || option[len] == '\0'));
 311 }
 312 
 313 // Return true if property starts with "jdk.module." and its ensuing chars match
 314 // any of the reserved module properties.
 315 // property should be passed without the leading "-D".
 316 bool Arguments::is_internal_module_property(const char* property) {
 317   assert((strncmp(property, "-D", 2) != 0), "Unexpected leading -D");
 318   if  (strncmp(property, MODULE_PROPERTY_PREFIX, MODULE_PROPERTY_PREFIX_LEN) == 0) {
 319     const char* property_suffix = property + MODULE_PROPERTY_PREFIX_LEN;
 320     if (matches_property_suffix(property_suffix, ADDEXPORTS, ADDEXPORTS_LEN) ||
 321         matches_property_suffix(property_suffix, ADDREADS, ADDREADS_LEN) ||
 322         matches_property_suffix(property_suffix, ADDOPENS, ADDOPENS_LEN) ||
 323         matches_property_suffix(property_suffix, PATCH, PATCH_LEN) ||
 324         matches_property_suffix(property_suffix, ADDMODS, ADDMODS_LEN) ||
 325         matches_property_suffix(property_suffix, LIMITMODS, LIMITMODS_LEN) ||
 326         matches_property_suffix(property_suffix, PATH, PATH_LEN) ||
 327         matches_property_suffix(property_suffix, UPGRADE_PATH, UPGRADE_PATH_LEN) ||
 328         matches_property_suffix(property_suffix, ENABLE_NATIVE_ACCESS, ENABLE_NATIVE_ACCESS_LEN)) {
 329       return true;
 330     }
 331   }
 332   return false;
 333 }
 334 
 335 // Process java launcher properties.
 336 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
 337   // See if sun.java.launcher or sun.java.launcher.is_altjvm is defined.
 338   // Must do this before setting up other system properties,
 339   // as some of them may depend on launcher type.
 340   for (int index = 0; index < args->nOptions; index++) {
 341     const JavaVMOption* option = args->options + index;
 342     const char* tail;
 343 
 344     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
 345       process_java_launcher_argument(tail, option->extraInfo);
 346       continue;
 347     }
 348     if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
 349       if (strcmp(tail, "true") == 0) {
 350         _sun_java_launcher_is_altjvm = true;
 351       }
 352       continue;
 353     }
 354   }
 355 }
 356 
 357 // Initialize system properties key and value.
 358 void Arguments::init_system_properties() {
 359 
 360   // Set up _boot_class_path which is not a property but
 361   // relies heavily on argument processing and the jdk.boot.class.path.append
 362   // property. It is used to store the underlying boot class path.
 363   _boot_class_path = new PathString(nullptr);
 364 
 365   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
 366                                                            "Java Virtual Machine Specification",  false));
 367   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
 368   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
 369   PropertyList_add(&_system_properties, new SystemProperty("jdk.debug", VM_Version::jdk_debug_level(),  false));
 370 
 371   // Initialize the vm.info now, but it will need updating after argument parsing.
 372   _vm_info = new SystemProperty("java.vm.info", VM_Version::vm_info_string(), true);
 373 
 374   // Following are JVMTI agent writable properties.
 375   // Properties values are set to nullptr and they are
 376   // os specific they are initialized in os::init_system_properties_values().
 377   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", nullptr,  true);
 378   _java_library_path = new SystemProperty("java.library.path", nullptr,  true);
 379   _java_home =  new SystemProperty("java.home", nullptr,  true);
 380   _java_class_path = new SystemProperty("java.class.path", "",  true);
 381   // jdk.boot.class.path.append is a non-writeable, internal property.
 382   // It can only be set by either:
 383   //    - -Xbootclasspath/a:
 384   //    - AddToBootstrapClassLoaderSearch during JVMTI OnLoad phase
 385   _jdk_boot_class_path_append = new SystemProperty("jdk.boot.class.path.append", nullptr, false, true);
 386 
 387   // Add to System Property list.
 388   PropertyList_add(&_system_properties, _sun_boot_library_path);
 389   PropertyList_add(&_system_properties, _java_library_path);
 390   PropertyList_add(&_system_properties, _java_home);
 391   PropertyList_add(&_system_properties, _java_class_path);
 392   PropertyList_add(&_system_properties, _jdk_boot_class_path_append);
 393   PropertyList_add(&_system_properties, _vm_info);
 394 
 395   // Set OS specific system properties values
 396   os::init_system_properties_values();
 397 }
 398 
 399 // Update/Initialize System properties after JDK version number is known
 400 void Arguments::init_version_specific_system_properties() {
 401   enum { bufsz = 16 };
 402   char buffer[bufsz];
 403   const char* spec_vendor = "Oracle Corporation";
 404   uint32_t spec_version = JDK_Version::current().major_version();
 405 
 406   jio_snprintf(buffer, bufsz, UINT32_FORMAT, spec_version);
 407 
 408   PropertyList_add(&_system_properties,
 409       new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
 410   PropertyList_add(&_system_properties,
 411       new SystemProperty("java.vm.specification.version", buffer, false));
 412   PropertyList_add(&_system_properties,
 413       new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
 414 }
 415 
 416 /*
 417  *  -XX argument processing:
 418  *
 419  *  -XX arguments are defined in several places, such as:
 420  *      globals.hpp, globals_<cpu>.hpp, globals_<os>.hpp, <compiler>_globals.hpp, or <gc>_globals.hpp.
 421  *  -XX arguments are parsed in parse_argument().
 422  *  -XX argument bounds checking is done in check_vm_args_consistency().
 423  *
 424  * Over time -XX arguments may change. There are mechanisms to handle common cases:
 425  *
 426  *      ALIASED: An option that is simply another name for another option. This is often
 427  *               part of the process of deprecating a flag, but not all aliases need
 428  *               to be deprecated.
 429  *
 430  *               Create an alias for an option by adding the old and new option names to the
 431  *               "aliased_jvm_flags" table. Delete the old variable from globals.hpp (etc).
 432  *
 433  *   DEPRECATED: An option that is supported, but a warning is printed to let the user know that
 434  *               support may be removed in the future. Both regular and aliased options may be
 435  *               deprecated.
 436  *
 437  *               Add a deprecation warning for an option (or alias) by adding an entry in the
 438  *               "special_jvm_flags" table and setting the "deprecated_in" field.
 439  *               Often an option "deprecated" in one major release will
 440  *               be made "obsolete" in the next. In this case the entry should also have its
 441  *               "obsolete_in" field set.
 442  *
 443  *     OBSOLETE: An option that has been removed (and deleted from globals.hpp), but is still accepted
 444  *               on the command line. A warning is printed to let the user know that option might not
 445  *               be accepted in the future.
 446  *
 447  *               Add an obsolete warning for an option by adding an entry in the "special_jvm_flags"
 448  *               table and setting the "obsolete_in" field.
 449  *
 450  *      EXPIRED: A deprecated or obsolete option that has an "accept_until" version less than or equal
 451  *               to the current JDK version. The system will flatly refuse to admit the existence of
 452  *               the flag. This allows a flag to die automatically over JDK releases.
 453  *
 454  *               Note that manual cleanup of expired options should be done at major JDK version upgrades:
 455  *                  - Newly expired options should be removed from the special_jvm_flags and aliased_jvm_flags tables.
 456  *                  - Newly obsolete or expired deprecated options should have their global variable
 457  *                    definitions removed (from globals.hpp, etc) and related implementations removed.
 458  *
 459  * Recommended approach for removing options:
 460  *
 461  * To remove options commonly used by customers (e.g. product -XX options), use
 462  * the 3-step model adding major release numbers to the deprecate, obsolete and expire columns.
 463  *
 464  * To remove internal options (e.g. diagnostic, experimental, develop options), use
 465  * a 2-step model adding major release numbers to the obsolete and expire columns.
 466  *
 467  * To change the name of an option, use the alias table as well as a 2-step
 468  * model adding major release numbers to the deprecate and expire columns.
 469  * Think twice about aliasing commonly used customer options.
 470  *
 471  * There are times when it is appropriate to leave a future release number as undefined.
 472  *
 473  * Tests:  Aliases should be tested in VMAliasOptions.java.
 474  *         Deprecated options should be tested in VMDeprecatedOptions.java.
 475  */
 476 
 477 // The special_jvm_flags table declares options that are being deprecated and/or obsoleted. The
 478 // "deprecated_in" or "obsolete_in" fields may be set to "undefined", but not both.
 479 // When the JDK version reaches 'deprecated_in' limit, the JVM will process this flag on
 480 // the command-line as usual, but will issue a warning.
 481 // When the JDK version reaches 'obsolete_in' limit, the JVM will continue accepting this flag on
 482 // the command-line, while issuing a warning and ignoring the flag value.
 483 // Once the JDK version reaches 'expired_in' limit, the JVM will flatly refuse to admit the
 484 // existence of the flag.
 485 //
 486 // MANUAL CLEANUP ON JDK VERSION UPDATES:
 487 // This table ensures that the handling of options will update automatically when the JDK
 488 // version is incremented, but the source code needs to be cleanup up manually:
 489 // - As "deprecated" options age into "obsolete" or "expired" options, the associated "globals"
 490 //   variable should be removed, as well as users of the variable.
 491 // - As "deprecated" options age into "obsolete" options, move the entry into the
 492 //   "Obsolete Flags" section of the table.
 493 // - All expired options should be removed from the table.
 494 static SpecialFlag const special_jvm_flags[] = {
 495   // -------------- Deprecated Flags --------------
 496   // --- Non-alias flags - sorted by obsolete_in then expired_in:
 497   { "MaxGCMinorPauseMillis",        JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
 498   { "MaxRAMFraction",               JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 499   { "MinRAMFraction",               JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 500   { "InitialRAMFraction",           JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 501   { "AllowRedefinitionToAddDeleteMethods", JDK_Version::jdk(13), JDK_Version::undefined(), JDK_Version::undefined() },
 502   { "FlightRecorder",               JDK_Version::jdk(13), JDK_Version::undefined(), JDK_Version::undefined() },
 503   { "DumpSharedSpaces",             JDK_Version::jdk(18), JDK_Version::jdk(19), JDK_Version::undefined() },
 504   { "DynamicDumpSharedSpaces",      JDK_Version::jdk(18), JDK_Version::jdk(19), JDK_Version::undefined() },
 505   { "RequireSharedSpaces",          JDK_Version::jdk(18), JDK_Version::jdk(19), JDK_Version::undefined() },
 506   { "UseSharedSpaces",              JDK_Version::jdk(18), JDK_Version::jdk(19), JDK_Version::undefined() },
 507 
 508   // --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in:
 509   { "DefaultMaxRAMFraction",        JDK_Version::jdk(8),  JDK_Version::undefined(), JDK_Version::undefined() },
 510   { "CreateMinidumpOnCrash",        JDK_Version::jdk(9),  JDK_Version::undefined(), JDK_Version::undefined() },
 511   { "TLABStats",                    JDK_Version::jdk(12), JDK_Version::undefined(), JDK_Version::undefined() },
 512 
 513   // -------------- Obsolete Flags - sorted by expired_in --------------
 514 
 515   { "EnableWaitForParallelLoad",    JDK_Version::jdk(20), JDK_Version::jdk(21), JDK_Version::jdk(22) },
 516   { "G1ConcRefinementGreenZone",    JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::undefined() },
 517   { "G1ConcRefinementYellowZone",   JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::undefined() },
 518   { "G1ConcRefinementRedZone",      JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::undefined() },
 519   { "G1ConcRefinementThresholdStep", JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::undefined() },
 520   { "G1UseAdaptiveConcRefinement",  JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::undefined() },
 521   { "G1ConcRefinementServiceIntervalMillis", JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::undefined() },
 522 
 523   { "G1UsePreventiveGC",            JDK_Version::undefined(), JDK_Version::jdk(21), JDK_Version::jdk(22) },
 524   { "G1ConcRSLogCacheSize",         JDK_Version::undefined(), JDK_Version::jdk(21), JDK_Version::undefined() },
 525   { "G1ConcRSHotCardLimit",         JDK_Version::undefined(), JDK_Version::jdk(21), JDK_Version::undefined() },
 526   { "RefDiscoveryPolicy",           JDK_Version::undefined(), JDK_Version::jdk(21), JDK_Version::undefined() },
 527   { "MetaspaceReclaimPolicy",       JDK_Version::undefined(), JDK_Version::jdk(21), JDK_Version::undefined() },
 528 
 529 #ifdef ASSERT
 530   { "DummyObsoleteTestFlag",        JDK_Version::undefined(), JDK_Version::jdk(18), JDK_Version::undefined() },
 531 #endif
 532 
 533 #ifdef TEST_VERIFY_SPECIAL_JVM_FLAGS
 534   // These entries will generate build errors.  Their purpose is to test the macros.
 535   { "dep > obs",                    JDK_Version::jdk(9), JDK_Version::jdk(8), JDK_Version::undefined() },
 536   { "dep > exp ",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(8) },
 537   { "obs > exp ",                   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(8) },
 538   { "obs > exp",                    JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::jdk(10) },
 539   { "not deprecated or obsolete",   JDK_Version::undefined(), JDK_Version::undefined(), JDK_Version::jdk(9) },
 540   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 541   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 542 #endif
 543 
 544   { nullptr, JDK_Version(0), JDK_Version(0) }
 545 };
 546 
 547 // Flags that are aliases for other flags.
 548 typedef struct {
 549   const char* alias_name;
 550   const char* real_name;
 551 } AliasedFlag;
 552 
 553 static AliasedFlag const aliased_jvm_flags[] = {
 554   { "DefaultMaxRAMFraction",    "MaxRAMFraction"    },
 555   { "CreateMinidumpOnCrash",    "CreateCoredumpOnCrash" },
 556   { nullptr, nullptr}
 557 };
 558 
 559 // Return true if "v" is less than "other", where "other" may be "undefined".
 560 static bool version_less_than(JDK_Version v, JDK_Version other) {
 561   assert(!v.is_undefined(), "must be defined");
 562   if (!other.is_undefined() && v.compare(other) >= 0) {
 563     return false;
 564   } else {
 565     return true;
 566   }
 567 }
 568 
 569 static bool lookup_special_flag(const char *flag_name, SpecialFlag& flag) {
 570   for (size_t i = 0; special_jvm_flags[i].name != nullptr; i++) {
 571     if ((strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 572       flag = special_jvm_flags[i];
 573       return true;
 574     }
 575   }
 576   return false;
 577 }
 578 
 579 bool Arguments::is_obsolete_flag(const char *flag_name, JDK_Version* version) {
 580   assert(version != nullptr, "Must provide a version buffer");
 581   SpecialFlag flag;
 582   if (lookup_special_flag(flag_name, flag)) {
 583     if (!flag.obsolete_in.is_undefined()) {
 584       if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 585         *version = flag.obsolete_in;
 586         // This flag may have been marked for obsoletion in this version, but we may not
 587         // have actually removed it yet. Rather than ignoring it as soon as we reach
 588         // this version we allow some time for the removal to happen. So if the flag
 589         // still actually exists we process it as normal, but issue an adjusted warning.
 590         const JVMFlag *real_flag = JVMFlag::find_declared_flag(flag_name);
 591         if (real_flag != nullptr) {
 592           char version_str[256];
 593           version->to_string(version_str, sizeof(version_str));
 594           warning("Temporarily processing option %s; support is scheduled for removal in %s",
 595                   flag_name, version_str);
 596           return false;
 597         }
 598         return true;
 599       }
 600     }
 601   }
 602   return false;
 603 }
 604 
 605 int Arguments::is_deprecated_flag(const char *flag_name, JDK_Version* version) {
 606   assert(version != nullptr, "Must provide a version buffer");
 607   SpecialFlag flag;
 608   if (lookup_special_flag(flag_name, flag)) {
 609     if (!flag.deprecated_in.is_undefined()) {
 610       if (version_less_than(JDK_Version::current(), flag.obsolete_in) &&
 611           version_less_than(JDK_Version::current(), flag.expired_in)) {
 612         *version = flag.deprecated_in;
 613         return 1;
 614       } else {
 615         return -1;
 616       }
 617     }
 618   }
 619   return 0;
 620 }
 621 
 622 const char* Arguments::real_flag_name(const char *flag_name) {
 623   for (size_t i = 0; aliased_jvm_flags[i].alias_name != nullptr; i++) {
 624     const AliasedFlag& flag_status = aliased_jvm_flags[i];
 625     if (strcmp(flag_status.alias_name, flag_name) == 0) {
 626         return flag_status.real_name;
 627     }
 628   }
 629   return flag_name;
 630 }
 631 
 632 #ifdef ASSERT
 633 static bool lookup_special_flag(const char *flag_name, size_t skip_index) {
 634   for (size_t i = 0; special_jvm_flags[i].name != nullptr; i++) {
 635     if ((i != skip_index) && (strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 636       return true;
 637     }
 638   }
 639   return false;
 640 }
 641 
 642 // Verifies the correctness of the entries in the special_jvm_flags table.
 643 // If there is a semantic error (i.e. a bug in the table) such as the obsoletion
 644 // version being earlier than the deprecation version, then a warning is issued
 645 // and verification fails - by returning false. If it is detected that the table
 646 // is out of date, with respect to the current version, then ideally a warning is
 647 // issued but verification does not fail. This allows the VM to operate when the
 648 // version is first updated, without needing to update all the impacted flags at
 649 // the same time. In practice we can't issue the warning immediately when the version
 650 // is updated as it occurs for every test and some tests are not prepared to handle
 651 // unexpected output - see 8196739. Instead we only check if the table is up-to-date
 652 // if the check_globals flag is true, and in addition allow a grace period and only
 653 // check for stale flags when we hit build 25 (which is far enough into the 6 month
 654 // release cycle that all flag updates should have been processed, whilst still
 655 // leaving time to make the change before RDP2).
 656 // We use a gtest to call this, passing true, so that we can detect stale flags before
 657 // the end of the release cycle.
 658 
 659 static const int SPECIAL_FLAG_VALIDATION_BUILD = 25;
 660 
 661 bool Arguments::verify_special_jvm_flags(bool check_globals) {
 662   bool success = true;
 663   for (size_t i = 0; special_jvm_flags[i].name != nullptr; i++) {
 664     const SpecialFlag& flag = special_jvm_flags[i];
 665     if (lookup_special_flag(flag.name, i)) {
 666       warning("Duplicate special flag declaration \"%s\"", flag.name);
 667       success = false;
 668     }
 669     if (flag.deprecated_in.is_undefined() &&
 670         flag.obsolete_in.is_undefined()) {
 671       warning("Special flag entry \"%s\" must declare version deprecated and/or obsoleted in.", flag.name);
 672       success = false;
 673     }
 674 
 675     if (!flag.deprecated_in.is_undefined()) {
 676       if (!version_less_than(flag.deprecated_in, flag.obsolete_in)) {
 677         warning("Special flag entry \"%s\" must be deprecated before obsoleted.", flag.name);
 678         success = false;
 679       }
 680 
 681       if (!version_less_than(flag.deprecated_in, flag.expired_in)) {
 682         warning("Special flag entry \"%s\" must be deprecated before expired.", flag.name);
 683         success = false;
 684       }
 685     }
 686 
 687     if (!flag.obsolete_in.is_undefined()) {
 688       if (!version_less_than(flag.obsolete_in, flag.expired_in)) {
 689         warning("Special flag entry \"%s\" must be obsoleted before expired.", flag.name);
 690         success = false;
 691       }
 692 
 693       // if flag has become obsolete it should not have a "globals" flag defined anymore.
 694       if (check_globals && VM_Version::vm_build_number() >= SPECIAL_FLAG_VALIDATION_BUILD &&
 695           !version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 696         if (JVMFlag::find_declared_flag(flag.name) != nullptr) {
 697           warning("Global variable for obsolete special flag entry \"%s\" should be removed", flag.name);
 698           success = false;
 699         }
 700       }
 701 
 702     } else if (!flag.expired_in.is_undefined()) {
 703       warning("Special flag entry \"%s\" must be explicitly obsoleted before expired.", flag.name);
 704       success = false;
 705     }
 706 
 707     if (!flag.expired_in.is_undefined()) {
 708       // if flag has become expired it should not have a "globals" flag defined anymore.
 709       if (check_globals && VM_Version::vm_build_number() >= SPECIAL_FLAG_VALIDATION_BUILD &&
 710           !version_less_than(JDK_Version::current(), flag.expired_in)) {
 711         if (JVMFlag::find_declared_flag(flag.name) != nullptr) {
 712           warning("Global variable for expired flag entry \"%s\" should be removed", flag.name);
 713           success = false;
 714         }
 715       }
 716     }
 717   }
 718   return success;
 719 }
 720 #endif
 721 
 722 bool Arguments::atojulong(const char *s, julong* result) {
 723   return parse_integer(s, result);
 724 }
 725 
 726 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size, julong max_size) {
 727   if (size < min_size) return arg_too_small;
 728   if (size > max_size) return arg_too_big;
 729   return arg_in_range;
 730 }
 731 
 732 // Describe an argument out of range error
 733 void Arguments::describe_range_error(ArgsRange errcode) {
 734   switch(errcode) {
 735   case arg_too_big:
 736     jio_fprintf(defaultStream::error_stream(),
 737                 "The specified size exceeds the maximum "
 738                 "representable size.\n");
 739     break;
 740   case arg_too_small:
 741   case arg_unreadable:
 742   case arg_in_range:
 743     // do nothing for now
 744     break;
 745   default:
 746     ShouldNotReachHere();
 747   }
 748 }
 749 
 750 static bool set_bool_flag(JVMFlag* flag, bool value, JVMFlagOrigin origin) {
 751   if (JVMFlagAccess::set_bool(flag, &value, origin) == JVMFlag::SUCCESS) {
 752     return true;
 753   } else {
 754     return false;
 755   }
 756 }
 757 
 758 static bool set_fp_numeric_flag(JVMFlag* flag, const char* value, JVMFlagOrigin origin) {
 759   // strtod allows leading whitespace, but our flag format does not.
 760   if (*value == '\0' || isspace(*value)) {
 761     return false;
 762   }
 763   char* end;
 764   errno = 0;
 765   double v = strtod(value, &end);
 766   if ((errno != 0) || (*end != 0)) {
 767     return false;
 768   }
 769   if (g_isnan(v) || !g_isfinite(v)) {
 770     // Currently we cannot handle these special values.
 771     return false;
 772   }
 773 
 774   if (JVMFlagAccess::set_double(flag, &v, origin) == JVMFlag::SUCCESS) {
 775     return true;
 776   }
 777   return false;
 778 }
 779 
 780 static bool set_numeric_flag(JVMFlag* flag, const char* value, JVMFlagOrigin origin) {
 781   JVMFlag::Error result = JVMFlag::WRONG_FORMAT;
 782 
 783   if (flag->is_int()) {
 784     int v;
 785     if (parse_integer(value, &v)) {
 786       result = JVMFlagAccess::set_int(flag, &v, origin);
 787     }
 788   } else if (flag->is_uint()) {
 789     uint v;
 790     if (parse_integer(value, &v)) {
 791       result = JVMFlagAccess::set_uint(flag, &v, origin);
 792     }
 793   } else if (flag->is_intx()) {
 794     intx v;
 795     if (parse_integer(value, &v)) {
 796       result = JVMFlagAccess::set_intx(flag, &v, origin);
 797     }
 798   } else if (flag->is_uintx()) {
 799     uintx v;
 800     if (parse_integer(value, &v)) {
 801       result = JVMFlagAccess::set_uintx(flag, &v, origin);
 802     }
 803   } else if (flag->is_uint64_t()) {
 804     uint64_t v;
 805     if (parse_integer(value, &v)) {
 806       result = JVMFlagAccess::set_uint64_t(flag, &v, origin);
 807     }
 808   } else if (flag->is_size_t()) {
 809     size_t v;
 810     if (parse_integer(value, &v)) {
 811       result = JVMFlagAccess::set_size_t(flag, &v, origin);
 812     }
 813   }
 814 
 815   return result == JVMFlag::SUCCESS;
 816 }
 817 
 818 static bool set_string_flag(JVMFlag* flag, const char* value, JVMFlagOrigin origin) {
 819   if (value[0] == '\0') {
 820     value = nullptr;
 821   }
 822   if (JVMFlagAccess::set_ccstr(flag, &value, origin) != JVMFlag::SUCCESS) return false;
 823   // Contract:  JVMFlag always returns a pointer that needs freeing.
 824   FREE_C_HEAP_ARRAY(char, value);
 825   return true;
 826 }
 827 
 828 static bool append_to_string_flag(JVMFlag* flag, const char* new_value, JVMFlagOrigin origin) {
 829   const char* old_value = "";
 830   if (JVMFlagAccess::get_ccstr(flag, &old_value) != JVMFlag::SUCCESS) return false;
 831   size_t old_len = old_value != nullptr ? strlen(old_value) : 0;
 832   size_t new_len = strlen(new_value);
 833   const char* value;
 834   char* free_this_too = nullptr;
 835   if (old_len == 0) {
 836     value = new_value;
 837   } else if (new_len == 0) {
 838     value = old_value;
 839   } else {
 840      size_t length = old_len + 1 + new_len + 1;
 841      char* buf = NEW_C_HEAP_ARRAY(char, length, mtArguments);
 842     // each new setting adds another LINE to the switch:
 843     jio_snprintf(buf, length, "%s\n%s", old_value, new_value);
 844     value = buf;
 845     free_this_too = buf;
 846   }
 847   (void) JVMFlagAccess::set_ccstr(flag, &value, origin);
 848   // JVMFlag always returns a pointer that needs freeing.
 849   FREE_C_HEAP_ARRAY(char, value);
 850   // JVMFlag made its own copy, so I must delete my own temp. buffer.
 851   FREE_C_HEAP_ARRAY(char, free_this_too);
 852   return true;
 853 }
 854 
 855 const char* Arguments::handle_aliases_and_deprecation(const char* arg) {
 856   const char* real_name = real_flag_name(arg);
 857   JDK_Version since = JDK_Version();
 858   switch (is_deprecated_flag(arg, &since)) {
 859   case -1: {
 860       // Obsolete or expired, so don't process normally,
 861       // but allow for an obsolete flag we're still
 862       // temporarily allowing.
 863       if (!is_obsolete_flag(arg, &since)) {
 864         return real_name;
 865       }
 866       // Note if we're not considered obsolete then we can't be expired either
 867       // as obsoletion must come first.
 868       return nullptr;
 869     }
 870     case 0:
 871       return real_name;
 872     case 1: {
 873       char version[256];
 874       since.to_string(version, sizeof(version));
 875       if (real_name != arg) {
 876         warning("Option %s was deprecated in version %s and will likely be removed in a future release. Use option %s instead.",
 877                 arg, version, real_name);
 878       } else {
 879         warning("Option %s was deprecated in version %s and will likely be removed in a future release.",
 880                 arg, version);
 881       }
 882       return real_name;
 883     }
 884   }
 885   ShouldNotReachHere();
 886   return nullptr;
 887 }
 888 
 889 #define BUFLEN 255
 890 
 891 JVMFlag* Arguments::find_jvm_flag(const char* name, size_t name_length) {
 892   char name_copied[BUFLEN+1];
 893   if (name[name_length] != 0) {
 894     if (name_length > BUFLEN) {
 895       return nullptr;
 896     } else {
 897       strncpy(name_copied, name, name_length);
 898       name_copied[name_length] = '\0';
 899       name = name_copied;
 900     }
 901   }
 902 
 903   const char* real_name = Arguments::handle_aliases_and_deprecation(name);
 904   if (real_name == nullptr) {
 905     return nullptr;
 906   }
 907   JVMFlag* flag = JVMFlag::find_flag(real_name);
 908   return flag;
 909 }
 910 
 911 bool Arguments::parse_argument(const char* arg, JVMFlagOrigin origin) {
 912   bool is_bool = false;
 913   bool bool_val = false;
 914   char c = *arg;
 915   if (c == '+' || c == '-') {
 916     is_bool = true;
 917     bool_val = (c == '+');
 918     arg++;
 919   }
 920 
 921   const char* name = arg;
 922   while (true) {
 923     c = *arg;
 924     if (isalnum(c) || (c == '_')) {
 925       ++arg;
 926     } else {
 927       break;
 928     }
 929   }
 930 
 931   size_t name_len = size_t(arg - name);
 932   if (name_len == 0) {
 933     return false;
 934   }
 935 
 936   JVMFlag* flag = find_jvm_flag(name, name_len);
 937   if (flag == nullptr) {
 938     return false;
 939   }
 940 
 941   if (is_bool) {
 942     if (*arg != 0) {
 943       // Error -- extra characters such as -XX:+BoolFlag=123
 944       return false;
 945     }
 946     return set_bool_flag(flag, bool_val, origin);
 947   }
 948 
 949   if (arg[0] == '=') {
 950     const char* value = arg + 1;
 951     if (flag->is_ccstr()) {
 952       if (flag->ccstr_accumulates()) {
 953         return append_to_string_flag(flag, value, origin);
 954       } else {
 955         return set_string_flag(flag, value, origin);
 956       }
 957     } else if (flag->is_double()) {
 958       return set_fp_numeric_flag(flag, value, origin);
 959     } else {
 960       return set_numeric_flag(flag, value, origin);
 961     }
 962   }
 963 
 964   if (arg[0] == ':' && arg[1] == '=') {
 965     // -XX:Foo:=xxx will reset the string flag to the given value.
 966     const char* value = arg + 2;
 967     return set_string_flag(flag, value, origin);
 968   }
 969 
 970   return false;
 971 }
 972 
 973 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
 974   assert(bldarray != nullptr, "illegal argument");
 975 
 976   if (arg == nullptr) {
 977     return;
 978   }
 979 
 980   int new_count = *count + 1;
 981 
 982   // expand the array and add arg to the last element
 983   if (*bldarray == nullptr) {
 984     *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtArguments);
 985   } else {
 986     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtArguments);
 987   }
 988   (*bldarray)[*count] = os::strdup_check_oom(arg);
 989   *count = new_count;
 990 }
 991 
 992 void Arguments::build_jvm_args(const char* arg) {
 993   add_string(&_jvm_args_array, &_num_jvm_args, arg);
 994 }
 995 
 996 void Arguments::build_jvm_flags(const char* arg) {
 997   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
 998 }
 999 
1000 // utility function to return a string that concatenates all
1001 // strings in a given char** array
1002 const char* Arguments::build_resource_string(char** args, int count) {
1003   if (args == nullptr || count == 0) {
1004     return nullptr;
1005   }
1006   size_t length = 0;
1007   for (int i = 0; i < count; i++) {
1008     length += strlen(args[i]) + 1; // add 1 for a space or null terminating character
1009   }
1010   char* s = NEW_RESOURCE_ARRAY(char, length);
1011   char* dst = s;
1012   for (int j = 0; j < count; j++) {
1013     size_t offset = strlen(args[j]) + 1; // add 1 for a space or null terminating character
1014     jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with null character
1015     dst += offset;
1016     length -= offset;
1017   }
1018   return (const char*) s;
1019 }
1020 
1021 void Arguments::print_on(outputStream* st) {
1022   st->print_cr("VM Arguments:");
1023   if (num_jvm_flags() > 0) {
1024     st->print("jvm_flags: "); print_jvm_flags_on(st);
1025     st->cr();
1026   }
1027   if (num_jvm_args() > 0) {
1028     st->print("jvm_args: "); print_jvm_args_on(st);
1029     st->cr();
1030   }
1031   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
1032   if (_java_class_path != nullptr) {
1033     char* path = _java_class_path->value();
1034     size_t len = strlen(path);
1035     st->print("java_class_path (initial): ");
1036     // Avoid using st->print_cr() because path length maybe longer than O_BUFLEN.
1037     if (len == 0) {
1038       st->print_raw_cr("<not set>");
1039     } else {
1040       st->print_raw_cr(path, len);
1041     }
1042   }
1043   st->print_cr("Launcher Type: %s", _sun_java_launcher);
1044 }
1045 
1046 void Arguments::print_summary_on(outputStream* st) {
1047   // Print the command line.  Environment variables that are helpful for
1048   // reproducing the problem are written later in the hs_err file.
1049   // flags are from setting file
1050   if (num_jvm_flags() > 0) {
1051     st->print_raw("Settings File: ");
1052     print_jvm_flags_on(st);
1053     st->cr();
1054   }
1055   // args are the command line and environment variable arguments.
1056   st->print_raw("Command Line: ");
1057   if (num_jvm_args() > 0) {
1058     print_jvm_args_on(st);
1059   }
1060   // this is the classfile and any arguments to the java program
1061   if (java_command() != nullptr) {
1062     st->print("%s", java_command());
1063   }
1064   st->cr();
1065 }
1066 
1067 void Arguments::print_jvm_flags_on(outputStream* st) {
1068   if (_num_jvm_flags > 0) {
1069     for (int i=0; i < _num_jvm_flags; i++) {
1070       st->print("%s ", _jvm_flags_array[i]);
1071     }
1072   }
1073 }
1074 
1075 void Arguments::print_jvm_args_on(outputStream* st) {
1076   if (_num_jvm_args > 0) {
1077     for (int i=0; i < _num_jvm_args; i++) {
1078       st->print("%s ", _jvm_args_array[i]);
1079     }
1080   }
1081 }
1082 
1083 bool Arguments::process_argument(const char* arg,
1084                                  jboolean ignore_unrecognized,
1085                                  JVMFlagOrigin origin) {
1086   JDK_Version since = JDK_Version();
1087 
1088   if (parse_argument(arg, origin)) {
1089     return true;
1090   }
1091 
1092   // Determine if the flag has '+', '-', or '=' characters.
1093   bool has_plus_minus = (*arg == '+' || *arg == '-');
1094   const char* const argname = has_plus_minus ? arg + 1 : arg;
1095 
1096   size_t arg_len;
1097   const char* equal_sign = strchr(argname, '=');
1098   if (equal_sign == nullptr) {
1099     arg_len = strlen(argname);
1100   } else {
1101     arg_len = equal_sign - argname;
1102   }
1103 
1104   // Only make the obsolete check for valid arguments.
1105   if (arg_len <= BUFLEN) {
1106     // Construct a string which consists only of the argument name without '+', '-', or '='.
1107     char stripped_argname[BUFLEN+1]; // +1 for '\0'
1108     jio_snprintf(stripped_argname, arg_len+1, "%s", argname); // +1 for '\0'
1109     if (is_obsolete_flag(stripped_argname, &since)) {
1110       char version[256];
1111       since.to_string(version, sizeof(version));
1112       warning("Ignoring option %s; support was removed in %s", stripped_argname, version);
1113       return true;
1114     }
1115   }
1116 
1117   // For locked flags, report a custom error message if available.
1118   // Otherwise, report the standard unrecognized VM option.
1119   const JVMFlag* found_flag = JVMFlag::find_declared_flag((const char*)argname, arg_len);
1120   if (found_flag != nullptr) {
1121     char locked_message_buf[BUFLEN];
1122     JVMFlag::MsgType msg_type = found_flag->get_locked_message(locked_message_buf, BUFLEN);
1123     if (strlen(locked_message_buf) == 0) {
1124       if (found_flag->is_bool() && !has_plus_minus) {
1125         jio_fprintf(defaultStream::error_stream(),
1126           "Missing +/- setting for VM option '%s'\n", argname);
1127       } else if (!found_flag->is_bool() && has_plus_minus) {
1128         jio_fprintf(defaultStream::error_stream(),
1129           "Unexpected +/- setting in VM option '%s'\n", argname);
1130       } else {
1131         jio_fprintf(defaultStream::error_stream(),
1132           "Improperly specified VM option '%s'\n", argname);
1133       }
1134     } else {
1135 #ifdef PRODUCT
1136       bool mismatched = ((msg_type == JVMFlag::NOTPRODUCT_FLAG_BUT_PRODUCT_BUILD) ||
1137                          (msg_type == JVMFlag::DEVELOPER_FLAG_BUT_PRODUCT_BUILD));
1138       if (ignore_unrecognized && mismatched) {
1139         return true;
1140       }
1141 #endif
1142       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
1143     }
1144   } else {
1145     if (ignore_unrecognized) {
1146       return true;
1147     }
1148     jio_fprintf(defaultStream::error_stream(),
1149                 "Unrecognized VM option '%s'\n", argname);
1150     JVMFlag* fuzzy_matched = JVMFlag::fuzzy_match((const char*)argname, arg_len, true);
1151     if (fuzzy_matched != nullptr) {
1152       jio_fprintf(defaultStream::error_stream(),
1153                   "Did you mean '%s%s%s'? ",
1154                   (fuzzy_matched->is_bool()) ? "(+/-)" : "",
1155                   fuzzy_matched->name(),
1156                   (fuzzy_matched->is_bool()) ? "" : "=<value>");
1157     }
1158   }
1159 
1160   // allow for commandline "commenting out" options like -XX:#+Verbose
1161   return arg[0] == '#';
1162 }
1163 
1164 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
1165   FILE* stream = os::fopen(file_name, "rb");
1166   if (stream == nullptr) {
1167     if (should_exist) {
1168       jio_fprintf(defaultStream::error_stream(),
1169                   "Could not open settings file %s\n", file_name);
1170       return false;
1171     } else {
1172       return true;
1173     }
1174   }
1175 
1176   char token[1024];
1177   int  pos = 0;
1178 
1179   bool in_white_space = true;
1180   bool in_comment     = false;
1181   bool in_quote       = false;
1182   char quote_c        = 0;
1183   bool result         = true;
1184 
1185   int c = getc(stream);
1186   while(c != EOF && pos < (int)(sizeof(token)-1)) {
1187     if (in_white_space) {
1188       if (in_comment) {
1189         if (c == '\n') in_comment = false;
1190       } else {
1191         if (c == '#') in_comment = true;
1192         else if (!isspace(c)) {
1193           in_white_space = false;
1194           token[pos++] = c;
1195         }
1196       }
1197     } else {
1198       if (c == '\n' || (!in_quote && isspace(c))) {
1199         // token ends at newline, or at unquoted whitespace
1200         // this allows a way to include spaces in string-valued options
1201         token[pos] = '\0';
1202         logOption(token);
1203         result &= process_argument(token, ignore_unrecognized, JVMFlagOrigin::CONFIG_FILE);
1204         build_jvm_flags(token);
1205         pos = 0;
1206         in_white_space = true;
1207         in_quote = false;
1208       } else if (!in_quote && (c == '\'' || c == '"')) {
1209         in_quote = true;
1210         quote_c = c;
1211       } else if (in_quote && (c == quote_c)) {
1212         in_quote = false;
1213       } else {
1214         token[pos++] = c;
1215       }
1216     }
1217     c = getc(stream);
1218   }
1219   if (pos > 0) {
1220     token[pos] = '\0';
1221     result &= process_argument(token, ignore_unrecognized, JVMFlagOrigin::CONFIG_FILE);
1222     build_jvm_flags(token);
1223   }
1224   fclose(stream);
1225   return result;
1226 }
1227 
1228 //=============================================================================================================
1229 // Parsing of properties (-D)
1230 
1231 const char* Arguments::get_property(const char* key) {
1232   return PropertyList_get_value(system_properties(), key);
1233 }
1234 
1235 bool Arguments::add_property(const char* prop, PropertyWriteable writeable, PropertyInternal internal) {
1236   const char* eq = strchr(prop, '=');
1237   const char* key;
1238   const char* value = "";
1239 
1240   if (eq == nullptr) {
1241     // property doesn't have a value, thus use passed string
1242     key = prop;
1243   } else {
1244     // property have a value, thus extract it and save to the
1245     // allocated string
1246     size_t key_len = eq - prop;
1247     char* tmp_key = AllocateHeap(key_len + 1, mtArguments);
1248 
1249     jio_snprintf(tmp_key, key_len + 1, "%s", prop);
1250     key = tmp_key;
1251 
1252     value = &prop[key_len + 1];
1253   }
1254 
1255 #if INCLUDE_CDS
1256   if (is_internal_module_property(key) ||
1257       strcmp(key, "jdk.module.main") == 0) {
1258     MetaspaceShared::disable_optimized_module_handling();
1259     log_info(cds)("optimized module handling: disabled due to incompatible property: %s=%s", key, value);
1260   }
1261   if (strcmp(key, "jdk.module.showModuleResolution") == 0 ||
1262       strcmp(key, "jdk.module.validation") == 0 ||
1263       strcmp(key, "java.system.class.loader") == 0) {
1264     MetaspaceShared::disable_full_module_graph();
1265     log_info(cds)("full module graph: disabled due to incompatible property: %s=%s", key, value);
1266   }
1267 #endif
1268 
1269   if (strcmp(key, "java.compiler") == 0) {
1270     // we no longer support java.compiler system property, log a warning and let it get
1271     // passed to Java, like any other system property
1272     if (strlen(value) == 0 || strcasecmp(value, "NONE") == 0) {
1273         // for applications using NONE or empty value, log a more informative message
1274         warning("The java.compiler system property is obsolete and no longer supported, use -Xint");
1275     } else {
1276         warning("The java.compiler system property is obsolete and no longer supported.");
1277     }
1278   } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0) {
1279     // sun.java.launcher.is_altjvm property is
1280     // private and is processed in process_sun_java_launcher_properties();
1281     // the sun.java.launcher property is passed on to the java application
1282   } else if (strcmp(key, "sun.boot.library.path") == 0) {
1283     // append is true, writable is true, internal is false
1284     PropertyList_unique_add(&_system_properties, key, value, AppendProperty,
1285                             WriteableProperty, ExternalProperty);
1286   } else {
1287     if (strcmp(key, "sun.java.command") == 0) {
1288       char *old_java_command = _java_command;
1289       _java_command = os::strdup_check_oom(value, mtArguments);
1290       if (old_java_command != nullptr) {
1291         os::free(old_java_command);
1292       }
1293     } else if (strcmp(key, "java.vendor.url.bug") == 0) {
1294       // If this property is set on the command line then its value will be
1295       // displayed in VM error logs as the URL at which to submit such logs.
1296       // Normally the URL displayed in error logs is different from the value
1297       // of this system property, so a different property should have been
1298       // used here, but we leave this as-is in case someone depends upon it.
1299       const char* old_java_vendor_url_bug = _java_vendor_url_bug;
1300       // save it in _java_vendor_url_bug, so JVM fatal error handler can access
1301       // its value without going through the property list or making a Java call.
1302       _java_vendor_url_bug = os::strdup_check_oom(value, mtArguments);
1303       if (old_java_vendor_url_bug != nullptr) {
1304         os::free((void *)old_java_vendor_url_bug);
1305       }
1306     }
1307 
1308     // Create new property and add at the end of the list
1309     PropertyList_unique_add(&_system_properties, key, value, AddProperty, writeable, internal);
1310   }
1311 
1312   if (key != prop) {
1313     // SystemProperty copy passed value, thus free previously allocated
1314     // memory
1315     FreeHeap((void *)key);
1316   }
1317 
1318   return true;
1319 }
1320 
1321 #if INCLUDE_CDS
1322 const char* unsupported_properties[] = { "jdk.module.limitmods",
1323                                          "jdk.module.upgrade.path",
1324                                          "jdk.module.patch.0" };
1325 const char* unsupported_options[] = { "--limit-modules",
1326                                       "--upgrade-module-path",
1327                                       "--patch-module"
1328                                     };
1329 void Arguments::check_unsupported_dumping_properties() {
1330   assert(is_dumping_archive(),
1331          "this function is only used with CDS dump time");
1332   assert(ARRAY_SIZE(unsupported_properties) == ARRAY_SIZE(unsupported_options), "must be");
1333   // If a vm option is found in the unsupported_options array, vm will exit with an error message.
1334   SystemProperty* sp = system_properties();
1335   while (sp != nullptr) {
1336     for (uint i = 0; i < ARRAY_SIZE(unsupported_properties); i++) {
1337       if (strcmp(sp->key(), unsupported_properties[i]) == 0) {
1338         vm_exit_during_initialization(
1339           "Cannot use the following option when dumping the shared archive", unsupported_options[i]);
1340       }
1341     }
1342     sp = sp->next();
1343   }
1344 
1345   // Check for an exploded module build in use with -Xshare:dump.
1346   if (!has_jimage()) {
1347     vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
1348   }
1349 }
1350 
1351 bool Arguments::check_unsupported_cds_runtime_properties() {
1352   assert(UseSharedSpaces, "this function is only used with -Xshare:{on,auto}");
1353   assert(ARRAY_SIZE(unsupported_properties) == ARRAY_SIZE(unsupported_options), "must be");
1354   if (ArchiveClassesAtExit != nullptr) {
1355     // dynamic dumping, just return false for now.
1356     // check_unsupported_dumping_properties() will be called later to check the same set of
1357     // properties, and will exit the VM with the correct error message if the unsupported properties
1358     // are used.
1359     return false;
1360   }
1361   for (uint i = 0; i < ARRAY_SIZE(unsupported_properties); i++) {
1362     if (get_property(unsupported_properties[i]) != nullptr) {
1363       if (RequireSharedSpaces) {
1364         warning("CDS is disabled when the %s option is specified.", unsupported_options[i]);
1365       } else {
1366         log_info(cds)("CDS is disabled when the %s option is specified.", unsupported_options[i]);
1367       }
1368       return true;
1369     }
1370   }
1371   return false;
1372 }
1373 #endif
1374 
1375 //===========================================================================================================
1376 // Setting int/mixed/comp mode flags
1377 
1378 void Arguments::set_mode_flags(Mode mode) {
1379   // Set up default values for all flags.
1380   // If you add a flag to any of the branches below,
1381   // add a default value for it here.
1382   _mode                      = mode;
1383 
1384   // Ensure Agent_OnLoad has the correct initial values.
1385   // This may not be the final mode; mode may change later in onload phase.
1386   PropertyList_unique_add(&_system_properties, "java.vm.info",
1387                           VM_Version::vm_info_string(), AddProperty, UnwriteableProperty, ExternalProperty);
1388 
1389   UseInterpreter             = true;
1390   UseCompiler                = true;
1391   UseLoopCounter             = true;
1392 
1393   // Default values may be platform/compiler dependent -
1394   // use the saved values
1395   ClipInlining               = Arguments::_ClipInlining;
1396   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1397   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1398   BackgroundCompilation      = Arguments::_BackgroundCompilation;
1399 
1400   // Change from defaults based on mode
1401   switch (mode) {
1402   default:
1403     ShouldNotReachHere();
1404     break;
1405   case _int:
1406     UseCompiler              = false;
1407     UseLoopCounter           = false;
1408     AlwaysCompileLoopMethods = false;
1409     UseOnStackReplacement    = false;
1410     break;
1411   case _mixed:
1412     // same as default
1413     break;
1414   case _comp:
1415     UseInterpreter           = false;
1416     BackgroundCompilation    = false;
1417     ClipInlining             = false;
1418     break;
1419   }
1420 }
1421 
1422 // Conflict: required to use shared spaces (-Xshare:on), but
1423 // incompatible command line options were chosen.
1424 static void no_shared_spaces(const char* message) {
1425   if (RequireSharedSpaces) {
1426     jio_fprintf(defaultStream::error_stream(),
1427       "Class data sharing is inconsistent with other specified options.\n");
1428     vm_exit_during_initialization("Unable to use shared archive", message);
1429   } else {
1430     log_info(cds)("Unable to use shared archive: %s", message);
1431     UseSharedSpaces = false;
1432   }
1433 }
1434 
1435 void set_object_alignment() {
1436   // Object alignment.
1437   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1438   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1439   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1440   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1441   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1442   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1443 
1444   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1445   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1446 
1447   // Oop encoding heap max
1448   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1449 }
1450 
1451 size_t Arguments::max_heap_for_compressed_oops() {
1452   // Avoid sign flip.
1453   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1454   // We need to fit both the null page and the heap into the memory budget, while
1455   // keeping alignment constraints of the heap. To guarantee the latter, as the
1456   // null page is located before the heap, we pad the null page to the conservative
1457   // maximum alignment that the GC may ever impose upon the heap.
1458   size_t displacement_due_to_null_page = align_up(os::vm_page_size(),
1459                                                   _conservative_max_heap_alignment);
1460 
1461   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1462   NOT_LP64(ShouldNotReachHere(); return 0);
1463 }
1464 
1465 void Arguments::set_use_compressed_oops() {
1466 #ifdef _LP64
1467   // MaxHeapSize is not set up properly at this point, but
1468   // the only value that can override MaxHeapSize if we are
1469   // to use UseCompressedOops are InitialHeapSize and MinHeapSize.
1470   size_t max_heap_size = MAX3(MaxHeapSize, InitialHeapSize, MinHeapSize);
1471 
1472   if (max_heap_size <= max_heap_for_compressed_oops()) {
1473     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1474       FLAG_SET_ERGO(UseCompressedOops, true);
1475     }
1476   } else {
1477     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1478       warning("Max heap size too large for Compressed Oops");
1479       FLAG_SET_DEFAULT(UseCompressedOops, false);
1480     }
1481   }
1482 #endif // _LP64
1483 }
1484 
1485 void Arguments::set_use_compressed_klass_ptrs() {
1486 #ifdef _LP64
1487   assert(!UseCompressedClassPointers || CompressedClassSpaceSize <= KlassEncodingMetaspaceMax,
1488          "CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1489 #endif // _LP64
1490 }
1491 
1492 void Arguments::set_conservative_max_heap_alignment() {
1493   // The conservative maximum required alignment for the heap is the maximum of
1494   // the alignments imposed by several sources: any requirements from the heap
1495   // itself and the maximum page size we may run the VM with.
1496   size_t heap_alignment = GCConfig::arguments()->conservative_max_heap_alignment();
1497   _conservative_max_heap_alignment = MAX4(heap_alignment,
1498                                           os::vm_allocation_granularity(),
1499                                           os::max_page_size(),
1500                                           GCArguments::compute_heap_alignment());
1501 }
1502 
1503 jint Arguments::set_ergonomics_flags() {
1504   GCConfig::initialize();
1505 
1506   set_conservative_max_heap_alignment();
1507 
1508 #ifdef _LP64
1509   set_use_compressed_oops();
1510   set_use_compressed_klass_ptrs();
1511 
1512   // Also checks that certain machines are slower with compressed oops
1513   // in vm_version initialization code.
1514 #endif // _LP64
1515 
1516   return JNI_OK;
1517 }
1518 
1519 size_t Arguments::limit_heap_by_allocatable_memory(size_t limit) {
1520   size_t max_allocatable;
1521   size_t result = limit;
1522   if (os::has_allocatable_memory_limit(&max_allocatable)) {
1523     // The AggressiveHeap check is a temporary workaround to avoid calling
1524     // GCarguments::heap_virtual_to_physical_ratio() before a GC has been
1525     // selected. This works because AggressiveHeap implies UseParallelGC
1526     // where we know the ratio will be 1. Once the AggressiveHeap option is
1527     // removed, this can be cleaned up.
1528     size_t heap_virtual_to_physical_ratio = (AggressiveHeap ? 1 : GCConfig::arguments()->heap_virtual_to_physical_ratio());
1529     size_t fraction = MaxVirtMemFraction * heap_virtual_to_physical_ratio;
1530     result = MIN2(result, max_allocatable / fraction);
1531   }
1532   return result;
1533 }
1534 
1535 // Use static initialization to get the default before parsing
1536 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1537 
1538 void Arguments::set_heap_size() {
1539   julong phys_mem;
1540 
1541   // If the user specified one of these options, they
1542   // want specific memory sizing so do not limit memory
1543   // based on compressed oops addressability.
1544   // Also, memory limits will be calculated based on
1545   // available os physical memory, not our MaxRAM limit,
1546   // unless MaxRAM is also specified.
1547   bool override_coop_limit = (!FLAG_IS_DEFAULT(MaxRAMPercentage) ||
1548                            !FLAG_IS_DEFAULT(MaxRAMFraction) ||
1549                            !FLAG_IS_DEFAULT(MinRAMPercentage) ||
1550                            !FLAG_IS_DEFAULT(MinRAMFraction) ||
1551                            !FLAG_IS_DEFAULT(InitialRAMPercentage) ||
1552                            !FLAG_IS_DEFAULT(InitialRAMFraction) ||
1553                            !FLAG_IS_DEFAULT(MaxRAM));
1554   if (override_coop_limit) {
1555     if (FLAG_IS_DEFAULT(MaxRAM)) {
1556       phys_mem = os::physical_memory();
1557       FLAG_SET_ERGO(MaxRAM, (uint64_t)phys_mem);
1558     } else {
1559       phys_mem = (julong)MaxRAM;
1560     }
1561   } else {
1562     phys_mem = FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1563                                        : (julong)MaxRAM;
1564   }
1565 
1566 
1567   // Convert deprecated flags
1568   if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&
1569       !FLAG_IS_DEFAULT(MaxRAMFraction))
1570     MaxRAMPercentage = 100.0 / MaxRAMFraction;
1571 
1572   if (FLAG_IS_DEFAULT(MinRAMPercentage) &&
1573       !FLAG_IS_DEFAULT(MinRAMFraction))
1574     MinRAMPercentage = 100.0 / MinRAMFraction;
1575 
1576   if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&
1577       !FLAG_IS_DEFAULT(InitialRAMFraction))
1578     InitialRAMPercentage = 100.0 / InitialRAMFraction;
1579 
1580   // If the maximum heap size has not been set with -Xmx,
1581   // then set it as fraction of the size of physical memory,
1582   // respecting the maximum and minimum sizes of the heap.
1583   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1584     julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);
1585     const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);
1586     if (reasonable_min < MaxHeapSize) {
1587       // Small physical memory, so use a minimum fraction of it for the heap
1588       reasonable_max = reasonable_min;
1589     } else {
1590       // Not-small physical memory, so require a heap at least
1591       // as large as MaxHeapSize
1592       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1593     }
1594 
1595     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1596       // Limit the heap size to ErgoHeapSizeLimit
1597       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1598     }
1599 
1600     reasonable_max = limit_heap_by_allocatable_memory(reasonable_max);
1601 
1602     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1603       // An initial heap size was specified on the command line,
1604       // so be sure that the maximum size is consistent.  Done
1605       // after call to limit_heap_by_allocatable_memory because that
1606       // method might reduce the allocation size.
1607       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1608     } else if (!FLAG_IS_DEFAULT(MinHeapSize)) {
1609       reasonable_max = MAX2(reasonable_max, (julong)MinHeapSize);
1610     }
1611 
1612 #ifdef _LP64
1613     if (UseCompressedOops || UseCompressedClassPointers) {
1614       // HeapBaseMinAddress can be greater than default but not less than.
1615       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1616         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1617           // matches compressed oops printing flags
1618           log_debug(gc, heap, coops)("HeapBaseMinAddress must be at least " SIZE_FORMAT
1619                                      " (" SIZE_FORMAT "G) which is greater than value given " SIZE_FORMAT,
1620                                      DefaultHeapBaseMinAddress,
1621                                      DefaultHeapBaseMinAddress/G,
1622                                      HeapBaseMinAddress);
1623           FLAG_SET_ERGO(HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1624         }
1625       }
1626     }
1627     if (UseCompressedOops) {
1628       // Limit the heap size to the maximum possible when using compressed oops
1629       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1630 
1631       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1632         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1633         // but it should be not less than default MaxHeapSize.
1634         max_coop_heap -= HeapBaseMinAddress;
1635       }
1636 
1637       // If user specified flags prioritizing os physical
1638       // memory limits, then disable compressed oops if
1639       // limits exceed max_coop_heap and UseCompressedOops
1640       // was not specified.
1641       if (reasonable_max > max_coop_heap) {
1642         if (FLAG_IS_ERGO(UseCompressedOops) && override_coop_limit) {
1643           log_info(cds)("UseCompressedOops and UseCompressedClassPointers have been disabled due to"
1644             " max heap " SIZE_FORMAT " > compressed oop heap " SIZE_FORMAT ". "
1645             "Please check the setting of MaxRAMPercentage %5.2f."
1646             ,(size_t)reasonable_max, (size_t)max_coop_heap, MaxRAMPercentage);
1647           FLAG_SET_ERGO(UseCompressedOops, false);
1648         } else {
1649           reasonable_max = MIN2(reasonable_max, max_coop_heap);
1650         }
1651       }
1652     }
1653 #endif // _LP64
1654 
1655     log_trace(gc, heap)("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1656     FLAG_SET_ERGO(MaxHeapSize, (size_t)reasonable_max);
1657   }
1658 
1659   // If the minimum or initial heap_size have not been set or requested to be set
1660   // ergonomically, set them accordingly.
1661   if (InitialHeapSize == 0 || MinHeapSize == 0) {
1662     julong reasonable_minimum = (julong)(OldSize + NewSize);
1663 
1664     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1665 
1666     reasonable_minimum = limit_heap_by_allocatable_memory(reasonable_minimum);
1667 
1668     if (InitialHeapSize == 0) {
1669       julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);
1670       reasonable_initial = limit_heap_by_allocatable_memory(reasonable_initial);
1671 
1672       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)MinHeapSize);
1673       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1674 
1675       FLAG_SET_ERGO(InitialHeapSize, (size_t)reasonable_initial);
1676       log_trace(gc, heap)("  Initial heap size " SIZE_FORMAT, InitialHeapSize);
1677     }
1678     // If the minimum heap size has not been set (via -Xms or -XX:MinHeapSize),
1679     // synchronize with InitialHeapSize to avoid errors with the default value.
1680     if (MinHeapSize == 0) {
1681       FLAG_SET_ERGO(MinHeapSize, MIN2((size_t)reasonable_minimum, InitialHeapSize));
1682       log_trace(gc, heap)("  Minimum heap size " SIZE_FORMAT, MinHeapSize);
1683     }
1684   }
1685 }
1686 
1687 // This option inspects the machine and attempts to set various
1688 // parameters to be optimal for long-running, memory allocation
1689 // intensive jobs.  It is intended for machines with large
1690 // amounts of cpu and memory.
1691 jint Arguments::set_aggressive_heap_flags() {
1692   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
1693   // VM, but we may not be able to represent the total physical memory
1694   // available (like having 8gb of memory on a box but using a 32bit VM).
1695   // Thus, we need to make sure we're using a julong for intermediate
1696   // calculations.
1697   julong initHeapSize;
1698   julong total_memory = os::physical_memory();
1699 
1700   if (total_memory < (julong) 256 * M) {
1701     jio_fprintf(defaultStream::error_stream(),
1702             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
1703     vm_exit(1);
1704   }
1705 
1706   // The heap size is half of available memory, or (at most)
1707   // all of possible memory less 160mb (leaving room for the OS
1708   // when using ISM).  This is the maximum; because adaptive sizing
1709   // is turned on below, the actual space used may be smaller.
1710 
1711   initHeapSize = MIN2(total_memory / (julong) 2,
1712           total_memory - (julong) 160 * M);
1713 
1714   initHeapSize = limit_heap_by_allocatable_memory(initHeapSize);
1715 
1716   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1717     if (FLAG_SET_CMDLINE(MaxHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1718       return JNI_EINVAL;
1719     }
1720     if (FLAG_SET_CMDLINE(InitialHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1721       return JNI_EINVAL;
1722     }
1723     if (FLAG_SET_CMDLINE(MinHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1724       return JNI_EINVAL;
1725     }
1726   }
1727   if (FLAG_IS_DEFAULT(NewSize)) {
1728     // Make the young generation 3/8ths of the total heap.
1729     if (FLAG_SET_CMDLINE(NewSize,
1730             ((julong) MaxHeapSize / (julong) 8) * (julong) 3) != JVMFlag::SUCCESS) {
1731       return JNI_EINVAL;
1732     }
1733     if (FLAG_SET_CMDLINE(MaxNewSize, NewSize) != JVMFlag::SUCCESS) {
1734       return JNI_EINVAL;
1735     }
1736   }
1737 
1738 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
1739   FLAG_SET_DEFAULT(UseLargePages, true);
1740 #endif
1741 
1742   // Increase some data structure sizes for efficiency
1743   if (FLAG_SET_CMDLINE(BaseFootPrintEstimate, MaxHeapSize) != JVMFlag::SUCCESS) {
1744     return JNI_EINVAL;
1745   }
1746   if (FLAG_SET_CMDLINE(ResizeTLAB, false) != JVMFlag::SUCCESS) {
1747     return JNI_EINVAL;
1748   }
1749   if (FLAG_SET_CMDLINE(TLABSize, 256 * K) != JVMFlag::SUCCESS) {
1750     return JNI_EINVAL;
1751   }
1752 
1753   // See the OldPLABSize comment below, but replace 'after promotion'
1754   // with 'after copying'.  YoungPLABSize is the size of the survivor
1755   // space per-gc-thread buffers.  The default is 4kw.
1756   if (FLAG_SET_CMDLINE(YoungPLABSize, 256 * K) != JVMFlag::SUCCESS) { // Note: this is in words
1757     return JNI_EINVAL;
1758   }
1759 
1760   // OldPLABSize is the size of the buffers in the old gen that
1761   // UseParallelGC uses to promote live data that doesn't fit in the
1762   // survivor spaces.  At any given time, there's one for each gc thread.
1763   // The default size is 1kw. These buffers are rarely used, since the
1764   // survivor spaces are usually big enough.  For specjbb, however, there
1765   // are occasions when there's lots of live data in the young gen
1766   // and we end up promoting some of it.  We don't have a definite
1767   // explanation for why bumping OldPLABSize helps, but the theory
1768   // is that a bigger PLAB results in retaining something like the
1769   // original allocation order after promotion, which improves mutator
1770   // locality.  A minor effect may be that larger PLABs reduce the
1771   // number of PLAB allocation events during gc.  The value of 8kw
1772   // was arrived at by experimenting with specjbb.
1773   if (FLAG_SET_CMDLINE(OldPLABSize, 8 * K) != JVMFlag::SUCCESS) { // Note: this is in words
1774     return JNI_EINVAL;
1775   }
1776 
1777   // Enable parallel GC and adaptive generation sizing
1778   if (FLAG_SET_CMDLINE(UseParallelGC, true) != JVMFlag::SUCCESS) {
1779     return JNI_EINVAL;
1780   }
1781 
1782   // Encourage steady state memory management
1783   if (FLAG_SET_CMDLINE(ThresholdTolerance, 100) != JVMFlag::SUCCESS) {
1784     return JNI_EINVAL;
1785   }
1786 
1787   // This appears to improve mutator locality
1788   if (FLAG_SET_CMDLINE(ScavengeBeforeFullGC, false) != JVMFlag::SUCCESS) {
1789     return JNI_EINVAL;
1790   }
1791 
1792   return JNI_OK;
1793 }
1794 
1795 // This must be called after ergonomics.
1796 void Arguments::set_bytecode_flags() {
1797   if (!RewriteBytecodes) {
1798     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1799   }
1800 }
1801 
1802 // Aggressive optimization flags
1803 jint Arguments::set_aggressive_opts_flags() {
1804 #ifdef COMPILER2
1805   if (AggressiveUnboxing) {
1806     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1807       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1808     } else if (!EliminateAutoBox) {
1809       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
1810       AggressiveUnboxing = false;
1811     }
1812     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1813       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1814     } else if (!DoEscapeAnalysis) {
1815       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
1816       AggressiveUnboxing = false;
1817     }
1818   }
1819   if (!FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1820     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1821       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1822     }
1823     // Feed the cache size setting into the JDK
1824     char buffer[1024];
1825     jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
1826     if (!add_property(buffer)) {
1827       return JNI_ENOMEM;
1828     }
1829   }
1830 #endif
1831 
1832   return JNI_OK;
1833 }
1834 
1835 //===========================================================================================================
1836 
1837 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1838   if (_sun_java_launcher != _default_java_launcher) {
1839     os::free(const_cast<char*>(_sun_java_launcher));
1840   }
1841   _sun_java_launcher = os::strdup_check_oom(launcher);
1842 }
1843 
1844 bool Arguments::created_by_java_launcher() {
1845   assert(_sun_java_launcher != nullptr, "property must have value");
1846   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1847 }
1848 
1849 bool Arguments::sun_java_launcher_is_altjvm() {
1850   return _sun_java_launcher_is_altjvm;
1851 }
1852 
1853 //===========================================================================================================
1854 // Parsing of main arguments
1855 
1856 unsigned int addreads_count = 0;
1857 unsigned int addexports_count = 0;
1858 unsigned int addopens_count = 0;
1859 unsigned int addmods_count = 0;
1860 unsigned int patch_mod_count = 0;
1861 unsigned int enable_native_access_count = 0;
1862 
1863 // Check the consistency of vm_init_args
1864 bool Arguments::check_vm_args_consistency() {
1865   // Method for adding checks for flag consistency.
1866   // The intent is to warn the user of all possible conflicts,
1867   // before returning an error.
1868   // Note: Needs platform-dependent factoring.
1869   bool status = true;
1870 
1871   if (TLABRefillWasteFraction == 0) {
1872     jio_fprintf(defaultStream::error_stream(),
1873                 "TLABRefillWasteFraction should be a denominator, "
1874                 "not " SIZE_FORMAT "\n",
1875                 TLABRefillWasteFraction);
1876     status = false;
1877   }
1878 
1879   status = CompilerConfig::check_args_consistency(status);
1880 #if INCLUDE_JVMCI
1881   if (status && EnableJVMCI) {
1882     PropertyList_unique_add(&_system_properties, "jdk.internal.vm.ci.enabled", "true",
1883         AddProperty, UnwriteableProperty, InternalProperty);
1884     if (ClassLoader::is_module_observable("jdk.internal.vm.ci")) {
1885       if (!create_numbered_module_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {
1886         return false;
1887       }
1888     }
1889   }
1890 #endif
1891 
1892 #if INCLUDE_JFR
1893   if (status && (FlightRecorderOptions || StartFlightRecording)) {
1894     if (!create_numbered_module_property("jdk.module.addmods", "jdk.jfr", addmods_count++)) {
1895       return false;
1896     }
1897   }
1898 #endif
1899 
1900 #ifndef SUPPORT_RESERVED_STACK_AREA
1901   if (StackReservedPages != 0) {
1902     FLAG_SET_CMDLINE(StackReservedPages, 0);
1903     warning("Reserved Stack Area not supported on this platform");
1904   }
1905 #endif
1906 
1907 #if !defined(X86) && !defined(AARCH64) && !defined(RISCV64) && !defined(ARM) && !defined(PPC64) && !defined(S390)
1908   if (LockingMode == LM_LIGHTWEIGHT) {
1909     FLAG_SET_CMDLINE(LockingMode, LM_LEGACY);
1910     warning("New lightweight locking not supported on this platform");
1911   }
1912 #endif
1913 
1914 #if !defined(X86) && !defined(AARCH64) && !defined(PPC64) && !defined(RISCV64) && !defined(S390)
1915   if (LockingMode == LM_MONITOR) {
1916     jio_fprintf(defaultStream::error_stream(),
1917                 "LockingMode == 0 (LM_MONITOR) is not fully implemented on this architecture");
1918     return false;
1919   }
1920 #endif
1921 #if defined(X86) && !defined(ZERO)
1922   if (LockingMode == LM_MONITOR && UseRTMForStackLocks) {
1923     jio_fprintf(defaultStream::error_stream(),
1924                 "LockingMode == 0 (LM_MONITOR) and -XX:+UseRTMForStackLocks are mutually exclusive");
1925 
1926     return false;
1927   }
1928 #endif
1929   if (VerifyHeavyMonitors && LockingMode != LM_MONITOR) {
1930     jio_fprintf(defaultStream::error_stream(),
1931                 "-XX:+VerifyHeavyMonitors requires LockingMode == 0 (LM_MONITOR)");
1932     return false;
1933   }
1934   return status;
1935 }
1936 
1937 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
1938   const char* option_type) {
1939   if (ignore) return false;
1940 
1941   const char* spacer = " ";
1942   if (option_type == nullptr) {
1943     option_type = ++spacer; // Set both to the empty string.
1944   }
1945 
1946   jio_fprintf(defaultStream::error_stream(),
1947               "Unrecognized %s%soption: %s\n", option_type, spacer,
1948               option->optionString);
1949   return true;
1950 }
1951 
1952 static const char* user_assertion_options[] = {
1953   "-da", "-ea", "-disableassertions", "-enableassertions", 0
1954 };
1955 
1956 static const char* system_assertion_options[] = {
1957   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
1958 };
1959 
1960 bool Arguments::parse_uintx(const char* value,
1961                             uintx* uintx_arg,
1962                             uintx min_size) {
1963   uintx n;
1964   if (!parse_integer(value, &n)) {
1965     return false;
1966   }
1967   if (n >= min_size) {
1968     *uintx_arg = n;
1969     return true;
1970   } else {
1971     return false;
1972   }
1973 }
1974 
1975 bool Arguments::create_module_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
1976   assert(is_internal_module_property(prop_name), "unknown module property: '%s'", prop_name);
1977   size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
1978   char* property = AllocateHeap(prop_len, mtArguments);
1979   int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);
1980   if (ret < 0 || ret >= (int)prop_len) {
1981     FreeHeap(property);
1982     return false;
1983   }
1984   // These are not strictly writeable properties as they cannot be set via -Dprop=val. But that
1985   // is enforced by checking is_internal_module_property(). We need the property to be writeable so
1986   // that multiple occurrences of the associated flag just causes the existing property value to be
1987   // replaced ("last option wins"). Otherwise we would need to keep track of the flags and only convert
1988   // to a property after we have finished flag processing.
1989   bool added = add_property(property, WriteableProperty, internal);
1990   FreeHeap(property);
1991   return added;
1992 }
1993 
1994 bool Arguments::create_numbered_module_property(const char* prop_base_name, const char* prop_value, unsigned int count) {
1995   assert(is_internal_module_property(prop_base_name), "unknown module property: '%s'", prop_base_name);
1996   const unsigned int props_count_limit = 1000;
1997   const int max_digits = 3;
1998   const int extra_symbols_count = 3; // includes '.', '=', '\0'
1999 
2000   // Make sure count is < props_count_limit. Otherwise, memory allocation will be too small.
2001   if (count < props_count_limit) {
2002     size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + max_digits + extra_symbols_count;
2003     char* property = AllocateHeap(prop_len, mtArguments);
2004     int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);
2005     if (ret < 0 || ret >= (int)prop_len) {
2006       FreeHeap(property);
2007       jio_fprintf(defaultStream::error_stream(), "Failed to create property %s.%d=%s\n", prop_base_name, count, prop_value);
2008       return false;
2009     }
2010     bool added = add_property(property, UnwriteableProperty, InternalProperty);
2011     FreeHeap(property);
2012     return added;
2013   }
2014 
2015   jio_fprintf(defaultStream::error_stream(), "Property count limit exceeded: %s, limit=%d\n", prop_base_name, props_count_limit);
2016   return false;
2017 }
2018 
2019 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2020                                                   julong* long_arg,
2021                                                   julong min_size,
2022                                                   julong max_size) {
2023   if (!parse_integer(s, long_arg)) return arg_unreadable;
2024   return check_memory_size(*long_arg, min_size, max_size);
2025 }
2026 
2027 // Parse JavaVMInitArgs structure
2028 
2029 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *vm_options_args,
2030                                    const JavaVMInitArgs *java_tool_options_args,
2031                                    const JavaVMInitArgs *java_options_args,
2032                                    const JavaVMInitArgs *cmd_line_args) {
2033   bool patch_mod_javabase = false;
2034 
2035   // Save default settings for some mode flags
2036   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2037   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2038   Arguments::_ClipInlining             = ClipInlining;
2039   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2040 
2041   // Remember the default value of SharedBaseAddress.
2042   Arguments::_default_SharedBaseAddress = SharedBaseAddress;
2043 
2044   // Setup flags for mixed which is the default
2045   set_mode_flags(_mixed);
2046 
2047   // Parse args structure generated from java.base vm options resource
2048   jint result = parse_each_vm_init_arg(vm_options_args, &patch_mod_javabase, JVMFlagOrigin::JIMAGE_RESOURCE);
2049   if (result != JNI_OK) {
2050     return result;
2051   }
2052 
2053   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2054   // variable (if present).
2055   result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR);
2056   if (result != JNI_OK) {
2057     return result;
2058   }
2059 
2060   // Parse args structure generated from the command line flags.
2061   result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, JVMFlagOrigin::COMMAND_LINE);
2062   if (result != JNI_OK) {
2063     return result;
2064   }
2065 
2066   // Parse args structure generated from the _JAVA_OPTIONS environment
2067   // variable (if present) (mimics classic VM)
2068   result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR);
2069   if (result != JNI_OK) {
2070     return result;
2071   }
2072 
2073   // Disable CDS for exploded image
2074   if (!has_jimage()) {
2075     no_shared_spaces("CDS disabled on exploded JDK");
2076   }
2077 
2078   // We need to ensure processor and memory resources have been properly
2079   // configured - which may rely on arguments we just processed - before
2080   // doing the final argument processing. Any argument processing that
2081   // needs to know about processor and memory resources must occur after
2082   // this point.
2083 
2084   os::init_container_support();
2085 
2086   SystemMemoryBarrier::initialize();
2087 
2088   // Do final processing now that all arguments have been parsed
2089   result = finalize_vm_init_args(patch_mod_javabase);
2090   if (result != JNI_OK) {
2091     return result;
2092   }
2093 
2094   return JNI_OK;
2095 }
2096 
2097 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2098 // represents a valid JDWP agent.  is_path==true denotes that we
2099 // are dealing with -agentpath (case where name is a path), otherwise with
2100 // -agentlib
2101 bool valid_jdwp_agent(char *name, bool is_path) {
2102   char *_name;
2103   const char *_jdwp = "jdwp";
2104   size_t _len_jdwp, _len_prefix;
2105 
2106   if (is_path) {
2107     if ((_name = strrchr(name, (int) *os::file_separator())) == nullptr) {
2108       return false;
2109     }
2110 
2111     _name++;  // skip past last path separator
2112     _len_prefix = strlen(JNI_LIB_PREFIX);
2113 
2114     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2115       return false;
2116     }
2117 
2118     _name += _len_prefix;
2119     _len_jdwp = strlen(_jdwp);
2120 
2121     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2122       _name += _len_jdwp;
2123     }
2124     else {
2125       return false;
2126     }
2127 
2128     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2129       return false;
2130     }
2131 
2132     return true;
2133   }
2134 
2135   if (strcmp(name, _jdwp) == 0) {
2136     return true;
2137   }
2138 
2139   return false;
2140 }
2141 
2142 int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {
2143   // --patch-module=<module>=<file>(<pathsep><file>)*
2144   assert(patch_mod_tail != nullptr, "Unexpected null patch-module value");
2145   // Find the equal sign between the module name and the path specification
2146   const char* module_equal = strchr(patch_mod_tail, '=');
2147   if (module_equal == nullptr) {
2148     jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");
2149     return JNI_ERR;
2150   } else {
2151     // Pick out the module name
2152     size_t module_len = module_equal - patch_mod_tail;
2153     char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);
2154     if (module_name != nullptr) {
2155       memcpy(module_name, patch_mod_tail, module_len);
2156       *(module_name + module_len) = '\0';
2157       // The path piece begins one past the module_equal sign
2158       add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);
2159       FREE_C_HEAP_ARRAY(char, module_name);
2160       if (!create_numbered_module_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {
2161         return JNI_ENOMEM;
2162       }
2163     } else {
2164       return JNI_ENOMEM;
2165     }
2166   }
2167   return JNI_OK;
2168 }
2169 
2170 // Parse -Xss memory string parameter and convert to ThreadStackSize in K.
2171 jint Arguments::parse_xss(const JavaVMOption* option, const char* tail, intx* out_ThreadStackSize) {
2172   // The min and max sizes match the values in globals.hpp, but scaled
2173   // with K. The values have been chosen so that alignment with page
2174   // size doesn't change the max value, which makes the conversions
2175   // back and forth between Xss value and ThreadStackSize value easier.
2176   // The values have also been chosen to fit inside a 32-bit signed type.
2177   const julong min_ThreadStackSize = 0;
2178   const julong max_ThreadStackSize = 1 * M;
2179 
2180   // Make sure the above values match the range set in globals.hpp
2181   const JVMTypedFlagLimit<intx>* limit = JVMFlagLimit::get_range_at(FLAG_MEMBER_ENUM(ThreadStackSize))->cast<intx>();
2182   assert(min_ThreadStackSize == static_cast<julong>(limit->min()), "must be");
2183   assert(max_ThreadStackSize == static_cast<julong>(limit->max()), "must be");
2184 
2185   const julong min_size = min_ThreadStackSize * K;
2186   const julong max_size = max_ThreadStackSize * K;
2187 
2188   assert(is_aligned(max_size, os::vm_page_size()), "Implementation assumption");
2189 
2190   julong size = 0;
2191   ArgsRange errcode = parse_memory_size(tail, &size, min_size, max_size);
2192   if (errcode != arg_in_range) {
2193     bool silent = (option == nullptr); // Allow testing to silence error messages
2194     if (!silent) {
2195       jio_fprintf(defaultStream::error_stream(),
2196                   "Invalid thread stack size: %s\n", option->optionString);
2197       describe_range_error(errcode);
2198     }
2199     return JNI_EINVAL;
2200   }
2201 
2202   // Internally track ThreadStackSize in units of 1024 bytes.
2203   const julong size_aligned = align_up(size, K);
2204   assert(size <= size_aligned,
2205          "Overflow: " JULONG_FORMAT " " JULONG_FORMAT,
2206          size, size_aligned);
2207 
2208   const julong size_in_K = size_aligned / K;
2209   assert(size_in_K < (julong)max_intx,
2210          "size_in_K doesn't fit in the type of ThreadStackSize: " JULONG_FORMAT,
2211          size_in_K);
2212 
2213   // Check that code expanding ThreadStackSize to a page aligned number of bytes won't overflow.
2214   const julong max_expanded = align_up(size_in_K * K, os::vm_page_size());
2215   assert(max_expanded < max_uintx && max_expanded >= size_in_K,
2216          "Expansion overflowed: " JULONG_FORMAT " " JULONG_FORMAT,
2217          max_expanded, size_in_K);
2218 
2219   *out_ThreadStackSize = (intx)size_in_K;
2220 
2221   return JNI_OK;
2222 }
2223 
2224 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, JVMFlagOrigin origin) {
2225   // For match_option to return remaining or value part of option string
2226   const char* tail;
2227 
2228   // iterate over arguments
2229   for (int index = 0; index < args->nOptions; index++) {
2230     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2231 
2232     const JavaVMOption* option = args->options + index;
2233 
2234     if (!match_option(option, "-Djava.class.path", &tail) &&
2235         !match_option(option, "-Dsun.java.command", &tail) &&
2236         !match_option(option, "-Dsun.java.launcher", &tail)) {
2237 
2238         // add all jvm options to the jvm_args string. This string
2239         // is used later to set the java.vm.args PerfData string constant.
2240         // the -Djava.class.path and the -Dsun.java.command options are
2241         // omitted from jvm_args string as each have their own PerfData
2242         // string constant object.
2243         build_jvm_args(option->optionString);
2244     }
2245 
2246     // -verbose:[class/module/gc/jni]
2247     if (match_option(option, "-verbose", &tail)) {
2248       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2249         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));
2250         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));
2251       } else if (!strcmp(tail, ":module")) {
2252         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, load));
2253         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, unload));
2254       } else if (!strcmp(tail, ":gc")) {
2255         if (_legacyGCLogging.lastFlag == 0) {
2256           _legacyGCLogging.lastFlag = 1;
2257         }
2258       } else if (!strcmp(tail, ":jni")) {
2259         LogConfiguration::configure_stdout(LogLevel::Debug, true, LOG_TAGS(jni, resolve));
2260       }
2261     // -da / -ea / -disableassertions / -enableassertions
2262     // These accept an optional class/package name separated by a colon, e.g.,
2263     // -da:java.lang.Thread.
2264     } else if (match_option(option, user_assertion_options, &tail, true)) {
2265       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2266       if (*tail == '\0') {
2267         JavaAssertions::setUserClassDefault(enable);
2268       } else {
2269         assert(*tail == ':', "bogus match by match_option()");
2270         JavaAssertions::addOption(tail + 1, enable);
2271       }
2272     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2273     } else if (match_option(option, system_assertion_options, &tail, false)) {
2274       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2275       JavaAssertions::setSystemClassDefault(enable);
2276     // -bootclasspath:
2277     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2278         jio_fprintf(defaultStream::output_stream(),
2279           "-Xbootclasspath is no longer a supported option.\n");
2280         return JNI_EINVAL;
2281     // -bootclasspath/a:
2282     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2283       Arguments::append_sysclasspath(tail);
2284 #if INCLUDE_CDS
2285       MetaspaceShared::disable_optimized_module_handling();
2286       log_info(cds)("optimized module handling: disabled because bootclasspath was appended");
2287 #endif
2288     // -bootclasspath/p:
2289     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2290         jio_fprintf(defaultStream::output_stream(),
2291           "-Xbootclasspath/p is no longer a supported option.\n");
2292         return JNI_EINVAL;
2293     // -Xrun
2294     } else if (match_option(option, "-Xrun", &tail)) {
2295       if (tail != nullptr) {
2296         const char* pos = strchr(tail, ':');
2297         size_t len = (pos == nullptr) ? strlen(tail) : pos - tail;
2298         char* name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2299         jio_snprintf(name, len + 1, "%s", tail);
2300 
2301         char *options = nullptr;
2302         if(pos != nullptr) {
2303           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2304           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);
2305         }
2306 #if !INCLUDE_JVMTI
2307         if (strcmp(name, "jdwp") == 0) {
2308           jio_fprintf(defaultStream::error_stream(),
2309             "Debugging agents are not supported in this VM\n");
2310           return JNI_ERR;
2311         }
2312 #endif // !INCLUDE_JVMTI
2313         JvmtiAgentList::add_xrun(name, options, false);
2314         FREE_C_HEAP_ARRAY(char, name);
2315         FREE_C_HEAP_ARRAY(char, options);
2316       }
2317     } else if (match_option(option, "--add-reads=", &tail)) {
2318       if (!create_numbered_module_property("jdk.module.addreads", tail, addreads_count++)) {
2319         return JNI_ENOMEM;
2320       }
2321     } else if (match_option(option, "--add-exports=", &tail)) {
2322       if (!create_numbered_module_property("jdk.module.addexports", tail, addexports_count++)) {
2323         return JNI_ENOMEM;
2324       }
2325     } else if (match_option(option, "--add-opens=", &tail)) {
2326       if (!create_numbered_module_property("jdk.module.addopens", tail, addopens_count++)) {
2327         return JNI_ENOMEM;
2328       }
2329     } else if (match_option(option, "--add-modules=", &tail)) {
2330       if (!create_numbered_module_property("jdk.module.addmods", tail, addmods_count++)) {
2331         return JNI_ENOMEM;
2332       }
2333     } else if (match_option(option, "--enable-native-access=", &tail)) {
2334       if (!create_numbered_module_property("jdk.module.enable.native.access", tail, enable_native_access_count++)) {
2335         return JNI_ENOMEM;
2336       }
2337     } else if (match_option(option, "--limit-modules=", &tail)) {
2338       if (!create_module_property("jdk.module.limitmods", tail, InternalProperty)) {
2339         return JNI_ENOMEM;
2340       }
2341     } else if (match_option(option, "--module-path=", &tail)) {
2342       if (!create_module_property("jdk.module.path", tail, ExternalProperty)) {
2343         return JNI_ENOMEM;
2344       }
2345     } else if (match_option(option, "--upgrade-module-path=", &tail)) {
2346       if (!create_module_property("jdk.module.upgrade.path", tail, ExternalProperty)) {
2347         return JNI_ENOMEM;
2348       }
2349     } else if (match_option(option, "--patch-module=", &tail)) {
2350       // --patch-module=<module>=<file>(<pathsep><file>)*
2351       int res = process_patch_mod_option(tail, patch_mod_javabase);
2352       if (res != JNI_OK) {
2353         return res;
2354       }
2355     } else if (match_option(option, "--illegal-access=", &tail)) {
2356       char version[256];
2357       JDK_Version::jdk(17).to_string(version, sizeof(version));
2358       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2359     // -agentlib and -agentpath
2360     } else if (match_option(option, "-agentlib:", &tail) ||
2361           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2362       if(tail != nullptr) {
2363         const char* pos = strchr(tail, '=');
2364         char* name;
2365         if (pos == nullptr) {
2366           name = os::strdup_check_oom(tail, mtArguments);
2367         } else {
2368           size_t len = pos - tail;
2369           name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2370           memcpy(name, tail, len);
2371           name[len] = '\0';
2372         }
2373 
2374         char *options = nullptr;
2375         if(pos != nullptr) {
2376           options = os::strdup_check_oom(pos + 1, mtArguments);
2377         }
2378 #if !INCLUDE_JVMTI
2379         if (valid_jdwp_agent(name, is_absolute_path)) {
2380           jio_fprintf(defaultStream::error_stream(),
2381             "Debugging agents are not supported in this VM\n");
2382           return JNI_ERR;
2383         }
2384 #endif // !INCLUDE_JVMTI
2385         JvmtiAgentList::add(name, options, is_absolute_path);
2386         os::free(name);
2387         os::free(options);
2388       }
2389     // -javaagent
2390     } else if (match_option(option, "-javaagent:", &tail)) {
2391 #if !INCLUDE_JVMTI
2392       jio_fprintf(defaultStream::error_stream(),
2393         "Instrumentation agents are not supported in this VM\n");
2394       return JNI_ERR;
2395 #else
2396       if (tail != nullptr) {
2397         size_t length = strlen(tail) + 1;
2398         char *options = NEW_C_HEAP_ARRAY(char, length, mtArguments);
2399         jio_snprintf(options, length, "%s", tail);
2400         JvmtiAgentList::add("instrument", options, false);
2401         FREE_C_HEAP_ARRAY(char, options);
2402 
2403         // java agents need module java.instrument
2404         if (!create_numbered_module_property("jdk.module.addmods", "java.instrument", addmods_count++)) {
2405           return JNI_ENOMEM;
2406         }
2407       }
2408 #endif // !INCLUDE_JVMTI
2409     // --enable_preview
2410     } else if (match_option(option, "--enable-preview")) {
2411       set_enable_preview();
2412     // -Xnoclassgc
2413     } else if (match_option(option, "-Xnoclassgc")) {
2414       if (FLAG_SET_CMDLINE(ClassUnloading, false) != JVMFlag::SUCCESS) {
2415         return JNI_EINVAL;
2416       }
2417     // -Xbatch
2418     } else if (match_option(option, "-Xbatch")) {
2419       if (FLAG_SET_CMDLINE(BackgroundCompilation, false) != JVMFlag::SUCCESS) {
2420         return JNI_EINVAL;
2421       }
2422     // -Xmn for compatibility with other JVM vendors
2423     } else if (match_option(option, "-Xmn", &tail)) {
2424       julong long_initial_young_size = 0;
2425       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2426       if (errcode != arg_in_range) {
2427         jio_fprintf(defaultStream::error_stream(),
2428                     "Invalid initial young generation size: %s\n", option->optionString);
2429         describe_range_error(errcode);
2430         return JNI_EINVAL;
2431       }
2432       if (FLAG_SET_CMDLINE(MaxNewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {
2433         return JNI_EINVAL;
2434       }
2435       if (FLAG_SET_CMDLINE(NewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {
2436         return JNI_EINVAL;
2437       }
2438     // -Xms
2439     } else if (match_option(option, "-Xms", &tail)) {
2440       julong size = 0;
2441       // an initial heap size of 0 means automatically determine
2442       ArgsRange errcode = parse_memory_size(tail, &size, 0);
2443       if (errcode != arg_in_range) {
2444         jio_fprintf(defaultStream::error_stream(),
2445                     "Invalid initial heap size: %s\n", option->optionString);
2446         describe_range_error(errcode);
2447         return JNI_EINVAL;
2448       }
2449       if (FLAG_SET_CMDLINE(MinHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
2450         return JNI_EINVAL;
2451       }
2452       if (FLAG_SET_CMDLINE(InitialHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
2453         return JNI_EINVAL;
2454       }
2455     // -Xmx
2456     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2457       julong long_max_heap_size = 0;
2458       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2459       if (errcode != arg_in_range) {
2460         jio_fprintf(defaultStream::error_stream(),
2461                     "Invalid maximum heap size: %s\n", option->optionString);
2462         describe_range_error(errcode);
2463         return JNI_EINVAL;
2464       }
2465       if (FLAG_SET_CMDLINE(MaxHeapSize, (size_t)long_max_heap_size) != JVMFlag::SUCCESS) {
2466         return JNI_EINVAL;
2467       }
2468     // Xmaxf
2469     } else if (match_option(option, "-Xmaxf", &tail)) {
2470       char* err;
2471       int maxf = (int)(strtod(tail, &err) * 100);
2472       if (*err != '\0' || *tail == '\0') {
2473         jio_fprintf(defaultStream::error_stream(),
2474                     "Bad max heap free percentage size: %s\n",
2475                     option->optionString);
2476         return JNI_EINVAL;
2477       } else {
2478         if (FLAG_SET_CMDLINE(MaxHeapFreeRatio, maxf) != JVMFlag::SUCCESS) {
2479             return JNI_EINVAL;
2480         }
2481       }
2482     // Xminf
2483     } else if (match_option(option, "-Xminf", &tail)) {
2484       char* err;
2485       int minf = (int)(strtod(tail, &err) * 100);
2486       if (*err != '\0' || *tail == '\0') {
2487         jio_fprintf(defaultStream::error_stream(),
2488                     "Bad min heap free percentage size: %s\n",
2489                     option->optionString);
2490         return JNI_EINVAL;
2491       } else {
2492         if (FLAG_SET_CMDLINE(MinHeapFreeRatio, minf) != JVMFlag::SUCCESS) {
2493           return JNI_EINVAL;
2494         }
2495       }
2496     // -Xss
2497     } else if (match_option(option, "-Xss", &tail)) {
2498       intx value = 0;
2499       jint err = parse_xss(option, tail, &value);
2500       if (err != JNI_OK) {
2501         return err;
2502       }
2503       if (FLAG_SET_CMDLINE(ThreadStackSize, value) != JVMFlag::SUCCESS) {
2504         return JNI_EINVAL;
2505       }
2506     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2507                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2508       julong long_ReservedCodeCacheSize = 0;
2509 
2510       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2511       if (errcode != arg_in_range) {
2512         jio_fprintf(defaultStream::error_stream(),
2513                     "Invalid maximum code cache size: %s.\n", option->optionString);
2514         return JNI_EINVAL;
2515       }
2516       if (FLAG_SET_CMDLINE(ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != JVMFlag::SUCCESS) {
2517         return JNI_EINVAL;
2518       }
2519     // -green
2520     } else if (match_option(option, "-green")) {
2521       jio_fprintf(defaultStream::error_stream(),
2522                   "Green threads support not available\n");
2523           return JNI_EINVAL;
2524     // -native
2525     } else if (match_option(option, "-native")) {
2526           // HotSpot always uses native threads, ignore silently for compatibility
2527     // -Xrs
2528     } else if (match_option(option, "-Xrs")) {
2529           // Classic/EVM option, new functionality
2530       if (FLAG_SET_CMDLINE(ReduceSignalUsage, true) != JVMFlag::SUCCESS) {
2531         return JNI_EINVAL;
2532       }
2533       // -Xprof
2534     } else if (match_option(option, "-Xprof")) {
2535       char version[256];
2536       // Obsolete in JDK 10
2537       JDK_Version::jdk(10).to_string(version, sizeof(version));
2538       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2539     // -Xinternalversion
2540     } else if (match_option(option, "-Xinternalversion")) {
2541       jio_fprintf(defaultStream::output_stream(), "%s\n",
2542                   VM_Version::internal_vm_info_string());
2543       vm_exit(0);
2544 #ifndef PRODUCT
2545     // -Xprintflags
2546     } else if (match_option(option, "-Xprintflags")) {
2547       JVMFlag::printFlags(tty, false);
2548       vm_exit(0);
2549 #endif
2550     // -D
2551     } else if (match_option(option, "-D", &tail)) {
2552       const char* value;
2553       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2554             *value!= '\0' && strcmp(value, "\"\"") != 0) {
2555         // abort if -Djava.endorsed.dirs is set
2556         jio_fprintf(defaultStream::output_stream(),
2557           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2558           "in modular form will be supported via the concept of upgradeable modules.\n", value);
2559         return JNI_EINVAL;
2560       }
2561       if (match_option(option, "-Djava.ext.dirs=", &value) &&
2562             *value != '\0' && strcmp(value, "\"\"") != 0) {
2563         // abort if -Djava.ext.dirs is set
2564         jio_fprintf(defaultStream::output_stream(),
2565           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2566         return JNI_EINVAL;
2567       }
2568       // Check for module related properties.  They must be set using the modules
2569       // options. For example: use "--add-modules=java.sql", not
2570       // "-Djdk.module.addmods=java.sql"
2571       if (is_internal_module_property(option->optionString + 2)) {
2572         needs_module_property_warning = true;
2573         continue;
2574       }
2575       if (!add_property(tail)) {
2576         return JNI_ENOMEM;
2577       }
2578       // Out of the box management support
2579       if (match_option(option, "-Dcom.sun.management", &tail)) {
2580 #if INCLUDE_MANAGEMENT
2581         if (FLAG_SET_CMDLINE(ManagementServer, true) != JVMFlag::SUCCESS) {
2582           return JNI_EINVAL;
2583         }
2584         // management agent in module jdk.management.agent
2585         if (!create_numbered_module_property("jdk.module.addmods", "jdk.management.agent", addmods_count++)) {
2586           return JNI_ENOMEM;
2587         }
2588 #else
2589         jio_fprintf(defaultStream::output_stream(),
2590           "-Dcom.sun.management is not supported in this VM.\n");
2591         return JNI_ERR;
2592 #endif
2593       }
2594     // -Xint
2595     } else if (match_option(option, "-Xint")) {
2596           set_mode_flags(_int);
2597     // -Xmixed
2598     } else if (match_option(option, "-Xmixed")) {
2599           set_mode_flags(_mixed);
2600     // -Xcomp
2601     } else if (match_option(option, "-Xcomp")) {
2602       // for testing the compiler; turn off all flags that inhibit compilation
2603           set_mode_flags(_comp);
2604     // -Xshare:dump
2605     } else if (match_option(option, "-Xshare:dump")) {
2606       DumpSharedSpaces = true;
2607     // -Xshare:on
2608     } else if (match_option(option, "-Xshare:on")) {
2609       UseSharedSpaces = true;
2610       RequireSharedSpaces = true;
2611     // -Xshare:auto || -XX:ArchiveClassesAtExit=<archive file>
2612     } else if (match_option(option, "-Xshare:auto")) {
2613       UseSharedSpaces = true;
2614       RequireSharedSpaces = false;
2615       xshare_auto_cmd_line = true;
2616     // -Xshare:off
2617     } else if (match_option(option, "-Xshare:off")) {
2618       UseSharedSpaces = false;
2619       RequireSharedSpaces = false;
2620     // -Xverify
2621     } else if (match_option(option, "-Xverify", &tail)) {
2622       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
2623         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, true) != JVMFlag::SUCCESS) {
2624           return JNI_EINVAL;
2625         }
2626         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {
2627           return JNI_EINVAL;
2628         }
2629       } else if (strcmp(tail, ":remote") == 0) {
2630         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {
2631           return JNI_EINVAL;
2632         }
2633         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {
2634           return JNI_EINVAL;
2635         }
2636       } else if (strcmp(tail, ":none") == 0) {
2637         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {
2638           return JNI_EINVAL;
2639         }
2640         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, false) != JVMFlag::SUCCESS) {
2641           return JNI_EINVAL;
2642         }
2643         warning("Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.");
2644       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
2645         return JNI_EINVAL;
2646       }
2647     // -Xdebug
2648     } else if (match_option(option, "-Xdebug")) {
2649       // note this flag has been used, then ignore
2650       set_xdebug_mode(true);
2651     // -Xnoagent
2652     } else if (match_option(option, "-Xnoagent")) {
2653       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
2654     } else if (match_option(option, "-Xloggc:", &tail)) {
2655       // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
2656       log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
2657       _legacyGCLogging.lastFlag = 2;
2658       _legacyGCLogging.file = os::strdup_check_oom(tail);
2659     } else if (match_option(option, "-Xlog", &tail)) {
2660       bool ret = false;
2661       if (strcmp(tail, ":help") == 0) {
2662         fileStream stream(defaultStream::output_stream());
2663         LogConfiguration::print_command_line_help(&stream);
2664         vm_exit(0);
2665       } else if (strcmp(tail, ":disable") == 0) {
2666         LogConfiguration::disable_logging();
2667         ret = true;
2668       } else if (strcmp(tail, ":async") == 0) {
2669         LogConfiguration::set_async_mode(true);
2670         ret = true;
2671       } else if (*tail == '\0') {
2672         ret = LogConfiguration::parse_command_line_arguments();
2673         assert(ret, "-Xlog without arguments should never fail to parse");
2674       } else if (*tail == ':') {
2675         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
2676       }
2677       if (ret == false) {
2678         jio_fprintf(defaultStream::error_stream(),
2679                     "Invalid -Xlog option '-Xlog%s', see error log for details.\n",
2680                     tail);
2681         return JNI_EINVAL;
2682       }
2683     // JNI hooks
2684     } else if (match_option(option, "-Xcheck", &tail)) {
2685       if (!strcmp(tail, ":jni")) {
2686 #if !INCLUDE_JNI_CHECK
2687         warning("JNI CHECKING is not supported in this VM");
2688 #else
2689         CheckJNICalls = true;
2690 #endif // INCLUDE_JNI_CHECK
2691       } else if (is_bad_option(option, args->ignoreUnrecognized,
2692                                      "check")) {
2693         return JNI_EINVAL;
2694       }
2695     } else if (match_option(option, "vfprintf")) {
2696       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
2697     } else if (match_option(option, "exit")) {
2698       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
2699     } else if (match_option(option, "abort")) {
2700       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
2701     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
2702     // and the last option wins.
2703     } else if (match_option(option, "-XX:+NeverTenure")) {
2704       if (FLAG_SET_CMDLINE(NeverTenure, true) != JVMFlag::SUCCESS) {
2705         return JNI_EINVAL;
2706       }
2707       if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {
2708         return JNI_EINVAL;
2709       }
2710       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, markWord::max_age + 1) != JVMFlag::SUCCESS) {
2711         return JNI_EINVAL;
2712       }
2713     } else if (match_option(option, "-XX:+AlwaysTenure")) {
2714       if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2715         return JNI_EINVAL;
2716       }
2717       if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {
2718         return JNI_EINVAL;
2719       }
2720       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, 0) != JVMFlag::SUCCESS) {
2721         return JNI_EINVAL;
2722       }
2723     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
2724       uintx max_tenuring_thresh = 0;
2725       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
2726         jio_fprintf(defaultStream::error_stream(),
2727                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
2728         return JNI_EINVAL;
2729       }
2730 
2731       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, max_tenuring_thresh) != JVMFlag::SUCCESS) {
2732         return JNI_EINVAL;
2733       }
2734 
2735       if (MaxTenuringThreshold == 0) {
2736         if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2737           return JNI_EINVAL;
2738         }
2739         if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {
2740           return JNI_EINVAL;
2741         }
2742       } else {
2743         if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2744           return JNI_EINVAL;
2745         }
2746         if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {
2747           return JNI_EINVAL;
2748         }
2749       }
2750     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
2751       if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, false) != JVMFlag::SUCCESS) {
2752         return JNI_EINVAL;
2753       }
2754       if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, true) != JVMFlag::SUCCESS) {
2755         return JNI_EINVAL;
2756       }
2757     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
2758       if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, false) != JVMFlag::SUCCESS) {
2759         return JNI_EINVAL;
2760       }
2761       if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, true) != JVMFlag::SUCCESS) {
2762         return JNI_EINVAL;
2763       }
2764     } else if (match_option(option, "-XX:+ErrorFileToStderr")) {
2765       if (FLAG_SET_CMDLINE(ErrorFileToStdout, false) != JVMFlag::SUCCESS) {
2766         return JNI_EINVAL;
2767       }
2768       if (FLAG_SET_CMDLINE(ErrorFileToStderr, true) != JVMFlag::SUCCESS) {
2769         return JNI_EINVAL;
2770       }
2771     } else if (match_option(option, "-XX:+ErrorFileToStdout")) {
2772       if (FLAG_SET_CMDLINE(ErrorFileToStderr, false) != JVMFlag::SUCCESS) {
2773         return JNI_EINVAL;
2774       }
2775       if (FLAG_SET_CMDLINE(ErrorFileToStdout, true) != JVMFlag::SUCCESS) {
2776         return JNI_EINVAL;
2777       }
2778     } else if (match_option(option, "--finalization=", &tail)) {
2779       if (strcmp(tail, "enabled") == 0) {
2780         InstanceKlass::set_finalization_enabled(true);
2781       } else if (strcmp(tail, "disabled") == 0) {
2782         InstanceKlass::set_finalization_enabled(false);
2783       } else {
2784         jio_fprintf(defaultStream::error_stream(),
2785                     "Invalid finalization value '%s', must be 'disabled' or 'enabled'.\n",
2786                     tail);
2787         return JNI_EINVAL;
2788       }
2789 #if !defined(DTRACE_ENABLED)
2790     } else if (match_option(option, "-XX:+DTraceMethodProbes")) {
2791       jio_fprintf(defaultStream::error_stream(),
2792                   "DTraceMethodProbes flag is not applicable for this configuration\n");
2793       return JNI_EINVAL;
2794     } else if (match_option(option, "-XX:+DTraceAllocProbes")) {
2795       jio_fprintf(defaultStream::error_stream(),
2796                   "DTraceAllocProbes flag is not applicable for this configuration\n");
2797       return JNI_EINVAL;
2798     } else if (match_option(option, "-XX:+DTraceMonitorProbes")) {
2799       jio_fprintf(defaultStream::error_stream(),
2800                   "DTraceMonitorProbes flag is not applicable for this configuration\n");
2801       return JNI_EINVAL;
2802 #endif // !defined(DTRACE_ENABLED)
2803 #ifdef ASSERT
2804     } else if (match_option(option, "-XX:+FullGCALot")) {
2805       if (FLAG_SET_CMDLINE(FullGCALot, true) != JVMFlag::SUCCESS) {
2806         return JNI_EINVAL;
2807       }
2808       // disable scavenge before parallel mark-compact
2809       if (FLAG_SET_CMDLINE(ScavengeBeforeFullGC, false) != JVMFlag::SUCCESS) {
2810         return JNI_EINVAL;
2811       }
2812 #endif
2813 #if !INCLUDE_MANAGEMENT
2814     } else if (match_option(option, "-XX:+ManagementServer")) {
2815         jio_fprintf(defaultStream::error_stream(),
2816           "ManagementServer is not supported in this VM.\n");
2817         return JNI_ERR;
2818 #endif // INCLUDE_MANAGEMENT
2819 #if INCLUDE_JVMCI
2820     } else if (match_option(option, "-XX:-EnableJVMCIProduct") || match_option(option, "-XX:-UseGraalJIT")) {
2821       if (EnableJVMCIProduct) {
2822         jio_fprintf(defaultStream::error_stream(),
2823                   "-XX:-EnableJVMCIProduct or -XX:-UseGraalJIT cannot come after -XX:+EnableJVMCIProduct or -XX:+UseGraalJIT\n");
2824         return JNI_EINVAL;
2825       }
2826     } else if (match_option(option, "-XX:+EnableJVMCIProduct") || match_option(option, "-XX:+UseGraalJIT")) {
2827       bool use_graal_jit = match_option(option, "-XX:+UseGraalJIT");
2828       if (use_graal_jit) {
2829         const char* jvmci_compiler = get_property("jvmci.Compiler");
2830         if (jvmci_compiler != nullptr) {
2831           if (strncmp(jvmci_compiler, "graal", strlen("graal")) != 0) {
2832             jio_fprintf(defaultStream::error_stream(),
2833               "Value of jvmci.Compiler incompatible with +UseGraalJIT: %s", jvmci_compiler);
2834             return JNI_ERR;
2835           }
2836         } else if (!add_property("jvmci.Compiler=graal")) {
2837             return JNI_ENOMEM;
2838         }
2839       }
2840 
2841       // Just continue, since "-XX:+EnableJVMCIProduct" or "-XX:+UseGraalJIT" has been specified before
2842       if (EnableJVMCIProduct) {
2843         continue;
2844       }
2845       JVMFlag *jvmciFlag = JVMFlag::find_flag("EnableJVMCIProduct");
2846       // Allow this flag if it has been unlocked.
2847       if (jvmciFlag != nullptr && jvmciFlag->is_unlocked()) {
2848         if (!JVMCIGlobals::enable_jvmci_product_mode(origin, use_graal_jit)) {
2849           jio_fprintf(defaultStream::error_stream(),
2850             "Unable to enable JVMCI in product mode");
2851           return JNI_ERR;
2852         }
2853       }
2854       // The flag was locked so process normally to report that error
2855       else if (!process_argument(use_graal_jit ? "UseGraalJIT" : "EnableJVMCIProduct", args->ignoreUnrecognized, origin)) {
2856         return JNI_EINVAL;
2857       }
2858 #endif // INCLUDE_JVMCI
2859 #if INCLUDE_JFR
2860     } else if (match_jfr_option(&option)) {
2861       return JNI_EINVAL;
2862 #endif
2863     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
2864       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
2865       // already been handled
2866       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
2867           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
2868         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
2869           return JNI_EINVAL;
2870         }
2871       }
2872     // Unknown option
2873     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
2874       return JNI_ERR;
2875     }
2876   }
2877 
2878   // PrintSharedArchiveAndExit will turn on
2879   //   -Xshare:on
2880   //   -Xlog:class+path=info
2881   if (PrintSharedArchiveAndExit) {
2882     UseSharedSpaces = true;
2883     RequireSharedSpaces = true;
2884     LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));
2885   }
2886 
2887   fix_appclasspath();
2888 
2889   return JNI_OK;
2890 }
2891 
2892 void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {
2893   // For java.base check for duplicate --patch-module options being specified on the command line.
2894   // This check is only required for java.base, all other duplicate module specifications
2895   // will be checked during module system initialization.  The module system initialization
2896   // will throw an ExceptionInInitializerError if this situation occurs.
2897   if (strcmp(module_name, JAVA_BASE_NAME) == 0) {
2898     if (*patch_mod_javabase) {
2899       vm_exit_during_initialization("Cannot specify " JAVA_BASE_NAME " more than once to --patch-module");
2900     } else {
2901       *patch_mod_javabase = true;
2902     }
2903   }
2904 
2905   // Create GrowableArray lazily, only if --patch-module has been specified
2906   if (_patch_mod_prefix == nullptr) {
2907     _patch_mod_prefix = new (mtArguments) GrowableArray<ModulePatchPath*>(10, mtArguments);
2908   }
2909 
2910   _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
2911 }
2912 
2913 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
2914 //
2915 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
2916 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
2917 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
2918 // path is treated as the current directory.
2919 //
2920 // This causes problems with CDS, which requires that all directories specified in the classpath
2921 // must be empty. In most cases, applications do NOT want to load classes from the current
2922 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
2923 // scripts compatible with CDS.
2924 void Arguments::fix_appclasspath() {
2925   if (IgnoreEmptyClassPaths) {
2926     const char separator = *os::path_separator();
2927     const char* src = _java_class_path->value();
2928 
2929     // skip over all the leading empty paths
2930     while (*src == separator) {
2931       src ++;
2932     }
2933 
2934     char* copy = os::strdup_check_oom(src, mtArguments);
2935 
2936     // trim all trailing empty paths
2937     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
2938       *tail = '\0';
2939     }
2940 
2941     char from[3] = {separator, separator, '\0'};
2942     char to  [2] = {separator, '\0'};
2943     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
2944       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
2945       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
2946     }
2947 
2948     _java_class_path->set_writeable_value(copy);
2949     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
2950   }
2951 }
2952 
2953 jint Arguments::finalize_vm_init_args(bool patch_mod_javabase) {
2954   // check if the default lib/endorsed directory exists; if so, error
2955   char path[JVM_MAXPATHLEN];
2956   const char* fileSep = os::file_separator();
2957   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
2958 
2959   DIR* dir = os::opendir(path);
2960   if (dir != nullptr) {
2961     jio_fprintf(defaultStream::output_stream(),
2962       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
2963       "in modular form will be supported via the concept of upgradeable modules.\n");
2964     os::closedir(dir);
2965     return JNI_ERR;
2966   }
2967 
2968   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
2969   dir = os::opendir(path);
2970   if (dir != nullptr) {
2971     jio_fprintf(defaultStream::output_stream(),
2972       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
2973       "Use -classpath instead.\n.");
2974     os::closedir(dir);
2975     return JNI_ERR;
2976   }
2977 
2978   // This must be done after all arguments have been processed
2979   // and the container support has been initialized since AggressiveHeap
2980   // relies on the amount of total memory available.
2981   if (AggressiveHeap) {
2982     jint result = set_aggressive_heap_flags();
2983     if (result != JNI_OK) {
2984       return result;
2985     }
2986   }
2987 
2988   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
2989   // but like -Xint, leave compilation thresholds unaffected.
2990   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
2991   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
2992     set_mode_flags(_int);
2993   }
2994 
2995 #ifdef ZERO
2996   // Zero always runs in interpreted mode
2997   set_mode_flags(_int);
2998 #endif
2999 
3000   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3001   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3002     FLAG_SET_ERGO(InitialTenuringThreshold, MaxTenuringThreshold);
3003   }
3004 
3005 #if !COMPILER2_OR_JVMCI
3006   // Don't degrade server performance for footprint
3007   if (FLAG_IS_DEFAULT(UseLargePages) &&
3008       MaxHeapSize < LargePageHeapSizeThreshold) {
3009     // No need for large granularity pages w/small heaps.
3010     // Note that large pages are enabled/disabled for both the
3011     // Java heap and the code cache.
3012     FLAG_SET_DEFAULT(UseLargePages, false);
3013   }
3014 
3015   UNSUPPORTED_OPTION(ProfileInterpreter);
3016 #endif
3017 
3018   // Parse the CompilationMode flag
3019   if (!CompilationModeFlag::initialize()) {
3020     return JNI_ERR;
3021   }
3022 
3023   if (!check_vm_args_consistency()) {
3024     return JNI_ERR;
3025   }
3026 
3027 #if INCLUDE_CDS
3028   if (DumpSharedSpaces) {
3029     // Compiler threads may concurrently update the class metadata (such as method entries), so it's
3030     // unsafe with -Xshare:dump (which modifies the class metadata in place). Let's disable
3031     // compiler just to be safe.
3032     //
3033     // Note: this is not a concern for dynamically dumping shared spaces, which makes a copy of the
3034     // class metadata instead of modifying them in place. The copy is inaccessible to the compiler.
3035     // TODO: revisit the following for the static archive case.
3036     set_mode_flags(_int);
3037 
3038     // String deduplication may cause CDS to iterate the strings in different order from one
3039     // run to another which resulting in non-determinstic CDS archives.
3040     // Disable UseStringDeduplication while dumping CDS archive.
3041     UseStringDeduplication = false;
3042   }
3043 
3044   // RecordDynamicDumpInfo is not compatible with ArchiveClassesAtExit
3045   if (ArchiveClassesAtExit != nullptr && RecordDynamicDumpInfo) {
3046     jio_fprintf(defaultStream::output_stream(),
3047                 "-XX:+RecordDynamicDumpInfo cannot be used with -XX:ArchiveClassesAtExit.\n");
3048     return JNI_ERR;
3049   }
3050 
3051   if (ArchiveClassesAtExit == nullptr && !RecordDynamicDumpInfo) {
3052     DynamicDumpSharedSpaces = false;
3053   } else {
3054     DynamicDumpSharedSpaces = true;
3055   }
3056 
3057   if (AutoCreateSharedArchive) {
3058     if (SharedArchiveFile == nullptr) {
3059       log_warning(cds)("-XX:+AutoCreateSharedArchive requires -XX:SharedArchiveFile");
3060       return JNI_ERR;
3061     }
3062     if (ArchiveClassesAtExit != nullptr) {
3063       log_warning(cds)("-XX:+AutoCreateSharedArchive does not work with ArchiveClassesAtExit");
3064       return JNI_ERR;
3065     }
3066   }
3067 
3068   if (UseSharedSpaces && patch_mod_javabase) {
3069     no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
3070   }
3071   if (UseSharedSpaces && !DumpSharedSpaces && check_unsupported_cds_runtime_properties()) {
3072     UseSharedSpaces = false;
3073   }
3074 
3075   if (DumpSharedSpaces || DynamicDumpSharedSpaces) {
3076     // Always verify non-system classes during CDS dump
3077     if (!BytecodeVerificationRemote) {
3078       BytecodeVerificationRemote = true;
3079       log_info(cds)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");
3080     }
3081   }
3082 #endif
3083 
3084 #ifndef CAN_SHOW_REGISTERS_ON_ASSERT
3085   UNSUPPORTED_OPTION(ShowRegistersOnAssert);
3086 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
3087 
3088 #ifdef _LP64
3089   if (UseCompactObjectHeaders && UseZGC && !ZGenerational) {
3090     if (FLAG_IS_CMDLINE(UseCompactObjectHeaders)) {
3091       warning("Single-generational ZGC does not work with compact object headers, disabling UseCompactObjectHeaders");
3092     }
3093     FLAG_SET_DEFAULT(UseCompactObjectHeaders, false);
3094   }
3095   if (UseCompactObjectHeaders && FLAG_IS_CMDLINE(UseCompressedClassPointers) && !UseCompressedClassPointers) {
3096     warning("Compact object headers require compressed class pointers. Disabling compact object headers.");
3097     FLAG_SET_DEFAULT(UseCompactObjectHeaders, false);
3098   }
3099   if (UseCompactObjectHeaders && LockingMode == LM_LEGACY) {
3100     FLAG_SET_DEFAULT(LockingMode, LM_LIGHTWEIGHT);
3101   }
3102   if (UseCompactObjectHeaders && !UseAltGCForwarding) {
3103     FLAG_SET_DEFAULT(UseAltGCForwarding, true);
3104   }
3105   if (UseCompactObjectHeaders && !UseCompressedClassPointers) {
3106     FLAG_SET_DEFAULT(UseCompressedClassPointers, true);
3107   }
3108 #endif
3109 
3110   return JNI_OK;
3111 }
3112 
3113 // Helper class for controlling the lifetime of JavaVMInitArgs
3114 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3115 // deleted on the destruction of the ScopedVMInitArgs object.
3116 class ScopedVMInitArgs : public StackObj {
3117  private:
3118   JavaVMInitArgs _args;
3119   char*          _container_name;
3120   bool           _is_set;
3121   char*          _vm_options_file_arg;
3122 
3123  public:
3124   ScopedVMInitArgs(const char *container_name) {
3125     _args.version = JNI_VERSION_1_2;
3126     _args.nOptions = 0;
3127     _args.options = nullptr;
3128     _args.ignoreUnrecognized = false;
3129     _container_name = (char *)container_name;
3130     _is_set = false;
3131     _vm_options_file_arg = nullptr;
3132   }
3133 
3134   // Populates the JavaVMInitArgs object represented by this
3135   // ScopedVMInitArgs object with the arguments in options.  The
3136   // allocated memory is deleted by the destructor.  If this method
3137   // returns anything other than JNI_OK, then this object is in a
3138   // partially constructed state, and should be abandoned.
3139   jint set_args(const GrowableArrayView<JavaVMOption>* options) {
3140     _is_set = true;
3141     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3142         JavaVMOption, options->length(), mtArguments);
3143     if (options_arr == nullptr) {
3144       return JNI_ENOMEM;
3145     }
3146     _args.options = options_arr;
3147 
3148     for (int i = 0; i < options->length(); i++) {
3149       options_arr[i] = options->at(i);
3150       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3151       if (options_arr[i].optionString == nullptr) {
3152         // Rely on the destructor to do cleanup.
3153         _args.nOptions = i;
3154         return JNI_ENOMEM;
3155       }
3156     }
3157 
3158     _args.nOptions = options->length();
3159     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3160     return JNI_OK;
3161   }
3162 
3163   JavaVMInitArgs* get()             { return &_args; }
3164   char* container_name()            { return _container_name; }
3165   bool  is_set()                    { return _is_set; }
3166   bool  found_vm_options_file_arg() { return _vm_options_file_arg != nullptr; }
3167   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3168 
3169   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3170     if (_vm_options_file_arg != nullptr) {
3171       os::free(_vm_options_file_arg);
3172     }
3173     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3174   }
3175 
3176   ~ScopedVMInitArgs() {
3177     if (_vm_options_file_arg != nullptr) {
3178       os::free(_vm_options_file_arg);
3179     }
3180     if (_args.options == nullptr) return;
3181     for (int i = 0; i < _args.nOptions; i++) {
3182       os::free(_args.options[i].optionString);
3183     }
3184     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3185   }
3186 
3187   // Insert options into this option list, to replace option at
3188   // vm_options_file_pos (-XX:VMOptionsFile)
3189   jint insert(const JavaVMInitArgs* args,
3190               const JavaVMInitArgs* args_to_insert,
3191               const int vm_options_file_pos) {
3192     assert(_args.options == nullptr, "shouldn't be set yet");
3193     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3194     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3195 
3196     int length = args->nOptions + args_to_insert->nOptions - 1;
3197     // Construct new option array
3198     GrowableArrayCHeap<JavaVMOption, mtArguments> options(length);
3199     for (int i = 0; i < args->nOptions; i++) {
3200       if (i == vm_options_file_pos) {
3201         // insert the new options starting at the same place as the
3202         // -XX:VMOptionsFile option
3203         for (int j = 0; j < args_to_insert->nOptions; j++) {
3204           options.push(args_to_insert->options[j]);
3205         }
3206       } else {
3207         options.push(args->options[i]);
3208       }
3209     }
3210     // make into options array
3211     return set_args(&options);
3212   }
3213 };
3214 
3215 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3216   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3217 }
3218 
3219 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3220   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3221 }
3222 
3223 jint Arguments::parse_options_environment_variable(const char* name,
3224                                                    ScopedVMInitArgs* vm_args) {
3225   char *buffer = ::getenv(name);
3226 
3227   // Don't check this environment variable if user has special privileges
3228   // (e.g. unix su command).
3229   if (buffer == nullptr || os::have_special_privileges()) {
3230     return JNI_OK;
3231   }
3232 
3233   if ((buffer = os::strdup(buffer)) == nullptr) {
3234     return JNI_ENOMEM;
3235   }
3236 
3237   jio_fprintf(defaultStream::error_stream(),
3238               "Picked up %s: %s\n", name, buffer);
3239 
3240   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3241 
3242   os::free(buffer);
3243   return retcode;
3244 }
3245 
3246 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3247   // read file into buffer
3248   int fd = ::open(file_name, O_RDONLY);
3249   if (fd < 0) {
3250     jio_fprintf(defaultStream::error_stream(),
3251                 "Could not open options file '%s'\n",
3252                 file_name);
3253     return JNI_ERR;
3254   }
3255 
3256   struct stat stbuf;
3257   int retcode = os::stat(file_name, &stbuf);
3258   if (retcode != 0) {
3259     jio_fprintf(defaultStream::error_stream(),
3260                 "Could not stat options file '%s'\n",
3261                 file_name);
3262     ::close(fd);
3263     return JNI_ERR;
3264   }
3265 
3266   if (stbuf.st_size == 0) {
3267     // tell caller there is no option data and that is ok
3268     ::close(fd);
3269     return JNI_OK;
3270   }
3271 
3272   // '+ 1' for null termination even with max bytes
3273   size_t bytes_alloc = stbuf.st_size + 1;
3274 
3275   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3276   if (nullptr == buf) {
3277     jio_fprintf(defaultStream::error_stream(),
3278                 "Could not allocate read buffer for options file parse\n");
3279     ::close(fd);
3280     return JNI_ENOMEM;
3281   }
3282 
3283   memset(buf, 0, bytes_alloc);
3284 
3285   // Fill buffer
3286   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3287   ::close(fd);
3288   if (bytes_read < 0) {
3289     FREE_C_HEAP_ARRAY(char, buf);
3290     jio_fprintf(defaultStream::error_stream(),
3291                 "Could not read options file '%s'\n", file_name);
3292     return JNI_ERR;
3293   }
3294 
3295   if (bytes_read == 0) {
3296     // tell caller there is no option data and that is ok
3297     FREE_C_HEAP_ARRAY(char, buf);
3298     return JNI_OK;
3299   }
3300 
3301   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3302 
3303   FREE_C_HEAP_ARRAY(char, buf);
3304   return retcode;
3305 }
3306 
3307 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3308   // Construct option array
3309   GrowableArrayCHeap<JavaVMOption, mtArguments> options(2);
3310 
3311   // some pointers to help with parsing
3312   char *buffer_end = buffer + buf_len;
3313   char *opt_hd = buffer;
3314   char *wrt = buffer;
3315   char *rd = buffer;
3316 
3317   // parse all options
3318   while (rd < buffer_end) {
3319     // skip leading white space from the input string
3320     while (rd < buffer_end && isspace(*rd)) {
3321       rd++;
3322     }
3323 
3324     if (rd >= buffer_end) {
3325       break;
3326     }
3327 
3328     // Remember this is where we found the head of the token.
3329     opt_hd = wrt;
3330 
3331     // Tokens are strings of non white space characters separated
3332     // by one or more white spaces.
3333     while (rd < buffer_end && !isspace(*rd)) {
3334       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3335         int quote = *rd;                    // matching quote to look for
3336         rd++;                               // don't copy open quote
3337         while (rd < buffer_end && *rd != quote) {
3338                                             // include everything (even spaces)
3339                                             // up until the close quote
3340           *wrt++ = *rd++;                   // copy to option string
3341         }
3342 
3343         if (rd < buffer_end) {
3344           rd++;                             // don't copy close quote
3345         } else {
3346                                             // did not see closing quote
3347           jio_fprintf(defaultStream::error_stream(),
3348                       "Unmatched quote in %s\n", name);
3349           return JNI_ERR;
3350         }
3351       } else {
3352         *wrt++ = *rd++;                     // copy to option string
3353       }
3354     }
3355 
3356     // steal a white space character and set it to null
3357     *wrt++ = '\0';
3358     // We now have a complete token
3359 
3360     JavaVMOption option;
3361     option.optionString = opt_hd;
3362     option.extraInfo = nullptr;
3363 
3364     options.append(option);                // Fill in option
3365 
3366     rd++;  // Advance to next character
3367   }
3368 
3369   // Fill out JavaVMInitArgs structure.
3370   return vm_args->set_args(&options);
3371 }
3372 
3373 void Arguments::set_shared_spaces_flags_and_archive_paths() {
3374   if (DumpSharedSpaces) {
3375     if (RequireSharedSpaces) {
3376       warning("Cannot dump shared archive while using shared archive");
3377     }
3378     UseSharedSpaces = false;
3379   }
3380 #if INCLUDE_CDS
3381   // Initialize shared archive paths which could include both base and dynamic archive paths
3382   // This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.
3383   //
3384   // UseSharedSpaces may be disabled if -XX:SharedArchiveFile is invalid.
3385   if (DumpSharedSpaces || UseSharedSpaces) {
3386     init_shared_archive_paths();
3387   }
3388 #endif  // INCLUDE_CDS
3389 }
3390 
3391 #if INCLUDE_CDS
3392 // Sharing support
3393 // Construct the path to the archive
3394 char* Arguments::get_default_shared_archive_path() {
3395   if (_default_shared_archive_path == nullptr) {
3396     char jvm_path[JVM_MAXPATHLEN];
3397     os::jvm_path(jvm_path, sizeof(jvm_path));
3398     char *end = strrchr(jvm_path, *os::file_separator());
3399     if (end != nullptr) *end = '\0';
3400     stringStream tmp;
3401     tmp.print("%s%sclasses", jvm_path, os::file_separator());
3402 #ifdef _LP64
3403     if (!UseCompressedOops) {
3404       tmp.print_raw("_nocoops");
3405     }
3406     if (UseCompactObjectHeaders) {
3407       // Note that generation of xxx_coh.jsa variants require
3408       // --enable-cds-archive-coh at build time
3409       tmp.print_raw("_coh");
3410     }
3411 #endif
3412     tmp.print_raw(".jsa");
3413     _default_shared_archive_path = os::strdup(tmp.base());
3414   }
3415   return _default_shared_archive_path;
3416 }
3417 
3418 int Arguments::num_archives(const char* archive_path) {
3419   if (archive_path == nullptr) {
3420     return 0;
3421   }
3422   int npaths = 1;
3423   char* p = (char*)archive_path;
3424   while (*p != '\0') {
3425     if (*p == os::path_separator()[0]) {
3426       npaths++;
3427     }
3428     p++;
3429   }
3430   return npaths;
3431 }
3432 
3433 void Arguments::extract_shared_archive_paths(const char* archive_path,
3434                                          char** base_archive_path,
3435                                          char** top_archive_path) {
3436   char* begin_ptr = (char*)archive_path;
3437   char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);
3438   if (end_ptr == nullptr || end_ptr == begin_ptr) {
3439     vm_exit_during_initialization("Base archive was not specified", archive_path);
3440   }
3441   size_t len = end_ptr - begin_ptr;
3442   char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
3443   strncpy(cur_path, begin_ptr, len);
3444   cur_path[len] = '\0';
3445   *base_archive_path = cur_path;
3446 
3447   begin_ptr = ++end_ptr;
3448   if (*begin_ptr == '\0') {
3449     vm_exit_during_initialization("Top archive was not specified", archive_path);
3450   }
3451   end_ptr = strchr(begin_ptr, '\0');
3452   assert(end_ptr != nullptr, "sanity");
3453   len = end_ptr - begin_ptr;
3454   cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
3455   strncpy(cur_path, begin_ptr, len + 1);
3456   *top_archive_path = cur_path;
3457 }
3458 
3459 void Arguments::init_shared_archive_paths() {
3460   if (ArchiveClassesAtExit != nullptr) {
3461     assert(!RecordDynamicDumpInfo, "already checked");
3462     if (DumpSharedSpaces) {
3463       vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");
3464     }
3465     check_unsupported_dumping_properties();
3466 
3467     if (os::same_files(get_default_shared_archive_path(), ArchiveClassesAtExit)) {
3468       vm_exit_during_initialization(
3469         "Cannot specify the default CDS archive for -XX:ArchiveClassesAtExit", get_default_shared_archive_path());
3470     }
3471   }
3472 
3473   if (SharedArchiveFile == nullptr) {
3474     SharedArchivePath = get_default_shared_archive_path();
3475   } else {
3476     int archives = num_archives(SharedArchiveFile);
3477     assert(archives > 0, "must be");
3478 
3479     if (is_dumping_archive() && archives > 1) {
3480       vm_exit_during_initialization(
3481         "Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");
3482     }
3483 
3484     if (DumpSharedSpaces) {
3485       assert(archives == 1, "must be");
3486       // Static dump is simple: only one archive is allowed in SharedArchiveFile. This file
3487       // will be overwritten no matter regardless of its contents
3488       SharedArchivePath = os::strdup_check_oom(SharedArchiveFile, mtArguments);
3489     } else {
3490       // SharedArchiveFile may specify one or two files. In case (c), the path for base.jsa
3491       // is read from top.jsa
3492       //    (a) 1 file:  -XX:SharedArchiveFile=base.jsa
3493       //    (b) 2 files: -XX:SharedArchiveFile=base.jsa:top.jsa
3494       //    (c) 2 files: -XX:SharedArchiveFile=top.jsa
3495       //
3496       // However, if either RecordDynamicDumpInfo or ArchiveClassesAtExit is used, we do not
3497       // allow cases (b) and (c). Case (b) is already checked above.
3498 
3499       if (archives > 2) {
3500         vm_exit_during_initialization(
3501           "Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");
3502       }
3503       if (archives == 1) {
3504         char* base_archive_path = nullptr;
3505         bool success =
3506           FileMapInfo::get_base_archive_name_from_header(SharedArchiveFile, &base_archive_path);
3507         if (!success) {
3508           // If +AutoCreateSharedArchive and the specified shared archive does not exist,
3509           // regenerate the dynamic archive base on default archive.
3510           if (AutoCreateSharedArchive && !os::file_exists(SharedArchiveFile)) {
3511             DynamicDumpSharedSpaces = true;
3512             ArchiveClassesAtExit = const_cast<char *>(SharedArchiveFile);
3513             SharedArchivePath = get_default_shared_archive_path();
3514             SharedArchiveFile = nullptr;
3515           } else {
3516             if (AutoCreateSharedArchive) {
3517               warning("-XX:+AutoCreateSharedArchive is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
3518               AutoCreateSharedArchive = false;
3519             }
3520             no_shared_spaces("invalid archive");
3521           }
3522         } else if (base_archive_path == nullptr) {
3523           // User has specified a single archive, which is a static archive.
3524           SharedArchivePath = const_cast<char *>(SharedArchiveFile);
3525         } else {
3526           // User has specified a single archive, which is a dynamic archive.
3527           SharedDynamicArchivePath = const_cast<char *>(SharedArchiveFile);
3528           SharedArchivePath = base_archive_path; // has been c-heap allocated.
3529         }
3530       } else {
3531         extract_shared_archive_paths((const char*)SharedArchiveFile,
3532                                       &SharedArchivePath, &SharedDynamicArchivePath);
3533         if (SharedArchivePath == nullptr) {
3534           assert(SharedDynamicArchivePath == nullptr, "must be");
3535           no_shared_spaces("invalid archive");
3536         }
3537       }
3538 
3539       if (SharedDynamicArchivePath != nullptr) {
3540         // Check for case (c)
3541         if (RecordDynamicDumpInfo) {
3542           vm_exit_during_initialization("-XX:+RecordDynamicDumpInfo is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
3543                                         SharedArchiveFile);
3544         }
3545         if (ArchiveClassesAtExit != nullptr) {
3546           vm_exit_during_initialization("-XX:ArchiveClassesAtExit is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
3547                                         SharedArchiveFile);
3548         }
3549       }
3550 
3551       if (ArchiveClassesAtExit != nullptr && os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {
3552           vm_exit_during_initialization(
3553             "Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",
3554             SharedArchiveFile);
3555       }
3556     }
3557   }
3558 }
3559 #endif // INCLUDE_CDS
3560 
3561 #ifndef PRODUCT
3562 // Determine whether LogVMOutput should be implicitly turned on.
3563 static bool use_vm_log() {
3564   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3565       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3566       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3567       PrintAssembly || TraceDeoptimization ||
3568       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3569     return true;
3570   }
3571 
3572 #ifdef COMPILER1
3573   if (PrintC1Statistics) {
3574     return true;
3575   }
3576 #endif // COMPILER1
3577 
3578 #ifdef COMPILER2
3579   if (PrintOptoAssembly || PrintOptoStatistics) {
3580     return true;
3581   }
3582 #endif // COMPILER2
3583 
3584   return false;
3585 }
3586 
3587 #endif // PRODUCT
3588 
3589 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3590   for (int index = 0; index < args->nOptions; index++) {
3591     const JavaVMOption* option = args->options + index;
3592     const char* tail;
3593     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3594       return true;
3595     }
3596   }
3597   return false;
3598 }
3599 
3600 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3601                                        const char* vm_options_file,
3602                                        const int vm_options_file_pos,
3603                                        ScopedVMInitArgs* vm_options_file_args,
3604                                        ScopedVMInitArgs* args_out) {
3605   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
3606   if (code != JNI_OK) {
3607     return code;
3608   }
3609 
3610   if (vm_options_file_args->get()->nOptions < 1) {
3611     return JNI_OK;
3612   }
3613 
3614   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
3615     jio_fprintf(defaultStream::error_stream(),
3616                 "A VM options file may not refer to a VM options file. "
3617                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
3618                 "options file '%s' in options container '%s' is an error.\n",
3619                 vm_options_file_args->vm_options_file_arg(),
3620                 vm_options_file_args->container_name());
3621     return JNI_EINVAL;
3622   }
3623 
3624   return args_out->insert(args, vm_options_file_args->get(),
3625                           vm_options_file_pos);
3626 }
3627 
3628 // Expand -XX:VMOptionsFile found in args_in as needed.
3629 // mod_args and args_out parameters may return values as needed.
3630 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
3631                                             ScopedVMInitArgs* mod_args,
3632                                             JavaVMInitArgs** args_out) {
3633   jint code = match_special_option_and_act(args_in, mod_args);
3634   if (code != JNI_OK) {
3635     return code;
3636   }
3637 
3638   if (mod_args->is_set()) {
3639     // args_in contains -XX:VMOptionsFile and mod_args contains the
3640     // original options from args_in along with the options expanded
3641     // from the VMOptionsFile. Return a short-hand to the caller.
3642     *args_out = mod_args->get();
3643   } else {
3644     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
3645   }
3646   return JNI_OK;
3647 }
3648 
3649 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3650                                              ScopedVMInitArgs* args_out) {
3651   // Remaining part of option string
3652   const char* tail;
3653   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
3654 
3655   for (int index = 0; index < args->nOptions; index++) {
3656     const JavaVMOption* option = args->options + index;
3657     if (match_option(option, "-XX:Flags=", &tail)) {
3658       Arguments::set_jvm_flags_file(tail);
3659       continue;
3660     }
3661     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3662       if (vm_options_file_args.found_vm_options_file_arg()) {
3663         jio_fprintf(defaultStream::error_stream(),
3664                     "The option '%s' is already specified in the options "
3665                     "container '%s' so the specification of '%s' in the "
3666                     "same options container is an error.\n",
3667                     vm_options_file_args.vm_options_file_arg(),
3668                     vm_options_file_args.container_name(),
3669                     option->optionString);
3670         return JNI_EINVAL;
3671       }
3672       vm_options_file_args.set_vm_options_file_arg(option->optionString);
3673       // If there's a VMOptionsFile, parse that
3674       jint code = insert_vm_options_file(args, tail, index,
3675                                          &vm_options_file_args, args_out);
3676       if (code != JNI_OK) {
3677         return code;
3678       }
3679       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
3680       if (args_out->is_set()) {
3681         // The VMOptions file inserted some options so switch 'args'
3682         // to the new set of options, and continue processing which
3683         // preserves "last option wins" semantics.
3684         args = args_out->get();
3685         // The first option from the VMOptionsFile replaces the
3686         // current option.  So we back track to process the
3687         // replacement option.
3688         index--;
3689       }
3690       continue;
3691     }
3692     if (match_option(option, "-XX:+PrintVMOptions")) {
3693       PrintVMOptions = true;
3694       continue;
3695     }
3696     if (match_option(option, "-XX:-PrintVMOptions")) {
3697       PrintVMOptions = false;
3698       continue;
3699     }
3700     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3701       IgnoreUnrecognizedVMOptions = true;
3702       continue;
3703     }
3704     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3705       IgnoreUnrecognizedVMOptions = false;
3706       continue;
3707     }
3708     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3709       JVMFlag::printFlags(tty, false);
3710       vm_exit(0);
3711     }
3712 
3713 #ifndef PRODUCT
3714     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3715       JVMFlag::printFlags(tty, true);
3716       vm_exit(0);
3717     }
3718 #endif
3719   }
3720   return JNI_OK;
3721 }
3722 
3723 static void print_options(const JavaVMInitArgs *args) {
3724   const char* tail;
3725   for (int index = 0; index < args->nOptions; index++) {
3726     const JavaVMOption *option = args->options + index;
3727     if (match_option(option, "-XX:", &tail)) {
3728       logOption(tail);
3729     }
3730   }
3731 }
3732 
3733 bool Arguments::handle_deprecated_print_gc_flags() {
3734   if (PrintGC) {
3735     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
3736   }
3737   if (PrintGCDetails) {
3738     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
3739   }
3740 
3741   if (_legacyGCLogging.lastFlag == 2) {
3742     // -Xloggc was used to specify a filename
3743     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
3744 
3745     LogTarget(Error, logging) target;
3746     LogStream errstream(target);
3747     return LogConfiguration::parse_log_arguments(_legacyGCLogging.file, gc_conf, nullptr, nullptr, &errstream);
3748   } else if (PrintGC || PrintGCDetails || (_legacyGCLogging.lastFlag == 1)) {
3749     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
3750   }
3751   return true;
3752 }
3753 
3754 static void apply_debugger_ergo() {
3755 #ifndef PRODUCT
3756   // UseDebuggerErgo is notproduct
3757   if (ReplayCompiles) {
3758     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo, true);
3759   }
3760 #endif
3761 
3762 #ifndef PRODUCT
3763   if (UseDebuggerErgo) {
3764     // Turn on sub-flags
3765     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo1, true);
3766     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo2, true);
3767   }
3768 #endif
3769 
3770   if (UseDebuggerErgo2) {
3771     // Debugging with limited number of CPUs
3772     FLAG_SET_ERGO_IF_DEFAULT(UseNUMA, false);
3773     FLAG_SET_ERGO_IF_DEFAULT(ConcGCThreads, 1);
3774     FLAG_SET_ERGO_IF_DEFAULT(ParallelGCThreads, 1);
3775     FLAG_SET_ERGO_IF_DEFAULT(CICompilerCount, 2);
3776   }
3777 }
3778 
3779 // Parse entry point called from JNI_CreateJavaVM
3780 
3781 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
3782   assert(verify_special_jvm_flags(false), "deprecated and obsolete flag table inconsistent");
3783   JVMFlag::check_all_flag_declarations();
3784 
3785   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3786   const char* hotspotrc = ".hotspotrc";
3787   bool settings_file_specified = false;
3788   bool needs_hotspotrc_warning = false;
3789   ScopedVMInitArgs initial_vm_options_args("");
3790   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3791   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
3792 
3793   // Pointers to current working set of containers
3794   JavaVMInitArgs* cur_cmd_args;
3795   JavaVMInitArgs* cur_vm_options_args;
3796   JavaVMInitArgs* cur_java_options_args;
3797   JavaVMInitArgs* cur_java_tool_options_args;
3798 
3799   // Containers for modified/expanded options
3800   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
3801   ScopedVMInitArgs mod_vm_options_args("vm_options_args");
3802   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3803   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
3804 
3805 
3806   jint code =
3807       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
3808   if (code != JNI_OK) {
3809     return code;
3810   }
3811 
3812   code = parse_java_options_environment_variable(&initial_java_options_args);
3813   if (code != JNI_OK) {
3814     return code;
3815   }
3816 
3817   // Parse the options in the /java.base/jdk/internal/vm/options resource, if present
3818   char *vmoptions = ClassLoader::lookup_vm_options();
3819   if (vmoptions != nullptr) {
3820     code = parse_options_buffer("vm options resource", vmoptions, strlen(vmoptions), &initial_vm_options_args);
3821     FREE_C_HEAP_ARRAY(char, vmoptions);
3822     if (code != JNI_OK) {
3823       return code;
3824     }
3825   }
3826 
3827   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
3828                                      &mod_java_tool_options_args,
3829                                      &cur_java_tool_options_args);
3830   if (code != JNI_OK) {
3831     return code;
3832   }
3833 
3834   code = expand_vm_options_as_needed(initial_cmd_args,
3835                                      &mod_cmd_args,
3836                                      &cur_cmd_args);
3837   if (code != JNI_OK) {
3838     return code;
3839   }
3840 
3841   code = expand_vm_options_as_needed(initial_java_options_args.get(),
3842                                      &mod_java_options_args,
3843                                      &cur_java_options_args);
3844   if (code != JNI_OK) {
3845     return code;
3846   }
3847 
3848   code = expand_vm_options_as_needed(initial_vm_options_args.get(),
3849                                      &mod_vm_options_args,
3850                                      &cur_vm_options_args);
3851   if (code != JNI_OK) {
3852     return code;
3853   }
3854 
3855   const char* flags_file = Arguments::get_jvm_flags_file();
3856   settings_file_specified = (flags_file != nullptr);
3857 
3858   if (IgnoreUnrecognizedVMOptions) {
3859     cur_cmd_args->ignoreUnrecognized = true;
3860     cur_java_tool_options_args->ignoreUnrecognized = true;
3861     cur_java_options_args->ignoreUnrecognized = true;
3862   }
3863 
3864   // Parse specified settings file
3865   if (settings_file_specified) {
3866     if (!process_settings_file(flags_file, true,
3867                                cur_cmd_args->ignoreUnrecognized)) {
3868       return JNI_EINVAL;
3869     }
3870   } else {
3871 #ifdef ASSERT
3872     // Parse default .hotspotrc settings file
3873     if (!process_settings_file(".hotspotrc", false,
3874                                cur_cmd_args->ignoreUnrecognized)) {
3875       return JNI_EINVAL;
3876     }
3877 #else
3878     struct stat buf;
3879     if (os::stat(hotspotrc, &buf) == 0) {
3880       needs_hotspotrc_warning = true;
3881     }
3882 #endif
3883   }
3884 
3885   if (PrintVMOptions) {
3886     print_options(cur_java_tool_options_args);
3887     print_options(cur_cmd_args);
3888     print_options(cur_java_options_args);
3889   }
3890 
3891   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
3892   jint result = parse_vm_init_args(cur_vm_options_args,
3893                                    cur_java_tool_options_args,
3894                                    cur_java_options_args,
3895                                    cur_cmd_args);
3896 
3897   if (result != JNI_OK) {
3898     return result;
3899   }
3900 
3901   // Delay warning until here so that we've had a chance to process
3902   // the -XX:-PrintWarnings flag
3903   if (needs_hotspotrc_warning) {
3904     warning("%s file is present but has been ignored.  "
3905             "Run with -XX:Flags=%s to load the file.",
3906             hotspotrc, hotspotrc);
3907   }
3908 
3909   if (needs_module_property_warning) {
3910     warning("Ignoring system property options whose names match the '-Djdk.module.*'."
3911             " names that are reserved for internal use.");
3912   }
3913 
3914 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
3915   UNSUPPORTED_OPTION(UseLargePages);
3916 #endif
3917 
3918 #if defined(AIX)
3919   UNSUPPORTED_OPTION_NULL(AllocateHeapAt);
3920 #endif
3921 
3922 #ifndef PRODUCT
3923   if (TraceBytecodesAt != 0) {
3924     TraceBytecodes = true;
3925   }
3926   if (CountCompiledCalls) {
3927     if (UseCounterDecay) {
3928       warning("UseCounterDecay disabled because CountCalls is set");
3929       UseCounterDecay = false;
3930     }
3931   }
3932 #endif // PRODUCT
3933 
3934   if (ScavengeRootsInCode == 0) {
3935     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3936       warning("Forcing ScavengeRootsInCode non-zero");
3937     }
3938     ScavengeRootsInCode = 1;
3939   }
3940 
3941   if (!handle_deprecated_print_gc_flags()) {
3942     return JNI_EINVAL;
3943   }
3944 
3945   // Set object alignment values.
3946   set_object_alignment();
3947 
3948 #if !INCLUDE_CDS
3949   if (DumpSharedSpaces || RequireSharedSpaces) {
3950     jio_fprintf(defaultStream::error_stream(),
3951       "Shared spaces are not supported in this VM\n");
3952     return JNI_ERR;
3953   }
3954   if (DumpLoadedClassList != nullptr) {
3955     jio_fprintf(defaultStream::error_stream(),
3956       "DumpLoadedClassList is not supported in this VM\n");
3957     return JNI_ERR;
3958   }
3959   if ((UseSharedSpaces && xshare_auto_cmd_line) ||
3960       log_is_enabled(Info, cds)) {
3961     warning("Shared spaces are not supported in this VM");
3962     UseSharedSpaces = false;
3963     LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(cds));
3964   }
3965   no_shared_spaces("CDS Disabled");
3966 #endif // INCLUDE_CDS
3967 
3968   // Verify NMT arguments
3969   const NMT_TrackingLevel lvl = NMTUtil::parse_tracking_level(NativeMemoryTracking);
3970   if (lvl == NMT_unknown) {
3971     jio_fprintf(defaultStream::error_stream(),
3972                 "Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", nullptr);
3973     return JNI_ERR;
3974   }
3975   if (PrintNMTStatistics && lvl == NMT_off) {
3976     warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
3977     FLAG_SET_DEFAULT(PrintNMTStatistics, false);
3978   }
3979 
3980   bool trace_dependencies = log_is_enabled(Debug, dependencies);
3981   if (trace_dependencies && VerifyDependencies) {
3982     warning("dependency logging results may be inflated by VerifyDependencies");
3983   }
3984 
3985   apply_debugger_ergo();
3986 
3987   if (log_is_enabled(Info, arguments)) {
3988     LogStream st(Log(arguments)::info());
3989     Arguments::print_on(&st);
3990   }
3991 
3992   return JNI_OK;
3993 }
3994 
3995 jint Arguments::apply_ergo() {
3996   // Set flags based on ergonomics.
3997   jint result = set_ergonomics_flags();
3998   if (result != JNI_OK) return result;
3999 
4000   // Set heap size based on available physical memory
4001   set_heap_size();
4002 
4003   GCConfig::arguments()->initialize();
4004 
4005   set_shared_spaces_flags_and_archive_paths();
4006 
4007   // Initialize Metaspace flags and alignments
4008   Metaspace::ergo_initialize();
4009 
4010   if (!StringDedup::ergo_initialize()) {
4011     return JNI_EINVAL;
4012   }
4013 
4014   // Set compiler flags after GC is selected and GC specific
4015   // flags (LoopStripMiningIter) are set.
4016   CompilerConfig::ergo_initialize();
4017 
4018   // Set bytecode rewriting flags
4019   set_bytecode_flags();
4020 
4021   // Set flags if aggressive optimization flags are enabled
4022   jint code = set_aggressive_opts_flags();
4023   if (code != JNI_OK) {
4024     return code;
4025   }
4026 
4027 #ifdef ZERO
4028   // Clear flags not supported on zero.
4029   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4030 #endif // ZERO
4031 
4032   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4033     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4034     DebugNonSafepoints = true;
4035   }
4036 
4037   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4038     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4039   }
4040 
4041   // Treat the odd case where local verification is enabled but remote
4042   // verification is not as if both were enabled.
4043   if (BytecodeVerificationLocal && !BytecodeVerificationRemote) {
4044     log_info(verification)("Turning on remote verification because local verification is on");
4045     FLAG_SET_DEFAULT(BytecodeVerificationRemote, true);
4046   }
4047 
4048 #ifndef PRODUCT
4049   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4050     if (use_vm_log()) {
4051       LogVMOutput = true;
4052     }
4053   }
4054 #endif // PRODUCT
4055 
4056   if (PrintCommandLineFlags) {
4057     JVMFlag::printSetFlags(tty);
4058   }
4059 
4060 #ifdef COMPILER2
4061   if (!FLAG_IS_DEFAULT(EnableVectorSupport) && !EnableVectorSupport) {
4062     if (!FLAG_IS_DEFAULT(EnableVectorReboxing) && EnableVectorReboxing) {
4063       warning("Disabling EnableVectorReboxing since EnableVectorSupport is turned off.");
4064     }
4065     FLAG_SET_DEFAULT(EnableVectorReboxing, false);
4066 
4067     if (!FLAG_IS_DEFAULT(EnableVectorAggressiveReboxing) && EnableVectorAggressiveReboxing) {
4068       if (!EnableVectorReboxing) {
4069         warning("Disabling EnableVectorAggressiveReboxing since EnableVectorReboxing is turned off.");
4070       } else {
4071         warning("Disabling EnableVectorAggressiveReboxing since EnableVectorSupport is turned off.");
4072       }
4073     }
4074     FLAG_SET_DEFAULT(EnableVectorAggressiveReboxing, false);
4075 
4076     if (!FLAG_IS_DEFAULT(UseVectorStubs) && UseVectorStubs) {
4077       warning("Disabling UseVectorStubs since EnableVectorSupport is turned off.");
4078     }
4079     FLAG_SET_DEFAULT(UseVectorStubs, false);
4080   }
4081 #endif // COMPILER2
4082 
4083   if (FLAG_IS_CMDLINE(DiagnoseSyncOnValueBasedClasses)) {
4084     if (DiagnoseSyncOnValueBasedClasses == ObjectSynchronizer::LOG_WARNING && !log_is_enabled(Info, valuebasedclasses)) {
4085       LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(valuebasedclasses));
4086     }
4087   }
4088   return JNI_OK;
4089 }
4090 
4091 jint Arguments::adjust_after_os() {
4092   if (UseNUMA) {
4093     if (UseParallelGC) {
4094       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4095          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4096       }
4097     }
4098   }
4099   return JNI_OK;
4100 }
4101 
4102 int Arguments::PropertyList_count(SystemProperty* pl) {
4103   int count = 0;
4104   while(pl != nullptr) {
4105     count++;
4106     pl = pl->next();
4107   }
4108   return count;
4109 }
4110 
4111 // Return the number of readable properties.
4112 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
4113   int count = 0;
4114   while(pl != nullptr) {
4115     if (pl->readable()) {
4116       count++;
4117     }
4118     pl = pl->next();
4119   }
4120   return count;
4121 }
4122 
4123 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4124   assert(key != nullptr, "just checking");
4125   SystemProperty* prop;
4126   for (prop = pl; prop != nullptr; prop = prop->next()) {
4127     if (strcmp(key, prop->key()) == 0) return prop->value();
4128   }
4129   return nullptr;
4130 }
4131 
4132 // Return the value of the requested property provided that it is a readable property.
4133 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4134   assert(key != nullptr, "just checking");
4135   SystemProperty* prop;
4136   // Return the property value if the keys match and the property is not internal or
4137   // it's the special internal property "jdk.boot.class.path.append".
4138   for (prop = pl; prop != nullptr; prop = prop->next()) {
4139     if (strcmp(key, prop->key()) == 0) {
4140       if (!prop->internal()) {
4141         return prop->value();
4142       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4143         return prop->value();
4144       } else {
4145         // Property is internal and not jdk.boot.class.path.append so return null.
4146         return nullptr;
4147       }
4148     }
4149   }
4150   return nullptr;
4151 }
4152 
4153 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4154   SystemProperty* p = *plist;
4155   if (p == nullptr) {
4156     *plist = new_p;
4157   } else {
4158     while (p->next() != nullptr) {
4159       p = p->next();
4160     }
4161     p->set_next(new_p);
4162   }
4163 }
4164 
4165 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4166                                  bool writeable, bool internal) {
4167   if (plist == nullptr)
4168     return;
4169 
4170   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4171   PropertyList_add(plist, new_p);
4172 }
4173 
4174 void Arguments::PropertyList_add(SystemProperty *element) {
4175   PropertyList_add(&_system_properties, element);
4176 }
4177 
4178 // This add maintains unique property key in the list.
4179 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4180                                         PropertyAppendable append, PropertyWriteable writeable,
4181                                         PropertyInternal internal) {
4182   if (plist == nullptr)
4183     return;
4184 
4185   // If property key exists and is writeable, then update with new value.
4186   // Trying to update a non-writeable property is silently ignored.
4187   SystemProperty* prop;
4188   for (prop = *plist; prop != nullptr; prop = prop->next()) {
4189     if (strcmp(k, prop->key()) == 0) {
4190       if (append == AppendProperty) {
4191         prop->append_writeable_value(v);
4192       } else {
4193         prop->set_writeable_value(v);
4194       }
4195       return;
4196     }
4197   }
4198 
4199   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4200 }
4201 
4202 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4203 // Returns true if all of the source pointed by src has been copied over to
4204 // the destination buffer pointed by buf. Otherwise, returns false.
4205 // Notes:
4206 // 1. If the length (buflen) of the destination buffer excluding the
4207 // null terminator character is not long enough for holding the expanded
4208 // pid characters, it also returns false instead of returning the partially
4209 // expanded one.
4210 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4211 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4212                                 char* buf, size_t buflen) {
4213   const char* p = src;
4214   char* b = buf;
4215   const char* src_end = &src[srclen];
4216   char* buf_end = &buf[buflen - 1];
4217 
4218   while (p < src_end && b < buf_end) {
4219     if (*p == '%') {
4220       switch (*(++p)) {
4221       case '%':         // "%%" ==> "%"
4222         *b++ = *p++;
4223         break;
4224       case 'p':  {       //  "%p" ==> current process id
4225         // buf_end points to the character before the last character so
4226         // that we could write '\0' to the end of the buffer.
4227         size_t buf_sz = buf_end - b + 1;
4228         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4229 
4230         // if jio_snprintf fails or the buffer is not long enough to hold
4231         // the expanded pid, returns false.
4232         if (ret < 0 || ret >= (int)buf_sz) {
4233           return false;
4234         } else {
4235           b += ret;
4236           assert(*b == '\0', "fail in copy_expand_pid");
4237           if (p == src_end && b == buf_end + 1) {
4238             // reach the end of the buffer.
4239             return true;
4240           }
4241         }
4242         p++;
4243         break;
4244       }
4245       default :
4246         *b++ = '%';
4247       }
4248     } else {
4249       *b++ = *p++;
4250     }
4251   }
4252   *b = '\0';
4253   return (p == src_end); // return false if not all of the source was copied
4254 }