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