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