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