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