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