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