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