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