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