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