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