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