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