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