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