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