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