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