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