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