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