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