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