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