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