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