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