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(PPC64)) && !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   return JNI_OK;
3089 }
3090 
3091 // Helper class for controlling the lifetime of JavaVMInitArgs
3092 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3093 // deleted on the destruction of the ScopedVMInitArgs object.
3094 class ScopedVMInitArgs : public StackObj {
3095  private:
3096   JavaVMInitArgs _args;
3097   char*          _container_name;
3098   bool           _is_set;
3099   char*          _vm_options_file_arg;
3100 
3101  public:
3102   ScopedVMInitArgs(const char *container_name) {
3103     _args.version = JNI_VERSION_1_2;
3104     _args.nOptions = 0;
3105     _args.options = nullptr;
3106     _args.ignoreUnrecognized = false;
3107     _container_name = (char *)container_name;
3108     _is_set = false;
3109     _vm_options_file_arg = nullptr;
3110   }
3111 
3112   // Populates the JavaVMInitArgs object represented by this
3113   // ScopedVMInitArgs object with the arguments in options.  The
3114   // allocated memory is deleted by the destructor.  If this method
3115   // returns anything other than JNI_OK, then this object is in a
3116   // partially constructed state, and should be abandoned.
3117   jint set_args(const GrowableArrayView<JavaVMOption>* options) {
3118     _is_set = true;
3119     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3120         JavaVMOption, options->length(), mtArguments);
3121     if (options_arr == nullptr) {
3122       return JNI_ENOMEM;
3123     }
3124     _args.options = options_arr;
3125 
3126     for (int i = 0; i < options->length(); i++) {
3127       options_arr[i] = options->at(i);
3128       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3129       if (options_arr[i].optionString == nullptr) {
3130         // Rely on the destructor to do cleanup.
3131         _args.nOptions = i;
3132         return JNI_ENOMEM;
3133       }
3134     }
3135 
3136     _args.nOptions = options->length();
3137     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3138     return JNI_OK;
3139   }
3140 
3141   JavaVMInitArgs* get()             { return &_args; }
3142   char* container_name()            { return _container_name; }
3143   bool  is_set()                    { return _is_set; }
3144   bool  found_vm_options_file_arg() { return _vm_options_file_arg != nullptr; }
3145   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3146 
3147   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3148     if (_vm_options_file_arg != nullptr) {
3149       os::free(_vm_options_file_arg);
3150     }
3151     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3152   }
3153 
3154   ~ScopedVMInitArgs() {
3155     if (_vm_options_file_arg != nullptr) {
3156       os::free(_vm_options_file_arg);
3157     }
3158     if (_args.options == nullptr) return;
3159     for (int i = 0; i < _args.nOptions; i++) {
3160       os::free(_args.options[i].optionString);
3161     }
3162     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3163   }
3164 
3165   // Insert options into this option list, to replace option at
3166   // vm_options_file_pos (-XX:VMOptionsFile)
3167   jint insert(const JavaVMInitArgs* args,
3168               const JavaVMInitArgs* args_to_insert,
3169               const int vm_options_file_pos) {
3170     assert(_args.options == nullptr, "shouldn't be set yet");
3171     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3172     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3173 
3174     int length = args->nOptions + args_to_insert->nOptions - 1;
3175     // Construct new option array
3176     GrowableArrayCHeap<JavaVMOption, mtArguments> options(length);
3177     for (int i = 0; i < args->nOptions; i++) {
3178       if (i == vm_options_file_pos) {
3179         // insert the new options starting at the same place as the
3180         // -XX:VMOptionsFile option
3181         for (int j = 0; j < args_to_insert->nOptions; j++) {
3182           options.push(args_to_insert->options[j]);
3183         }
3184       } else {
3185         options.push(args->options[i]);
3186       }
3187     }
3188     // make into options array
3189     return set_args(&options);
3190   }
3191 };
3192 
3193 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3194   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3195 }
3196 
3197 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3198   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3199 }
3200 
3201 jint Arguments::parse_options_environment_variable(const char* name,
3202                                                    ScopedVMInitArgs* vm_args) {
3203   char *buffer = ::getenv(name);
3204 
3205   // Don't check this environment variable if user has special privileges
3206   // (e.g. unix su command).
3207   if (buffer == nullptr || os::have_special_privileges()) {
3208     return JNI_OK;
3209   }
3210 
3211   if ((buffer = os::strdup(buffer)) == nullptr) {
3212     return JNI_ENOMEM;
3213   }
3214 
3215   jio_fprintf(defaultStream::error_stream(),
3216               "Picked up %s: %s\n", name, buffer);
3217 
3218   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3219 
3220   os::free(buffer);
3221   return retcode;
3222 }
3223 
3224 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3225   // read file into buffer
3226   int fd = ::open(file_name, O_RDONLY);
3227   if (fd < 0) {
3228     jio_fprintf(defaultStream::error_stream(),
3229                 "Could not open options file '%s'\n",
3230                 file_name);
3231     return JNI_ERR;
3232   }
3233 
3234   struct stat stbuf;
3235   int retcode = os::stat(file_name, &stbuf);
3236   if (retcode != 0) {
3237     jio_fprintf(defaultStream::error_stream(),
3238                 "Could not stat options file '%s'\n",
3239                 file_name);
3240     ::close(fd);
3241     return JNI_ERR;
3242   }
3243 
3244   if (stbuf.st_size == 0) {
3245     // tell caller there is no option data and that is ok
3246     ::close(fd);
3247     return JNI_OK;
3248   }
3249 
3250   // '+ 1' for null termination even with max bytes
3251   size_t bytes_alloc = stbuf.st_size + 1;
3252 
3253   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3254   if (nullptr == buf) {
3255     jio_fprintf(defaultStream::error_stream(),
3256                 "Could not allocate read buffer for options file parse\n");
3257     ::close(fd);
3258     return JNI_ENOMEM;
3259   }
3260 
3261   memset(buf, 0, bytes_alloc);
3262 
3263   // Fill buffer
3264   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3265   ::close(fd);
3266   if (bytes_read < 0) {
3267     FREE_C_HEAP_ARRAY(char, buf);
3268     jio_fprintf(defaultStream::error_stream(),
3269                 "Could not read options file '%s'\n", file_name);
3270     return JNI_ERR;
3271   }
3272 
3273   if (bytes_read == 0) {
3274     // tell caller there is no option data and that is ok
3275     FREE_C_HEAP_ARRAY(char, buf);
3276     return JNI_OK;
3277   }
3278 
3279   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3280 
3281   FREE_C_HEAP_ARRAY(char, buf);
3282   return retcode;
3283 }
3284 
3285 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3286   // Construct option array
3287   GrowableArrayCHeap<JavaVMOption, mtArguments> options(2);
3288 
3289   // some pointers to help with parsing
3290   char *buffer_end = buffer + buf_len;
3291   char *opt_hd = buffer;
3292   char *wrt = buffer;
3293   char *rd = buffer;
3294 
3295   // parse all options
3296   while (rd < buffer_end) {
3297     // skip leading white space from the input string
3298     while (rd < buffer_end && isspace(*rd)) {
3299       rd++;
3300     }
3301 
3302     if (rd >= buffer_end) {
3303       break;
3304     }
3305 
3306     // Remember this is where we found the head of the token.
3307     opt_hd = wrt;
3308 
3309     // Tokens are strings of non white space characters separated
3310     // by one or more white spaces.
3311     while (rd < buffer_end && !isspace(*rd)) {
3312       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3313         int quote = *rd;                    // matching quote to look for
3314         rd++;                               // don't copy open quote
3315         while (rd < buffer_end && *rd != quote) {
3316                                             // include everything (even spaces)
3317                                             // up until the close quote
3318           *wrt++ = *rd++;                   // copy to option string
3319         }
3320 
3321         if (rd < buffer_end) {
3322           rd++;                             // don't copy close quote
3323         } else {
3324                                             // did not see closing quote
3325           jio_fprintf(defaultStream::error_stream(),
3326                       "Unmatched quote in %s\n", name);
3327           return JNI_ERR;
3328         }
3329       } else {
3330         *wrt++ = *rd++;                     // copy to option string
3331       }
3332     }
3333 
3334     // steal a white space character and set it to null
3335     *wrt++ = '\0';
3336     // We now have a complete token
3337 
3338     JavaVMOption option;
3339     option.optionString = opt_hd;
3340     option.extraInfo = nullptr;
3341 
3342     options.append(option);                // Fill in option
3343 
3344     rd++;  // Advance to next character
3345   }
3346 
3347   // Fill out JavaVMInitArgs structure.
3348   return vm_args->set_args(&options);
3349 }
3350 
3351 void Arguments::set_shared_spaces_flags_and_archive_paths() {
3352   if (DumpSharedSpaces) {
3353     if (RequireSharedSpaces) {
3354       warning("Cannot dump shared archive while using shared archive");
3355     }
3356     UseSharedSpaces = false;
3357   }
3358 #if INCLUDE_CDS
3359   // Initialize shared archive paths which could include both base and dynamic archive paths
3360   // This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.
3361   //
3362   // UseSharedSpaces may be disabled if -XX:SharedArchiveFile is invalid.
3363   if (DumpSharedSpaces || UseSharedSpaces) {
3364     init_shared_archive_paths();
3365   }
3366 #endif  // INCLUDE_CDS
3367 }
3368 
3369 #if INCLUDE_CDS
3370 // Sharing support
3371 // Construct the path to the archive
3372 char* Arguments::get_default_shared_archive_path() {
3373   if (_default_shared_archive_path == nullptr) {
3374     char jvm_path[JVM_MAXPATHLEN];
3375     os::jvm_path(jvm_path, sizeof(jvm_path));
3376     char *end = strrchr(jvm_path, *os::file_separator());
3377     if (end != nullptr) *end = '\0';
3378     size_t jvm_path_len = strlen(jvm_path);
3379     size_t file_sep_len = strlen(os::file_separator());
3380     const size_t len = jvm_path_len + file_sep_len + 20;
3381     _default_shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);
3382     jio_snprintf(_default_shared_archive_path, len,
3383                 LP64_ONLY(!UseCompressedOops ? "%s%sclasses_nocoops.jsa":) "%s%sclasses.jsa",
3384                 jvm_path, os::file_separator());
3385   }
3386   return _default_shared_archive_path;
3387 }
3388 
3389 int Arguments::num_archives(const char* archive_path) {
3390   if (archive_path == nullptr) {
3391     return 0;
3392   }
3393   int npaths = 1;
3394   char* p = (char*)archive_path;
3395   while (*p != '\0') {
3396     if (*p == os::path_separator()[0]) {
3397       npaths++;
3398     }
3399     p++;
3400   }
3401   return npaths;
3402 }
3403 
3404 void Arguments::extract_shared_archive_paths(const char* archive_path,
3405                                          char** base_archive_path,
3406                                          char** top_archive_path) {
3407   char* begin_ptr = (char*)archive_path;
3408   char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);
3409   if (end_ptr == nullptr || end_ptr == begin_ptr) {
3410     vm_exit_during_initialization("Base archive was not specified", archive_path);
3411   }
3412   size_t len = end_ptr - begin_ptr;
3413   char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
3414   strncpy(cur_path, begin_ptr, len);
3415   cur_path[len] = '\0';
3416   *base_archive_path = cur_path;
3417 
3418   begin_ptr = ++end_ptr;
3419   if (*begin_ptr == '\0') {
3420     vm_exit_during_initialization("Top archive was not specified", archive_path);
3421   }
3422   end_ptr = strchr(begin_ptr, '\0');
3423   assert(end_ptr != nullptr, "sanity");
3424   len = end_ptr - begin_ptr;
3425   cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
3426   strncpy(cur_path, begin_ptr, len + 1);
3427   *top_archive_path = cur_path;
3428 }
3429 
3430 void Arguments::init_shared_archive_paths() {
3431   if (ArchiveClassesAtExit != nullptr) {
3432     assert(!RecordDynamicDumpInfo, "already checked");
3433     if (DumpSharedSpaces) {
3434       vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");
3435     }
3436     check_unsupported_dumping_properties();
3437 
3438     if (os::same_files(get_default_shared_archive_path(), ArchiveClassesAtExit)) {
3439       vm_exit_during_initialization(
3440         "Cannot specify the default CDS archive for -XX:ArchiveClassesAtExit", get_default_shared_archive_path());
3441     }
3442   }
3443 
3444   if (SharedArchiveFile == nullptr) {
3445     SharedArchivePath = get_default_shared_archive_path();
3446   } else {
3447     int archives = num_archives(SharedArchiveFile);
3448     assert(archives > 0, "must be");
3449 
3450     if (is_dumping_archive() && archives > 1) {
3451       vm_exit_during_initialization(
3452         "Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");
3453     }
3454 
3455     if (DumpSharedSpaces) {
3456       assert(archives == 1, "must be");
3457       // Static dump is simple: only one archive is allowed in SharedArchiveFile. This file
3458       // will be overwritten no matter regardless of its contents
3459       SharedArchivePath = os::strdup_check_oom(SharedArchiveFile, mtArguments);
3460     } else {
3461       // SharedArchiveFile may specify one or two files. In case (c), the path for base.jsa
3462       // is read from top.jsa
3463       //    (a) 1 file:  -XX:SharedArchiveFile=base.jsa
3464       //    (b) 2 files: -XX:SharedArchiveFile=base.jsa:top.jsa
3465       //    (c) 2 files: -XX:SharedArchiveFile=top.jsa
3466       //
3467       // However, if either RecordDynamicDumpInfo or ArchiveClassesAtExit is used, we do not
3468       // allow cases (b) and (c). Case (b) is already checked above.
3469 
3470       if (archives > 2) {
3471         vm_exit_during_initialization(
3472           "Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");
3473       }
3474       if (archives == 1) {
3475         char* base_archive_path = nullptr;
3476         bool success =
3477           FileMapInfo::get_base_archive_name_from_header(SharedArchiveFile, &base_archive_path);
3478         if (!success) {
3479           // If +AutoCreateSharedArchive and the specified shared archive does not exist,
3480           // regenerate the dynamic archive base on default archive.
3481           if (AutoCreateSharedArchive && !os::file_exists(SharedArchiveFile)) {
3482             DynamicDumpSharedSpaces = true;
3483             ArchiveClassesAtExit = const_cast<char *>(SharedArchiveFile);
3484             SharedArchivePath = get_default_shared_archive_path();
3485             SharedArchiveFile = nullptr;
3486           } else {
3487             if (AutoCreateSharedArchive) {
3488               warning("-XX:+AutoCreateSharedArchive is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
3489               AutoCreateSharedArchive = false;
3490             }
3491             no_shared_spaces("invalid archive");
3492           }
3493         } else if (base_archive_path == nullptr) {
3494           // User has specified a single archive, which is a static archive.
3495           SharedArchivePath = const_cast<char *>(SharedArchiveFile);
3496         } else {
3497           // User has specified a single archive, which is a dynamic archive.
3498           SharedDynamicArchivePath = const_cast<char *>(SharedArchiveFile);
3499           SharedArchivePath = base_archive_path; // has been c-heap allocated.
3500         }
3501       } else {
3502         extract_shared_archive_paths((const char*)SharedArchiveFile,
3503                                       &SharedArchivePath, &SharedDynamicArchivePath);
3504         if (SharedArchivePath == nullptr) {
3505           assert(SharedDynamicArchivePath == nullptr, "must be");
3506           no_shared_spaces("invalid archive");
3507         }
3508       }
3509 
3510       if (SharedDynamicArchivePath != nullptr) {
3511         // Check for case (c)
3512         if (RecordDynamicDumpInfo) {
3513           vm_exit_during_initialization("-XX:+RecordDynamicDumpInfo is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
3514                                         SharedArchiveFile);
3515         }
3516         if (ArchiveClassesAtExit != nullptr) {
3517           vm_exit_during_initialization("-XX:ArchiveClassesAtExit is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
3518                                         SharedArchiveFile);
3519         }
3520       }
3521 
3522       if (ArchiveClassesAtExit != nullptr && os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {
3523           vm_exit_during_initialization(
3524             "Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",
3525             SharedArchiveFile);
3526       }
3527     }
3528   }
3529 }
3530 #endif // INCLUDE_CDS
3531 
3532 #ifndef PRODUCT
3533 // Determine whether LogVMOutput should be implicitly turned on.
3534 static bool use_vm_log() {
3535   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3536       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3537       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3538       PrintAssembly || TraceDeoptimization ||
3539       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3540     return true;
3541   }
3542 
3543 #ifdef COMPILER1
3544   if (PrintC1Statistics) {
3545     return true;
3546   }
3547 #endif // COMPILER1
3548 
3549 #ifdef COMPILER2
3550   if (PrintOptoAssembly || PrintOptoStatistics) {
3551     return true;
3552   }
3553 #endif // COMPILER2
3554 
3555   return false;
3556 }
3557 
3558 #endif // PRODUCT
3559 
3560 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3561   for (int index = 0; index < args->nOptions; index++) {
3562     const JavaVMOption* option = args->options + index;
3563     const char* tail;
3564     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3565       return true;
3566     }
3567   }
3568   return false;
3569 }
3570 
3571 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3572                                        const char* vm_options_file,
3573                                        const int vm_options_file_pos,
3574                                        ScopedVMInitArgs* vm_options_file_args,
3575                                        ScopedVMInitArgs* args_out) {
3576   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
3577   if (code != JNI_OK) {
3578     return code;
3579   }
3580 
3581   if (vm_options_file_args->get()->nOptions < 1) {
3582     return JNI_OK;
3583   }
3584 
3585   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
3586     jio_fprintf(defaultStream::error_stream(),
3587                 "A VM options file may not refer to a VM options file. "
3588                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
3589                 "options file '%s' in options container '%s' is an error.\n",
3590                 vm_options_file_args->vm_options_file_arg(),
3591                 vm_options_file_args->container_name());
3592     return JNI_EINVAL;
3593   }
3594 
3595   return args_out->insert(args, vm_options_file_args->get(),
3596                           vm_options_file_pos);
3597 }
3598 
3599 // Expand -XX:VMOptionsFile found in args_in as needed.
3600 // mod_args and args_out parameters may return values as needed.
3601 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
3602                                             ScopedVMInitArgs* mod_args,
3603                                             JavaVMInitArgs** args_out) {
3604   jint code = match_special_option_and_act(args_in, mod_args);
3605   if (code != JNI_OK) {
3606     return code;
3607   }
3608 
3609   if (mod_args->is_set()) {
3610     // args_in contains -XX:VMOptionsFile and mod_args contains the
3611     // original options from args_in along with the options expanded
3612     // from the VMOptionsFile. Return a short-hand to the caller.
3613     *args_out = mod_args->get();
3614   } else {
3615     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
3616   }
3617   return JNI_OK;
3618 }
3619 
3620 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3621                                              ScopedVMInitArgs* args_out) {
3622   // Remaining part of option string
3623   const char* tail;
3624   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
3625 
3626   for (int index = 0; index < args->nOptions; index++) {
3627     const JavaVMOption* option = args->options + index;
3628     if (match_option(option, "-XX:Flags=", &tail)) {
3629       Arguments::set_jvm_flags_file(tail);
3630       continue;
3631     }
3632     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3633       if (vm_options_file_args.found_vm_options_file_arg()) {
3634         jio_fprintf(defaultStream::error_stream(),
3635                     "The option '%s' is already specified in the options "
3636                     "container '%s' so the specification of '%s' in the "
3637                     "same options container is an error.\n",
3638                     vm_options_file_args.vm_options_file_arg(),
3639                     vm_options_file_args.container_name(),
3640                     option->optionString);
3641         return JNI_EINVAL;
3642       }
3643       vm_options_file_args.set_vm_options_file_arg(option->optionString);
3644       // If there's a VMOptionsFile, parse that
3645       jint code = insert_vm_options_file(args, tail, index,
3646                                          &vm_options_file_args, args_out);
3647       if (code != JNI_OK) {
3648         return code;
3649       }
3650       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
3651       if (args_out->is_set()) {
3652         // The VMOptions file inserted some options so switch 'args'
3653         // to the new set of options, and continue processing which
3654         // preserves "last option wins" semantics.
3655         args = args_out->get();
3656         // The first option from the VMOptionsFile replaces the
3657         // current option.  So we back track to process the
3658         // replacement option.
3659         index--;
3660       }
3661       continue;
3662     }
3663     if (match_option(option, "-XX:+PrintVMOptions")) {
3664       PrintVMOptions = true;
3665       continue;
3666     }
3667     if (match_option(option, "-XX:-PrintVMOptions")) {
3668       PrintVMOptions = false;
3669       continue;
3670     }
3671     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3672       IgnoreUnrecognizedVMOptions = true;
3673       continue;
3674     }
3675     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3676       IgnoreUnrecognizedVMOptions = false;
3677       continue;
3678     }
3679     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3680       JVMFlag::printFlags(tty, false);
3681       vm_exit(0);
3682     }
3683 
3684 #ifndef PRODUCT
3685     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3686       JVMFlag::printFlags(tty, true);
3687       vm_exit(0);
3688     }
3689 #endif
3690   }
3691   return JNI_OK;
3692 }
3693 
3694 static void print_options(const JavaVMInitArgs *args) {
3695   const char* tail;
3696   for (int index = 0; index < args->nOptions; index++) {
3697     const JavaVMOption *option = args->options + index;
3698     if (match_option(option, "-XX:", &tail)) {
3699       logOption(tail);
3700     }
3701   }
3702 }
3703 
3704 bool Arguments::handle_deprecated_print_gc_flags() {
3705   if (PrintGC) {
3706     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
3707   }
3708   if (PrintGCDetails) {
3709     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
3710   }
3711 
3712   if (_legacyGCLogging.lastFlag == 2) {
3713     // -Xloggc was used to specify a filename
3714     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
3715 
3716     LogTarget(Error, logging) target;
3717     LogStream errstream(target);
3718     return LogConfiguration::parse_log_arguments(_legacyGCLogging.file, gc_conf, nullptr, nullptr, &errstream);
3719   } else if (PrintGC || PrintGCDetails || (_legacyGCLogging.lastFlag == 1)) {
3720     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
3721   }
3722   return true;
3723 }
3724 
3725 static void apply_debugger_ergo() {
3726 #ifndef PRODUCT
3727   // UseDebuggerErgo is notproduct
3728   if (ReplayCompiles) {
3729     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo, true);
3730   }
3731 #endif
3732 
3733 #ifndef PRODUCT
3734   if (UseDebuggerErgo) {
3735     // Turn on sub-flags
3736     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo1, true);
3737     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo2, true);
3738   }
3739 #endif
3740 
3741   if (UseDebuggerErgo2) {
3742     // Debugging with limited number of CPUs
3743     FLAG_SET_ERGO_IF_DEFAULT(UseNUMA, false);
3744     FLAG_SET_ERGO_IF_DEFAULT(ConcGCThreads, 1);
3745     FLAG_SET_ERGO_IF_DEFAULT(ParallelGCThreads, 1);
3746     FLAG_SET_ERGO_IF_DEFAULT(CICompilerCount, 2);
3747   }
3748 }
3749 
3750 // Parse entry point called from JNI_CreateJavaVM
3751 
3752 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
3753   assert(verify_special_jvm_flags(false), "deprecated and obsolete flag table inconsistent");
3754   JVMFlag::check_all_flag_declarations();
3755 
3756   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3757   const char* hotspotrc = ".hotspotrc";
3758   bool settings_file_specified = false;
3759   bool needs_hotspotrc_warning = false;
3760   ScopedVMInitArgs initial_vm_options_args("");
3761   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3762   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
3763 
3764   // Pointers to current working set of containers
3765   JavaVMInitArgs* cur_cmd_args;
3766   JavaVMInitArgs* cur_vm_options_args;
3767   JavaVMInitArgs* cur_java_options_args;
3768   JavaVMInitArgs* cur_java_tool_options_args;
3769 
3770   // Containers for modified/expanded options
3771   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
3772   ScopedVMInitArgs mod_vm_options_args("vm_options_args");
3773   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3774   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
3775 
3776 
3777   jint code =
3778       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
3779   if (code != JNI_OK) {
3780     return code;
3781   }
3782 
3783   code = parse_java_options_environment_variable(&initial_java_options_args);
3784   if (code != JNI_OK) {
3785     return code;
3786   }
3787 
3788   // Parse the options in the /java.base/jdk/internal/vm/options resource, if present
3789   char *vmoptions = ClassLoader::lookup_vm_options();
3790   if (vmoptions != nullptr) {
3791     code = parse_options_buffer("vm options resource", vmoptions, strlen(vmoptions), &initial_vm_options_args);
3792     FREE_C_HEAP_ARRAY(char, vmoptions);
3793     if (code != JNI_OK) {
3794       return code;
3795     }
3796   }
3797 
3798   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
3799                                      &mod_java_tool_options_args,
3800                                      &cur_java_tool_options_args);
3801   if (code != JNI_OK) {
3802     return code;
3803   }
3804 
3805   code = expand_vm_options_as_needed(initial_cmd_args,
3806                                      &mod_cmd_args,
3807                                      &cur_cmd_args);
3808   if (code != JNI_OK) {
3809     return code;
3810   }
3811 
3812   code = expand_vm_options_as_needed(initial_java_options_args.get(),
3813                                      &mod_java_options_args,
3814                                      &cur_java_options_args);
3815   if (code != JNI_OK) {
3816     return code;
3817   }
3818 
3819   code = expand_vm_options_as_needed(initial_vm_options_args.get(),
3820                                      &mod_vm_options_args,
3821                                      &cur_vm_options_args);
3822   if (code != JNI_OK) {
3823     return code;
3824   }
3825 
3826   const char* flags_file = Arguments::get_jvm_flags_file();
3827   settings_file_specified = (flags_file != nullptr);
3828 
3829   if (IgnoreUnrecognizedVMOptions) {
3830     cur_cmd_args->ignoreUnrecognized = true;
3831     cur_java_tool_options_args->ignoreUnrecognized = true;
3832     cur_java_options_args->ignoreUnrecognized = true;
3833   }
3834 
3835   // Parse specified settings file
3836   if (settings_file_specified) {
3837     if (!process_settings_file(flags_file, true,
3838                                cur_cmd_args->ignoreUnrecognized)) {
3839       return JNI_EINVAL;
3840     }
3841   } else {
3842 #ifdef ASSERT
3843     // Parse default .hotspotrc settings file
3844     if (!process_settings_file(".hotspotrc", false,
3845                                cur_cmd_args->ignoreUnrecognized)) {
3846       return JNI_EINVAL;
3847     }
3848 #else
3849     struct stat buf;
3850     if (os::stat(hotspotrc, &buf) == 0) {
3851       needs_hotspotrc_warning = true;
3852     }
3853 #endif
3854   }
3855 
3856   if (PrintVMOptions) {
3857     print_options(cur_java_tool_options_args);
3858     print_options(cur_cmd_args);
3859     print_options(cur_java_options_args);
3860   }
3861 
3862   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
3863   jint result = parse_vm_init_args(cur_vm_options_args,
3864                                    cur_java_tool_options_args,
3865                                    cur_java_options_args,
3866                                    cur_cmd_args);
3867 
3868   if (result != JNI_OK) {
3869     return result;
3870   }
3871 
3872   // Delay warning until here so that we've had a chance to process
3873   // the -XX:-PrintWarnings flag
3874   if (needs_hotspotrc_warning) {
3875     warning("%s file is present but has been ignored.  "
3876             "Run with -XX:Flags=%s to load the file.",
3877             hotspotrc, hotspotrc);
3878   }
3879 
3880   if (needs_module_property_warning) {
3881     warning("Ignoring system property options whose names match the '-Djdk.module.*'."
3882             " names that are reserved for internal use.");
3883   }
3884 
3885 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
3886   UNSUPPORTED_OPTION(UseLargePages);
3887 #endif
3888 
3889 #if defined(AIX)
3890   UNSUPPORTED_OPTION_NULL(AllocateHeapAt);
3891 #endif
3892 
3893 #ifndef PRODUCT
3894   if (TraceBytecodesAt != 0) {
3895     TraceBytecodes = true;
3896   }
3897   if (CountCompiledCalls) {
3898     if (UseCounterDecay) {
3899       warning("UseCounterDecay disabled because CountCalls is set");
3900       UseCounterDecay = false;
3901     }
3902   }
3903 #endif // PRODUCT
3904 
3905   if (ScavengeRootsInCode == 0) {
3906     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3907       warning("Forcing ScavengeRootsInCode non-zero");
3908     }
3909     ScavengeRootsInCode = 1;
3910   }
3911 
3912   if (!handle_deprecated_print_gc_flags()) {
3913     return JNI_EINVAL;
3914   }
3915 
3916   // Set object alignment values.
3917   set_object_alignment();
3918 
3919 #if !INCLUDE_CDS
3920   if (DumpSharedSpaces || RequireSharedSpaces) {
3921     jio_fprintf(defaultStream::error_stream(),
3922       "Shared spaces are not supported in this VM\n");
3923     return JNI_ERR;
3924   }
3925   if (DumpLoadedClassList != nullptr) {
3926     jio_fprintf(defaultStream::error_stream(),
3927       "DumpLoadedClassList is not supported in this VM\n");
3928     return JNI_ERR;
3929   }
3930   if ((UseSharedSpaces && xshare_auto_cmd_line) ||
3931       log_is_enabled(Info, cds)) {
3932     warning("Shared spaces are not supported in this VM");
3933     UseSharedSpaces = false;
3934     LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(cds));
3935   }
3936   no_shared_spaces("CDS Disabled");
3937 #endif // INCLUDE_CDS
3938 
3939   // Verify NMT arguments
3940   const NMT_TrackingLevel lvl = NMTUtil::parse_tracking_level(NativeMemoryTracking);
3941   if (lvl == NMT_unknown) {
3942     jio_fprintf(defaultStream::error_stream(),
3943                 "Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", nullptr);
3944     return JNI_ERR;
3945   }
3946   if (PrintNMTStatistics && lvl == NMT_off) {
3947     warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
3948     FLAG_SET_DEFAULT(PrintNMTStatistics, false);
3949   }
3950 
3951   bool trace_dependencies = log_is_enabled(Debug, dependencies);
3952   if (trace_dependencies && VerifyDependencies) {
3953     warning("dependency logging results may be inflated by VerifyDependencies");
3954   }
3955 
3956   apply_debugger_ergo();
3957 
3958   if (log_is_enabled(Info, arguments)) {
3959     LogStream st(Log(arguments)::info());
3960     Arguments::print_on(&st);
3961   }
3962 
3963   return JNI_OK;
3964 }
3965 
3966 jint Arguments::apply_ergo() {
3967   // Set flags based on ergonomics.
3968   jint result = set_ergonomics_flags();
3969   if (result != JNI_OK) return result;
3970 
3971   // Set heap size based on available physical memory
3972   set_heap_size();
3973 
3974   GCConfig::arguments()->initialize();
3975 
3976   set_shared_spaces_flags_and_archive_paths();
3977 
3978   // Initialize Metaspace flags and alignments
3979   Metaspace::ergo_initialize();
3980 
3981   if (!StringDedup::ergo_initialize()) {
3982     return JNI_EINVAL;
3983   }
3984 
3985   // Set compiler flags after GC is selected and GC specific
3986   // flags (LoopStripMiningIter) are set.
3987   CompilerConfig::ergo_initialize();
3988 
3989   // Set bytecode rewriting flags
3990   set_bytecode_flags();
3991 
3992   // Set flags if aggressive optimization flags are enabled
3993   jint code = set_aggressive_opts_flags();
3994   if (code != JNI_OK) {
3995     return code;
3996   }
3997 
3998 #ifdef ZERO
3999   // Clear flags not supported on zero.
4000   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4001 #endif // ZERO
4002 
4003   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4004     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4005     DebugNonSafepoints = true;
4006   }
4007 
4008   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4009     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4010   }
4011 
4012   // Treat the odd case where local verification is enabled but remote
4013   // verification is not as if both were enabled.
4014   if (BytecodeVerificationLocal && !BytecodeVerificationRemote) {
4015     log_info(verification)("Turning on remote verification because local verification is on");
4016     FLAG_SET_DEFAULT(BytecodeVerificationRemote, true);
4017   }
4018 
4019 #ifndef PRODUCT
4020   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4021     if (use_vm_log()) {
4022       LogVMOutput = true;
4023     }
4024   }
4025 #endif // PRODUCT
4026 
4027   if (PrintCommandLineFlags) {
4028     JVMFlag::printSetFlags(tty);
4029   }
4030 
4031 #ifdef COMPILER2
4032   if (!FLAG_IS_DEFAULT(EnableVectorSupport) && !EnableVectorSupport) {
4033     if (!FLAG_IS_DEFAULT(EnableVectorReboxing) && EnableVectorReboxing) {
4034       warning("Disabling EnableVectorReboxing since EnableVectorSupport is turned off.");
4035     }
4036     FLAG_SET_DEFAULT(EnableVectorReboxing, false);
4037 
4038     if (!FLAG_IS_DEFAULT(EnableVectorAggressiveReboxing) && EnableVectorAggressiveReboxing) {
4039       if (!EnableVectorReboxing) {
4040         warning("Disabling EnableVectorAggressiveReboxing since EnableVectorReboxing is turned off.");
4041       } else {
4042         warning("Disabling EnableVectorAggressiveReboxing since EnableVectorSupport is turned off.");
4043       }
4044     }
4045     FLAG_SET_DEFAULT(EnableVectorAggressiveReboxing, false);
4046 
4047     if (!FLAG_IS_DEFAULT(UseVectorStubs) && UseVectorStubs) {
4048       warning("Disabling UseVectorStubs since EnableVectorSupport is turned off.");
4049     }
4050     FLAG_SET_DEFAULT(UseVectorStubs, false);
4051   }
4052 #endif // COMPILER2
4053 
4054   if (FLAG_IS_CMDLINE(DiagnoseSyncOnValueBasedClasses)) {
4055     if (DiagnoseSyncOnValueBasedClasses == ObjectSynchronizer::LOG_WARNING && !log_is_enabled(Info, valuebasedclasses)) {
4056       LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(valuebasedclasses));
4057     }
4058   }
4059   return JNI_OK;
4060 }
4061 
4062 jint Arguments::adjust_after_os() {
4063   if (UseNUMA) {
4064     if (UseParallelGC) {
4065       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4066          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4067       }
4068     }
4069   }
4070   return JNI_OK;
4071 }
4072 
4073 int Arguments::PropertyList_count(SystemProperty* pl) {
4074   int count = 0;
4075   while(pl != nullptr) {
4076     count++;
4077     pl = pl->next();
4078   }
4079   return count;
4080 }
4081 
4082 // Return the number of readable properties.
4083 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
4084   int count = 0;
4085   while(pl != nullptr) {
4086     if (pl->readable()) {
4087       count++;
4088     }
4089     pl = pl->next();
4090   }
4091   return count;
4092 }
4093 
4094 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4095   assert(key != nullptr, "just checking");
4096   SystemProperty* prop;
4097   for (prop = pl; prop != nullptr; prop = prop->next()) {
4098     if (strcmp(key, prop->key()) == 0) return prop->value();
4099   }
4100   return nullptr;
4101 }
4102 
4103 // Return the value of the requested property provided that it is a readable property.
4104 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4105   assert(key != nullptr, "just checking");
4106   SystemProperty* prop;
4107   // Return the property value if the keys match and the property is not internal or
4108   // it's the special internal property "jdk.boot.class.path.append".
4109   for (prop = pl; prop != nullptr; prop = prop->next()) {
4110     if (strcmp(key, prop->key()) == 0) {
4111       if (!prop->internal()) {
4112         return prop->value();
4113       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4114         return prop->value();
4115       } else {
4116         // Property is internal and not jdk.boot.class.path.append so return null.
4117         return nullptr;
4118       }
4119     }
4120   }
4121   return nullptr;
4122 }
4123 
4124 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4125   SystemProperty* p = *plist;
4126   if (p == nullptr) {
4127     *plist = new_p;
4128   } else {
4129     while (p->next() != nullptr) {
4130       p = p->next();
4131     }
4132     p->set_next(new_p);
4133   }
4134 }
4135 
4136 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4137                                  bool writeable, bool internal) {
4138   if (plist == nullptr)
4139     return;
4140 
4141   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4142   PropertyList_add(plist, new_p);
4143 }
4144 
4145 void Arguments::PropertyList_add(SystemProperty *element) {
4146   PropertyList_add(&_system_properties, element);
4147 }
4148 
4149 // This add maintains unique property key in the list.
4150 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4151                                         PropertyAppendable append, PropertyWriteable writeable,
4152                                         PropertyInternal internal) {
4153   if (plist == nullptr)
4154     return;
4155 
4156   // If property key exists and is writeable, then update with new value.
4157   // Trying to update a non-writeable property is silently ignored.
4158   SystemProperty* prop;
4159   for (prop = *plist; prop != nullptr; prop = prop->next()) {
4160     if (strcmp(k, prop->key()) == 0) {
4161       if (append == AppendProperty) {
4162         prop->append_writeable_value(v);
4163       } else {
4164         prop->set_writeable_value(v);
4165       }
4166       return;
4167     }
4168   }
4169 
4170   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4171 }
4172 
4173 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4174 // Returns true if all of the source pointed by src has been copied over to
4175 // the destination buffer pointed by buf. Otherwise, returns false.
4176 // Notes:
4177 // 1. If the length (buflen) of the destination buffer excluding the
4178 // null terminator character is not long enough for holding the expanded
4179 // pid characters, it also returns false instead of returning the partially
4180 // expanded one.
4181 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4182 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4183                                 char* buf, size_t buflen) {
4184   const char* p = src;
4185   char* b = buf;
4186   const char* src_end = &src[srclen];
4187   char* buf_end = &buf[buflen - 1];
4188 
4189   while (p < src_end && b < buf_end) {
4190     if (*p == '%') {
4191       switch (*(++p)) {
4192       case '%':         // "%%" ==> "%"
4193         *b++ = *p++;
4194         break;
4195       case 'p':  {       //  "%p" ==> current process id
4196         // buf_end points to the character before the last character so
4197         // that we could write '\0' to the end of the buffer.
4198         size_t buf_sz = buf_end - b + 1;
4199         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4200 
4201         // if jio_snprintf fails or the buffer is not long enough to hold
4202         // the expanded pid, returns false.
4203         if (ret < 0 || ret >= (int)buf_sz) {
4204           return false;
4205         } else {
4206           b += ret;
4207           assert(*b == '\0', "fail in copy_expand_pid");
4208           if (p == src_end && b == buf_end + 1) {
4209             // reach the end of the buffer.
4210             return true;
4211           }
4212         }
4213         p++;
4214         break;
4215       }
4216       default :
4217         *b++ = '%';
4218       }
4219     } else {
4220       *b++ = *p++;
4221     }
4222   }
4223   *b = '\0';
4224   return (p == src_end); // return false if not all of the source was copied
4225 }