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