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