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