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 
  78 static const char _default_java_launcher[] = "generic";
  79 
  80 #define DEFAULT_JAVA_LAUNCHER _default_java_launcher
  81 
  82 char*  Arguments::_jvm_flags_file               = nullptr;
  83 char** Arguments::_jvm_flags_array              = nullptr;
  84 int    Arguments::_num_jvm_flags                = 0;
  85 char** Arguments::_jvm_args_array               = nullptr;
  86 int    Arguments::_num_jvm_args                 = 0;
  87 char*  Arguments::_java_command                 = nullptr;
  88 SystemProperty* Arguments::_system_properties   = nullptr;
  89 size_t Arguments::_conservative_max_heap_alignment = 0;
  90 Arguments::Mode Arguments::_mode                = _mixed;
  91 const char*  Arguments::_java_vendor_url_bug    = nullptr;
  92 const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
  93 bool   Arguments::_sun_java_launcher_is_altjvm  = false;
  94 
  95 // These parameters are reset in method parse_vm_init_args()
  96 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
  97 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
  98 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
  99 bool   Arguments::_ClipInlining                 = ClipInlining;
 100 size_t Arguments::_default_SharedBaseAddress    = SharedBaseAddress;
 101 
 102 bool   Arguments::_enable_preview               = false;
 103 
 104 LegacyGCLogging Arguments::_legacyGCLogging     = { 0, 0 };
 105 
 106 // These are not set by the JDK's built-in launchers, but they can be set by
 107 // programs that embed the JVM using JNI_CreateJavaVM. See comments around
 108 // JavaVMOption in jni.h.
 109 abort_hook_t     Arguments::_abort_hook         = nullptr;
 110 exit_hook_t      Arguments::_exit_hook          = nullptr;
 111 vfprintf_hook_t  Arguments::_vfprintf_hook      = nullptr;
 112 
 113 
 114 SystemProperty *Arguments::_sun_boot_library_path = nullptr;
 115 SystemProperty *Arguments::_java_library_path = nullptr;
 116 SystemProperty *Arguments::_java_home = nullptr;
 117 SystemProperty *Arguments::_java_class_path = nullptr;
 118 SystemProperty *Arguments::_jdk_boot_class_path_append = nullptr;
 119 SystemProperty *Arguments::_vm_info = nullptr;
 120 
 121 GrowableArray<ModulePatchPath*> *Arguments::_patch_mod_prefix = nullptr;
 122 PathString *Arguments::_boot_class_path = nullptr;
 123 bool Arguments::_has_jimage = false;
 124 
 125 char* Arguments::_ext_dirs = nullptr;
 126 
 127 // True if -Xshare:auto option was specified.
 128 static bool xshare_auto_cmd_line = false;
 129 
 130 // True if -Xint/-Xmixed/-Xcomp were specified
 131 static bool mode_flag_cmd_line = false;
 132 
 133 bool PathString::set_value(const char *value, AllocFailType alloc_failmode) {
 134   char* new_value = AllocateHeap(strlen(value)+1, mtArguments, alloc_failmode);
 135   if (new_value == nullptr) {
 136     assert(alloc_failmode == AllocFailStrategy::RETURN_NULL, "must be");
 137     return false;
 138   }
 139   if (_value != nullptr) {
 140     FreeHeap(_value);
 141   }
 142   _value = new_value;
 143   strcpy(_value, value);
 144   return true;
 145 }
 146 
 147 void PathString::append_value(const char *value) {
 148   char *sp;
 149   size_t len = 0;
 150   if (value != nullptr) {
 151     len = strlen(value);
 152     if (_value != nullptr) {
 153       len += strlen(_value);
 154     }
 155     sp = AllocateHeap(len+2, mtArguments);
 156     assert(sp != nullptr, "Unable to allocate space for new append path value");
 157     if (sp != nullptr) {
 158       if (_value != nullptr) {
 159         strcpy(sp, _value);
 160         strcat(sp, os::path_separator());
 161         strcat(sp, value);
 162         FreeHeap(_value);
 163       } else {
 164         strcpy(sp, value);
 165       }
 166       _value = sp;
 167     }
 168   }
 169 }
 170 
 171 PathString::PathString(const char* value) {
 172   if (value == nullptr) {
 173     _value = nullptr;
 174   } else {
 175     _value = AllocateHeap(strlen(value)+1, mtArguments);
 176     strcpy(_value, value);
 177   }
 178 }
 179 
 180 PathString::~PathString() {
 181   if (_value != nullptr) {
 182     FreeHeap(_value);
 183     _value = nullptr;
 184   }
 185 }
 186 
 187 ModulePatchPath::ModulePatchPath(const char* module_name, const char* path) {
 188   assert(module_name != nullptr && path != nullptr, "Invalid module name or path value");
 189   size_t len = strlen(module_name) + 1;
 190   _module_name = AllocateHeap(len, mtInternal);
 191   strncpy(_module_name, module_name, len); // copy the trailing null
 192   _path =  new PathString(path);
 193 }
 194 
 195 ModulePatchPath::~ModulePatchPath() {
 196   if (_module_name != nullptr) {
 197     FreeHeap(_module_name);
 198     _module_name = nullptr;
 199   }
 200   if (_path != nullptr) {
 201     delete _path;
 202     _path = nullptr;
 203   }
 204 }
 205 
 206 SystemProperty::SystemProperty(const char* key, const char* value, bool writeable, bool internal) : PathString(value) {
 207   if (key == nullptr) {
 208     _key = nullptr;
 209   } else {
 210     _key = AllocateHeap(strlen(key)+1, mtArguments);
 211     strcpy(_key, key);
 212   }
 213   _next = nullptr;
 214   _internal = internal;
 215   _writeable = writeable;
 216 }
 217 
 218 // Check if head of 'option' matches 'name', and sets 'tail' to the remaining
 219 // part of the option string.
 220 static bool match_option(const JavaVMOption *option, const char* name,
 221                          const char** tail) {
 222   size_t len = strlen(name);
 223   if (strncmp(option->optionString, name, len) == 0) {
 224     *tail = option->optionString + len;
 225     return true;
 226   } else {
 227     return false;
 228   }
 229 }
 230 
 231 // Check if 'option' matches 'name'. No "tail" is allowed.
 232 static bool match_option(const JavaVMOption *option, const char* name) {
 233   const char* tail = nullptr;
 234   bool result = match_option(option, name, &tail);
 235   if (tail != nullptr && *tail == '\0') {
 236     return result;
 237   } else {
 238     return false;
 239   }
 240 }
 241 
 242 // Return true if any of the strings in null-terminated array 'names' matches.
 243 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
 244 // the option must match exactly.
 245 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
 246   bool tail_allowed) {
 247   for (/* empty */; *names != nullptr; ++names) {
 248   if (match_option(option, *names, tail)) {
 249       if (**tail == '\0' || (tail_allowed && **tail == ':')) {
 250         return true;
 251       }
 252     }
 253   }
 254   return false;
 255 }
 256 
 257 #if INCLUDE_JFR
 258 static bool _has_jfr_option = false;  // is using JFR
 259 
 260 // return true on failure
 261 static bool match_jfr_option(const JavaVMOption** option) {
 262   assert((*option)->optionString != nullptr, "invariant");
 263   char* tail = nullptr;
 264   if (match_option(*option, "-XX:StartFlightRecording", (const char**)&tail)) {
 265     _has_jfr_option = true;
 266     return Jfr::on_start_flight_recording_option(option, tail);
 267   } else if (match_option(*option, "-XX:FlightRecorderOptions", (const char**)&tail)) {
 268     _has_jfr_option = true;
 269     return Jfr::on_flight_recorder_option(option, tail);
 270   }
 271   return false;
 272 }
 273 
 274 bool Arguments::has_jfr_option() {
 275   return _has_jfr_option;
 276 }
 277 #endif
 278 
 279 static void logOption(const char* opt) {
 280   if (PrintVMOptions) {
 281     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
 282   }
 283 }
 284 
 285 bool needs_module_property_warning = false;
 286 
 287 #define MODULE_PROPERTY_PREFIX "jdk.module."
 288 #define MODULE_PROPERTY_PREFIX_LEN 11
 289 #define ADDEXPORTS "addexports"
 290 #define ADDEXPORTS_LEN 10
 291 #define ADDREADS "addreads"
 292 #define ADDREADS_LEN 8
 293 #define ADDOPENS "addopens"
 294 #define ADDOPENS_LEN 8
 295 #define PATCH "patch"
 296 #define PATCH_LEN 5
 297 #define ADDMODS "addmods"
 298 #define ADDMODS_LEN 7
 299 #define LIMITMODS "limitmods"
 300 #define LIMITMODS_LEN 9
 301 #define PATH "path"
 302 #define PATH_LEN 4
 303 #define UPGRADE_PATH "upgrade.path"
 304 #define UPGRADE_PATH_LEN 12
 305 #define ENABLE_NATIVE_ACCESS "enable.native.access"
 306 #define ENABLE_NATIVE_ACCESS_LEN 20
 307 
 308 // Return TRUE if option matches 'property', or 'property=', or 'property.'.
 309 static bool matches_property_suffix(const char* option, const char* property, size_t len) {
 310   return ((strncmp(option, property, len) == 0) &&
 311           (option[len] == '=' || option[len] == '.' || option[len] == '\0'));
 312 }
 313 
 314 // Return true if property starts with "jdk.module." and its ensuing chars match
 315 // any of the reserved module properties.
 316 // property should be passed without the leading "-D".
 317 bool Arguments::is_internal_module_property(const char* property) {
 318   if  (strncmp(property, MODULE_PROPERTY_PREFIX, MODULE_PROPERTY_PREFIX_LEN) == 0) {
 319     const char* property_suffix = property + MODULE_PROPERTY_PREFIX_LEN;
 320     if (matches_property_suffix(property_suffix, ADDEXPORTS, ADDEXPORTS_LEN) ||
 321         matches_property_suffix(property_suffix, ADDREADS, ADDREADS_LEN) ||
 322         matches_property_suffix(property_suffix, ADDOPENS, ADDOPENS_LEN) ||
 323         matches_property_suffix(property_suffix, PATCH, PATCH_LEN) ||
 324         matches_property_suffix(property_suffix, ADDMODS, ADDMODS_LEN) ||
 325         matches_property_suffix(property_suffix, LIMITMODS, LIMITMODS_LEN) ||
 326         matches_property_suffix(property_suffix, PATH, PATH_LEN) ||
 327         matches_property_suffix(property_suffix, UPGRADE_PATH, UPGRADE_PATH_LEN) ||
 328         matches_property_suffix(property_suffix, ENABLE_NATIVE_ACCESS, ENABLE_NATIVE_ACCESS_LEN)) {
 329       return true;
 330     }
 331   }
 332   return false;
 333 }
 334 
 335 // Process java launcher properties.
 336 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
 337   // See if sun.java.launcher or sun.java.launcher.is_altjvm is defined.
 338   // Must do this before setting up other system properties,
 339   // as some of them may depend on launcher type.
 340   for (int index = 0; index < args->nOptions; index++) {
 341     const JavaVMOption* option = args->options + index;
 342     const char* tail;
 343 
 344     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
 345       process_java_launcher_argument(tail, option->extraInfo);
 346       continue;
 347     }
 348     if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
 349       if (strcmp(tail, "true") == 0) {
 350         _sun_java_launcher_is_altjvm = true;
 351       }
 352       continue;
 353     }
 354   }
 355 }
 356 
 357 // Initialize system properties key and value.
 358 void Arguments::init_system_properties() {
 359 
 360   // Set up _boot_class_path which is not a property but
 361   // relies heavily on argument processing and the jdk.boot.class.path.append
 362   // property. It is used to store the underlying boot class path.
 363   _boot_class_path = new PathString(nullptr);
 364 
 365   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
 366                                                            "Java Virtual Machine Specification",  false));
 367   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
 368   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
 369   PropertyList_add(&_system_properties, new SystemProperty("jdk.debug", VM_Version::jdk_debug_level(),  false));
 370 
 371   // Initialize the vm.info now, but it will need updating after argument parsing.
 372   _vm_info = new SystemProperty("java.vm.info", VM_Version::vm_info_string(), true);
 373 
 374   // Following are JVMTI agent writable properties.
 375   // Properties values are set to nullptr and they are
 376   // os specific they are initialized in os::init_system_properties_values().
 377   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", nullptr,  true);
 378   _java_library_path = new SystemProperty("java.library.path", nullptr,  true);
 379   _java_home =  new SystemProperty("java.home", nullptr,  true);
 380   _java_class_path = new SystemProperty("java.class.path", "",  true);
 381   // jdk.boot.class.path.append is a non-writeable, internal property.
 382   // It can only be set by either:
 383   //    - -Xbootclasspath/a:
 384   //    - AddToBootstrapClassLoaderSearch during JVMTI OnLoad phase
 385   _jdk_boot_class_path_append = new SystemProperty("jdk.boot.class.path.append", nullptr, false, true);
 386 
 387   // Add to System Property list.
 388   PropertyList_add(&_system_properties, _sun_boot_library_path);
 389   PropertyList_add(&_system_properties, _java_library_path);
 390   PropertyList_add(&_system_properties, _java_home);
 391   PropertyList_add(&_system_properties, _java_class_path);
 392   PropertyList_add(&_system_properties, _jdk_boot_class_path_append);
 393   PropertyList_add(&_system_properties, _vm_info);
 394 
 395   // Set OS specific system properties values
 396   os::init_system_properties_values();
 397 }
 398 
 399 // Update/Initialize System properties after JDK version number is known
 400 void Arguments::init_version_specific_system_properties() {
 401   enum { bufsz = 16 };
 402   char buffer[bufsz];
 403   const char* spec_vendor = "Oracle Corporation";
 404   uint32_t spec_version = JDK_Version::current().major_version();
 405 
 406   jio_snprintf(buffer, bufsz, UINT32_FORMAT, spec_version);
 407 
 408   PropertyList_add(&_system_properties,
 409       new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
 410   PropertyList_add(&_system_properties,
 411       new SystemProperty("java.vm.specification.version", buffer, false));
 412   PropertyList_add(&_system_properties,
 413       new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
 414 }
 415 
 416 /*
 417  *  -XX argument processing:
 418  *
 419  *  -XX arguments are defined in several places, such as:
 420  *      globals.hpp, globals_<cpu>.hpp, globals_<os>.hpp, <compiler>_globals.hpp, or <gc>_globals.hpp.
 421  *  -XX arguments are parsed in parse_argument().
 422  *  -XX argument bounds checking is done in check_vm_args_consistency().
 423  *
 424  * Over time -XX arguments may change. There are mechanisms to handle common cases:
 425  *
 426  *      ALIASED: An option that is simply another name for another option. This is often
 427  *               part of the process of deprecating a flag, but not all aliases need
 428  *               to be deprecated.
 429  *
 430  *               Create an alias for an option by adding the old and new option names to the
 431  *               "aliased_jvm_flags" table. Delete the old variable from globals.hpp (etc).
 432  *
 433  *   DEPRECATED: An option that is supported, but a warning is printed to let the user know that
 434  *               support may be removed in the future. Both regular and aliased options may be
 435  *               deprecated.
 436  *
 437  *               Add a deprecation warning for an option (or alias) by adding an entry in the
 438  *               "special_jvm_flags" table and setting the "deprecated_in" field.
 439  *               Often an option "deprecated" in one major release will
 440  *               be made "obsolete" in the next. In this case the entry should also have its
 441  *               "obsolete_in" field set.
 442  *
 443  *     OBSOLETE: An option that has been removed (and deleted from globals.hpp), but is still accepted
 444  *               on the command line. A warning is printed to let the user know that option might not
 445  *               be accepted in the future.
 446  *
 447  *               Add an obsolete warning for an option by adding an entry in the "special_jvm_flags"
 448  *               table and setting the "obsolete_in" field.
 449  *
 450  *      EXPIRED: A deprecated or obsolete option that has an "accept_until" version less than or equal
 451  *               to the current JDK version. The system will flatly refuse to admit the existence of
 452  *               the flag. This allows a flag to die automatically over JDK releases.
 453  *
 454  *               Note that manual cleanup of expired options should be done at major JDK version upgrades:
 455  *                  - Newly expired options should be removed from the special_jvm_flags and aliased_jvm_flags tables.
 456  *                  - Newly obsolete or expired deprecated options should have their global variable
 457  *                    definitions removed (from globals.hpp, etc) and related implementations removed.
 458  *
 459  * Recommended approach for removing options:
 460  *
 461  * To remove options commonly used by customers (e.g. product -XX options), use
 462  * the 3-step model adding major release numbers to the deprecate, obsolete and expire columns.
 463  *
 464  * To remove internal options (e.g. diagnostic, experimental, develop options), use
 465  * a 2-step model adding major release numbers to the obsolete and expire columns.
 466  *
 467  * To change the name of an option, use the alias table as well as a 2-step
 468  * model adding major release numbers to the deprecate and expire columns.
 469  * Think twice about aliasing commonly used customer options.
 470  *
 471  * There are times when it is appropriate to leave a future release number as undefined.
 472  *
 473  * Tests:  Aliases should be tested in VMAliasOptions.java.
 474  *         Deprecated options should be tested in VMDeprecatedOptions.java.
 475  */
 476 
 477 // The special_jvm_flags table declares options that are being deprecated and/or obsoleted. The
 478 // "deprecated_in" or "obsolete_in" fields may be set to "undefined", but not both.
 479 // When the JDK version reaches 'deprecated_in' limit, the JVM will process this flag on
 480 // the command-line as usual, but will issue a warning.
 481 // When the JDK version reaches 'obsolete_in' limit, the JVM will continue accepting this flag on
 482 // the command-line, while issuing a warning and ignoring the flag value.
 483 // Once the JDK version reaches 'expired_in' limit, the JVM will flatly refuse to admit the
 484 // existence of the flag.
 485 //
 486 // MANUAL CLEANUP ON JDK VERSION UPDATES:
 487 // This table ensures that the handling of options will update automatically when the JDK
 488 // version is incremented, but the source code needs to be cleanup up manually:
 489 // - As "deprecated" options age into "obsolete" or "expired" options, the associated "globals"
 490 //   variable should be removed, as well as users of the variable.
 491 // - As "deprecated" options age into "obsolete" options, move the entry into the
 492 //   "Obsolete Flags" section of the table.
 493 // - All expired options should be removed from the table.
 494 static SpecialFlag const special_jvm_flags[] = {
 495   // -------------- Deprecated Flags --------------
 496   // --- Non-alias flags - sorted by obsolete_in then expired_in:
 497   { "AllowRedefinitionToAddDeleteMethods", JDK_Version::jdk(13), JDK_Version::undefined(), JDK_Version::undefined() },
 498   { "FlightRecorder",               JDK_Version::jdk(13), JDK_Version::undefined(), JDK_Version::undefined() },
 499   { "DumpSharedSpaces",             JDK_Version::jdk(18), JDK_Version::jdk(19), JDK_Version::undefined() },
 500   { "DynamicDumpSharedSpaces",      JDK_Version::jdk(18), JDK_Version::jdk(19), JDK_Version::undefined() },
 501   { "RequireSharedSpaces",          JDK_Version::jdk(18), JDK_Version::jdk(19), JDK_Version::undefined() },
 502   { "UseSharedSpaces",              JDK_Version::jdk(18), JDK_Version::jdk(19), JDK_Version::undefined() },
 503   { "RegisterFinalizersAtInit",     JDK_Version::jdk(22), JDK_Version::jdk(23), JDK_Version::jdk(24) },
 504 #if defined(X86)
 505   { "UseRTMLocking",                JDK_Version::jdk(23), JDK_Version::jdk(24), JDK_Version::jdk(25) },
 506   { "UseRTMDeopt",                  JDK_Version::jdk(23), JDK_Version::jdk(24), JDK_Version::jdk(25) },
 507   { "RTMRetryCount",                JDK_Version::jdk(23), JDK_Version::jdk(24), JDK_Version::jdk(25) },
 508 #endif // X86
 509   // --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in:
 510   { "CreateMinidumpOnCrash",        JDK_Version::jdk(9),  JDK_Version::undefined(), JDK_Version::undefined() },
 511 
 512   // -------------- Obsolete Flags - sorted by expired_in --------------
 513 
 514   { "MetaspaceReclaimPolicy",       JDK_Version::undefined(), JDK_Version::jdk(21), JDK_Version::undefined() },
 515 
 516   { "G1ConcRefinementGreenZone",    JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::jdk(24) },
 517   { "G1ConcRefinementYellowZone",   JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::jdk(24) },
 518   { "G1ConcRefinementRedZone",      JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::jdk(24) },
 519   { "G1ConcRefinementThresholdStep", JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::jdk(24) },
 520   { "G1UseAdaptiveConcRefinement",  JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::jdk(24) },
 521   { "G1ConcRefinementServiceIntervalMillis", JDK_Version::undefined(), JDK_Version::jdk(20), JDK_Version::jdk(24) },
 522 
 523   { "G1ConcRSLogCacheSize",         JDK_Version::undefined(), JDK_Version::jdk(21), JDK_Version::jdk(24) },
 524   { "G1ConcRSHotCardLimit",         JDK_Version::undefined(), JDK_Version::jdk(21), JDK_Version::jdk(24) },
 525   { "RefDiscoveryPolicy",           JDK_Version::undefined(), JDK_Version::jdk(21), JDK_Version::jdk(24) },
 526 
 527   { "AdaptiveSizePolicyCollectionCostMargin",   JDK_Version::undefined(), JDK_Version::jdk(23), JDK_Version::jdk(24) },
 528   { "MaxGCMinorPauseMillis",        JDK_Version::jdk(8), JDK_Version::jdk(23), JDK_Version::jdk(24) },
 529   { "MaxRAMFraction",               JDK_Version::jdk(10),  JDK_Version::jdk(23), JDK_Version::jdk(24) },
 530   { "MinRAMFraction",               JDK_Version::jdk(10),  JDK_Version::jdk(23), JDK_Version::jdk(24) },
 531   { "InitialRAMFraction",           JDK_Version::jdk(10),  JDK_Version::jdk(23), JDK_Version::jdk(24) },
 532   { "DefaultMaxRAMFraction",        JDK_Version::jdk(8),  JDK_Version::jdk(23), JDK_Version::jdk(24) },
 533   { "TLABStats",                    JDK_Version::jdk(12), JDK_Version::jdk(23), JDK_Version::jdk(24) },
 534   { "GCLockerEdenExpansionPercent", JDK_Version::undefined(), JDK_Version::jdk(23), JDK_Version::jdk(24) },
 535   { "NUMAPageScanRate",             JDK_Version::undefined(), JDK_Version::jdk(23), JDK_Version::jdk(24) },
 536   { "ProcessDistributionStride",    JDK_Version::undefined(), JDK_Version::jdk(23), JDK_Version::jdk(24) },
 537 
 538   { "ParallelOldDeadWoodLimiterMean",   JDK_Version::undefined(), JDK_Version::jdk(23), JDK_Version::jdk(24) },
 539   { "ParallelOldDeadWoodLimiterStdDev", JDK_Version::undefined(), JDK_Version::jdk(23), JDK_Version::jdk(24) },
 540 #ifdef ASSERT
 541   { "DummyObsoleteTestFlag",        JDK_Version::undefined(), JDK_Version::jdk(18), JDK_Version::undefined() },
 542 #endif
 543 
 544 #ifdef TEST_VERIFY_SPECIAL_JVM_FLAGS
 545   // These entries will generate build errors.  Their purpose is to test the macros.
 546   { "dep > obs",                    JDK_Version::jdk(9), JDK_Version::jdk(8), JDK_Version::undefined() },
 547   { "dep > exp ",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(8) },
 548   { "obs > exp ",                   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(8) },
 549   { "obs > exp",                    JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::jdk(10) },
 550   { "not deprecated or obsolete",   JDK_Version::undefined(), JDK_Version::undefined(), JDK_Version::jdk(9) },
 551   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 552   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 553 #endif
 554 
 555   { nullptr, JDK_Version(0), JDK_Version(0) }
 556 };
 557 
 558 // Flags that are aliases for other flags.
 559 typedef struct {
 560   const char* alias_name;
 561   const char* real_name;
 562 } AliasedFlag;
 563 
 564 static AliasedFlag const aliased_jvm_flags[] = {
 565   { "CreateMinidumpOnCrash",    "CreateCoredumpOnCrash" },
 566   { nullptr, nullptr}
 567 };
 568 
 569 // Return true if "v" is less than "other", where "other" may be "undefined".
 570 static bool version_less_than(JDK_Version v, JDK_Version other) {
 571   assert(!v.is_undefined(), "must be defined");
 572   if (!other.is_undefined() && v.compare(other) >= 0) {
 573     return false;
 574   } else {
 575     return true;
 576   }
 577 }
 578 
 579 static bool lookup_special_flag(const char *flag_name, SpecialFlag& flag) {
 580   for (size_t i = 0; special_jvm_flags[i].name != nullptr; i++) {
 581     if ((strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 582       flag = special_jvm_flags[i];
 583       return true;
 584     }
 585   }
 586   return false;
 587 }
 588 
 589 bool Arguments::is_obsolete_flag(const char *flag_name, JDK_Version* version) {
 590   assert(version != nullptr, "Must provide a version buffer");
 591   SpecialFlag flag;
 592   if (lookup_special_flag(flag_name, flag)) {
 593     if (!flag.obsolete_in.is_undefined()) {
 594       if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 595         *version = flag.obsolete_in;
 596         // This flag may have been marked for obsoletion in this version, but we may not
 597         // have actually removed it yet. Rather than ignoring it as soon as we reach
 598         // this version we allow some time for the removal to happen. So if the flag
 599         // still actually exists we process it as normal, but issue an adjusted warning.
 600         const JVMFlag *real_flag = JVMFlag::find_declared_flag(flag_name);
 601         if (real_flag != nullptr) {
 602           char version_str[256];
 603           version->to_string(version_str, sizeof(version_str));
 604           warning("Temporarily processing option %s; support is scheduled for removal in %s",
 605                   flag_name, version_str);
 606           return false;
 607         }
 608         return true;
 609       }
 610     }
 611   }
 612   return false;
 613 }
 614 
 615 int Arguments::is_deprecated_flag(const char *flag_name, JDK_Version* version) {
 616   assert(version != nullptr, "Must provide a version buffer");
 617   SpecialFlag flag;
 618   if (lookup_special_flag(flag_name, flag)) {
 619     if (!flag.deprecated_in.is_undefined()) {
 620       if (version_less_than(JDK_Version::current(), flag.obsolete_in) &&
 621           version_less_than(JDK_Version::current(), flag.expired_in)) {
 622         *version = flag.deprecated_in;
 623         return 1;
 624       } else {
 625         return -1;
 626       }
 627     }
 628   }
 629   return 0;
 630 }
 631 
 632 const char* Arguments::real_flag_name(const char *flag_name) {
 633   for (size_t i = 0; aliased_jvm_flags[i].alias_name != nullptr; i++) {
 634     const AliasedFlag& flag_status = aliased_jvm_flags[i];
 635     if (strcmp(flag_status.alias_name, flag_name) == 0) {
 636         return flag_status.real_name;
 637     }
 638   }
 639   return flag_name;
 640 }
 641 
 642 #ifdef ASSERT
 643 static bool lookup_special_flag(const char *flag_name, size_t skip_index) {
 644   for (size_t i = 0; special_jvm_flags[i].name != nullptr; i++) {
 645     if ((i != skip_index) && (strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 646       return true;
 647     }
 648   }
 649   return false;
 650 }
 651 
 652 // Verifies the correctness of the entries in the special_jvm_flags table.
 653 // If there is a semantic error (i.e. a bug in the table) such as the obsoletion
 654 // version being earlier than the deprecation version, then a warning is issued
 655 // and verification fails - by returning false. If it is detected that the table
 656 // is out of date, with respect to the current version, then ideally a warning is
 657 // issued but verification does not fail. This allows the VM to operate when the
 658 // version is first updated, without needing to update all the impacted flags at
 659 // the same time. In practice we can't issue the warning immediately when the version
 660 // is updated as it occurs for every test and some tests are not prepared to handle
 661 // unexpected output - see 8196739. Instead we only check if the table is up-to-date
 662 // if the check_globals flag is true, and in addition allow a grace period and only
 663 // check for stale flags when we hit build 25 (which is far enough into the 6 month
 664 // release cycle that all flag updates should have been processed, whilst still
 665 // leaving time to make the change before RDP2).
 666 // We use a gtest to call this, passing true, so that we can detect stale flags before
 667 // the end of the release cycle.
 668 
 669 static const int SPECIAL_FLAG_VALIDATION_BUILD = 25;
 670 
 671 bool Arguments::verify_special_jvm_flags(bool check_globals) {
 672   bool success = true;
 673   for (size_t i = 0; special_jvm_flags[i].name != nullptr; i++) {
 674     const SpecialFlag& flag = special_jvm_flags[i];
 675     if (lookup_special_flag(flag.name, i)) {
 676       warning("Duplicate special flag declaration \"%s\"", flag.name);
 677       success = false;
 678     }
 679     if (flag.deprecated_in.is_undefined() &&
 680         flag.obsolete_in.is_undefined()) {
 681       warning("Special flag entry \"%s\" must declare version deprecated and/or obsoleted in.", flag.name);
 682       success = false;
 683     }
 684 
 685     if (!flag.deprecated_in.is_undefined()) {
 686       if (!version_less_than(flag.deprecated_in, flag.obsolete_in)) {
 687         warning("Special flag entry \"%s\" must be deprecated before obsoleted.", flag.name);
 688         success = false;
 689       }
 690 
 691       if (!version_less_than(flag.deprecated_in, flag.expired_in)) {
 692         warning("Special flag entry \"%s\" must be deprecated before expired.", flag.name);
 693         success = false;
 694       }
 695     }
 696 
 697     if (!flag.obsolete_in.is_undefined()) {
 698       if (!version_less_than(flag.obsolete_in, flag.expired_in)) {
 699         warning("Special flag entry \"%s\" must be obsoleted before expired.", flag.name);
 700         success = false;
 701       }
 702 
 703       // if flag has become obsolete it should not have a "globals" flag defined anymore.
 704       if (check_globals && VM_Version::vm_build_number() >= SPECIAL_FLAG_VALIDATION_BUILD &&
 705           !version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 706         if (JVMFlag::find_declared_flag(flag.name) != nullptr) {
 707           warning("Global variable for obsolete special flag entry \"%s\" should be removed", flag.name);
 708           success = false;
 709         }
 710       }
 711 
 712     } else if (!flag.expired_in.is_undefined()) {
 713       warning("Special flag entry \"%s\" must be explicitly obsoleted before expired.", flag.name);
 714       success = false;
 715     }
 716 
 717     if (!flag.expired_in.is_undefined()) {
 718       // if flag has become expired it should not have a "globals" flag defined anymore.
 719       if (check_globals && VM_Version::vm_build_number() >= SPECIAL_FLAG_VALIDATION_BUILD &&
 720           !version_less_than(JDK_Version::current(), flag.expired_in)) {
 721         if (JVMFlag::find_declared_flag(flag.name) != nullptr) {
 722           warning("Global variable for expired flag entry \"%s\" should be removed", flag.name);
 723           success = false;
 724         }
 725       }
 726     }
 727   }
 728   return success;
 729 }
 730 #endif
 731 
 732 bool Arguments::atojulong(const char *s, julong* result) {
 733   return parse_integer(s, result);
 734 }
 735 
 736 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size, julong max_size) {
 737   if (size < min_size) return arg_too_small;
 738   if (size > max_size) return arg_too_big;
 739   return arg_in_range;
 740 }
 741 
 742 // Describe an argument out of range error
 743 void Arguments::describe_range_error(ArgsRange errcode) {
 744   switch(errcode) {
 745   case arg_too_big:
 746     jio_fprintf(defaultStream::error_stream(),
 747                 "The specified size exceeds the maximum "
 748                 "representable size.\n");
 749     break;
 750   case arg_too_small:
 751   case arg_unreadable:
 752   case arg_in_range:
 753     // do nothing for now
 754     break;
 755   default:
 756     ShouldNotReachHere();
 757   }
 758 }
 759 
 760 static bool set_bool_flag(JVMFlag* flag, bool value, JVMFlagOrigin origin) {
 761   if (JVMFlagAccess::set_bool(flag, &value, origin) == JVMFlag::SUCCESS) {
 762     return true;
 763   } else {
 764     return false;
 765   }
 766 }
 767 
 768 static bool set_fp_numeric_flag(JVMFlag* flag, const char* value, JVMFlagOrigin origin) {
 769   // strtod allows leading whitespace, but our flag format does not.
 770   if (*value == '\0' || isspace(*value)) {
 771     return false;
 772   }
 773   char* end;
 774   errno = 0;
 775   double v = strtod(value, &end);
 776   if ((errno != 0) || (*end != 0)) {
 777     return false;
 778   }
 779   if (g_isnan(v) || !g_isfinite(v)) {
 780     // Currently we cannot handle these special values.
 781     return false;
 782   }
 783 
 784   if (JVMFlagAccess::set_double(flag, &v, origin) == JVMFlag::SUCCESS) {
 785     return true;
 786   }
 787   return false;
 788 }
 789 
 790 static bool set_numeric_flag(JVMFlag* flag, const char* value, JVMFlagOrigin origin) {
 791   JVMFlag::Error result = JVMFlag::WRONG_FORMAT;
 792 
 793   if (flag->is_int()) {
 794     int v;
 795     if (parse_integer(value, &v)) {
 796       result = JVMFlagAccess::set_int(flag, &v, origin);
 797     }
 798   } else if (flag->is_uint()) {
 799     uint v;
 800     if (parse_integer(value, &v)) {
 801       result = JVMFlagAccess::set_uint(flag, &v, origin);
 802     }
 803   } else if (flag->is_intx()) {
 804     intx v;
 805     if (parse_integer(value, &v)) {
 806       result = JVMFlagAccess::set_intx(flag, &v, origin);
 807     }
 808   } else if (flag->is_uintx()) {
 809     uintx v;
 810     if (parse_integer(value, &v)) {
 811       result = JVMFlagAccess::set_uintx(flag, &v, origin);
 812     }
 813   } else if (flag->is_uint64_t()) {
 814     uint64_t v;
 815     if (parse_integer(value, &v)) {
 816       result = JVMFlagAccess::set_uint64_t(flag, &v, origin);
 817     }
 818   } else if (flag->is_size_t()) {
 819     size_t v;
 820     if (parse_integer(value, &v)) {
 821       result = JVMFlagAccess::set_size_t(flag, &v, origin);
 822     }
 823   }
 824 
 825   return result == JVMFlag::SUCCESS;
 826 }
 827 
 828 static bool set_string_flag(JVMFlag* flag, const char* value, JVMFlagOrigin origin) {
 829   if (value[0] == '\0') {
 830     value = nullptr;
 831   }
 832   if (JVMFlagAccess::set_ccstr(flag, &value, origin) != JVMFlag::SUCCESS) return false;
 833   // Contract:  JVMFlag always returns a pointer that needs freeing.
 834   FREE_C_HEAP_ARRAY(char, value);
 835   return true;
 836 }
 837 
 838 static bool append_to_string_flag(JVMFlag* flag, const char* new_value, JVMFlagOrigin origin) {
 839   const char* old_value = "";
 840   if (JVMFlagAccess::get_ccstr(flag, &old_value) != JVMFlag::SUCCESS) return false;
 841   size_t old_len = old_value != nullptr ? strlen(old_value) : 0;
 842   size_t new_len = strlen(new_value);
 843   const char* value;
 844   char* free_this_too = nullptr;
 845   if (old_len == 0) {
 846     value = new_value;
 847   } else if (new_len == 0) {
 848     value = old_value;
 849   } else {
 850      size_t length = old_len + 1 + new_len + 1;
 851      char* buf = NEW_C_HEAP_ARRAY(char, length, mtArguments);
 852     // each new setting adds another LINE to the switch:
 853     jio_snprintf(buf, length, "%s\n%s", old_value, new_value);
 854     value = buf;
 855     free_this_too = buf;
 856   }
 857   (void) JVMFlagAccess::set_ccstr(flag, &value, origin);
 858   // JVMFlag always returns a pointer that needs freeing.
 859   FREE_C_HEAP_ARRAY(char, value);
 860   // JVMFlag made its own copy, so I must delete my own temp. buffer.
 861   FREE_C_HEAP_ARRAY(char, free_this_too);
 862   return true;
 863 }
 864 
 865 const char* Arguments::handle_aliases_and_deprecation(const char* arg) {
 866   const char* real_name = real_flag_name(arg);
 867   JDK_Version since = JDK_Version();
 868   switch (is_deprecated_flag(arg, &since)) {
 869   case -1: {
 870       // Obsolete or expired, so don't process normally,
 871       // but allow for an obsolete flag we're still
 872       // temporarily allowing.
 873       if (!is_obsolete_flag(arg, &since)) {
 874         return real_name;
 875       }
 876       // Note if we're not considered obsolete then we can't be expired either
 877       // as obsoletion must come first.
 878       return nullptr;
 879     }
 880     case 0:
 881       return real_name;
 882     case 1: {
 883       char version[256];
 884       since.to_string(version, sizeof(version));
 885       if (real_name != arg) {
 886         warning("Option %s was deprecated in version %s and will likely be removed in a future release. Use option %s instead.",
 887                 arg, version, real_name);
 888       } else {
 889         warning("Option %s was deprecated in version %s and will likely be removed in a future release.",
 890                 arg, version);
 891       }
 892       return real_name;
 893     }
 894   }
 895   ShouldNotReachHere();
 896   return nullptr;
 897 }
 898 
 899 #define BUFLEN 255
 900 
 901 JVMFlag* Arguments::find_jvm_flag(const char* name, size_t name_length) {
 902   char name_copied[BUFLEN+1];
 903   if (name[name_length] != 0) {
 904     if (name_length > BUFLEN) {
 905       return nullptr;
 906     } else {
 907       strncpy(name_copied, name, name_length);
 908       name_copied[name_length] = '\0';
 909       name = name_copied;
 910     }
 911   }
 912 
 913   const char* real_name = Arguments::handle_aliases_and_deprecation(name);
 914   if (real_name == nullptr) {
 915     return nullptr;
 916   }
 917   JVMFlag* flag = JVMFlag::find_flag(real_name);
 918   return flag;
 919 }
 920 
 921 bool Arguments::parse_argument(const char* arg, JVMFlagOrigin origin) {
 922   bool is_bool = false;
 923   bool bool_val = false;
 924   char c = *arg;
 925   if (c == '+' || c == '-') {
 926     is_bool = true;
 927     bool_val = (c == '+');
 928     arg++;
 929   }
 930 
 931   const char* name = arg;
 932   while (true) {
 933     c = *arg;
 934     if (isalnum(c) || (c == '_')) {
 935       ++arg;
 936     } else {
 937       break;
 938     }
 939   }
 940 
 941   size_t name_len = size_t(arg - name);
 942   if (name_len == 0) {
 943     return false;
 944   }
 945 
 946   JVMFlag* flag = find_jvm_flag(name, name_len);
 947   if (flag == nullptr) {
 948     return false;
 949   }
 950 
 951   if (is_bool) {
 952     if (*arg != 0) {
 953       // Error -- extra characters such as -XX:+BoolFlag=123
 954       return false;
 955     }
 956     return set_bool_flag(flag, bool_val, origin);
 957   }
 958 
 959   if (arg[0] == '=') {
 960     const char* value = arg + 1;
 961     if (flag->is_ccstr()) {
 962       if (flag->ccstr_accumulates()) {
 963         return append_to_string_flag(flag, value, origin);
 964       } else {
 965         return set_string_flag(flag, value, origin);
 966       }
 967     } else if (flag->is_double()) {
 968       return set_fp_numeric_flag(flag, value, origin);
 969     } else {
 970       return set_numeric_flag(flag, value, origin);
 971     }
 972   }
 973 
 974   if (arg[0] == ':' && arg[1] == '=') {
 975     // -XX:Foo:=xxx will reset the string flag to the given value.
 976     const char* value = arg + 2;
 977     return set_string_flag(flag, value, origin);
 978   }
 979 
 980   return false;
 981 }
 982 
 983 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
 984   assert(bldarray != nullptr, "illegal argument");
 985 
 986   if (arg == nullptr) {
 987     return;
 988   }
 989 
 990   int new_count = *count + 1;
 991 
 992   // expand the array and add arg to the last element
 993   if (*bldarray == nullptr) {
 994     *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtArguments);
 995   } else {
 996     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtArguments);
 997   }
 998   (*bldarray)[*count] = os::strdup_check_oom(arg);
 999   *count = new_count;
1000 }
1001 
1002 void Arguments::build_jvm_args(const char* arg) {
1003   add_string(&_jvm_args_array, &_num_jvm_args, arg);
1004 }
1005 
1006 void Arguments::build_jvm_flags(const char* arg) {
1007   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
1008 }
1009 
1010 // utility function to return a string that concatenates all
1011 // strings in a given char** array
1012 const char* Arguments::build_resource_string(char** args, int count) {
1013   if (args == nullptr || count == 0) {
1014     return nullptr;
1015   }
1016   size_t length = 0;
1017   for (int i = 0; i < count; i++) {
1018     length += strlen(args[i]) + 1; // add 1 for a space or null terminating character
1019   }
1020   char* s = NEW_RESOURCE_ARRAY(char, length);
1021   char* dst = s;
1022   for (int j = 0; j < count; j++) {
1023     size_t offset = strlen(args[j]) + 1; // add 1 for a space or null terminating character
1024     jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with null character
1025     dst += offset;
1026     length -= offset;
1027   }
1028   return (const char*) s;
1029 }
1030 
1031 void Arguments::print_on(outputStream* st) {
1032   st->print_cr("VM Arguments:");
1033   if (num_jvm_flags() > 0) {
1034     st->print("jvm_flags: "); print_jvm_flags_on(st);
1035     st->cr();
1036   }
1037   if (num_jvm_args() > 0) {
1038     st->print("jvm_args: "); print_jvm_args_on(st);
1039     st->cr();
1040   }
1041   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
1042   if (_java_class_path != nullptr) {
1043     char* path = _java_class_path->value();
1044     size_t len = strlen(path);
1045     st->print("java_class_path (initial): ");
1046     // Avoid using st->print_cr() because path length maybe longer than O_BUFLEN.
1047     if (len == 0) {
1048       st->print_raw_cr("<not set>");
1049     } else {
1050       st->print_raw_cr(path, len);
1051     }
1052   }
1053   st->print_cr("Launcher Type: %s", _sun_java_launcher);
1054 }
1055 
1056 void Arguments::print_summary_on(outputStream* st) {
1057   // Print the command line.  Environment variables that are helpful for
1058   // reproducing the problem are written later in the hs_err file.
1059   // flags are from setting file
1060   if (num_jvm_flags() > 0) {
1061     st->print_raw("Settings File: ");
1062     print_jvm_flags_on(st);
1063     st->cr();
1064   }
1065   // args are the command line and environment variable arguments.
1066   st->print_raw("Command Line: ");
1067   if (num_jvm_args() > 0) {
1068     print_jvm_args_on(st);
1069   }
1070   // this is the classfile and any arguments to the java program
1071   if (java_command() != nullptr) {
1072     st->print("%s", java_command());
1073   }
1074   st->cr();
1075 }
1076 
1077 void Arguments::print_jvm_flags_on(outputStream* st) {
1078   if (_num_jvm_flags > 0) {
1079     for (int i=0; i < _num_jvm_flags; i++) {
1080       st->print("%s ", _jvm_flags_array[i]);
1081     }
1082   }
1083 }
1084 
1085 void Arguments::print_jvm_args_on(outputStream* st) {
1086   if (_num_jvm_args > 0) {
1087     for (int i=0; i < _num_jvm_args; i++) {
1088       st->print("%s ", _jvm_args_array[i]);
1089     }
1090   }
1091 }
1092 
1093 bool Arguments::process_argument(const char* arg,
1094                                  jboolean ignore_unrecognized,
1095                                  JVMFlagOrigin origin) {
1096   JDK_Version since = JDK_Version();
1097 
1098   if (parse_argument(arg, origin)) {
1099     return true;
1100   }
1101 
1102   // Determine if the flag has '+', '-', or '=' characters.
1103   bool has_plus_minus = (*arg == '+' || *arg == '-');
1104   const char* const argname = has_plus_minus ? arg + 1 : arg;
1105 
1106   size_t arg_len;
1107   const char* equal_sign = strchr(argname, '=');
1108   if (equal_sign == nullptr) {
1109     arg_len = strlen(argname);
1110   } else {
1111     arg_len = equal_sign - argname;
1112   }
1113 
1114   // Only make the obsolete check for valid arguments.
1115   if (arg_len <= BUFLEN) {
1116     // Construct a string which consists only of the argument name without '+', '-', or '='.
1117     char stripped_argname[BUFLEN+1]; // +1 for '\0'
1118     jio_snprintf(stripped_argname, arg_len+1, "%s", argname); // +1 for '\0'
1119     if (is_obsolete_flag(stripped_argname, &since)) {
1120       char version[256];
1121       since.to_string(version, sizeof(version));
1122       warning("Ignoring option %s; support was removed in %s", stripped_argname, version);
1123       return true;
1124     }
1125   }
1126 
1127   // For locked flags, report a custom error message if available.
1128   // Otherwise, report the standard unrecognized VM option.
1129   const JVMFlag* found_flag = JVMFlag::find_declared_flag((const char*)argname, arg_len);
1130   if (found_flag != nullptr) {
1131     char locked_message_buf[BUFLEN];
1132     JVMFlag::MsgType msg_type = found_flag->get_locked_message(locked_message_buf, BUFLEN);
1133     if (strlen(locked_message_buf) != 0) {
1134 #ifdef PRODUCT
1135       bool mismatched = msg_type == JVMFlag::DEVELOPER_FLAG_BUT_PRODUCT_BUILD;
1136       if (ignore_unrecognized && mismatched) {
1137         return true;
1138       }
1139 #endif
1140       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
1141     }
1142     if (found_flag->is_bool() && !has_plus_minus) {
1143       jio_fprintf(defaultStream::error_stream(),
1144         "Missing +/- setting for VM option '%s'\n", argname);
1145     } else if (!found_flag->is_bool() && has_plus_minus) {
1146       jio_fprintf(defaultStream::error_stream(),
1147         "Unexpected +/- setting in VM option '%s'\n", argname);
1148     } else {
1149       jio_fprintf(defaultStream::error_stream(),
1150         "Improperly specified VM option '%s'\n", argname);
1151     }
1152   } else {
1153     if (ignore_unrecognized) {
1154       return true;
1155     }
1156     jio_fprintf(defaultStream::error_stream(),
1157                 "Unrecognized VM option '%s'\n", argname);
1158     JVMFlag* fuzzy_matched = JVMFlag::fuzzy_match((const char*)argname, arg_len, true);
1159     if (fuzzy_matched != nullptr) {
1160       jio_fprintf(defaultStream::error_stream(),
1161                   "Did you mean '%s%s%s'?\n",
1162                   (fuzzy_matched->is_bool()) ? "(+/-)" : "",
1163                   fuzzy_matched->name(),
1164                   (fuzzy_matched->is_bool()) ? "" : "=<value>");
1165     }
1166   }
1167 
1168   // allow for commandline "commenting out" options like -XX:#+Verbose
1169   return arg[0] == '#';
1170 }
1171 
1172 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
1173   FILE* stream = os::fopen(file_name, "rb");
1174   if (stream == nullptr) {
1175     if (should_exist) {
1176       jio_fprintf(defaultStream::error_stream(),
1177                   "Could not open settings file %s\n", file_name);
1178       return false;
1179     } else {
1180       return true;
1181     }
1182   }
1183 
1184   char token[1024];
1185   int  pos = 0;
1186 
1187   bool in_white_space = true;
1188   bool in_comment     = false;
1189   bool in_quote       = false;
1190   int  quote_c        = 0;
1191   bool result         = true;
1192 
1193   int c = getc(stream);
1194   while(c != EOF && pos < (int)(sizeof(token)-1)) {
1195     if (in_white_space) {
1196       if (in_comment) {
1197         if (c == '\n') in_comment = false;
1198       } else {
1199         if (c == '#') in_comment = true;
1200         else if (!isspace(c)) {
1201           in_white_space = false;
1202           token[pos++] = checked_cast<char>(c);
1203         }
1204       }
1205     } else {
1206       if (c == '\n' || (!in_quote && isspace(c))) {
1207         // token ends at newline, or at unquoted whitespace
1208         // this allows a way to include spaces in string-valued options
1209         token[pos] = '\0';
1210         logOption(token);
1211         result &= process_argument(token, ignore_unrecognized, JVMFlagOrigin::CONFIG_FILE);
1212         build_jvm_flags(token);
1213         pos = 0;
1214         in_white_space = true;
1215         in_quote = false;
1216       } else if (!in_quote && (c == '\'' || c == '"')) {
1217         in_quote = true;
1218         quote_c = c;
1219       } else if (in_quote && (c == quote_c)) {
1220         in_quote = false;
1221       } else {
1222         token[pos++] = checked_cast<char>(c);
1223       }
1224     }
1225     c = getc(stream);
1226   }
1227   if (pos > 0) {
1228     token[pos] = '\0';
1229     result &= process_argument(token, ignore_unrecognized, JVMFlagOrigin::CONFIG_FILE);
1230     build_jvm_flags(token);
1231   }
1232   fclose(stream);
1233   return result;
1234 }
1235 
1236 //=============================================================================================================
1237 // Parsing of properties (-D)
1238 
1239 const char* Arguments::get_property(const char* key) {
1240   return PropertyList_get_value(system_properties(), key);
1241 }
1242 
1243 bool Arguments::add_property(const char* prop, PropertyWriteable writeable, PropertyInternal internal) {
1244   const char* eq = strchr(prop, '=');
1245   const char* key;
1246   const char* value = "";
1247 
1248   if (eq == nullptr) {
1249     // property doesn't have a value, thus use passed string
1250     key = prop;
1251   } else {
1252     // property have a value, thus extract it and save to the
1253     // allocated string
1254     size_t key_len = eq - prop;
1255     char* tmp_key = AllocateHeap(key_len + 1, mtArguments);
1256 
1257     jio_snprintf(tmp_key, key_len + 1, "%s", prop);
1258     key = tmp_key;
1259 
1260     value = &prop[key_len + 1];
1261   }
1262 
1263   if (internal == ExternalProperty) {
1264     CDSConfig::check_incompatible_property(key, value);
1265   }
1266 
1267   if (strcmp(key, "java.compiler") == 0) {
1268     // we no longer support java.compiler system property, log a warning and let it get
1269     // passed to Java, like any other system property
1270     if (strlen(value) == 0 || strcasecmp(value, "NONE") == 0) {
1271         // for applications using NONE or empty value, log a more informative message
1272         warning("The java.compiler system property is obsolete and no longer supported, use -Xint");
1273     } else {
1274         warning("The java.compiler system property is obsolete and no longer supported.");
1275     }
1276   } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0) {
1277     // sun.java.launcher.is_altjvm property is
1278     // private and is processed in process_sun_java_launcher_properties();
1279     // the sun.java.launcher property is passed on to the java application
1280   } else if (strcmp(key, "sun.boot.library.path") == 0) {
1281     // append is true, writable is true, internal is false
1282     PropertyList_unique_add(&_system_properties, key, value, AppendProperty,
1283                             WriteableProperty, ExternalProperty);
1284   } else {
1285     if (strcmp(key, "sun.java.command") == 0) {
1286       char *old_java_command = _java_command;
1287       _java_command = os::strdup_check_oom(value, mtArguments);
1288       if (old_java_command != nullptr) {
1289         os::free(old_java_command);
1290       }
1291     } else if (strcmp(key, "java.vendor.url.bug") == 0) {
1292       // If this property is set on the command line then its value will be
1293       // displayed in VM error logs as the URL at which to submit such logs.
1294       // Normally the URL displayed in error logs is different from the value
1295       // of this system property, so a different property should have been
1296       // used here, but we leave this as-is in case someone depends upon it.
1297       const char* old_java_vendor_url_bug = _java_vendor_url_bug;
1298       // save it in _java_vendor_url_bug, so JVM fatal error handler can access
1299       // its value without going through the property list or making a Java call.
1300       _java_vendor_url_bug = os::strdup_check_oom(value, mtArguments);
1301       if (old_java_vendor_url_bug != nullptr) {
1302         os::free((void *)old_java_vendor_url_bug);
1303       }
1304     }
1305 
1306     // Create new property and add at the end of the list
1307     PropertyList_unique_add(&_system_properties, key, value, AddProperty, writeable, internal);
1308   }
1309 
1310   if (key != prop) {
1311     // SystemProperty copy passed value, thus free previously allocated
1312     // memory
1313     FreeHeap((void *)key);
1314   }
1315 
1316   return true;
1317 }
1318 
1319 //===========================================================================================================
1320 // Setting int/mixed/comp mode flags
1321 
1322 void Arguments::set_mode_flags(Mode mode) {
1323   // Set up default values for all flags.
1324   // If you add a flag to any of the branches below,
1325   // add a default value for it here.
1326   _mode                      = mode;
1327 
1328   // Ensure Agent_OnLoad has the correct initial values.
1329   // This may not be the final mode; mode may change later in onload phase.
1330   PropertyList_unique_add(&_system_properties, "java.vm.info",
1331                           VM_Version::vm_info_string(), AddProperty, UnwriteableProperty, ExternalProperty);
1332 
1333   UseInterpreter             = true;
1334   UseCompiler                = true;
1335   UseLoopCounter             = true;
1336 
1337   // Default values may be platform/compiler dependent -
1338   // use the saved values
1339   ClipInlining               = Arguments::_ClipInlining;
1340   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1341   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1342   BackgroundCompilation      = Arguments::_BackgroundCompilation;
1343 
1344   // Change from defaults based on mode
1345   switch (mode) {
1346   default:
1347     ShouldNotReachHere();
1348     break;
1349   case _int:
1350     UseCompiler              = false;
1351     UseLoopCounter           = false;
1352     AlwaysCompileLoopMethods = false;
1353     UseOnStackReplacement    = false;
1354     break;
1355   case _mixed:
1356     // same as default
1357     break;
1358   case _comp:
1359     UseInterpreter           = false;
1360     BackgroundCompilation    = false;
1361     ClipInlining             = false;
1362     break;
1363   }
1364 }
1365 
1366 // Conflict: required to use shared spaces (-Xshare:on), but
1367 // incompatible command line options were chosen.
1368 void Arguments::no_shared_spaces(const char* message) {
1369   if (RequireSharedSpaces) {
1370     jio_fprintf(defaultStream::error_stream(),
1371       "Class data sharing is inconsistent with other specified options.\n");
1372     vm_exit_during_initialization("Unable to use shared archive", message);
1373   } else {
1374     log_info(cds)("Unable to use shared archive: %s", message);
1375     UseSharedSpaces = false;
1376   }
1377 }
1378 
1379 static void set_object_alignment() {
1380   // Object alignment.
1381   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1382   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1383   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1384   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1385   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1386   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1387 
1388   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1389   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1390 
1391   // Oop encoding heap max
1392   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1393 }
1394 
1395 size_t Arguments::max_heap_for_compressed_oops() {
1396   // Avoid sign flip.
1397   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1398   // We need to fit both the null page and the heap into the memory budget, while
1399   // keeping alignment constraints of the heap. To guarantee the latter, as the
1400   // null page is located before the heap, we pad the null page to the conservative
1401   // maximum alignment that the GC may ever impose upon the heap.
1402   size_t displacement_due_to_null_page = align_up(os::vm_page_size(),
1403                                                   _conservative_max_heap_alignment);
1404 
1405   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1406   NOT_LP64(ShouldNotReachHere(); return 0);
1407 }
1408 
1409 void Arguments::set_use_compressed_oops() {
1410 #ifdef _LP64
1411   // MaxHeapSize is not set up properly at this point, but
1412   // the only value that can override MaxHeapSize if we are
1413   // to use UseCompressedOops are InitialHeapSize and MinHeapSize.
1414   size_t max_heap_size = MAX3(MaxHeapSize, InitialHeapSize, MinHeapSize);
1415 
1416   if (max_heap_size <= max_heap_for_compressed_oops()) {
1417     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1418       FLAG_SET_ERGO(UseCompressedOops, true);
1419     }
1420   } else {
1421     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1422       warning("Max heap size too large for Compressed Oops");
1423       FLAG_SET_DEFAULT(UseCompressedOops, false);
1424     }
1425   }
1426 #endif // _LP64
1427 }
1428 
1429 void Arguments::set_use_compressed_klass_ptrs() {
1430 #ifdef _LP64
1431   assert(!UseCompressedClassPointers || CompressedClassSpaceSize <= KlassEncodingMetaspaceMax,
1432          "CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1433 #endif // _LP64
1434 }
1435 
1436 void Arguments::set_conservative_max_heap_alignment() {
1437   // The conservative maximum required alignment for the heap is the maximum of
1438   // the alignments imposed by several sources: any requirements from the heap
1439   // itself and the maximum page size we may run the VM with.
1440   size_t heap_alignment = GCConfig::arguments()->conservative_max_heap_alignment();
1441   _conservative_max_heap_alignment = MAX4(heap_alignment,
1442                                           os::vm_allocation_granularity(),
1443                                           os::max_page_size(),
1444                                           GCArguments::compute_heap_alignment());
1445 }
1446 
1447 jint Arguments::set_ergonomics_flags() {
1448   GCConfig::initialize();
1449 
1450   set_conservative_max_heap_alignment();
1451 
1452 #ifdef _LP64
1453   set_use_compressed_oops();
1454   set_use_compressed_klass_ptrs();
1455 
1456   // Also checks that certain machines are slower with compressed oops
1457   // in vm_version initialization code.
1458 #endif // _LP64
1459 
1460   return JNI_OK;
1461 }
1462 
1463 size_t Arguments::limit_heap_by_allocatable_memory(size_t limit) {
1464   size_t max_allocatable;
1465   size_t result = limit;
1466   if (os::has_allocatable_memory_limit(&max_allocatable)) {
1467     // The AggressiveHeap check is a temporary workaround to avoid calling
1468     // GCarguments::heap_virtual_to_physical_ratio() before a GC has been
1469     // selected. This works because AggressiveHeap implies UseParallelGC
1470     // where we know the ratio will be 1. Once the AggressiveHeap option is
1471     // removed, this can be cleaned up.
1472     size_t heap_virtual_to_physical_ratio = (AggressiveHeap ? 1 : GCConfig::arguments()->heap_virtual_to_physical_ratio());
1473     size_t fraction = MaxVirtMemFraction * heap_virtual_to_physical_ratio;
1474     result = MIN2(result, max_allocatable / fraction);
1475   }
1476   return result;
1477 }
1478 
1479 // Use static initialization to get the default before parsing
1480 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1481 
1482 void Arguments::set_heap_size() {
1483   julong phys_mem;
1484 
1485   // If the user specified one of these options, they
1486   // want specific memory sizing so do not limit memory
1487   // based on compressed oops addressability.
1488   // Also, memory limits will be calculated based on
1489   // available os physical memory, not our MaxRAM limit,
1490   // unless MaxRAM is also specified.
1491   bool override_coop_limit = (!FLAG_IS_DEFAULT(MaxRAMPercentage) ||
1492                            !FLAG_IS_DEFAULT(MinRAMPercentage) ||
1493                            !FLAG_IS_DEFAULT(InitialRAMPercentage) ||
1494                            !FLAG_IS_DEFAULT(MaxRAM));
1495   if (override_coop_limit) {
1496     if (FLAG_IS_DEFAULT(MaxRAM)) {
1497       phys_mem = os::physical_memory();
1498       FLAG_SET_ERGO(MaxRAM, (uint64_t)phys_mem);
1499     } else {
1500       phys_mem = (julong)MaxRAM;
1501     }
1502   } else {
1503     phys_mem = FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1504                                        : (julong)MaxRAM;
1505   }
1506 
1507   // If the maximum heap size has not been set with -Xmx,
1508   // then set it as fraction of the size of physical memory,
1509   // respecting the maximum and minimum sizes of the heap.
1510   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1511     julong reasonable_max = (julong)(((double)phys_mem * MaxRAMPercentage) / 100);
1512     const julong reasonable_min = (julong)(((double)phys_mem * MinRAMPercentage) / 100);
1513     if (reasonable_min < MaxHeapSize) {
1514       // Small physical memory, so use a minimum fraction of it for the heap
1515       reasonable_max = reasonable_min;
1516     } else {
1517       // Not-small physical memory, so require a heap at least
1518       // as large as MaxHeapSize
1519       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1520     }
1521 
1522     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1523       // Limit the heap size to ErgoHeapSizeLimit
1524       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1525     }
1526 
1527     reasonable_max = limit_heap_by_allocatable_memory(reasonable_max);
1528 
1529     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1530       // An initial heap size was specified on the command line,
1531       // so be sure that the maximum size is consistent.  Done
1532       // after call to limit_heap_by_allocatable_memory because that
1533       // method might reduce the allocation size.
1534       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1535     } else if (!FLAG_IS_DEFAULT(MinHeapSize)) {
1536       reasonable_max = MAX2(reasonable_max, (julong)MinHeapSize);
1537     }
1538 
1539 #ifdef _LP64
1540     if (UseCompressedOops || UseCompressedClassPointers) {
1541       // HeapBaseMinAddress can be greater than default but not less than.
1542       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1543         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1544           // matches compressed oops printing flags
1545           log_debug(gc, heap, coops)("HeapBaseMinAddress must be at least " SIZE_FORMAT
1546                                      " (" SIZE_FORMAT "G) which is greater than value given " SIZE_FORMAT,
1547                                      DefaultHeapBaseMinAddress,
1548                                      DefaultHeapBaseMinAddress/G,
1549                                      HeapBaseMinAddress);
1550           FLAG_SET_ERGO(HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1551         }
1552       }
1553     }
1554     if (UseCompressedOops) {
1555       // Limit the heap size to the maximum possible when using compressed oops
1556       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1557 
1558       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1559         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1560         // but it should be not less than default MaxHeapSize.
1561         max_coop_heap -= HeapBaseMinAddress;
1562       }
1563 
1564       // If user specified flags prioritizing os physical
1565       // memory limits, then disable compressed oops if
1566       // limits exceed max_coop_heap and UseCompressedOops
1567       // was not specified.
1568       if (reasonable_max > max_coop_heap) {
1569         if (FLAG_IS_ERGO(UseCompressedOops) && override_coop_limit) {
1570           log_info(cds)("UseCompressedOops and UseCompressedClassPointers have been disabled due to"
1571             " max heap " SIZE_FORMAT " > compressed oop heap " SIZE_FORMAT ". "
1572             "Please check the setting of MaxRAMPercentage %5.2f."
1573             ,(size_t)reasonable_max, (size_t)max_coop_heap, MaxRAMPercentage);
1574           FLAG_SET_ERGO(UseCompressedOops, false);
1575         } else {
1576           reasonable_max = MIN2(reasonable_max, max_coop_heap);
1577         }
1578       }
1579     }
1580 #endif // _LP64
1581 
1582     log_trace(gc, heap)("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1583     FLAG_SET_ERGO(MaxHeapSize, (size_t)reasonable_max);
1584   }
1585 
1586   // If the minimum or initial heap_size have not been set or requested to be set
1587   // ergonomically, set them accordingly.
1588   if (InitialHeapSize == 0 || MinHeapSize == 0) {
1589     julong reasonable_minimum = (julong)(OldSize + NewSize);
1590 
1591     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1592 
1593     reasonable_minimum = limit_heap_by_allocatable_memory(reasonable_minimum);
1594 
1595     if (InitialHeapSize == 0) {
1596       julong reasonable_initial = (julong)(((double)phys_mem * InitialRAMPercentage) / 100);
1597       reasonable_initial = limit_heap_by_allocatable_memory(reasonable_initial);
1598 
1599       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)MinHeapSize);
1600       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1601 
1602       FLAG_SET_ERGO(InitialHeapSize, (size_t)reasonable_initial);
1603       log_trace(gc, heap)("  Initial heap size " SIZE_FORMAT, InitialHeapSize);
1604     }
1605     // If the minimum heap size has not been set (via -Xms or -XX:MinHeapSize),
1606     // synchronize with InitialHeapSize to avoid errors with the default value.
1607     if (MinHeapSize == 0) {
1608       FLAG_SET_ERGO(MinHeapSize, MIN2((size_t)reasonable_minimum, InitialHeapSize));
1609       log_trace(gc, heap)("  Minimum heap size " SIZE_FORMAT, MinHeapSize);
1610     }
1611   }
1612 }
1613 
1614 // This option inspects the machine and attempts to set various
1615 // parameters to be optimal for long-running, memory allocation
1616 // intensive jobs.  It is intended for machines with large
1617 // amounts of cpu and memory.
1618 jint Arguments::set_aggressive_heap_flags() {
1619   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
1620   // VM, but we may not be able to represent the total physical memory
1621   // available (like having 8gb of memory on a box but using a 32bit VM).
1622   // Thus, we need to make sure we're using a julong for intermediate
1623   // calculations.
1624   julong initHeapSize;
1625   julong total_memory = os::physical_memory();
1626 
1627   if (total_memory < (julong) 256 * M) {
1628     jio_fprintf(defaultStream::error_stream(),
1629             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
1630     vm_exit(1);
1631   }
1632 
1633   // The heap size is half of available memory, or (at most)
1634   // all of possible memory less 160mb (leaving room for the OS
1635   // when using ISM).  This is the maximum; because adaptive sizing
1636   // is turned on below, the actual space used may be smaller.
1637 
1638   initHeapSize = MIN2(total_memory / (julong) 2,
1639           total_memory - (julong) 160 * M);
1640 
1641   initHeapSize = limit_heap_by_allocatable_memory(initHeapSize);
1642 
1643   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1644     if (FLAG_SET_CMDLINE(MaxHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1645       return JNI_EINVAL;
1646     }
1647     if (FLAG_SET_CMDLINE(InitialHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1648       return JNI_EINVAL;
1649     }
1650     if (FLAG_SET_CMDLINE(MinHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1651       return JNI_EINVAL;
1652     }
1653   }
1654   if (FLAG_IS_DEFAULT(NewSize)) {
1655     // Make the young generation 3/8ths of the total heap.
1656     if (FLAG_SET_CMDLINE(NewSize,
1657             ((julong) MaxHeapSize / (julong) 8) * (julong) 3) != JVMFlag::SUCCESS) {
1658       return JNI_EINVAL;
1659     }
1660     if (FLAG_SET_CMDLINE(MaxNewSize, NewSize) != JVMFlag::SUCCESS) {
1661       return JNI_EINVAL;
1662     }
1663   }
1664 
1665 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
1666   FLAG_SET_DEFAULT(UseLargePages, true);
1667 #endif
1668 
1669   // Increase some data structure sizes for efficiency
1670   if (FLAG_SET_CMDLINE(BaseFootPrintEstimate, MaxHeapSize) != JVMFlag::SUCCESS) {
1671     return JNI_EINVAL;
1672   }
1673   if (FLAG_SET_CMDLINE(ResizeTLAB, false) != JVMFlag::SUCCESS) {
1674     return JNI_EINVAL;
1675   }
1676   if (FLAG_SET_CMDLINE(TLABSize, 256 * K) != JVMFlag::SUCCESS) {
1677     return JNI_EINVAL;
1678   }
1679 
1680   // See the OldPLABSize comment below, but replace 'after promotion'
1681   // with 'after copying'.  YoungPLABSize is the size of the survivor
1682   // space per-gc-thread buffers.  The default is 4kw.
1683   if (FLAG_SET_CMDLINE(YoungPLABSize, 256 * K) != JVMFlag::SUCCESS) { // Note: this is in words
1684     return JNI_EINVAL;
1685   }
1686 
1687   // OldPLABSize is the size of the buffers in the old gen that
1688   // UseParallelGC uses to promote live data that doesn't fit in the
1689   // survivor spaces.  At any given time, there's one for each gc thread.
1690   // The default size is 1kw. These buffers are rarely used, since the
1691   // survivor spaces are usually big enough.  For specjbb, however, there
1692   // are occasions when there's lots of live data in the young gen
1693   // and we end up promoting some of it.  We don't have a definite
1694   // explanation for why bumping OldPLABSize helps, but the theory
1695   // is that a bigger PLAB results in retaining something like the
1696   // original allocation order after promotion, which improves mutator
1697   // locality.  A minor effect may be that larger PLABs reduce the
1698   // number of PLAB allocation events during gc.  The value of 8kw
1699   // was arrived at by experimenting with specjbb.
1700   if (FLAG_SET_CMDLINE(OldPLABSize, 8 * K) != JVMFlag::SUCCESS) { // Note: this is in words
1701     return JNI_EINVAL;
1702   }
1703 
1704   // Enable parallel GC and adaptive generation sizing
1705   if (FLAG_SET_CMDLINE(UseParallelGC, true) != JVMFlag::SUCCESS) {
1706     return JNI_EINVAL;
1707   }
1708 
1709   // Encourage steady state memory management
1710   if (FLAG_SET_CMDLINE(ThresholdTolerance, 100) != JVMFlag::SUCCESS) {
1711     return JNI_EINVAL;
1712   }
1713 
1714   // This appears to improve mutator locality
1715   if (FLAG_SET_CMDLINE(ScavengeBeforeFullGC, false) != JVMFlag::SUCCESS) {
1716     return JNI_EINVAL;
1717   }
1718 
1719   return JNI_OK;
1720 }
1721 
1722 // This must be called after ergonomics.
1723 void Arguments::set_bytecode_flags() {
1724   if (!RewriteBytecodes) {
1725     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1726   }
1727 }
1728 
1729 // Aggressive optimization flags
1730 jint Arguments::set_aggressive_opts_flags() {
1731 #ifdef COMPILER2
1732   if (AggressiveUnboxing) {
1733     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1734       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1735     } else if (!EliminateAutoBox) {
1736       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
1737       AggressiveUnboxing = false;
1738     }
1739     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1740       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1741     } else if (!DoEscapeAnalysis) {
1742       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
1743       AggressiveUnboxing = false;
1744     }
1745   }
1746   if (!FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1747     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1748       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1749     }
1750     // Feed the cache size setting into the JDK
1751     char buffer[1024];
1752     jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
1753     if (!add_property(buffer)) {
1754       return JNI_ENOMEM;
1755     }
1756   }
1757 #endif
1758 
1759   return JNI_OK;
1760 }
1761 
1762 //===========================================================================================================
1763 
1764 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1765   if (_sun_java_launcher != _default_java_launcher) {
1766     os::free(const_cast<char*>(_sun_java_launcher));
1767   }
1768   _sun_java_launcher = os::strdup_check_oom(launcher);
1769 }
1770 
1771 bool Arguments::created_by_java_launcher() {
1772   assert(_sun_java_launcher != nullptr, "property must have value");
1773   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1774 }
1775 
1776 bool Arguments::sun_java_launcher_is_altjvm() {
1777   return _sun_java_launcher_is_altjvm;
1778 }
1779 
1780 //===========================================================================================================
1781 // Parsing of main arguments
1782 
1783 unsigned int addreads_count = 0;
1784 unsigned int addexports_count = 0;
1785 unsigned int addopens_count = 0;
1786 unsigned int addmods_count = 0;
1787 unsigned int patch_mod_count = 0;
1788 unsigned int enable_native_access_count = 0;
1789 
1790 // Check the consistency of vm_init_args
1791 bool Arguments::check_vm_args_consistency() {
1792   // Method for adding checks for flag consistency.
1793   // The intent is to warn the user of all possible conflicts,
1794   // before returning an error.
1795   // Note: Needs platform-dependent factoring.
1796   bool status = true;
1797 
1798   if (TLABRefillWasteFraction == 0) {
1799     jio_fprintf(defaultStream::error_stream(),
1800                 "TLABRefillWasteFraction should be a denominator, "
1801                 "not " SIZE_FORMAT "\n",
1802                 TLABRefillWasteFraction);
1803     status = false;
1804   }
1805 
1806   status = CompilerConfig::check_args_consistency(status);
1807 #if INCLUDE_JVMCI
1808   if (status && EnableJVMCI) {
1809     PropertyList_unique_add(&_system_properties, "jdk.internal.vm.ci.enabled", "true",
1810         AddProperty, UnwriteableProperty, InternalProperty);
1811     if (ClassLoader::is_module_observable("jdk.internal.vm.ci")) {





1812       if (!create_numbered_module_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {
1813         return false;
1814       }
1815     }
1816   }
1817 #endif
1818 
1819 #if INCLUDE_JFR
1820   if (status && (FlightRecorderOptions || StartFlightRecording)) {
1821     if (!create_numbered_module_property("jdk.module.addmods", "jdk.jfr", addmods_count++)) {
1822       return false;
1823     }
1824   }
1825 #endif
1826 
1827 #ifndef SUPPORT_RESERVED_STACK_AREA
1828   if (StackReservedPages != 0) {
1829     FLAG_SET_CMDLINE(StackReservedPages, 0);
1830     warning("Reserved Stack Area not supported on this platform");
1831   }
1832 #endif
1833 
1834 #if !defined(X86) && !defined(AARCH64) && !defined(RISCV64) && !defined(ARM) && !defined(PPC64) && !defined(S390)
1835   if (LockingMode == LM_LIGHTWEIGHT) {
1836     FLAG_SET_CMDLINE(LockingMode, LM_LEGACY);
1837     warning("New lightweight locking not supported on this platform");
1838   }
1839 #endif
1840 
1841 #if !defined(X86) && !defined(AARCH64) && !defined(PPC64) && !defined(RISCV64) && !defined(S390)
1842   if (LockingMode == LM_MONITOR) {
1843     jio_fprintf(defaultStream::error_stream(),
1844                 "LockingMode == 0 (LM_MONITOR) is not fully implemented on this architecture\n");
1845     return false;
1846   }
1847 #endif
1848 #if defined(X86) && !defined(ZERO)
1849   if (LockingMode == LM_MONITOR && UseRTMForStackLocks) {
1850     jio_fprintf(defaultStream::error_stream(),
1851                 "LockingMode == 0 (LM_MONITOR) and -XX:+UseRTMForStackLocks are mutually exclusive\n");
1852 
1853     return false;
1854   }
1855 #endif
1856   if (VerifyHeavyMonitors && LockingMode != LM_MONITOR) {
1857     jio_fprintf(defaultStream::error_stream(),
1858                 "-XX:+VerifyHeavyMonitors requires LockingMode == 0 (LM_MONITOR)\n");
1859     return false;
1860   }
1861   return status;
1862 }
1863 
1864 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
1865   const char* option_type) {
1866   if (ignore) return false;
1867 
1868   const char* spacer = " ";
1869   if (option_type == nullptr) {
1870     option_type = ++spacer; // Set both to the empty string.
1871   }
1872 
1873   jio_fprintf(defaultStream::error_stream(),
1874               "Unrecognized %s%soption: %s\n", option_type, spacer,
1875               option->optionString);
1876   return true;
1877 }
1878 
1879 static const char* user_assertion_options[] = {
1880   "-da", "-ea", "-disableassertions", "-enableassertions", 0
1881 };
1882 
1883 static const char* system_assertion_options[] = {
1884   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
1885 };
1886 
1887 bool Arguments::parse_uint(const char* value,
1888                            uint* uint_arg,
1889                            uint min_size) {
1890   uint n;
1891   if (!parse_integer(value, &n)) {
1892     return false;
1893   }
1894   if (n >= min_size) {
1895     *uint_arg = n;
1896     return true;
1897   } else {
1898     return false;
1899   }
1900 }
1901 
1902 bool Arguments::create_module_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
1903   assert(is_internal_module_property(prop_name), "unknown module property: '%s'", prop_name);
1904   CDSConfig::check_internal_module_property(prop_name, prop_value);
1905   size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
1906   char* property = AllocateHeap(prop_len, mtArguments);
1907   int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);
1908   if (ret < 0 || ret >= (int)prop_len) {
1909     FreeHeap(property);
1910     return false;
1911   }
1912   // These are not strictly writeable properties as they cannot be set via -Dprop=val. But that
1913   // is enforced by checking is_internal_module_property(). We need the property to be writeable so
1914   // that multiple occurrences of the associated flag just causes the existing property value to be
1915   // replaced ("last option wins"). Otherwise we would need to keep track of the flags and only convert
1916   // to a property after we have finished flag processing.
1917   bool added = add_property(property, WriteableProperty, internal);
1918   FreeHeap(property);
1919   return added;
1920 }
1921 
1922 bool Arguments::create_numbered_module_property(const char* prop_base_name, const char* prop_value, unsigned int count) {
1923   assert(is_internal_module_property(prop_base_name), "unknown module property: '%s'", prop_base_name);
1924   CDSConfig::check_internal_module_property(prop_base_name, prop_value);
1925   const unsigned int props_count_limit = 1000;
1926   const int max_digits = 3;
1927   const int extra_symbols_count = 3; // includes '.', '=', '\0'
1928 
1929   // Make sure count is < props_count_limit. Otherwise, memory allocation will be too small.
1930   if (count < props_count_limit) {
1931     size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + max_digits + extra_symbols_count;
1932     char* property = AllocateHeap(prop_len, mtArguments);
1933     int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);
1934     if (ret < 0 || ret >= (int)prop_len) {
1935       FreeHeap(property);
1936       jio_fprintf(defaultStream::error_stream(), "Failed to create property %s.%d=%s\n", prop_base_name, count, prop_value);
1937       return false;
1938     }
1939     bool added = add_property(property, UnwriteableProperty, InternalProperty);
1940     FreeHeap(property);
1941     return added;
1942   }
1943 
1944   jio_fprintf(defaultStream::error_stream(), "Property count limit exceeded: %s, limit=%d\n", prop_base_name, props_count_limit);
1945   return false;
1946 }
1947 
1948 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
1949                                                   julong* long_arg,
1950                                                   julong min_size,
1951                                                   julong max_size) {
1952   if (!parse_integer(s, long_arg)) return arg_unreadable;
1953   return check_memory_size(*long_arg, min_size, max_size);
1954 }
1955 
1956 // Parse JavaVMInitArgs structure
1957 
1958 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *vm_options_args,
1959                                    const JavaVMInitArgs *java_tool_options_args,
1960                                    const JavaVMInitArgs *java_options_args,
1961                                    const JavaVMInitArgs *cmd_line_args) {
1962   bool patch_mod_javabase = false;
1963 
1964   // Save default settings for some mode flags
1965   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
1966   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
1967   Arguments::_ClipInlining             = ClipInlining;
1968   Arguments::_BackgroundCompilation    = BackgroundCompilation;
1969 
1970   // Remember the default value of SharedBaseAddress.
1971   Arguments::_default_SharedBaseAddress = SharedBaseAddress;
1972 
1973   // Setup flags for mixed which is the default
1974   set_mode_flags(_mixed);
1975 
1976   // Parse args structure generated from java.base vm options resource
1977   jint result = parse_each_vm_init_arg(vm_options_args, &patch_mod_javabase, JVMFlagOrigin::JIMAGE_RESOURCE);
1978   if (result != JNI_OK) {
1979     return result;
1980   }
1981 
1982   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
1983   // variable (if present).
1984   result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR);
1985   if (result != JNI_OK) {
1986     return result;
1987   }
1988 
1989   // Parse args structure generated from the command line flags.
1990   result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, JVMFlagOrigin::COMMAND_LINE);
1991   if (result != JNI_OK) {
1992     return result;
1993   }
1994 
1995   // Parse args structure generated from the _JAVA_OPTIONS environment
1996   // variable (if present) (mimics classic VM)
1997   result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR);
1998   if (result != JNI_OK) {
1999     return result;
2000   }
2001 
2002   // Disable CDS for exploded image
2003   if (!has_jimage()) {
2004     no_shared_spaces("CDS disabled on exploded JDK");
2005   }
2006 
2007   // We need to ensure processor and memory resources have been properly
2008   // configured - which may rely on arguments we just processed - before
2009   // doing the final argument processing. Any argument processing that
2010   // needs to know about processor and memory resources must occur after
2011   // this point.
2012 
2013   os::init_container_support();
2014 
2015   SystemMemoryBarrier::initialize();
2016 
2017   // Do final processing now that all arguments have been parsed
2018   result = finalize_vm_init_args(patch_mod_javabase);
2019   if (result != JNI_OK) {
2020     return result;
2021   }
2022 
2023   return JNI_OK;
2024 }
2025 
2026 #if !INCLUDE_JVMTI
2027 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2028 // represents a valid JDWP agent.  is_path==true denotes that we
2029 // are dealing with -agentpath (case where name is a path), otherwise with
2030 // -agentlib
2031 static bool valid_jdwp_agent(char *name, bool is_path) {
2032   char *_name;
2033   const char *_jdwp = "jdwp";
2034   size_t _len_jdwp, _len_prefix;
2035 
2036   if (is_path) {
2037     if ((_name = strrchr(name, (int) *os::file_separator())) == nullptr) {
2038       return false;
2039     }
2040 
2041     _name++;  // skip past last path separator
2042     _len_prefix = strlen(JNI_LIB_PREFIX);
2043 
2044     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2045       return false;
2046     }
2047 
2048     _name += _len_prefix;
2049     _len_jdwp = strlen(_jdwp);
2050 
2051     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2052       _name += _len_jdwp;
2053     }
2054     else {
2055       return false;
2056     }
2057 
2058     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2059       return false;
2060     }
2061 
2062     return true;
2063   }
2064 
2065   if (strcmp(name, _jdwp) == 0) {
2066     return true;
2067   }
2068 
2069   return false;
2070 }
2071 #endif
2072 
2073 int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {
2074   // --patch-module=<module>=<file>(<pathsep><file>)*
2075   assert(patch_mod_tail != nullptr, "Unexpected null patch-module value");
2076   // Find the equal sign between the module name and the path specification
2077   const char* module_equal = strchr(patch_mod_tail, '=');
2078   if (module_equal == nullptr) {
2079     jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");
2080     return JNI_ERR;
2081   } else {
2082     // Pick out the module name
2083     size_t module_len = module_equal - patch_mod_tail;
2084     char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);
2085     if (module_name != nullptr) {
2086       memcpy(module_name, patch_mod_tail, module_len);
2087       *(module_name + module_len) = '\0';
2088       // The path piece begins one past the module_equal sign
2089       add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);
2090       FREE_C_HEAP_ARRAY(char, module_name);
2091       if (!create_numbered_module_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {
2092         return JNI_ENOMEM;
2093       }
2094     } else {
2095       return JNI_ENOMEM;
2096     }
2097   }
2098   return JNI_OK;
2099 }
2100 
2101 // Parse -Xss memory string parameter and convert to ThreadStackSize in K.
2102 jint Arguments::parse_xss(const JavaVMOption* option, const char* tail, intx* out_ThreadStackSize) {
2103   // The min and max sizes match the values in globals.hpp, but scaled
2104   // with K. The values have been chosen so that alignment with page
2105   // size doesn't change the max value, which makes the conversions
2106   // back and forth between Xss value and ThreadStackSize value easier.
2107   // The values have also been chosen to fit inside a 32-bit signed type.
2108   const julong min_ThreadStackSize = 0;
2109   const julong max_ThreadStackSize = 1 * M;
2110 
2111   // Make sure the above values match the range set in globals.hpp
2112   const JVMTypedFlagLimit<intx>* limit = JVMFlagLimit::get_range_at(FLAG_MEMBER_ENUM(ThreadStackSize))->cast<intx>();
2113   assert(min_ThreadStackSize == static_cast<julong>(limit->min()), "must be");
2114   assert(max_ThreadStackSize == static_cast<julong>(limit->max()), "must be");
2115 
2116   const julong min_size = min_ThreadStackSize * K;
2117   const julong max_size = max_ThreadStackSize * K;
2118 
2119   assert(is_aligned(max_size, os::vm_page_size()), "Implementation assumption");
2120 
2121   julong size = 0;
2122   ArgsRange errcode = parse_memory_size(tail, &size, min_size, max_size);
2123   if (errcode != arg_in_range) {
2124     bool silent = (option == nullptr); // Allow testing to silence error messages
2125     if (!silent) {
2126       jio_fprintf(defaultStream::error_stream(),
2127                   "Invalid thread stack size: %s\n", option->optionString);
2128       describe_range_error(errcode);
2129     }
2130     return JNI_EINVAL;
2131   }
2132 
2133   // Internally track ThreadStackSize in units of 1024 bytes.
2134   const julong size_aligned = align_up(size, K);
2135   assert(size <= size_aligned,
2136          "Overflow: " JULONG_FORMAT " " JULONG_FORMAT,
2137          size, size_aligned);
2138 
2139   const julong size_in_K = size_aligned / K;
2140   assert(size_in_K < (julong)max_intx,
2141          "size_in_K doesn't fit in the type of ThreadStackSize: " JULONG_FORMAT,
2142          size_in_K);
2143 
2144   // Check that code expanding ThreadStackSize to a page aligned number of bytes won't overflow.
2145   const julong max_expanded = align_up(size_in_K * K, os::vm_page_size());
2146   assert(max_expanded < max_uintx && max_expanded >= size_in_K,
2147          "Expansion overflowed: " JULONG_FORMAT " " JULONG_FORMAT,
2148          max_expanded, size_in_K);
2149 
2150   *out_ThreadStackSize = (intx)size_in_K;
2151 
2152   return JNI_OK;
2153 }
2154 
2155 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, JVMFlagOrigin origin) {
2156   // For match_option to return remaining or value part of option string
2157   const char* tail;
2158 
2159   // iterate over arguments
2160   for (int index = 0; index < args->nOptions; index++) {
2161     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2162 
2163     const JavaVMOption* option = args->options + index;
2164 
2165     if (!match_option(option, "-Djava.class.path", &tail) &&
2166         !match_option(option, "-Dsun.java.command", &tail) &&
2167         !match_option(option, "-Dsun.java.launcher", &tail)) {
2168 
2169         // add all jvm options to the jvm_args string. This string
2170         // is used later to set the java.vm.args PerfData string constant.
2171         // the -Djava.class.path and the -Dsun.java.command options are
2172         // omitted from jvm_args string as each have their own PerfData
2173         // string constant object.
2174         build_jvm_args(option->optionString);
2175     }
2176 
2177     // -verbose:[class/module/gc/jni]
2178     if (match_option(option, "-verbose", &tail)) {
2179       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2180         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));
2181         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));
2182       } else if (!strcmp(tail, ":module")) {
2183         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, load));
2184         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, unload));
2185       } else if (!strcmp(tail, ":gc")) {
2186         if (_legacyGCLogging.lastFlag == 0) {
2187           _legacyGCLogging.lastFlag = 1;
2188         }
2189       } else if (!strcmp(tail, ":jni")) {
2190         LogConfiguration::configure_stdout(LogLevel::Debug, true, LOG_TAGS(jni, resolve));
2191       }
2192     // -da / -ea / -disableassertions / -enableassertions
2193     // These accept an optional class/package name separated by a colon, e.g.,
2194     // -da:java.lang.Thread.
2195     } else if (match_option(option, user_assertion_options, &tail, true)) {
2196       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2197       if (*tail == '\0') {
2198         JavaAssertions::setUserClassDefault(enable);
2199       } else {
2200         assert(*tail == ':', "bogus match by match_option()");
2201         JavaAssertions::addOption(tail + 1, enable);
2202       }
2203     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2204     } else if (match_option(option, system_assertion_options, &tail, false)) {
2205       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2206       JavaAssertions::setSystemClassDefault(enable);
2207     // -bootclasspath:
2208     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2209         jio_fprintf(defaultStream::output_stream(),
2210           "-Xbootclasspath is no longer a supported option.\n");
2211         return JNI_EINVAL;
2212     // -bootclasspath/a:
2213     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2214       Arguments::append_sysclasspath(tail);
2215     // -bootclasspath/p:
2216     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2217         jio_fprintf(defaultStream::output_stream(),
2218           "-Xbootclasspath/p is no longer a supported option.\n");
2219         return JNI_EINVAL;
2220     // -Xrun
2221     } else if (match_option(option, "-Xrun", &tail)) {
2222       if (tail != nullptr) {
2223         const char* pos = strchr(tail, ':');
2224         size_t len = (pos == nullptr) ? strlen(tail) : pos - tail;
2225         char* name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2226         jio_snprintf(name, len + 1, "%s", tail);
2227 
2228         char *options = nullptr;
2229         if(pos != nullptr) {
2230           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2231           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);
2232         }
2233 #if !INCLUDE_JVMTI
2234         if (strcmp(name, "jdwp") == 0) {
2235           jio_fprintf(defaultStream::error_stream(),
2236             "Debugging agents are not supported in this VM\n");
2237           return JNI_ERR;
2238         }
2239 #endif // !INCLUDE_JVMTI
2240         JvmtiAgentList::add_xrun(name, options, false);
2241         FREE_C_HEAP_ARRAY(char, name);
2242         FREE_C_HEAP_ARRAY(char, options);
2243       }
2244     } else if (match_option(option, "--add-reads=", &tail)) {
2245       if (!create_numbered_module_property("jdk.module.addreads", tail, addreads_count++)) {
2246         return JNI_ENOMEM;
2247       }
2248     } else if (match_option(option, "--add-exports=", &tail)) {
2249       if (!create_numbered_module_property("jdk.module.addexports", tail, addexports_count++)) {
2250         return JNI_ENOMEM;
2251       }
2252     } else if (match_option(option, "--add-opens=", &tail)) {
2253       if (!create_numbered_module_property("jdk.module.addopens", tail, addopens_count++)) {
2254         return JNI_ENOMEM;
2255       }
2256     } else if (match_option(option, "--add-modules=", &tail)) {
2257       if (!create_numbered_module_property("jdk.module.addmods", tail, addmods_count++)) {
2258         return JNI_ENOMEM;
2259       }
2260     } else if (match_option(option, "--enable-native-access=", &tail)) {
2261       if (!create_numbered_module_property("jdk.module.enable.native.access", tail, enable_native_access_count++)) {
2262         return JNI_ENOMEM;
2263       }
2264     } else if (match_option(option, "--limit-modules=", &tail)) {
2265       if (!create_module_property("jdk.module.limitmods", tail, InternalProperty)) {
2266         return JNI_ENOMEM;
2267       }
2268     } else if (match_option(option, "--module-path=", &tail)) {
2269       if (!create_module_property("jdk.module.path", tail, ExternalProperty)) {
2270         return JNI_ENOMEM;
2271       }
2272     } else if (match_option(option, "--upgrade-module-path=", &tail)) {
2273       if (!create_module_property("jdk.module.upgrade.path", tail, ExternalProperty)) {
2274         return JNI_ENOMEM;
2275       }
2276     } else if (match_option(option, "--patch-module=", &tail)) {
2277       // --patch-module=<module>=<file>(<pathsep><file>)*
2278       int res = process_patch_mod_option(tail, patch_mod_javabase);
2279       if (res != JNI_OK) {
2280         return res;
2281       }
2282     } else if (match_option(option, "--illegal-access=", &tail)) {
2283       char version[256];
2284       JDK_Version::jdk(17).to_string(version, sizeof(version));
2285       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2286     // -agentlib and -agentpath
2287     } else if (match_option(option, "-agentlib:", &tail) ||
2288           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2289       if(tail != nullptr) {
2290         const char* pos = strchr(tail, '=');
2291         char* name;
2292         if (pos == nullptr) {
2293           name = os::strdup_check_oom(tail, mtArguments);
2294         } else {
2295           size_t len = pos - tail;
2296           name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2297           memcpy(name, tail, len);
2298           name[len] = '\0';
2299         }
2300 
2301         char *options = nullptr;
2302         if(pos != nullptr) {
2303           options = os::strdup_check_oom(pos + 1, mtArguments);
2304         }
2305 #if !INCLUDE_JVMTI
2306         if (valid_jdwp_agent(name, is_absolute_path)) {
2307           jio_fprintf(defaultStream::error_stream(),
2308             "Debugging agents are not supported in this VM\n");
2309           return JNI_ERR;
2310         }
2311 #endif // !INCLUDE_JVMTI
2312         JvmtiAgentList::add(name, options, is_absolute_path);
2313         os::free(name);
2314         os::free(options);
2315       }
2316     // -javaagent
2317     } else if (match_option(option, "-javaagent:", &tail)) {
2318 #if !INCLUDE_JVMTI
2319       jio_fprintf(defaultStream::error_stream(),
2320         "Instrumentation agents are not supported in this VM\n");
2321       return JNI_ERR;
2322 #else
2323       if (tail != nullptr) {
2324         size_t length = strlen(tail) + 1;
2325         char *options = NEW_C_HEAP_ARRAY(char, length, mtArguments);
2326         jio_snprintf(options, length, "%s", tail);
2327         JvmtiAgentList::add("instrument", options, false);
2328         FREE_C_HEAP_ARRAY(char, options);
2329 
2330         // java agents need module java.instrument
2331         if (!create_numbered_module_property("jdk.module.addmods", "java.instrument", addmods_count++)) {
2332           return JNI_ENOMEM;
2333         }
2334       }
2335 #endif // !INCLUDE_JVMTI
2336     // --enable_preview
2337     } else if (match_option(option, "--enable-preview")) {
2338       set_enable_preview();
2339     // -Xnoclassgc
2340     } else if (match_option(option, "-Xnoclassgc")) {
2341       if (FLAG_SET_CMDLINE(ClassUnloading, false) != JVMFlag::SUCCESS) {
2342         return JNI_EINVAL;
2343       }
2344     // -Xbatch
2345     } else if (match_option(option, "-Xbatch")) {
2346       if (FLAG_SET_CMDLINE(BackgroundCompilation, false) != JVMFlag::SUCCESS) {
2347         return JNI_EINVAL;
2348       }
2349     // -Xmn for compatibility with other JVM vendors
2350     } else if (match_option(option, "-Xmn", &tail)) {
2351       julong long_initial_young_size = 0;
2352       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2353       if (errcode != arg_in_range) {
2354         jio_fprintf(defaultStream::error_stream(),
2355                     "Invalid initial young generation size: %s\n", option->optionString);
2356         describe_range_error(errcode);
2357         return JNI_EINVAL;
2358       }
2359       if (FLAG_SET_CMDLINE(MaxNewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {
2360         return JNI_EINVAL;
2361       }
2362       if (FLAG_SET_CMDLINE(NewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {
2363         return JNI_EINVAL;
2364       }
2365     // -Xms
2366     } else if (match_option(option, "-Xms", &tail)) {
2367       julong size = 0;
2368       // an initial heap size of 0 means automatically determine
2369       ArgsRange errcode = parse_memory_size(tail, &size, 0);
2370       if (errcode != arg_in_range) {
2371         jio_fprintf(defaultStream::error_stream(),
2372                     "Invalid initial heap size: %s\n", option->optionString);
2373         describe_range_error(errcode);
2374         return JNI_EINVAL;
2375       }
2376       if (FLAG_SET_CMDLINE(MinHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
2377         return JNI_EINVAL;
2378       }
2379       if (FLAG_SET_CMDLINE(InitialHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
2380         return JNI_EINVAL;
2381       }
2382     // -Xmx
2383     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2384       julong long_max_heap_size = 0;
2385       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2386       if (errcode != arg_in_range) {
2387         jio_fprintf(defaultStream::error_stream(),
2388                     "Invalid maximum heap size: %s\n", option->optionString);
2389         describe_range_error(errcode);
2390         return JNI_EINVAL;
2391       }
2392       if (FLAG_SET_CMDLINE(MaxHeapSize, (size_t)long_max_heap_size) != JVMFlag::SUCCESS) {
2393         return JNI_EINVAL;
2394       }
2395     // Xmaxf
2396     } else if (match_option(option, "-Xmaxf", &tail)) {
2397       char* err;
2398       int maxf = (int)(strtod(tail, &err) * 100);
2399       if (*err != '\0' || *tail == '\0') {
2400         jio_fprintf(defaultStream::error_stream(),
2401                     "Bad max heap free percentage size: %s\n",
2402                     option->optionString);
2403         return JNI_EINVAL;
2404       } else {
2405         if (FLAG_SET_CMDLINE(MaxHeapFreeRatio, maxf) != JVMFlag::SUCCESS) {
2406             return JNI_EINVAL;
2407         }
2408       }
2409     // Xminf
2410     } else if (match_option(option, "-Xminf", &tail)) {
2411       char* err;
2412       int minf = (int)(strtod(tail, &err) * 100);
2413       if (*err != '\0' || *tail == '\0') {
2414         jio_fprintf(defaultStream::error_stream(),
2415                     "Bad min heap free percentage size: %s\n",
2416                     option->optionString);
2417         return JNI_EINVAL;
2418       } else {
2419         if (FLAG_SET_CMDLINE(MinHeapFreeRatio, minf) != JVMFlag::SUCCESS) {
2420           return JNI_EINVAL;
2421         }
2422       }
2423     // -Xss
2424     } else if (match_option(option, "-Xss", &tail)) {
2425       intx value = 0;
2426       jint err = parse_xss(option, tail, &value);
2427       if (err != JNI_OK) {
2428         return err;
2429       }
2430       if (FLAG_SET_CMDLINE(ThreadStackSize, value) != JVMFlag::SUCCESS) {
2431         return JNI_EINVAL;
2432       }
2433     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2434                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2435       julong long_ReservedCodeCacheSize = 0;
2436 
2437       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2438       if (errcode != arg_in_range) {
2439         jio_fprintf(defaultStream::error_stream(),
2440                     "Invalid maximum code cache size: %s.\n", option->optionString);
2441         return JNI_EINVAL;
2442       }
2443       if (FLAG_SET_CMDLINE(ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != JVMFlag::SUCCESS) {
2444         return JNI_EINVAL;
2445       }
2446     // -green
2447     } else if (match_option(option, "-green")) {
2448       jio_fprintf(defaultStream::error_stream(),
2449                   "Green threads support not available\n");
2450           return JNI_EINVAL;
2451     // -native
2452     } else if (match_option(option, "-native")) {
2453           // HotSpot always uses native threads, ignore silently for compatibility
2454     // -Xrs
2455     } else if (match_option(option, "-Xrs")) {
2456           // Classic/EVM option, new functionality
2457       if (FLAG_SET_CMDLINE(ReduceSignalUsage, true) != JVMFlag::SUCCESS) {
2458         return JNI_EINVAL;
2459       }
2460       // -Xprof
2461     } else if (match_option(option, "-Xprof")) {
2462       char version[256];
2463       // Obsolete in JDK 10
2464       JDK_Version::jdk(10).to_string(version, sizeof(version));
2465       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2466     // -Xinternalversion
2467     } else if (match_option(option, "-Xinternalversion")) {
2468       jio_fprintf(defaultStream::output_stream(), "%s\n",
2469                   VM_Version::internal_vm_info_string());
2470       vm_exit(0);
2471 #ifndef PRODUCT
2472     // -Xprintflags
2473     } else if (match_option(option, "-Xprintflags")) {
2474       JVMFlag::printFlags(tty, false);
2475       vm_exit(0);
2476 #endif
2477     // -D
2478     } else if (match_option(option, "-D", &tail)) {
2479       const char* value;
2480       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2481             *value!= '\0' && strcmp(value, "\"\"") != 0) {
2482         // abort if -Djava.endorsed.dirs is set
2483         jio_fprintf(defaultStream::output_stream(),
2484           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2485           "in modular form will be supported via the concept of upgradeable modules.\n", value);
2486         return JNI_EINVAL;
2487       }
2488       if (match_option(option, "-Djava.ext.dirs=", &value) &&
2489             *value != '\0' && strcmp(value, "\"\"") != 0) {
2490         // abort if -Djava.ext.dirs is set
2491         jio_fprintf(defaultStream::output_stream(),
2492           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2493         return JNI_EINVAL;
2494       }
2495       // Check for module related properties.  They must be set using the modules
2496       // options. For example: use "--add-modules=java.sql", not
2497       // "-Djdk.module.addmods=java.sql"
2498       if (is_internal_module_property(option->optionString + 2)) {
2499         needs_module_property_warning = true;
2500         continue;
2501       }
2502       if (!add_property(tail)) {
2503         return JNI_ENOMEM;
2504       }
2505       // Out of the box management support
2506       if (match_option(option, "-Dcom.sun.management", &tail)) {
2507 #if INCLUDE_MANAGEMENT
2508         if (FLAG_SET_CMDLINE(ManagementServer, true) != JVMFlag::SUCCESS) {
2509           return JNI_EINVAL;
2510         }
2511         // management agent in module jdk.management.agent
2512         if (!create_numbered_module_property("jdk.module.addmods", "jdk.management.agent", addmods_count++)) {
2513           return JNI_ENOMEM;
2514         }
2515 #else
2516         jio_fprintf(defaultStream::output_stream(),
2517           "-Dcom.sun.management is not supported in this VM.\n");
2518         return JNI_ERR;
2519 #endif
2520       }
2521     // -Xint
2522     } else if (match_option(option, "-Xint")) {
2523           set_mode_flags(_int);
2524           mode_flag_cmd_line = true;
2525     // -Xmixed
2526     } else if (match_option(option, "-Xmixed")) {
2527           set_mode_flags(_mixed);
2528           mode_flag_cmd_line = true;
2529     // -Xcomp
2530     } else if (match_option(option, "-Xcomp")) {
2531       // for testing the compiler; turn off all flags that inhibit compilation
2532           set_mode_flags(_comp);
2533           mode_flag_cmd_line = true;
2534     // -Xshare:dump
2535     } else if (match_option(option, "-Xshare:dump")) {
2536       CDSConfig::enable_dumping_static_archive();
2537     // -Xshare:on
2538     } else if (match_option(option, "-Xshare:on")) {
2539       UseSharedSpaces = true;
2540       RequireSharedSpaces = true;
2541     // -Xshare:auto || -XX:ArchiveClassesAtExit=<archive file>
2542     } else if (match_option(option, "-Xshare:auto")) {
2543       UseSharedSpaces = true;
2544       RequireSharedSpaces = false;
2545       xshare_auto_cmd_line = true;
2546     // -Xshare:off
2547     } else if (match_option(option, "-Xshare:off")) {
2548       UseSharedSpaces = false;
2549       RequireSharedSpaces = false;
2550     // -Xverify
2551     } else if (match_option(option, "-Xverify", &tail)) {
2552       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
2553         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, true) != JVMFlag::SUCCESS) {
2554           return JNI_EINVAL;
2555         }
2556         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {
2557           return JNI_EINVAL;
2558         }
2559       } else if (strcmp(tail, ":remote") == 0) {
2560         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {
2561           return JNI_EINVAL;
2562         }
2563         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {
2564           return JNI_EINVAL;
2565         }
2566       } else if (strcmp(tail, ":none") == 0) {
2567         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {
2568           return JNI_EINVAL;
2569         }
2570         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, false) != JVMFlag::SUCCESS) {
2571           return JNI_EINVAL;
2572         }
2573         warning("Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.");
2574       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
2575         return JNI_EINVAL;
2576       }
2577     // -Xdebug
2578     } else if (match_option(option, "-Xdebug")) {
2579       warning("Option -Xdebug was deprecated in JDK 22 and will likely be removed in a future release.");
2580     } else if (match_option(option, "-Xloggc:", &tail)) {
2581       // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
2582       log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
2583       _legacyGCLogging.lastFlag = 2;
2584       _legacyGCLogging.file = os::strdup_check_oom(tail);
2585     } else if (match_option(option, "-Xlog", &tail)) {
2586       bool ret = false;
2587       if (strcmp(tail, ":help") == 0) {
2588         fileStream stream(defaultStream::output_stream());
2589         LogConfiguration::print_command_line_help(&stream);
2590         vm_exit(0);
2591       } else if (strcmp(tail, ":disable") == 0) {
2592         LogConfiguration::disable_logging();
2593         ret = true;
2594       } else if (strcmp(tail, ":async") == 0) {
2595         LogConfiguration::set_async_mode(true);
2596         ret = true;
2597       } else if (*tail == '\0') {
2598         ret = LogConfiguration::parse_command_line_arguments();
2599         assert(ret, "-Xlog without arguments should never fail to parse");
2600       } else if (*tail == ':') {
2601         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
2602       }
2603       if (ret == false) {
2604         jio_fprintf(defaultStream::error_stream(),
2605                     "Invalid -Xlog option '-Xlog%s', see error log for details.\n",
2606                     tail);
2607         return JNI_EINVAL;
2608       }
2609     // JNI hooks
2610     } else if (match_option(option, "-Xcheck", &tail)) {
2611       if (!strcmp(tail, ":jni")) {
2612 #if !INCLUDE_JNI_CHECK
2613         warning("JNI CHECKING is not supported in this VM");
2614 #else
2615         CheckJNICalls = true;
2616 #endif // INCLUDE_JNI_CHECK
2617       } else if (is_bad_option(option, args->ignoreUnrecognized,
2618                                      "check")) {
2619         return JNI_EINVAL;
2620       }
2621     } else if (match_option(option, "vfprintf")) {
2622       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
2623     } else if (match_option(option, "exit")) {
2624       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
2625     } else if (match_option(option, "abort")) {
2626       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
2627     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
2628     // and the last option wins.
2629     } else if (match_option(option, "-XX:+NeverTenure")) {
2630       if (FLAG_SET_CMDLINE(NeverTenure, true) != JVMFlag::SUCCESS) {
2631         return JNI_EINVAL;
2632       }
2633       if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {
2634         return JNI_EINVAL;
2635       }
2636       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, markWord::max_age + 1) != JVMFlag::SUCCESS) {
2637         return JNI_EINVAL;
2638       }
2639     } else if (match_option(option, "-XX:+AlwaysTenure")) {
2640       if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2641         return JNI_EINVAL;
2642       }
2643       if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {
2644         return JNI_EINVAL;
2645       }
2646       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, 0) != JVMFlag::SUCCESS) {
2647         return JNI_EINVAL;
2648       }
2649     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
2650       uint max_tenuring_thresh = 0;
2651       if (!parse_uint(tail, &max_tenuring_thresh, 0)) {
2652         jio_fprintf(defaultStream::error_stream(),
2653                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
2654         return JNI_EINVAL;
2655       }
2656 
2657       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, max_tenuring_thresh) != JVMFlag::SUCCESS) {
2658         return JNI_EINVAL;
2659       }
2660 
2661       if (MaxTenuringThreshold == 0) {
2662         if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2663           return JNI_EINVAL;
2664         }
2665         if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {
2666           return JNI_EINVAL;
2667         }
2668       } else {
2669         if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2670           return JNI_EINVAL;
2671         }
2672         if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {
2673           return JNI_EINVAL;
2674         }
2675       }
2676     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
2677       if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, false) != JVMFlag::SUCCESS) {
2678         return JNI_EINVAL;
2679       }
2680       if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, true) != JVMFlag::SUCCESS) {
2681         return JNI_EINVAL;
2682       }
2683     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
2684       if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, false) != JVMFlag::SUCCESS) {
2685         return JNI_EINVAL;
2686       }
2687       if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, true) != JVMFlag::SUCCESS) {
2688         return JNI_EINVAL;
2689       }
2690     } else if (match_option(option, "-XX:+ErrorFileToStderr")) {
2691       if (FLAG_SET_CMDLINE(ErrorFileToStdout, false) != JVMFlag::SUCCESS) {
2692         return JNI_EINVAL;
2693       }
2694       if (FLAG_SET_CMDLINE(ErrorFileToStderr, true) != JVMFlag::SUCCESS) {
2695         return JNI_EINVAL;
2696       }
2697     } else if (match_option(option, "-XX:+ErrorFileToStdout")) {
2698       if (FLAG_SET_CMDLINE(ErrorFileToStderr, false) != JVMFlag::SUCCESS) {
2699         return JNI_EINVAL;
2700       }
2701       if (FLAG_SET_CMDLINE(ErrorFileToStdout, true) != JVMFlag::SUCCESS) {
2702         return JNI_EINVAL;
2703       }
2704     } else if (match_option(option, "--finalization=", &tail)) {
2705       if (strcmp(tail, "enabled") == 0) {
2706         InstanceKlass::set_finalization_enabled(true);
2707       } else if (strcmp(tail, "disabled") == 0) {
2708         InstanceKlass::set_finalization_enabled(false);
2709       } else {
2710         jio_fprintf(defaultStream::error_stream(),
2711                     "Invalid finalization value '%s', must be 'disabled' or 'enabled'.\n",
2712                     tail);
2713         return JNI_EINVAL;
2714       }
2715 #if !defined(DTRACE_ENABLED)
2716     } else if (match_option(option, "-XX:+DTraceMethodProbes")) {
2717       jio_fprintf(defaultStream::error_stream(),
2718                   "DTraceMethodProbes flag is not applicable for this configuration\n");
2719       return JNI_EINVAL;
2720     } else if (match_option(option, "-XX:+DTraceAllocProbes")) {
2721       jio_fprintf(defaultStream::error_stream(),
2722                   "DTraceAllocProbes flag is not applicable for this configuration\n");
2723       return JNI_EINVAL;
2724     } else if (match_option(option, "-XX:+DTraceMonitorProbes")) {
2725       jio_fprintf(defaultStream::error_stream(),
2726                   "DTraceMonitorProbes flag is not applicable for this configuration\n");
2727       return JNI_EINVAL;
2728 #endif // !defined(DTRACE_ENABLED)
2729 #ifdef ASSERT
2730     } else if (match_option(option, "-XX:+FullGCALot")) {
2731       if (FLAG_SET_CMDLINE(FullGCALot, true) != JVMFlag::SUCCESS) {
2732         return JNI_EINVAL;
2733       }
2734       // disable scavenge before parallel mark-compact
2735       if (FLAG_SET_CMDLINE(ScavengeBeforeFullGC, false) != JVMFlag::SUCCESS) {
2736         return JNI_EINVAL;
2737       }
2738 #endif
2739 #if !INCLUDE_MANAGEMENT
2740     } else if (match_option(option, "-XX:+ManagementServer")) {
2741         jio_fprintf(defaultStream::error_stream(),
2742           "ManagementServer is not supported in this VM.\n");
2743         return JNI_ERR;
2744 #endif // INCLUDE_MANAGEMENT
2745 #if INCLUDE_JVMCI
2746     } else if (match_option(option, "-XX:-EnableJVMCIProduct") || match_option(option, "-XX:-UseGraalJIT")) {
2747       if (EnableJVMCIProduct) {
2748         jio_fprintf(defaultStream::error_stream(),
2749                   "-XX:-EnableJVMCIProduct or -XX:-UseGraalJIT cannot come after -XX:+EnableJVMCIProduct or -XX:+UseGraalJIT\n");
2750         return JNI_EINVAL;
2751       }
2752     } else if (match_option(option, "-XX:+EnableJVMCIProduct") || match_option(option, "-XX:+UseGraalJIT")) {
2753       bool use_graal_jit = match_option(option, "-XX:+UseGraalJIT");
2754       if (use_graal_jit) {
2755         const char* jvmci_compiler = get_property("jvmci.Compiler");
2756         if (jvmci_compiler != nullptr) {
2757           if (strncmp(jvmci_compiler, "graal", strlen("graal")) != 0) {
2758             jio_fprintf(defaultStream::error_stream(),
2759               "Value of jvmci.Compiler incompatible with +UseGraalJIT: %s\n", jvmci_compiler);
2760             return JNI_ERR;
2761           }
2762         } else if (!add_property("jvmci.Compiler=graal")) {
2763             return JNI_ENOMEM;
2764         }
2765       }
2766 
2767       // Just continue, since "-XX:+EnableJVMCIProduct" or "-XX:+UseGraalJIT" has been specified before
2768       if (EnableJVMCIProduct) {
2769         continue;
2770       }
2771       JVMFlag *jvmciFlag = JVMFlag::find_flag("EnableJVMCIProduct");
2772       // Allow this flag if it has been unlocked.
2773       if (jvmciFlag != nullptr && jvmciFlag->is_unlocked()) {
2774         if (!JVMCIGlobals::enable_jvmci_product_mode(origin, use_graal_jit)) {
2775           jio_fprintf(defaultStream::error_stream(),
2776             "Unable to enable JVMCI in product mode\n");
2777           return JNI_ERR;
2778         }
2779       }
2780       // The flag was locked so process normally to report that error
2781       else if (!process_argument(use_graal_jit ? "UseGraalJIT" : "EnableJVMCIProduct", args->ignoreUnrecognized, origin)) {
2782         return JNI_EINVAL;
2783       }
2784 #endif // INCLUDE_JVMCI
2785 #if INCLUDE_JFR
2786     } else if (match_jfr_option(&option)) {
2787       return JNI_EINVAL;
2788 #endif
2789     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
2790       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
2791       // already been handled
2792       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
2793           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
2794         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
2795           return JNI_EINVAL;
2796         }
2797       }
2798     // Unknown option
2799     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
2800       return JNI_ERR;
2801     }
2802   }
2803 
2804   // PrintSharedArchiveAndExit will turn on
2805   //   -Xshare:on
2806   //   -Xlog:class+path=info
2807   if (PrintSharedArchiveAndExit) {
2808     UseSharedSpaces = true;
2809     RequireSharedSpaces = true;
2810     LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));
2811   }
2812 
2813   fix_appclasspath();
2814 
2815   return JNI_OK;
2816 }
2817 
2818 void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {
2819   // For java.base check for duplicate --patch-module options being specified on the command line.
2820   // This check is only required for java.base, all other duplicate module specifications
2821   // will be checked during module system initialization.  The module system initialization
2822   // will throw an ExceptionInInitializerError if this situation occurs.
2823   if (strcmp(module_name, JAVA_BASE_NAME) == 0) {
2824     if (*patch_mod_javabase) {
2825       vm_exit_during_initialization("Cannot specify " JAVA_BASE_NAME " more than once to --patch-module");
2826     } else {
2827       *patch_mod_javabase = true;
2828     }
2829   }
2830 
2831   // Create GrowableArray lazily, only if --patch-module has been specified
2832   if (_patch_mod_prefix == nullptr) {
2833     _patch_mod_prefix = new (mtArguments) GrowableArray<ModulePatchPath*>(10, mtArguments);
2834   }
2835 
2836   _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
2837 }
2838 
2839 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
2840 //
2841 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
2842 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
2843 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
2844 // path is treated as the current directory.
2845 //
2846 // This causes problems with CDS, which requires that all directories specified in the classpath
2847 // must be empty. In most cases, applications do NOT want to load classes from the current
2848 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
2849 // scripts compatible with CDS.
2850 void Arguments::fix_appclasspath() {
2851   if (IgnoreEmptyClassPaths) {
2852     const char separator = *os::path_separator();
2853     const char* src = _java_class_path->value();
2854 
2855     // skip over all the leading empty paths
2856     while (*src == separator) {
2857       src ++;
2858     }
2859 
2860     char* copy = os::strdup_check_oom(src, mtArguments);
2861 
2862     // trim all trailing empty paths
2863     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
2864       *tail = '\0';
2865     }
2866 
2867     char from[3] = {separator, separator, '\0'};
2868     char to  [2] = {separator, '\0'};
2869     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
2870       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
2871       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
2872     }
2873 
2874     _java_class_path->set_writeable_value(copy);
2875     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
2876   }
2877 }
2878 
2879 jint Arguments::finalize_vm_init_args(bool patch_mod_javabase) {
2880   // check if the default lib/endorsed directory exists; if so, error
2881   char path[JVM_MAXPATHLEN];
2882   const char* fileSep = os::file_separator();
2883   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
2884 
2885   DIR* dir = os::opendir(path);
2886   if (dir != nullptr) {
2887     jio_fprintf(defaultStream::output_stream(),
2888       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
2889       "in modular form will be supported via the concept of upgradeable modules.\n");
2890     os::closedir(dir);
2891     return JNI_ERR;
2892   }
2893 
2894   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
2895   dir = os::opendir(path);
2896   if (dir != nullptr) {
2897     jio_fprintf(defaultStream::output_stream(),
2898       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
2899       "Use -classpath instead.\n.");
2900     os::closedir(dir);
2901     return JNI_ERR;
2902   }
2903 
2904   // This must be done after all arguments have been processed
2905   // and the container support has been initialized since AggressiveHeap
2906   // relies on the amount of total memory available.
2907   if (AggressiveHeap) {
2908     jint result = set_aggressive_heap_flags();
2909     if (result != JNI_OK) {
2910       return result;
2911     }
2912   }
2913 
2914   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
2915   // but like -Xint, leave compilation thresholds unaffected.
2916   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
2917   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
2918     set_mode_flags(_int);
2919   }
2920 
2921 #ifdef ZERO
2922   // Zero always runs in interpreted mode
2923   set_mode_flags(_int);
2924 #endif
2925 
2926   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
2927   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
2928     FLAG_SET_ERGO(InitialTenuringThreshold, MaxTenuringThreshold);
2929   }
2930 
2931 #if !COMPILER2_OR_JVMCI
2932   // Don't degrade server performance for footprint
2933   if (FLAG_IS_DEFAULT(UseLargePages) &&
2934       MaxHeapSize < LargePageHeapSizeThreshold) {
2935     // No need for large granularity pages w/small heaps.
2936     // Note that large pages are enabled/disabled for both the
2937     // Java heap and the code cache.
2938     FLAG_SET_DEFAULT(UseLargePages, false);
2939   }
2940 
2941   UNSUPPORTED_OPTION(ProfileInterpreter);
2942 #endif
2943 
2944   // Parse the CompilationMode flag
2945   if (!CompilationModeFlag::initialize()) {
2946     return JNI_ERR;
2947   }
2948 
2949   if (!check_vm_args_consistency()) {
2950     return JNI_ERR;
2951   }
2952 
2953   if (!CDSConfig::check_vm_args_consistency(patch_mod_javabase, mode_flag_cmd_line)) {
2954     return JNI_ERR;
2955   }
2956 
2957 #ifndef CAN_SHOW_REGISTERS_ON_ASSERT
2958   UNSUPPORTED_OPTION(ShowRegistersOnAssert);
2959 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
2960 
2961   return JNI_OK;
2962 }
2963 
2964 // Helper class for controlling the lifetime of JavaVMInitArgs
2965 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
2966 // deleted on the destruction of the ScopedVMInitArgs object.
2967 class ScopedVMInitArgs : public StackObj {
2968  private:
2969   JavaVMInitArgs _args;
2970   char*          _container_name;
2971   bool           _is_set;
2972   char*          _vm_options_file_arg;
2973 
2974  public:
2975   ScopedVMInitArgs(const char *container_name) {
2976     _args.version = JNI_VERSION_1_2;
2977     _args.nOptions = 0;
2978     _args.options = nullptr;
2979     _args.ignoreUnrecognized = false;
2980     _container_name = (char *)container_name;
2981     _is_set = false;
2982     _vm_options_file_arg = nullptr;
2983   }
2984 
2985   // Populates the JavaVMInitArgs object represented by this
2986   // ScopedVMInitArgs object with the arguments in options.  The
2987   // allocated memory is deleted by the destructor.  If this method
2988   // returns anything other than JNI_OK, then this object is in a
2989   // partially constructed state, and should be abandoned.
2990   jint set_args(const GrowableArrayView<JavaVMOption>* options) {
2991     _is_set = true;
2992     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
2993         JavaVMOption, options->length(), mtArguments);
2994     if (options_arr == nullptr) {
2995       return JNI_ENOMEM;
2996     }
2997     _args.options = options_arr;
2998 
2999     for (int i = 0; i < options->length(); i++) {
3000       options_arr[i] = options->at(i);
3001       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3002       if (options_arr[i].optionString == nullptr) {
3003         // Rely on the destructor to do cleanup.
3004         _args.nOptions = i;
3005         return JNI_ENOMEM;
3006       }
3007     }
3008 
3009     _args.nOptions = options->length();
3010     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3011     return JNI_OK;
3012   }
3013 
3014   JavaVMInitArgs* get()             { return &_args; }
3015   char* container_name()            { return _container_name; }
3016   bool  is_set()                    { return _is_set; }
3017   bool  found_vm_options_file_arg() { return _vm_options_file_arg != nullptr; }
3018   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3019 
3020   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3021     if (_vm_options_file_arg != nullptr) {
3022       os::free(_vm_options_file_arg);
3023     }
3024     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3025   }
3026 
3027   ~ScopedVMInitArgs() {
3028     if (_vm_options_file_arg != nullptr) {
3029       os::free(_vm_options_file_arg);
3030     }
3031     if (_args.options == nullptr) return;
3032     for (int i = 0; i < _args.nOptions; i++) {
3033       os::free(_args.options[i].optionString);
3034     }
3035     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3036   }
3037 
3038   // Insert options into this option list, to replace option at
3039   // vm_options_file_pos (-XX:VMOptionsFile)
3040   jint insert(const JavaVMInitArgs* args,
3041               const JavaVMInitArgs* args_to_insert,
3042               const int vm_options_file_pos) {
3043     assert(_args.options == nullptr, "shouldn't be set yet");
3044     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3045     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3046 
3047     int length = args->nOptions + args_to_insert->nOptions - 1;
3048     // Construct new option array
3049     GrowableArrayCHeap<JavaVMOption, mtArguments> options(length);
3050     for (int i = 0; i < args->nOptions; i++) {
3051       if (i == vm_options_file_pos) {
3052         // insert the new options starting at the same place as the
3053         // -XX:VMOptionsFile option
3054         for (int j = 0; j < args_to_insert->nOptions; j++) {
3055           options.push(args_to_insert->options[j]);
3056         }
3057       } else {
3058         options.push(args->options[i]);
3059       }
3060     }
3061     // make into options array
3062     return set_args(&options);
3063   }
3064 };
3065 
3066 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3067   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3068 }
3069 
3070 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3071   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3072 }
3073 
3074 jint Arguments::parse_options_environment_variable(const char* name,
3075                                                    ScopedVMInitArgs* vm_args) {
3076   char *buffer = ::getenv(name);
3077 
3078   // Don't check this environment variable if user has special privileges
3079   // (e.g. unix su command).
3080   if (buffer == nullptr || os::have_special_privileges()) {
3081     return JNI_OK;
3082   }
3083 
3084   if ((buffer = os::strdup(buffer)) == nullptr) {
3085     return JNI_ENOMEM;
3086   }
3087 
3088   jio_fprintf(defaultStream::error_stream(),
3089               "Picked up %s: %s\n", name, buffer);
3090 
3091   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3092 
3093   os::free(buffer);
3094   return retcode;
3095 }
3096 
3097 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3098   // read file into buffer
3099   int fd = ::open(file_name, O_RDONLY);
3100   if (fd < 0) {
3101     jio_fprintf(defaultStream::error_stream(),
3102                 "Could not open options file '%s'\n",
3103                 file_name);
3104     return JNI_ERR;
3105   }
3106 
3107   struct stat stbuf;
3108   int retcode = os::stat(file_name, &stbuf);
3109   if (retcode != 0) {
3110     jio_fprintf(defaultStream::error_stream(),
3111                 "Could not stat options file '%s'\n",
3112                 file_name);
3113     ::close(fd);
3114     return JNI_ERR;
3115   }
3116 
3117   if (stbuf.st_size == 0) {
3118     // tell caller there is no option data and that is ok
3119     ::close(fd);
3120     return JNI_OK;
3121   }
3122 
3123   // '+ 1' for null termination even with max bytes
3124   size_t bytes_alloc = stbuf.st_size + 1;
3125 
3126   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3127   if (nullptr == buf) {
3128     jio_fprintf(defaultStream::error_stream(),
3129                 "Could not allocate read buffer for options file parse\n");
3130     ::close(fd);
3131     return JNI_ENOMEM;
3132   }
3133 
3134   memset(buf, 0, bytes_alloc);
3135 
3136   // Fill buffer
3137   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3138   ::close(fd);
3139   if (bytes_read < 0) {
3140     FREE_C_HEAP_ARRAY(char, buf);
3141     jio_fprintf(defaultStream::error_stream(),
3142                 "Could not read options file '%s'\n", file_name);
3143     return JNI_ERR;
3144   }
3145 
3146   if (bytes_read == 0) {
3147     // tell caller there is no option data and that is ok
3148     FREE_C_HEAP_ARRAY(char, buf);
3149     return JNI_OK;
3150   }
3151 
3152   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3153 
3154   FREE_C_HEAP_ARRAY(char, buf);
3155   return retcode;
3156 }
3157 
3158 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3159   // Construct option array
3160   GrowableArrayCHeap<JavaVMOption, mtArguments> options(2);
3161 
3162   // some pointers to help with parsing
3163   char *buffer_end = buffer + buf_len;
3164   char *opt_hd = buffer;
3165   char *wrt = buffer;
3166   char *rd = buffer;
3167 
3168   // parse all options
3169   while (rd < buffer_end) {
3170     // skip leading white space from the input string
3171     while (rd < buffer_end && isspace(*rd)) {
3172       rd++;
3173     }
3174 
3175     if (rd >= buffer_end) {
3176       break;
3177     }
3178 
3179     // Remember this is where we found the head of the token.
3180     opt_hd = wrt;
3181 
3182     // Tokens are strings of non white space characters separated
3183     // by one or more white spaces.
3184     while (rd < buffer_end && !isspace(*rd)) {
3185       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3186         int quote = *rd;                    // matching quote to look for
3187         rd++;                               // don't copy open quote
3188         while (rd < buffer_end && *rd != quote) {
3189                                             // include everything (even spaces)
3190                                             // up until the close quote
3191           *wrt++ = *rd++;                   // copy to option string
3192         }
3193 
3194         if (rd < buffer_end) {
3195           rd++;                             // don't copy close quote
3196         } else {
3197                                             // did not see closing quote
3198           jio_fprintf(defaultStream::error_stream(),
3199                       "Unmatched quote in %s\n", name);
3200           return JNI_ERR;
3201         }
3202       } else {
3203         *wrt++ = *rd++;                     // copy to option string
3204       }
3205     }
3206 
3207     // steal a white space character and set it to null
3208     *wrt++ = '\0';
3209     // We now have a complete token
3210 
3211     JavaVMOption option;
3212     option.optionString = opt_hd;
3213     option.extraInfo = nullptr;
3214 
3215     options.append(option);                // Fill in option
3216 
3217     rd++;  // Advance to next character
3218   }
3219 
3220   // Fill out JavaVMInitArgs structure.
3221   return vm_args->set_args(&options);
3222 }
3223 
3224 #ifndef PRODUCT
3225 // Determine whether LogVMOutput should be implicitly turned on.
3226 static bool use_vm_log() {
3227   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3228       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3229       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3230       PrintAssembly || TraceDeoptimization ||
3231       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3232     return true;
3233   }
3234 
3235 #ifdef COMPILER1
3236   if (PrintC1Statistics) {
3237     return true;
3238   }
3239 #endif // COMPILER1
3240 
3241 #ifdef COMPILER2
3242   if (PrintOptoAssembly || PrintOptoStatistics) {
3243     return true;
3244   }
3245 #endif // COMPILER2
3246 
3247   return false;
3248 }
3249 
3250 #endif // PRODUCT
3251 
3252 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3253   for (int index = 0; index < args->nOptions; index++) {
3254     const JavaVMOption* option = args->options + index;
3255     const char* tail;
3256     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3257       return true;
3258     }
3259   }
3260   return false;
3261 }
3262 
3263 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3264                                        const char* vm_options_file,
3265                                        const int vm_options_file_pos,
3266                                        ScopedVMInitArgs* vm_options_file_args,
3267                                        ScopedVMInitArgs* args_out) {
3268   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
3269   if (code != JNI_OK) {
3270     return code;
3271   }
3272 
3273   if (vm_options_file_args->get()->nOptions < 1) {
3274     return JNI_OK;
3275   }
3276 
3277   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
3278     jio_fprintf(defaultStream::error_stream(),
3279                 "A VM options file may not refer to a VM options file. "
3280                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
3281                 "options file '%s' in options container '%s' is an error.\n",
3282                 vm_options_file_args->vm_options_file_arg(),
3283                 vm_options_file_args->container_name());
3284     return JNI_EINVAL;
3285   }
3286 
3287   return args_out->insert(args, vm_options_file_args->get(),
3288                           vm_options_file_pos);
3289 }
3290 
3291 // Expand -XX:VMOptionsFile found in args_in as needed.
3292 // mod_args and args_out parameters may return values as needed.
3293 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
3294                                             ScopedVMInitArgs* mod_args,
3295                                             JavaVMInitArgs** args_out) {
3296   jint code = match_special_option_and_act(args_in, mod_args);
3297   if (code != JNI_OK) {
3298     return code;
3299   }
3300 
3301   if (mod_args->is_set()) {
3302     // args_in contains -XX:VMOptionsFile and mod_args contains the
3303     // original options from args_in along with the options expanded
3304     // from the VMOptionsFile. Return a short-hand to the caller.
3305     *args_out = mod_args->get();
3306   } else {
3307     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
3308   }
3309   return JNI_OK;
3310 }
3311 
3312 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3313                                              ScopedVMInitArgs* args_out) {
3314   // Remaining part of option string
3315   const char* tail;
3316   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
3317 
3318   for (int index = 0; index < args->nOptions; index++) {
3319     const JavaVMOption* option = args->options + index;
3320     if (match_option(option, "-XX:Flags=", &tail)) {
3321       Arguments::set_jvm_flags_file(tail);
3322       continue;
3323     }
3324     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3325       if (vm_options_file_args.found_vm_options_file_arg()) {
3326         jio_fprintf(defaultStream::error_stream(),
3327                     "The option '%s' is already specified in the options "
3328                     "container '%s' so the specification of '%s' in the "
3329                     "same options container is an error.\n",
3330                     vm_options_file_args.vm_options_file_arg(),
3331                     vm_options_file_args.container_name(),
3332                     option->optionString);
3333         return JNI_EINVAL;
3334       }
3335       vm_options_file_args.set_vm_options_file_arg(option->optionString);
3336       // If there's a VMOptionsFile, parse that
3337       jint code = insert_vm_options_file(args, tail, index,
3338                                          &vm_options_file_args, args_out);
3339       if (code != JNI_OK) {
3340         return code;
3341       }
3342       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
3343       if (args_out->is_set()) {
3344         // The VMOptions file inserted some options so switch 'args'
3345         // to the new set of options, and continue processing which
3346         // preserves "last option wins" semantics.
3347         args = args_out->get();
3348         // The first option from the VMOptionsFile replaces the
3349         // current option.  So we back track to process the
3350         // replacement option.
3351         index--;
3352       }
3353       continue;
3354     }
3355     if (match_option(option, "-XX:+PrintVMOptions")) {
3356       PrintVMOptions = true;
3357       continue;
3358     }
3359     if (match_option(option, "-XX:-PrintVMOptions")) {
3360       PrintVMOptions = false;
3361       continue;
3362     }
3363     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3364       IgnoreUnrecognizedVMOptions = true;
3365       continue;
3366     }
3367     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3368       IgnoreUnrecognizedVMOptions = false;
3369       continue;
3370     }
3371     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3372       JVMFlag::printFlags(tty, false);
3373       vm_exit(0);
3374     }
3375 
3376 #ifndef PRODUCT
3377     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3378       JVMFlag::printFlags(tty, true);
3379       vm_exit(0);
3380     }
3381 #endif
3382   }
3383   return JNI_OK;
3384 }
3385 
3386 static void print_options(const JavaVMInitArgs *args) {
3387   const char* tail;
3388   for (int index = 0; index < args->nOptions; index++) {
3389     const JavaVMOption *option = args->options + index;
3390     if (match_option(option, "-XX:", &tail)) {
3391       logOption(tail);
3392     }
3393   }
3394 }
3395 
3396 bool Arguments::handle_deprecated_print_gc_flags() {
3397   if (PrintGC) {
3398     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
3399   }
3400   if (PrintGCDetails) {
3401     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
3402   }
3403 
3404   if (_legacyGCLogging.lastFlag == 2) {
3405     // -Xloggc was used to specify a filename
3406     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
3407 
3408     LogTarget(Error, logging) target;
3409     LogStream errstream(target);
3410     return LogConfiguration::parse_log_arguments(_legacyGCLogging.file, gc_conf, nullptr, nullptr, &errstream);
3411   } else if (PrintGC || PrintGCDetails || (_legacyGCLogging.lastFlag == 1)) {
3412     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
3413   }
3414   return true;
3415 }
3416 
3417 static void apply_debugger_ergo() {
3418 #ifdef ASSERT
3419   if (ReplayCompiles) {
3420     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo, true);
3421   }
3422 
3423   if (UseDebuggerErgo) {
3424     // Turn on sub-flags
3425     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo1, true);
3426     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo2, true);
3427   }
3428 
3429   if (UseDebuggerErgo2) {
3430     // Debugging with limited number of CPUs
3431     FLAG_SET_ERGO_IF_DEFAULT(UseNUMA, false);
3432     FLAG_SET_ERGO_IF_DEFAULT(ConcGCThreads, 1);
3433     FLAG_SET_ERGO_IF_DEFAULT(ParallelGCThreads, 1);
3434     FLAG_SET_ERGO_IF_DEFAULT(CICompilerCount, 2);
3435   }
3436 #endif // ASSERT
3437 }
3438 
3439 // Parse entry point called from JNI_CreateJavaVM
3440 
3441 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
3442   assert(verify_special_jvm_flags(false), "deprecated and obsolete flag table inconsistent");
3443   JVMFlag::check_all_flag_declarations();
3444 
3445   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3446   const char* hotspotrc = ".hotspotrc";
3447   bool settings_file_specified = false;
3448   bool needs_hotspotrc_warning = false;
3449   ScopedVMInitArgs initial_vm_options_args("");
3450   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3451   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
3452 
3453   // Pointers to current working set of containers
3454   JavaVMInitArgs* cur_cmd_args;
3455   JavaVMInitArgs* cur_vm_options_args;
3456   JavaVMInitArgs* cur_java_options_args;
3457   JavaVMInitArgs* cur_java_tool_options_args;
3458 
3459   // Containers for modified/expanded options
3460   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
3461   ScopedVMInitArgs mod_vm_options_args("vm_options_args");
3462   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3463   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
3464 
3465 
3466   jint code =
3467       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
3468   if (code != JNI_OK) {
3469     return code;
3470   }
3471 
3472   code = parse_java_options_environment_variable(&initial_java_options_args);
3473   if (code != JNI_OK) {
3474     return code;
3475   }
3476 
3477   // Parse the options in the /java.base/jdk/internal/vm/options resource, if present
3478   char *vmoptions = ClassLoader::lookup_vm_options();
3479   if (vmoptions != nullptr) {
3480     code = parse_options_buffer("vm options resource", vmoptions, strlen(vmoptions), &initial_vm_options_args);
3481     FREE_C_HEAP_ARRAY(char, vmoptions);
3482     if (code != JNI_OK) {
3483       return code;
3484     }
3485   }
3486 
3487   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
3488                                      &mod_java_tool_options_args,
3489                                      &cur_java_tool_options_args);
3490   if (code != JNI_OK) {
3491     return code;
3492   }
3493 
3494   code = expand_vm_options_as_needed(initial_cmd_args,
3495                                      &mod_cmd_args,
3496                                      &cur_cmd_args);
3497   if (code != JNI_OK) {
3498     return code;
3499   }
3500 
3501   code = expand_vm_options_as_needed(initial_java_options_args.get(),
3502                                      &mod_java_options_args,
3503                                      &cur_java_options_args);
3504   if (code != JNI_OK) {
3505     return code;
3506   }
3507 
3508   code = expand_vm_options_as_needed(initial_vm_options_args.get(),
3509                                      &mod_vm_options_args,
3510                                      &cur_vm_options_args);
3511   if (code != JNI_OK) {
3512     return code;
3513   }
3514 
3515   const char* flags_file = Arguments::get_jvm_flags_file();
3516   settings_file_specified = (flags_file != nullptr);
3517 
3518   if (IgnoreUnrecognizedVMOptions) {
3519     cur_cmd_args->ignoreUnrecognized = true;
3520     cur_java_tool_options_args->ignoreUnrecognized = true;
3521     cur_java_options_args->ignoreUnrecognized = true;
3522   }
3523 
3524   // Parse specified settings file
3525   if (settings_file_specified) {
3526     if (!process_settings_file(flags_file, true,
3527                                cur_cmd_args->ignoreUnrecognized)) {
3528       return JNI_EINVAL;
3529     }
3530   } else {
3531 #ifdef ASSERT
3532     // Parse default .hotspotrc settings file
3533     if (!process_settings_file(".hotspotrc", false,
3534                                cur_cmd_args->ignoreUnrecognized)) {
3535       return JNI_EINVAL;
3536     }
3537 #else
3538     struct stat buf;
3539     if (os::stat(hotspotrc, &buf) == 0) {
3540       needs_hotspotrc_warning = true;
3541     }
3542 #endif
3543   }
3544 
3545   if (PrintVMOptions) {
3546     print_options(cur_java_tool_options_args);
3547     print_options(cur_cmd_args);
3548     print_options(cur_java_options_args);
3549   }
3550 
3551   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
3552   jint result = parse_vm_init_args(cur_vm_options_args,
3553                                    cur_java_tool_options_args,
3554                                    cur_java_options_args,
3555                                    cur_cmd_args);
3556 
3557   if (result != JNI_OK) {
3558     return result;
3559   }
3560 
3561   // Delay warning until here so that we've had a chance to process
3562   // the -XX:-PrintWarnings flag
3563   if (needs_hotspotrc_warning) {
3564     warning("%s file is present but has been ignored.  "
3565             "Run with -XX:Flags=%s to load the file.",
3566             hotspotrc, hotspotrc);
3567   }
3568 
3569   if (needs_module_property_warning) {
3570     warning("Ignoring system property options whose names match the '-Djdk.module.*'."
3571             " names that are reserved for internal use.");
3572   }
3573 
3574 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
3575   UNSUPPORTED_OPTION(UseLargePages);
3576 #endif
3577 
3578 #if defined(AIX)
3579   UNSUPPORTED_OPTION_NULL(AllocateHeapAt);
3580 #endif
3581 
3582 #ifndef PRODUCT
3583   if (TraceBytecodesAt != 0) {
3584     TraceBytecodes = true;
3585   }
3586 #endif // PRODUCT
3587 
3588   if (ScavengeRootsInCode == 0) {
3589     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3590       warning("Forcing ScavengeRootsInCode non-zero");
3591     }
3592     ScavengeRootsInCode = 1;
3593   }
3594 
3595   if (!handle_deprecated_print_gc_flags()) {
3596     return JNI_EINVAL;
3597   }
3598 
3599   // Set object alignment values.
3600   set_object_alignment();
3601 
3602 #if !INCLUDE_CDS
3603   if (CDSConfig::is_dumping_static_archive() || RequireSharedSpaces) {
3604     jio_fprintf(defaultStream::error_stream(),
3605       "Shared spaces are not supported in this VM\n");
3606     return JNI_ERR;
3607   }
3608   if (DumpLoadedClassList != nullptr) {
3609     jio_fprintf(defaultStream::error_stream(),
3610       "DumpLoadedClassList is not supported in this VM\n");
3611     return JNI_ERR;
3612   }
3613   if ((UseSharedSpaces && xshare_auto_cmd_line) ||
3614       log_is_enabled(Info, cds)) {
3615     warning("Shared spaces are not supported in this VM");
3616     UseSharedSpaces = false;
3617     LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(cds));
3618   }
3619   no_shared_spaces("CDS Disabled");
3620 #endif // INCLUDE_CDS
3621 
3622   // Verify NMT arguments
3623   const NMT_TrackingLevel lvl = NMTUtil::parse_tracking_level(NativeMemoryTracking);
3624   if (lvl == NMT_unknown) {
3625     jio_fprintf(defaultStream::error_stream(),
3626                 "Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]\n");
3627     return JNI_ERR;
3628   }
3629   if (PrintNMTStatistics && lvl == NMT_off) {
3630     warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
3631     FLAG_SET_DEFAULT(PrintNMTStatistics, false);
3632   }
3633 
3634   bool trace_dependencies = log_is_enabled(Debug, dependencies);
3635   if (trace_dependencies && VerifyDependencies) {
3636     warning("dependency logging results may be inflated by VerifyDependencies");
3637   }
3638 
3639   bool log_class_load_cause = log_is_enabled(Info, class, load, cause, native) ||
3640                               log_is_enabled(Info, class, load, cause);
3641   if (log_class_load_cause && LogClassLoadingCauseFor == nullptr) {
3642     warning("class load cause logging will not produce output without LogClassLoadingCauseFor");
3643   }
3644 
3645   apply_debugger_ergo();
3646 
3647   if (log_is_enabled(Info, arguments)) {
3648     LogStream st(Log(arguments)::info());
3649     Arguments::print_on(&st);
3650   }
3651 
3652   return JNI_OK;
3653 }
3654 
3655 jint Arguments::apply_ergo() {
3656   // Set flags based on ergonomics.
3657   jint result = set_ergonomics_flags();
3658   if (result != JNI_OK) return result;
3659 
3660   // Set heap size based on available physical memory
3661   set_heap_size();
3662 
3663   GCConfig::arguments()->initialize();
3664 
3665   CDSConfig::initialize();
3666 
3667   // Initialize Metaspace flags and alignments
3668   Metaspace::ergo_initialize();
3669 
3670   if (!StringDedup::ergo_initialize()) {
3671     return JNI_EINVAL;
3672   }
3673 
3674   // Set compiler flags after GC is selected and GC specific
3675   // flags (LoopStripMiningIter) are set.
3676   CompilerConfig::ergo_initialize();
3677 
3678   // Set bytecode rewriting flags
3679   set_bytecode_flags();
3680 
3681   // Set flags if aggressive optimization flags are enabled
3682   jint code = set_aggressive_opts_flags();
3683   if (code != JNI_OK) {
3684     return code;
3685   }
3686 
3687 #ifdef ZERO
3688   // Clear flags not supported on zero.
3689   FLAG_SET_DEFAULT(ProfileInterpreter, false);
3690 #endif // ZERO
3691 
3692   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
3693     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
3694     DebugNonSafepoints = true;
3695   }
3696 
3697   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
3698     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
3699   }
3700 
3701   // Treat the odd case where local verification is enabled but remote
3702   // verification is not as if both were enabled.
3703   if (BytecodeVerificationLocal && !BytecodeVerificationRemote) {
3704     log_info(verification)("Turning on remote verification because local verification is on");
3705     FLAG_SET_DEFAULT(BytecodeVerificationRemote, true);
3706   }
3707 
3708 #ifndef PRODUCT
3709   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
3710     if (use_vm_log()) {
3711       LogVMOutput = true;
3712     }
3713   }
3714 #endif // PRODUCT
3715 
3716   if (PrintCommandLineFlags) {
3717     JVMFlag::printSetFlags(tty);
3718   }
3719 
3720 #if COMPILER2_OR_JVMCI
3721   if (!FLAG_IS_DEFAULT(EnableVectorSupport) && !EnableVectorSupport) {
3722     if (!FLAG_IS_DEFAULT(EnableVectorReboxing) && EnableVectorReboxing) {
3723       warning("Disabling EnableVectorReboxing since EnableVectorSupport is turned off.");
3724     }
3725     FLAG_SET_DEFAULT(EnableVectorReboxing, false);
3726 
3727     if (!FLAG_IS_DEFAULT(EnableVectorAggressiveReboxing) && EnableVectorAggressiveReboxing) {
3728       if (!EnableVectorReboxing) {
3729         warning("Disabling EnableVectorAggressiveReboxing since EnableVectorReboxing is turned off.");
3730       } else {
3731         warning("Disabling EnableVectorAggressiveReboxing since EnableVectorSupport is turned off.");
3732       }
3733     }
3734     FLAG_SET_DEFAULT(EnableVectorAggressiveReboxing, false);
3735 
3736     if (!FLAG_IS_DEFAULT(UseVectorStubs) && UseVectorStubs) {
3737       warning("Disabling UseVectorStubs since EnableVectorSupport is turned off.");
3738     }
3739     FLAG_SET_DEFAULT(UseVectorStubs, false);
3740   }
3741 #endif // COMPILER2_OR_JVMCI
3742 

























3743   if (FLAG_IS_CMDLINE(DiagnoseSyncOnValueBasedClasses)) {
3744     if (DiagnoseSyncOnValueBasedClasses == ObjectSynchronizer::LOG_WARNING && !log_is_enabled(Info, valuebasedclasses)) {
3745       LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(valuebasedclasses));
3746     }
3747   }
3748   return JNI_OK;
3749 }
3750 
3751 jint Arguments::adjust_after_os() {
3752   if (UseNUMA) {
3753     if (UseParallelGC) {
3754       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
3755          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
3756       }
3757     }
3758   }
3759   return JNI_OK;
3760 }
3761 
3762 int Arguments::PropertyList_count(SystemProperty* pl) {
3763   int count = 0;
3764   while(pl != nullptr) {
3765     count++;
3766     pl = pl->next();
3767   }
3768   return count;
3769 }
3770 
3771 // Return the number of readable properties.
3772 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
3773   int count = 0;
3774   while(pl != nullptr) {
3775     if (pl->readable()) {
3776       count++;
3777     }
3778     pl = pl->next();
3779   }
3780   return count;
3781 }
3782 
3783 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
3784   assert(key != nullptr, "just checking");
3785   SystemProperty* prop;
3786   for (prop = pl; prop != nullptr; prop = prop->next()) {
3787     if (strcmp(key, prop->key()) == 0) return prop->value();
3788   }
3789   return nullptr;
3790 }
3791 
3792 // Return the value of the requested property provided that it is a readable property.
3793 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
3794   assert(key != nullptr, "just checking");
3795   SystemProperty* prop;
3796   // Return the property value if the keys match and the property is not internal or
3797   // it's the special internal property "jdk.boot.class.path.append".
3798   for (prop = pl; prop != nullptr; prop = prop->next()) {
3799     if (strcmp(key, prop->key()) == 0) {
3800       if (!prop->internal()) {
3801         return prop->value();
3802       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
3803         return prop->value();
3804       } else {
3805         // Property is internal and not jdk.boot.class.path.append so return null.
3806         return nullptr;
3807       }
3808     }
3809   }
3810   return nullptr;
3811 }
3812 
3813 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
3814   SystemProperty* p = *plist;
3815   if (p == nullptr) {
3816     *plist = new_p;
3817   } else {
3818     while (p->next() != nullptr) {
3819       p = p->next();
3820     }
3821     p->set_next(new_p);
3822   }
3823 }
3824 
3825 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
3826                                  bool writeable, bool internal) {
3827   if (plist == nullptr)
3828     return;
3829 
3830   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
3831   PropertyList_add(plist, new_p);
3832 }
3833 
3834 void Arguments::PropertyList_add(SystemProperty *element) {
3835   PropertyList_add(&_system_properties, element);
3836 }
3837 
3838 // This add maintains unique property key in the list.
3839 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
3840                                         PropertyAppendable append, PropertyWriteable writeable,
3841                                         PropertyInternal internal) {
3842   if (plist == nullptr)
3843     return;
3844 
3845   // If property key exists and is writeable, then update with new value.
3846   // Trying to update a non-writeable property is silently ignored.
3847   SystemProperty* prop;
3848   for (prop = *plist; prop != nullptr; prop = prop->next()) {
3849     if (strcmp(k, prop->key()) == 0) {
3850       if (append == AppendProperty) {
3851         prop->append_writeable_value(v);
3852       } else {
3853         prop->set_writeable_value(v);
3854       }
3855       return;
3856     }
3857   }
3858 
3859   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
3860 }
3861 
3862 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
3863 // Returns true if all of the source pointed by src has been copied over to
3864 // the destination buffer pointed by buf. Otherwise, returns false.
3865 // Notes:
3866 // 1. If the length (buflen) of the destination buffer excluding the
3867 // null terminator character is not long enough for holding the expanded
3868 // pid characters, it also returns false instead of returning the partially
3869 // expanded one.
3870 // 2. The passed in "buflen" should be large enough to hold the null terminator.
3871 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
3872                                 char* buf, size_t buflen) {
3873   const char* p = src;
3874   char* b = buf;
3875   const char* src_end = &src[srclen];
3876   char* buf_end = &buf[buflen - 1];
3877 
3878   while (p < src_end && b < buf_end) {
3879     if (*p == '%') {
3880       switch (*(++p)) {
3881       case '%':         // "%%" ==> "%"
3882         *b++ = *p++;
3883         break;
3884       case 'p':  {       //  "%p" ==> current process id
3885         // buf_end points to the character before the last character so
3886         // that we could write '\0' to the end of the buffer.
3887         size_t buf_sz = buf_end - b + 1;
3888         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
3889 
3890         // if jio_snprintf fails or the buffer is not long enough to hold
3891         // the expanded pid, returns false.
3892         if (ret < 0 || ret >= (int)buf_sz) {
3893           return false;
3894         } else {
3895           b += ret;
3896           assert(*b == '\0', "fail in copy_expand_pid");
3897           if (p == src_end && b == buf_end + 1) {
3898             // reach the end of the buffer.
3899             return true;
3900           }
3901         }
3902         p++;
3903         break;
3904       }
3905       default :
3906         *b++ = '%';
3907       }
3908     } else {
3909       *b++ = *p++;
3910     }
3911   }
3912   *b = '\0';
3913   return (p == src_end); // return false if not all of the source was copied
3914 }
--- EOF ---