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