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