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