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