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