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   { "AggressiveHeap",               JDK_Version::jdk(26),  JDK_Version::jdk(27), JDK_Version::jdk(28) },
 540   { "NeverActAsServerClassMachine", JDK_Version::jdk(26),  JDK_Version::jdk(27), JDK_Version::jdk(28) },
 541   { "AlwaysActAsServerClassMachine", JDK_Version::jdk(26),  JDK_Version::jdk(27), JDK_Version::jdk(28) },
 542   // --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in:
 543   { "CreateMinidumpOnCrash",        JDK_Version::jdk(9),  JDK_Version::undefined(), JDK_Version::undefined() },
 544 
 545   // -------------- Obsolete Flags - sorted by expired_in --------------
 546 
 547   { "MetaspaceReclaimPolicy",       JDK_Version::undefined(), JDK_Version::jdk(21), JDK_Version::undefined() },
 548 #if defined(AARCH64)
 549   { "NearCpool",                    JDK_Version::undefined(), JDK_Version::jdk(25), JDK_Version::undefined() },
 550 #endif
 551 
 552   { "PSChunkLargeArrays",           JDK_Version::jdk(26),  JDK_Version::jdk(27), JDK_Version::jdk(28) },
 553   { "ParallelRefProcEnabled",       JDK_Version::jdk(26),  JDK_Version::jdk(27), JDK_Version::jdk(28) },
 554   { "ParallelRefProcBalancingEnabled", JDK_Version::jdk(26),  JDK_Version::jdk(27), JDK_Version::jdk(28) },
 555   { "MaxRAM",                       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 
1515   // Limit the available memory if client emulation mode is enabled.
1516   const size_t avail_mem = CompilerConfig::should_set_client_emulation_mode_flags()
1517       ? 1ULL*G
1518       : os::physical_memory();
1519 
1520   // If the maximum heap size has not been set with -Xmx, then set it as
1521   // fraction of the size of physical memory, respecting the maximum and
1522   // minimum sizes of the heap.
1523   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1524     uint64_t min_memory = (uint64_t)(((double)avail_mem * MinRAMPercentage) / 100);
1525     uint64_t max_memory = (uint64_t)(((double)avail_mem * MaxRAMPercentage) / 100);
1526 
1527     const size_t reasonable_min = clamp_by_size_t_max(min_memory);
1528     size_t reasonable_max = clamp_by_size_t_max(max_memory);
1529 
1530     if (reasonable_min < MaxHeapSize) {
1531       // Small physical memory, so use a minimum fraction of it for the heap
1532       reasonable_max = reasonable_min;
1533     } else {
1534       // Not-small physical memory, so require a heap at least
1535       // as large as MaxHeapSize
1536       reasonable_max = MAX2(reasonable_max, MaxHeapSize);
1537     }
1538 
1539     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1540       // Limit the heap size to ErgoHeapSizeLimit
1541       reasonable_max = MIN2(reasonable_max, ErgoHeapSizeLimit);
1542     }
1543 
1544     reasonable_max = limit_heap_by_allocatable_memory(reasonable_max);
1545 
1546     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1547       // An initial heap size was specified on the command line,
1548       // so be sure that the maximum size is consistent.  Done
1549       // after call to limit_heap_by_allocatable_memory because that
1550       // method might reduce the allocation size.
1551       reasonable_max = MAX2(reasonable_max, InitialHeapSize);
1552     } else if (!FLAG_IS_DEFAULT(MinHeapSize)) {
1553       reasonable_max = MAX2(reasonable_max, MinHeapSize);
1554     }
1555 
1556 #ifdef _LP64
1557     if (UseCompressedOops || UseCompressedClassPointers) {
1558       // HeapBaseMinAddress can be greater than default but not less than.
1559       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1560         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1561           // matches compressed oops printing flags
1562           log_debug(gc, heap, coops)("HeapBaseMinAddress must be at least %zu "
1563                                      "(%zuG) which is greater than value given %zu",
1564                                      DefaultHeapBaseMinAddress,
1565                                      DefaultHeapBaseMinAddress/G,
1566                                      HeapBaseMinAddress);
1567           FLAG_SET_ERGO(HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1568         }
1569       }
1570     }
1571 
1572     if (UseCompressedOops) {
1573       uintptr_t heap_end = HeapBaseMinAddress + MaxHeapSize;
1574       uintptr_t max_coop_heap = max_heap_for_compressed_oops();
1575 
1576       // Limit the heap size to the maximum possible when using compressed oops
1577       if (heap_end < max_coop_heap) {
1578         // Heap should be above HeapBaseMinAddress to get zero based compressed
1579         // oops but it should be not less than default MaxHeapSize.
1580         max_coop_heap -= HeapBaseMinAddress;
1581       }
1582 
1583       // If the user has configured any limit on the amount of RAM we may use,
1584       // then disable compressed oops if the calculated max exceeds max_coop_heap
1585       // and UseCompressedOops was not specified.
1586       if (reasonable_max > max_coop_heap) {
1587         if (FLAG_IS_ERGO(UseCompressedOops) && has_ram_limit) {
1588           log_debug(gc, heap, coops)("UseCompressedOops disabled due to "
1589                                      "max heap %zu > compressed oop heap %zu. "
1590                                      "Please check the setting of MaxRAMPercentage %5.2f.",
1591                                      reasonable_max, (size_t)max_coop_heap, MaxRAMPercentage);
1592           FLAG_SET_ERGO(UseCompressedOops, false);
1593         } else {
1594           reasonable_max = max_coop_heap;
1595         }
1596       }
1597     }
1598 #endif // _LP64
1599 
1600     log_trace(gc, heap)("  Maximum heap size %zu", reasonable_max);
1601     FLAG_SET_ERGO(MaxHeapSize, reasonable_max);
1602   }
1603 
1604   // If the minimum or initial heap_size have not been set or requested to be set
1605   // ergonomically, set them accordingly.
1606   if (InitialHeapSize == 0 || MinHeapSize == 0) {
1607     size_t reasonable_minimum = clamp_by_size_t_max((uint64_t)OldSize + (uint64_t)NewSize);
1608     reasonable_minimum = MIN2(reasonable_minimum, MaxHeapSize);
1609     reasonable_minimum = limit_heap_by_allocatable_memory(reasonable_minimum);
1610 
1611     if (InitialHeapSize == 0) {
1612       uint64_t initial_memory = (uint64_t)(((double)avail_mem * InitialRAMPercentage) / 100);
1613       size_t reasonable_initial = clamp_by_size_t_max(initial_memory);
1614       reasonable_initial = limit_heap_by_allocatable_memory(reasonable_initial);
1615 
1616       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, MinHeapSize);
1617       reasonable_initial = MIN2(reasonable_initial, MaxHeapSize);
1618 
1619       FLAG_SET_ERGO(InitialHeapSize, (size_t)reasonable_initial);
1620       log_trace(gc, heap)("  Initial heap size %zu", InitialHeapSize);
1621     }
1622 
1623     // If the minimum heap size has not been set (via -Xms or -XX:MinHeapSize),
1624     // synchronize with InitialHeapSize to avoid errors with the default value.
1625     if (MinHeapSize == 0) {
1626       FLAG_SET_ERGO(MinHeapSize, MIN2(reasonable_minimum, InitialHeapSize));
1627       log_trace(gc, heap)("  Minimum heap size %zu", MinHeapSize);
1628     }
1629   }
1630 }
1631 
1632 // This option inspects the machine and attempts to set various
1633 // parameters to be optimal for long-running, memory allocation
1634 // intensive jobs.  It is intended for machines with large
1635 // amounts of cpu and memory.
1636 jint Arguments::set_aggressive_heap_flags() {
1637   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
1638   // VM, but we may not be able to represent the total physical memory
1639   // available (like having 8gb of memory on a box but using a 32bit VM).
1640   // Thus, we need to make sure we're using a julong for intermediate
1641   // calculations.
1642   julong initHeapSize;
1643   physical_memory_size_type phys_mem = os::physical_memory();
1644   julong total_memory = static_cast<julong>(phys_mem);
1645 
1646   if (total_memory < (julong) 256 * M) {
1647     jio_fprintf(defaultStream::error_stream(),
1648             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
1649     vm_exit(1);
1650   }
1651 
1652   // The heap size is half of available memory, or (at most)
1653   // all of possible memory less 160mb (leaving room for the OS
1654   // when using ISM).  This is the maximum; because adaptive sizing
1655   // is turned on below, the actual space used may be smaller.
1656 
1657   initHeapSize = MIN2(total_memory / (julong) 2,
1658           total_memory - (julong) 160 * M);
1659 
1660   initHeapSize = limit_heap_by_allocatable_memory(initHeapSize);
1661 
1662   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1663     if (FLAG_SET_CMDLINE(MaxHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1664       return JNI_EINVAL;
1665     }
1666     if (FLAG_SET_CMDLINE(InitialHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1667       return JNI_EINVAL;
1668     }
1669     if (FLAG_SET_CMDLINE(MinHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1670       return JNI_EINVAL;
1671     }
1672   }
1673   if (FLAG_IS_DEFAULT(NewSize)) {
1674     // Make the young generation 3/8ths of the total heap.
1675     if (FLAG_SET_CMDLINE(NewSize,
1676             ((julong) MaxHeapSize / (julong) 8) * (julong) 3) != JVMFlag::SUCCESS) {
1677       return JNI_EINVAL;
1678     }
1679     if (FLAG_SET_CMDLINE(MaxNewSize, NewSize) != JVMFlag::SUCCESS) {
1680       return JNI_EINVAL;
1681     }
1682   }
1683 
1684 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
1685   FLAG_SET_DEFAULT(UseLargePages, true);
1686 #endif
1687 
1688   // Increase some data structure sizes for efficiency
1689   if (FLAG_SET_CMDLINE(ResizeTLAB, false) != JVMFlag::SUCCESS) {
1690     return JNI_EINVAL;
1691   }
1692   if (FLAG_SET_CMDLINE(TLABSize, 256 * K) != JVMFlag::SUCCESS) {
1693     return JNI_EINVAL;
1694   }
1695 
1696   // See the OldPLABSize comment below, but replace 'after promotion'
1697   // with 'after copying'.  YoungPLABSize is the size of the survivor
1698   // space per-gc-thread buffers.  The default is 4kw.
1699   if (FLAG_SET_CMDLINE(YoungPLABSize, 256 * K) != JVMFlag::SUCCESS) { // Note: this is in words
1700     return JNI_EINVAL;
1701   }
1702 
1703   // OldPLABSize is the size of the buffers in the old gen that
1704   // UseParallelGC uses to promote live data that doesn't fit in the
1705   // survivor spaces.  At any given time, there's one for each gc thread.
1706   // The default size is 1kw. These buffers are rarely used, since the
1707   // survivor spaces are usually big enough.  For specjbb, however, there
1708   // are occasions when there's lots of live data in the young gen
1709   // and we end up promoting some of it.  We don't have a definite
1710   // explanation for why bumping OldPLABSize helps, but the theory
1711   // is that a bigger PLAB results in retaining something like the
1712   // original allocation order after promotion, which improves mutator
1713   // locality.  A minor effect may be that larger PLABs reduce the
1714   // number of PLAB allocation events during gc.  The value of 8kw
1715   // was arrived at by experimenting with specjbb.
1716   if (FLAG_SET_CMDLINE(OldPLABSize, 8 * K) != JVMFlag::SUCCESS) { // Note: this is in words
1717     return JNI_EINVAL;
1718   }
1719 
1720   // Enable parallel GC and adaptive generation sizing
1721   if (FLAG_SET_CMDLINE(UseParallelGC, true) != JVMFlag::SUCCESS) {
1722     return JNI_EINVAL;
1723   }
1724 
1725   // Encourage steady state memory management
1726   if (FLAG_SET_CMDLINE(ThresholdTolerance, 100) != JVMFlag::SUCCESS) {
1727     return JNI_EINVAL;
1728   }
1729 
1730   return JNI_OK;
1731 }
1732 
1733 // This must be called after ergonomics.
1734 void Arguments::set_bytecode_flags() {
1735   if (!RewriteBytecodes) {
1736     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1737   }
1738 }
1739 
1740 // Aggressive optimization flags
1741 jint Arguments::set_aggressive_opts_flags() {
1742 #ifdef COMPILER2
1743   if (AggressiveUnboxing) {
1744     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1745       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1746     } else if (!EliminateAutoBox) {
1747       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
1748       AggressiveUnboxing = false;
1749     }
1750     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1751       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1752     } else if (!DoEscapeAnalysis) {
1753       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
1754       AggressiveUnboxing = false;
1755     }
1756   }
1757   if (!FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1758     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1759       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1760     }
1761     // Feed the cache size setting into the JDK
1762     char buffer[1024];
1763     jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=%zd", AutoBoxCacheMax);
1764     if (!add_property(buffer)) {
1765       return JNI_ENOMEM;
1766     }
1767   }
1768 #endif
1769 
1770   return JNI_OK;
1771 }
1772 
1773 //===========================================================================================================
1774 
1775 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1776   if (_sun_java_launcher != _default_java_launcher) {
1777     os::free(const_cast<char*>(_sun_java_launcher));
1778   }
1779   _sun_java_launcher = os::strdup_check_oom(launcher);
1780 }
1781 
1782 bool Arguments::created_by_java_launcher() {
1783   assert(_sun_java_launcher != nullptr, "property must have value");
1784   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1785 }
1786 
1787 bool Arguments::executing_unit_tests() {
1788   return _executing_unit_tests;
1789 }
1790 
1791 //===========================================================================================================
1792 // Parsing of main arguments
1793 
1794 static unsigned int addreads_count = 0;
1795 static unsigned int addexports_count = 0;
1796 static unsigned int addopens_count = 0;
1797 static unsigned int patch_mod_count = 0;
1798 static unsigned int enable_native_access_count = 0;
1799 static unsigned int enable_final_field_mutation = 0;
1800 static bool patch_mod_javabase = false;
1801 
1802 // Check the consistency of vm_init_args
1803 bool Arguments::check_vm_args_consistency() {
1804   // This may modify compiler flags. Must be called before CompilerConfig::check_args_consistency()
1805   if (!CDSConfig::check_vm_args_consistency(patch_mod_javabase, mode_flag_cmd_line)) {
1806     return false;
1807   }
1808 
1809   // Method for adding checks for flag consistency.
1810   // The intent is to warn the user of all possible conflicts,
1811   // before returning an error.
1812   // Note: Needs platform-dependent factoring.
1813   bool status = true;
1814 
1815   if (TLABRefillWasteFraction == 0) {
1816     jio_fprintf(defaultStream::error_stream(),
1817                 "TLABRefillWasteFraction should be a denominator, "
1818                 "not %zu\n",
1819                 TLABRefillWasteFraction);
1820     status = false;
1821   }
1822 
1823   status = CompilerConfig::check_args_consistency(status);
1824 #if INCLUDE_JVMCI
1825   if (status && EnableJVMCI) {
1826     // Add the JVMCI module if not using libjvmci or EnableJVMCI
1827     // was explicitly set on the command line or in the jimage.
1828     if ((!UseJVMCINativeLibrary || FLAG_IS_CMDLINE(EnableJVMCI) || FLAG_IS_JIMAGE_RESOURCE(EnableJVMCI)) && ClassLoader::is_module_observable("jdk.internal.vm.ci") && !_jvmci_module_added) {
1829       if (!create_numbered_module_property("jdk.module.addmods", "jdk.internal.vm.ci", _addmods_count++)) {
1830         return false;
1831       }
1832     }
1833   }
1834 #endif
1835 
1836 #if INCLUDE_JFR
1837   if (status && (FlightRecorderOptions || StartFlightRecording)) {
1838     if (!create_numbered_module_property("jdk.module.addmods", "jdk.jfr", _addmods_count++)) {
1839       return false;
1840     }
1841   }
1842 #endif
1843 
1844 #ifndef SUPPORT_RESERVED_STACK_AREA
1845   if (StackReservedPages != 0) {
1846     FLAG_SET_CMDLINE(StackReservedPages, 0);
1847     warning("Reserved Stack Area not supported on this platform");
1848   }
1849 #endif
1850 
1851   return status;
1852 }
1853 
1854 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
1855   const char* option_type) {
1856   if (ignore) return false;
1857 
1858   const char* spacer = " ";
1859   if (option_type == nullptr) {
1860     option_type = ++spacer; // Set both to the empty string.
1861   }
1862 
1863   jio_fprintf(defaultStream::error_stream(),
1864               "Unrecognized %s%soption: %s\n", option_type, spacer,
1865               option->optionString);
1866   return true;
1867 }
1868 
1869 static const char* user_assertion_options[] = {
1870   "-da", "-ea", "-disableassertions", "-enableassertions", nullptr
1871 };
1872 
1873 static const char* system_assertion_options[] = {
1874   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", nullptr
1875 };
1876 
1877 bool Arguments::parse_uint(const char* value,
1878                            uint* uint_arg,
1879                            uint min_size) {
1880   uint n;
1881   if (!parse_integer(value, &n)) {
1882     return false;
1883   }
1884   if (n >= min_size) {
1885     *uint_arg = n;
1886     return true;
1887   } else {
1888     return false;
1889   }
1890 }
1891 
1892 bool Arguments::create_module_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
1893   assert(is_internal_module_property(prop_name), "unknown module property: '%s'", prop_name);
1894   CDSConfig::check_internal_module_property(prop_name, prop_value);
1895   size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
1896   char* property = AllocateHeap(prop_len, mtArguments);
1897   int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);
1898   if (ret < 0 || ret >= (int)prop_len) {
1899     FreeHeap(property);
1900     return false;
1901   }
1902   // These are not strictly writeable properties as they cannot be set via -Dprop=val. But that
1903   // is enforced by checking is_internal_module_property(). We need the property to be writeable so
1904   // that multiple occurrences of the associated flag just causes the existing property value to be
1905   // replaced ("last option wins"). Otherwise we would need to keep track of the flags and only convert
1906   // to a property after we have finished flag processing.
1907   bool added = add_property(property, WriteableProperty, internal);
1908   FreeHeap(property);
1909   return added;
1910 }
1911 
1912 bool Arguments::create_numbered_module_property(const char* prop_base_name, const char* prop_value, unsigned int count) {
1913   assert(is_internal_module_property(prop_base_name), "unknown module property: '%s'", prop_base_name);
1914   CDSConfig::check_internal_module_property(prop_base_name, prop_value);
1915   const unsigned int props_count_limit = 1000;
1916   const int max_digits = 3;
1917   const int extra_symbols_count = 3; // includes '.', '=', '\0'
1918 
1919   // Make sure count is < props_count_limit. Otherwise, memory allocation will be too small.
1920   if (count < props_count_limit) {
1921     size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + max_digits + extra_symbols_count;
1922     char* property = AllocateHeap(prop_len, mtArguments);
1923     int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);
1924     if (ret < 0 || ret >= (int)prop_len) {
1925       FreeHeap(property);
1926       jio_fprintf(defaultStream::error_stream(), "Failed to create property %s.%d=%s\n", prop_base_name, count, prop_value);
1927       return false;
1928     }
1929     bool added = add_property(property, UnwriteableProperty, InternalProperty);
1930     FreeHeap(property);
1931     return added;
1932   }
1933 
1934   jio_fprintf(defaultStream::error_stream(), "Property count limit exceeded: %s, limit=%d\n", prop_base_name, props_count_limit);
1935   return false;
1936 }
1937 
1938 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
1939                                                   julong* long_arg,
1940                                                   julong min_size,
1941                                                   julong max_size) {
1942   if (!parse_integer(s, long_arg)) return arg_unreadable;
1943   return check_memory_size(*long_arg, min_size, max_size);
1944 }
1945 
1946 jint Arguments::parse_vm_init_args(GrowableArrayCHeap<VMInitArgsGroup, mtArguments>* all_args) {
1947   // Save default settings for some mode flags
1948   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
1949   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
1950   Arguments::_ClipInlining             = ClipInlining;
1951   Arguments::_BackgroundCompilation    = BackgroundCompilation;
1952 
1953   // Remember the default value of SharedBaseAddress.
1954   Arguments::_default_SharedBaseAddress = SharedBaseAddress;
1955 
1956   // Setup flags for mixed which is the default
1957   set_mode_flags(_mixed);
1958 
1959   jint result;
1960   for (int i = 0; i < all_args->length(); i++) {
1961     result = parse_each_vm_init_arg(all_args->at(i)._args, all_args->at(i)._origin);
1962     if (result != JNI_OK) {
1963       return result;
1964     }
1965   }
1966 
1967   // Disable CDS for exploded image
1968   if (!has_jimage()) {
1969     no_shared_spaces("CDS disabled on exploded JDK");
1970   }
1971 
1972   // We need to ensure processor and memory resources have been properly
1973   // configured - which may rely on arguments we just processed - before
1974   // doing the final argument processing. Any argument processing that
1975   // needs to know about processor and memory resources must occur after
1976   // this point.
1977 
1978   os::init_container_support();
1979 
1980   SystemMemoryBarrier::initialize();
1981 
1982   // Do final processing now that all arguments have been parsed
1983   result = finalize_vm_init_args();
1984   if (result != JNI_OK) {
1985     return result;
1986   }
1987 
1988   return JNI_OK;
1989 }
1990 
1991 #if !INCLUDE_JVMTI || INCLUDE_CDS
1992 // Checks if name in command-line argument -agent{lib,path}:name[=options]
1993 // represents a valid JDWP agent.  is_path==true denotes that we
1994 // are dealing with -agentpath (case where name is a path), otherwise with
1995 // -agentlib
1996 static bool valid_jdwp_agent(char *name, bool is_path) {
1997   char *_name;
1998   const char *_jdwp = "jdwp";
1999   size_t _len_jdwp, _len_prefix;
2000 
2001   if (is_path) {
2002     if ((_name = strrchr(name, (int) *os::file_separator())) == nullptr) {
2003       return false;
2004     }
2005 
2006     _name++;  // skip past last path separator
2007     _len_prefix = strlen(JNI_LIB_PREFIX);
2008 
2009     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2010       return false;
2011     }
2012 
2013     _name += _len_prefix;
2014     _len_jdwp = strlen(_jdwp);
2015 
2016     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2017       _name += _len_jdwp;
2018     }
2019     else {
2020       return false;
2021     }
2022 
2023     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2024       return false;
2025     }
2026 
2027     return true;
2028   }
2029 
2030   if (strcmp(name, _jdwp) == 0) {
2031     return true;
2032   }
2033 
2034   return false;
2035 }
2036 #endif
2037 
2038 int Arguments::process_patch_mod_option(const char* patch_mod_tail) {
2039   // --patch-module=<module>=<file>(<pathsep><file>)*
2040   assert(patch_mod_tail != nullptr, "Unexpected null patch-module value");
2041   // Find the equal sign between the module name and the path specification
2042   const char* module_equal = strchr(patch_mod_tail, '=');
2043   if (module_equal == nullptr) {
2044     jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");
2045     return JNI_ERR;
2046   } else {
2047     // Pick out the module name
2048     size_t module_len = module_equal - patch_mod_tail;
2049     char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);
2050     if (module_name != nullptr) {
2051       memcpy(module_name, patch_mod_tail, module_len);
2052       *(module_name + module_len) = '\0';
2053       // The path piece begins one past the module_equal sign
2054       add_patch_mod_prefix(module_name, module_equal + 1);
2055       FREE_C_HEAP_ARRAY(char, module_name);
2056       if (!create_numbered_module_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {
2057         return JNI_ENOMEM;
2058       }
2059     } else {
2060       return JNI_ENOMEM;
2061     }
2062   }
2063   return JNI_OK;
2064 }
2065 
2066 // Parse -Xss memory string parameter and convert to ThreadStackSize in K.
2067 jint Arguments::parse_xss(const JavaVMOption* option, const char* tail, intx* out_ThreadStackSize) {
2068   // The min and max sizes match the values in globals.hpp, but scaled
2069   // with K. The values have been chosen so that alignment with page
2070   // size doesn't change the max value, which makes the conversions
2071   // back and forth between Xss value and ThreadStackSize value easier.
2072   // The values have also been chosen to fit inside a 32-bit signed type.
2073   const julong min_ThreadStackSize = 0;
2074   const julong max_ThreadStackSize = 1 * M;
2075 
2076   // Make sure the above values match the range set in globals.hpp
2077   const JVMTypedFlagLimit<intx>* limit = JVMFlagLimit::get_range_at(FLAG_MEMBER_ENUM(ThreadStackSize))->cast<intx>();
2078   assert(min_ThreadStackSize == static_cast<julong>(limit->min()), "must be");
2079   assert(max_ThreadStackSize == static_cast<julong>(limit->max()), "must be");
2080 
2081   const julong min_size = min_ThreadStackSize * K;
2082   const julong max_size = max_ThreadStackSize * K;
2083 
2084   assert(is_aligned(max_size, os::vm_page_size()), "Implementation assumption");
2085 
2086   julong size = 0;
2087   ArgsRange errcode = parse_memory_size(tail, &size, min_size, max_size);
2088   if (errcode != arg_in_range) {
2089     bool silent = (option == nullptr); // Allow testing to silence error messages
2090     if (!silent) {
2091       jio_fprintf(defaultStream::error_stream(),
2092                   "Invalid thread stack size: %s\n", option->optionString);
2093       describe_range_error(errcode);
2094     }
2095     return JNI_EINVAL;
2096   }
2097 
2098   // Internally track ThreadStackSize in units of 1024 bytes.
2099   const julong size_aligned = align_up(size, K);
2100   assert(size <= size_aligned,
2101          "Overflow: " JULONG_FORMAT " " JULONG_FORMAT,
2102          size, size_aligned);
2103 
2104   const julong size_in_K = size_aligned / K;
2105   assert(size_in_K < (julong)max_intx,
2106          "size_in_K doesn't fit in the type of ThreadStackSize: " JULONG_FORMAT,
2107          size_in_K);
2108 
2109   // Check that code expanding ThreadStackSize to a page aligned number of bytes won't overflow.
2110   const julong max_expanded = align_up(size_in_K * K, os::vm_page_size());
2111   assert(max_expanded < max_uintx && max_expanded >= size_in_K,
2112          "Expansion overflowed: " JULONG_FORMAT " " JULONG_FORMAT,
2113          max_expanded, size_in_K);
2114 
2115   *out_ThreadStackSize = (intx)size_in_K;
2116 
2117   return JNI_OK;
2118 }
2119 
2120 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, JVMFlagOrigin origin) {
2121   // For match_option to return remaining or value part of option string
2122   const char* tail;
2123 
2124   // iterate over arguments
2125   for (int index = 0; index < args->nOptions; index++) {
2126     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2127 
2128     const JavaVMOption* option = args->options + index;
2129 
2130     if (!match_option(option, "-Djava.class.path", &tail) &&
2131         !match_option(option, "-Dsun.java.command", &tail) &&
2132         !match_option(option, "-Dsun.java.launcher", &tail)) {
2133 
2134         // add all jvm options to the jvm_args string. This string
2135         // is used later to set the java.vm.args PerfData string constant.
2136         // the -Djava.class.path and the -Dsun.java.command options are
2137         // omitted from jvm_args string as each have their own PerfData
2138         // string constant object.
2139         build_jvm_args(option->optionString);
2140     }
2141 
2142     // -verbose:[class/module/gc/jni]
2143     if (match_option(option, "-verbose", &tail)) {
2144       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2145         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));
2146         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));
2147       } else if (!strcmp(tail, ":module")) {
2148         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, load));
2149         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, unload));
2150       } else if (!strcmp(tail, ":gc")) {
2151         if (_legacyGCLogging.lastFlag == 0) {
2152           _legacyGCLogging.lastFlag = 1;
2153         }
2154       } else if (!strcmp(tail, ":jni")) {
2155         LogConfiguration::configure_stdout(LogLevel::Debug, true, LOG_TAGS(jni, resolve));
2156       }
2157     // -da / -ea / -disableassertions / -enableassertions
2158     // These accept an optional class/package name separated by a colon, e.g.,
2159     // -da:java.lang.Thread.
2160     } else if (match_option(option, user_assertion_options, &tail, true)) {
2161       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2162       if (*tail == '\0') {
2163         JavaAssertions::setUserClassDefault(enable);
2164       } else {
2165         assert(*tail == ':', "bogus match by match_option()");
2166         JavaAssertions::addOption(tail + 1, enable);
2167       }
2168     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2169     } else if (match_option(option, system_assertion_options, &tail, false)) {
2170       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2171       JavaAssertions::setSystemClassDefault(enable);
2172     // -bootclasspath:
2173     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2174         jio_fprintf(defaultStream::output_stream(),
2175           "-Xbootclasspath is no longer a supported option.\n");
2176         return JNI_EINVAL;
2177     // -bootclasspath/a:
2178     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2179       Arguments::append_sysclasspath(tail);
2180     // -bootclasspath/p:
2181     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2182         jio_fprintf(defaultStream::output_stream(),
2183           "-Xbootclasspath/p is no longer a supported option.\n");
2184         return JNI_EINVAL;
2185     // -Xrun
2186     } else if (match_option(option, "-Xrun", &tail)) {
2187       if (tail != nullptr) {
2188         const char* pos = strchr(tail, ':');
2189         size_t len = (pos == nullptr) ? strlen(tail) : pos - tail;
2190         char* name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2191         jio_snprintf(name, len + 1, "%s", tail);
2192 
2193         char *options = nullptr;
2194         if(pos != nullptr) {
2195           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2196           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);
2197         }
2198 #if !INCLUDE_JVMTI
2199         if (strcmp(name, "jdwp") == 0) {
2200           jio_fprintf(defaultStream::error_stream(),
2201             "Debugging agents are not supported in this VM\n");
2202           return JNI_ERR;
2203         }
2204 #endif // !INCLUDE_JVMTI
2205         JvmtiAgentList::add_xrun(name, options, false);
2206         FREE_C_HEAP_ARRAY(char, name);
2207         FREE_C_HEAP_ARRAY(char, options);
2208       }
2209     } else if (match_option(option, "--add-reads=", &tail)) {
2210       if (!create_numbered_module_property("jdk.module.addreads", tail, addreads_count++)) {
2211         return JNI_ENOMEM;
2212       }
2213     } else if (match_option(option, "--add-exports=", &tail)) {
2214       if (!create_numbered_module_property("jdk.module.addexports", tail, addexports_count++)) {
2215         return JNI_ENOMEM;
2216       }
2217     } else if (match_option(option, "--add-opens=", &tail)) {
2218       if (!create_numbered_module_property("jdk.module.addopens", tail, addopens_count++)) {
2219         return JNI_ENOMEM;
2220       }
2221     } else if (match_option(option, "--add-modules=", &tail)) {
2222       if (!create_numbered_module_property("jdk.module.addmods", tail, _addmods_count++)) {
2223         return JNI_ENOMEM;
2224       }
2225 #if INCLUDE_JVMCI
2226       if (!_jvmci_module_added) {
2227         const char *jvmci_module = strstr(tail, "jdk.internal.vm.ci");
2228         if (jvmci_module != nullptr) {
2229           char before = *(jvmci_module - 1);
2230           char after  = *(jvmci_module + strlen("jdk.internal.vm.ci"));
2231           if ((before == '=' || before == ',') && (after == '\0' || after == ',')) {
2232             FLAG_SET_DEFAULT(EnableJVMCI, true);
2233             _jvmci_module_added = true;
2234           }
2235         }
2236       }
2237 #endif
2238     } else if (match_option(option, "--enable-native-access=", &tail)) {
2239       if (!create_numbered_module_property("jdk.module.enable.native.access", tail, enable_native_access_count++)) {
2240         return JNI_ENOMEM;
2241       }
2242     } else if (match_option(option, "--illegal-native-access=", &tail)) {
2243       if (!create_module_property("jdk.module.illegal.native.access", tail, InternalProperty)) {
2244         return JNI_ENOMEM;
2245       }
2246     } else if (match_option(option, "--limit-modules=", &tail)) {
2247       if (!create_module_property("jdk.module.limitmods", tail, InternalProperty)) {
2248         return JNI_ENOMEM;
2249       }
2250     } else if (match_option(option, "--module-path=", &tail)) {
2251       if (!create_module_property("jdk.module.path", tail, ExternalProperty)) {
2252         return JNI_ENOMEM;
2253       }
2254     } else if (match_option(option, "--upgrade-module-path=", &tail)) {
2255       if (!create_module_property("jdk.module.upgrade.path", tail, ExternalProperty)) {
2256         return JNI_ENOMEM;
2257       }
2258     } else if (match_option(option, "--patch-module=", &tail)) {
2259       // --patch-module=<module>=<file>(<pathsep><file>)*
2260       int res = process_patch_mod_option(tail);
2261       if (res != JNI_OK) {
2262         return res;
2263       }
2264     } else if (match_option(option, "--enable-final-field-mutation=", &tail)) {
2265       if (!create_numbered_module_property("jdk.module.enable.final.field.mutation", tail, enable_final_field_mutation++)) {
2266         return JNI_ENOMEM;
2267       }
2268     } else if (match_option(option, "--illegal-final-field-mutation=", &tail)) {
2269       if (strcmp(tail, "allow") == 0 || strcmp(tail, "warn") == 0 || strcmp(tail, "debug") == 0 || strcmp(tail, "deny") == 0) {
2270         PropertyList_unique_add(&_system_properties, "jdk.module.illegal.final.field.mutation", tail,
2271                                 AddProperty, WriteableProperty, InternalProperty);
2272       } else {
2273         jio_fprintf(defaultStream::error_stream(),
2274                     "Value specified to --illegal-final-field-mutation not recognized: '%s'\n", tail);
2275         return JNI_ERR;
2276       }
2277     } else if (match_option(option, "--sun-misc-unsafe-memory-access=", &tail)) {
2278       if (strcmp(tail, "allow") == 0 || strcmp(tail, "warn") == 0 || strcmp(tail, "debug") == 0 || strcmp(tail, "deny") == 0) {
2279         PropertyList_unique_add(&_system_properties, "sun.misc.unsafe.memory.access", tail,
2280                                 AddProperty, WriteableProperty, InternalProperty);
2281       } else {
2282         jio_fprintf(defaultStream::error_stream(),
2283                     "Value specified to --sun-misc-unsafe-memory-access not recognized: '%s'\n", tail);
2284         return JNI_ERR;
2285       }
2286     } else if (match_option(option, "--illegal-access=", &tail)) {
2287       char version[256];
2288       JDK_Version::jdk(17).to_string(version, sizeof(version));
2289       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2290     // -agentlib and -agentpath
2291     } else if (match_option(option, "-agentlib:", &tail) ||
2292           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2293       if(tail != nullptr) {
2294         const char* pos = strchr(tail, '=');
2295         char* name;
2296         if (pos == nullptr) {
2297           name = os::strdup_check_oom(tail, mtArguments);
2298         } else {
2299           size_t len = pos - tail;
2300           name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2301           memcpy(name, tail, len);
2302           name[len] = '\0';
2303         }
2304 
2305         char *options = nullptr;
2306         if(pos != nullptr) {
2307           options = os::strdup_check_oom(pos + 1, mtArguments);
2308         }
2309 #if !INCLUDE_JVMTI
2310         if (valid_jdwp_agent(name, is_absolute_path)) {
2311           jio_fprintf(defaultStream::error_stream(),
2312             "Debugging agents are not supported in this VM\n");
2313           return JNI_ERR;
2314         }
2315 #elif INCLUDE_CDS
2316         if (valid_jdwp_agent(name, is_absolute_path)) {
2317           _has_jdwp_agent = true;
2318         }
2319 #endif // !INCLUDE_JVMTI
2320         JvmtiAgentList::add(name, options, is_absolute_path);
2321         os::free(name);
2322         os::free(options);
2323       }
2324     // -javaagent
2325     } else if (match_option(option, "-javaagent:", &tail)) {
2326 #if !INCLUDE_JVMTI
2327       jio_fprintf(defaultStream::error_stream(),
2328         "Instrumentation agents are not supported in this VM\n");
2329       return JNI_ERR;
2330 #else
2331       if (tail != nullptr) {
2332         size_t length = strlen(tail) + 1;
2333         char *options = NEW_C_HEAP_ARRAY(char, length, mtArguments);
2334         jio_snprintf(options, length, "%s", tail);
2335         JvmtiAgentList::add("instrument", options, false);
2336         FREE_C_HEAP_ARRAY(char, options);
2337 
2338         // java agents need module java.instrument
2339         if (!create_numbered_module_property("jdk.module.addmods", "java.instrument", _addmods_count++)) {
2340           return JNI_ENOMEM;
2341         }
2342       }
2343 #endif // !INCLUDE_JVMTI
2344     // --enable_preview
2345     } else if (match_option(option, "--enable-preview")) {
2346       set_enable_preview();
2347     // -Xnoclassgc
2348     } else if (match_option(option, "-Xnoclassgc")) {
2349       if (FLAG_SET_CMDLINE(ClassUnloading, false) != JVMFlag::SUCCESS) {
2350         return JNI_EINVAL;
2351       }
2352     // -Xbatch
2353     } else if (match_option(option, "-Xbatch")) {
2354       if (FLAG_SET_CMDLINE(BackgroundCompilation, false) != JVMFlag::SUCCESS) {
2355         return JNI_EINVAL;
2356       }
2357     // -Xmn for compatibility with other JVM vendors
2358     } else if (match_option(option, "-Xmn", &tail)) {
2359       julong long_initial_young_size = 0;
2360       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2361       if (errcode != arg_in_range) {
2362         jio_fprintf(defaultStream::error_stream(),
2363                     "Invalid initial young generation size: %s\n", option->optionString);
2364         describe_range_error(errcode);
2365         return JNI_EINVAL;
2366       }
2367       if (FLAG_SET_CMDLINE(MaxNewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {
2368         return JNI_EINVAL;
2369       }
2370       if (FLAG_SET_CMDLINE(NewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {
2371         return JNI_EINVAL;
2372       }
2373     // -Xms
2374     } else if (match_option(option, "-Xms", &tail)) {
2375       julong size = 0;
2376       // an initial heap size of 0 means automatically determine
2377       ArgsRange errcode = parse_memory_size(tail, &size, 0);
2378       if (errcode != arg_in_range) {
2379         jio_fprintf(defaultStream::error_stream(),
2380                     "Invalid initial heap size: %s\n", option->optionString);
2381         describe_range_error(errcode);
2382         return JNI_EINVAL;
2383       }
2384       if (FLAG_SET_CMDLINE(MinHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
2385         return JNI_EINVAL;
2386       }
2387       if (FLAG_SET_CMDLINE(InitialHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
2388         return JNI_EINVAL;
2389       }
2390     // -Xmx
2391     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2392       julong long_max_heap_size = 0;
2393       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2394       if (errcode != arg_in_range) {
2395         jio_fprintf(defaultStream::error_stream(),
2396                     "Invalid maximum heap size: %s\n", option->optionString);
2397         describe_range_error(errcode);
2398         return JNI_EINVAL;
2399       }
2400       if (FLAG_SET_CMDLINE(MaxHeapSize, (size_t)long_max_heap_size) != JVMFlag::SUCCESS) {
2401         return JNI_EINVAL;
2402       }
2403     // Xmaxf
2404     } else if (match_option(option, "-Xmaxf", &tail)) {
2405       char* err;
2406       double dmaxf = strtod(tail, &err);
2407       if (*err != '\0' || *tail == '\0') {
2408         jio_fprintf(defaultStream::error_stream(),
2409                     "Bad max heap free ratio: %s\n",
2410                     option->optionString);
2411         return JNI_EINVAL;
2412       }
2413       if (dmaxf < 0.0 || dmaxf > 1.0) {
2414         jio_fprintf(defaultStream::error_stream(),
2415                     "-Xmaxf value (%s) is outside the allowed range [ 0.0 ... 1.0 ]\n",
2416                     option->optionString);
2417         return JNI_EINVAL;
2418       }
2419       const uintx umaxf = (uintx)(dmaxf * 100);
2420       if (MinHeapFreeRatio > umaxf) {
2421         jio_fprintf(defaultStream::error_stream(),
2422                     "-Xmaxf value (%s) must be greater than or equal to the implicit -Xminf value (%.2f)\n",
2423                     tail, MinHeapFreeRatio / 100.0f);
2424         return JNI_EINVAL;
2425       }
2426       if (FLAG_SET_CMDLINE(MaxHeapFreeRatio, umaxf) != JVMFlag::SUCCESS) {
2427         return JNI_EINVAL;
2428       }
2429     // Xminf
2430     } else if (match_option(option, "-Xminf", &tail)) {
2431       char* err;
2432       double dminf = strtod(tail, &err);
2433       if (*err != '\0' || *tail == '\0') {
2434         jio_fprintf(defaultStream::error_stream(),
2435                     "Bad min heap free ratio: %s\n",
2436                     option->optionString);
2437         return JNI_EINVAL;
2438       }
2439       if (dminf < 0.0 || dminf > 1.0) {
2440         jio_fprintf(defaultStream::error_stream(),
2441                     "-Xminf value (%s) is outside the allowed range [ 0.0 ... 1.0 ]\n",
2442                     tail);
2443         return JNI_EINVAL;
2444       }
2445       const uintx uminf = (uintx)(dminf * 100);
2446       if (MaxHeapFreeRatio < uminf) {
2447         jio_fprintf(defaultStream::error_stream(),
2448                     "-Xminf value (%s) must be less than or equal to the implicit -Xmaxf value (%.2f)\n",
2449                     tail, MaxHeapFreeRatio / 100.0f);
2450         return JNI_EINVAL;
2451       }
2452       if (FLAG_SET_CMDLINE(MinHeapFreeRatio, uminf) != JVMFlag::SUCCESS) {
2453         return JNI_EINVAL;
2454       }
2455     // -Xss
2456     } else if (match_option(option, "-Xss", &tail)) {
2457       intx value = 0;
2458       jint err = parse_xss(option, tail, &value);
2459       if (err != JNI_OK) {
2460         return err;
2461       }
2462       if (FLAG_SET_CMDLINE(ThreadStackSize, value) != JVMFlag::SUCCESS) {
2463         return JNI_EINVAL;
2464       }
2465     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2466                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2467       if (match_option(option, "-Xmaxjitcodesize", &tail)) {
2468         warning("Option -Xmaxjitcodesize was deprecated in JDK 26 and will likely be removed in a future release.");
2469       }
2470       julong long_ReservedCodeCacheSize = 0;
2471 
2472       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2473       if (errcode != arg_in_range) {
2474         jio_fprintf(defaultStream::error_stream(),
2475                     "Invalid maximum code cache size: %s.\n", option->optionString);
2476         return JNI_EINVAL;
2477       }
2478       if (FLAG_SET_CMDLINE(ReservedCodeCacheSize, (size_t)long_ReservedCodeCacheSize) != JVMFlag::SUCCESS) {
2479         return JNI_EINVAL;
2480       }
2481     // -green
2482     } else if (match_option(option, "-green")) {
2483       jio_fprintf(defaultStream::error_stream(),
2484                   "Green threads support not available\n");
2485           return JNI_EINVAL;
2486     // -native
2487     } else if (match_option(option, "-native")) {
2488           // HotSpot always uses native threads, ignore silently for compatibility
2489     // -Xrs
2490     } else if (match_option(option, "-Xrs")) {
2491           // Classic/EVM option, new functionality
2492       if (FLAG_SET_CMDLINE(ReduceSignalUsage, true) != JVMFlag::SUCCESS) {
2493         return JNI_EINVAL;
2494       }
2495       // -Xprof
2496     } else if (match_option(option, "-Xprof")) {
2497       char version[256];
2498       // Obsolete in JDK 10
2499       JDK_Version::jdk(10).to_string(version, sizeof(version));
2500       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2501     // -Xinternalversion
2502     } else if (match_option(option, "-Xinternalversion")) {
2503       jio_fprintf(defaultStream::output_stream(), "%s\n",
2504                   VM_Version::internal_vm_info_string());
2505       vm_exit(0);
2506 #ifndef PRODUCT
2507     // -Xprintflags
2508     } else if (match_option(option, "-Xprintflags")) {
2509       JVMFlag::printFlags(tty, false);
2510       vm_exit(0);
2511 #endif
2512     // -D
2513     } else if (match_option(option, "-D", &tail)) {
2514       const char* value;
2515       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2516             *value!= '\0' && strcmp(value, "\"\"") != 0) {
2517         // abort if -Djava.endorsed.dirs is set
2518         jio_fprintf(defaultStream::output_stream(),
2519           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2520           "in modular form will be supported via the concept of upgradeable modules.\n", value);
2521         return JNI_EINVAL;
2522       }
2523       if (match_option(option, "-Djava.ext.dirs=", &value) &&
2524             *value != '\0' && strcmp(value, "\"\"") != 0) {
2525         // abort if -Djava.ext.dirs is set
2526         jio_fprintf(defaultStream::output_stream(),
2527           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2528         return JNI_EINVAL;
2529       }
2530       // Check for module related properties.  They must be set using the modules
2531       // options. For example: use "--add-modules=java.sql", not
2532       // "-Djdk.module.addmods=java.sql"
2533       if (is_internal_module_property(option->optionString + 2)) {
2534         needs_module_property_warning = true;
2535         continue;
2536       }
2537       if (!add_property(tail)) {
2538         return JNI_ENOMEM;
2539       }
2540       // Out of the box management support
2541       if (match_option(option, "-Dcom.sun.management", &tail)) {
2542 #if INCLUDE_MANAGEMENT
2543         if (FLAG_SET_CMDLINE(ManagementServer, true) != JVMFlag::SUCCESS) {
2544           return JNI_EINVAL;
2545         }
2546         // management agent in module jdk.management.agent
2547         if (!create_numbered_module_property("jdk.module.addmods", "jdk.management.agent", _addmods_count++)) {
2548           return JNI_ENOMEM;
2549         }
2550 #else
2551         jio_fprintf(defaultStream::output_stream(),
2552           "-Dcom.sun.management is not supported in this VM.\n");
2553         return JNI_ERR;
2554 #endif
2555       }
2556     // -Xint
2557     } else if (match_option(option, "-Xint")) {
2558           set_mode_flags(_int);
2559           mode_flag_cmd_line = true;
2560     // -Xmixed
2561     } else if (match_option(option, "-Xmixed")) {
2562           set_mode_flags(_mixed);
2563           mode_flag_cmd_line = true;
2564     // -Xcomp
2565     } else if (match_option(option, "-Xcomp")) {
2566       // for testing the compiler; turn off all flags that inhibit compilation
2567           set_mode_flags(_comp);
2568           mode_flag_cmd_line = true;
2569     // -Xshare:dump
2570     } else if (match_option(option, "-Xshare:dump")) {
2571       CDSConfig::enable_dumping_static_archive();
2572       CDSConfig::set_old_cds_flags_used();
2573     // -Xshare:on
2574     } else if (match_option(option, "-Xshare:on")) {
2575       UseSharedSpaces = true;
2576       RequireSharedSpaces = true;
2577       CDSConfig::set_old_cds_flags_used();
2578     // -Xshare:auto || -XX:ArchiveClassesAtExit=<archive file>
2579     } else if (match_option(option, "-Xshare:auto")) {
2580       UseSharedSpaces = true;
2581       RequireSharedSpaces = false;
2582       xshare_auto_cmd_line = true;
2583       CDSConfig::set_old_cds_flags_used();
2584     // -Xshare:off
2585     } else if (match_option(option, "-Xshare:off")) {
2586       UseSharedSpaces = false;
2587       RequireSharedSpaces = false;
2588       CDSConfig::set_old_cds_flags_used();
2589     // -Xverify
2590     } else if (match_option(option, "-Xverify", &tail)) {
2591       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
2592         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, true) != JVMFlag::SUCCESS) {
2593           return JNI_EINVAL;
2594         }
2595         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {
2596           return JNI_EINVAL;
2597         }
2598       } else if (strcmp(tail, ":remote") == 0) {
2599         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {
2600           return JNI_EINVAL;
2601         }
2602         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {
2603           return JNI_EINVAL;
2604         }
2605       } else if (strcmp(tail, ":none") == 0) {
2606         if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {
2607           return JNI_EINVAL;
2608         }
2609         if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, false) != JVMFlag::SUCCESS) {
2610           return JNI_EINVAL;
2611         }
2612         warning("Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.");
2613       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
2614         return JNI_EINVAL;
2615       }
2616     // -Xdebug
2617     } else if (match_option(option, "-Xdebug")) {
2618       warning("Option -Xdebug was deprecated in JDK 22 and will likely be removed in a future release.");
2619     } else if (match_option(option, "-Xloggc:", &tail)) {
2620       // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
2621       log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
2622       _legacyGCLogging.lastFlag = 2;
2623       _legacyGCLogging.file = os::strdup_check_oom(tail);
2624     } else if (match_option(option, "-Xlog", &tail)) {
2625       bool ret = false;
2626       if (strcmp(tail, ":help") == 0) {
2627         fileStream stream(defaultStream::output_stream());
2628         LogConfiguration::print_command_line_help(&stream);
2629         vm_exit(0);
2630       } else if (strcmp(tail, ":disable") == 0) {
2631         LogConfiguration::disable_logging();
2632         ret = true;
2633       } else if (strncmp(tail, ":async", strlen(":async")) == 0) {
2634         const char* async_tail = tail + strlen(":async");
2635         ret = LogConfiguration::parse_async_argument(async_tail);
2636       } else if (*tail == '\0') {
2637         ret = LogConfiguration::parse_command_line_arguments();
2638         assert(ret, "-Xlog without arguments should never fail to parse");
2639       } else if (*tail == ':') {
2640         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
2641       }
2642       if (ret == false) {
2643         jio_fprintf(defaultStream::error_stream(),
2644                     "Invalid -Xlog option '-Xlog%s', see error log for details.\n",
2645                     tail);
2646         return JNI_EINVAL;
2647       }
2648     // JNI hooks
2649     } else if (match_option(option, "-Xcheck", &tail)) {
2650       if (!strcmp(tail, ":jni")) {
2651 #if !INCLUDE_JNI_CHECK
2652         warning("JNI CHECKING is not supported in this VM");
2653 #else
2654         CheckJNICalls = true;
2655 #endif // INCLUDE_JNI_CHECK
2656       } else if (is_bad_option(option, args->ignoreUnrecognized,
2657                                      "check")) {
2658         return JNI_EINVAL;
2659       }
2660     } else if (match_option(option, "vfprintf")) {
2661       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
2662     } else if (match_option(option, "exit")) {
2663       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
2664     } else if (match_option(option, "abort")) {
2665       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
2666     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
2667     // and the last option wins.
2668     } else if (match_option(option, "-XX:+NeverTenure")) {
2669       if (FLAG_SET_CMDLINE(NeverTenure, true) != JVMFlag::SUCCESS) {
2670         return JNI_EINVAL;
2671       }
2672       if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {
2673         return JNI_EINVAL;
2674       }
2675       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, markWord::max_age + 1) != JVMFlag::SUCCESS) {
2676         return JNI_EINVAL;
2677       }
2678     } else if (match_option(option, "-XX:+AlwaysTenure")) {
2679       if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2680         return JNI_EINVAL;
2681       }
2682       if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {
2683         return JNI_EINVAL;
2684       }
2685       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, 0) != JVMFlag::SUCCESS) {
2686         return JNI_EINVAL;
2687       }
2688     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
2689       uint max_tenuring_thresh = 0;
2690       if (!parse_uint(tail, &max_tenuring_thresh, 0)) {
2691         jio_fprintf(defaultStream::error_stream(),
2692                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
2693         return JNI_EINVAL;
2694       }
2695 
2696       if (FLAG_SET_CMDLINE(MaxTenuringThreshold, max_tenuring_thresh) != JVMFlag::SUCCESS) {
2697         return JNI_EINVAL;
2698       }
2699 
2700       if (MaxTenuringThreshold == 0) {
2701         if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2702           return JNI_EINVAL;
2703         }
2704         if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {
2705           return JNI_EINVAL;
2706         }
2707       } else {
2708         if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2709           return JNI_EINVAL;
2710         }
2711         if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {
2712           return JNI_EINVAL;
2713         }
2714       }
2715     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
2716       if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, false) != JVMFlag::SUCCESS) {
2717         return JNI_EINVAL;
2718       }
2719       if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, true) != JVMFlag::SUCCESS) {
2720         return JNI_EINVAL;
2721       }
2722     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
2723       if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, false) != JVMFlag::SUCCESS) {
2724         return JNI_EINVAL;
2725       }
2726       if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, true) != JVMFlag::SUCCESS) {
2727         return JNI_EINVAL;
2728       }
2729     } else if (match_option(option, "-XX:+ErrorFileToStderr")) {
2730       if (FLAG_SET_CMDLINE(ErrorFileToStdout, false) != JVMFlag::SUCCESS) {
2731         return JNI_EINVAL;
2732       }
2733       if (FLAG_SET_CMDLINE(ErrorFileToStderr, true) != JVMFlag::SUCCESS) {
2734         return JNI_EINVAL;
2735       }
2736     } else if (match_option(option, "-XX:+ErrorFileToStdout")) {
2737       if (FLAG_SET_CMDLINE(ErrorFileToStderr, false) != JVMFlag::SUCCESS) {
2738         return JNI_EINVAL;
2739       }
2740       if (FLAG_SET_CMDLINE(ErrorFileToStdout, true) != JVMFlag::SUCCESS) {
2741         return JNI_EINVAL;
2742       }
2743     } else if (match_option(option, "--finalization=", &tail)) {
2744       if (strcmp(tail, "enabled") == 0) {
2745         InstanceKlass::set_finalization_enabled(true);
2746       } else if (strcmp(tail, "disabled") == 0) {
2747         InstanceKlass::set_finalization_enabled(false);
2748       } else {
2749         jio_fprintf(defaultStream::error_stream(),
2750                     "Invalid finalization value '%s', must be 'disabled' or 'enabled'.\n",
2751                     tail);
2752         return JNI_EINVAL;
2753       }
2754 #if !defined(DTRACE_ENABLED)
2755     } else if (match_option(option, "-XX:+DTraceMethodProbes")) {
2756       jio_fprintf(defaultStream::error_stream(),
2757                   "DTraceMethodProbes flag is not applicable for this configuration\n");
2758       return JNI_EINVAL;
2759     } else if (match_option(option, "-XX:+DTraceAllocProbes")) {
2760       jio_fprintf(defaultStream::error_stream(),
2761                   "DTraceAllocProbes flag is not applicable for this configuration\n");
2762       return JNI_EINVAL;
2763     } else if (match_option(option, "-XX:+DTraceMonitorProbes")) {
2764       jio_fprintf(defaultStream::error_stream(),
2765                   "DTraceMonitorProbes flag is not applicable for this configuration\n");
2766       return JNI_EINVAL;
2767 #endif // !defined(DTRACE_ENABLED)
2768 #ifdef ASSERT
2769     } else if (match_option(option, "-XX:+FullGCALot")) {
2770       if (FLAG_SET_CMDLINE(FullGCALot, true) != JVMFlag::SUCCESS) {
2771         return JNI_EINVAL;
2772       }
2773 #endif
2774 #if !INCLUDE_MANAGEMENT
2775     } else if (match_option(option, "-XX:+ManagementServer")) {
2776         jio_fprintf(defaultStream::error_stream(),
2777           "ManagementServer is not supported in this VM.\n");
2778         return JNI_ERR;
2779 #endif // INCLUDE_MANAGEMENT
2780 #if INCLUDE_JVMCI
2781     } else if (match_option(option, "-XX:-EnableJVMCIProduct") || match_option(option, "-XX:-UseGraalJIT")) {
2782       if (EnableJVMCIProduct) {
2783         jio_fprintf(defaultStream::error_stream(),
2784                   "-XX:-EnableJVMCIProduct or -XX:-UseGraalJIT cannot come after -XX:+EnableJVMCIProduct or -XX:+UseGraalJIT\n");
2785         return JNI_EINVAL;
2786       }
2787     } else if (match_option(option, "-XX:+EnableJVMCIProduct") || match_option(option, "-XX:+UseGraalJIT")) {
2788       bool use_graal_jit = match_option(option, "-XX:+UseGraalJIT");
2789       if (use_graal_jit) {
2790         const char* jvmci_compiler = get_property("jvmci.Compiler");
2791         if (jvmci_compiler != nullptr) {
2792           if (strncmp(jvmci_compiler, "graal", strlen("graal")) != 0) {
2793             jio_fprintf(defaultStream::error_stream(),
2794               "Value of jvmci.Compiler incompatible with +UseGraalJIT: %s\n", jvmci_compiler);
2795             return JNI_ERR;
2796           }
2797         } else if (!add_property("jvmci.Compiler=graal")) {
2798             return JNI_ENOMEM;
2799         }
2800       }
2801 
2802       // Just continue, since "-XX:+EnableJVMCIProduct" or "-XX:+UseGraalJIT" has been specified before
2803       if (EnableJVMCIProduct) {
2804         continue;
2805       }
2806       JVMFlag *jvmciFlag = JVMFlag::find_flag("EnableJVMCIProduct");
2807       // Allow this flag if it has been unlocked.
2808       if (jvmciFlag != nullptr && jvmciFlag->is_unlocked()) {
2809         if (!JVMCIGlobals::enable_jvmci_product_mode(origin, use_graal_jit)) {
2810           jio_fprintf(defaultStream::error_stream(),
2811             "Unable to enable JVMCI in product mode\n");
2812           return JNI_ERR;
2813         }
2814       }
2815       // The flag was locked so process normally to report that error
2816       else if (!process_argument(use_graal_jit ? "UseGraalJIT" : "EnableJVMCIProduct", args->ignoreUnrecognized, origin)) {
2817         return JNI_EINVAL;
2818       }
2819 #endif // INCLUDE_JVMCI
2820 #if INCLUDE_JFR
2821     } else if (match_jfr_option(&option)) {
2822       return JNI_EINVAL;
2823 #endif
2824     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
2825       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
2826       // already been handled
2827       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
2828           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
2829         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
2830           return JNI_EINVAL;
2831         }
2832       }
2833     // Unknown option
2834     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
2835       return JNI_ERR;
2836     }
2837   }
2838 
2839   // PrintSharedArchiveAndExit will turn on
2840   //   -Xshare:on
2841   //   -Xlog:class+path=info
2842   if (PrintSharedArchiveAndExit) {
2843     UseSharedSpaces = true;
2844     RequireSharedSpaces = true;
2845     LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));
2846   }
2847 
2848   fix_appclasspath();
2849 
2850   return JNI_OK;
2851 }
2852 
2853 void Arguments::set_ext_dirs(char *value) {
2854   _ext_dirs = os::strdup_check_oom(value);
2855 }
2856 
2857 void Arguments::add_patch_mod_prefix(const char* module_name, const char* path) {
2858   // For java.base check for duplicate --patch-module options being specified on the command line.
2859   // This check is only required for java.base, all other duplicate module specifications
2860   // will be checked during module system initialization.  The module system initialization
2861   // will throw an ExceptionInInitializerError if this situation occurs.
2862   if (strcmp(module_name, JAVA_BASE_NAME) == 0) {
2863     if (patch_mod_javabase) {
2864       vm_exit_during_initialization("Cannot specify " JAVA_BASE_NAME " more than once to --patch-module");
2865     } else {
2866       patch_mod_javabase = true;
2867     }
2868   }
2869 
2870   // Create GrowableArray lazily, only if --patch-module has been specified
2871   if (_patch_mod_prefix == nullptr) {
2872     _patch_mod_prefix = new (mtArguments) GrowableArray<ModulePatchPath*>(10, mtArguments);
2873   }
2874 
2875   _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
2876 }
2877 
2878 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
2879 //
2880 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
2881 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
2882 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
2883 // path is treated as the current directory.
2884 //
2885 // This causes problems with CDS, which requires that all directories specified in the classpath
2886 // must be empty. In most cases, applications do NOT want to load classes from the current
2887 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
2888 // scripts compatible with CDS.
2889 void Arguments::fix_appclasspath() {
2890   if (IgnoreEmptyClassPaths) {
2891     const char separator = *os::path_separator();
2892     const char* src = _java_class_path->value();
2893 
2894     // skip over all the leading empty paths
2895     while (*src == separator) {
2896       src ++;
2897     }
2898 
2899     char* copy = os::strdup_check_oom(src, mtArguments);
2900 
2901     // trim all trailing empty paths
2902     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
2903       *tail = '\0';
2904     }
2905 
2906     char from[3] = {separator, separator, '\0'};
2907     char to  [2] = {separator, '\0'};
2908     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
2909       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
2910       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
2911     }
2912 
2913     _java_class_path->set_writeable_value(copy);
2914     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
2915   }
2916 }
2917 
2918 jint Arguments::finalize_vm_init_args() {
2919   // check if the default lib/endorsed directory exists; if so, error
2920   char path[JVM_MAXPATHLEN];
2921   const char* fileSep = os::file_separator();
2922   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
2923 
2924   DIR* dir = os::opendir(path);
2925   if (dir != nullptr) {
2926     jio_fprintf(defaultStream::output_stream(),
2927       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
2928       "in modular form will be supported via the concept of upgradeable modules.\n");
2929     os::closedir(dir);
2930     return JNI_ERR;
2931   }
2932 
2933   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
2934   dir = os::opendir(path);
2935   if (dir != nullptr) {
2936     jio_fprintf(defaultStream::output_stream(),
2937       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
2938       "Use -classpath instead.\n.");
2939     os::closedir(dir);
2940     return JNI_ERR;
2941   }
2942 
2943   // This must be done after all arguments have been processed
2944   // and the container support has been initialized since AggressiveHeap
2945   // relies on the amount of total memory available.
2946   if (AggressiveHeap) {
2947     jint result = set_aggressive_heap_flags();
2948     if (result != JNI_OK) {
2949       return result;
2950     }
2951   }
2952 
2953   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
2954   // but like -Xint, leave compilation thresholds unaffected.
2955   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
2956   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
2957     set_mode_flags(_int);
2958   }
2959 
2960 #ifdef ZERO
2961   // Zero always runs in interpreted mode
2962   set_mode_flags(_int);
2963 #endif
2964 
2965   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
2966   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
2967     FLAG_SET_ERGO(InitialTenuringThreshold, MaxTenuringThreshold);
2968   }
2969 
2970 #if !COMPILER2_OR_JVMCI
2971   // Don't degrade server performance for footprint
2972   if (FLAG_IS_DEFAULT(UseLargePages) &&
2973       MaxHeapSize < LargePageHeapSizeThreshold) {
2974     // No need for large granularity pages w/small heaps.
2975     // Note that large pages are enabled/disabled for both the
2976     // Java heap and the code cache.
2977     FLAG_SET_DEFAULT(UseLargePages, false);
2978   }
2979 
2980   UNSUPPORTED_OPTION(ProfileInterpreter);
2981 #endif
2982 
2983   // Parse the CompilationMode flag
2984   if (!CompilationModeFlag::initialize()) {
2985     return JNI_ERR;
2986   }
2987 
2988   if (!check_vm_args_consistency()) {
2989     return JNI_ERR;
2990   }
2991 
2992 
2993 #ifndef CAN_SHOW_REGISTERS_ON_ASSERT
2994   UNSUPPORTED_OPTION(ShowRegistersOnAssert);
2995 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
2996 
2997   return JNI_OK;
2998 }
2999 
3000 // Helper class for controlling the lifetime of JavaVMInitArgs
3001 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3002 // deleted on the destruction of the ScopedVMInitArgs object.
3003 class ScopedVMInitArgs : public StackObj {
3004  private:
3005   JavaVMInitArgs _args;
3006   char*          _container_name;
3007   bool           _is_set;
3008   char*          _vm_options_file_arg;
3009 
3010  public:
3011   ScopedVMInitArgs(const char *container_name) {
3012     _args.version = JNI_VERSION_1_2;
3013     _args.nOptions = 0;
3014     _args.options = nullptr;
3015     _args.ignoreUnrecognized = false;
3016     _container_name = (char *)container_name;
3017     _is_set = false;
3018     _vm_options_file_arg = nullptr;
3019   }
3020 
3021   // Populates the JavaVMInitArgs object represented by this
3022   // ScopedVMInitArgs object with the arguments in options.  The
3023   // allocated memory is deleted by the destructor.  If this method
3024   // returns anything other than JNI_OK, then this object is in a
3025   // partially constructed state, and should be abandoned.
3026   jint set_args(const GrowableArrayView<JavaVMOption>* options) {
3027     _is_set = true;
3028     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3029         JavaVMOption, options->length(), mtArguments);
3030     if (options_arr == nullptr) {
3031       return JNI_ENOMEM;
3032     }
3033     _args.options = options_arr;
3034 
3035     for (int i = 0; i < options->length(); i++) {
3036       options_arr[i] = options->at(i);
3037       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3038       if (options_arr[i].optionString == nullptr) {
3039         // Rely on the destructor to do cleanup.
3040         _args.nOptions = i;
3041         return JNI_ENOMEM;
3042       }
3043     }
3044 
3045     _args.nOptions = options->length();
3046     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3047     return JNI_OK;
3048   }
3049 
3050   JavaVMInitArgs* get()             { return &_args; }
3051   char* container_name()            { return _container_name; }
3052   bool  is_set()                    { return _is_set; }
3053   bool  found_vm_options_file_arg() { return _vm_options_file_arg != nullptr; }
3054   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3055 
3056   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3057     if (_vm_options_file_arg != nullptr) {
3058       os::free(_vm_options_file_arg);
3059     }
3060     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3061   }
3062 
3063   ~ScopedVMInitArgs() {
3064     if (_vm_options_file_arg != nullptr) {
3065       os::free(_vm_options_file_arg);
3066     }
3067     if (_args.options == nullptr) return;
3068     for (int i = 0; i < _args.nOptions; i++) {
3069       os::free(_args.options[i].optionString);
3070     }
3071     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3072   }
3073 
3074   // Insert options into this option list, to replace option at
3075   // vm_options_file_pos (-XX:VMOptionsFile)
3076   jint insert(const JavaVMInitArgs* args,
3077               const JavaVMInitArgs* args_to_insert,
3078               const int vm_options_file_pos) {
3079     assert(_args.options == nullptr, "shouldn't be set yet");
3080     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3081     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3082 
3083     int length = args->nOptions + args_to_insert->nOptions - 1;
3084     // Construct new option array
3085     GrowableArrayCHeap<JavaVMOption, mtArguments> options(length);
3086     for (int i = 0; i < args->nOptions; i++) {
3087       if (i == vm_options_file_pos) {
3088         // insert the new options starting at the same place as the
3089         // -XX:VMOptionsFile option
3090         for (int j = 0; j < args_to_insert->nOptions; j++) {
3091           options.push(args_to_insert->options[j]);
3092         }
3093       } else {
3094         options.push(args->options[i]);
3095       }
3096     }
3097     // make into options array
3098     return set_args(&options);
3099   }
3100 };
3101 
3102 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3103   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3104 }
3105 
3106 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3107   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3108 }
3109 
3110 static JavaVMOption* get_last_aotmode_arg(const JavaVMInitArgs* args) {
3111   for (int index = args->nOptions - 1; index >= 0; index--) {
3112     JavaVMOption* option = args->options + index;
3113     if (strstr(option->optionString, "-XX:AOTMode=") == option->optionString) {
3114       return option;
3115     }
3116   }
3117 
3118   return nullptr;
3119 }
3120 
3121 jint Arguments::parse_jdk_aot_vm_options_environment_variable(GrowableArrayCHeap<VMInitArgsGroup, mtArguments>* all_args,
3122                                                             ScopedVMInitArgs* jdk_aot_vm_options_args) {
3123   // Don't bother scanning all the args if this env variable is not set
3124   if (::getenv("JDK_AOT_VM_OPTIONS") == nullptr) {
3125     return JNI_OK;
3126   }
3127 
3128   // Scan backwards and find the last occurrence of -XX:AOTMode=xxx, which will decide the value
3129   // of AOTMode.
3130   JavaVMOption* option = nullptr;
3131   for (int i = all_args->length() - 1; i >= 0; i--) {
3132     if ((option = get_last_aotmode_arg(all_args->at(i)._args)) != nullptr) {
3133       break;
3134     }
3135   }
3136 
3137   if (option != nullptr) {
3138     // We have found the last -XX:AOTMode=xxx. At this point <option> has NOT been parsed yet,
3139     // so its value is not reflected inside the global variable AOTMode.
3140     if (strcmp(option->optionString, "-XX:AOTMode=create") != 0) {
3141       return JNI_OK; // Do not parse JDK_AOT_VM_OPTIONS
3142     }
3143   } else {
3144     // -XX:AOTMode is not specified in any of 4 options_args, let's check AOTMode,
3145     // which would have been set inside process_settings_file();
3146     if (AOTMode == nullptr || strcmp(AOTMode, "create") != 0) {
3147       return JNI_OK; // Do not parse JDK_AOT_VM_OPTIONS
3148     }
3149   }
3150 
3151   return parse_options_environment_variable("JDK_AOT_VM_OPTIONS", jdk_aot_vm_options_args);
3152 }
3153 
3154 jint Arguments::parse_options_environment_variable(const char* name,
3155                                                    ScopedVMInitArgs* vm_args) {
3156   char *buffer = ::getenv(name);
3157 
3158   // Don't check this environment variable if user has special privileges
3159   // (e.g. unix su command).
3160   if (buffer == nullptr || os::have_special_privileges()) {
3161     return JNI_OK;
3162   }
3163 
3164   if ((buffer = os::strdup(buffer)) == nullptr) {
3165     return JNI_ENOMEM;
3166   }
3167 
3168   jio_fprintf(defaultStream::error_stream(),
3169               "Picked up %s: %s\n", name, buffer);
3170 
3171   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3172 
3173   os::free(buffer);
3174   return retcode;
3175 }
3176 
3177 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3178   // read file into buffer
3179   int fd = ::open(file_name, O_RDONLY);
3180   if (fd < 0) {
3181     jio_fprintf(defaultStream::error_stream(),
3182                 "Could not open options file '%s'\n",
3183                 file_name);
3184     return JNI_ERR;
3185   }
3186 
3187   struct stat stbuf;
3188   int retcode = os::stat(file_name, &stbuf);
3189   if (retcode != 0) {
3190     jio_fprintf(defaultStream::error_stream(),
3191                 "Could not stat options file '%s'\n",
3192                 file_name);
3193     ::close(fd);
3194     return JNI_ERR;
3195   }
3196 
3197   if (stbuf.st_size == 0) {
3198     // tell caller there is no option data and that is ok
3199     ::close(fd);
3200     return JNI_OK;
3201   }
3202 
3203   // '+ 1' for null termination even with max bytes
3204   size_t bytes_alloc = stbuf.st_size + 1;
3205 
3206   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3207   if (nullptr == buf) {
3208     jio_fprintf(defaultStream::error_stream(),
3209                 "Could not allocate read buffer for options file parse\n");
3210     ::close(fd);
3211     return JNI_ENOMEM;
3212   }
3213 
3214   memset(buf, 0, bytes_alloc);
3215 
3216   // Fill buffer
3217   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3218   ::close(fd);
3219   if (bytes_read < 0) {
3220     FREE_C_HEAP_ARRAY(char, buf);
3221     jio_fprintf(defaultStream::error_stream(),
3222                 "Could not read options file '%s'\n", file_name);
3223     return JNI_ERR;
3224   }
3225 
3226   if (bytes_read == 0) {
3227     // tell caller there is no option data and that is ok
3228     FREE_C_HEAP_ARRAY(char, buf);
3229     return JNI_OK;
3230   }
3231 
3232   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3233 
3234   FREE_C_HEAP_ARRAY(char, buf);
3235   return retcode;
3236 }
3237 
3238 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3239   // Construct option array
3240   GrowableArrayCHeap<JavaVMOption, mtArguments> options(2);
3241 
3242   // some pointers to help with parsing
3243   char *buffer_end = buffer + buf_len;
3244   char *opt_hd = buffer;
3245   char *wrt = buffer;
3246   char *rd = buffer;
3247 
3248   // parse all options
3249   while (rd < buffer_end) {
3250     // skip leading white space from the input string
3251     while (rd < buffer_end && isspace((unsigned char) *rd)) {
3252       rd++;
3253     }
3254 
3255     if (rd >= buffer_end) {
3256       break;
3257     }
3258 
3259     // Remember this is where we found the head of the token.
3260     opt_hd = wrt;
3261 
3262     // Tokens are strings of non white space characters separated
3263     // by one or more white spaces.
3264     while (rd < buffer_end && !isspace((unsigned char) *rd)) {
3265       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3266         int quote = *rd;                    // matching quote to look for
3267         rd++;                               // don't copy open quote
3268         while (rd < buffer_end && *rd != quote) {
3269                                             // include everything (even spaces)
3270                                             // up until the close quote
3271           *wrt++ = *rd++;                   // copy to option string
3272         }
3273 
3274         if (rd < buffer_end) {
3275           rd++;                             // don't copy close quote
3276         } else {
3277                                             // did not see closing quote
3278           jio_fprintf(defaultStream::error_stream(),
3279                       "Unmatched quote in %s\n", name);
3280           return JNI_ERR;
3281         }
3282       } else {
3283         *wrt++ = *rd++;                     // copy to option string
3284       }
3285     }
3286 
3287     // steal a white space character and set it to null
3288     *wrt++ = '\0';
3289     // We now have a complete token
3290 
3291     JavaVMOption option;
3292     option.optionString = opt_hd;
3293     option.extraInfo = nullptr;
3294 
3295     options.append(option);                // Fill in option
3296 
3297     rd++;  // Advance to next character
3298   }
3299 
3300   // Fill out JavaVMInitArgs structure.
3301   return vm_args->set_args(&options);
3302 }
3303 
3304 #ifndef PRODUCT
3305 // Determine whether LogVMOutput should be implicitly turned on.
3306 static bool use_vm_log() {
3307   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3308       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3309       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3310       PrintAssembly || TraceDeoptimization ||
3311       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3312     return true;
3313   }
3314 
3315 #ifdef COMPILER1
3316   if (PrintC1Statistics) {
3317     return true;
3318   }
3319 #endif // COMPILER1
3320 
3321 #ifdef COMPILER2
3322   if (PrintOptoAssembly || PrintOptoStatistics) {
3323     return true;
3324   }
3325 #endif // COMPILER2
3326 
3327   return false;
3328 }
3329 
3330 #endif // PRODUCT
3331 
3332 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3333   for (int index = 0; index < args->nOptions; index++) {
3334     const JavaVMOption* option = args->options + index;
3335     const char* tail;
3336     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3337       return true;
3338     }
3339   }
3340   return false;
3341 }
3342 
3343 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3344                                        const char* vm_options_file,
3345                                        const int vm_options_file_pos,
3346                                        ScopedVMInitArgs* vm_options_file_args,
3347                                        ScopedVMInitArgs* args_out) {
3348   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
3349   if (code != JNI_OK) {
3350     return code;
3351   }
3352 
3353   if (vm_options_file_args->get()->nOptions < 1) {
3354     return JNI_OK;
3355   }
3356 
3357   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
3358     jio_fprintf(defaultStream::error_stream(),
3359                 "A VM options file may not refer to a VM options file. "
3360                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
3361                 "options file '%s' in options container '%s' is an error.\n",
3362                 vm_options_file_args->vm_options_file_arg(),
3363                 vm_options_file_args->container_name());
3364     return JNI_EINVAL;
3365   }
3366 
3367   return args_out->insert(args, vm_options_file_args->get(),
3368                           vm_options_file_pos);
3369 }
3370 
3371 // Expand -XX:VMOptionsFile found in args_in as needed.
3372 // mod_args and args_out parameters may return values as needed.
3373 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
3374                                             ScopedVMInitArgs* mod_args,
3375                                             JavaVMInitArgs** args_out) {
3376   jint code = match_special_option_and_act(args_in, mod_args);
3377   if (code != JNI_OK) {
3378     return code;
3379   }
3380 
3381   if (mod_args->is_set()) {
3382     // args_in contains -XX:VMOptionsFile and mod_args contains the
3383     // original options from args_in along with the options expanded
3384     // from the VMOptionsFile. Return a short-hand to the caller.
3385     *args_out = mod_args->get();
3386   } else {
3387     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
3388   }
3389   return JNI_OK;
3390 }
3391 
3392 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3393                                              ScopedVMInitArgs* args_out) {
3394   // Remaining part of option string
3395   const char* tail;
3396   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
3397 
3398   for (int index = 0; index < args->nOptions; index++) {
3399     const JavaVMOption* option = args->options + index;
3400     if (match_option(option, "-XX:Flags=", &tail)) {
3401       Arguments::set_jvm_flags_file(tail);
3402       continue;
3403     }
3404     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3405       if (vm_options_file_args.found_vm_options_file_arg()) {
3406         jio_fprintf(defaultStream::error_stream(),
3407                     "The option '%s' is already specified in the options "
3408                     "container '%s' so the specification of '%s' in the "
3409                     "same options container is an error.\n",
3410                     vm_options_file_args.vm_options_file_arg(),
3411                     vm_options_file_args.container_name(),
3412                     option->optionString);
3413         return JNI_EINVAL;
3414       }
3415       vm_options_file_args.set_vm_options_file_arg(option->optionString);
3416       // If there's a VMOptionsFile, parse that
3417       jint code = insert_vm_options_file(args, tail, index,
3418                                          &vm_options_file_args, args_out);
3419       if (code != JNI_OK) {
3420         return code;
3421       }
3422       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
3423       if (args_out->is_set()) {
3424         // The VMOptions file inserted some options so switch 'args'
3425         // to the new set of options, and continue processing which
3426         // preserves "last option wins" semantics.
3427         args = args_out->get();
3428         // The first option from the VMOptionsFile replaces the
3429         // current option.  So we back track to process the
3430         // replacement option.
3431         index--;
3432       }
3433       continue;
3434     }
3435     if (match_option(option, "-XX:+PrintVMOptions")) {
3436       PrintVMOptions = true;
3437       continue;
3438     }
3439     if (match_option(option, "-XX:-PrintVMOptions")) {
3440       PrintVMOptions = false;
3441       continue;
3442     }
3443     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3444       IgnoreUnrecognizedVMOptions = true;
3445       continue;
3446     }
3447     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3448       IgnoreUnrecognizedVMOptions = false;
3449       continue;
3450     }
3451     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3452       JVMFlag::printFlags(tty, false);
3453       vm_exit(0);
3454     }
3455 
3456 #ifndef PRODUCT
3457     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3458       JVMFlag::printFlags(tty, true);
3459       vm_exit(0);
3460     }
3461 #endif
3462   }
3463   return JNI_OK;
3464 }
3465 
3466 static void print_options(const JavaVMInitArgs *args) {
3467   const char* tail;
3468   for (int index = 0; index < args->nOptions; index++) {
3469     const JavaVMOption *option = args->options + index;
3470     if (match_option(option, "-XX:", &tail)) {
3471       logOption(tail);
3472     }
3473   }
3474 }
3475 
3476 bool Arguments::handle_deprecated_print_gc_flags() {
3477   if (PrintGC) {
3478     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
3479   }
3480   if (PrintGCDetails) {
3481     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
3482   }
3483 
3484   if (_legacyGCLogging.lastFlag == 2) {
3485     // -Xloggc was used to specify a filename
3486     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
3487 
3488     LogTarget(Error, logging) target;
3489     LogStream errstream(target);
3490     return LogConfiguration::parse_log_arguments(_legacyGCLogging.file, gc_conf, nullptr, nullptr, &errstream);
3491   } else if (PrintGC || PrintGCDetails || (_legacyGCLogging.lastFlag == 1)) {
3492     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
3493   }
3494   return true;
3495 }
3496 
3497 static void apply_debugger_ergo() {
3498 #ifdef ASSERT
3499   if (ReplayCompiles) {
3500     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo, true);
3501   }
3502 
3503   if (UseDebuggerErgo) {
3504     // Turn on sub-flags
3505     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo1, true);
3506     FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo2, true);
3507   }
3508 
3509   if (UseDebuggerErgo2) {
3510     // Debugging with limited number of CPUs
3511     FLAG_SET_ERGO_IF_DEFAULT(UseNUMA, false);
3512     FLAG_SET_ERGO_IF_DEFAULT(ConcGCThreads, 1);
3513     FLAG_SET_ERGO_IF_DEFAULT(ParallelGCThreads, 1);
3514     FLAG_SET_ERGO_IF_DEFAULT(CICompilerCount, 2);
3515   }
3516 #endif // ASSERT
3517 }
3518 
3519 // Parse entry point called from JNI_CreateJavaVM
3520 
3521 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
3522   assert(verify_special_jvm_flags(false), "deprecated and obsolete flag table inconsistent");
3523   JVMFlag::check_all_flag_declarations();
3524 
3525   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3526   const char* hotspotrc = ".hotspotrc";
3527   bool settings_file_specified = false;
3528   bool needs_hotspotrc_warning = false;
3529   ScopedVMInitArgs initial_vm_options_args("");
3530   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3531   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
3532   ScopedVMInitArgs initial_jdk_aot_vm_options_args("env_var='JDK_AOT_VM_OPTIONS'");
3533 
3534   // Pointers to current working set of containers
3535   JavaVMInitArgs* cur_cmd_args;
3536   JavaVMInitArgs* cur_vm_options_args;
3537   JavaVMInitArgs* cur_java_options_args;
3538   JavaVMInitArgs* cur_java_tool_options_args;
3539   JavaVMInitArgs* cur_jdk_aot_vm_options_args;
3540 
3541   // Containers for modified/expanded options
3542   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
3543   ScopedVMInitArgs mod_vm_options_args("vm_options_args");
3544   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3545   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
3546   ScopedVMInitArgs mod_jdk_aot_vm_options_args("env_var='_JDK_AOT_VM_OPTIONS'");
3547 
3548   GrowableArrayCHeap<VMInitArgsGroup, mtArguments> all_args;
3549 
3550   jint code =
3551       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
3552   if (code != JNI_OK) {
3553     return code;
3554   }
3555 
3556   // Yet another environment variable: _JAVA_OPTIONS. This mimics the classic VM.
3557   // This is an undocumented feature.
3558   code = parse_java_options_environment_variable(&initial_java_options_args);
3559   if (code != JNI_OK) {
3560     return code;
3561   }
3562 
3563   // Parse the options in the /java.base/jdk/internal/vm/options resource, if present
3564   char *vmoptions = ClassLoader::lookup_vm_options();
3565   if (vmoptions != nullptr) {
3566     code = parse_options_buffer("vm options resource", vmoptions, strlen(vmoptions), &initial_vm_options_args);
3567     FREE_C_HEAP_ARRAY(char, vmoptions);
3568     if (code != JNI_OK) {
3569       return code;
3570     }
3571   }
3572 
3573   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
3574                                      &mod_java_tool_options_args,
3575                                      &cur_java_tool_options_args);
3576   if (code != JNI_OK) {
3577     return code;
3578   }
3579 
3580   code = expand_vm_options_as_needed(initial_cmd_args,
3581                                      &mod_cmd_args,
3582                                      &cur_cmd_args);
3583   if (code != JNI_OK) {
3584     return code;
3585   }
3586 
3587   code = expand_vm_options_as_needed(initial_java_options_args.get(),
3588                                      &mod_java_options_args,
3589                                      &cur_java_options_args);
3590   if (code != JNI_OK) {
3591     return code;
3592   }
3593 
3594   code = expand_vm_options_as_needed(initial_vm_options_args.get(),
3595                                      &mod_vm_options_args,
3596                                      &cur_vm_options_args);
3597   if (code != JNI_OK) {
3598     return code;
3599   }
3600 
3601   const char* flags_file = Arguments::get_jvm_flags_file();
3602   settings_file_specified = (flags_file != nullptr);
3603 
3604   // Parse specified settings file (s) -- the effects are applied immediately into the JVM global flags.
3605   if (settings_file_specified) {
3606     if (!process_settings_file(flags_file, true,
3607                                IgnoreUnrecognizedVMOptions)) {
3608       return JNI_EINVAL;
3609     }
3610   } else {
3611 #ifdef ASSERT
3612     // Parse default .hotspotrc settings file
3613     if (!process_settings_file(".hotspotrc", false,
3614                                IgnoreUnrecognizedVMOptions)) {
3615       return JNI_EINVAL;
3616     }
3617 #else
3618     struct stat buf;
3619     if (os::stat(hotspotrc, &buf) == 0) {
3620       needs_hotspotrc_warning = true;
3621     }
3622 #endif
3623   }
3624 
3625   // The settings in the args are applied in this order to the the JVM global flags.
3626   // For historical reasons, the order is DIFFERENT than the scanning order of
3627   // the above expand_vm_options_as_needed() calls.
3628   all_args.append({cur_vm_options_args, JVMFlagOrigin::JIMAGE_RESOURCE});
3629   all_args.append({cur_java_tool_options_args, JVMFlagOrigin::ENVIRON_VAR});
3630   all_args.append({cur_cmd_args, JVMFlagOrigin::COMMAND_LINE});
3631   all_args.append({cur_java_options_args, JVMFlagOrigin::ENVIRON_VAR});
3632 
3633   // JDK_AOT_VM_OPTIONS are parsed only if -XX:AOTMode=create has been detected from all
3634   // the options that have been gathered above.
3635   code = parse_jdk_aot_vm_options_environment_variable(&all_args, &initial_jdk_aot_vm_options_args);
3636   if (code != JNI_OK) {
3637     return code;
3638   }
3639   code = expand_vm_options_as_needed(initial_jdk_aot_vm_options_args.get(),
3640                                      &mod_jdk_aot_vm_options_args,
3641                                      &cur_jdk_aot_vm_options_args);
3642   if (code != JNI_OK) {
3643     return code;
3644   }
3645 
3646   for (int index = 0; index < cur_jdk_aot_vm_options_args->nOptions; index++) {
3647     JavaVMOption* option = cur_jdk_aot_vm_options_args->options + index;
3648     const char* optionString = option->optionString;
3649     if (strstr(optionString, "-XX:AOTMode=") == optionString &&
3650         strcmp(optionString, "-XX:AOTMode=create") != 0) {
3651       jio_fprintf(defaultStream::error_stream(),
3652                   "Option %s cannot be specified in JDK_AOT_VM_OPTIONS\n", optionString);
3653       return JNI_ERR;
3654     }
3655   }
3656 
3657   all_args.append({cur_jdk_aot_vm_options_args, JVMFlagOrigin::ENVIRON_VAR});
3658 
3659   if (IgnoreUnrecognizedVMOptions) {
3660     // Note: unrecognized options in cur_vm_options_arg cannot be ignored. They are part of
3661     // the JDK so it shouldn't have bad options.
3662     cur_cmd_args->ignoreUnrecognized = true;
3663     cur_java_tool_options_args->ignoreUnrecognized = true;
3664     cur_java_options_args->ignoreUnrecognized = true;
3665     cur_jdk_aot_vm_options_args->ignoreUnrecognized = true;
3666   }
3667 
3668   if (PrintVMOptions) {
3669     // For historical reasons, options specified in cur_vm_options_arg and -XX:Flags are not printed.
3670     print_options(cur_java_tool_options_args);
3671     print_options(cur_cmd_args);
3672     print_options(cur_java_options_args);
3673     print_options(cur_jdk_aot_vm_options_args);
3674   }
3675 
3676   // Apply the settings in these args to the JVM global flags.
3677   jint result = parse_vm_init_args(&all_args);
3678 
3679   if (result != JNI_OK) {
3680     return result;
3681   }
3682 
3683   // Delay warning until here so that we've had a chance to process
3684   // the -XX:-PrintWarnings flag
3685   if (needs_hotspotrc_warning) {
3686     warning("%s file is present but has been ignored.  "
3687             "Run with -XX:Flags=%s to load the file.",
3688             hotspotrc, hotspotrc);
3689   }
3690 
3691   if (needs_module_property_warning) {
3692     warning("Ignoring system property options whose names match the '-Djdk.module.*'."
3693             " names that are reserved for internal use.");
3694   }
3695 
3696 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
3697   UNSUPPORTED_OPTION(UseLargePages);
3698 #endif
3699 
3700 #if defined(AIX)
3701   UNSUPPORTED_OPTION_NULL(AllocateHeapAt);
3702 #endif
3703 
3704 #ifndef PRODUCT
3705   if (TraceBytecodesAt != 0) {
3706     TraceBytecodes = true;
3707   }
3708 #endif // PRODUCT
3709 
3710   if (ScavengeRootsInCode == 0) {
3711     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3712       warning("Forcing ScavengeRootsInCode non-zero");
3713     }
3714     ScavengeRootsInCode = 1;
3715   }
3716 
3717   if (!handle_deprecated_print_gc_flags()) {
3718     return JNI_EINVAL;
3719   }
3720 
3721   // Set object alignment values.
3722   set_object_alignment();
3723 
3724 #if !INCLUDE_CDS
3725   if (CDSConfig::is_dumping_static_archive() || RequireSharedSpaces) {
3726     jio_fprintf(defaultStream::error_stream(),
3727       "Shared spaces are not supported in this VM\n");
3728     return JNI_ERR;
3729   }
3730   if (DumpLoadedClassList != nullptr) {
3731     jio_fprintf(defaultStream::error_stream(),
3732       "DumpLoadedClassList is not supported in this VM\n");
3733     return JNI_ERR;
3734   }
3735   if ((CDSConfig::is_using_archive() && xshare_auto_cmd_line) ||
3736       log_is_enabled(Info, cds) || log_is_enabled(Info, aot)) {
3737     warning("Shared spaces are not supported in this VM");
3738     UseSharedSpaces = false;
3739     LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(cds));
3740     LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(aot));
3741   }
3742   no_shared_spaces("CDS Disabled");
3743 #endif // INCLUDE_CDS
3744 
3745   // Verify NMT arguments
3746   const NMT_TrackingLevel lvl = NMTUtil::parse_tracking_level(NativeMemoryTracking);
3747   if (lvl == NMT_unknown) {
3748     jio_fprintf(defaultStream::error_stream(),
3749                 "Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]\n");
3750     return JNI_ERR;
3751   }
3752   if (PrintNMTStatistics && lvl == NMT_off) {
3753     warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
3754     FLAG_SET_DEFAULT(PrintNMTStatistics, false);
3755   }
3756 
3757   bool trace_dependencies = log_is_enabled(Debug, dependencies);
3758   if (trace_dependencies && VerifyDependencies) {
3759     warning("dependency logging results may be inflated by VerifyDependencies");
3760   }
3761 
3762   bool log_class_load_cause = log_is_enabled(Info, class, load, cause, native) ||
3763                               log_is_enabled(Info, class, load, cause);
3764   if (log_class_load_cause && LogClassLoadingCauseFor == nullptr) {
3765     warning("class load cause logging will not produce output without LogClassLoadingCauseFor");
3766   }
3767 
3768   apply_debugger_ergo();
3769 
3770   // The VMThread needs to stop now and then to execute these debug options.
3771   if ((HandshakeALot || SafepointALot) && FLAG_IS_DEFAULT(GuaranteedSafepointInterval)) {
3772     FLAG_SET_DEFAULT(GuaranteedSafepointInterval, 1000);
3773   }
3774 
3775   if (log_is_enabled(Info, arguments)) {
3776     LogStream st(Log(arguments)::info());
3777     Arguments::print_on(&st);
3778   }
3779 
3780   return JNI_OK;
3781 }
3782 
3783 void Arguments::set_compact_headers_flags() {
3784 #ifdef _LP64
3785   if (UseCompactObjectHeaders && FLAG_IS_CMDLINE(UseCompressedClassPointers) && !UseCompressedClassPointers) {
3786     warning("Compact object headers require compressed class pointers. Disabling compact object headers.");
3787     FLAG_SET_DEFAULT(UseCompactObjectHeaders, false);
3788   }
3789   if (UseCompactObjectHeaders && !UseObjectMonitorTable) {
3790     // If UseCompactObjectHeaders is on the command line, turn on UseObjectMonitorTable.
3791     if (FLAG_IS_CMDLINE(UseCompactObjectHeaders)) {
3792       FLAG_SET_DEFAULT(UseObjectMonitorTable, true);
3793 
3794       // If UseObjectMonitorTable is on the command line, turn off UseCompactObjectHeaders.
3795     } else if (FLAG_IS_CMDLINE(UseObjectMonitorTable)) {
3796       FLAG_SET_DEFAULT(UseCompactObjectHeaders, false);
3797       // If neither on the command line, the defaults are incompatible, but turn on UseObjectMonitorTable.
3798     } else {
3799       FLAG_SET_DEFAULT(UseObjectMonitorTable, true);
3800     }
3801   }
3802   if (UseCompactObjectHeaders && !UseCompressedClassPointers) {
3803     FLAG_SET_DEFAULT(UseCompressedClassPointers, true);
3804   }
3805 #endif
3806 }
3807 
3808 jint Arguments::apply_ergo() {
3809   // Set flags based on ergonomics.
3810   jint result = set_ergonomics_flags();
3811   if (result != JNI_OK) return result;
3812 
3813   // Set heap size based on available physical memory
3814   set_heap_size();
3815 
3816   GCConfig::arguments()->initialize();
3817 
3818   set_compact_headers_flags();
3819 
3820   if (UseCompressedClassPointers) {
3821     CompressedKlassPointers::pre_initialize();
3822   }
3823 
3824   CDSConfig::ergo_initialize();
3825 
3826   // Initialize Metaspace flags and alignments
3827   Metaspace::ergo_initialize();
3828 
3829   if (!StringDedup::ergo_initialize()) {
3830     return JNI_EINVAL;
3831   }
3832 
3833   // Set compiler flags after GC is selected and GC specific
3834   // flags (LoopStripMiningIter) are set.
3835   CompilerConfig::ergo_initialize();
3836 
3837   // Set bytecode rewriting flags
3838   set_bytecode_flags();
3839 
3840   // Set flags if aggressive optimization flags are enabled
3841   jint code = set_aggressive_opts_flags();
3842   if (code != JNI_OK) {
3843     return code;
3844   }
3845 
3846   if (FLAG_IS_DEFAULT(UseSecondarySupersTable)) {
3847     FLAG_SET_DEFAULT(UseSecondarySupersTable, VM_Version::supports_secondary_supers_table());
3848   } else if (UseSecondarySupersTable && !VM_Version::supports_secondary_supers_table()) {
3849     warning("UseSecondarySupersTable is not supported");
3850     FLAG_SET_DEFAULT(UseSecondarySupersTable, false);
3851   }
3852   if (!UseSecondarySupersTable) {
3853     FLAG_SET_DEFAULT(StressSecondarySupers, false);
3854     FLAG_SET_DEFAULT(VerifySecondarySupers, false);
3855   }
3856 
3857 #ifdef ZERO
3858   // Clear flags not supported on zero.
3859   FLAG_SET_DEFAULT(ProfileInterpreter, false);
3860 #endif // ZERO
3861 
3862   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
3863     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
3864     DebugNonSafepoints = true;
3865   }
3866 
3867   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
3868     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
3869   }
3870 
3871   // Treat the odd case where local verification is enabled but remote
3872   // verification is not as if both were enabled.
3873   if (BytecodeVerificationLocal && !BytecodeVerificationRemote) {
3874     log_info(verification)("Turning on remote verification because local verification is on");
3875     FLAG_SET_DEFAULT(BytecodeVerificationRemote, true);
3876   }
3877 
3878 #ifndef PRODUCT
3879   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
3880     if (use_vm_log()) {
3881       LogVMOutput = true;
3882     }
3883   }
3884 #endif // PRODUCT
3885 
3886   if (PrintCommandLineFlags) {
3887     JVMFlag::printSetFlags(tty);
3888   }
3889 
3890 #if COMPILER2_OR_JVMCI
3891   if (!FLAG_IS_DEFAULT(EnableVectorSupport) && !EnableVectorSupport) {
3892     if (!FLAG_IS_DEFAULT(EnableVectorReboxing) && EnableVectorReboxing) {
3893       warning("Disabling EnableVectorReboxing since EnableVectorSupport is turned off.");
3894     }
3895     FLAG_SET_DEFAULT(EnableVectorReboxing, false);
3896 
3897     if (!FLAG_IS_DEFAULT(EnableVectorAggressiveReboxing) && EnableVectorAggressiveReboxing) {
3898       if (!EnableVectorReboxing) {
3899         warning("Disabling EnableVectorAggressiveReboxing since EnableVectorReboxing is turned off.");
3900       } else {
3901         warning("Disabling EnableVectorAggressiveReboxing since EnableVectorSupport is turned off.");
3902       }
3903     }
3904     FLAG_SET_DEFAULT(EnableVectorAggressiveReboxing, false);
3905   }
3906 #endif // COMPILER2_OR_JVMCI
3907 
3908 #ifdef COMPILER2
3909   if (!FLAG_IS_DEFAULT(UseLoopPredicate) && !UseLoopPredicate && UseProfiledLoopPredicate) {
3910     warning("Disabling UseProfiledLoopPredicate since UseLoopPredicate is turned off.");
3911     FLAG_SET_ERGO(UseProfiledLoopPredicate, false);
3912   }
3913 #endif // COMPILER2
3914 
3915   if (log_is_enabled(Info, init)) {
3916     if (FLAG_IS_DEFAULT(ProfileVMLocks)) {
3917       FLAG_SET_DEFAULT(ProfileVMLocks, true);
3918     }
3919     if (UsePerfData && !log_is_enabled(Info, perf, class, link)) {
3920       // automatically enable -Xlog:perf+class+link
3921       LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(perf, class, link));
3922     }
3923     // Don't turn on ProfileVMCalls and ProfileRuntimeCalls by default.
3924   } else {
3925     if (!FLAG_IS_DEFAULT(ProfileVMLocks) && ProfileVMLocks) {
3926       warning("Disabling ProfileVMLocks since logging is turned off.");
3927       FLAG_SET_DEFAULT(ProfileVMLocks, false);
3928     }
3929     if (!FLAG_IS_DEFAULT(ProfileVMCalls) && ProfileVMCalls) {
3930       warning("Disabling ProfileVMCalls since logging is turned off.");
3931       FLAG_SET_DEFAULT(ProfileVMCalls, false);
3932     }
3933     if (!FLAG_IS_DEFAULT(ProfileRuntimeCalls) && ProfileRuntimeCalls) {
3934       warning("Disabling ProfileRuntimeCalls since logging is turned off.");
3935       FLAG_SET_DEFAULT(ProfileRuntimeCalls, false);
3936     }
3937     if (log_is_enabled(Info, perf, class, link)) {
3938       warning("Disabling -Xlog:perf+class+link since logging is turned off.");
3939       LogConfiguration::disable_tags(false, LOG_TAGS(perf, class, link));
3940       assert(!log_is_enabled(Info, perf, class, link), "sanity");
3941     }
3942   }
3943   if (FLAG_IS_DEFAULT(PerfDataMemorySize)) {
3944     if (ProfileVMLocks || ProfileVMCalls || ProfileRuntimeCalls) {
3945       FLAG_SET_DEFAULT(PerfDataMemorySize, 128*K); // reserve more space for extra perf counters
3946     }
3947   }
3948 
3949   if (FLAG_IS_CMDLINE(DiagnoseSyncOnValueBasedClasses)) {
3950     if (DiagnoseSyncOnValueBasedClasses == ObjectSynchronizer::LOG_WARNING && !log_is_enabled(Info, valuebasedclasses)) {
3951       LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(valuebasedclasses));
3952     }
3953   }
3954   return JNI_OK;
3955 }
3956 
3957 jint Arguments::adjust_after_os() {
3958   if (UseNUMA) {
3959     if (UseParallelGC) {
3960       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
3961          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
3962       }
3963     }
3964   }
3965   return JNI_OK;
3966 }
3967 
3968 int Arguments::PropertyList_count(SystemProperty* pl) {
3969   int count = 0;
3970   while(pl != nullptr) {
3971     count++;
3972     pl = pl->next();
3973   }
3974   return count;
3975 }
3976 
3977 // Return the number of readable properties.
3978 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
3979   int count = 0;
3980   while(pl != nullptr) {
3981     if (pl->readable()) {
3982       count++;
3983     }
3984     pl = pl->next();
3985   }
3986   return count;
3987 }
3988 
3989 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
3990   assert(key != nullptr, "just checking");
3991   SystemProperty* prop;
3992   for (prop = pl; prop != nullptr; prop = prop->next()) {
3993     if (strcmp(key, prop->key()) == 0) return prop->value();
3994   }
3995   return nullptr;
3996 }
3997 
3998 // Return the value of the requested property provided that it is a readable property.
3999 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4000   assert(key != nullptr, "just checking");
4001   SystemProperty* prop;
4002   // Return the property value if the keys match and the property is not internal or
4003   // it's the special internal property "jdk.boot.class.path.append".
4004   for (prop = pl; prop != nullptr; prop = prop->next()) {
4005     if (strcmp(key, prop->key()) == 0) {
4006       if (!prop->internal()) {
4007         return prop->value();
4008       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4009         return prop->value();
4010       } else {
4011         // Property is internal and not jdk.boot.class.path.append so return null.
4012         return nullptr;
4013       }
4014     }
4015   }
4016   return nullptr;
4017 }
4018 
4019 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4020   SystemProperty* p = *plist;
4021   if (p == nullptr) {
4022     *plist = new_p;
4023   } else {
4024     while (p->next() != nullptr) {
4025       p = p->next();
4026     }
4027     p->set_next(new_p);
4028   }
4029 }
4030 
4031 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4032                                  bool writeable, bool internal) {
4033   if (plist == nullptr)
4034     return;
4035 
4036   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4037   PropertyList_add(plist, new_p);
4038 }
4039 
4040 void Arguments::PropertyList_add(SystemProperty *element) {
4041   PropertyList_add(&_system_properties, element);
4042 }
4043 
4044 // This add maintains unique property key in the list.
4045 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4046                                         PropertyAppendable append, PropertyWriteable writeable,
4047                                         PropertyInternal internal) {
4048   if (plist == nullptr)
4049     return;
4050 
4051   // If property key exists and is writeable, then update with new value.
4052   // Trying to update a non-writeable property is silently ignored.
4053   SystemProperty* prop;
4054   for (prop = *plist; prop != nullptr; prop = prop->next()) {
4055     if (strcmp(k, prop->key()) == 0) {
4056       if (append == AppendProperty) {
4057         prop->append_writeable_value(v);
4058       } else {
4059         prop->set_writeable_value(v);
4060       }
4061       return;
4062     }
4063   }
4064 
4065   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4066 }
4067 
4068 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4069 // Returns true if all of the source pointed by src has been copied over to
4070 // the destination buffer pointed by buf. Otherwise, returns false.
4071 // Notes:
4072 // 1. If the length (buflen) of the destination buffer excluding the
4073 // null terminator character is not long enough for holding the expanded
4074 // pid characters, it also returns false instead of returning the partially
4075 // expanded one.
4076 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4077 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4078                                 char* buf, size_t buflen) {
4079   const char* p = src;
4080   char* b = buf;
4081   const char* src_end = &src[srclen];
4082   char* buf_end = &buf[buflen - 1];
4083 
4084   while (p < src_end && b < buf_end) {
4085     if (*p == '%') {
4086       switch (*(++p)) {
4087       case '%':         // "%%" ==> "%"
4088         *b++ = *p++;
4089         break;
4090       case 'p':  {       //  "%p" ==> current process id
4091         // buf_end points to the character before the last character so
4092         // that we could write '\0' to the end of the buffer.
4093         size_t buf_sz = buf_end - b + 1;
4094         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4095 
4096         // if jio_snprintf fails or the buffer is not long enough to hold
4097         // the expanded pid, returns false.
4098         if (ret < 0 || ret >= (int)buf_sz) {
4099           return false;
4100         } else {
4101           b += ret;
4102           assert(*b == '\0', "fail in copy_expand_pid");
4103           if (p == src_end && b == buf_end + 1) {
4104             // reach the end of the buffer.
4105             return true;
4106           }
4107         }
4108         p++;
4109         break;
4110       }
4111       default :
4112         *b++ = '%';
4113       }
4114     } else {
4115       *b++ = *p++;
4116     }
4117   }
4118   *b = '\0';
4119   return (p == src_end); // return false if not all of the source was copied
4120 }