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