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

4142   return JNI_OK;
4143 }
4144 
4145 jint Arguments::adjust_after_os() {
4146   if (UseNUMA) {
4147     if (UseParallelGC) {
4148       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4149          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4150       }
4151     }
4152   }
4153   return JNI_OK;
4154 }
4155 
4156 int Arguments::PropertyList_count(SystemProperty* pl) {
4157   int count = 0;
4158   while(pl != NULL) {
4159     count++;
4160     pl = pl->next();
4161   }
4162   return count;
4163 }
4164 
4165 // Return the number of readable properties.
4166 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
4167   int count = 0;
4168   while(pl != NULL) {
4169     if (pl->is_readable()) {
4170       count++;
4171     }
4172     pl = pl->next();
4173   }
4174   return count;
4175 }
4176 
4177 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4178   assert(key != NULL, "just checking");
4179   SystemProperty* prop;
4180   for (prop = pl; prop != NULL; prop = prop->next()) {
4181     if (strcmp(key, prop->key()) == 0) return prop->value();
4182   }
4183   return NULL;
4184 }
4185 
4186 // Return the value of the requested property provided that it is a readable property.
4187 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4188   assert(key != NULL, "just checking");
4189   SystemProperty* prop;
4190   // Return the property value if the keys match and the property is not internal or
4191   // it's the special internal property "jdk.boot.class.path.append".
4192   for (prop = pl; prop != NULL; prop = prop->next()) {
4193     if (strcmp(key, prop->key()) == 0) {
4194       if (!prop->internal()) {
4195         return prop->value();
4196       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4197         return prop->value();
4198       } else {
4199         // Property is internal and not jdk.boot.class.path.append so return NULL.
4200         return NULL;
4201       }
4202     }
4203   }
4204   return NULL;
4205 }
4206 
4207 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4208   int count = 0;
4209   const char* ret_val = NULL;
4210 
4211   while(pl != NULL) {
4212     if(count >= index) {
4213       ret_val = pl->key();
4214       break;
4215     }
4216     count++;
4217     pl = pl->next();
4218   }
4219 
4220   return ret_val;
4221 }
4222 
4223 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4224   int count = 0;
4225   char* ret_val = NULL;
4226 
4227   while(pl != NULL) {
4228     if(count >= index) {
4229       ret_val = pl->value();
4230       break;
4231     }
4232     count++;
4233     pl = pl->next();
4234   }
4235 
4236   return ret_val;
4237 }
4238 
4239 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4240   SystemProperty* p = *plist;
4241   if (p == NULL) {
4242     *plist = new_p;
4243   } else {
4244     while (p->next() != NULL) {
4245       p = p->next();
4246     }
4247     p->set_next(new_p);
4248   }
4249 }
4250 
4251 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4252                                  bool writeable, bool internal) {
4253   if (plist == NULL)
4254     return;
4255 
4256   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4257   PropertyList_add(plist, new_p);
4258 }
4259 
4260 void Arguments::PropertyList_add(SystemProperty *element) {
4261   PropertyList_add(&_system_properties, element);
4262 }
4263 
4264 // This add maintains unique property key in the list.
4265 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4266                                         PropertyAppendable append, PropertyWriteable writeable,
4267                                         PropertyInternal internal) {
4268   if (plist == NULL)
4269     return;
4270 
4271   // If property key exists and is writeable, then update with new value.
4272   // Trying to update a non-writeable property is silently ignored.
4273   SystemProperty* prop;
4274   for (prop = *plist; prop != NULL; prop = prop->next()) {
4275     if (strcmp(k, prop->key()) == 0) {
4276       if (append == AppendProperty) {
4277         prop->append_writeable_value(v);
4278       } else {
4279         prop->set_writeable_value(v);
4280       }
4281       return;
4282     }
4283   }
4284 
4285   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4286 }
4287 
4288 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4289 // Returns true if all of the source pointed by src has been copied over to
4290 // the destination buffer pointed by buf. Otherwise, returns false.
4291 // Notes:
4292 // 1. If the length (buflen) of the destination buffer excluding the
4293 // NULL terminator character is not long enough for holding the expanded
4294 // pid characters, it also returns false instead of returning the partially
4295 // expanded one.
4296 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4297 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4298                                 char* buf, size_t buflen) {
4299   const char* p = src;
4300   char* b = buf;
4301   const char* src_end = &src[srclen];
4302   char* buf_end = &buf[buflen - 1];
4303 
4304   while (p < src_end && b < buf_end) {
4305     if (*p == '%') {
4306       switch (*(++p)) {
4307       case '%':         // "%%" ==> "%"
4308         *b++ = *p++;
4309         break;
4310       case 'p':  {       //  "%p" ==> current process id
4311         // buf_end points to the character before the last character so
4312         // that we could write '\0' to the end of the buffer.
4313         size_t buf_sz = buf_end - b + 1;
4314         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4315 
4316         // if jio_snprintf fails or the buffer is not long enough to hold
4317         // the expanded pid, returns false.
4318         if (ret < 0 || ret >= (int)buf_sz) {
4319           return false;
4320         } else {
4321           b += ret;
4322           assert(*b == '\0', "fail in copy_expand_pid");
4323           if (p == src_end && b == buf_end + 1) {
4324             // reach the end of the buffer.
4325             return true;
4326           }
4327         }
4328         p++;
4329         break;
4330       }
4331       default :
4332         *b++ = '%';
4333       }
4334     } else {
4335       *b++ = *p++;
4336     }
4337   }
4338   *b = '\0';
4339   return (p == src_end); // return false if not all of the source was copied
4340 }
--- EOF ---