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