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