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