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