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