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