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