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