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