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