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