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