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   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2478     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2479   }
2480 
2481 #ifndef SUPPORT_RESERVED_STACK_AREA
2482   if (StackReservedPages != 0) {
2483     FLAG_SET_CMDLINE(intx, StackReservedPages, 0);
2484     warning("Reserved Stack Area not supported on this platform");
2485   }
2486 #endif
2487 
2488   if (LINUX_ONLY(LP64_ONLY(false &&)) !FLAG_IS_DEFAULT(ValueTypePassFieldsAsArgs)) {
2489     FLAG_SET_CMDLINE(bool, ValueTypePassFieldsAsArgs, false);
2490     warning("ValueTypePassFieldsAsArgs is not supported on this platform");
2491   }
2492   return status;
2493 }
2494 
2495 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2496   const char* option_type) {
2497   if (ignore) return false;
2498 
2499   const char* spacer = " ";
2500   if (option_type == NULL) {
2501     option_type = ++spacer; // Set both to the empty string.
2502   }
2503 
2504   if (os::obsolete_option(option)) {
2505     jio_fprintf(defaultStream::error_stream(),
2506                 "Obsolete %s%soption: %s\n", option_type, spacer,
2507       option->optionString);
2508     return false;
2509   } else {
2510     jio_fprintf(defaultStream::error_stream(),
2511                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2512       option->optionString);
2513     return true;
2514   }
2515 }
2516 
2517 static const char* user_assertion_options[] = {
2518   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2519 };
2520 
2521 static const char* system_assertion_options[] = {
2522   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2523 };
2524 
2525 bool Arguments::parse_uintx(const char* value,
2526                             uintx* uintx_arg,
2527                             uintx min_size) {
2528 
2529   // Check the sign first since atomull() parses only unsigned values.
2530   bool value_is_positive = !(*value == '-');
2531 
2532   if (value_is_positive) {
2533     julong n;
2534     bool good_return = atomull(value, &n);
2535     if (good_return) {
2536       bool above_minimum = n >= min_size;
2537       bool value_is_too_large = n > max_uintx;
2538 
2539       if (above_minimum && !value_is_too_large) {
2540         *uintx_arg = n;
2541         return true;
2542       }
2543     }
2544   }
2545   return false;
2546 }
2547 
2548 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2549                                                   julong* long_arg,
2550                                                   julong min_size) {
2551   if (!atomull(s, long_arg)) return arg_unreadable;
2552   return check_memory_size(*long_arg, min_size);
2553 }
2554 
2555 // Parse JavaVMInitArgs structure
2556 
2557 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *java_tool_options_args,
2558                                    const JavaVMInitArgs *java_options_args,
2559                                    const JavaVMInitArgs *cmd_line_args) {
2560   // For components of the system classpath.
2561   SysClassPath scp(Arguments::get_sysclasspath());
2562   bool scp_assembly_required = false;
2563 
2564   // Save default settings for some mode flags
2565   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2566   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2567   Arguments::_ClipInlining             = ClipInlining;
2568   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2569   if (TieredCompilation) {
2570     Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2571     Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2572   }
2573 
2574   // Setup flags for mixed which is the default
2575   set_mode_flags(_mixed);
2576 
2577   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2578   // variable (if present).
2579   jint result = parse_each_vm_init_arg(
2580       java_tool_options_args, &scp, &scp_assembly_required, Flag::ENVIRON_VAR);
2581   if (result != JNI_OK) {
2582     return result;
2583   }
2584 
2585   // Parse args structure generated from the command line flags.
2586   result = parse_each_vm_init_arg(cmd_line_args, &scp, &scp_assembly_required,
2587                                   Flag::COMMAND_LINE);
2588   if (result != JNI_OK) {
2589     return result;
2590   }
2591 
2592   // Parse args structure generated from the _JAVA_OPTIONS environment
2593   // variable (if present) (mimics classic VM)
2594   result = parse_each_vm_init_arg(
2595       java_options_args, &scp, &scp_assembly_required, Flag::ENVIRON_VAR);
2596   if (result != JNI_OK) {
2597     return result;
2598   }
2599 
2600   // Do final processing now that all arguments have been parsed
2601   result = finalize_vm_init_args(&scp, scp_assembly_required);
2602   if (result != JNI_OK) {
2603     return result;
2604   }
2605 
2606   return JNI_OK;
2607 }
2608 
2609 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2610 // represents a valid JDWP agent.  is_path==true denotes that we
2611 // are dealing with -agentpath (case where name is a path), otherwise with
2612 // -agentlib
2613 bool valid_jdwp_agent(char *name, bool is_path) {
2614   char *_name;
2615   const char *_jdwp = "jdwp";
2616   size_t _len_jdwp, _len_prefix;
2617 
2618   if (is_path) {
2619     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2620       return false;
2621     }
2622 
2623     _name++;  // skip past last path separator
2624     _len_prefix = strlen(JNI_LIB_PREFIX);
2625 
2626     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2627       return false;
2628     }
2629 
2630     _name += _len_prefix;
2631     _len_jdwp = strlen(_jdwp);
2632 
2633     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2634       _name += _len_jdwp;
2635     }
2636     else {
2637       return false;
2638     }
2639 
2640     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2641       return false;
2642     }
2643 
2644     return true;
2645   }
2646 
2647   if (strcmp(name, _jdwp) == 0) {
2648     return true;
2649   }
2650 
2651   return false;
2652 }
2653 
2654 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2655                                        SysClassPath* scp_p,
2656                                        bool* scp_assembly_required_p,
2657                                        Flag::Flags origin) {
2658   // For match_option to return remaining or value part of option string
2659   const char* tail;
2660 
2661   // iterate over arguments
2662   for (int index = 0; index < args->nOptions; index++) {
2663     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2664 
2665     const JavaVMOption* option = args->options + index;
2666 
2667     if (!match_option(option, "-Djava.class.path", &tail) &&
2668         !match_option(option, "-Dsun.java.command", &tail) &&
2669         !match_option(option, "-Dsun.java.launcher", &tail)) {
2670 
2671         // add all jvm options to the jvm_args string. This string
2672         // is used later to set the java.vm.args PerfData string constant.
2673         // the -Djava.class.path and the -Dsun.java.command options are
2674         // omitted from jvm_args string as each have their own PerfData
2675         // string constant object.
2676         build_jvm_args(option->optionString);
2677     }
2678 
2679     // -verbose:[class/gc/jni]
2680     if (match_option(option, "-verbose", &tail)) {
2681       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2682         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(classload));
2683         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(classunload));
2684       } else if (!strcmp(tail, ":gc")) {
2685         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(gc));
2686       } else if (!strcmp(tail, ":jni")) {
2687         if (FLAG_SET_CMDLINE(bool, PrintJNIResolving, true) != Flag::SUCCESS) {
2688           return JNI_EINVAL;
2689         }
2690       }
2691     // -da / -ea / -disableassertions / -enableassertions
2692     // These accept an optional class/package name separated by a colon, e.g.,
2693     // -da:java.lang.Thread.
2694     } else if (match_option(option, user_assertion_options, &tail, true)) {
2695       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2696       if (*tail == '\0') {
2697         JavaAssertions::setUserClassDefault(enable);
2698       } else {
2699         assert(*tail == ':', "bogus match by match_option()");
2700         JavaAssertions::addOption(tail + 1, enable);
2701       }
2702     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2703     } else if (match_option(option, system_assertion_options, &tail, false)) {
2704       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2705       JavaAssertions::setSystemClassDefault(enable);
2706     // -bootclasspath:
2707     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2708       scp_p->reset_path(tail);
2709       *scp_assembly_required_p = true;
2710     // -bootclasspath/a:
2711     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2712       scp_p->add_suffix(tail);
2713       *scp_assembly_required_p = true;
2714     // -bootclasspath/p:
2715     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2716       scp_p->add_prefix(tail);
2717       *scp_assembly_required_p = true;
2718     // -Xrun
2719     } else if (match_option(option, "-Xrun", &tail)) {
2720       if (tail != NULL) {
2721         const char* pos = strchr(tail, ':');
2722         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2723         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2724         name[len] = '\0';
2725 
2726         char *options = NULL;
2727         if(pos != NULL) {
2728           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2729           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
2730         }
2731 #if !INCLUDE_JVMTI
2732         if (strcmp(name, "jdwp") == 0) {
2733           jio_fprintf(defaultStream::error_stream(),
2734             "Debugging agents are not supported in this VM\n");
2735           return JNI_ERR;
2736         }
2737 #endif // !INCLUDE_JVMTI
2738         add_init_library(name, options);
2739       }
2740     // -agentlib and -agentpath
2741     } else if (match_option(option, "-agentlib:", &tail) ||
2742           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2743       if(tail != NULL) {
2744         const char* pos = strchr(tail, '=');
2745         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2746         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2747         name[len] = '\0';
2748 
2749         char *options = NULL;
2750         if(pos != NULL) {
2751           options = os::strdup_check_oom(pos + 1, mtInternal);
2752         }
2753 #if !INCLUDE_JVMTI
2754         if (valid_jdwp_agent(name, is_absolute_path)) {
2755           jio_fprintf(defaultStream::error_stream(),
2756             "Debugging agents are not supported in this VM\n");
2757           return JNI_ERR;
2758         }
2759 #endif // !INCLUDE_JVMTI
2760         add_init_agent(name, options, is_absolute_path);
2761       }
2762     // -javaagent
2763     } else if (match_option(option, "-javaagent:", &tail)) {
2764 #if !INCLUDE_JVMTI
2765       jio_fprintf(defaultStream::error_stream(),
2766         "Instrumentation agents are not supported in this VM\n");
2767       return JNI_ERR;
2768 #else
2769       if(tail != NULL) {
2770         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtInternal), tail);
2771         add_init_agent("instrument", options, false);
2772       }
2773 #endif // !INCLUDE_JVMTI
2774     // -Xnoclassgc
2775     } else if (match_option(option, "-Xnoclassgc")) {
2776       if (FLAG_SET_CMDLINE(bool, ClassUnloading, false) != Flag::SUCCESS) {
2777         return JNI_EINVAL;
2778       }
2779     // -Xconcgc
2780     } else if (match_option(option, "-Xconcgc")) {
2781       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true) != Flag::SUCCESS) {
2782         return JNI_EINVAL;
2783       }
2784     // -Xnoconcgc
2785     } else if (match_option(option, "-Xnoconcgc")) {
2786       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false) != Flag::SUCCESS) {
2787         return JNI_EINVAL;
2788       }
2789     // -Xbatch
2790     } else if (match_option(option, "-Xbatch")) {
2791       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2792         return JNI_EINVAL;
2793       }
2794     // -Xmn for compatibility with other JVM vendors
2795     } else if (match_option(option, "-Xmn", &tail)) {
2796       julong long_initial_young_size = 0;
2797       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2798       if (errcode != arg_in_range) {
2799         jio_fprintf(defaultStream::error_stream(),
2800                     "Invalid initial young generation size: %s\n", option->optionString);
2801         describe_range_error(errcode);
2802         return JNI_EINVAL;
2803       }
2804       if (FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2805         return JNI_EINVAL;
2806       }
2807       if (FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2808         return JNI_EINVAL;
2809       }
2810     // -Xms
2811     } else if (match_option(option, "-Xms", &tail)) {
2812       julong long_initial_heap_size = 0;
2813       // an initial heap size of 0 means automatically determine
2814       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2815       if (errcode != arg_in_range) {
2816         jio_fprintf(defaultStream::error_stream(),
2817                     "Invalid initial heap size: %s\n", option->optionString);
2818         describe_range_error(errcode);
2819         return JNI_EINVAL;
2820       }
2821       set_min_heap_size((size_t)long_initial_heap_size);
2822       // Currently the minimum size and the initial heap sizes are the same.
2823       // Can be overridden with -XX:InitialHeapSize.
2824       if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size) != Flag::SUCCESS) {
2825         return JNI_EINVAL;
2826       }
2827     // -Xmx
2828     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2829       julong long_max_heap_size = 0;
2830       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2831       if (errcode != arg_in_range) {
2832         jio_fprintf(defaultStream::error_stream(),
2833                     "Invalid maximum heap size: %s\n", option->optionString);
2834         describe_range_error(errcode);
2835         return JNI_EINVAL;
2836       }
2837       if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size) != Flag::SUCCESS) {
2838         return JNI_EINVAL;
2839       }
2840     // Xmaxf
2841     } else if (match_option(option, "-Xmaxf", &tail)) {
2842       char* err;
2843       int maxf = (int)(strtod(tail, &err) * 100);
2844       if (*err != '\0' || *tail == '\0') {
2845         jio_fprintf(defaultStream::error_stream(),
2846                     "Bad max heap free percentage size: %s\n",
2847                     option->optionString);
2848         return JNI_EINVAL;
2849       } else {
2850         if (FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf) != Flag::SUCCESS) {
2851             return JNI_EINVAL;
2852         }
2853       }
2854     // Xminf
2855     } else if (match_option(option, "-Xminf", &tail)) {
2856       char* err;
2857       int minf = (int)(strtod(tail, &err) * 100);
2858       if (*err != '\0' || *tail == '\0') {
2859         jio_fprintf(defaultStream::error_stream(),
2860                     "Bad min heap free percentage size: %s\n",
2861                     option->optionString);
2862         return JNI_EINVAL;
2863       } else {
2864         if (FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf) != Flag::SUCCESS) {
2865           return JNI_EINVAL;
2866         }
2867       }
2868     // -Xss
2869     } else if (match_option(option, "-Xss", &tail)) {
2870       julong long_ThreadStackSize = 0;
2871       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2872       if (errcode != arg_in_range) {
2873         jio_fprintf(defaultStream::error_stream(),
2874                     "Invalid thread stack size: %s\n", option->optionString);
2875         describe_range_error(errcode);
2876         return JNI_EINVAL;
2877       }
2878       // Internally track ThreadStackSize in units of 1024 bytes.
2879       if (FLAG_SET_CMDLINE(intx, ThreadStackSize,
2880                        round_to((int)long_ThreadStackSize, K) / K) != Flag::SUCCESS) {
2881         return JNI_EINVAL;
2882       }
2883     // -Xoss, -Xsqnopause, -Xoptimize, -Xboundthreads, -Xusealtsigs
2884     } else if (match_option(option, "-Xoss", &tail) ||
2885                match_option(option, "-Xsqnopause") ||
2886                match_option(option, "-Xoptimize") ||
2887                match_option(option, "-Xboundthreads") ||
2888                match_option(option, "-Xusealtsigs")) {
2889       // All these options are deprecated in JDK 9 and will be removed in a future release
2890       char version[256];
2891       JDK_Version::jdk(9).to_string(version, sizeof(version));
2892       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2893     } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
2894       julong long_CodeCacheExpansionSize = 0;
2895       ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
2896       if (errcode != arg_in_range) {
2897         jio_fprintf(defaultStream::error_stream(),
2898                    "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
2899                    os::vm_page_size()/K);
2900         return JNI_EINVAL;
2901       }
2902       if (FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize) != Flag::SUCCESS) {
2903         return JNI_EINVAL;
2904       }
2905     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2906                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2907       julong long_ReservedCodeCacheSize = 0;
2908 
2909       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2910       if (errcode != arg_in_range) {
2911         jio_fprintf(defaultStream::error_stream(),
2912                     "Invalid maximum code cache size: %s.\n", option->optionString);
2913         return JNI_EINVAL;
2914       }
2915       if (FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != Flag::SUCCESS) {
2916         return JNI_EINVAL;
2917       }
2918       // -XX:NonNMethodCodeHeapSize=
2919     } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
2920       julong long_NonNMethodCodeHeapSize = 0;
2921 
2922       ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
2923       if (errcode != arg_in_range) {
2924         jio_fprintf(defaultStream::error_stream(),
2925                     "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
2926         return JNI_EINVAL;
2927       }
2928       if (FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize) != Flag::SUCCESS) {
2929         return JNI_EINVAL;
2930       }
2931       // -XX:ProfiledCodeHeapSize=
2932     } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
2933       julong long_ProfiledCodeHeapSize = 0;
2934 
2935       ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
2936       if (errcode != arg_in_range) {
2937         jio_fprintf(defaultStream::error_stream(),
2938                     "Invalid maximum profiled code heap size: %s.\n", option->optionString);
2939         return JNI_EINVAL;
2940       }
2941       if (FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize) != Flag::SUCCESS) {
2942         return JNI_EINVAL;
2943       }
2944       // -XX:NonProfiledCodeHeapSizee=
2945     } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
2946       julong long_NonProfiledCodeHeapSize = 0;
2947 
2948       ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
2949       if (errcode != arg_in_range) {
2950         jio_fprintf(defaultStream::error_stream(),
2951                     "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
2952         return JNI_EINVAL;
2953       }
2954       if (FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize) != Flag::SUCCESS) {
2955         return JNI_EINVAL;
2956       }
2957     // -green
2958     } else if (match_option(option, "-green")) {
2959       jio_fprintf(defaultStream::error_stream(),
2960                   "Green threads support not available\n");
2961           return JNI_EINVAL;
2962     // -native
2963     } else if (match_option(option, "-native")) {
2964           // HotSpot always uses native threads, ignore silently for compatibility
2965     // -Xrs
2966     } else if (match_option(option, "-Xrs")) {
2967           // Classic/EVM option, new functionality
2968       if (FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true) != Flag::SUCCESS) {
2969         return JNI_EINVAL;
2970       }
2971     // -Xprof
2972     } else if (match_option(option, "-Xprof")) {
2973 #if INCLUDE_FPROF
2974       _has_profile = true;
2975 #else // INCLUDE_FPROF
2976       jio_fprintf(defaultStream::error_stream(),
2977         "Flat profiling is not supported in this VM.\n");
2978       return JNI_ERR;
2979 #endif // INCLUDE_FPROF
2980     // -Xconcurrentio
2981     } else if (match_option(option, "-Xconcurrentio")) {
2982       if (FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true) != Flag::SUCCESS) {
2983         return JNI_EINVAL;
2984       }
2985       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2986         return JNI_EINVAL;
2987       }
2988       if (FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1) != Flag::SUCCESS) {
2989         return JNI_EINVAL;
2990       }
2991       if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
2992         return JNI_EINVAL;
2993       }
2994       if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
2995         return JNI_EINVAL;
2996       }
2997 
2998       // -Xinternalversion
2999     } else if (match_option(option, "-Xinternalversion")) {
3000       jio_fprintf(defaultStream::output_stream(), "%s\n",
3001                   VM_Version::internal_vm_info_string());
3002       vm_exit(0);
3003 #ifndef PRODUCT
3004     // -Xprintflags
3005     } else if (match_option(option, "-Xprintflags")) {
3006       CommandLineFlags::printFlags(tty, false);
3007       vm_exit(0);
3008 #endif
3009     // -D
3010     } else if (match_option(option, "-D", &tail)) {
3011       const char* value;
3012       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
3013             *value!= '\0' && strcmp(value, "\"\"") != 0) {
3014         // abort if -Djava.endorsed.dirs is set
3015         jio_fprintf(defaultStream::output_stream(),
3016           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
3017           "in modular form will be supported via the concept of upgradeable modules.\n", value);
3018         return JNI_EINVAL;
3019       }
3020       if (match_option(option, "-Djava.ext.dirs=", &value) &&
3021             *value != '\0' && strcmp(value, "\"\"") != 0) {
3022         // abort if -Djava.ext.dirs is set
3023         jio_fprintf(defaultStream::output_stream(),
3024           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
3025         return JNI_EINVAL;
3026       }
3027 
3028       if (!add_property(tail)) {
3029         return JNI_ENOMEM;
3030       }
3031       // Out of the box management support
3032       if (match_option(option, "-Dcom.sun.management", &tail)) {
3033 #if INCLUDE_MANAGEMENT
3034         if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
3035           return JNI_EINVAL;
3036         }
3037 #else
3038         jio_fprintf(defaultStream::output_stream(),
3039           "-Dcom.sun.management is not supported in this VM.\n");
3040         return JNI_ERR;
3041 #endif
3042       }
3043     // -Xint
3044     } else if (match_option(option, "-Xint")) {
3045           set_mode_flags(_int);
3046     // -Xmixed
3047     } else if (match_option(option, "-Xmixed")) {
3048           set_mode_flags(_mixed);
3049     // -Xcomp
3050     } else if (match_option(option, "-Xcomp")) {
3051       // for testing the compiler; turn off all flags that inhibit compilation
3052           set_mode_flags(_comp);
3053     // -Xshare:dump
3054     } else if (match_option(option, "-Xshare:dump")) {
3055       if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
3056         return JNI_EINVAL;
3057       }
3058       set_mode_flags(_int);     // Prevent compilation, which creates objects
3059     // -Xshare:on
3060     } else if (match_option(option, "-Xshare:on")) {
3061       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3062         return JNI_EINVAL;
3063       }
3064       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3065         return JNI_EINVAL;
3066       }
3067     // -Xshare:auto
3068     } else if (match_option(option, "-Xshare:auto")) {
3069       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3070         return JNI_EINVAL;
3071       }
3072       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3073         return JNI_EINVAL;
3074       }
3075     // -Xshare:off
3076     } else if (match_option(option, "-Xshare:off")) {
3077       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
3078         return JNI_EINVAL;
3079       }
3080       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3081         return JNI_EINVAL;
3082       }
3083     // -Xverify
3084     } else if (match_option(option, "-Xverify", &tail)) {
3085       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
3086         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
3087           return JNI_EINVAL;
3088         }
3089         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3090           return JNI_EINVAL;
3091         }
3092       } else if (strcmp(tail, ":remote") == 0) {
3093         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3094           return JNI_EINVAL;
3095         }
3096         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3097           return JNI_EINVAL;
3098         }
3099       } else if (strcmp(tail, ":none") == 0) {
3100         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3101           return JNI_EINVAL;
3102         }
3103         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
3104           return JNI_EINVAL;
3105         }
3106       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3107         return JNI_EINVAL;
3108       }
3109     // -Xdebug
3110     } else if (match_option(option, "-Xdebug")) {
3111       // note this flag has been used, then ignore
3112       set_xdebug_mode(true);
3113     // -Xnoagent
3114     } else if (match_option(option, "-Xnoagent")) {
3115       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3116     } else if (match_option(option, "-Xloggc:", &tail)) {
3117       // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
3118       log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
3119       _gc_log_filename = os::strdup_check_oom(tail);
3120     } else if (match_option(option, "-Xlog", &tail)) {
3121       bool ret = false;
3122       if (strcmp(tail, ":help") == 0) {
3123         LogConfiguration::print_command_line_help(defaultStream::output_stream());
3124         vm_exit(0);
3125       } else if (strcmp(tail, ":disable") == 0) {
3126         LogConfiguration::disable_logging();
3127         ret = true;
3128       } else if (*tail == '\0') {
3129         ret = LogConfiguration::parse_command_line_arguments();
3130         assert(ret, "-Xlog without arguments should never fail to parse");
3131       } else if (*tail == ':') {
3132         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
3133       }
3134       if (ret == false) {
3135         jio_fprintf(defaultStream::error_stream(),
3136                     "Invalid -Xlog option '-Xlog%s'\n",
3137                     tail);
3138         return JNI_EINVAL;
3139       }
3140     // JNI hooks
3141     } else if (match_option(option, "-Xcheck", &tail)) {
3142       if (!strcmp(tail, ":jni")) {
3143 #if !INCLUDE_JNI_CHECK
3144         warning("JNI CHECKING is not supported in this VM");
3145 #else
3146         CheckJNICalls = true;
3147 #endif // INCLUDE_JNI_CHECK
3148       } else if (is_bad_option(option, args->ignoreUnrecognized,
3149                                      "check")) {
3150         return JNI_EINVAL;
3151       }
3152     } else if (match_option(option, "vfprintf")) {
3153       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3154     } else if (match_option(option, "exit")) {
3155       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3156     } else if (match_option(option, "abort")) {
3157       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3158     // -XX:+AggressiveHeap
3159     } else if (match_option(option, "-XX:+AggressiveHeap")) {
3160       jint result = set_aggressive_heap_flags();
3161       if (result != JNI_OK) {
3162           return result;
3163       }
3164     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
3165     // and the last option wins.
3166     } else if (match_option(option, "-XX:+NeverTenure")) {
3167       if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
3168         return JNI_EINVAL;
3169       }
3170       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3171         return JNI_EINVAL;
3172       }
3173       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
3174         return JNI_EINVAL;
3175       }
3176     } else if (match_option(option, "-XX:+AlwaysTenure")) {
3177       if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3178         return JNI_EINVAL;
3179       }
3180       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3181         return JNI_EINVAL;
3182       }
3183       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
3184         return JNI_EINVAL;
3185       }
3186     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
3187       uintx max_tenuring_thresh = 0;
3188       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
3189         jio_fprintf(defaultStream::error_stream(),
3190                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
3191         return JNI_EINVAL;
3192       }
3193 
3194       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
3195         return JNI_EINVAL;
3196       }
3197 
3198       if (MaxTenuringThreshold == 0) {
3199         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3200           return JNI_EINVAL;
3201         }
3202         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3203           return JNI_EINVAL;
3204         }
3205       } else {
3206         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3207           return JNI_EINVAL;
3208         }
3209         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3210           return JNI_EINVAL;
3211         }
3212       }
3213     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3214       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
3215         return JNI_EINVAL;
3216       }
3217       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
3218         return JNI_EINVAL;
3219       }
3220     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3221       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
3222         return JNI_EINVAL;
3223       }
3224       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3225         return JNI_EINVAL;
3226       }
3227     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3228 #if defined(DTRACE_ENABLED)
3229       if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3230         return JNI_EINVAL;
3231       }
3232       if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3233         return JNI_EINVAL;
3234       }
3235       if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3236         return JNI_EINVAL;
3237       }
3238       if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3239         return JNI_EINVAL;
3240       }
3241 #else // defined(DTRACE_ENABLED)
3242       jio_fprintf(defaultStream::error_stream(),
3243                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3244       return JNI_EINVAL;
3245 #endif // defined(DTRACE_ENABLED)
3246 #ifdef ASSERT
3247     } else if (match_option(option, "-XX:+FullGCALot")) {
3248       if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3249         return JNI_EINVAL;
3250       }
3251       // disable scavenge before parallel mark-compact
3252       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3253         return JNI_EINVAL;
3254       }
3255 #endif
3256 #if !INCLUDE_MANAGEMENT
3257     } else if (match_option(option, "-XX:+ManagementServer")) {
3258         jio_fprintf(defaultStream::error_stream(),
3259           "ManagementServer is not supported in this VM.\n");
3260         return JNI_ERR;
3261 #endif // INCLUDE_MANAGEMENT
3262     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3263       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
3264       // already been handled
3265       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
3266           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
3267         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3268           return JNI_EINVAL;
3269         }
3270       }
3271     // Unknown option
3272     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3273       return JNI_ERR;
3274     }
3275   }
3276 
3277   // PrintSharedArchiveAndExit will turn on
3278   //   -Xshare:on
3279   //   -Xlog:classpath=info
3280   if (PrintSharedArchiveAndExit) {
3281     if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3282       return JNI_EINVAL;
3283     }
3284     if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3285       return JNI_EINVAL;
3286     }
3287     LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(classpath));
3288   }
3289 
3290   // Change the default value for flags  which have different default values
3291   // when working with older JDKs.
3292 #ifdef LINUX
3293  if (JDK_Version::current().compare_major(6) <= 0 &&
3294       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3295     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3296   }
3297 #endif // LINUX
3298   fix_appclasspath();
3299   return JNI_OK;
3300 }
3301 
3302 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3303 //
3304 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3305 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3306 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3307 // path is treated as the current directory.
3308 //
3309 // This causes problems with CDS, which requires that all directories specified in the classpath
3310 // must be empty. In most cases, applications do NOT want to load classes from the current
3311 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3312 // scripts compatible with CDS.
3313 void Arguments::fix_appclasspath() {
3314   if (IgnoreEmptyClassPaths) {
3315     const char separator = *os::path_separator();
3316     const char* src = _java_class_path->value();
3317 
3318     // skip over all the leading empty paths
3319     while (*src == separator) {
3320       src ++;
3321     }
3322 
3323     char* copy = os::strdup_check_oom(src, mtInternal);
3324 
3325     // trim all trailing empty paths
3326     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3327       *tail = '\0';
3328     }
3329 
3330     char from[3] = {separator, separator, '\0'};
3331     char to  [2] = {separator, '\0'};
3332     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3333       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3334       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3335     }
3336 
3337     _java_class_path->set_value(copy);
3338     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3339   }
3340 }
3341 
3342 static bool has_jar_files(const char* directory) {
3343   DIR* dir = os::opendir(directory);
3344   if (dir == NULL) return false;
3345 
3346   struct dirent *entry;
3347   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
3348   bool hasJarFile = false;
3349   while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3350     const char* name = entry->d_name;
3351     const char* ext = name + strlen(name) - 4;
3352     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3353   }
3354   FREE_C_HEAP_ARRAY(char, dbuf);
3355   os::closedir(dir);
3356   return hasJarFile ;
3357 }
3358 
3359 static int check_non_empty_dirs(const char* path) {
3360   const char separator = *os::path_separator();
3361   const char* const end = path + strlen(path);
3362   int nonEmptyDirs = 0;
3363   while (path < end) {
3364     const char* tmp_end = strchr(path, separator);
3365     if (tmp_end == NULL) {
3366       if (has_jar_files(path)) {
3367         nonEmptyDirs++;
3368         jio_fprintf(defaultStream::output_stream(),
3369           "Non-empty directory: %s\n", path);
3370       }
3371       path = end;
3372     } else {
3373       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
3374       memcpy(dirpath, path, tmp_end - path);
3375       dirpath[tmp_end - path] = '\0';
3376       if (has_jar_files(dirpath)) {
3377         nonEmptyDirs++;
3378         jio_fprintf(defaultStream::output_stream(),
3379           "Non-empty directory: %s\n", dirpath);
3380       }
3381       FREE_C_HEAP_ARRAY(char, dirpath);
3382       path = tmp_end + 1;
3383     }
3384   }
3385   return nonEmptyDirs;
3386 }
3387 
3388 jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
3389   // check if the default lib/endorsed directory exists; if so, error
3390   char path[JVM_MAXPATHLEN];
3391   const char* fileSep = os::file_separator();
3392   sprintf(path, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3393 
3394   if (CheckEndorsedAndExtDirs) {
3395     int nonEmptyDirs = 0;
3396     // check endorsed directory
3397     nonEmptyDirs += check_non_empty_dirs(path);
3398     // check the extension directories
3399     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3400     if (nonEmptyDirs > 0) {
3401       return JNI_ERR;
3402     }
3403   }
3404 
3405   DIR* dir = os::opendir(path);
3406   if (dir != NULL) {
3407     jio_fprintf(defaultStream::output_stream(),
3408       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3409       "in modular form will be supported via the concept of upgradeable modules.\n");
3410     os::closedir(dir);
3411     return JNI_ERR;
3412   }
3413 
3414   sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3415   dir = os::opendir(path);
3416   if (dir != NULL) {
3417     jio_fprintf(defaultStream::output_stream(),
3418       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3419       "Use -classpath instead.\n.");
3420     os::closedir(dir);
3421     return JNI_ERR;
3422   }
3423 
3424   if (scp_assembly_required) {
3425     // Assemble the bootclasspath elements into the final path.
3426     char *combined_path = scp_p->combined_path();
3427     Arguments::set_sysclasspath(combined_path);
3428     FREE_C_HEAP_ARRAY(char, combined_path);
3429   }
3430 
3431   // This must be done after all arguments have been processed.
3432   // java_compiler() true means set to "NONE" or empty.
3433   if (java_compiler() && !xdebug_mode()) {
3434     // For backwards compatibility, we switch to interpreted mode if
3435     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3436     // not specified.
3437     set_mode_flags(_int);
3438   }
3439 
3440   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3441   // but like -Xint, leave compilation thresholds unaffected.
3442   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3443   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3444     set_mode_flags(_int);
3445   }
3446 
3447   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3448   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3449     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3450   }
3451 
3452 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3453   // Don't degrade server performance for footprint
3454   if (FLAG_IS_DEFAULT(UseLargePages) &&
3455       MaxHeapSize < LargePageHeapSizeThreshold) {
3456     // No need for large granularity pages w/small heaps.
3457     // Note that large pages are enabled/disabled for both the
3458     // Java heap and the code cache.
3459     FLAG_SET_DEFAULT(UseLargePages, false);
3460   }
3461 
3462 #elif defined(COMPILER2)
3463   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3464     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3465   }
3466 #endif
3467 
3468 #ifndef TIERED
3469   // Tiered compilation is undefined.
3470   UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
3471 #endif
3472 
3473   // If we are running in a headless jre, force java.awt.headless property
3474   // to be true unless the property has already been set.
3475   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3476   if (os::is_headless_jre()) {
3477     const char* headless = Arguments::get_property("java.awt.headless");
3478     if (headless == NULL) {
3479       const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3480       if (headless_env == NULL) {
3481         if (!add_property("java.awt.headless=true")) {
3482           return JNI_ENOMEM;
3483         }
3484       } else {
3485         char buffer[256];
3486         jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3487         if (!add_property(buffer)) {
3488           return JNI_ENOMEM;
3489         }
3490       }
3491     }
3492   }
3493 
3494   if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3495     // CMS can only be used with ParNew
3496     FLAG_SET_ERGO(bool, UseParNewGC, true);
3497   }
3498 
3499   if (!check_vm_args_consistency()) {
3500     return JNI_ERR;
3501   }
3502 
3503   return JNI_OK;
3504 }
3505 
3506 // Helper class for controlling the lifetime of JavaVMInitArgs
3507 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3508 // deleted on the destruction of the ScopedVMInitArgs object.
3509 class ScopedVMInitArgs : public StackObj {
3510  private:
3511   JavaVMInitArgs _args;
3512   char*          _container_name;
3513   bool           _is_set;
3514   char*          _vm_options_file_arg;
3515 
3516  public:
3517   ScopedVMInitArgs(const char *container_name) {
3518     _args.version = JNI_VERSION_1_2;
3519     _args.nOptions = 0;
3520     _args.options = NULL;
3521     _args.ignoreUnrecognized = false;
3522     _container_name = (char *)container_name;
3523     _is_set = false;
3524     _vm_options_file_arg = NULL;
3525   }
3526 
3527   // Populates the JavaVMInitArgs object represented by this
3528   // ScopedVMInitArgs object with the arguments in options.  The
3529   // allocated memory is deleted by the destructor.  If this method
3530   // returns anything other than JNI_OK, then this object is in a
3531   // partially constructed state, and should be abandoned.
3532   jint set_args(GrowableArray<JavaVMOption>* options) {
3533     _is_set = true;
3534     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3535         JavaVMOption, options->length(), mtInternal);
3536     if (options_arr == NULL) {
3537       return JNI_ENOMEM;
3538     }
3539     _args.options = options_arr;
3540 
3541     for (int i = 0; i < options->length(); i++) {
3542       options_arr[i] = options->at(i);
3543       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3544       if (options_arr[i].optionString == NULL) {
3545         // Rely on the destructor to do cleanup.
3546         _args.nOptions = i;
3547         return JNI_ENOMEM;
3548       }
3549     }
3550 
3551     _args.nOptions = options->length();
3552     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3553     return JNI_OK;
3554   }
3555 
3556   JavaVMInitArgs* get()             { return &_args; }
3557   char* container_name()            { return _container_name; }
3558   bool  is_set()                    { return _is_set; }
3559   bool  found_vm_options_file_arg() { return _vm_options_file_arg != NULL; }
3560   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3561 
3562   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3563     if (_vm_options_file_arg != NULL) {
3564       os::free(_vm_options_file_arg);
3565     }
3566     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3567   }
3568 
3569   ~ScopedVMInitArgs() {
3570     if (_vm_options_file_arg != NULL) {
3571       os::free(_vm_options_file_arg);
3572     }
3573     if (_args.options == NULL) return;
3574     for (int i = 0; i < _args.nOptions; i++) {
3575       os::free(_args.options[i].optionString);
3576     }
3577     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3578   }
3579 
3580   // Insert options into this option list, to replace option at
3581   // vm_options_file_pos (-XX:VMOptionsFile)
3582   jint insert(const JavaVMInitArgs* args,
3583               const JavaVMInitArgs* args_to_insert,
3584               const int vm_options_file_pos) {
3585     assert(_args.options == NULL, "shouldn't be set yet");
3586     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3587     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3588 
3589     int length = args->nOptions + args_to_insert->nOptions - 1;
3590     GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal)
3591               GrowableArray<JavaVMOption>(length, true);    // Construct new option array
3592     for (int i = 0; i < args->nOptions; i++) {
3593       if (i == vm_options_file_pos) {
3594         // insert the new options starting at the same place as the
3595         // -XX:VMOptionsFile option
3596         for (int j = 0; j < args_to_insert->nOptions; j++) {
3597           options->push(args_to_insert->options[j]);
3598         }
3599       } else {
3600         options->push(args->options[i]);
3601       }
3602     }
3603     // make into options array
3604     jint result = set_args(options);
3605     delete options;
3606     return result;
3607   }
3608 };
3609 
3610 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3611   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3612 }
3613 
3614 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3615   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3616 }
3617 
3618 jint Arguments::parse_options_environment_variable(const char* name,
3619                                                    ScopedVMInitArgs* vm_args) {
3620   char *buffer = ::getenv(name);
3621 
3622   // Don't check this environment variable if user has special privileges
3623   // (e.g. unix su command).
3624   if (buffer == NULL || os::have_special_privileges()) {
3625     return JNI_OK;
3626   }
3627 
3628   if ((buffer = os::strdup(buffer)) == NULL) {
3629     return JNI_ENOMEM;
3630   }
3631 
3632   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3633 
3634   os::free(buffer);
3635   return retcode;
3636 }
3637 
3638 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3639   // read file into buffer
3640   int fd = ::open(file_name, O_RDONLY);
3641   if (fd < 0) {
3642     jio_fprintf(defaultStream::error_stream(),
3643                 "Could not open options file '%s'\n",
3644                 file_name);
3645     return JNI_ERR;
3646   }
3647 
3648   struct stat stbuf;
3649   int retcode = os::stat(file_name, &stbuf);
3650   if (retcode != 0) {
3651     jio_fprintf(defaultStream::error_stream(),
3652                 "Could not stat options file '%s'\n",
3653                 file_name);
3654     os::close(fd);
3655     return JNI_ERR;
3656   }
3657 
3658   if (stbuf.st_size == 0) {
3659     // tell caller there is no option data and that is ok
3660     os::close(fd);
3661     return JNI_OK;
3662   }
3663 
3664   // '+ 1' for NULL termination even with max bytes
3665   size_t bytes_alloc = stbuf.st_size + 1;
3666 
3667   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtInternal);
3668   if (NULL == buf) {
3669     jio_fprintf(defaultStream::error_stream(),
3670                 "Could not allocate read buffer for options file parse\n");
3671     os::close(fd);
3672     return JNI_ENOMEM;
3673   }
3674 
3675   memset(buf, 0, bytes_alloc);
3676 
3677   // Fill buffer
3678   // Use ::read() instead of os::read because os::read()
3679   // might do a thread state transition
3680   // and it is too early for that here
3681 
3682   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3683   os::close(fd);
3684   if (bytes_read < 0) {
3685     FREE_C_HEAP_ARRAY(char, buf);
3686     jio_fprintf(defaultStream::error_stream(),
3687                 "Could not read options file '%s'\n", file_name);
3688     return JNI_ERR;
3689   }
3690 
3691   if (bytes_read == 0) {
3692     // tell caller there is no option data and that is ok
3693     FREE_C_HEAP_ARRAY(char, buf);
3694     return JNI_OK;
3695   }
3696 
3697   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3698 
3699   FREE_C_HEAP_ARRAY(char, buf);
3700   return retcode;
3701 }
3702 
3703 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3704   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3705 
3706   // some pointers to help with parsing
3707   char *buffer_end = buffer + buf_len;
3708   char *opt_hd = buffer;
3709   char *wrt = buffer;
3710   char *rd = buffer;
3711 
3712   // parse all options
3713   while (rd < buffer_end) {
3714     // skip leading white space from the input string
3715     while (rd < buffer_end && isspace(*rd)) {
3716       rd++;
3717     }
3718 
3719     if (rd >= buffer_end) {
3720       break;
3721     }
3722 
3723     // Remember this is where we found the head of the token.
3724     opt_hd = wrt;
3725 
3726     // Tokens are strings of non white space characters separated
3727     // by one or more white spaces.
3728     while (rd < buffer_end && !isspace(*rd)) {
3729       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3730         int quote = *rd;                    // matching quote to look for
3731         rd++;                               // don't copy open quote
3732         while (rd < buffer_end && *rd != quote) {
3733                                             // include everything (even spaces)
3734                                             // up until the close quote
3735           *wrt++ = *rd++;                   // copy to option string
3736         }
3737 
3738         if (rd < buffer_end) {
3739           rd++;                             // don't copy close quote
3740         } else {
3741                                             // did not see closing quote
3742           jio_fprintf(defaultStream::error_stream(),
3743                       "Unmatched quote in %s\n", name);
3744           delete options;
3745           return JNI_ERR;
3746         }
3747       } else {
3748         *wrt++ = *rd++;                     // copy to option string
3749       }
3750     }
3751 
3752     // steal a white space character and set it to NULL
3753     *wrt++ = '\0';
3754     // We now have a complete token
3755 
3756     JavaVMOption option;
3757     option.optionString = opt_hd;
3758     option.extraInfo = NULL;
3759 
3760     options->append(option);                // Fill in option
3761 
3762     rd++;  // Advance to next character
3763   }
3764 
3765   // Fill out JavaVMInitArgs structure.
3766   jint status = vm_args->set_args(options);
3767 
3768   delete options;
3769   return status;
3770 }
3771 
3772 void Arguments::set_shared_spaces_flags() {
3773   if (DumpSharedSpaces) {
3774     if (RequireSharedSpaces) {
3775       warning("Cannot dump shared archive while using shared archive");
3776     }
3777     UseSharedSpaces = false;
3778 #ifdef _LP64
3779     if (!UseCompressedOops || !UseCompressedClassPointers) {
3780       vm_exit_during_initialization(
3781         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3782     }
3783   } else {
3784     if (!UseCompressedOops || !UseCompressedClassPointers) {
3785       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3786     }
3787 #endif
3788   }
3789 }
3790 
3791 #if !INCLUDE_ALL_GCS
3792 static void force_serial_gc() {
3793   FLAG_SET_DEFAULT(UseSerialGC, true);
3794   UNSUPPORTED_GC_OPTION(UseG1GC);
3795   UNSUPPORTED_GC_OPTION(UseParallelGC);
3796   UNSUPPORTED_GC_OPTION(UseParallelOldGC);
3797   UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
3798   UNSUPPORTED_GC_OPTION(UseParNewGC);
3799 }
3800 #endif // INCLUDE_ALL_GCS
3801 
3802 // Sharing support
3803 // Construct the path to the archive
3804 static char* get_shared_archive_path() {
3805   char *shared_archive_path;
3806   if (SharedArchiveFile == NULL) {
3807     char jvm_path[JVM_MAXPATHLEN];
3808     os::jvm_path(jvm_path, sizeof(jvm_path));
3809     char *end = strrchr(jvm_path, *os::file_separator());
3810     if (end != NULL) *end = '\0';
3811     size_t jvm_path_len = strlen(jvm_path);
3812     size_t file_sep_len = strlen(os::file_separator());
3813     const size_t len = jvm_path_len + file_sep_len + 20;
3814     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtInternal);
3815     if (shared_archive_path != NULL) {
3816       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3817         jvm_path, os::file_separator());
3818     }
3819   } else {
3820     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtInternal);
3821   }
3822   return shared_archive_path;
3823 }
3824 
3825 #ifndef PRODUCT
3826 // Determine whether LogVMOutput should be implicitly turned on.
3827 static bool use_vm_log() {
3828   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3829       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3830       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3831       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3832       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3833     return true;
3834   }
3835 
3836 #ifdef COMPILER1
3837   if (PrintC1Statistics) {
3838     return true;
3839   }
3840 #endif // COMPILER1
3841 
3842 #ifdef COMPILER2
3843   if (PrintOptoAssembly || PrintOptoStatistics) {
3844     return true;
3845   }
3846 #endif // COMPILER2
3847 
3848   return false;
3849 }
3850 
3851 #endif // PRODUCT
3852 
3853 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3854   for (int index = 0; index < args->nOptions; index++) {
3855     const JavaVMOption* option = args->options + index;
3856     const char* tail;
3857     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3858       return true;
3859     }
3860   }
3861   return false;
3862 }
3863 
3864 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3865                                        const char* vm_options_file,
3866                                        const int vm_options_file_pos,
3867                                        ScopedVMInitArgs* vm_options_file_args,
3868                                        ScopedVMInitArgs* args_out) {
3869   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
3870   if (code != JNI_OK) {
3871     return code;
3872   }
3873 
3874   if (vm_options_file_args->get()->nOptions < 1) {
3875     return JNI_OK;
3876   }
3877 
3878   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
3879     jio_fprintf(defaultStream::error_stream(),
3880                 "A VM options file may not refer to a VM options file. "
3881                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
3882                 "options file '%s' in options container '%s' is an error.\n",
3883                 vm_options_file_args->vm_options_file_arg(),
3884                 vm_options_file_args->container_name());
3885     return JNI_EINVAL;
3886   }
3887 
3888   return args_out->insert(args, vm_options_file_args->get(),
3889                           vm_options_file_pos);
3890 }
3891 
3892 // Expand -XX:VMOptionsFile found in args_in as needed.
3893 // mod_args and args_out parameters may return values as needed.
3894 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
3895                                             ScopedVMInitArgs* mod_args,
3896                                             JavaVMInitArgs** args_out) {
3897   jint code = match_special_option_and_act(args_in, mod_args);
3898   if (code != JNI_OK) {
3899     return code;
3900   }
3901 
3902   if (mod_args->is_set()) {
3903     // args_in contains -XX:VMOptionsFile and mod_args contains the
3904     // original options from args_in along with the options expanded
3905     // from the VMOptionsFile. Return a short-hand to the caller.
3906     *args_out = mod_args->get();
3907   } else {
3908     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
3909   }
3910   return JNI_OK;
3911 }
3912 
3913 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3914                                              ScopedVMInitArgs* args_out) {
3915   // Remaining part of option string
3916   const char* tail;
3917   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
3918 
3919   for (int index = 0; index < args->nOptions; index++) {
3920     const JavaVMOption* option = args->options + index;
3921     if (ArgumentsExt::process_options(option)) {
3922       continue;
3923     }
3924     if (match_option(option, "-XX:Flags=", &tail)) {
3925       Arguments::set_jvm_flags_file(tail);
3926       continue;
3927     }
3928     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3929       if (vm_options_file_args.found_vm_options_file_arg()) {
3930         jio_fprintf(defaultStream::error_stream(),
3931                     "The option '%s' is already specified in the options "
3932                     "container '%s' so the specification of '%s' in the "
3933                     "same options container is an error.\n",
3934                     vm_options_file_args.vm_options_file_arg(),
3935                     vm_options_file_args.container_name(),
3936                     option->optionString);
3937         return JNI_EINVAL;
3938       }
3939       vm_options_file_args.set_vm_options_file_arg(option->optionString);
3940       // If there's a VMOptionsFile, parse that
3941       jint code = insert_vm_options_file(args, tail, index,
3942                                          &vm_options_file_args, args_out);
3943       if (code != JNI_OK) {
3944         return code;
3945       }
3946       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
3947       if (args_out->is_set()) {
3948         // The VMOptions file inserted some options so switch 'args'
3949         // to the new set of options, and continue processing which
3950         // preserves "last option wins" semantics.
3951         args = args_out->get();
3952         // The first option from the VMOptionsFile replaces the
3953         // current option.  So we back track to process the
3954         // replacement option.
3955         index--;
3956       }
3957       continue;
3958     }
3959     if (match_option(option, "-XX:+PrintVMOptions")) {
3960       PrintVMOptions = true;
3961       continue;
3962     }
3963     if (match_option(option, "-XX:-PrintVMOptions")) {
3964       PrintVMOptions = false;
3965       continue;
3966     }
3967     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3968       IgnoreUnrecognizedVMOptions = true;
3969       continue;
3970     }
3971     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3972       IgnoreUnrecognizedVMOptions = false;
3973       continue;
3974     }
3975     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3976       CommandLineFlags::printFlags(tty, false);
3977       vm_exit(0);
3978     }
3979     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3980 #if INCLUDE_NMT
3981       // The launcher did not setup nmt environment variable properly.
3982       if (!MemTracker::check_launcher_nmt_support(tail)) {
3983         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3984       }
3985 
3986       // Verify if nmt option is valid.
3987       if (MemTracker::verify_nmt_option()) {
3988         // Late initialization, still in single-threaded mode.
3989         if (MemTracker::tracking_level() >= NMT_summary) {
3990           MemTracker::init();
3991         }
3992       } else {
3993         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3994       }
3995       continue;
3996 #else
3997       jio_fprintf(defaultStream::error_stream(),
3998         "Native Memory Tracking is not supported in this VM\n");
3999       return JNI_ERR;
4000 #endif
4001     }
4002 
4003 #ifndef PRODUCT
4004     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
4005       CommandLineFlags::printFlags(tty, true);
4006       vm_exit(0);
4007     }
4008 #endif
4009   }
4010   return JNI_OK;
4011 }
4012 
4013 static void print_options(const JavaVMInitArgs *args) {
4014   const char* tail;
4015   for (int index = 0; index < args->nOptions; index++) {
4016     const JavaVMOption *option = args->options + index;
4017     if (match_option(option, "-XX:", &tail)) {
4018       logOption(tail);
4019     }
4020   }
4021 }
4022 
4023 bool Arguments::handle_deprecated_print_gc_flags() {
4024   if (PrintGC) {
4025     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
4026   }
4027   if (PrintGCDetails) {
4028     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
4029   }
4030 
4031   if (_gc_log_filename != NULL) {
4032     // -Xloggc was used to specify a filename
4033     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
4034     return  LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, NULL);
4035   } else if (PrintGC || PrintGCDetails) {
4036     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
4037   }
4038   return true;
4039 }
4040 
4041 // Parse entry point called from JNI_CreateJavaVM
4042 
4043 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
4044   assert(verify_special_jvm_flags(), "deprecated and obsolete flag table inconsistent");
4045 
4046   // Initialize ranges and constraints
4047   CommandLineFlagRangeList::init();
4048   CommandLineFlagConstraintList::init();
4049 
4050   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
4051   const char* hotspotrc = ".hotspotrc";
4052   bool settings_file_specified = false;
4053   bool needs_hotspotrc_warning = false;
4054   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4055   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
4056 
4057   // Pointers to current working set of containers
4058   JavaVMInitArgs* cur_cmd_args;
4059   JavaVMInitArgs* cur_java_options_args;
4060   JavaVMInitArgs* cur_java_tool_options_args;
4061 
4062   // Containers for modified/expanded options
4063   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
4064   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4065   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
4066 
4067 
4068   jint code =
4069       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
4070   if (code != JNI_OK) {
4071     return code;
4072   }
4073 
4074   code = parse_java_options_environment_variable(&initial_java_options_args);
4075   if (code != JNI_OK) {
4076     return code;
4077   }
4078 
4079   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
4080                                      &mod_java_tool_options_args,
4081                                      &cur_java_tool_options_args);
4082   if (code != JNI_OK) {
4083     return code;
4084   }
4085 
4086   code = expand_vm_options_as_needed(initial_cmd_args,
4087                                      &mod_cmd_args,
4088                                      &cur_cmd_args);
4089   if (code != JNI_OK) {
4090     return code;
4091   }
4092 
4093   code = expand_vm_options_as_needed(initial_java_options_args.get(),
4094                                      &mod_java_options_args,
4095                                      &cur_java_options_args);
4096   if (code != JNI_OK) {
4097     return code;
4098   }
4099 
4100   const char* flags_file = Arguments::get_jvm_flags_file();
4101   settings_file_specified = (flags_file != NULL);
4102 
4103   if (IgnoreUnrecognizedVMOptions) {
4104     cur_cmd_args->ignoreUnrecognized = true;
4105     cur_java_tool_options_args->ignoreUnrecognized = true;
4106     cur_java_options_args->ignoreUnrecognized = true;
4107   }
4108 
4109   // Parse specified settings file
4110   if (settings_file_specified) {
4111     if (!process_settings_file(flags_file, true,
4112                                cur_cmd_args->ignoreUnrecognized)) {
4113       return JNI_EINVAL;
4114     }
4115   } else {
4116 #ifdef ASSERT
4117     // Parse default .hotspotrc settings file
4118     if (!process_settings_file(".hotspotrc", false,
4119                                cur_cmd_args->ignoreUnrecognized)) {
4120       return JNI_EINVAL;
4121     }
4122 #else
4123     struct stat buf;
4124     if (os::stat(hotspotrc, &buf) == 0) {
4125       needs_hotspotrc_warning = true;
4126     }
4127 #endif
4128   }
4129 
4130   if (PrintVMOptions) {
4131     print_options(cur_java_tool_options_args);
4132     print_options(cur_cmd_args);
4133     print_options(cur_java_options_args);
4134   }
4135 
4136   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
4137   jint result = parse_vm_init_args(cur_java_tool_options_args,
4138                                    cur_java_options_args,
4139                                    cur_cmd_args);
4140 
4141   if (result != JNI_OK) {
4142     return result;
4143   }
4144 
4145   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
4146   SharedArchivePath = get_shared_archive_path();
4147   if (SharedArchivePath == NULL) {
4148     return JNI_ENOMEM;
4149   }
4150 
4151   // Set up VerifySharedSpaces
4152   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
4153     VerifySharedSpaces = true;
4154   }
4155 
4156   // Delay warning until here so that we've had a chance to process
4157   // the -XX:-PrintWarnings flag
4158   if (needs_hotspotrc_warning) {
4159     warning("%s file is present but has been ignored.  "
4160             "Run with -XX:Flags=%s to load the file.",
4161             hotspotrc, hotspotrc);
4162   }
4163 
4164 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
4165   UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
4166 #endif
4167 
4168   ArgumentsExt::report_unsupported_options();
4169 
4170 #ifndef PRODUCT
4171   if (TraceBytecodesAt != 0) {
4172     TraceBytecodes = true;
4173   }
4174   if (CountCompiledCalls) {
4175     if (UseCounterDecay) {
4176       warning("UseCounterDecay disabled because CountCalls is set");
4177       UseCounterDecay = false;
4178     }
4179   }
4180 #endif // PRODUCT
4181 
4182   if (ScavengeRootsInCode == 0) {
4183     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4184       warning("Forcing ScavengeRootsInCode non-zero");
4185     }
4186     ScavengeRootsInCode = 1;
4187   }
4188 
4189   if (!handle_deprecated_print_gc_flags()) {
4190     return JNI_EINVAL;
4191   }
4192 
4193   // Set object alignment values.
4194   set_object_alignment();
4195 
4196 #if !INCLUDE_ALL_GCS
4197   force_serial_gc();
4198 #endif // INCLUDE_ALL_GCS
4199 #if !INCLUDE_CDS
4200   if (DumpSharedSpaces || RequireSharedSpaces) {
4201     jio_fprintf(defaultStream::error_stream(),
4202       "Shared spaces are not supported in this VM\n");
4203     return JNI_ERR;
4204   }
4205   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
4206     warning("Shared spaces are not supported in this VM");
4207     FLAG_SET_DEFAULT(UseSharedSpaces, false);
4208     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
4209   }
4210   no_shared_spaces("CDS Disabled");
4211 #endif // INCLUDE_CDS
4212 
4213   return JNI_OK;
4214 }
4215 
4216 jint Arguments::apply_ergo() {
4217 
4218   // Set flags based on ergonomics.
4219   set_ergonomics_flags();
4220 
4221   set_shared_spaces_flags();
4222 
4223   // Check the GC selections again.
4224   if (!check_gc_consistency()) {
4225     return JNI_EINVAL;
4226   }
4227 
4228   if (TieredCompilation) {
4229     set_tiered_flags();
4230   } else {
4231     int max_compilation_policy_choice = 1;
4232 #ifdef COMPILER2
4233     max_compilation_policy_choice = 2;
4234 #endif
4235     // Check if the policy is valid.
4236     if (CompilationPolicyChoice >= max_compilation_policy_choice) {
4237       vm_exit_during_initialization(
4238         "Incompatible compilation policy selected", NULL);
4239     }
4240     // Scale CompileThreshold
4241     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
4242     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
4243       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
4244     }
4245   }
4246 
4247 #ifdef COMPILER2
4248 #ifndef PRODUCT
4249   if (PrintIdealGraphLevel > 0) {
4250     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
4251   }
4252 #endif
4253 #endif
4254 
4255   // Set heap size based on available physical memory
4256   set_heap_size();
4257 
4258   ArgumentsExt::set_gc_specific_flags();
4259 
4260   // Initialize Metaspace flags and alignments
4261   Metaspace::ergo_initialize();
4262 
4263   // Set bytecode rewriting flags
4264   set_bytecode_flags();
4265 
4266   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
4267   jint code = set_aggressive_opts_flags();
4268   if (code != JNI_OK) {
4269     return code;
4270   }
4271 
4272   // Turn off biased locking for locking debug mode flags,
4273   // which are subtly different from each other but neither works with
4274   // biased locking
4275   if (UseHeavyMonitors
4276 #ifdef COMPILER1
4277       || !UseFastLocking
4278 #endif // COMPILER1
4279 #if INCLUDE_JVMCI
4280       || !JVMCIUseFastLocking
4281 #endif
4282     ) {
4283     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4284       // flag set to true on command line; warn the user that they
4285       // can't enable biased locking here
4286       warning("Biased Locking is not supported with locking debug flags"
4287               "; ignoring UseBiasedLocking flag." );
4288     }
4289     UseBiasedLocking = false;
4290   }
4291 
4292 #ifdef CC_INTERP
4293   // Clear flags not supported on zero.
4294   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4295   FLAG_SET_DEFAULT(UseBiasedLocking, false);
4296   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4297   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4298 #endif // CC_INTERP
4299 
4300 #ifdef COMPILER2
4301   if (!EliminateLocks) {
4302     EliminateNestedLocks = false;
4303   }
4304   if (!Inline) {
4305     IncrementalInline = false;
4306   }
4307 #ifndef PRODUCT
4308   if (!IncrementalInline) {
4309     AlwaysIncrementalInline = false;
4310   }
4311 #endif
4312   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
4313     // nothing to use the profiling, turn if off
4314     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
4315   }
4316 #endif
4317 
4318   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4319     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4320     DebugNonSafepoints = true;
4321   }
4322 
4323   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4324     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4325   }
4326 
4327 #ifndef PRODUCT
4328   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4329     if (use_vm_log()) {
4330       LogVMOutput = true;
4331     }
4332   }
4333 #endif // PRODUCT
4334 
4335   if (PrintCommandLineFlags) {
4336     CommandLineFlags::printSetFlags(tty);
4337   }
4338 
4339   // Apply CPU specific policy for the BiasedLocking
4340   if (UseBiasedLocking) {
4341     if (!VM_Version::use_biased_locking() &&
4342         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4343       UseBiasedLocking = false;
4344     }
4345   }
4346 #ifdef COMPILER2
4347   if (!UseBiasedLocking || EmitSync != 0) {
4348     UseOptoBiasInlining = false;
4349   }
4350 #endif
4351 
4352 #ifndef TARGET_ARCH_x86 // Some macroasm missing at this stage
4353   EnableExtraSuper = false;
4354 #endif
4355 
4356   return JNI_OK;
4357 }
4358 
4359 jint Arguments::adjust_after_os() {
4360   if (UseNUMA) {
4361     if (UseParallelGC || UseParallelOldGC) {
4362       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4363          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4364       }
4365     }
4366     // UseNUMAInterleaving is set to ON for all collectors and
4367     // platforms when UseNUMA is set to ON. NUMA-aware collectors
4368     // such as the parallel collector for Linux and Solaris will
4369     // interleave old gen and survivor spaces on top of NUMA
4370     // allocation policy for the eden space.
4371     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4372     // all platforms and ParallelGC on Windows will interleave all
4373     // of the heap spaces across NUMA nodes.
4374     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4375       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4376     }
4377   }
4378   return JNI_OK;
4379 }
4380 
4381 int Arguments::PropertyList_count(SystemProperty* pl) {
4382   int count = 0;
4383   while(pl != NULL) {
4384     count++;
4385     pl = pl->next();
4386   }
4387   return count;
4388 }
4389 
4390 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4391   assert(key != NULL, "just checking");
4392   SystemProperty* prop;
4393   for (prop = pl; prop != NULL; prop = prop->next()) {
4394     if (strcmp(key, prop->key()) == 0) return prop->value();
4395   }
4396   return NULL;
4397 }
4398 
4399 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4400   int count = 0;
4401   const char* ret_val = NULL;
4402 
4403   while(pl != NULL) {
4404     if(count >= index) {
4405       ret_val = pl->key();
4406       break;
4407     }
4408     count++;
4409     pl = pl->next();
4410   }
4411 
4412   return ret_val;
4413 }
4414 
4415 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4416   int count = 0;
4417   char* ret_val = NULL;
4418 
4419   while(pl != NULL) {
4420     if(count >= index) {
4421       ret_val = pl->value();
4422       break;
4423     }
4424     count++;
4425     pl = pl->next();
4426   }
4427 
4428   return ret_val;
4429 }
4430 
4431 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4432   SystemProperty* p = *plist;
4433   if (p == NULL) {
4434     *plist = new_p;
4435   } else {
4436     while (p->next() != NULL) {
4437       p = p->next();
4438     }
4439     p->set_next(new_p);
4440   }
4441 }
4442 
4443 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v) {
4444   if (plist == NULL)
4445     return;
4446 
4447   SystemProperty* new_p = new SystemProperty(k, v, true);
4448   PropertyList_add(plist, new_p);
4449 }
4450 
4451 void Arguments::PropertyList_add(SystemProperty *element) {
4452   PropertyList_add(&_system_properties, element);
4453 }
4454 
4455 // This add maintains unique property key in the list.
4456 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v, jboolean append) {
4457   if (plist == NULL)
4458     return;
4459 
4460   // If property key exist then update with new value.
4461   SystemProperty* prop;
4462   for (prop = *plist; prop != NULL; prop = prop->next()) {
4463     if (strcmp(k, prop->key()) == 0) {
4464       if (append) {
4465         prop->append_value(v);
4466       } else {
4467         prop->set_value(v);
4468       }
4469       return;
4470     }
4471   }
4472 
4473   PropertyList_add(plist, k, v);
4474 }
4475 
4476 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4477 // Returns true if all of the source pointed by src has been copied over to
4478 // the destination buffer pointed by buf. Otherwise, returns false.
4479 // Notes:
4480 // 1. If the length (buflen) of the destination buffer excluding the
4481 // NULL terminator character is not long enough for holding the expanded
4482 // pid characters, it also returns false instead of returning the partially
4483 // expanded one.
4484 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4485 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4486                                 char* buf, size_t buflen) {
4487   const char* p = src;
4488   char* b = buf;
4489   const char* src_end = &src[srclen];
4490   char* buf_end = &buf[buflen - 1];
4491 
4492   while (p < src_end && b < buf_end) {
4493     if (*p == '%') {
4494       switch (*(++p)) {
4495       case '%':         // "%%" ==> "%"
4496         *b++ = *p++;
4497         break;
4498       case 'p':  {       //  "%p" ==> current process id
4499         // buf_end points to the character before the last character so
4500         // that we could write '\0' to the end of the buffer.
4501         size_t buf_sz = buf_end - b + 1;
4502         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4503 
4504         // if jio_snprintf fails or the buffer is not long enough to hold
4505         // the expanded pid, returns false.
4506         if (ret < 0 || ret >= (int)buf_sz) {
4507           return false;
4508         } else {
4509           b += ret;
4510           assert(*b == '\0', "fail in copy_expand_pid");
4511           if (p == src_end && b == buf_end + 1) {
4512             // reach the end of the buffer.
4513             return true;
4514           }
4515         }
4516         p++;
4517         break;
4518       }
4519       default :
4520         *b++ = '%';
4521       }
4522     } else {
4523       *b++ = *p++;
4524     }
4525   }
4526   *b = '\0';
4527   return (p == src_end); // return false if not all of the source was copied
4528 }