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