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