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