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