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