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