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