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