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