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 
1486 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1487 // set_use_compressed_oops().
1488 void Arguments::set_use_compressed_klass_ptrs() {
1489 #ifdef _LP64
1490   // On some architectures, the use of UseCompressedClassPointers implies the use of
1491   // UseCompressedOops. The reason is that the rheap_base register of said platforms
1492   // is reused to perform some optimized spilling, in order to use rheap_base as a
1493   // temp register. But by treating it as any other temp register, spilling can typically
1494   // be completely avoided instead. So it is better not to perform this trick. And by
1495   // not having that reliance, large heaps, or heaps not supporting compressed oops,
1496   // can still use compressed class pointers.
1497   // Turn on UseCompressedClassPointers too
1498   if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1499     FLAG_SET_ERGO(UseCompressedClassPointers, true);
1500   }
1501   // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1502   if (UseCompressedClassPointers) {
1503     if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1504       warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1505       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1506     }
1507   }
1508 #endif // _LP64
1509 }
1510 
1511 void Arguments::set_conservative_max_heap_alignment() {
1512   // The conservative maximum required alignment for the heap is the maximum of
1513   // the alignments imposed by several sources: any requirements from the heap
1514   // itself and the maximum page size we may run the VM with.
1515   size_t heap_alignment = GCConfig::arguments()->conservative_max_heap_alignment();
1516   _conservative_max_heap_alignment = MAX4(heap_alignment,
1517                                           os::vm_allocation_granularity(),
1518                                           os::max_page_size(),
1519                                           GCArguments::compute_heap_alignment());
1520 }
1521 
1522 jint Arguments::set_ergonomics_flags() {
1523   GCConfig::initialize();
1524 
1525   set_conservative_max_heap_alignment();
1526 
1527 #ifdef _LP64
1528   set_use_compressed_oops();
1529 
1530   // set_use_compressed_klass_ptrs() must be called after calling
1531   // set_use_compressed_oops().
1532   set_use_compressed_klass_ptrs();
1533 
1534   // Also checks that certain machines are slower with compressed oops
1535   // in vm_version initialization code.
1536 #endif // _LP64
1537 
1538   return JNI_OK;
1539 }
1540 
1541 size_t Arguments::limit_heap_by_allocatable_memory(size_t limit) {
1542   size_t max_allocatable;
1543   size_t result = limit;
1544   if (os::has_allocatable_memory_limit(&max_allocatable)) {
1545     // The AggressiveHeap check is a temporary workaround to avoid calling
1546     // GCarguments::heap_virtual_to_physical_ratio() before a GC has been
1547     // selected. This works because AggressiveHeap implies UseParallelGC
1548     // where we know the ratio will be 1. Once the AggressiveHeap option is
1549     // removed, this can be cleaned up.
1550     size_t heap_virtual_to_physical_ratio = (AggressiveHeap ? 1 : GCConfig::arguments()->heap_virtual_to_physical_ratio());
1551     size_t fraction = MaxVirtMemFraction * heap_virtual_to_physical_ratio;
1552     result = MIN2(result, max_allocatable / fraction);
1553   }
1554   return result;
1555 }
1556 
1557 // Use static initialization to get the default before parsing
1558 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1559 
1560 void Arguments::set_heap_size() {
1561   julong phys_mem;
1562 
1563   // If the user specified one of these options, they
1564   // want specific memory sizing so do not limit memory
1565   // based on compressed oops addressability.
1566   // Also, memory limits will be calculated based on
1567   // available os physical memory, not our MaxRAM limit,
1568   // unless MaxRAM is also specified.
1569   bool override_coop_limit = (!FLAG_IS_DEFAULT(MaxRAMPercentage) ||
1570                            !FLAG_IS_DEFAULT(MaxRAMFraction) ||
1571                            !FLAG_IS_DEFAULT(MinRAMPercentage) ||
1572                            !FLAG_IS_DEFAULT(MinRAMFraction) ||
1573                            !FLAG_IS_DEFAULT(InitialRAMPercentage) ||
1574                            !FLAG_IS_DEFAULT(InitialRAMFraction) ||
1575                            !FLAG_IS_DEFAULT(MaxRAM));
1576   if (override_coop_limit) {
1577     if (FLAG_IS_DEFAULT(MaxRAM)) {
1578       phys_mem = os::physical_memory();
1579       FLAG_SET_ERGO(MaxRAM, (uint64_t)phys_mem);
1580     } else {
1581       phys_mem = (julong)MaxRAM;
1582     }
1583   } else {
1584     phys_mem = FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1585                                        : (julong)MaxRAM;
1586   }
1587 
1588 
1589   // Convert deprecated flags
1590   if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&
1591       !FLAG_IS_DEFAULT(MaxRAMFraction))
1592     MaxRAMPercentage = 100.0 / MaxRAMFraction;
1593 
1594   if (FLAG_IS_DEFAULT(MinRAMPercentage) &&
1595       !FLAG_IS_DEFAULT(MinRAMFraction))
1596     MinRAMPercentage = 100.0 / MinRAMFraction;
1597 
1598   if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&
1599       !FLAG_IS_DEFAULT(InitialRAMFraction))
1600     InitialRAMPercentage = 100.0 / InitialRAMFraction;
1601 
1602   // If the maximum heap size has not been set with -Xmx,
1603   // then set it as fraction of the size of physical memory,
1604   // respecting the maximum and minimum sizes of the heap.
1605   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1606     julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);
1607     const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);
1608     if (reasonable_min < MaxHeapSize) {
1609       // Small physical memory, so use a minimum fraction of it for the heap
1610       reasonable_max = reasonable_min;
1611     } else {
1612       // Not-small physical memory, so require a heap at least
1613       // as large as MaxHeapSize
1614       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1615     }
1616 
1617     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1618       // Limit the heap size to ErgoHeapSizeLimit
1619       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1620     }
1621 
1622     reasonable_max = limit_heap_by_allocatable_memory(reasonable_max);
1623 
1624     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1625       // An initial heap size was specified on the command line,
1626       // so be sure that the maximum size is consistent.  Done
1627       // after call to limit_heap_by_allocatable_memory because that
1628       // method might reduce the allocation size.
1629       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1630     } else if (!FLAG_IS_DEFAULT(MinHeapSize)) {
1631       reasonable_max = MAX2(reasonable_max, (julong)MinHeapSize);
1632     }
1633 
1634 #ifdef _LP64
1635     if (UseCompressedOops || UseCompressedClassPointers) {
1636       // HeapBaseMinAddress can be greater than default but not less than.
1637       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1638         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1639           // matches compressed oops printing flags
1640           log_debug(gc, heap, coops)("HeapBaseMinAddress must be at least " SIZE_FORMAT
1641                                      " (" SIZE_FORMAT "G) which is greater than value given " SIZE_FORMAT,
1642                                      DefaultHeapBaseMinAddress,
1643                                      DefaultHeapBaseMinAddress/G,
1644                                      HeapBaseMinAddress);
1645           FLAG_SET_ERGO(HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1646         }
1647       }
1648     }
1649     if (UseCompressedOops) {
1650       // Limit the heap size to the maximum possible when using compressed oops
1651       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1652 
1653       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1654         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1655         // but it should be not less than default MaxHeapSize.
1656         max_coop_heap -= HeapBaseMinAddress;
1657       }
1658 
1659       // If user specified flags prioritizing os physical
1660       // memory limits, then disable compressed oops if
1661       // limits exceed max_coop_heap and UseCompressedOops
1662       // was not specified.
1663       if (reasonable_max > max_coop_heap) {
1664         if (FLAG_IS_ERGO(UseCompressedOops) && override_coop_limit) {
1665           log_info(cds)("UseCompressedOops and UseCompressedClassPointers have been disabled due to"
1666             " max heap " SIZE_FORMAT " > compressed oop heap " SIZE_FORMAT ". "
1667             "Please check the setting of MaxRAMPercentage %5.2f."
1668             ,(size_t)reasonable_max, (size_t)max_coop_heap, MaxRAMPercentage);
1669           FLAG_SET_ERGO(UseCompressedOops, false);
1670         } else {
1671           reasonable_max = MIN2(reasonable_max, max_coop_heap);
1672         }
1673       }
1674     }
1675 #endif // _LP64
1676 
1677     log_trace(gc, heap)("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1678     FLAG_SET_ERGO(MaxHeapSize, (size_t)reasonable_max);
1679   }
1680 
1681   // If the minimum or initial heap_size have not been set or requested to be set
1682   // ergonomically, set them accordingly.
1683   if (InitialHeapSize == 0 || MinHeapSize == 0) {
1684     julong reasonable_minimum = (julong)(OldSize + NewSize);
1685 
1686     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1687 
1688     reasonable_minimum = limit_heap_by_allocatable_memory(reasonable_minimum);
1689 
1690     if (InitialHeapSize == 0) {
1691       julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);
1692       reasonable_initial = limit_heap_by_allocatable_memory(reasonable_initial);
1693 
1694       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)MinHeapSize);
1695       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1696 
1697       FLAG_SET_ERGO(InitialHeapSize, (size_t)reasonable_initial);
1698       log_trace(gc, heap)("  Initial heap size " SIZE_FORMAT, InitialHeapSize);
1699     }
1700     // If the minimum heap size has not been set (via -Xms or -XX:MinHeapSize),
1701     // synchronize with InitialHeapSize to avoid errors with the default value.
1702     if (MinHeapSize == 0) {
1703       FLAG_SET_ERGO(MinHeapSize, MIN2((size_t)reasonable_minimum, InitialHeapSize));
1704       log_trace(gc, heap)("  Minimum heap size " SIZE_FORMAT, MinHeapSize);
1705     }
1706   }
1707 }
1708 
1709 // This option inspects the machine and attempts to set various
1710 // parameters to be optimal for long-running, memory allocation
1711 // intensive jobs.  It is intended for machines with large
1712 // amounts of cpu and memory.
1713 jint Arguments::set_aggressive_heap_flags() {
1714   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
1715   // VM, but we may not be able to represent the total physical memory
1716   // available (like having 8gb of memory on a box but using a 32bit VM).
1717   // Thus, we need to make sure we're using a julong for intermediate
1718   // calculations.
1719   julong initHeapSize;
1720   julong total_memory = os::physical_memory();
1721 
1722   if (total_memory < (julong) 256 * M) {
1723     jio_fprintf(defaultStream::error_stream(),
1724             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
1725     vm_exit(1);
1726   }
1727 
1728   // The heap size is half of available memory, or (at most)
1729   // all of possible memory less 160mb (leaving room for the OS
1730   // when using ISM).  This is the maximum; because adaptive sizing
1731   // is turned on below, the actual space used may be smaller.
1732 
1733   initHeapSize = MIN2(total_memory / (julong) 2,
1734           total_memory - (julong) 160 * M);
1735 
1736   initHeapSize = limit_heap_by_allocatable_memory(initHeapSize);
1737 
1738   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1739     if (FLAG_SET_CMDLINE(MaxHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1740       return JNI_EINVAL;
1741     }
1742     if (FLAG_SET_CMDLINE(InitialHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1743       return JNI_EINVAL;
1744     }
1745     if (FLAG_SET_CMDLINE(MinHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1746       return JNI_EINVAL;
1747     }
1748   }
1749   if (FLAG_IS_DEFAULT(NewSize)) {
1750     // Make the young generation 3/8ths of the total heap.
1751     if (FLAG_SET_CMDLINE(NewSize,
1752             ((julong) MaxHeapSize / (julong) 8) * (julong) 3) != JVMFlag::SUCCESS) {
1753       return JNI_EINVAL;
1754     }
1755     if (FLAG_SET_CMDLINE(MaxNewSize, NewSize) != JVMFlag::SUCCESS) {
1756       return JNI_EINVAL;
1757     }
1758   }
1759 
1760 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
1761   FLAG_SET_DEFAULT(UseLargePages, true);
1762 #endif
1763 
1764   // Increase some data structure sizes for efficiency
1765   if (FLAG_SET_CMDLINE(BaseFootPrintEstimate, MaxHeapSize) != JVMFlag::SUCCESS) {
1766     return JNI_EINVAL;
1767   }
1768   if (FLAG_SET_CMDLINE(ResizeTLAB, false) != JVMFlag::SUCCESS) {
1769     return JNI_EINVAL;
1770   }
1771   if (FLAG_SET_CMDLINE(TLABSize, 256 * K) != JVMFlag::SUCCESS) {
1772     return JNI_EINVAL;
1773   }
1774 
1775   // See the OldPLABSize comment below, but replace 'after promotion'
1776   // with 'after copying'.  YoungPLABSize is the size of the survivor
1777   // space per-gc-thread buffers.  The default is 4kw.
1778   if (FLAG_SET_CMDLINE(YoungPLABSize, 256 * K) != JVMFlag::SUCCESS) { // Note: this is in words
1779     return JNI_EINVAL;
1780   }
1781 
1782   // OldPLABSize is the size of the buffers in the old gen that
1783   // UseParallelGC uses to promote live data that doesn't fit in the
1784   // survivor spaces.  At any given time, there's one for each gc thread.
1785   // The default size is 1kw. These buffers are rarely used, since the
1786   // survivor spaces are usually big enough.  For specjbb, however, there
1787   // are occasions when there's lots of live data in the young gen
1788   // and we end up promoting some of it.  We don't have a definite
1789   // explanation for why bumping OldPLABSize helps, but the theory
1790   // is that a bigger PLAB results in retaining something like the
1791   // original allocation order after promotion, which improves mutator
1792   // locality.  A minor effect may be that larger PLABs reduce the
1793   // number of PLAB allocation events during gc.  The value of 8kw
1794   // was arrived at by experimenting with specjbb.
1795   if (FLAG_SET_CMDLINE(OldPLABSize, 8 * K) != JVMFlag::SUCCESS) { // Note: this is in words
1796     return JNI_EINVAL;
1797   }
1798 
1799   // Enable parallel GC and adaptive generation sizing
1800   if (FLAG_SET_CMDLINE(UseParallelGC, true) != JVMFlag::SUCCESS) {
1801     return JNI_EINVAL;
1802   }
1803 
1804   // Encourage steady state memory management
1805   if (FLAG_SET_CMDLINE(ThresholdTolerance, 100) != JVMFlag::SUCCESS) {
1806     return JNI_EINVAL;
1807   }
1808 
1809   // This appears to improve mutator locality
1810   if (FLAG_SET_CMDLINE(ScavengeBeforeFullGC, false) != JVMFlag::SUCCESS) {
1811     return JNI_EINVAL;
1812   }
1813 
1814   return JNI_OK;
1815 }
1816 
1817 // This must be called after ergonomics.
1818 void Arguments::set_bytecode_flags() {
1819   if (!RewriteBytecodes) {
1820     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1821   }
1822 }
1823 
1824 // Aggressive optimization flags
1825 jint Arguments::set_aggressive_opts_flags() {
1826 #ifdef COMPILER2
1827   if (AggressiveUnboxing) {
1828     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1829       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1830     } else if (!EliminateAutoBox) {
1831       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
1832       AggressiveUnboxing = false;
1833     }
1834     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1835       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1836     } else if (!DoEscapeAnalysis) {
1837       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
1838       AggressiveUnboxing = false;
1839     }
1840   }
1841   if (!FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1842     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1843       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1844     }
1845     // Feed the cache size setting into the JDK
1846     char buffer[1024];
1847     jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
1848     if (!add_property(buffer)) {
1849       return JNI_ENOMEM;
1850     }
1851   }
1852 #endif
1853 
1854   return JNI_OK;
1855 }
1856 
1857 //===========================================================================================================
1858 
1859 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1860   if (_sun_java_launcher != _default_java_launcher) {
1861     os::free(const_cast<char*>(_sun_java_launcher));
1862   }
1863   _sun_java_launcher = os::strdup_check_oom(launcher);
1864 }
1865 
1866 bool Arguments::created_by_java_launcher() {
1867   assert(_sun_java_launcher != nullptr, "property must have value");
1868   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1869 }
1870 
1871 bool Arguments::sun_java_launcher_is_altjvm() {
1872   return _sun_java_launcher_is_altjvm;
1873 }
1874 
1875 //===========================================================================================================
1876 // Parsing of main arguments
1877 
1878 unsigned int addreads_count = 0;
1879 unsigned int addexports_count = 0;
1880 unsigned int addopens_count = 0;
1881 unsigned int addmods_count = 0;
1882 unsigned int patch_mod_count = 0;
1883 unsigned int enable_native_access_count = 0;
1884 
1885 // Check the consistency of vm_init_args
1886 bool Arguments::check_vm_args_consistency() {
1887   // Method for adding checks for flag consistency.
1888   // The intent is to warn the user of all possible conflicts,
1889   // before returning an error.
1890   // Note: Needs platform-dependent factoring.
1891   bool status = true;
1892 
1893   if (TLABRefillWasteFraction == 0) {
1894     jio_fprintf(defaultStream::error_stream(),
1895                 "TLABRefillWasteFraction should be a denominator, "
1896                 "not " SIZE_FORMAT "\n",
1897                 TLABRefillWasteFraction);
1898     status = false;
1899   }
1900 
1901   status = CompilerConfig::check_args_consistency(status);
1902 #if INCLUDE_JVMCI
1903   if (status && EnableJVMCI) {
1904     PropertyList_unique_add(&_system_properties, "jdk.internal.vm.ci.enabled", "true",
1905         AddProperty, UnwriteableProperty, InternalProperty);
1906     if (ClassLoader::is_module_observable("jdk.internal.vm.ci")) {
1907       if (!create_numbered_module_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {
1908         return false;
1909       }
1910     }
1911   }
1912 #endif
1913 
1914 #if INCLUDE_JFR
1915   if (status && (FlightRecorderOptions || StartFlightRecording)) {
1916     if (!create_numbered_module_property("jdk.module.addmods", "jdk.jfr", addmods_count++)) {
1917       return false;
1918     }
1919   }
1920 #endif
1921 
1922 #ifndef SUPPORT_RESERVED_STACK_AREA
1923   if (StackReservedPages != 0) {
1924     FLAG_SET_CMDLINE(StackReservedPages, 0);
1925     warning("Reserved Stack Area not supported on this platform");
1926   }
1927 #endif
1928 
1929 
1930 #if !defined(X86) && !defined(AARCH64) && !defined(RISCV64) && !defined(ARM)
1931   if (LockingMode == LM_LIGHTWEIGHT) {
1932     FLAG_SET_CMDLINE(LockingMode, LM_LEGACY);
1933     warning("New lightweight locking not supported on this platform");
1934   }
1935 #endif
1936 
1937   if (UseHeavyMonitors) {
1938     if (FLAG_IS_CMDLINE(LockingMode) && LockingMode != LM_MONITOR) {
1939       jio_fprintf(defaultStream::error_stream(),
1940                   "Conflicting -XX:+UseHeavyMonitors and -XX:LockingMode=%d flags", LockingMode);
1941       return false;
1942     }
1943     FLAG_SET_CMDLINE(LockingMode, LM_MONITOR);
1944   }
1945 
1946 #if !defined(X86) && !defined(AARCH64) && !defined(PPC64) && !defined(RISCV64)
1947   if (LockingMode == LM_MONITOR) {
1948     jio_fprintf(defaultStream::error_stream(),
1949                 "LockingMode == 0 (LM_MONITOR) is not fully implemented on this architecture");
1950     return false;
1951   }
1952 #endif
1953 #if (defined(X86) || defined(PPC64)) && !defined(ZERO)
1954   if (LockingMode == LM_MONITOR && UseRTMForStackLocks) {
1955     jio_fprintf(defaultStream::error_stream(),
1956                 "LockingMode == 0 (LM_MONITOR) and -XX:+UseRTMForStackLocks are mutually exclusive");
1957 
1958     return false;
1959   }
1960 #endif
1961   if (VerifyHeavyMonitors && LockingMode != LM_MONITOR) {
1962     jio_fprintf(defaultStream::error_stream(),
1963                 "-XX:+VerifyHeavyMonitors requires LockingMode == 0 (LM_MONITOR)");
1964     return false;
1965   }
1966   return status;
1967 }
1968 
1969 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
1970   const char* option_type) {
1971   if (ignore) return false;
1972 
1973   const char* spacer = " ";
1974   if (option_type == nullptr) {
1975     option_type = ++spacer; // Set both to the empty string.
1976   }
1977 
1978   jio_fprintf(defaultStream::error_stream(),
1979               "Unrecognized %s%soption: %s\n", option_type, spacer,
1980               option->optionString);
1981   return true;
1982 }
1983 
1984 static const char* user_assertion_options[] = {
1985   "-da", "-ea", "-disableassertions", "-enableassertions", 0
1986 };
1987 
1988 static const char* system_assertion_options[] = {
1989   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
1990 };
1991 
1992 bool Arguments::parse_uintx(const char* value,
1993                             uintx* uintx_arg,
1994                             uintx min_size) {
1995   uintx n;
1996   if (!parse_integer(value, &n)) {
1997     return false;
1998   }
1999   if (n >= min_size) {
2000     *uintx_arg = n;
2001     return true;
2002   } else {
2003     return false;
2004   }
2005 }
2006 
2007 bool Arguments::create_module_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
2008   assert(is_internal_module_property(prop_name), "unknown module property: '%s'", prop_name);
2009   size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
2010   char* property = AllocateHeap(prop_len, mtArguments);
2011   int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);
2012   if (ret < 0 || ret >= (int)prop_len) {
2013     FreeHeap(property);
2014     return false;
2015   }
2016   // These are not strictly writeable properties as they cannot be set via -Dprop=val. But that
2017   // is enforced by checking is_internal_module_property(). We need the property to be writeable so
2018   // that multiple occurrences of the associated flag just causes the existing property value to be
2019   // replaced ("last option wins"). Otherwise we would need to keep track of the flags and only convert
2020   // to a property after we have finished flag processing.
2021   bool added = add_property(property, WriteableProperty, internal);
2022   FreeHeap(property);
2023   return added;
2024 }
2025 
2026 bool Arguments::create_numbered_module_property(const char* prop_base_name, const char* prop_value, unsigned int count) {
2027   assert(is_internal_module_property(prop_base_name), "unknown module property: '%s'", prop_base_name);
2028   const unsigned int props_count_limit = 1000;
2029   const int max_digits = 3;
2030   const int extra_symbols_count = 3; // includes '.', '=', '\0'
2031 
2032   // Make sure count is < props_count_limit. Otherwise, memory allocation will be too small.
2033   if (count < props_count_limit) {
2034     size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + max_digits + extra_symbols_count;
2035     char* property = AllocateHeap(prop_len, mtArguments);
2036     int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);
2037     if (ret < 0 || ret >= (int)prop_len) {
2038       FreeHeap(property);
2039       jio_fprintf(defaultStream::error_stream(), "Failed to create property %s.%d=%s\n", prop_base_name, count, prop_value);
2040       return false;
2041     }
2042     bool added = add_property(property, UnwriteableProperty, InternalProperty);
2043     FreeHeap(property);
2044     return added;
2045   }
2046 
2047   jio_fprintf(defaultStream::error_stream(), "Property count limit exceeded: %s, limit=%d\n", prop_base_name, props_count_limit);
2048   return false;
2049 }
2050 
2051 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2052                                                   julong* long_arg,
2053                                                   julong min_size,
2054                                                   julong max_size) {
2055   if (!parse_integer(s, long_arg)) return arg_unreadable;
2056   return check_memory_size(*long_arg, min_size, max_size);
2057 }
2058 
2059 // Parse JavaVMInitArgs structure
2060 
2061 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *vm_options_args,
2062                                    const JavaVMInitArgs *java_tool_options_args,
2063                                    const JavaVMInitArgs *java_options_args,
2064                                    const JavaVMInitArgs *cmd_line_args) {
2065   bool patch_mod_javabase = false;
2066 
2067   // Save default settings for some mode flags
2068   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2069   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2070   Arguments::_ClipInlining             = ClipInlining;
2071   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2072 
2073   // Remember the default value of SharedBaseAddress.
2074   Arguments::_default_SharedBaseAddress = SharedBaseAddress;
2075 
2076   // Setup flags for mixed which is the default
2077   set_mode_flags(_mixed);
2078 
2079   // Parse args structure generated from java.base vm options resource
2080   jint result = parse_each_vm_init_arg(vm_options_args, &patch_mod_javabase, JVMFlagOrigin::JIMAGE_RESOURCE);
2081   if (result != JNI_OK) {
2082     return result;
2083   }
2084 
2085   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2086   // variable (if present).
2087   result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR);
2088   if (result != JNI_OK) {
2089     return result;
2090   }
2091 
2092   // Parse args structure generated from the command line flags.
2093   result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, JVMFlagOrigin::COMMAND_LINE);
2094   if (result != JNI_OK) {
2095     return result;
2096   }
2097 
2098   // Parse args structure generated from the _JAVA_OPTIONS environment
2099   // variable (if present) (mimics classic VM)
2100   result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR);
2101   if (result != JNI_OK) {
2102     return result;
2103   }
2104 
2105   // Disable CDS for exploded image
2106   if (!has_jimage()) {
2107     no_shared_spaces("CDS disabled on exploded JDK");
2108   }
2109 
2110   // We need to ensure processor and memory resources have been properly
2111   // configured - which may rely on arguments we just processed - before
2112   // doing the final argument processing. Any argument processing that
2113   // needs to know about processor and memory resources must occur after
2114   // this point.
2115 
2116   os::init_container_support();
2117 
2118   SystemMemoryBarrier::initialize();
2119 
2120   // Do final processing now that all arguments have been parsed
2121   result = finalize_vm_init_args(patch_mod_javabase);
2122   if (result != JNI_OK) {
2123     return result;
2124   }
2125 
2126   return JNI_OK;
2127 }
2128 
2129 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2130 // represents a valid JDWP agent.  is_path==true denotes that we
2131 // are dealing with -agentpath (case where name is a path), otherwise with
2132 // -agentlib
2133 bool valid_jdwp_agent(char *name, bool is_path) {
2134   char *_name;
2135   const char *_jdwp = "jdwp";
2136   size_t _len_jdwp, _len_prefix;
2137 
2138   if (is_path) {
2139     if ((_name = strrchr(name, (int) *os::file_separator())) == nullptr) {
2140       return false;
2141     }
2142 
2143     _name++;  // skip past last path separator
2144     _len_prefix = strlen(JNI_LIB_PREFIX);
2145 
2146     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2147       return false;
2148     }
2149 
2150     _name += _len_prefix;
2151     _len_jdwp = strlen(_jdwp);
2152 
2153     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2154       _name += _len_jdwp;
2155     }
2156     else {
2157       return false;
2158     }
2159 
2160     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2161       return false;
2162     }
2163 
2164     return true;
2165   }
2166 
2167   if (strcmp(name, _jdwp) == 0) {
2168     return true;
2169   }
2170 
2171   return false;
2172 }
2173 
2174 int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {
2175   // --patch-module=<module>=<file>(<pathsep><file>)*
2176   assert(patch_mod_tail != nullptr, "Unexpected null patch-module value");
2177   // Find the equal sign between the module name and the path specification
2178   const char* module_equal = strchr(patch_mod_tail, '=');
2179   if (module_equal == nullptr) {
2180     jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");
2181     return JNI_ERR;
2182   } else {
2183     // Pick out the module name
2184     size_t module_len = module_equal - patch_mod_tail;
2185     char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);
2186     if (module_name != nullptr) {
2187       memcpy(module_name, patch_mod_tail, module_len);
2188       *(module_name + module_len) = '\0';
2189       // The path piece begins one past the module_equal sign
2190       add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);
2191       FREE_C_HEAP_ARRAY(char, module_name);
2192       if (!create_numbered_module_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {
2193         return JNI_ENOMEM;
2194       }
2195     } else {
2196       return JNI_ENOMEM;
2197     }
2198   }
2199   return JNI_OK;
2200 }
2201 
2202 // Parse -Xss memory string parameter and convert to ThreadStackSize in K.
2203 jint Arguments::parse_xss(const JavaVMOption* option, const char* tail, intx* out_ThreadStackSize) {
2204   // The min and max sizes match the values in globals.hpp, but scaled
2205   // with K. The values have been chosen so that alignment with page
2206   // size doesn't change the max value, which makes the conversions
2207   // back and forth between Xss value and ThreadStackSize value easier.
2208   // The values have also been chosen to fit inside a 32-bit signed type.
2209   const julong min_ThreadStackSize = 0;
2210   const julong max_ThreadStackSize = 1 * M;
2211 
2212   // Make sure the above values match the range set in globals.hpp
2213   const JVMTypedFlagLimit<intx>* limit = JVMFlagLimit::get_range_at(FLAG_MEMBER_ENUM(ThreadStackSize))->cast<intx>();
2214   assert(min_ThreadStackSize == static_cast<julong>(limit->min()), "must be");
2215   assert(max_ThreadStackSize == static_cast<julong>(limit->max()), "must be");
2216 
2217   const julong min_size = min_ThreadStackSize * K;
2218   const julong max_size = max_ThreadStackSize * K;
2219 
2220   assert(is_aligned(max_size, os::vm_page_size()), "Implementation assumption");
2221 
2222   julong size = 0;
2223   ArgsRange errcode = parse_memory_size(tail, &size, min_size, max_size);
2224   if (errcode != arg_in_range) {
2225     bool silent = (option == nullptr); // Allow testing to silence error messages
2226     if (!silent) {
2227       jio_fprintf(defaultStream::error_stream(),
2228                   "Invalid thread stack size: %s\n", option->optionString);
2229       describe_range_error(errcode);
2230     }
2231     return JNI_EINVAL;
2232   }
2233 
2234   // Internally track ThreadStackSize in units of 1024 bytes.
2235   const julong size_aligned = align_up(size, K);
2236   assert(size <= size_aligned,
2237          "Overflow: " JULONG_FORMAT " " JULONG_FORMAT,
2238          size, size_aligned);
2239 
2240   const julong size_in_K = size_aligned / K;
2241   assert(size_in_K < (julong)max_intx,
2242          "size_in_K doesn't fit in the type of ThreadStackSize: " JULONG_FORMAT,
2243          size_in_K);
2244 
2245   // Check that code expanding ThreadStackSize to a page aligned number of bytes won't overflow.
2246   const julong max_expanded = align_up(size_in_K * K, os::vm_page_size());
2247   assert(max_expanded < max_uintx && max_expanded >= size_in_K,
2248          "Expansion overflowed: " JULONG_FORMAT " " JULONG_FORMAT,
2249          max_expanded, size_in_K);
2250 
2251   *out_ThreadStackSize = (intx)size_in_K;
2252 
2253   return JNI_OK;
2254 }
2255 
2256 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, JVMFlagOrigin origin) {
2257   // For match_option to return remaining or value part of option string
2258   const char* tail;
2259 
2260   // iterate over arguments
2261   for (int index = 0; index < args->nOptions; index++) {
2262     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2263 
2264     const JavaVMOption* option = args->options + index;
2265 
2266     if (!match_option(option, "-Djava.class.path", &tail) &&
2267         !match_option(option, "-Dsun.java.command", &tail) &&
2268         !match_option(option, "-Dsun.java.launcher", &tail)) {
2269 
2270         // add all jvm options to the jvm_args string. This string
2271         // is used later to set the java.vm.args PerfData string constant.
2272         // the -Djava.class.path and the -Dsun.java.command options are
2273         // omitted from jvm_args string as each have their own PerfData
2274         // string constant object.
2275         build_jvm_args(option->optionString);
2276     }
2277 
2278     // -verbose:[class/module/gc/jni]
2279     if (match_option(option, "-verbose", &tail)) {
2280       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2281         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));
2282         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));
2283       } else if (!strcmp(tail, ":module")) {
2284         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, load));
2285         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, unload));
2286       } else if (!strcmp(tail, ":gc")) {
2287         if (_legacyGCLogging.lastFlag == 0) {
2288           _legacyGCLogging.lastFlag = 1;
2289         }
2290       } else if (!strcmp(tail, ":jni")) {
2291         LogConfiguration::configure_stdout(LogLevel::Debug, true, LOG_TAGS(jni, resolve));
2292       }
2293     // -da / -ea / -disableassertions / -enableassertions
2294     // These accept an optional class/package name separated by a colon, e.g.,
2295     // -da:java.lang.Thread.
2296     } else if (match_option(option, user_assertion_options, &tail, true)) {
2297       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2298       if (*tail == '\0') {
2299         JavaAssertions::setUserClassDefault(enable);
2300       } else {
2301         assert(*tail == ':', "bogus match by match_option()");
2302         JavaAssertions::addOption(tail + 1, enable);
2303       }
2304     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2305     } else if (match_option(option, system_assertion_options, &tail, false)) {
2306       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2307       JavaAssertions::setSystemClassDefault(enable);
2308     // -bootclasspath:
2309     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2310         jio_fprintf(defaultStream::output_stream(),
2311           "-Xbootclasspath is no longer a supported option.\n");
2312         return JNI_EINVAL;
2313     // -bootclasspath/a:
2314     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2315       Arguments::append_sysclasspath(tail);
2316 #if INCLUDE_CDS
2317       MetaspaceShared::disable_optimized_module_handling();
2318       log_info(cds)("optimized module handling: disabled because bootclasspath was appended");
2319 #endif
2320     // -bootclasspath/p:
2321     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2322         jio_fprintf(defaultStream::output_stream(),
2323           "-Xbootclasspath/p is no longer a supported option.\n");
2324         return JNI_EINVAL;
2325     // -Xrun
2326     } else if (match_option(option, "-Xrun", &tail)) {
2327       if (tail != nullptr) {
2328         const char* pos = strchr(tail, ':');
2329         size_t len = (pos == nullptr) ? strlen(tail) : pos - tail;
2330         char* name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2331         jio_snprintf(name, len + 1, "%s", tail);
2332 
2333         char *options = nullptr;
2334         if(pos != nullptr) {
2335           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2336           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);
2337         }
2338 #if !INCLUDE_JVMTI
2339         if (strcmp(name, "jdwp") == 0) {
2340           jio_fprintf(defaultStream::error_stream(),
2341             "Debugging agents are not supported in this VM\n");
2342           return JNI_ERR;
2343         }
2344 #endif // !INCLUDE_JVMTI
2345         JvmtiAgentList::add_xrun(name, options, false);
2346         FREE_C_HEAP_ARRAY(char, name);
2347         FREE_C_HEAP_ARRAY(char, options);
2348       }
2349     } else if (match_option(option, "--add-reads=", &tail)) {
2350       if (!create_numbered_module_property("jdk.module.addreads", tail, addreads_count++)) {
2351         return JNI_ENOMEM;
2352       }
2353     } else if (match_option(option, "--add-exports=", &tail)) {
2354       if (!create_numbered_module_property("jdk.module.addexports", tail, addexports_count++)) {
2355         return JNI_ENOMEM;
2356       }
2357     } else if (match_option(option, "--add-opens=", &tail)) {
2358       if (!create_numbered_module_property("jdk.module.addopens", tail, addopens_count++)) {
2359         return JNI_ENOMEM;
2360       }
2361     } else if (match_option(option, "--add-modules=", &tail)) {
2362       if (!create_numbered_module_property("jdk.module.addmods", tail, addmods_count++)) {
2363         return JNI_ENOMEM;
2364       }
2365     } else if (match_option(option, "--enable-native-access=", &tail)) {
2366       if (!create_numbered_module_property("jdk.module.enable.native.access", tail, enable_native_access_count++)) {
2367         return JNI_ENOMEM;
2368       }
2369     } else if (match_option(option, "--limit-modules=", &tail)) {
2370       if (!create_module_property("jdk.module.limitmods", tail, InternalProperty)) {
2371         return JNI_ENOMEM;
2372       }
2373     } else if (match_option(option, "--module-path=", &tail)) {
2374       if (!create_module_property("jdk.module.path", tail, ExternalProperty)) {
2375         return JNI_ENOMEM;
2376       }
2377     } else if (match_option(option, "--upgrade-module-path=", &tail)) {
2378       if (!create_module_property("jdk.module.upgrade.path", tail, ExternalProperty)) {
2379         return JNI_ENOMEM;
2380       }
2381     } else if (match_option(option, "--patch-module=", &tail)) {
2382       // --patch-module=<module>=<file>(<pathsep><file>)*
2383       int res = process_patch_mod_option(tail, patch_mod_javabase);
2384       if (res != JNI_OK) {
2385         return res;
2386       }
2387     } else if (match_option(option, "--illegal-access=", &tail)) {
2388       char version[256];
2389       JDK_Version::jdk(17).to_string(version, sizeof(version));
2390       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2391     // -agentlib and -agentpath
2392     } else if (match_option(option, "-agentlib:", &tail) ||
2393           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2394       if(tail != nullptr) {
2395         const char* pos = strchr(tail, '=');
2396         char* name;
2397         if (pos == nullptr) {
2398           name = os::strdup_check_oom(tail, mtArguments);
2399         } else {
2400           size_t len = pos - tail;
2401           name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2402           memcpy(name, tail, len);
2403           name[len] = '\0';
2404         }
2405 
2406         char *options = nullptr;
2407         if(pos != nullptr) {
2408           options = os::strdup_check_oom(pos + 1, mtArguments);
2409         }
2410 #if !INCLUDE_JVMTI
2411         if (valid_jdwp_agent(name, is_absolute_path)) {
2412           jio_fprintf(defaultStream::error_stream(),
2413             "Debugging agents are not supported in this VM\n");
2414           return JNI_ERR;
2415         }
2416 #endif // !INCLUDE_JVMTI
2417         JvmtiAgentList::add(name, options, is_absolute_path);
2418         os::free(name);
2419         os::free(options);
2420       }
2421     // -javaagent
2422     } else if (match_option(option, "-javaagent:", &tail)) {
2423 #if !INCLUDE_JVMTI
2424       jio_fprintf(defaultStream::error_stream(),
2425         "Instrumentation agents are not supported in this VM\n");
2426       return JNI_ERR;
2427 #else
2428       if (tail != nullptr) {
2429         size_t length = strlen(tail) + 1;
2430         char *options = NEW_C_HEAP_ARRAY(char, length, mtArguments);
2431         jio_snprintf(options, length, "%s", tail);
2432         JvmtiAgentList::add("instrument", options, false);
2433         FREE_C_HEAP_ARRAY(char, options);
2434 
2435         // java agents need module java.instrument
2436         if (!create_numbered_module_property("jdk.module.addmods", "java.instrument", addmods_count++)) {
2437           return JNI_ENOMEM;
2438         }
2439       }
2440 #endif // !INCLUDE_JVMTI
2441     // --enable_preview
2442     } else if (match_option(option, "--enable-preview")) {
2443       set_enable_preview();
2444     // -Xnoclassgc
2445     } else if (match_option(option, "-Xnoclassgc")) {
2446       if (FLAG_SET_CMDLINE(ClassUnloading, false) != JVMFlag::SUCCESS) {
2447         return JNI_EINVAL;
2448       }
2449     // -Xbatch
2450     } else if (match_option(option, "-Xbatch")) {
2451       if (FLAG_SET_CMDLINE(BackgroundCompilation, false) != JVMFlag::SUCCESS) {
2452         return JNI_EINVAL;
2453       }
2454     // -Xmn for compatibility with other JVM vendors
2455     } else if (match_option(option, "-Xmn", &tail)) {
2456       julong long_initial_young_size = 0;
2457       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2458       if (errcode != arg_in_range) {
2459         jio_fprintf(defaultStream::error_stream(),
2460                     "Invalid initial young generation size: %s\n", option->optionString);
2461         describe_range_error(errcode);
2462         return JNI_EINVAL;
2463       }
2464       if (FLAG_SET_CMDLINE(MaxNewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {
2465         return JNI_EINVAL;
2466       }
2467       if (FLAG_SET_CMDLINE(NewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {
2468         return JNI_EINVAL;
2469       }
2470     // -Xms
2471     } else if (match_option(option, "-Xms", &tail)) {
2472       julong size = 0;
2473       // an initial heap size of 0 means automatically determine
2474       ArgsRange errcode = parse_memory_size(tail, &size, 0);
2475       if (errcode != arg_in_range) {
2476         jio_fprintf(defaultStream::error_stream(),
2477                     "Invalid initial heap size: %s\n", option->optionString);
2478         describe_range_error(errcode);
2479         return JNI_EINVAL;
2480       }
2481       if (FLAG_SET_CMDLINE(MinHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
2482         return JNI_EINVAL;
2483       }
2484       if (FLAG_SET_CMDLINE(InitialHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
2485         return JNI_EINVAL;
2486       }
2487     // -Xmx
2488     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2489       julong long_max_heap_size = 0;
2490       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2491       if (errcode != arg_in_range) {
2492         jio_fprintf(defaultStream::error_stream(),
2493                     "Invalid maximum heap size: %s\n", option->optionString);
2494         describe_range_error(errcode);
2495         return JNI_EINVAL;
2496       }
2497       if (FLAG_SET_CMDLINE(MaxHeapSize, (size_t)long_max_heap_size) != JVMFlag::SUCCESS) {
2498         return JNI_EINVAL;
2499       }
2500     // Xmaxf
2501     } else if (match_option(option, "-Xmaxf", &tail)) {
2502       char* err;
2503       int maxf = (int)(strtod(tail, &err) * 100);
2504       if (*err != '\0' || *tail == '\0') {
2505         jio_fprintf(defaultStream::error_stream(),
2506                     "Bad max heap free percentage size: %s\n",
2507                     option->optionString);
2508         return JNI_EINVAL;
2509       } else {
2510         if (FLAG_SET_CMDLINE(MaxHeapFreeRatio, maxf) != JVMFlag::SUCCESS) {
2511             return JNI_EINVAL;
2512         }
2513       }
2514     // Xminf
2515     } else if (match_option(option, "-Xminf", &tail)) {
2516       char* err;
2517       int minf = (int)(strtod(tail, &err) * 100);
2518       if (*err != '\0' || *tail == '\0') {
2519         jio_fprintf(defaultStream::error_stream(),
2520                     "Bad min heap free percentage size: %s\n",
2521                     option->optionString);
2522         return JNI_EINVAL;
2523       } else {
2524         if (FLAG_SET_CMDLINE(MinHeapFreeRatio, minf) != JVMFlag::SUCCESS) {
2525           return JNI_EINVAL;
2526         }
2527       }
2528     // -Xss
2529     } else if (match_option(option, "-Xss", &tail)) {
2530       intx value = 0;
2531       jint err = parse_xss(option, tail, &value);
2532       if (err != JNI_OK) {
2533         return err;
2534       }
2535       if (FLAG_SET_CMDLINE(ThreadStackSize, value) != JVMFlag::SUCCESS) {
2536         return JNI_EINVAL;
2537       }
2538     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2539                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2540       julong long_ReservedCodeCacheSize = 0;
2541 
2542       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2543       if (errcode != arg_in_range) {
2544         jio_fprintf(defaultStream::error_stream(),
2545                     "Invalid maximum code cache size: %s.\n", option->optionString);
2546         return JNI_EINVAL;
2547       }
2548       if (FLAG_SET_CMDLINE(ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != JVMFlag::SUCCESS) {
2549         return JNI_EINVAL;
2550       }
2551     // -green
2552     } else if (match_option(option, "-green")) {
2553       jio_fprintf(defaultStream::error_stream(),
2554                   "Green threads support not available\n");
2555           return JNI_EINVAL;
2556     // -native
2557     } else if (match_option(option, "-native")) {
2558           // HotSpot always uses native threads, ignore silently for compatibility
2559     // -Xrs
2560     } else if (match_option(option, "-Xrs")) {
2561           // Classic/EVM option, new functionality
2562       if (FLAG_SET_CMDLINE(ReduceSignalUsage, true) != JVMFlag::SUCCESS) {
2563         return JNI_EINVAL;
2564       }
2565       // -Xprof
2566     } else if (match_option(option, "-Xprof")) {
2567       char version[256];
2568       // Obsolete in JDK 10
2569       JDK_Version::jdk(10).to_string(version, sizeof(version));
2570       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2571     // -Xinternalversion
2572     } else if (match_option(option, "-Xinternalversion")) {
2573       jio_fprintf(defaultStream::output_stream(), "%s\n",
2574                   VM_Version::internal_vm_info_string());
2575       vm_exit(0);
2576 #ifndef PRODUCT
2577     // -Xprintflags
2578     } else if (match_option(option, "-Xprintflags")) {
2579       JVMFlag::printFlags(tty, false);
2580       vm_exit(0);
2581 #endif
2582     // -D
2583     } else if (match_option(option, "-D", &tail)) {
2584       const char* value;
2585       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2586             *value!= '\0' && strcmp(value, "\"\"") != 0) {
2587         // abort if -Djava.endorsed.dirs is set
2588         jio_fprintf(defaultStream::output_stream(),
2589           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2590           "in modular form will be supported via the concept of upgradeable modules.\n", value);
2591         return JNI_EINVAL;
2592       }
2593       if (match_option(option, "-Djava.ext.dirs=", &value) &&
2594             *value != '\0' && strcmp(value, "\"\"") != 0) {
2595         // abort if -Djava.ext.dirs is set
2596         jio_fprintf(defaultStream::output_stream(),
2597           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2598         return JNI_EINVAL;
2599       }
2600       // Check for module related properties.  They must be set using the modules
2601       // options. For example: use "--add-modules=java.sql", not
2602       // "-Djdk.module.addmods=java.sql"
2603       if (is_internal_module_property(option->optionString + 2)) {
2604         needs_module_property_warning = true;
2605         continue;
2606       }
2607       if (!add_property(tail)) {
2608         return JNI_ENOMEM;
2609       }
2610       // Out of the box management support
2611       if (match_option(option, "-Dcom.sun.management", &tail)) {
2612 #if INCLUDE_MANAGEMENT
2613         if (FLAG_SET_CMDLINE(ManagementServer, true) != JVMFlag::SUCCESS) {
2614           return JNI_EINVAL;
2615         }
2616         // management agent in module jdk.management.agent
2617         if (!create_numbered_module_property("jdk.module.addmods", "jdk.management.agent", addmods_count++)) {
2618           return JNI_ENOMEM;
2619         }
2620 #else
2621         jio_fprintf(defaultStream::output_stream(),
2622           "-Dcom.sun.management is not supported in this VM.\n");
2623         return JNI_ERR;
2624 #endif
2625       }
2626     // -Xint
2627     } else if (match_option(option, "-Xint")) {
2628           set_mode_flags(_int);
2629     // -Xmixed
2630     } else if (match_option(option, "-Xmixed")) {
2631           set_mode_flags(_mixed);
2632     // -Xcomp
2633     } else if (match_option(option, "-Xcomp")) {
2634       // for testing the compiler; turn off all flags that inhibit compilation
2635           set_mode_flags(_comp);
2636     // -Xshare:dump
2637     } else if (match_option(option, "-Xshare:dump")) {
2638       DumpSharedSpaces = true;
2639     // -Xshare:on
2640     } else if (match_option(option, "-Xshare:on")) {
2641       UseSharedSpaces = true;
2642       RequireSharedSpaces = true;
2643     // -Xshare:auto || -XX:ArchiveClassesAtExit=<archive file>
2644     } else if (match_option(option, "-Xshare:auto")) {
2645       UseSharedSpaces = true;
2646       RequireSharedSpaces = false;
2647       xshare_auto_cmd_line = true;
2648     // -Xshare:off
2649     } else if (match_option(option, "-Xshare:off")) {
2650       UseSharedSpaces = false;
2651       RequireSharedSpaces = false;
2652     // -Xverify
2653     } else if (match_option(option, "-Xverify", &tail)) {
2654       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
2655         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, true) != JVMFlag::SUCCESS) {
2656           return JNI_EINVAL;
2657         }
2658         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {
2659           return JNI_EINVAL;
2660         }
2661       } else if (strcmp(tail, ":remote") == 0) {
2662         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {
2663           return JNI_EINVAL;
2664         }
2665         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {
2666           return JNI_EINVAL;
2667         }
2668       } else if (strcmp(tail, ":none") == 0) {
2669         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {
2670           return JNI_EINVAL;
2671         }
2672         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, false) != JVMFlag::SUCCESS) {
2673           return JNI_EINVAL;
2674         }
2675         warning("Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.");
2676       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
2677         return JNI_EINVAL;
2678       }
2679     // -Xdebug
2680     } else if (match_option(option, "-Xdebug")) {
2681       // note this flag has been used, then ignore
2682       set_xdebug_mode(true);
2683     // -Xnoagent
2684     } else if (match_option(option, "-Xnoagent")) {
2685       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
2686     } else if (match_option(option, "-Xloggc:", &tail)) {
2687       // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
2688       log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
2689       _legacyGCLogging.lastFlag = 2;
2690       _legacyGCLogging.file = os::strdup_check_oom(tail);
2691     } else if (match_option(option, "-Xlog", &tail)) {
2692       bool ret = false;
2693       if (strcmp(tail, ":help") == 0) {
2694         fileStream stream(defaultStream::output_stream());
2695         LogConfiguration::print_command_line_help(&stream);
2696         vm_exit(0);
2697       } else if (strcmp(tail, ":disable") == 0) {
2698         LogConfiguration::disable_logging();
2699         ret = true;
2700       } else if (strcmp(tail, ":async") == 0) {
2701         LogConfiguration::set_async_mode(true);
2702         ret = true;
2703       } else if (*tail == '\0') {
2704         ret = LogConfiguration::parse_command_line_arguments();
2705         assert(ret, "-Xlog without arguments should never fail to parse");
2706       } else if (*tail == ':') {
2707         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
2708       }
2709       if (ret == false) {
2710         jio_fprintf(defaultStream::error_stream(),
2711                     "Invalid -Xlog option '-Xlog%s', see error log for details.\n",
2712                     tail);
2713         return JNI_EINVAL;
2714       }
2715     // JNI hooks
2716     } else if (match_option(option, "-Xcheck", &tail)) {
2717       if (!strcmp(tail, ":jni")) {
2718 #if !INCLUDE_JNI_CHECK
2719         warning("JNI CHECKING is not supported in this VM");
2720 #else
2721         CheckJNICalls = true;
2722 #endif // INCLUDE_JNI_CHECK
2723       } else if (is_bad_option(option, args->ignoreUnrecognized,
2724                                      "check")) {
2725         return JNI_EINVAL;
2726       }
2727     } else if (match_option(option, "vfprintf")) {
2728       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
2729     } else if (match_option(option, "exit")) {
2730       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
2731     } else if (match_option(option, "abort")) {
2732       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
2733     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
2734     // and the last option wins.
2735     } else if (match_option(option, "-XX:+NeverTenure")) {
2736       if (FLAG_SET_CMDLINE(NeverTenure, true) != JVMFlag::SUCCESS) {
2737         return JNI_EINVAL;
2738       }
2739       if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {
2740         return JNI_EINVAL;
2741       }
2742       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, markWord::max_age + 1) != JVMFlag::SUCCESS) {
2743         return JNI_EINVAL;
2744       }
2745     } else if (match_option(option, "-XX:+AlwaysTenure")) {
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       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, 0) != JVMFlag::SUCCESS) {
2753         return JNI_EINVAL;
2754       }
2755     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
2756       uintx max_tenuring_thresh = 0;
2757       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
2758         jio_fprintf(defaultStream::error_stream(),
2759                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
2760         return JNI_EINVAL;
2761       }
2762 
2763       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, max_tenuring_thresh) != JVMFlag::SUCCESS) {
2764         return JNI_EINVAL;
2765       }
2766 
2767       if (MaxTenuringThreshold == 0) {
2768         if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2769           return JNI_EINVAL;
2770         }
2771         if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {
2772           return JNI_EINVAL;
2773         }
2774       } else {
2775         if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2776           return JNI_EINVAL;
2777         }
2778         if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {
2779           return JNI_EINVAL;
2780         }
2781       }
2782     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
2783       if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, false) != JVMFlag::SUCCESS) {
2784         return JNI_EINVAL;
2785       }
2786       if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, true) != JVMFlag::SUCCESS) {
2787         return JNI_EINVAL;
2788       }
2789     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
2790       if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, false) != JVMFlag::SUCCESS) {
2791         return JNI_EINVAL;
2792       }
2793       if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, true) != JVMFlag::SUCCESS) {
2794         return JNI_EINVAL;
2795       }
2796     } else if (match_option(option, "-XX:+ErrorFileToStderr")) {
2797       if (FLAG_SET_CMDLINE(ErrorFileToStdout, false) != JVMFlag::SUCCESS) {
2798         return JNI_EINVAL;
2799       }
2800       if (FLAG_SET_CMDLINE(ErrorFileToStderr, true) != JVMFlag::SUCCESS) {
2801         return JNI_EINVAL;
2802       }
2803     } else if (match_option(option, "-XX:+ErrorFileToStdout")) {
2804       if (FLAG_SET_CMDLINE(ErrorFileToStderr, false) != JVMFlag::SUCCESS) {
2805         return JNI_EINVAL;
2806       }
2807       if (FLAG_SET_CMDLINE(ErrorFileToStdout, true) != JVMFlag::SUCCESS) {
2808         return JNI_EINVAL;
2809       }
2810     } else if (match_option(option, "--finalization=", &tail)) {
2811       if (strcmp(tail, "enabled") == 0) {
2812         InstanceKlass::set_finalization_enabled(true);
2813       } else if (strcmp(tail, "disabled") == 0) {
2814         InstanceKlass::set_finalization_enabled(false);
2815       } else {
2816         jio_fprintf(defaultStream::error_stream(),
2817                     "Invalid finalization value '%s', must be 'disabled' or 'enabled'.\n",
2818                     tail);
2819         return JNI_EINVAL;
2820       }
2821 #if !defined(DTRACE_ENABLED)
2822     } else if (match_option(option, "-XX:+DTraceMethodProbes")) {
2823       jio_fprintf(defaultStream::error_stream(),
2824                   "DTraceMethodProbes flag is not applicable for this configuration\n");
2825       return JNI_EINVAL;
2826     } else if (match_option(option, "-XX:+DTraceAllocProbes")) {
2827       jio_fprintf(defaultStream::error_stream(),
2828                   "DTraceAllocProbes flag is not applicable for this configuration\n");
2829       return JNI_EINVAL;
2830     } else if (match_option(option, "-XX:+DTraceMonitorProbes")) {
2831       jio_fprintf(defaultStream::error_stream(),
2832                   "DTraceMonitorProbes flag is not applicable for this configuration\n");
2833       return JNI_EINVAL;
2834 #endif // !defined(DTRACE_ENABLED)
2835 #ifdef ASSERT
2836     } else if (match_option(option, "-XX:+FullGCALot")) {
2837       if (FLAG_SET_CMDLINE(FullGCALot, true) != JVMFlag::SUCCESS) {
2838         return JNI_EINVAL;
2839       }
2840       // disable scavenge before parallel mark-compact
2841       if (FLAG_SET_CMDLINE(ScavengeBeforeFullGC, false) != JVMFlag::SUCCESS) {
2842         return JNI_EINVAL;
2843       }
2844 #endif
2845 #if !INCLUDE_MANAGEMENT
2846     } else if (match_option(option, "-XX:+ManagementServer")) {
2847         jio_fprintf(defaultStream::error_stream(),
2848           "ManagementServer is not supported in this VM.\n");
2849         return JNI_ERR;
2850 #endif // INCLUDE_MANAGEMENT
2851 #if INCLUDE_JVMCI
2852     } else if (match_option(option, "-XX:-EnableJVMCIProduct")) {
2853       if (EnableJVMCIProduct) {
2854         jio_fprintf(defaultStream::error_stream(),
2855                   "-XX:-EnableJVMCIProduct cannot come after -XX:+EnableJVMCIProduct\n");
2856         return JNI_EINVAL;
2857       }
2858     } else if (match_option(option, "-XX:+EnableJVMCIProduct")) {
2859       // Just continue, since "-XX:+EnableJVMCIProduct" has been specified before
2860       if (EnableJVMCIProduct) {
2861         continue;
2862       }
2863       JVMFlag *jvmciFlag = JVMFlag::find_flag("EnableJVMCIProduct");
2864       // Allow this flag if it has been unlocked.
2865       if (jvmciFlag != nullptr && jvmciFlag->is_unlocked()) {
2866         if (!JVMCIGlobals::enable_jvmci_product_mode(origin)) {
2867           jio_fprintf(defaultStream::error_stream(),
2868             "Unable to enable JVMCI in product mode");
2869           return JNI_ERR;
2870         }
2871       }
2872       // The flag was locked so process normally to report that error
2873       else if (!process_argument("EnableJVMCIProduct", args->ignoreUnrecognized, origin)) {
2874         return JNI_EINVAL;
2875       }
2876 #endif // INCLUDE_JVMCI
2877 #if INCLUDE_JFR
2878     } else if (match_jfr_option(&option)) {
2879       return JNI_EINVAL;
2880 #endif
2881     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
2882       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
2883       // already been handled
2884       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
2885           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
2886         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
2887           return JNI_EINVAL;
2888         }
2889       }
2890     // Unknown option
2891     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
2892       return JNI_ERR;
2893     }
2894   }
2895 
2896   // PrintSharedArchiveAndExit will turn on
2897   //   -Xshare:on
2898   //   -Xlog:class+path=info
2899   if (PrintSharedArchiveAndExit) {
2900     UseSharedSpaces = true;
2901     RequireSharedSpaces = true;
2902     LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));
2903   }
2904 
2905   fix_appclasspath();
2906 
2907   return JNI_OK;
2908 }
2909 
2910 void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {
2911   // For java.base check for duplicate --patch-module options being specified on the command line.
2912   // This check is only required for java.base, all other duplicate module specifications
2913   // will be checked during module system initialization.  The module system initialization
2914   // will throw an ExceptionInInitializerError if this situation occurs.
2915   if (strcmp(module_name, JAVA_BASE_NAME) == 0) {
2916     if (*patch_mod_javabase) {
2917       vm_exit_during_initialization("Cannot specify " JAVA_BASE_NAME " more than once to --patch-module");
2918     } else {
2919       *patch_mod_javabase = true;
2920     }
2921   }
2922 
2923   // Create GrowableArray lazily, only if --patch-module has been specified
2924   if (_patch_mod_prefix == nullptr) {
2925     _patch_mod_prefix = new (mtArguments) GrowableArray<ModulePatchPath*>(10, mtArguments);
2926   }
2927 
2928   _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
2929 }
2930 
2931 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
2932 //
2933 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
2934 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
2935 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
2936 // path is treated as the current directory.
2937 //
2938 // This causes problems with CDS, which requires that all directories specified in the classpath
2939 // must be empty. In most cases, applications do NOT want to load classes from the current
2940 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
2941 // scripts compatible with CDS.
2942 void Arguments::fix_appclasspath() {
2943   if (IgnoreEmptyClassPaths) {
2944     const char separator = *os::path_separator();
2945     const char* src = _java_class_path->value();
2946 
2947     // skip over all the leading empty paths
2948     while (*src == separator) {
2949       src ++;
2950     }
2951 
2952     char* copy = os::strdup_check_oom(src, mtArguments);
2953 
2954     // trim all trailing empty paths
2955     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
2956       *tail = '\0';
2957     }
2958 
2959     char from[3] = {separator, separator, '\0'};
2960     char to  [2] = {separator, '\0'};
2961     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
2962       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
2963       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
2964     }
2965 
2966     _java_class_path->set_writeable_value(copy);
2967     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
2968   }
2969 }
2970 
2971 jint Arguments::finalize_vm_init_args(bool patch_mod_javabase) {
2972   // check if the default lib/endorsed directory exists; if so, error
2973   char path[JVM_MAXPATHLEN];
2974   const char* fileSep = os::file_separator();
2975   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
2976 
2977   DIR* dir = os::opendir(path);
2978   if (dir != nullptr) {
2979     jio_fprintf(defaultStream::output_stream(),
2980       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
2981       "in modular form will be supported via the concept of upgradeable modules.\n");
2982     os::closedir(dir);
2983     return JNI_ERR;
2984   }
2985 
2986   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
2987   dir = os::opendir(path);
2988   if (dir != nullptr) {
2989     jio_fprintf(defaultStream::output_stream(),
2990       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
2991       "Use -classpath instead.\n.");
2992     os::closedir(dir);
2993     return JNI_ERR;
2994   }
2995 
2996   // This must be done after all arguments have been processed
2997   // and the container support has been initialized since AggressiveHeap
2998   // relies on the amount of total memory available.
2999   if (AggressiveHeap) {
3000     jint result = set_aggressive_heap_flags();
3001     if (result != JNI_OK) {
3002       return result;
3003     }
3004   }
3005 
3006   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3007   // but like -Xint, leave compilation thresholds unaffected.
3008   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3009   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3010     set_mode_flags(_int);
3011   }
3012 
3013 #ifdef ZERO
3014   // Zero always runs in interpreted mode
3015   set_mode_flags(_int);
3016 #endif
3017 
3018   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3019   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3020     FLAG_SET_ERGO(InitialTenuringThreshold, MaxTenuringThreshold);
3021   }
3022 
3023 #if !COMPILER2_OR_JVMCI
3024   // Don't degrade server performance for footprint
3025   if (FLAG_IS_DEFAULT(UseLargePages) &&
3026       MaxHeapSize < LargePageHeapSizeThreshold) {
3027     // No need for large granularity pages w/small heaps.
3028     // Note that large pages are enabled/disabled for both the
3029     // Java heap and the code cache.
3030     FLAG_SET_DEFAULT(UseLargePages, false);
3031   }
3032 
3033   UNSUPPORTED_OPTION(ProfileInterpreter);
3034 #endif
3035 
3036   // Parse the CompilationMode flag
3037   if (!CompilationModeFlag::initialize()) {
3038     return JNI_ERR;
3039   }
3040 
3041   if (!check_vm_args_consistency()) {
3042     return JNI_ERR;
3043   }
3044 
3045 #if INCLUDE_CDS
3046   if (DumpSharedSpaces) {
3047     // Compiler threads may concurrently update the class metadata (such as method entries), so it's
3048     // unsafe with -Xshare:dump (which modifies the class metadata in place). Let's disable
3049     // compiler just to be safe.
3050     //
3051     // Note: this is not a concern for dynamically dumping shared spaces, which makes a copy of the
3052     // class metadata instead of modifying them in place. The copy is inaccessible to the compiler.
3053     // TODO: revisit the following for the static archive case.
3054     set_mode_flags(_int);
3055 
3056     // String deduplication may cause CDS to iterate the strings in different order from one
3057     // run to another which resulting in non-determinstic CDS archives.
3058     // Disable UseStringDeduplication while dumping CDS archive.
3059     UseStringDeduplication = false;
3060   }
3061 
3062   // RecordDynamicDumpInfo is not compatible with ArchiveClassesAtExit
3063   if (ArchiveClassesAtExit != nullptr && RecordDynamicDumpInfo) {
3064     jio_fprintf(defaultStream::output_stream(),
3065                 "-XX:+RecordDynamicDumpInfo cannot be used with -XX:ArchiveClassesAtExit.\n");
3066     return JNI_ERR;
3067   }
3068 
3069   if (ArchiveClassesAtExit == nullptr && !RecordDynamicDumpInfo) {
3070     DynamicDumpSharedSpaces = false;
3071   } else {
3072     DynamicDumpSharedSpaces = true;
3073   }
3074 
3075   if (AutoCreateSharedArchive) {
3076     if (SharedArchiveFile == nullptr) {
3077       log_warning(cds)("-XX:+AutoCreateSharedArchive requires -XX:SharedArchiveFile");
3078       return JNI_ERR;
3079     }
3080     if (ArchiveClassesAtExit != nullptr) {
3081       log_warning(cds)("-XX:+AutoCreateSharedArchive does not work with ArchiveClassesAtExit");
3082       return JNI_ERR;
3083     }
3084   }
3085 
3086   if (UseSharedSpaces && patch_mod_javabase) {
3087     no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
3088   }
3089   if (UseSharedSpaces && !DumpSharedSpaces && check_unsupported_cds_runtime_properties()) {
3090     UseSharedSpaces = false;
3091   }
3092 
3093   if (DumpSharedSpaces || DynamicDumpSharedSpaces) {
3094     // Always verify non-system classes during CDS dump
3095     if (!BytecodeVerificationRemote) {
3096       BytecodeVerificationRemote = true;
3097       log_info(cds)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");
3098     }
3099   }
3100 #endif
3101 
3102 #ifndef CAN_SHOW_REGISTERS_ON_ASSERT
3103   UNSUPPORTED_OPTION(ShowRegistersOnAssert);
3104 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
3105 
3106   return JNI_OK;
3107 }
3108 
3109 // Helper class for controlling the lifetime of JavaVMInitArgs
3110 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3111 // deleted on the destruction of the ScopedVMInitArgs object.
3112 class ScopedVMInitArgs : public StackObj {
3113  private:
3114   JavaVMInitArgs _args;
3115   char*          _container_name;
3116   bool           _is_set;
3117   char*          _vm_options_file_arg;
3118 
3119  public:
3120   ScopedVMInitArgs(const char *container_name) {
3121     _args.version = JNI_VERSION_1_2;
3122     _args.nOptions = 0;
3123     _args.options = nullptr;
3124     _args.ignoreUnrecognized = false;
3125     _container_name = (char *)container_name;
3126     _is_set = false;
3127     _vm_options_file_arg = nullptr;
3128   }
3129 
3130   // Populates the JavaVMInitArgs object represented by this
3131   // ScopedVMInitArgs object with the arguments in options.  The
3132   // allocated memory is deleted by the destructor.  If this method
3133   // returns anything other than JNI_OK, then this object is in a
3134   // partially constructed state, and should be abandoned.
3135   jint set_args(const GrowableArrayView<JavaVMOption>* options) {
3136     _is_set = true;
3137     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3138         JavaVMOption, options->length(), mtArguments);
3139     if (options_arr == nullptr) {
3140       return JNI_ENOMEM;
3141     }
3142     _args.options = options_arr;
3143 
3144     for (int i = 0; i < options->length(); i++) {
3145       options_arr[i] = options->at(i);
3146       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3147       if (options_arr[i].optionString == nullptr) {
3148         // Rely on the destructor to do cleanup.
3149         _args.nOptions = i;
3150         return JNI_ENOMEM;
3151       }
3152     }
3153 
3154     _args.nOptions = options->length();
3155     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3156     return JNI_OK;
3157   }
3158 
3159   JavaVMInitArgs* get()             { return &_args; }
3160   char* container_name()            { return _container_name; }
3161   bool  is_set()                    { return _is_set; }
3162   bool  found_vm_options_file_arg() { return _vm_options_file_arg != nullptr; }
3163   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3164 
3165   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3166     if (_vm_options_file_arg != nullptr) {
3167       os::free(_vm_options_file_arg);
3168     }
3169     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3170   }
3171 
3172   ~ScopedVMInitArgs() {
3173     if (_vm_options_file_arg != nullptr) {
3174       os::free(_vm_options_file_arg);
3175     }
3176     if (_args.options == nullptr) return;
3177     for (int i = 0; i < _args.nOptions; i++) {
3178       os::free(_args.options[i].optionString);
3179     }
3180     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3181   }
3182 
3183   // Insert options into this option list, to replace option at
3184   // vm_options_file_pos (-XX:VMOptionsFile)
3185   jint insert(const JavaVMInitArgs* args,
3186               const JavaVMInitArgs* args_to_insert,
3187               const int vm_options_file_pos) {
3188     assert(_args.options == nullptr, "shouldn't be set yet");
3189     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3190     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3191 
3192     int length = args->nOptions + args_to_insert->nOptions - 1;
3193     // Construct new option array
3194     GrowableArrayCHeap<JavaVMOption, mtArguments> options(length);
3195     for (int i = 0; i < args->nOptions; i++) {
3196       if (i == vm_options_file_pos) {
3197         // insert the new options starting at the same place as the
3198         // -XX:VMOptionsFile option
3199         for (int j = 0; j < args_to_insert->nOptions; j++) {
3200           options.push(args_to_insert->options[j]);
3201         }
3202       } else {
3203         options.push(args->options[i]);
3204       }
3205     }
3206     // make into options array
3207     return set_args(&options);
3208   }
3209 };
3210 
3211 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3212   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3213 }
3214 
3215 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3216   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3217 }
3218 
3219 jint Arguments::parse_options_environment_variable(const char* name,
3220                                                    ScopedVMInitArgs* vm_args) {
3221   char *buffer = ::getenv(name);
3222 
3223   // Don't check this environment variable if user has special privileges
3224   // (e.g. unix su command).
3225   if (buffer == nullptr || os::have_special_privileges()) {
3226     return JNI_OK;
3227   }
3228 
3229   if ((buffer = os::strdup(buffer)) == nullptr) {
3230     return JNI_ENOMEM;
3231   }
3232 
3233   jio_fprintf(defaultStream::error_stream(),
3234               "Picked up %s: %s\n", name, buffer);
3235 
3236   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3237 
3238   os::free(buffer);
3239   return retcode;
3240 }
3241 
3242 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3243   // read file into buffer
3244   int fd = ::open(file_name, O_RDONLY);
3245   if (fd < 0) {
3246     jio_fprintf(defaultStream::error_stream(),
3247                 "Could not open options file '%s'\n",
3248                 file_name);
3249     return JNI_ERR;
3250   }
3251 
3252   struct stat stbuf;
3253   int retcode = os::stat(file_name, &stbuf);
3254   if (retcode != 0) {
3255     jio_fprintf(defaultStream::error_stream(),
3256                 "Could not stat options file '%s'\n",
3257                 file_name);
3258     ::close(fd);
3259     return JNI_ERR;
3260   }
3261 
3262   if (stbuf.st_size == 0) {
3263     // tell caller there is no option data and that is ok
3264     ::close(fd);
3265     return JNI_OK;
3266   }
3267 
3268   // '+ 1' for null termination even with max bytes
3269   size_t bytes_alloc = stbuf.st_size + 1;
3270 
3271   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3272   if (nullptr == buf) {
3273     jio_fprintf(defaultStream::error_stream(),
3274                 "Could not allocate read buffer for options file parse\n");
3275     ::close(fd);
3276     return JNI_ENOMEM;
3277   }
3278 
3279   memset(buf, 0, bytes_alloc);
3280 
3281   // Fill buffer
3282   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3283   ::close(fd);
3284   if (bytes_read < 0) {
3285     FREE_C_HEAP_ARRAY(char, buf);
3286     jio_fprintf(defaultStream::error_stream(),
3287                 "Could not read options file '%s'\n", file_name);
3288     return JNI_ERR;
3289   }
3290 
3291   if (bytes_read == 0) {
3292     // tell caller there is no option data and that is ok
3293     FREE_C_HEAP_ARRAY(char, buf);
3294     return JNI_OK;
3295   }
3296 
3297   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3298 
3299   FREE_C_HEAP_ARRAY(char, buf);
3300   return retcode;
3301 }
3302 
3303 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3304   // Construct option array
3305   GrowableArrayCHeap<JavaVMOption, mtArguments> options(2);
3306 
3307   // some pointers to help with parsing
3308   char *buffer_end = buffer + buf_len;
3309   char *opt_hd = buffer;
3310   char *wrt = buffer;
3311   char *rd = buffer;
3312 
3313   // parse all options
3314   while (rd < buffer_end) {
3315     // skip leading white space from the input string
3316     while (rd < buffer_end && isspace(*rd)) {
3317       rd++;
3318     }
3319 
3320     if (rd >= buffer_end) {
3321       break;
3322     }
3323 
3324     // Remember this is where we found the head of the token.
3325     opt_hd = wrt;
3326 
3327     // Tokens are strings of non white space characters separated
3328     // by one or more white spaces.
3329     while (rd < buffer_end && !isspace(*rd)) {
3330       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3331         int quote = *rd;                    // matching quote to look for
3332         rd++;                               // don't copy open quote
3333         while (rd < buffer_end && *rd != quote) {
3334                                             // include everything (even spaces)
3335                                             // up until the close quote
3336           *wrt++ = *rd++;                   // copy to option string
3337         }
3338 
3339         if (rd < buffer_end) {
3340           rd++;                             // don't copy close quote
3341         } else {
3342                                             // did not see closing quote
3343           jio_fprintf(defaultStream::error_stream(),
3344                       "Unmatched quote in %s\n", name);
3345           return JNI_ERR;
3346         }
3347       } else {
3348         *wrt++ = *rd++;                     // copy to option string
3349       }
3350     }
3351 
3352     // steal a white space character and set it to null
3353     *wrt++ = '\0';
3354     // We now have a complete token
3355 
3356     JavaVMOption option;
3357     option.optionString = opt_hd;
3358     option.extraInfo = nullptr;
3359 
3360     options.append(option);                // Fill in option
3361 
3362     rd++;  // Advance to next character
3363   }
3364 
3365   // Fill out JavaVMInitArgs structure.
3366   return vm_args->set_args(&options);
3367 }
3368 
3369 void Arguments::set_shared_spaces_flags_and_archive_paths() {
3370   if (DumpSharedSpaces) {
3371     if (RequireSharedSpaces) {
3372       warning("Cannot dump shared archive while using shared archive");
3373     }
3374     UseSharedSpaces = false;
3375   }
3376 #if INCLUDE_CDS
3377   // Initialize shared archive paths which could include both base and dynamic archive paths
3378   // This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.
3379   //
3380   // UseSharedSpaces may be disabled if -XX:SharedArchiveFile is invalid.
3381   if (DumpSharedSpaces || UseSharedSpaces) {
3382     init_shared_archive_paths();
3383   }
3384 #endif  // INCLUDE_CDS
3385 }
3386 
3387 #if INCLUDE_CDS
3388 // Sharing support
3389 // Construct the path to the archive
3390 char* Arguments::get_default_shared_archive_path() {
3391   if (_default_shared_archive_path == nullptr) {
3392     char jvm_path[JVM_MAXPATHLEN];
3393     os::jvm_path(jvm_path, sizeof(jvm_path));
3394     char *end = strrchr(jvm_path, *os::file_separator());
3395     if (end != nullptr) *end = '\0';
3396     size_t jvm_path_len = strlen(jvm_path);
3397     size_t file_sep_len = strlen(os::file_separator());
3398     const size_t len = jvm_path_len + file_sep_len + 20;
3399     _default_shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);
3400     jio_snprintf(_default_shared_archive_path, len,
3401                 LP64_ONLY(!UseCompressedOops ? "%s%sclasses_nocoops.jsa":) "%s%sclasses.jsa",
3402                 jvm_path, os::file_separator());
3403   }
3404   return _default_shared_archive_path;
3405 }
3406 
3407 int Arguments::num_archives(const char* archive_path) {
3408   if (archive_path == nullptr) {
3409     return 0;
3410   }
3411   int npaths = 1;
3412   char* p = (char*)archive_path;
3413   while (*p != '\0') {
3414     if (*p == os::path_separator()[0]) {
3415       npaths++;
3416     }
3417     p++;
3418   }
3419   return npaths;
3420 }
3421 
3422 void Arguments::extract_shared_archive_paths(const char* archive_path,
3423                                          char** base_archive_path,
3424                                          char** top_archive_path) {
3425   char* begin_ptr = (char*)archive_path;
3426   char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);
3427   if (end_ptr == nullptr || end_ptr == begin_ptr) {
3428     vm_exit_during_initialization("Base archive was not specified", archive_path);
3429   }
3430   size_t len = end_ptr - begin_ptr;
3431   char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
3432   strncpy(cur_path, begin_ptr, len);
3433   cur_path[len] = '\0';
3434   *base_archive_path = cur_path;
3435 
3436   begin_ptr = ++end_ptr;
3437   if (*begin_ptr == '\0') {
3438     vm_exit_during_initialization("Top archive was not specified", archive_path);
3439   }
3440   end_ptr = strchr(begin_ptr, '\0');
3441   assert(end_ptr != nullptr, "sanity");
3442   len = end_ptr - begin_ptr;
3443   cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
3444   strncpy(cur_path, begin_ptr, len + 1);
3445   *top_archive_path = cur_path;
3446 }
3447 
3448 void Arguments::init_shared_archive_paths() {
3449   if (ArchiveClassesAtExit != nullptr) {
3450     assert(!RecordDynamicDumpInfo, "already checked");
3451     if (DumpSharedSpaces) {
3452       vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");
3453     }
3454     check_unsupported_dumping_properties();
3455 
3456     if (os::same_files(get_default_shared_archive_path(), ArchiveClassesAtExit)) {
3457       vm_exit_during_initialization(
3458         "Cannot specify the default CDS archive for -XX:ArchiveClassesAtExit", get_default_shared_archive_path());
3459     }
3460   }
3461 
3462   if (SharedArchiveFile == nullptr) {
3463     SharedArchivePath = get_default_shared_archive_path();
3464   } else {
3465     int archives = num_archives(SharedArchiveFile);
3466     assert(archives > 0, "must be");
3467 
3468     if (is_dumping_archive() && archives > 1) {
3469       vm_exit_during_initialization(
3470         "Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");
3471     }
3472 
3473     if (DumpSharedSpaces) {
3474       assert(archives == 1, "must be");
3475       // Static dump is simple: only one archive is allowed in SharedArchiveFile. This file
3476       // will be overwritten no matter regardless of its contents
3477       SharedArchivePath = os::strdup_check_oom(SharedArchiveFile, mtArguments);
3478     } else {
3479       // SharedArchiveFile may specify one or two files. In case (c), the path for base.jsa
3480       // is read from top.jsa
3481       //    (a) 1 file:  -XX:SharedArchiveFile=base.jsa
3482       //    (b) 2 files: -XX:SharedArchiveFile=base.jsa:top.jsa
3483       //    (c) 2 files: -XX:SharedArchiveFile=top.jsa
3484       //
3485       // However, if either RecordDynamicDumpInfo or ArchiveClassesAtExit is used, we do not
3486       // allow cases (b) and (c). Case (b) is already checked above.
3487 
3488       if (archives > 2) {
3489         vm_exit_during_initialization(
3490           "Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");
3491       }
3492       if (archives == 1) {
3493         char* base_archive_path = nullptr;
3494         bool success =
3495           FileMapInfo::get_base_archive_name_from_header(SharedArchiveFile, &base_archive_path);
3496         if (!success) {
3497           // If +AutoCreateSharedArchive and the specified shared archive does not exist,
3498           // regenerate the dynamic archive base on default archive.
3499           if (AutoCreateSharedArchive && !os::file_exists(SharedArchiveFile)) {
3500             DynamicDumpSharedSpaces = true;
3501             ArchiveClassesAtExit = const_cast<char *>(SharedArchiveFile);
3502             SharedArchivePath = get_default_shared_archive_path();
3503             SharedArchiveFile = nullptr;
3504           } else {
3505             if (AutoCreateSharedArchive) {
3506               warning("-XX:+AutoCreateSharedArchive is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
3507               AutoCreateSharedArchive = false;
3508             }
3509             no_shared_spaces("invalid archive");
3510           }
3511         } else if (base_archive_path == nullptr) {
3512           // User has specified a single archive, which is a static archive.
3513           SharedArchivePath = const_cast<char *>(SharedArchiveFile);
3514         } else {
3515           // User has specified a single archive, which is a dynamic archive.
3516           SharedDynamicArchivePath = const_cast<char *>(SharedArchiveFile);
3517           SharedArchivePath = base_archive_path; // has been c-heap allocated.
3518         }
3519       } else {
3520         extract_shared_archive_paths((const char*)SharedArchiveFile,
3521                                       &SharedArchivePath, &SharedDynamicArchivePath);
3522         if (SharedArchivePath == nullptr) {
3523           assert(SharedDynamicArchivePath == nullptr, "must be");
3524           no_shared_spaces("invalid archive");
3525         }
3526       }
3527 
3528       if (SharedDynamicArchivePath != nullptr) {
3529         // Check for case (c)
3530         if (RecordDynamicDumpInfo) {
3531           vm_exit_during_initialization("-XX:+RecordDynamicDumpInfo is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
3532                                         SharedArchiveFile);
3533         }
3534         if (ArchiveClassesAtExit != nullptr) {
3535           vm_exit_during_initialization("-XX:ArchiveClassesAtExit is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
3536                                         SharedArchiveFile);
3537         }
3538       }
3539 
3540       if (ArchiveClassesAtExit != nullptr && os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {
3541           vm_exit_during_initialization(
3542             "Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",
3543             SharedArchiveFile);
3544       }
3545     }
3546   }
3547 }
3548 #endif // INCLUDE_CDS
3549 
3550 #ifndef PRODUCT
3551 // Determine whether LogVMOutput should be implicitly turned on.
3552 static bool use_vm_log() {
3553   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3554       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3555       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3556       PrintAssembly || TraceDeoptimization ||
3557       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3558     return true;
3559   }
3560 
3561 #ifdef COMPILER1
3562   if (PrintC1Statistics) {
3563     return true;
3564   }
3565 #endif // COMPILER1
3566 
3567 #ifdef COMPILER2
3568   if (PrintOptoAssembly || PrintOptoStatistics) {
3569     return true;
3570   }
3571 #endif // COMPILER2
3572 
3573   return false;
3574 }
3575 
3576 #endif // PRODUCT
3577 
3578 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3579   for (int index = 0; index < args->nOptions; index++) {
3580     const JavaVMOption* option = args->options + index;
3581     const char* tail;
3582     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3583       return true;
3584     }
3585   }
3586   return false;
3587 }
3588 
3589 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3590                                        const char* vm_options_file,
3591                                        const int vm_options_file_pos,
3592                                        ScopedVMInitArgs* vm_options_file_args,
3593                                        ScopedVMInitArgs* args_out) {
3594   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
3595   if (code != JNI_OK) {
3596     return code;
3597   }
3598 
3599   if (vm_options_file_args->get()->nOptions < 1) {
3600     return JNI_OK;
3601   }
3602 
3603   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
3604     jio_fprintf(defaultStream::error_stream(),
3605                 "A VM options file may not refer to a VM options file. "
3606                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
3607                 "options file '%s' in options container '%s' is an error.\n",
3608                 vm_options_file_args->vm_options_file_arg(),
3609                 vm_options_file_args->container_name());
3610     return JNI_EINVAL;
3611   }
3612 
3613   return args_out->insert(args, vm_options_file_args->get(),
3614                           vm_options_file_pos);
3615 }
3616 
3617 // Expand -XX:VMOptionsFile found in args_in as needed.
3618 // mod_args and args_out parameters may return values as needed.
3619 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
3620                                             ScopedVMInitArgs* mod_args,
3621                                             JavaVMInitArgs** args_out) {
3622   jint code = match_special_option_and_act(args_in, mod_args);
3623   if (code != JNI_OK) {
3624     return code;
3625   }
3626 
3627   if (mod_args->is_set()) {
3628     // args_in contains -XX:VMOptionsFile and mod_args contains the
3629     // original options from args_in along with the options expanded
3630     // from the VMOptionsFile. Return a short-hand to the caller.
3631     *args_out = mod_args->get();
3632   } else {
3633     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
3634   }
3635   return JNI_OK;
3636 }
3637 
3638 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3639                                              ScopedVMInitArgs* args_out) {
3640   // Remaining part of option string
3641   const char* tail;
3642   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
3643 
3644   for (int index = 0; index < args->nOptions; index++) {
3645     const JavaVMOption* option = args->options + index;
3646     if (match_option(option, "-XX:Flags=", &tail)) {
3647       Arguments::set_jvm_flags_file(tail);
3648       continue;
3649     }
3650     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3651       if (vm_options_file_args.found_vm_options_file_arg()) {
3652         jio_fprintf(defaultStream::error_stream(),
3653                     "The option '%s' is already specified in the options "
3654                     "container '%s' so the specification of '%s' in the "
3655                     "same options container is an error.\n",
3656                     vm_options_file_args.vm_options_file_arg(),
3657                     vm_options_file_args.container_name(),
3658                     option->optionString);
3659         return JNI_EINVAL;
3660       }
3661       vm_options_file_args.set_vm_options_file_arg(option->optionString);
3662       // If there's a VMOptionsFile, parse that
3663       jint code = insert_vm_options_file(args, tail, index,
3664                                          &vm_options_file_args, args_out);
3665       if (code != JNI_OK) {
3666         return code;
3667       }
3668       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
3669       if (args_out->is_set()) {
3670         // The VMOptions file inserted some options so switch 'args'
3671         // to the new set of options, and continue processing which
3672         // preserves "last option wins" semantics.
3673         args = args_out->get();
3674         // The first option from the VMOptionsFile replaces the
3675         // current option.  So we back track to process the
3676         // replacement option.
3677         index--;
3678       }
3679       continue;
3680     }
3681     if (match_option(option, "-XX:+PrintVMOptions")) {
3682       PrintVMOptions = true;
3683       continue;
3684     }
3685     if (match_option(option, "-XX:-PrintVMOptions")) {
3686       PrintVMOptions = false;
3687       continue;
3688     }
3689     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3690       IgnoreUnrecognizedVMOptions = true;
3691       continue;
3692     }
3693     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3694       IgnoreUnrecognizedVMOptions = false;
3695       continue;
3696     }
3697     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3698       JVMFlag::printFlags(tty, false);
3699       vm_exit(0);
3700     }
3701 
3702 #ifndef PRODUCT
3703     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3704       JVMFlag::printFlags(tty, true);
3705       vm_exit(0);
3706     }
3707 #endif
3708   }
3709   return JNI_OK;
3710 }
3711 
3712 static void print_options(const JavaVMInitArgs *args) {
3713   const char* tail;
3714   for (int index = 0; index < args->nOptions; index++) {
3715     const JavaVMOption *option = args->options + index;
3716     if (match_option(option, "-XX:", &tail)) {
3717       logOption(tail);
3718     }
3719   }
3720 }
3721 
3722 bool Arguments::handle_deprecated_print_gc_flags() {
3723   if (PrintGC) {
3724     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
3725   }
3726   if (PrintGCDetails) {
3727     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
3728   }
3729 
3730   if (_legacyGCLogging.lastFlag == 2) {
3731     // -Xloggc was used to specify a filename
3732     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
3733 
3734     LogTarget(Error, logging) target;
3735     LogStream errstream(target);
3736     return LogConfiguration::parse_log_arguments(_legacyGCLogging.file, gc_conf, nullptr, nullptr, &errstream);
3737   } else if (PrintGC || PrintGCDetails || (_legacyGCLogging.lastFlag == 1)) {
3738     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
3739   }
3740   return true;
3741 }
3742 
3743 static void apply_debugger_ergo() {
3744 #ifndef PRODUCT
3745   // UseDebuggerErgo is notproduct
3746   if (ReplayCompiles) {
3747     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo, true);
3748   }
3749 #endif
3750 
3751 #ifndef PRODUCT
3752   if (UseDebuggerErgo) {
3753     // Turn on sub-flags
3754     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo1, true);
3755     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo2, true);
3756   }
3757 #endif
3758 
3759   if (UseDebuggerErgo2) {
3760     // Debugging with limited number of CPUs
3761     FLAG_SET_ERGO_IF_DEFAULT(UseNUMA, false);
3762     FLAG_SET_ERGO_IF_DEFAULT(ConcGCThreads, 1);
3763     FLAG_SET_ERGO_IF_DEFAULT(ParallelGCThreads, 1);
3764     FLAG_SET_ERGO_IF_DEFAULT(CICompilerCount, 2);
3765   }
3766 }
3767 
3768 // Parse entry point called from JNI_CreateJavaVM
3769 
3770 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
3771   assert(verify_special_jvm_flags(false), "deprecated and obsolete flag table inconsistent");
3772   JVMFlag::check_all_flag_declarations();
3773 
3774   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3775   const char* hotspotrc = ".hotspotrc";
3776   bool settings_file_specified = false;
3777   bool needs_hotspotrc_warning = false;
3778   ScopedVMInitArgs initial_vm_options_args("");
3779   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3780   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
3781 
3782   // Pointers to current working set of containers
3783   JavaVMInitArgs* cur_cmd_args;
3784   JavaVMInitArgs* cur_vm_options_args;
3785   JavaVMInitArgs* cur_java_options_args;
3786   JavaVMInitArgs* cur_java_tool_options_args;
3787 
3788   // Containers for modified/expanded options
3789   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
3790   ScopedVMInitArgs mod_vm_options_args("vm_options_args");
3791   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3792   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
3793 
3794 
3795   jint code =
3796       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
3797   if (code != JNI_OK) {
3798     return code;
3799   }
3800 
3801   code = parse_java_options_environment_variable(&initial_java_options_args);
3802   if (code != JNI_OK) {
3803     return code;
3804   }
3805 
3806   // Parse the options in the /java.base/jdk/internal/vm/options resource, if present
3807   char *vmoptions = ClassLoader::lookup_vm_options();
3808   if (vmoptions != nullptr) {
3809     code = parse_options_buffer("vm options resource", vmoptions, strlen(vmoptions), &initial_vm_options_args);
3810     FREE_C_HEAP_ARRAY(char, vmoptions);
3811     if (code != JNI_OK) {
3812       return code;
3813     }
3814   }
3815 
3816   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
3817                                      &mod_java_tool_options_args,
3818                                      &cur_java_tool_options_args);
3819   if (code != JNI_OK) {
3820     return code;
3821   }
3822 
3823   code = expand_vm_options_as_needed(initial_cmd_args,
3824                                      &mod_cmd_args,
3825                                      &cur_cmd_args);
3826   if (code != JNI_OK) {
3827     return code;
3828   }
3829 
3830   code = expand_vm_options_as_needed(initial_java_options_args.get(),
3831                                      &mod_java_options_args,
3832                                      &cur_java_options_args);
3833   if (code != JNI_OK) {
3834     return code;
3835   }
3836 
3837   code = expand_vm_options_as_needed(initial_vm_options_args.get(),
3838                                      &mod_vm_options_args,
3839                                      &cur_vm_options_args);
3840   if (code != JNI_OK) {
3841     return code;
3842   }
3843 
3844   const char* flags_file = Arguments::get_jvm_flags_file();
3845   settings_file_specified = (flags_file != nullptr);
3846 
3847   if (IgnoreUnrecognizedVMOptions) {
3848     cur_cmd_args->ignoreUnrecognized = true;
3849     cur_java_tool_options_args->ignoreUnrecognized = true;
3850     cur_java_options_args->ignoreUnrecognized = true;
3851   }
3852 
3853   // Parse specified settings file
3854   if (settings_file_specified) {
3855     if (!process_settings_file(flags_file, true,
3856                                cur_cmd_args->ignoreUnrecognized)) {
3857       return JNI_EINVAL;
3858     }
3859   } else {
3860 #ifdef ASSERT
3861     // Parse default .hotspotrc settings file
3862     if (!process_settings_file(".hotspotrc", false,
3863                                cur_cmd_args->ignoreUnrecognized)) {
3864       return JNI_EINVAL;
3865     }
3866 #else
3867     struct stat buf;
3868     if (os::stat(hotspotrc, &buf) == 0) {
3869       needs_hotspotrc_warning = true;
3870     }
3871 #endif
3872   }
3873 
3874   if (PrintVMOptions) {
3875     print_options(cur_java_tool_options_args);
3876     print_options(cur_cmd_args);
3877     print_options(cur_java_options_args);
3878   }
3879 
3880   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
3881   jint result = parse_vm_init_args(cur_vm_options_args,
3882                                    cur_java_tool_options_args,
3883                                    cur_java_options_args,
3884                                    cur_cmd_args);
3885 
3886   if (result != JNI_OK) {
3887     return result;
3888   }
3889 
3890   // Delay warning until here so that we've had a chance to process
3891   // the -XX:-PrintWarnings flag
3892   if (needs_hotspotrc_warning) {
3893     warning("%s file is present but has been ignored.  "
3894             "Run with -XX:Flags=%s to load the file.",
3895             hotspotrc, hotspotrc);
3896   }
3897 
3898   if (needs_module_property_warning) {
3899     warning("Ignoring system property options whose names match the '-Djdk.module.*'."
3900             " names that are reserved for internal use.");
3901   }
3902 
3903 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
3904   UNSUPPORTED_OPTION(UseLargePages);
3905 #endif
3906 
3907 #if defined(AIX)
3908   UNSUPPORTED_OPTION_NULL(AllocateHeapAt);
3909 #endif
3910 
3911 #ifndef PRODUCT
3912   if (TraceBytecodesAt != 0) {
3913     TraceBytecodes = true;
3914   }
3915   if (CountCompiledCalls) {
3916     if (UseCounterDecay) {
3917       warning("UseCounterDecay disabled because CountCalls is set");
3918       UseCounterDecay = false;
3919     }
3920   }
3921 #endif // PRODUCT
3922 
3923   if (ScavengeRootsInCode == 0) {
3924     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3925       warning("Forcing ScavengeRootsInCode non-zero");
3926     }
3927     ScavengeRootsInCode = 1;
3928   }
3929 
3930   if (!handle_deprecated_print_gc_flags()) {
3931     return JNI_EINVAL;
3932   }
3933 
3934   // Set object alignment values.
3935   set_object_alignment();
3936 
3937 #if !INCLUDE_CDS
3938   if (DumpSharedSpaces || RequireSharedSpaces) {
3939     jio_fprintf(defaultStream::error_stream(),
3940       "Shared spaces are not supported in this VM\n");
3941     return JNI_ERR;
3942   }
3943   if (DumpLoadedClassList != nullptr) {
3944     jio_fprintf(defaultStream::error_stream(),
3945       "DumpLoadedClassList is not supported in this VM\n");
3946     return JNI_ERR;
3947   }
3948   if ((UseSharedSpaces && xshare_auto_cmd_line) ||
3949       log_is_enabled(Info, cds)) {
3950     warning("Shared spaces are not supported in this VM");
3951     UseSharedSpaces = false;
3952     LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(cds));
3953   }
3954   no_shared_spaces("CDS Disabled");
3955 #endif // INCLUDE_CDS
3956 
3957   // Verify NMT arguments
3958   const NMT_TrackingLevel lvl = NMTUtil::parse_tracking_level(NativeMemoryTracking);
3959   if (lvl == NMT_unknown) {
3960     jio_fprintf(defaultStream::error_stream(),
3961                 "Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", nullptr);
3962     return JNI_ERR;
3963   }
3964   if (PrintNMTStatistics && lvl == NMT_off) {
3965     warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
3966     FLAG_SET_DEFAULT(PrintNMTStatistics, false);
3967   }
3968 
3969   bool trace_dependencies = log_is_enabled(Debug, dependencies);
3970   if (trace_dependencies && VerifyDependencies) {
3971     warning("dependency logging results may be inflated by VerifyDependencies");
3972   }
3973 
3974   apply_debugger_ergo();
3975 
3976   if (log_is_enabled(Info, arguments)) {
3977     LogStream st(Log(arguments)::info());
3978     Arguments::print_on(&st);
3979   }
3980 
3981   return JNI_OK;
3982 }
3983 
3984 jint Arguments::apply_ergo() {
3985   // Set flags based on ergonomics.
3986   jint result = set_ergonomics_flags();
3987   if (result != JNI_OK) return result;
3988 
3989   // Set heap size based on available physical memory
3990   set_heap_size();
3991 
3992   GCConfig::arguments()->initialize();
3993 
3994   set_shared_spaces_flags_and_archive_paths();
3995 
3996   // Initialize Metaspace flags and alignments
3997   Metaspace::ergo_initialize();
3998 
3999   if (!StringDedup::ergo_initialize()) {
4000     return JNI_EINVAL;
4001   }
4002 
4003   // Set compiler flags after GC is selected and GC specific
4004   // flags (LoopStripMiningIter) are set.
4005   CompilerConfig::ergo_initialize();
4006 
4007   // Set bytecode rewriting flags
4008   set_bytecode_flags();
4009 
4010   // Set flags if aggressive optimization flags are enabled
4011   jint code = set_aggressive_opts_flags();
4012   if (code != JNI_OK) {
4013     return code;
4014   }
4015 
4016 #ifdef ZERO
4017   // Clear flags not supported on zero.
4018   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4019 #endif // ZERO
4020 
4021   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4022     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4023     DebugNonSafepoints = true;
4024   }
4025 
4026   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4027     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4028   }
4029 
4030   // Treat the odd case where local verification is enabled but remote
4031   // verification is not as if both were enabled.
4032   if (BytecodeVerificationLocal && !BytecodeVerificationRemote) {
4033     log_info(verification)("Turning on remote verification because local verification is on");
4034     FLAG_SET_DEFAULT(BytecodeVerificationRemote, true);
4035   }
4036 
4037 #ifndef PRODUCT
4038   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4039     if (use_vm_log()) {
4040       LogVMOutput = true;
4041     }
4042   }
4043 #endif // PRODUCT
4044 
4045   if (PrintCommandLineFlags) {
4046     JVMFlag::printSetFlags(tty);
4047   }
4048 
4049 #ifdef COMPILER2
4050   if (!FLAG_IS_DEFAULT(EnableVectorSupport) && !EnableVectorSupport) {
4051     if (!FLAG_IS_DEFAULT(EnableVectorReboxing) && EnableVectorReboxing) {
4052       warning("Disabling EnableVectorReboxing since EnableVectorSupport is turned off.");
4053     }
4054     FLAG_SET_DEFAULT(EnableVectorReboxing, false);
4055 
4056     if (!FLAG_IS_DEFAULT(EnableVectorAggressiveReboxing) && EnableVectorAggressiveReboxing) {
4057       if (!EnableVectorReboxing) {
4058         warning("Disabling EnableVectorAggressiveReboxing since EnableVectorReboxing is turned off.");
4059       } else {
4060         warning("Disabling EnableVectorAggressiveReboxing since EnableVectorSupport is turned off.");
4061       }
4062     }
4063     FLAG_SET_DEFAULT(EnableVectorAggressiveReboxing, false);
4064 
4065     if (!FLAG_IS_DEFAULT(UseVectorStubs) && UseVectorStubs) {
4066       warning("Disabling UseVectorStubs since EnableVectorSupport is turned off.");
4067     }
4068     FLAG_SET_DEFAULT(UseVectorStubs, false);
4069   }
4070 #endif // COMPILER2
4071 
4072   if (FLAG_IS_CMDLINE(DiagnoseSyncOnValueBasedClasses)) {
4073     if (DiagnoseSyncOnValueBasedClasses == ObjectSynchronizer::LOG_WARNING && !log_is_enabled(Info, valuebasedclasses)) {
4074       LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(valuebasedclasses));
4075     }
4076   }
4077   return JNI_OK;
4078 }
4079 
4080 jint Arguments::adjust_after_os() {
4081   if (UseNUMA) {
4082     if (UseParallelGC) {
4083       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4084          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4085       }
4086     }
4087   }
4088   return JNI_OK;
4089 }
4090 
4091 int Arguments::PropertyList_count(SystemProperty* pl) {
4092   int count = 0;
4093   while(pl != nullptr) {
4094     count++;
4095     pl = pl->next();
4096   }
4097   return count;
4098 }
4099 
4100 // Return the number of readable properties.
4101 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
4102   int count = 0;
4103   while(pl != nullptr) {
4104     if (pl->readable()) {
4105       count++;
4106     }
4107     pl = pl->next();
4108   }
4109   return count;
4110 }
4111 
4112 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4113   assert(key != nullptr, "just checking");
4114   SystemProperty* prop;
4115   for (prop = pl; prop != nullptr; prop = prop->next()) {
4116     if (strcmp(key, prop->key()) == 0) return prop->value();
4117   }
4118   return nullptr;
4119 }
4120 
4121 // Return the value of the requested property provided that it is a readable property.
4122 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4123   assert(key != nullptr, "just checking");
4124   SystemProperty* prop;
4125   // Return the property value if the keys match and the property is not internal or
4126   // it's the special internal property "jdk.boot.class.path.append".
4127   for (prop = pl; prop != nullptr; prop = prop->next()) {
4128     if (strcmp(key, prop->key()) == 0) {
4129       if (!prop->internal()) {
4130         return prop->value();
4131       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4132         return prop->value();
4133       } else {
4134         // Property is internal and not jdk.boot.class.path.append so return null.
4135         return nullptr;
4136       }
4137     }
4138   }
4139   return nullptr;
4140 }
4141 
4142 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4143   SystemProperty* p = *plist;
4144   if (p == nullptr) {
4145     *plist = new_p;
4146   } else {
4147     while (p->next() != nullptr) {
4148       p = p->next();
4149     }
4150     p->set_next(new_p);
4151   }
4152 }
4153 
4154 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4155                                  bool writeable, bool internal) {
4156   if (plist == nullptr)
4157     return;
4158 
4159   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4160   PropertyList_add(plist, new_p);
4161 }
4162 
4163 void Arguments::PropertyList_add(SystemProperty *element) {
4164   PropertyList_add(&_system_properties, element);
4165 }
4166 
4167 // This add maintains unique property key in the list.
4168 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4169                                         PropertyAppendable append, PropertyWriteable writeable,
4170                                         PropertyInternal internal) {
4171   if (plist == nullptr)
4172     return;
4173 
4174   // If property key exists and is writeable, then update with new value.
4175   // Trying to update a non-writeable property is silently ignored.
4176   SystemProperty* prop;
4177   for (prop = *plist; prop != nullptr; prop = prop->next()) {
4178     if (strcmp(k, prop->key()) == 0) {
4179       if (append == AppendProperty) {
4180         prop->append_writeable_value(v);
4181       } else {
4182         prop->set_writeable_value(v);
4183       }
4184       return;
4185     }
4186   }
4187 
4188   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4189 }
4190 
4191 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4192 // Returns true if all of the source pointed by src has been copied over to
4193 // the destination buffer pointed by buf. Otherwise, returns false.
4194 // Notes:
4195 // 1. If the length (buflen) of the destination buffer excluding the
4196 // null terminator character is not long enough for holding the expanded
4197 // pid characters, it also returns false instead of returning the partially
4198 // expanded one.
4199 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4200 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4201                                 char* buf, size_t buflen) {
4202   const char* p = src;
4203   char* b = buf;
4204   const char* src_end = &src[srclen];
4205   char* buf_end = &buf[buflen - 1];
4206 
4207   while (p < src_end && b < buf_end) {
4208     if (*p == '%') {
4209       switch (*(++p)) {
4210       case '%':         // "%%" ==> "%"
4211         *b++ = *p++;
4212         break;
4213       case 'p':  {       //  "%p" ==> current process id
4214         // buf_end points to the character before the last character so
4215         // that we could write '\0' to the end of the buffer.
4216         size_t buf_sz = buf_end - b + 1;
4217         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4218 
4219         // if jio_snprintf fails or the buffer is not long enough to hold
4220         // the expanded pid, returns false.
4221         if (ret < 0 || ret >= (int)buf_sz) {
4222           return false;
4223         } else {
4224           b += ret;
4225           assert(*b == '\0', "fail in copy_expand_pid");
4226           if (p == src_end && b == buf_end + 1) {
4227             // reach the end of the buffer.
4228             return true;
4229           }
4230         }
4231         p++;
4232         break;
4233       }
4234       default :
4235         *b++ = '%';
4236       }
4237     } else {
4238       *b++ = *p++;
4239     }
4240   }
4241   *b = '\0';
4242   return (p == src_end); // return false if not all of the source was copied
4243 }