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