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