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