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