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