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