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