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