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