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