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