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