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