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