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