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   if (!ClassUnloading) {
1691     FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
1692     FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
1693   }
1694 
1695   log_trace(gc)("MarkStackSize: %uk  MarkStackSizeMax: %uk", (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1696 }
1697 #endif // INCLUDE_ALL_GCS
1698 
1699 void set_object_alignment() {
1700   // Object alignment.
1701   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1702   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1703   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1704   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1705   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1706   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1707 
1708   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1709   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1710 
1711   // Oop encoding heap max
1712   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1713 
1714   if (SurvivorAlignmentInBytes == 0) {
1715     SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1716   }
1717 
1718 #if INCLUDE_ALL_GCS
1719   // Set CMS global values
1720   CompactibleFreeListSpace::set_cms_values();
1721 #endif // INCLUDE_ALL_GCS
1722 }
1723 
1724 size_t Arguments::max_heap_for_compressed_oops() {
1725   // Avoid sign flip.
1726   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1727   // We need to fit both the NULL page and the heap into the memory budget, while
1728   // keeping alignment constraints of the heap. To guarantee the latter, as the
1729   // NULL page is located before the heap, we pad the NULL page to the conservative
1730   // maximum alignment that the GC may ever impose upon the heap.
1731   size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
1732                                                         _conservative_max_heap_alignment);
1733 
1734   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1735   NOT_LP64(ShouldNotReachHere(); return 0);
1736 }
1737 
1738 bool Arguments::should_auto_select_low_pause_collector() {
1739   if (UseAutoGCSelectPolicy &&
1740       !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
1741       (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
1742     log_trace(gc)("Automatic selection of the low pause collector based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
1743     return true;
1744   }
1745   return false;
1746 }
1747 
1748 void Arguments::set_use_compressed_oops() {
1749 #ifndef ZERO
1750 #ifdef _LP64
1751   // MaxHeapSize is not set up properly at this point, but
1752   // the only value that can override MaxHeapSize if we are
1753   // to use UseCompressedOops is InitialHeapSize.
1754   size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1755 
1756   if (max_heap_size <= max_heap_for_compressed_oops()) {
1757 #if !defined(COMPILER1) || defined(TIERED)
1758     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1759       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1760     }
1761 #endif
1762   } else {
1763     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1764       warning("Max heap size too large for Compressed Oops");
1765       FLAG_SET_DEFAULT(UseCompressedOops, false);
1766       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1767     }
1768   }
1769 #endif // _LP64
1770 #endif // ZERO
1771 }
1772 
1773 
1774 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1775 // set_use_compressed_oops().
1776 void Arguments::set_use_compressed_klass_ptrs() {
1777 #ifndef ZERO
1778 #ifdef _LP64
1779   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1780   if (!UseCompressedOops) {
1781     if (UseCompressedClassPointers) {
1782       warning("UseCompressedClassPointers requires UseCompressedOops");
1783     }
1784     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1785   } else {
1786     // Turn on UseCompressedClassPointers too
1787     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1788       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1789     }
1790     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1791     if (UseCompressedClassPointers) {
1792       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1793         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1794         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1795       }
1796     }
1797   }
1798 #endif // _LP64
1799 #endif // !ZERO
1800 }
1801 
1802 void Arguments::set_conservative_max_heap_alignment() {
1803   // The conservative maximum required alignment for the heap is the maximum of
1804   // the alignments imposed by several sources: any requirements from the heap
1805   // itself, the collector policy and the maximum page size we may run the VM
1806   // with.
1807   size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
1808 #if INCLUDE_ALL_GCS
1809   if (UseParallelGC) {
1810     heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
1811   } else if (UseG1GC) {
1812     heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
1813   }
1814 #endif // INCLUDE_ALL_GCS
1815   _conservative_max_heap_alignment = MAX4(heap_alignment,
1816                                           (size_t)os::vm_allocation_granularity(),
1817                                           os::max_page_size(),
1818                                           CollectorPolicy::compute_heap_alignment());
1819 }
1820 
1821 bool Arguments::gc_selected() {
1822 #if INCLUDE_ALL_GCS
1823   return UseSerialGC || UseParallelGC || UseParallelOldGC || UseConcMarkSweepGC || UseG1GC;
1824 #else
1825   return UseSerialGC;
1826 #endif // INCLUDE_ALL_GCS
1827 }
1828 
1829 void Arguments::select_gc_ergonomically() {
1830 #if INCLUDE_ALL_GCS
1831   if (os::is_server_class_machine()) {
1832     if (should_auto_select_low_pause_collector()) {
1833       FLAG_SET_ERGO_IF_DEFAULT(bool, UseConcMarkSweepGC, true);
1834     } else {
1835       FLAG_SET_ERGO_IF_DEFAULT(bool, UseG1GC, true);
1836     }
1837   } else {
1838     FLAG_SET_ERGO_IF_DEFAULT(bool, UseSerialGC, true);
1839   }
1840 #else
1841   UNSUPPORTED_OPTION(UseG1GC);
1842   UNSUPPORTED_OPTION(UseParallelGC);
1843   UNSUPPORTED_OPTION(UseParallelOldGC);
1844   UNSUPPORTED_OPTION(UseConcMarkSweepGC);
1845   UNSUPPORTED_OPTION(UseParNewGC);
1846   FLAG_SET_ERGO_IF_DEFAULT(bool, UseSerialGC, true);
1847 #endif // INCLUDE_ALL_GCS
1848 }
1849 
1850 void Arguments::select_gc() {
1851   if (!gc_selected()) {
1852     select_gc_ergonomically();
1853     if (!gc_selected()) {
1854       vm_exit_during_initialization("Garbage collector not selected (default collector explicitly disabled)", NULL);
1855     }
1856   }
1857 }
1858 
1859 void Arguments::set_ergonomics_flags() {
1860   select_gc();
1861 
1862 #if defined(COMPILER2) || INCLUDE_JVMCI
1863   // Shared spaces work fine with other GCs but causes bytecode rewriting
1864   // to be disabled, which hurts interpreter performance and decreases
1865   // server performance.  When -server is specified, keep the default off
1866   // unless it is asked for.  Future work: either add bytecode rewriting
1867   // at link time, or rewrite bytecodes in non-shared methods.
1868   if (!DumpSharedSpaces && !RequireSharedSpaces &&
1869       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1870     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1871   }
1872 #endif
1873 
1874   set_conservative_max_heap_alignment();
1875 
1876 #ifndef ZERO
1877 #ifdef _LP64
1878   set_use_compressed_oops();
1879 
1880   // set_use_compressed_klass_ptrs() must be called after calling
1881   // set_use_compressed_oops().
1882   set_use_compressed_klass_ptrs();
1883 
1884   // Also checks that certain machines are slower with compressed oops
1885   // in vm_version initialization code.
1886 #endif // _LP64
1887 #endif // !ZERO
1888 
1889   CodeCacheExtensions::set_ergonomics_flags();
1890 }
1891 
1892 void Arguments::set_parallel_gc_flags() {
1893   assert(UseParallelGC || UseParallelOldGC, "Error");
1894   // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1895   if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1896     FLAG_SET_DEFAULT(UseParallelOldGC, true);
1897   }
1898   FLAG_SET_DEFAULT(UseParallelGC, true);
1899 
1900   // If no heap maximum was requested explicitly, use some reasonable fraction
1901   // of the physical memory, up to a maximum of 1GB.
1902   FLAG_SET_DEFAULT(ParallelGCThreads,
1903                    Abstract_VM_Version::parallel_worker_threads());
1904   if (ParallelGCThreads == 0) {
1905     jio_fprintf(defaultStream::error_stream(),
1906         "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1907     vm_exit(1);
1908   }
1909 
1910   if (UseAdaptiveSizePolicy) {
1911     // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1912     // unless the user actually sets these flags.
1913     if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1914       FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1915     }
1916     if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1917       FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1918     }
1919   }
1920 
1921   // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1922   // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1923   // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1924   // See CR 6362902 for details.
1925   if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1926     if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1927        FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1928     }
1929     if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1930       FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1931     }
1932   }
1933 
1934   if (UseParallelOldGC) {
1935     // Par compact uses lower default values since they are treated as
1936     // minimums.  These are different defaults because of the different
1937     // interpretation and are not ergonomically set.
1938     if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1939       FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1940     }
1941   }
1942 }
1943 
1944 void Arguments::set_g1_gc_flags() {
1945   assert(UseG1GC, "Error");
1946 #if defined(COMPILER1) || INCLUDE_JVMCI
1947   FastTLABRefill = false;
1948 #endif
1949   FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1950   if (ParallelGCThreads == 0) {
1951     assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
1952     vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1953   }
1954 
1955 #if INCLUDE_ALL_GCS
1956   if (FLAG_IS_DEFAULT(G1ConcRefinementThreads)) {
1957     FLAG_SET_ERGO(uint, G1ConcRefinementThreads, ParallelGCThreads);
1958   }
1959 #endif
1960 
1961   // MarkStackSize will be set (if it hasn't been set by the user)
1962   // when concurrent marking is initialized.
1963   // Its value will be based upon the number of parallel marking threads.
1964   // But we do set the maximum mark stack size here.
1965   if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1966     FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1967   }
1968 
1969   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1970     // In G1, we want the default GC overhead goal to be higher than
1971     // it is for PS, or the heap might be expanded too aggressively.
1972     // We set it here to ~8%.
1973     FLAG_SET_DEFAULT(GCTimeRatio, 12);
1974   }
1975 
1976   // Below, we might need to calculate the pause time interval based on
1977   // the pause target. When we do so we are going to give G1 maximum
1978   // flexibility and allow it to do pauses when it needs to. So, we'll
1979   // arrange that the pause interval to be pause time target + 1 to
1980   // ensure that a) the pause time target is maximized with respect to
1981   // the pause interval and b) we maintain the invariant that pause
1982   // time target < pause interval. If the user does not want this
1983   // maximum flexibility, they will have to set the pause interval
1984   // explicitly.
1985 
1986   if (FLAG_IS_DEFAULT(MaxGCPauseMillis)) {
1987     // The default pause time target in G1 is 200ms
1988     FLAG_SET_DEFAULT(MaxGCPauseMillis, 200);
1989   }
1990 
1991   // Then, if the interval parameter was not set, set it according to
1992   // the pause time target (this will also deal with the case when the
1993   // pause time target is the default value).
1994   if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
1995     FLAG_SET_DEFAULT(GCPauseIntervalMillis, MaxGCPauseMillis + 1);
1996   }
1997 
1998   log_trace(gc)("MarkStackSize: %uk  MarkStackSizeMax: %uk", (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1999 }
2000 
2001 void Arguments::set_gc_specific_flags() {
2002 #if INCLUDE_ALL_GCS
2003   // Set per-collector flags
2004   if (UseParallelGC || UseParallelOldGC) {
2005     set_parallel_gc_flags();
2006   } else if (UseConcMarkSweepGC) {
2007     set_cms_and_parnew_gc_flags();
2008   } else if (UseG1GC) {
2009     set_g1_gc_flags();
2010   }
2011   if (AssumeMP && !UseSerialGC) {
2012     if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
2013       warning("If the number of processors is expected to increase from one, then"
2014               " you should configure the number of parallel GC threads appropriately"
2015               " using -XX:ParallelGCThreads=N");
2016     }
2017   }
2018   if (MinHeapFreeRatio == 100) {
2019     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
2020     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
2021   }
2022 #endif // INCLUDE_ALL_GCS
2023 }
2024 
2025 julong Arguments::limit_by_allocatable_memory(julong limit) {
2026   julong max_allocatable;
2027   julong result = limit;
2028   if (os::has_allocatable_memory_limit(&max_allocatable)) {
2029     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
2030   }
2031   return result;
2032 }
2033 
2034 // Use static initialization to get the default before parsing
2035 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
2036 
2037 void Arguments::set_heap_size() {
2038   const julong phys_mem =
2039     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
2040                             : (julong)MaxRAM;
2041 
2042   // If the maximum heap size has not been set with -Xmx,
2043   // then set it as fraction of the size of physical memory,
2044   // respecting the maximum and minimum sizes of the heap.
2045   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2046     julong reasonable_max = phys_mem / MaxRAMFraction;
2047 
2048     if (phys_mem <= MaxHeapSize * MinRAMFraction) {
2049       // Small physical memory, so use a minimum fraction of it for the heap
2050       reasonable_max = phys_mem / MinRAMFraction;
2051     } else {
2052       // Not-small physical memory, so require a heap at least
2053       // as large as MaxHeapSize
2054       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
2055     }
2056     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
2057       // Limit the heap size to ErgoHeapSizeLimit
2058       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
2059     }
2060     if (UseCompressedOops) {
2061       // Limit the heap size to the maximum possible when using compressed oops
2062       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
2063 
2064       // HeapBaseMinAddress can be greater than default but not less than.
2065       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
2066         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
2067           // matches compressed oops printing flags
2068           log_debug(gc, heap, coops)("HeapBaseMinAddress must be at least " SIZE_FORMAT
2069                                      " (" SIZE_FORMAT "G) which is greater than value given " SIZE_FORMAT,
2070                                      DefaultHeapBaseMinAddress,
2071                                      DefaultHeapBaseMinAddress/G,
2072                                      HeapBaseMinAddress);
2073           FLAG_SET_ERGO(size_t, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
2074         }
2075       }
2076 
2077       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
2078         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
2079         // but it should be not less than default MaxHeapSize.
2080         max_coop_heap -= HeapBaseMinAddress;
2081       }
2082       reasonable_max = MIN2(reasonable_max, max_coop_heap);
2083     }
2084     reasonable_max = limit_by_allocatable_memory(reasonable_max);
2085 
2086     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
2087       // An initial heap size was specified on the command line,
2088       // so be sure that the maximum size is consistent.  Done
2089       // after call to limit_by_allocatable_memory because that
2090       // method might reduce the allocation size.
2091       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
2092     }
2093 
2094     log_trace(gc, heap)("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
2095     FLAG_SET_ERGO(size_t, MaxHeapSize, (size_t)reasonable_max);
2096   }
2097 
2098   // If the minimum or initial heap_size have not been set or requested to be set
2099   // ergonomically, set them accordingly.
2100   if (InitialHeapSize == 0 || min_heap_size() == 0) {
2101     julong reasonable_minimum = (julong)(OldSize + NewSize);
2102 
2103     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
2104 
2105     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
2106 
2107     if (InitialHeapSize == 0) {
2108       julong reasonable_initial = phys_mem / InitialRAMFraction;
2109 
2110       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
2111       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
2112 
2113       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
2114 
2115       log_trace(gc, heap)("  Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
2116       FLAG_SET_ERGO(size_t, InitialHeapSize, (size_t)reasonable_initial);
2117     }
2118     // If the minimum heap size has not been set (via -Xms),
2119     // synchronize with InitialHeapSize to avoid errors with the default value.
2120     if (min_heap_size() == 0) {
2121       set_min_heap_size(MIN2((size_t)reasonable_minimum, InitialHeapSize));
2122       log_trace(gc, heap)("  Minimum heap size " SIZE_FORMAT, min_heap_size());
2123     }
2124   }
2125 }
2126 
2127 // This option inspects the machine and attempts to set various
2128 // parameters to be optimal for long-running, memory allocation
2129 // intensive jobs.  It is intended for machines with large
2130 // amounts of cpu and memory.
2131 jint Arguments::set_aggressive_heap_flags() {
2132   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
2133   // VM, but we may not be able to represent the total physical memory
2134   // available (like having 8gb of memory on a box but using a 32bit VM).
2135   // Thus, we need to make sure we're using a julong for intermediate
2136   // calculations.
2137   julong initHeapSize;
2138   julong total_memory = os::physical_memory();
2139 
2140   if (total_memory < (julong) 256 * M) {
2141     jio_fprintf(defaultStream::error_stream(),
2142             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
2143     vm_exit(1);
2144   }
2145 
2146   // The heap size is half of available memory, or (at most)
2147   // all of possible memory less 160mb (leaving room for the OS
2148   // when using ISM).  This is the maximum; because adaptive sizing
2149   // is turned on below, the actual space used may be smaller.
2150 
2151   initHeapSize = MIN2(total_memory / (julong) 2,
2152           total_memory - (julong) 160 * M);
2153 
2154   initHeapSize = limit_by_allocatable_memory(initHeapSize);
2155 
2156   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2157     if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, initHeapSize) != Flag::SUCCESS) {
2158       return JNI_EINVAL;
2159     }
2160     if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, initHeapSize) != Flag::SUCCESS) {
2161       return JNI_EINVAL;
2162     }
2163     // Currently the minimum size and the initial heap sizes are the same.
2164     set_min_heap_size(initHeapSize);
2165   }
2166   if (FLAG_IS_DEFAULT(NewSize)) {
2167     // Make the young generation 3/8ths of the total heap.
2168     if (FLAG_SET_CMDLINE(size_t, NewSize,
2169             ((julong) MaxHeapSize / (julong) 8) * (julong) 3) != Flag::SUCCESS) {
2170       return JNI_EINVAL;
2171     }
2172     if (FLAG_SET_CMDLINE(size_t, MaxNewSize, NewSize) != Flag::SUCCESS) {
2173       return JNI_EINVAL;
2174     }
2175   }
2176 
2177 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
2178   FLAG_SET_DEFAULT(UseLargePages, true);
2179 #endif
2180 
2181   // Increase some data structure sizes for efficiency
2182   if (FLAG_SET_CMDLINE(size_t, BaseFootPrintEstimate, MaxHeapSize) != Flag::SUCCESS) {
2183     return JNI_EINVAL;
2184   }
2185   if (FLAG_SET_CMDLINE(bool, ResizeTLAB, false) != Flag::SUCCESS) {
2186     return JNI_EINVAL;
2187   }
2188   if (FLAG_SET_CMDLINE(size_t, TLABSize, 256 * K) != Flag::SUCCESS) {
2189     return JNI_EINVAL;
2190   }
2191 
2192   // See the OldPLABSize comment below, but replace 'after promotion'
2193   // with 'after copying'.  YoungPLABSize is the size of the survivor
2194   // space per-gc-thread buffers.  The default is 4kw.
2195   if (FLAG_SET_CMDLINE(size_t, YoungPLABSize, 256 * K) != Flag::SUCCESS) { // Note: this is in words
2196     return JNI_EINVAL;
2197   }
2198 
2199   // OldPLABSize is the size of the buffers in the old gen that
2200   // UseParallelGC uses to promote live data that doesn't fit in the
2201   // survivor spaces.  At any given time, there's one for each gc thread.
2202   // The default size is 1kw. These buffers are rarely used, since the
2203   // survivor spaces are usually big enough.  For specjbb, however, there
2204   // are occasions when there's lots of live data in the young gen
2205   // and we end up promoting some of it.  We don't have a definite
2206   // explanation for why bumping OldPLABSize helps, but the theory
2207   // is that a bigger PLAB results in retaining something like the
2208   // original allocation order after promotion, which improves mutator
2209   // locality.  A minor effect may be that larger PLABs reduce the
2210   // number of PLAB allocation events during gc.  The value of 8kw
2211   // was arrived at by experimenting with specjbb.
2212   if (FLAG_SET_CMDLINE(size_t, OldPLABSize, 8 * K) != Flag::SUCCESS) { // Note: this is in words
2213     return JNI_EINVAL;
2214   }
2215 
2216   // Enable parallel GC and adaptive generation sizing
2217   if (FLAG_SET_CMDLINE(bool, UseParallelGC, true) != Flag::SUCCESS) {
2218     return JNI_EINVAL;
2219   }
2220   FLAG_SET_DEFAULT(ParallelGCThreads,
2221           Abstract_VM_Version::parallel_worker_threads());
2222 
2223   // Encourage steady state memory management
2224   if (FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100) != Flag::SUCCESS) {
2225     return JNI_EINVAL;
2226   }
2227 
2228   // This appears to improve mutator locality
2229   if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2230     return JNI_EINVAL;
2231   }
2232 
2233   // Get around early Solaris scheduling bug
2234   // (affinity vs other jobs on system)
2235   // but disallow DR and offlining (5008695).
2236   if (FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true) != Flag::SUCCESS) {
2237     return JNI_EINVAL;
2238   }
2239 
2240   return JNI_OK;
2241 }
2242 
2243 // This must be called after ergonomics.
2244 void Arguments::set_bytecode_flags() {
2245   if (!RewriteBytecodes) {
2246     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
2247   }
2248 }
2249 
2250 // Aggressive optimization flags  -XX:+AggressiveOpts
2251 jint Arguments::set_aggressive_opts_flags() {
2252 #ifdef COMPILER2
2253   if (AggressiveUnboxing) {
2254     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2255       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2256     } else if (!EliminateAutoBox) {
2257       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
2258       AggressiveUnboxing = false;
2259     }
2260     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
2261       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
2262     } else if (!DoEscapeAnalysis) {
2263       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
2264       AggressiveUnboxing = false;
2265     }
2266   }
2267   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2268     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2269       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2270     }
2271     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2272       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
2273     }
2274 
2275     // Feed the cache size setting into the JDK
2276     char buffer[1024];
2277     sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
2278     if (!add_property(buffer)) {
2279       return JNI_ENOMEM;
2280     }
2281   }
2282   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
2283     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
2284   }
2285 #endif
2286 
2287   if (AggressiveOpts) {
2288 // Sample flag setting code
2289 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
2290 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
2291 //    }
2292   }
2293 
2294   return JNI_OK;
2295 }
2296 
2297 //===========================================================================================================
2298 // Parsing of java.compiler property
2299 
2300 void Arguments::process_java_compiler_argument(const char* arg) {
2301   // For backwards compatibility, Djava.compiler=NONE or ""
2302   // causes us to switch to -Xint mode UNLESS -Xdebug
2303   // is also specified.
2304   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
2305     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
2306   }
2307 }
2308 
2309 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
2310   _sun_java_launcher = os::strdup_check_oom(launcher);
2311 }
2312 
2313 bool Arguments::created_by_java_launcher() {
2314   assert(_sun_java_launcher != NULL, "property must have value");
2315   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
2316 }
2317 
2318 bool Arguments::sun_java_launcher_is_altjvm() {
2319   return _sun_java_launcher_is_altjvm;
2320 }
2321 
2322 //===========================================================================================================
2323 // Parsing of main arguments
2324 
2325 #if INCLUDE_JVMCI
2326 // Check consistency of jvmci vm argument settings.
2327 bool Arguments::check_jvmci_args_consistency() {
2328    return JVMCIGlobals::check_jvmci_flags_are_consistent();
2329 }
2330 #endif //INCLUDE_JVMCI
2331 
2332 // Check consistency of GC selection
2333 bool Arguments::check_gc_consistency() {
2334   // Ensure that the user has not selected conflicting sets
2335   // of collectors.
2336   uint i = 0;
2337   if (UseSerialGC)                       i++;
2338   if (UseConcMarkSweepGC)                i++;
2339   if (UseParallelGC || UseParallelOldGC) i++;
2340   if (UseG1GC)                           i++;
2341   if (i > 1) {
2342     jio_fprintf(defaultStream::error_stream(),
2343                 "Conflicting collector combinations in option list; "
2344                 "please refer to the release notes for the combinations "
2345                 "allowed\n");
2346     return false;
2347   }
2348 
2349   if (UseConcMarkSweepGC && !UseParNewGC) {
2350     jio_fprintf(defaultStream::error_stream(),
2351         "It is not possible to combine the DefNew young collector with the CMS collector.\n");
2352     return false;
2353   }
2354 
2355   if (UseParNewGC && !UseConcMarkSweepGC) {
2356     jio_fprintf(defaultStream::error_stream(),
2357         "It is not possible to combine the ParNew young collector with any collector other than CMS.\n");
2358     return false;
2359   }
2360 
2361   return true;
2362 }
2363 
2364 // Check the consistency of vm_init_args
2365 bool Arguments::check_vm_args_consistency() {
2366   // Method for adding checks for flag consistency.
2367   // The intent is to warn the user of all possible conflicts,
2368   // before returning an error.
2369   // Note: Needs platform-dependent factoring.
2370   bool status = true;
2371 
2372   if (TLABRefillWasteFraction == 0) {
2373     jio_fprintf(defaultStream::error_stream(),
2374                 "TLABRefillWasteFraction should be a denominator, "
2375                 "not " SIZE_FORMAT "\n",
2376                 TLABRefillWasteFraction);
2377     status = false;
2378   }
2379 
2380   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2381     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
2382   }
2383 
2384   if (!(UseParallelGC || UseParallelOldGC) && FLAG_IS_DEFAULT(ScavengeBeforeFullGC)) {
2385     FLAG_SET_DEFAULT(ScavengeBeforeFullGC, false);
2386   }
2387 
2388   if (GCTimeLimit == 100) {
2389     // Turn off gc-overhead-limit-exceeded checks
2390     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2391   }
2392 
2393   status = status && check_gc_consistency();
2394 
2395   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2396   // insists that we hold the requisite locks so that the iteration is
2397   // MT-safe. For the verification at start-up and shut-down, we don't
2398   // yet have a good way of acquiring and releasing these locks,
2399   // which are not visible at the CollectedHeap level. We want to
2400   // be able to acquire these locks and then do the iteration rather
2401   // than just disable the lock verification. This will be fixed under
2402   // bug 4788986.
2403   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2404     if (VerifyDuringStartup) {
2405       warning("Heap verification at start-up disabled "
2406               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2407       VerifyDuringStartup = false; // Disable verification at start-up
2408     }
2409 
2410     if (VerifyBeforeExit) {
2411       warning("Heap verification at shutdown disabled "
2412               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2413       VerifyBeforeExit = false; // Disable verification at shutdown
2414     }
2415   }
2416 
2417   if (PrintNMTStatistics) {
2418 #if INCLUDE_NMT
2419     if (MemTracker::tracking_level() == NMT_off) {
2420 #endif // INCLUDE_NMT
2421       warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2422       PrintNMTStatistics = false;
2423 #if INCLUDE_NMT
2424     }
2425 #endif
2426   }
2427 #if INCLUDE_JVMCI
2428 
2429   status = status && check_jvmci_args_consistency();
2430 
2431   if (EnableJVMCI) {
2432     if (!ScavengeRootsInCode) {
2433       warning("forcing ScavengeRootsInCode non-zero because JVMCI is enabled");
2434       ScavengeRootsInCode = 1;
2435     }
2436     if (FLAG_IS_DEFAULT(TypeProfileLevel)) {
2437       TypeProfileLevel = 0;
2438     }
2439     if (UseJVMCICompiler) {
2440       if (FLAG_IS_DEFAULT(TypeProfileWidth)) {
2441         TypeProfileWidth = 8;
2442       }
2443     }
2444   }
2445 #endif
2446 
2447   // Check lower bounds of the code cache
2448   // Template Interpreter code is approximately 3X larger in debug builds.
2449   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2450   if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2451     jio_fprintf(defaultStream::error_stream(),
2452                 "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
2453                 os::vm_page_size()/K);
2454     status = false;
2455   } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2456     jio_fprintf(defaultStream::error_stream(),
2457                 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2458                 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2459     status = false;
2460   } else if (ReservedCodeCacheSize < min_code_cache_size) {
2461     jio_fprintf(defaultStream::error_stream(),
2462                 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2463                 min_code_cache_size/K);
2464     status = false;
2465   } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2466     // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2467     jio_fprintf(defaultStream::error_stream(),
2468                 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2469                 CODE_CACHE_SIZE_LIMIT/M);
2470     status = false;
2471   } else if (NonNMethodCodeHeapSize < min_code_cache_size) {
2472     jio_fprintf(defaultStream::error_stream(),
2473                 "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2474                 min_code_cache_size/K);
2475     status = false;
2476   }
2477 
2478 #ifdef _LP64
2479   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2480     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2481   }
2482 #endif
2483 
2484 #ifndef SUPPORT_RESERVED_STACK_AREA
2485   if (StackReservedPages != 0) {
2486     FLAG_SET_CMDLINE(intx, StackReservedPages, 0);
2487     warning("Reserved Stack Area not supported on this platform");
2488   }
2489 #endif
2490 
2491   if (BackgroundCompilation && (CompileTheWorld || ReplayCompiles)) {
2492     if (!FLAG_IS_DEFAULT(BackgroundCompilation)) {
2493       warning("BackgroundCompilation disabled due to CompileTheWorld or ReplayCompiles options.");
2494     }
2495     FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2496   }
2497   if (UseCompiler && is_interpreter_only()) {
2498     if (!FLAG_IS_DEFAULT(UseCompiler)) {
2499       warning("UseCompiler disabled due to -Xint.");
2500     }
2501     FLAG_SET_CMDLINE(bool, UseCompiler, false);
2502   }
2503 #ifdef COMPILER2
2504   if (PostLoopMultiversioning && !RangeCheckElimination) {
2505     if (!FLAG_IS_DEFAULT(PostLoopMultiversioning)) {
2506       warning("PostLoopMultiversioning disabled because RangeCheckElimination is disabled.");
2507     }
2508     FLAG_SET_CMDLINE(bool, PostLoopMultiversioning, false);
2509   }
2510 #endif
2511   return status;
2512 }
2513 
2514 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2515   const char* option_type) {
2516   if (ignore) return false;
2517 
2518   const char* spacer = " ";
2519   if (option_type == NULL) {
2520     option_type = ++spacer; // Set both to the empty string.
2521   }
2522 
2523   if (os::obsolete_option(option)) {
2524     jio_fprintf(defaultStream::error_stream(),
2525                 "Obsolete %s%soption: %s\n", option_type, spacer,
2526       option->optionString);
2527     return false;
2528   } else {
2529     jio_fprintf(defaultStream::error_stream(),
2530                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2531       option->optionString);
2532     return true;
2533   }
2534 }
2535 
2536 static const char* user_assertion_options[] = {
2537   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2538 };
2539 
2540 static const char* system_assertion_options[] = {
2541   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2542 };
2543 
2544 bool Arguments::parse_uintx(const char* value,
2545                             uintx* uintx_arg,
2546                             uintx min_size) {
2547 
2548   // Check the sign first since atojulong() parses only unsigned values.
2549   bool value_is_positive = !(*value == '-');
2550 
2551   if (value_is_positive) {
2552     julong n;
2553     bool good_return = atojulong(value, &n);
2554     if (good_return) {
2555       bool above_minimum = n >= min_size;
2556       bool value_is_too_large = n > max_uintx;
2557 
2558       if (above_minimum && !value_is_too_large) {
2559         *uintx_arg = n;
2560         return true;
2561       }
2562     }
2563   }
2564   return false;
2565 }
2566 
2567 unsigned int addreads_count = 0;
2568 unsigned int addexports_count = 0;
2569 unsigned int patch_mod_count = 0;
2570 const char* add_modules_value = NULL;
2571 
2572 bool Arguments::create_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
2573   size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
2574   char* property = AllocateHeap(prop_len, mtArguments);
2575   int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);
2576   if (ret < 0 || ret >= (int)prop_len) {
2577     FreeHeap(property);
2578     return false;
2579   }
2580   bool added = add_property(property, UnwriteableProperty, internal);
2581   FreeHeap(property);
2582   return added;
2583 }
2584 
2585 bool Arguments::create_numbered_property(const char* prop_base_name, const char* prop_value, unsigned int count) {
2586   // Make sure count is < 1,000. Otherwise, memory allocation will be too small.
2587   if (count < 1000) {
2588     size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + 5;
2589     char* property = AllocateHeap(prop_len, mtArguments);
2590     int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);
2591     if (ret < 0 || ret >= (int)prop_len) {
2592       FreeHeap(property);
2593       return false;
2594     }
2595     bool added = add_property(property, UnwriteableProperty, InternalProperty);
2596     FreeHeap(property);
2597     return added;
2598   }
2599   return false;
2600 }
2601 
2602 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2603                                                   julong* long_arg,
2604                                                   julong min_size) {
2605   if (!atojulong(s, long_arg)) return arg_unreadable;
2606   return check_memory_size(*long_arg, min_size);
2607 }
2608 
2609 // Parse JavaVMInitArgs structure
2610 
2611 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *java_tool_options_args,
2612                                    const JavaVMInitArgs *java_options_args,
2613                                    const JavaVMInitArgs *cmd_line_args) {
2614   bool patch_mod_javabase = false;
2615 
2616   // Save default settings for some mode flags
2617   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2618   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2619   Arguments::_ClipInlining             = ClipInlining;
2620   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2621   if (TieredCompilation) {
2622     Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2623     Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2624   }
2625 
2626   // Setup flags for mixed which is the default
2627   set_mode_flags(_mixed);
2628 
2629   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2630   // variable (if present).
2631   jint result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
2632   if (result != JNI_OK) {
2633     return result;
2634   }
2635 
2636   // Parse args structure generated from the command line flags.
2637   result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, Flag::COMMAND_LINE);
2638   if (result != JNI_OK) {
2639     return result;
2640   }
2641 
2642   // Parse args structure generated from the _JAVA_OPTIONS environment
2643   // variable (if present) (mimics classic VM)
2644   result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
2645   if (result != JNI_OK) {
2646     return result;
2647   }
2648 
2649   // Do final processing now that all arguments have been parsed
2650   result = finalize_vm_init_args();
2651   if (result != JNI_OK) {
2652     return result;
2653   }
2654 
2655   return JNI_OK;
2656 }
2657 
2658 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2659 // represents a valid JDWP agent.  is_path==true denotes that we
2660 // are dealing with -agentpath (case where name is a path), otherwise with
2661 // -agentlib
2662 bool valid_jdwp_agent(char *name, bool is_path) {
2663   char *_name;
2664   const char *_jdwp = "jdwp";
2665   size_t _len_jdwp, _len_prefix;
2666 
2667   if (is_path) {
2668     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2669       return false;
2670     }
2671 
2672     _name++;  // skip past last path separator
2673     _len_prefix = strlen(JNI_LIB_PREFIX);
2674 
2675     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2676       return false;
2677     }
2678 
2679     _name += _len_prefix;
2680     _len_jdwp = strlen(_jdwp);
2681 
2682     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2683       _name += _len_jdwp;
2684     }
2685     else {
2686       return false;
2687     }
2688 
2689     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2690       return false;
2691     }
2692 
2693     return true;
2694   }
2695 
2696   if (strcmp(name, _jdwp) == 0) {
2697     return true;
2698   }
2699 
2700   return false;
2701 }
2702 
2703 int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {
2704   // --patch-module=<module>=<file>(<pathsep><file>)*
2705   assert(patch_mod_tail != NULL, "Unexpected NULL patch-module value");
2706   // Find the equal sign between the module name and the path specification
2707   const char* module_equal = strchr(patch_mod_tail, '=');
2708   if (module_equal == NULL) {
2709     jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");
2710     return JNI_ERR;
2711   } else {
2712     // Pick out the module name
2713     size_t module_len = module_equal - patch_mod_tail;
2714     char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);
2715     if (module_name != NULL) {
2716       memcpy(module_name, patch_mod_tail, module_len);
2717       *(module_name + module_len) = '\0';
2718       // The path piece begins one past the module_equal sign
2719       add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);
2720       FREE_C_HEAP_ARRAY(char, module_name);
2721       if (!create_numbered_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {
2722         return JNI_ENOMEM;
2723       }
2724     } else {
2725       return JNI_ENOMEM;
2726     }
2727   }
2728   return JNI_OK;
2729 }
2730 
2731 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, Flag::Flags origin) {
2732   // For match_option to return remaining or value part of option string
2733   const char* tail;
2734 
2735   // iterate over arguments
2736   for (int index = 0; index < args->nOptions; index++) {
2737     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2738 
2739     const JavaVMOption* option = args->options + index;
2740 
2741     if (!match_option(option, "-Djava.class.path", &tail) &&
2742         !match_option(option, "-Dsun.java.command", &tail) &&
2743         !match_option(option, "-Dsun.java.launcher", &tail)) {
2744 
2745         // add all jvm options to the jvm_args string. This string
2746         // is used later to set the java.vm.args PerfData string constant.
2747         // the -Djava.class.path and the -Dsun.java.command options are
2748         // omitted from jvm_args string as each have their own PerfData
2749         // string constant object.
2750         build_jvm_args(option->optionString);
2751     }
2752 
2753     // -verbose:[class/gc/jni]
2754     if (match_option(option, "-verbose", &tail)) {
2755       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2756         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));
2757         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));
2758       } else if (!strcmp(tail, ":gc")) {
2759         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(gc));
2760       } else if (!strcmp(tail, ":jni")) {
2761         if (FLAG_SET_CMDLINE(bool, PrintJNIResolving, true) != Flag::SUCCESS) {
2762           return JNI_EINVAL;
2763         }
2764       }
2765     // -da / -ea / -disableassertions / -enableassertions
2766     // These accept an optional class/package name separated by a colon, e.g.,
2767     // -da:java.lang.Thread.
2768     } else if (match_option(option, user_assertion_options, &tail, true)) {
2769       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2770       if (*tail == '\0') {
2771         JavaAssertions::setUserClassDefault(enable);
2772       } else {
2773         assert(*tail == ':', "bogus match by match_option()");
2774         JavaAssertions::addOption(tail + 1, enable);
2775       }
2776     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2777     } else if (match_option(option, system_assertion_options, &tail, false)) {
2778       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2779       JavaAssertions::setSystemClassDefault(enable);
2780     // -bootclasspath:
2781     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2782         jio_fprintf(defaultStream::output_stream(),
2783           "-Xbootclasspath is no longer a supported option.\n");
2784         return JNI_EINVAL;
2785     // -bootclasspath/a:
2786     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2787       Arguments::append_sysclasspath(tail);
2788     // -bootclasspath/p:
2789     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2790         jio_fprintf(defaultStream::output_stream(),
2791           "-Xbootclasspath/p is no longer a supported option.\n");
2792         return JNI_EINVAL;
2793     // -Xrun
2794     } else if (match_option(option, "-Xrun", &tail)) {
2795       if (tail != NULL) {
2796         const char* pos = strchr(tail, ':');
2797         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2798         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtArguments), tail, len);
2799         name[len] = '\0';
2800 
2801         char *options = NULL;
2802         if(pos != NULL) {
2803           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2804           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);
2805         }
2806 #if !INCLUDE_JVMTI
2807         if (strcmp(name, "jdwp") == 0) {
2808           jio_fprintf(defaultStream::error_stream(),
2809             "Debugging agents are not supported in this VM\n");
2810           return JNI_ERR;
2811         }
2812 #endif // !INCLUDE_JVMTI
2813         add_init_library(name, options);
2814       }
2815     } else if (match_option(option, "--add-reads=", &tail)) {
2816       if (!create_numbered_property("jdk.module.addreads", tail, addreads_count++)) {
2817         return JNI_ENOMEM;
2818       }
2819     } else if (match_option(option, "--add-exports=", &tail)) {
2820       if (!create_numbered_property("jdk.module.addexports", tail, addexports_count++)) {
2821         return JNI_ENOMEM;
2822       }
2823     } else if (match_option(option, "--add-modules=", &tail)) {
2824       add_modules_value = tail;
2825     } else if (match_option(option, "--limit-modules=", &tail)) {
2826       if (!create_property("jdk.module.limitmods", tail, InternalProperty)) {
2827         return JNI_ENOMEM;
2828       }
2829     } else if (match_option(option, "--module-path=", &tail)) {
2830       if (!create_property("jdk.module.path", tail, ExternalProperty)) {
2831         return JNI_ENOMEM;
2832       }
2833     } else if (match_option(option, "--upgrade-module-path=", &tail)) {
2834       if (!create_property("jdk.module.upgrade.path", tail, ExternalProperty)) {
2835         return JNI_ENOMEM;
2836       }
2837     } else if (match_option(option, "--patch-module=", &tail)) {
2838       // --patch-module=<module>=<file>(<pathsep><file>)*
2839       int res = process_patch_mod_option(tail, patch_mod_javabase);
2840       if (res != JNI_OK) {
2841         return res;
2842       }
2843     // -agentlib and -agentpath
2844     } else if (match_option(option, "-agentlib:", &tail) ||
2845           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2846       if(tail != NULL) {
2847         const char* pos = strchr(tail, '=');
2848         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2849         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtArguments), tail, len);
2850         name[len] = '\0';
2851 
2852         char *options = NULL;
2853         if(pos != NULL) {
2854           options = os::strdup_check_oom(pos + 1, mtArguments);
2855         }
2856 #if !INCLUDE_JVMTI
2857         if (valid_jdwp_agent(name, is_absolute_path)) {
2858           jio_fprintf(defaultStream::error_stream(),
2859             "Debugging agents are not supported in this VM\n");
2860           return JNI_ERR;
2861         }
2862 #endif // !INCLUDE_JVMTI
2863         add_init_agent(name, options, is_absolute_path);
2864       }
2865     // -javaagent
2866     } else if (match_option(option, "-javaagent:", &tail)) {
2867 #if !INCLUDE_JVMTI
2868       jio_fprintf(defaultStream::error_stream(),
2869         "Instrumentation agents are not supported in this VM\n");
2870       return JNI_ERR;
2871 #else
2872       if (tail != NULL) {
2873         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtArguments), tail);
2874         add_init_agent("instrument", options, false);
2875         // java agents need module java.instrument
2876         if (!Arguments::append_to_addmods_property("java.instrument")) {
2877           return JNI_ENOMEM;
2878         }
2879       }
2880 #endif // !INCLUDE_JVMTI
2881     // -Xnoclassgc
2882     } else if (match_option(option, "-Xnoclassgc")) {
2883       if (FLAG_SET_CMDLINE(bool, ClassUnloading, false) != Flag::SUCCESS) {
2884         return JNI_EINVAL;
2885       }
2886     // -Xconcgc
2887     } else if (match_option(option, "-Xconcgc")) {
2888       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true) != Flag::SUCCESS) {
2889         return JNI_EINVAL;
2890       }
2891     // -Xnoconcgc
2892     } else if (match_option(option, "-Xnoconcgc")) {
2893       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false) != Flag::SUCCESS) {
2894         return JNI_EINVAL;
2895       }
2896     // -Xbatch
2897     } else if (match_option(option, "-Xbatch")) {
2898       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2899         return JNI_EINVAL;
2900       }
2901     // -Xmn for compatibility with other JVM vendors
2902     } else if (match_option(option, "-Xmn", &tail)) {
2903       julong long_initial_young_size = 0;
2904       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2905       if (errcode != arg_in_range) {
2906         jio_fprintf(defaultStream::error_stream(),
2907                     "Invalid initial young generation size: %s\n", option->optionString);
2908         describe_range_error(errcode);
2909         return JNI_EINVAL;
2910       }
2911       if (FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2912         return JNI_EINVAL;
2913       }
2914       if (FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2915         return JNI_EINVAL;
2916       }
2917     // -Xms
2918     } else if (match_option(option, "-Xms", &tail)) {
2919       julong long_initial_heap_size = 0;
2920       // an initial heap size of 0 means automatically determine
2921       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2922       if (errcode != arg_in_range) {
2923         jio_fprintf(defaultStream::error_stream(),
2924                     "Invalid initial heap size: %s\n", option->optionString);
2925         describe_range_error(errcode);
2926         return JNI_EINVAL;
2927       }
2928       set_min_heap_size((size_t)long_initial_heap_size);
2929       // Currently the minimum size and the initial heap sizes are the same.
2930       // Can be overridden with -XX:InitialHeapSize.
2931       if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size) != Flag::SUCCESS) {
2932         return JNI_EINVAL;
2933       }
2934     // -Xmx
2935     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2936       julong long_max_heap_size = 0;
2937       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2938       if (errcode != arg_in_range) {
2939         jio_fprintf(defaultStream::error_stream(),
2940                     "Invalid maximum heap size: %s\n", option->optionString);
2941         describe_range_error(errcode);
2942         return JNI_EINVAL;
2943       }
2944       if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size) != Flag::SUCCESS) {
2945         return JNI_EINVAL;
2946       }
2947     // Xmaxf
2948     } else if (match_option(option, "-Xmaxf", &tail)) {
2949       char* err;
2950       int maxf = (int)(strtod(tail, &err) * 100);
2951       if (*err != '\0' || *tail == '\0') {
2952         jio_fprintf(defaultStream::error_stream(),
2953                     "Bad max heap free percentage size: %s\n",
2954                     option->optionString);
2955         return JNI_EINVAL;
2956       } else {
2957         if (FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf) != Flag::SUCCESS) {
2958             return JNI_EINVAL;
2959         }
2960       }
2961     // Xminf
2962     } else if (match_option(option, "-Xminf", &tail)) {
2963       char* err;
2964       int minf = (int)(strtod(tail, &err) * 100);
2965       if (*err != '\0' || *tail == '\0') {
2966         jio_fprintf(defaultStream::error_stream(),
2967                     "Bad min heap free percentage size: %s\n",
2968                     option->optionString);
2969         return JNI_EINVAL;
2970       } else {
2971         if (FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf) != Flag::SUCCESS) {
2972           return JNI_EINVAL;
2973         }
2974       }
2975     // -Xss
2976     } else if (match_option(option, "-Xss", &tail)) {
2977       julong long_ThreadStackSize = 0;
2978       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2979       if (errcode != arg_in_range) {
2980         jio_fprintf(defaultStream::error_stream(),
2981                     "Invalid thread stack size: %s\n", option->optionString);
2982         describe_range_error(errcode);
2983         return JNI_EINVAL;
2984       }
2985       // Internally track ThreadStackSize in units of 1024 bytes.
2986       if (FLAG_SET_CMDLINE(intx, ThreadStackSize,
2987                        round_to((int)long_ThreadStackSize, K) / K) != Flag::SUCCESS) {
2988         return JNI_EINVAL;
2989       }
2990     // -Xoss, -Xsqnopause, -Xoptimize, -Xboundthreads, -Xusealtsigs
2991     } else if (match_option(option, "-Xoss", &tail) ||
2992                match_option(option, "-Xsqnopause") ||
2993                match_option(option, "-Xoptimize") ||
2994                match_option(option, "-Xboundthreads") ||
2995                match_option(option, "-Xusealtsigs")) {
2996       // All these options are deprecated in JDK 9 and will be removed in a future release
2997       char version[256];
2998       JDK_Version::jdk(9).to_string(version, sizeof(version));
2999       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
3000     } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
3001       julong long_CodeCacheExpansionSize = 0;
3002       ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
3003       if (errcode != arg_in_range) {
3004         jio_fprintf(defaultStream::error_stream(),
3005                    "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
3006                    os::vm_page_size()/K);
3007         return JNI_EINVAL;
3008       }
3009       if (FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize) != Flag::SUCCESS) {
3010         return JNI_EINVAL;
3011       }
3012     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
3013                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
3014       julong long_ReservedCodeCacheSize = 0;
3015 
3016       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
3017       if (errcode != arg_in_range) {
3018         jio_fprintf(defaultStream::error_stream(),
3019                     "Invalid maximum code cache size: %s.\n", option->optionString);
3020         return JNI_EINVAL;
3021       }
3022       if (FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != Flag::SUCCESS) {
3023         return JNI_EINVAL;
3024       }
3025       // -XX:NonNMethodCodeHeapSize=
3026     } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
3027       julong long_NonNMethodCodeHeapSize = 0;
3028 
3029       ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
3030       if (errcode != arg_in_range) {
3031         jio_fprintf(defaultStream::error_stream(),
3032                     "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
3033         return JNI_EINVAL;
3034       }
3035       if (FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize) != Flag::SUCCESS) {
3036         return JNI_EINVAL;
3037       }
3038       // -XX:ProfiledCodeHeapSize=
3039     } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
3040       julong long_ProfiledCodeHeapSize = 0;
3041 
3042       ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
3043       if (errcode != arg_in_range) {
3044         jio_fprintf(defaultStream::error_stream(),
3045                     "Invalid maximum profiled code heap size: %s.\n", option->optionString);
3046         return JNI_EINVAL;
3047       }
3048       if (FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize) != Flag::SUCCESS) {
3049         return JNI_EINVAL;
3050       }
3051       // -XX:NonProfiledCodeHeapSizee=
3052     } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
3053       julong long_NonProfiledCodeHeapSize = 0;
3054 
3055       ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
3056       if (errcode != arg_in_range) {
3057         jio_fprintf(defaultStream::error_stream(),
3058                     "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
3059         return JNI_EINVAL;
3060       }
3061       if (FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize) != Flag::SUCCESS) {
3062         return JNI_EINVAL;
3063       }
3064     // -green
3065     } else if (match_option(option, "-green")) {
3066       jio_fprintf(defaultStream::error_stream(),
3067                   "Green threads support not available\n");
3068           return JNI_EINVAL;
3069     // -native
3070     } else if (match_option(option, "-native")) {
3071           // HotSpot always uses native threads, ignore silently for compatibility
3072     // -Xrs
3073     } else if (match_option(option, "-Xrs")) {
3074           // Classic/EVM option, new functionality
3075       if (FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true) != Flag::SUCCESS) {
3076         return JNI_EINVAL;
3077       }
3078     // -Xprof
3079     } else if (match_option(option, "-Xprof")) {
3080 #if INCLUDE_FPROF
3081       _has_profile = true;
3082 #else // INCLUDE_FPROF
3083       jio_fprintf(defaultStream::error_stream(),
3084         "Flat profiling is not supported in this VM.\n");
3085       return JNI_ERR;
3086 #endif // INCLUDE_FPROF
3087     // -Xconcurrentio
3088     } else if (match_option(option, "-Xconcurrentio")) {
3089       if (FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true) != Flag::SUCCESS) {
3090         return JNI_EINVAL;
3091       }
3092       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
3093         return JNI_EINVAL;
3094       }
3095       if (FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1) != Flag::SUCCESS) {
3096         return JNI_EINVAL;
3097       }
3098       if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
3099         return JNI_EINVAL;
3100       }
3101       if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
3102         return JNI_EINVAL;
3103       }
3104 
3105       // -Xinternalversion
3106     } else if (match_option(option, "-Xinternalversion")) {
3107       jio_fprintf(defaultStream::output_stream(), "%s\n",
3108                   VM_Version::internal_vm_info_string());
3109       vm_exit(0);
3110 #ifndef PRODUCT
3111     // -Xprintflags
3112     } else if (match_option(option, "-Xprintflags")) {
3113       CommandLineFlags::printFlags(tty, false);
3114       vm_exit(0);
3115 #endif
3116     // -D
3117     } else if (match_option(option, "-D", &tail)) {
3118       const char* value;
3119       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
3120             *value!= '\0' && strcmp(value, "\"\"") != 0) {
3121         // abort if -Djava.endorsed.dirs is set
3122         jio_fprintf(defaultStream::output_stream(),
3123           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
3124           "in modular form will be supported via the concept of upgradeable modules.\n", value);
3125         return JNI_EINVAL;
3126       }
3127       if (match_option(option, "-Djava.ext.dirs=", &value) &&
3128             *value != '\0' && strcmp(value, "\"\"") != 0) {
3129         // abort if -Djava.ext.dirs is set
3130         jio_fprintf(defaultStream::output_stream(),
3131           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
3132         return JNI_EINVAL;
3133       }
3134       // Check for module related properties.  They must be set using the modules
3135       // options. For example: use "--add-modules=java.sql", not
3136       // "-Djdk.module.addmods=java.sql"
3137       if (is_internal_module_property(option->optionString + 2)) {
3138         needs_module_property_warning = true;
3139         continue;
3140       }
3141 
3142       if (!add_property(tail)) {
3143         return JNI_ENOMEM;
3144       }
3145       // Out of the box management support
3146       if (match_option(option, "-Dcom.sun.management", &tail)) {
3147 #if INCLUDE_MANAGEMENT
3148         if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
3149           return JNI_EINVAL;
3150         }
3151         // management agent in module java.management
3152         if (!Arguments::append_to_addmods_property("java.management")) {
3153           return JNI_ENOMEM;
3154         }
3155 #else
3156         jio_fprintf(defaultStream::output_stream(),
3157           "-Dcom.sun.management is not supported in this VM.\n");
3158         return JNI_ERR;
3159 #endif
3160       }
3161     // -Xint
3162     } else if (match_option(option, "-Xint")) {
3163           set_mode_flags(_int);
3164     // -Xmixed
3165     } else if (match_option(option, "-Xmixed")) {
3166           set_mode_flags(_mixed);
3167     // -Xcomp
3168     } else if (match_option(option, "-Xcomp")) {
3169       // for testing the compiler; turn off all flags that inhibit compilation
3170           set_mode_flags(_comp);
3171     // -Xshare:dump
3172     } else if (match_option(option, "-Xshare:dump")) {
3173       if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
3174         return JNI_EINVAL;
3175       }
3176       set_mode_flags(_int);     // Prevent compilation, which creates objects
3177     // -Xshare:on
3178     } else if (match_option(option, "-Xshare:on")) {
3179       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3180         return JNI_EINVAL;
3181       }
3182       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3183         return JNI_EINVAL;
3184       }
3185     // -Xshare:auto
3186     } else if (match_option(option, "-Xshare:auto")) {
3187       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3188         return JNI_EINVAL;
3189       }
3190       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3191         return JNI_EINVAL;
3192       }
3193     // -Xshare:off
3194     } else if (match_option(option, "-Xshare:off")) {
3195       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
3196         return JNI_EINVAL;
3197       }
3198       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3199         return JNI_EINVAL;
3200       }
3201     // -Xverify
3202     } else if (match_option(option, "-Xverify", &tail)) {
3203       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
3204         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
3205           return JNI_EINVAL;
3206         }
3207         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3208           return JNI_EINVAL;
3209         }
3210       } else if (strcmp(tail, ":remote") == 0) {
3211         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3212           return JNI_EINVAL;
3213         }
3214         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3215           return JNI_EINVAL;
3216         }
3217       } else if (strcmp(tail, ":none") == 0) {
3218         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3219           return JNI_EINVAL;
3220         }
3221         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
3222           return JNI_EINVAL;
3223         }
3224       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3225         return JNI_EINVAL;
3226       }
3227     // -Xdebug
3228     } else if (match_option(option, "-Xdebug")) {
3229       // note this flag has been used, then ignore
3230       set_xdebug_mode(true);
3231     // -Xnoagent
3232     } else if (match_option(option, "-Xnoagent")) {
3233       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3234     } else if (match_option(option, "-Xloggc:", &tail)) {
3235       // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
3236       log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
3237       _gc_log_filename = os::strdup_check_oom(tail);
3238     } else if (match_option(option, "-Xlog", &tail)) {
3239       bool ret = false;
3240       if (strcmp(tail, ":help") == 0) {
3241         LogConfiguration::print_command_line_help(defaultStream::output_stream());
3242         vm_exit(0);
3243       } else if (strcmp(tail, ":disable") == 0) {
3244         LogConfiguration::disable_logging();
3245         ret = true;
3246       } else if (*tail == '\0') {
3247         ret = LogConfiguration::parse_command_line_arguments();
3248         assert(ret, "-Xlog without arguments should never fail to parse");
3249       } else if (*tail == ':') {
3250         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
3251       }
3252       if (ret == false) {
3253         jio_fprintf(defaultStream::error_stream(),
3254                     "Invalid -Xlog option '-Xlog%s'\n",
3255                     tail);
3256         return JNI_EINVAL;
3257       }
3258     // JNI hooks
3259     } else if (match_option(option, "-Xcheck", &tail)) {
3260       if (!strcmp(tail, ":jni")) {
3261 #if !INCLUDE_JNI_CHECK
3262         warning("JNI CHECKING is not supported in this VM");
3263 #else
3264         CheckJNICalls = true;
3265 #endif // INCLUDE_JNI_CHECK
3266       } else if (is_bad_option(option, args->ignoreUnrecognized,
3267                                      "check")) {
3268         return JNI_EINVAL;
3269       }
3270     } else if (match_option(option, "vfprintf")) {
3271       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3272     } else if (match_option(option, "exit")) {
3273       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3274     } else if (match_option(option, "abort")) {
3275       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3276     // -XX:+AggressiveHeap
3277     } else if (match_option(option, "-XX:+AggressiveHeap")) {
3278       jint result = set_aggressive_heap_flags();
3279       if (result != JNI_OK) {
3280           return result;
3281       }
3282     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
3283     // and the last option wins.
3284     } else if (match_option(option, "-XX:+NeverTenure")) {
3285       if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
3286         return JNI_EINVAL;
3287       }
3288       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3289         return JNI_EINVAL;
3290       }
3291       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
3292         return JNI_EINVAL;
3293       }
3294     } else if (match_option(option, "-XX:+AlwaysTenure")) {
3295       if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3296         return JNI_EINVAL;
3297       }
3298       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3299         return JNI_EINVAL;
3300       }
3301       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
3302         return JNI_EINVAL;
3303       }
3304     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
3305       uintx max_tenuring_thresh = 0;
3306       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
3307         jio_fprintf(defaultStream::error_stream(),
3308                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
3309         return JNI_EINVAL;
3310       }
3311 
3312       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
3313         return JNI_EINVAL;
3314       }
3315 
3316       if (MaxTenuringThreshold == 0) {
3317         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3318           return JNI_EINVAL;
3319         }
3320         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3321           return JNI_EINVAL;
3322         }
3323       } else {
3324         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3325           return JNI_EINVAL;
3326         }
3327         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3328           return JNI_EINVAL;
3329         }
3330       }
3331     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3332       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
3333         return JNI_EINVAL;
3334       }
3335       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
3336         return JNI_EINVAL;
3337       }
3338     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3339       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
3340         return JNI_EINVAL;
3341       }
3342       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3343         return JNI_EINVAL;
3344       }
3345     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3346 #if defined(DTRACE_ENABLED)
3347       if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3348         return JNI_EINVAL;
3349       }
3350       if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3351         return JNI_EINVAL;
3352       }
3353       if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3354         return JNI_EINVAL;
3355       }
3356       if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3357         return JNI_EINVAL;
3358       }
3359 #else // defined(DTRACE_ENABLED)
3360       jio_fprintf(defaultStream::error_stream(),
3361                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3362       return JNI_EINVAL;
3363 #endif // defined(DTRACE_ENABLED)
3364 #ifdef ASSERT
3365     } else if (match_option(option, "-XX:+FullGCALot")) {
3366       if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3367         return JNI_EINVAL;
3368       }
3369       // disable scavenge before parallel mark-compact
3370       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3371         return JNI_EINVAL;
3372       }
3373 #endif
3374 #if !INCLUDE_MANAGEMENT
3375     } else if (match_option(option, "-XX:+ManagementServer")) {
3376         jio_fprintf(defaultStream::error_stream(),
3377           "ManagementServer is not supported in this VM.\n");
3378         return JNI_ERR;
3379 #endif // INCLUDE_MANAGEMENT
3380     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3381       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
3382       // already been handled
3383       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
3384           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
3385         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3386           return JNI_EINVAL;
3387         }
3388       }
3389     // Unknown option
3390     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3391       return JNI_ERR;
3392     }
3393   }
3394 
3395   // PrintSharedArchiveAndExit will turn on
3396   //   -Xshare:on
3397   //   -Xlog:class+path=info
3398   if (PrintSharedArchiveAndExit) {
3399     if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3400       return JNI_EINVAL;
3401     }
3402     if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3403       return JNI_EINVAL;
3404     }
3405     LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));
3406   }
3407 
3408   // Change the default value for flags  which have different default values
3409   // when working with older JDKs.
3410 #ifdef LINUX
3411  if (JDK_Version::current().compare_major(6) <= 0 &&
3412       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3413     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3414   }
3415 #endif // LINUX
3416   fix_appclasspath();
3417   return JNI_OK;
3418 }
3419 
3420 void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {
3421   // For java.base check for duplicate --patch-module options being specified on the command line.
3422   // This check is only required for java.base, all other duplicate module specifications
3423   // will be checked during module system initialization.  The module system initialization
3424   // will throw an ExceptionInInitializerError if this situation occurs.
3425   if (strcmp(module_name, "java.base") == 0) {
3426     if (*patch_mod_javabase) {
3427       vm_exit_during_initialization("Cannot specify java.base more than once to --patch-module");
3428     } else {
3429       *patch_mod_javabase = true;
3430     }
3431   }
3432 
3433   // Create GrowableArray lazily, only if --patch-module has been specified
3434   if (_patch_mod_prefix == NULL) {
3435     _patch_mod_prefix = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<ModulePatchPath*>(10, true);
3436   }
3437 
3438   _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
3439 }
3440 
3441 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3442 //
3443 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3444 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3445 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3446 // path is treated as the current directory.
3447 //
3448 // This causes problems with CDS, which requires that all directories specified in the classpath
3449 // must be empty. In most cases, applications do NOT want to load classes from the current
3450 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3451 // scripts compatible with CDS.
3452 void Arguments::fix_appclasspath() {
3453   if (IgnoreEmptyClassPaths) {
3454     const char separator = *os::path_separator();
3455     const char* src = _java_class_path->value();
3456 
3457     // skip over all the leading empty paths
3458     while (*src == separator) {
3459       src ++;
3460     }
3461 
3462     char* copy = os::strdup_check_oom(src, mtArguments);
3463 
3464     // trim all trailing empty paths
3465     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3466       *tail = '\0';
3467     }
3468 
3469     char from[3] = {separator, separator, '\0'};
3470     char to  [2] = {separator, '\0'};
3471     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3472       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3473       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3474     }
3475 
3476     _java_class_path->set_writeable_value(copy);
3477     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3478   }
3479 }
3480 
3481 static bool has_jar_files(const char* directory) {
3482   DIR* dir = os::opendir(directory);
3483   if (dir == NULL) return false;
3484 
3485   struct dirent *entry;
3486   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtArguments);
3487   bool hasJarFile = false;
3488   while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3489     const char* name = entry->d_name;
3490     const char* ext = name + strlen(name) - 4;
3491     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3492   }
3493   FREE_C_HEAP_ARRAY(char, dbuf);
3494   os::closedir(dir);
3495   return hasJarFile ;
3496 }
3497 
3498 static int check_non_empty_dirs(const char* path) {
3499   const char separator = *os::path_separator();
3500   const char* const end = path + strlen(path);
3501   int nonEmptyDirs = 0;
3502   while (path < end) {
3503     const char* tmp_end = strchr(path, separator);
3504     if (tmp_end == NULL) {
3505       if (has_jar_files(path)) {
3506         nonEmptyDirs++;
3507         jio_fprintf(defaultStream::output_stream(),
3508           "Non-empty directory: %s\n", path);
3509       }
3510       path = end;
3511     } else {
3512       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtArguments);
3513       memcpy(dirpath, path, tmp_end - path);
3514       dirpath[tmp_end - path] = '\0';
3515       if (has_jar_files(dirpath)) {
3516         nonEmptyDirs++;
3517         jio_fprintf(defaultStream::output_stream(),
3518           "Non-empty directory: %s\n", dirpath);
3519       }
3520       FREE_C_HEAP_ARRAY(char, dirpath);
3521       path = tmp_end + 1;
3522     }
3523   }
3524   return nonEmptyDirs;
3525 }
3526 
3527 jint Arguments::finalize_vm_init_args() {
3528   // check if the default lib/endorsed directory exists; if so, error
3529   char path[JVM_MAXPATHLEN];
3530   const char* fileSep = os::file_separator();
3531   sprintf(path, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3532 
3533   if (CheckEndorsedAndExtDirs) {
3534     int nonEmptyDirs = 0;
3535     // check endorsed directory
3536     nonEmptyDirs += check_non_empty_dirs(path);
3537     // check the extension directories
3538     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3539     if (nonEmptyDirs > 0) {
3540       return JNI_ERR;
3541     }
3542   }
3543 
3544   DIR* dir = os::opendir(path);
3545   if (dir != NULL) {
3546     jio_fprintf(defaultStream::output_stream(),
3547       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3548       "in modular form will be supported via the concept of upgradeable modules.\n");
3549     os::closedir(dir);
3550     return JNI_ERR;
3551   }
3552 
3553   sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3554   dir = os::opendir(path);
3555   if (dir != NULL) {
3556     jio_fprintf(defaultStream::output_stream(),
3557       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3558       "Use -classpath instead.\n.");
3559     os::closedir(dir);
3560     return JNI_ERR;
3561   }
3562 
3563   // Append the value of the last --add-modules option specified on the command line.
3564   // This needs to be done here, to prevent overwriting possible values written
3565   // to the jdk.module.addmods property by -javaagent and other options.
3566   if (add_modules_value != NULL) {
3567     if (!append_to_addmods_property(add_modules_value)) {
3568       return JNI_ENOMEM;
3569     }
3570   }
3571 
3572   // This must be done after all arguments have been processed.
3573   // java_compiler() true means set to "NONE" or empty.
3574   if (java_compiler() && !xdebug_mode()) {
3575     // For backwards compatibility, we switch to interpreted mode if
3576     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3577     // not specified.
3578     set_mode_flags(_int);
3579   }
3580 
3581   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3582   // but like -Xint, leave compilation thresholds unaffected.
3583   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3584   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3585     set_mode_flags(_int);
3586   }
3587 
3588   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3589   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3590     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3591   }
3592 
3593 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3594   // Don't degrade server performance for footprint
3595   if (FLAG_IS_DEFAULT(UseLargePages) &&
3596       MaxHeapSize < LargePageHeapSizeThreshold) {
3597     // No need for large granularity pages w/small heaps.
3598     // Note that large pages are enabled/disabled for both the
3599     // Java heap and the code cache.
3600     FLAG_SET_DEFAULT(UseLargePages, false);
3601   }
3602 
3603 #elif defined(COMPILER2)
3604   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3605     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3606   }
3607 #endif
3608 
3609 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3610   UNSUPPORTED_OPTION(ProfileInterpreter);
3611   NOT_PRODUCT(UNSUPPORTED_OPTION(TraceProfileInterpreter));
3612 #endif
3613 
3614 #ifndef TIERED
3615   // Tiered compilation is undefined.
3616   UNSUPPORTED_OPTION(TieredCompilation);
3617 #endif
3618 
3619 #if INCLUDE_JVMCI
3620   if (EnableJVMCI && !append_to_addmods_property("jdk.vm.ci")) {
3621     return JNI_ENOMEM;
3622   }
3623 #endif
3624 
3625   // If we are running in a headless jre, force java.awt.headless property
3626   // to be true unless the property has already been set.
3627   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3628   if (os::is_headless_jre()) {
3629     const char* headless = Arguments::get_property("java.awt.headless");
3630     if (headless == NULL) {
3631       const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3632       if (headless_env == NULL) {
3633         if (!add_property("java.awt.headless=true")) {
3634           return JNI_ENOMEM;
3635         }
3636       } else {
3637         char buffer[256];
3638         jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3639         if (!add_property(buffer)) {
3640           return JNI_ENOMEM;
3641         }
3642       }
3643     }
3644   }
3645 
3646   if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3647     // CMS can only be used with ParNew
3648     FLAG_SET_ERGO(bool, UseParNewGC, true);
3649   }
3650 
3651   if (!check_vm_args_consistency()) {
3652     return JNI_ERR;
3653   }
3654 
3655   return JNI_OK;
3656 }
3657 
3658 // Helper class for controlling the lifetime of JavaVMInitArgs
3659 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3660 // deleted on the destruction of the ScopedVMInitArgs object.
3661 class ScopedVMInitArgs : public StackObj {
3662  private:
3663   JavaVMInitArgs _args;
3664   char*          _container_name;
3665   bool           _is_set;
3666   char*          _vm_options_file_arg;
3667 
3668  public:
3669   ScopedVMInitArgs(const char *container_name) {
3670     _args.version = JNI_VERSION_1_2;
3671     _args.nOptions = 0;
3672     _args.options = NULL;
3673     _args.ignoreUnrecognized = false;
3674     _container_name = (char *)container_name;
3675     _is_set = false;
3676     _vm_options_file_arg = NULL;
3677   }
3678 
3679   // Populates the JavaVMInitArgs object represented by this
3680   // ScopedVMInitArgs object with the arguments in options.  The
3681   // allocated memory is deleted by the destructor.  If this method
3682   // returns anything other than JNI_OK, then this object is in a
3683   // partially constructed state, and should be abandoned.
3684   jint set_args(GrowableArray<JavaVMOption>* options) {
3685     _is_set = true;
3686     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3687         JavaVMOption, options->length(), mtArguments);
3688     if (options_arr == NULL) {
3689       return JNI_ENOMEM;
3690     }
3691     _args.options = options_arr;
3692 
3693     for (int i = 0; i < options->length(); i++) {
3694       options_arr[i] = options->at(i);
3695       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3696       if (options_arr[i].optionString == NULL) {
3697         // Rely on the destructor to do cleanup.
3698         _args.nOptions = i;
3699         return JNI_ENOMEM;
3700       }
3701     }
3702 
3703     _args.nOptions = options->length();
3704     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3705     return JNI_OK;
3706   }
3707 
3708   JavaVMInitArgs* get()             { return &_args; }
3709   char* container_name()            { return _container_name; }
3710   bool  is_set()                    { return _is_set; }
3711   bool  found_vm_options_file_arg() { return _vm_options_file_arg != NULL; }
3712   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3713 
3714   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3715     if (_vm_options_file_arg != NULL) {
3716       os::free(_vm_options_file_arg);
3717     }
3718     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3719   }
3720 
3721   ~ScopedVMInitArgs() {
3722     if (_vm_options_file_arg != NULL) {
3723       os::free(_vm_options_file_arg);
3724     }
3725     if (_args.options == NULL) return;
3726     for (int i = 0; i < _args.nOptions; i++) {
3727       os::free(_args.options[i].optionString);
3728     }
3729     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3730   }
3731 
3732   // Insert options into this option list, to replace option at
3733   // vm_options_file_pos (-XX:VMOptionsFile)
3734   jint insert(const JavaVMInitArgs* args,
3735               const JavaVMInitArgs* args_to_insert,
3736               const int vm_options_file_pos) {
3737     assert(_args.options == NULL, "shouldn't be set yet");
3738     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3739     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3740 
3741     int length = args->nOptions + args_to_insert->nOptions - 1;
3742     GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments)
3743               GrowableArray<JavaVMOption>(length, true);    // Construct new option array
3744     for (int i = 0; i < args->nOptions; i++) {
3745       if (i == vm_options_file_pos) {
3746         // insert the new options starting at the same place as the
3747         // -XX:VMOptionsFile option
3748         for (int j = 0; j < args_to_insert->nOptions; j++) {
3749           options->push(args_to_insert->options[j]);
3750         }
3751       } else {
3752         options->push(args->options[i]);
3753       }
3754     }
3755     // make into options array
3756     jint result = set_args(options);
3757     delete options;
3758     return result;
3759   }
3760 };
3761 
3762 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3763   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3764 }
3765 
3766 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3767   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3768 }
3769 
3770 jint Arguments::parse_options_environment_variable(const char* name,
3771                                                    ScopedVMInitArgs* vm_args) {
3772   char *buffer = ::getenv(name);
3773 
3774   // Don't check this environment variable if user has special privileges
3775   // (e.g. unix su command).
3776   if (buffer == NULL || os::have_special_privileges()) {
3777     return JNI_OK;
3778   }
3779 
3780   if ((buffer = os::strdup(buffer)) == NULL) {
3781     return JNI_ENOMEM;
3782   }
3783 
3784   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3785 
3786   os::free(buffer);
3787   return retcode;
3788 }
3789 
3790 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3791   // read file into buffer
3792   int fd = ::open(file_name, O_RDONLY);
3793   if (fd < 0) {
3794     jio_fprintf(defaultStream::error_stream(),
3795                 "Could not open options file '%s'\n",
3796                 file_name);
3797     return JNI_ERR;
3798   }
3799 
3800   struct stat stbuf;
3801   int retcode = os::stat(file_name, &stbuf);
3802   if (retcode != 0) {
3803     jio_fprintf(defaultStream::error_stream(),
3804                 "Could not stat options file '%s'\n",
3805                 file_name);
3806     os::close(fd);
3807     return JNI_ERR;
3808   }
3809 
3810   if (stbuf.st_size == 0) {
3811     // tell caller there is no option data and that is ok
3812     os::close(fd);
3813     return JNI_OK;
3814   }
3815 
3816   // '+ 1' for NULL termination even with max bytes
3817   size_t bytes_alloc = stbuf.st_size + 1;
3818 
3819   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3820   if (NULL == buf) {
3821     jio_fprintf(defaultStream::error_stream(),
3822                 "Could not allocate read buffer for options file parse\n");
3823     os::close(fd);
3824     return JNI_ENOMEM;
3825   }
3826 
3827   memset(buf, 0, bytes_alloc);
3828 
3829   // Fill buffer
3830   // Use ::read() instead of os::read because os::read()
3831   // might do a thread state transition
3832   // and it is too early for that here
3833 
3834   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3835   os::close(fd);
3836   if (bytes_read < 0) {
3837     FREE_C_HEAP_ARRAY(char, buf);
3838     jio_fprintf(defaultStream::error_stream(),
3839                 "Could not read options file '%s'\n", file_name);
3840     return JNI_ERR;
3841   }
3842 
3843   if (bytes_read == 0) {
3844     // tell caller there is no option data and that is ok
3845     FREE_C_HEAP_ARRAY(char, buf);
3846     return JNI_OK;
3847   }
3848 
3849   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3850 
3851   FREE_C_HEAP_ARRAY(char, buf);
3852   return retcode;
3853 }
3854 
3855 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3856   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3857 
3858   // some pointers to help with parsing
3859   char *buffer_end = buffer + buf_len;
3860   char *opt_hd = buffer;
3861   char *wrt = buffer;
3862   char *rd = buffer;
3863 
3864   // parse all options
3865   while (rd < buffer_end) {
3866     // skip leading white space from the input string
3867     while (rd < buffer_end && isspace(*rd)) {
3868       rd++;
3869     }
3870 
3871     if (rd >= buffer_end) {
3872       break;
3873     }
3874 
3875     // Remember this is where we found the head of the token.
3876     opt_hd = wrt;
3877 
3878     // Tokens are strings of non white space characters separated
3879     // by one or more white spaces.
3880     while (rd < buffer_end && !isspace(*rd)) {
3881       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3882         int quote = *rd;                    // matching quote to look for
3883         rd++;                               // don't copy open quote
3884         while (rd < buffer_end && *rd != quote) {
3885                                             // include everything (even spaces)
3886                                             // up until the close quote
3887           *wrt++ = *rd++;                   // copy to option string
3888         }
3889 
3890         if (rd < buffer_end) {
3891           rd++;                             // don't copy close quote
3892         } else {
3893                                             // did not see closing quote
3894           jio_fprintf(defaultStream::error_stream(),
3895                       "Unmatched quote in %s\n", name);
3896           delete options;
3897           return JNI_ERR;
3898         }
3899       } else {
3900         *wrt++ = *rd++;                     // copy to option string
3901       }
3902     }
3903 
3904     // steal a white space character and set it to NULL
3905     *wrt++ = '\0';
3906     // We now have a complete token
3907 
3908     JavaVMOption option;
3909     option.optionString = opt_hd;
3910     option.extraInfo = NULL;
3911 
3912     options->append(option);                // Fill in option
3913 
3914     rd++;  // Advance to next character
3915   }
3916 
3917   // Fill out JavaVMInitArgs structure.
3918   jint status = vm_args->set_args(options);
3919 
3920   delete options;
3921   return status;
3922 }
3923 
3924 void Arguments::set_shared_spaces_flags() {
3925   if (DumpSharedSpaces) {
3926     if (Arguments::get_patch_mod_prefix() != NULL) {
3927       vm_exit_during_initialization(
3928         "Cannot use the following option when dumping the shared archive: --patch-module");
3929     }
3930 
3931     if (RequireSharedSpaces) {
3932       warning("Cannot dump shared archive while using shared archive");
3933     }
3934     UseSharedSpaces = false;
3935 #ifdef _LP64
3936     if (!UseCompressedOops || !UseCompressedClassPointers) {
3937       vm_exit_during_initialization(
3938         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3939     }
3940   } else {
3941     if (!UseCompressedOops || !UseCompressedClassPointers) {
3942       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3943     }
3944 #endif
3945   }
3946 }
3947 
3948 // Sharing support
3949 // Construct the path to the archive
3950 static char* get_shared_archive_path() {
3951   char *shared_archive_path;
3952   if (SharedArchiveFile == NULL) {
3953     char jvm_path[JVM_MAXPATHLEN];
3954     os::jvm_path(jvm_path, sizeof(jvm_path));
3955     char *end = strrchr(jvm_path, *os::file_separator());
3956     if (end != NULL) *end = '\0';
3957     size_t jvm_path_len = strlen(jvm_path);
3958     size_t file_sep_len = strlen(os::file_separator());
3959     const size_t len = jvm_path_len + file_sep_len + 20;
3960     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);
3961     if (shared_archive_path != NULL) {
3962       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3963         jvm_path, os::file_separator());
3964     }
3965   } else {
3966     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);
3967   }
3968   return shared_archive_path;
3969 }
3970 
3971 #ifndef PRODUCT
3972 // Determine whether LogVMOutput should be implicitly turned on.
3973 static bool use_vm_log() {
3974   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3975       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3976       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3977       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3978       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3979     return true;
3980   }
3981 
3982 #ifdef COMPILER1
3983   if (PrintC1Statistics) {
3984     return true;
3985   }
3986 #endif // COMPILER1
3987 
3988 #ifdef COMPILER2
3989   if (PrintOptoAssembly || PrintOptoStatistics) {
3990     return true;
3991   }
3992 #endif // COMPILER2
3993 
3994   return false;
3995 }
3996 
3997 #endif // PRODUCT
3998 
3999 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
4000   for (int index = 0; index < args->nOptions; index++) {
4001     const JavaVMOption* option = args->options + index;
4002     const char* tail;
4003     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
4004       return true;
4005     }
4006   }
4007   return false;
4008 }
4009 
4010 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
4011                                        const char* vm_options_file,
4012                                        const int vm_options_file_pos,
4013                                        ScopedVMInitArgs* vm_options_file_args,
4014                                        ScopedVMInitArgs* args_out) {
4015   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
4016   if (code != JNI_OK) {
4017     return code;
4018   }
4019 
4020   if (vm_options_file_args->get()->nOptions < 1) {
4021     return JNI_OK;
4022   }
4023 
4024   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
4025     jio_fprintf(defaultStream::error_stream(),
4026                 "A VM options file may not refer to a VM options file. "
4027                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
4028                 "options file '%s' in options container '%s' is an error.\n",
4029                 vm_options_file_args->vm_options_file_arg(),
4030                 vm_options_file_args->container_name());
4031     return JNI_EINVAL;
4032   }
4033 
4034   return args_out->insert(args, vm_options_file_args->get(),
4035                           vm_options_file_pos);
4036 }
4037 
4038 // Expand -XX:VMOptionsFile found in args_in as needed.
4039 // mod_args and args_out parameters may return values as needed.
4040 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
4041                                             ScopedVMInitArgs* mod_args,
4042                                             JavaVMInitArgs** args_out) {
4043   jint code = match_special_option_and_act(args_in, mod_args);
4044   if (code != JNI_OK) {
4045     return code;
4046   }
4047 
4048   if (mod_args->is_set()) {
4049     // args_in contains -XX:VMOptionsFile and mod_args contains the
4050     // original options from args_in along with the options expanded
4051     // from the VMOptionsFile. Return a short-hand to the caller.
4052     *args_out = mod_args->get();
4053   } else {
4054     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
4055   }
4056   return JNI_OK;
4057 }
4058 
4059 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
4060                                              ScopedVMInitArgs* args_out) {
4061   // Remaining part of option string
4062   const char* tail;
4063   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
4064 
4065   for (int index = 0; index < args->nOptions; index++) {
4066     const JavaVMOption* option = args->options + index;
4067     if (ArgumentsExt::process_options(option)) {
4068       continue;
4069     }
4070     if (match_option(option, "-XX:Flags=", &tail)) {
4071       Arguments::set_jvm_flags_file(tail);
4072       continue;
4073     }
4074     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
4075       if (vm_options_file_args.found_vm_options_file_arg()) {
4076         jio_fprintf(defaultStream::error_stream(),
4077                     "The option '%s' is already specified in the options "
4078                     "container '%s' so the specification of '%s' in the "
4079                     "same options container is an error.\n",
4080                     vm_options_file_args.vm_options_file_arg(),
4081                     vm_options_file_args.container_name(),
4082                     option->optionString);
4083         return JNI_EINVAL;
4084       }
4085       vm_options_file_args.set_vm_options_file_arg(option->optionString);
4086       // If there's a VMOptionsFile, parse that
4087       jint code = insert_vm_options_file(args, tail, index,
4088                                          &vm_options_file_args, args_out);
4089       if (code != JNI_OK) {
4090         return code;
4091       }
4092       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
4093       if (args_out->is_set()) {
4094         // The VMOptions file inserted some options so switch 'args'
4095         // to the new set of options, and continue processing which
4096         // preserves "last option wins" semantics.
4097         args = args_out->get();
4098         // The first option from the VMOptionsFile replaces the
4099         // current option.  So we back track to process the
4100         // replacement option.
4101         index--;
4102       }
4103       continue;
4104     }
4105     if (match_option(option, "-XX:+PrintVMOptions")) {
4106       PrintVMOptions = true;
4107       continue;
4108     }
4109     if (match_option(option, "-XX:-PrintVMOptions")) {
4110       PrintVMOptions = false;
4111       continue;
4112     }
4113     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
4114       IgnoreUnrecognizedVMOptions = true;
4115       continue;
4116     }
4117     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
4118       IgnoreUnrecognizedVMOptions = false;
4119       continue;
4120     }
4121     if (match_option(option, "-XX:+PrintFlagsInitial")) {
4122       CommandLineFlags::printFlags(tty, false);
4123       vm_exit(0);
4124     }
4125     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
4126 #if INCLUDE_NMT
4127       // The launcher did not setup nmt environment variable properly.
4128       if (!MemTracker::check_launcher_nmt_support(tail)) {
4129         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
4130       }
4131 
4132       // Verify if nmt option is valid.
4133       if (MemTracker::verify_nmt_option()) {
4134         // Late initialization, still in single-threaded mode.
4135         if (MemTracker::tracking_level() >= NMT_summary) {
4136           MemTracker::init();
4137         }
4138       } else {
4139         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
4140       }
4141       continue;
4142 #else
4143       jio_fprintf(defaultStream::error_stream(),
4144         "Native Memory Tracking is not supported in this VM\n");
4145       return JNI_ERR;
4146 #endif
4147     }
4148 
4149 #ifndef PRODUCT
4150     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
4151       CommandLineFlags::printFlags(tty, true);
4152       vm_exit(0);
4153     }
4154 #endif
4155   }
4156   return JNI_OK;
4157 }
4158 
4159 static void print_options(const JavaVMInitArgs *args) {
4160   const char* tail;
4161   for (int index = 0; index < args->nOptions; index++) {
4162     const JavaVMOption *option = args->options + index;
4163     if (match_option(option, "-XX:", &tail)) {
4164       logOption(tail);
4165     }
4166   }
4167 }
4168 
4169 bool Arguments::handle_deprecated_print_gc_flags() {
4170   if (PrintGC) {
4171     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
4172   }
4173   if (PrintGCDetails) {
4174     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
4175   }
4176 
4177   if (_gc_log_filename != NULL) {
4178     // -Xloggc was used to specify a filename
4179     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
4180 
4181     LogTarget(Error, logging) target;
4182     LogStreamCHeap errstream(target);
4183     return LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, &errstream);
4184   } else if (PrintGC || PrintGCDetails) {
4185     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
4186   }
4187   return true;
4188 }
4189 
4190 // Parse entry point called from JNI_CreateJavaVM
4191 
4192 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
4193   assert(verify_special_jvm_flags(), "deprecated and obsolete flag table inconsistent");
4194 
4195   // Initialize ranges, constraints and writeables
4196   CommandLineFlagRangeList::init();
4197   CommandLineFlagConstraintList::init();
4198   CommandLineFlagWriteableList::init();
4199 
4200   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
4201   const char* hotspotrc = ".hotspotrc";
4202   bool settings_file_specified = false;
4203   bool needs_hotspotrc_warning = false;
4204   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4205   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
4206 
4207   // Pointers to current working set of containers
4208   JavaVMInitArgs* cur_cmd_args;
4209   JavaVMInitArgs* cur_java_options_args;
4210   JavaVMInitArgs* cur_java_tool_options_args;
4211 
4212   // Containers for modified/expanded options
4213   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
4214   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4215   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
4216 
4217 
4218   jint code =
4219       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
4220   if (code != JNI_OK) {
4221     return code;
4222   }
4223 
4224   code = parse_java_options_environment_variable(&initial_java_options_args);
4225   if (code != JNI_OK) {
4226     return code;
4227   }
4228 
4229   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
4230                                      &mod_java_tool_options_args,
4231                                      &cur_java_tool_options_args);
4232   if (code != JNI_OK) {
4233     return code;
4234   }
4235 
4236   code = expand_vm_options_as_needed(initial_cmd_args,
4237                                      &mod_cmd_args,
4238                                      &cur_cmd_args);
4239   if (code != JNI_OK) {
4240     return code;
4241   }
4242 
4243   code = expand_vm_options_as_needed(initial_java_options_args.get(),
4244                                      &mod_java_options_args,
4245                                      &cur_java_options_args);
4246   if (code != JNI_OK) {
4247     return code;
4248   }
4249 
4250   const char* flags_file = Arguments::get_jvm_flags_file();
4251   settings_file_specified = (flags_file != NULL);
4252 
4253   if (IgnoreUnrecognizedVMOptions) {
4254     cur_cmd_args->ignoreUnrecognized = true;
4255     cur_java_tool_options_args->ignoreUnrecognized = true;
4256     cur_java_options_args->ignoreUnrecognized = true;
4257   }
4258 
4259   // Parse specified settings file
4260   if (settings_file_specified) {
4261     if (!process_settings_file(flags_file, true,
4262                                cur_cmd_args->ignoreUnrecognized)) {
4263       return JNI_EINVAL;
4264     }
4265   } else {
4266 #ifdef ASSERT
4267     // Parse default .hotspotrc settings file
4268     if (!process_settings_file(".hotspotrc", false,
4269                                cur_cmd_args->ignoreUnrecognized)) {
4270       return JNI_EINVAL;
4271     }
4272 #else
4273     struct stat buf;
4274     if (os::stat(hotspotrc, &buf) == 0) {
4275       needs_hotspotrc_warning = true;
4276     }
4277 #endif
4278   }
4279 
4280   if (PrintVMOptions) {
4281     print_options(cur_java_tool_options_args);
4282     print_options(cur_cmd_args);
4283     print_options(cur_java_options_args);
4284   }
4285 
4286   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
4287   jint result = parse_vm_init_args(cur_java_tool_options_args,
4288                                    cur_java_options_args,
4289                                    cur_cmd_args);
4290 
4291   if (result != JNI_OK) {
4292     return result;
4293   }
4294 
4295   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
4296   SharedArchivePath = get_shared_archive_path();
4297   if (SharedArchivePath == NULL) {
4298     return JNI_ENOMEM;
4299   }
4300 
4301   // Set up VerifySharedSpaces
4302   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
4303     VerifySharedSpaces = true;
4304   }
4305 
4306   // Delay warning until here so that we've had a chance to process
4307   // the -XX:-PrintWarnings flag
4308   if (needs_hotspotrc_warning) {
4309     warning("%s file is present but has been ignored.  "
4310             "Run with -XX:Flags=%s to load the file.",
4311             hotspotrc, hotspotrc);
4312   }
4313 
4314   if (needs_module_property_warning) {
4315     warning("Ignoring system property options whose names match the '-Djdk.module.*'."
4316             " names that are reserved for internal use.");
4317   }
4318 
4319 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
4320   UNSUPPORTED_OPTION(UseLargePages);
4321 #endif
4322 
4323   ArgumentsExt::report_unsupported_options();
4324 
4325 #ifndef PRODUCT
4326   if (TraceBytecodesAt != 0) {
4327     TraceBytecodes = true;
4328   }
4329   if (CountCompiledCalls) {
4330     if (UseCounterDecay) {
4331       warning("UseCounterDecay disabled because CountCalls is set");
4332       UseCounterDecay = false;
4333     }
4334   }
4335 #endif // PRODUCT
4336 
4337   if (ScavengeRootsInCode == 0) {
4338     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4339       warning("Forcing ScavengeRootsInCode non-zero");
4340     }
4341     ScavengeRootsInCode = 1;
4342   }
4343 
4344   if (!handle_deprecated_print_gc_flags()) {
4345     return JNI_EINVAL;
4346   }
4347 
4348   // Set object alignment values.
4349   set_object_alignment();
4350 
4351 #if !INCLUDE_CDS
4352   if (DumpSharedSpaces || RequireSharedSpaces) {
4353     jio_fprintf(defaultStream::error_stream(),
4354       "Shared spaces are not supported in this VM\n");
4355     return JNI_ERR;
4356   }
4357   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
4358     warning("Shared spaces are not supported in this VM");
4359     FLAG_SET_DEFAULT(UseSharedSpaces, false);
4360     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
4361   }
4362   no_shared_spaces("CDS Disabled");
4363 #endif // INCLUDE_CDS
4364 
4365   return JNI_OK;
4366 }
4367 
4368 jint Arguments::apply_ergo() {
4369 
4370   // Set flags based on ergonomics.
4371   set_ergonomics_flags();
4372 
4373   set_shared_spaces_flags();
4374 
4375   // Check the GC selections again.
4376   if (!check_gc_consistency()) {
4377     return JNI_EINVAL;
4378   }
4379 
4380   if (TieredCompilation) {
4381     set_tiered_flags();
4382   } else {
4383     int max_compilation_policy_choice = 1;
4384 #ifdef COMPILER2
4385     max_compilation_policy_choice = 2;
4386 #endif
4387     // Check if the policy is valid.
4388     if (CompilationPolicyChoice >= max_compilation_policy_choice) {
4389       vm_exit_during_initialization(
4390         "Incompatible compilation policy selected", NULL);
4391     }
4392     // Scale CompileThreshold
4393     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
4394     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
4395       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
4396     }
4397   }
4398 
4399 #ifdef COMPILER2
4400 #ifndef PRODUCT
4401   if (PrintIdealGraphLevel > 0) {
4402     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
4403   }
4404 #endif
4405 #endif
4406 
4407   // Set heap size based on available physical memory
4408   set_heap_size();
4409 
4410   ArgumentsExt::set_gc_specific_flags();
4411 
4412   // Initialize Metaspace flags and alignments
4413   Metaspace::ergo_initialize();
4414 
4415   // Set bytecode rewriting flags
4416   set_bytecode_flags();
4417 
4418   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
4419   jint code = set_aggressive_opts_flags();
4420   if (code != JNI_OK) {
4421     return code;
4422   }
4423 
4424   // Turn off biased locking for locking debug mode flags,
4425   // which are subtly different from each other but neither works with
4426   // biased locking
4427   if (UseHeavyMonitors
4428 #ifdef COMPILER1
4429       || !UseFastLocking
4430 #endif // COMPILER1
4431 #if INCLUDE_JVMCI
4432       || !JVMCIUseFastLocking
4433 #endif
4434     ) {
4435     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4436       // flag set to true on command line; warn the user that they
4437       // can't enable biased locking here
4438       warning("Biased Locking is not supported with locking debug flags"
4439               "; ignoring UseBiasedLocking flag." );
4440     }
4441     UseBiasedLocking = false;
4442   }
4443 
4444 #ifdef CC_INTERP
4445   // Clear flags not supported on zero.
4446   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4447   FLAG_SET_DEFAULT(UseBiasedLocking, false);
4448   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4449   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4450 #endif // CC_INTERP
4451 
4452 #ifdef COMPILER2
4453   if (!EliminateLocks) {
4454     EliminateNestedLocks = false;
4455   }
4456   if (!Inline) {
4457     IncrementalInline = false;
4458   }
4459 #ifndef PRODUCT
4460   if (!IncrementalInline) {
4461     AlwaysIncrementalInline = false;
4462   }
4463 #endif
4464   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
4465     // nothing to use the profiling, turn if off
4466     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
4467   }
4468 #endif
4469 
4470   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4471     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4472     DebugNonSafepoints = true;
4473   }
4474 
4475   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4476     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4477   }
4478 
4479   if (UseOnStackReplacement && !UseLoopCounter) {
4480     warning("On-stack-replacement requires loop counters; enabling loop counters");
4481     FLAG_SET_DEFAULT(UseLoopCounter, true);
4482   }
4483 
4484 #ifndef PRODUCT
4485   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4486     if (use_vm_log()) {
4487       LogVMOutput = true;
4488     }
4489   }
4490 #endif // PRODUCT
4491 
4492   if (PrintCommandLineFlags) {
4493     CommandLineFlags::printSetFlags(tty);
4494   }
4495 
4496   // Apply CPU specific policy for the BiasedLocking
4497   if (UseBiasedLocking) {
4498     if (!VM_Version::use_biased_locking() &&
4499         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4500       UseBiasedLocking = false;
4501     }
4502   }
4503 #ifdef COMPILER2
4504   if (!UseBiasedLocking || EmitSync != 0) {
4505     UseOptoBiasInlining = false;
4506   }
4507 #endif
4508 
4509   return JNI_OK;
4510 }
4511 
4512 jint Arguments::adjust_after_os() {
4513   if (UseNUMA) {
4514     if (UseParallelGC || UseParallelOldGC) {
4515       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4516          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4517       }
4518     }
4519     // UseNUMAInterleaving is set to ON for all collectors and
4520     // platforms when UseNUMA is set to ON. NUMA-aware collectors
4521     // such as the parallel collector for Linux and Solaris will
4522     // interleave old gen and survivor spaces on top of NUMA
4523     // allocation policy for the eden space.
4524     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4525     // all platforms and ParallelGC on Windows will interleave all
4526     // of the heap spaces across NUMA nodes.
4527     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4528       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4529     }
4530   }
4531   return JNI_OK;
4532 }
4533 
4534 int Arguments::PropertyList_count(SystemProperty* pl) {
4535   int count = 0;
4536   while(pl != NULL) {
4537     count++;
4538     pl = pl->next();
4539   }
4540   return count;
4541 }
4542 
4543 // Return the number of readable properties.
4544 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
4545   int count = 0;
4546   while(pl != NULL) {
4547     if (pl->is_readable()) {
4548       count++;
4549     }
4550     pl = pl->next();
4551   }
4552   return count;
4553 }
4554 
4555 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4556   assert(key != NULL, "just checking");
4557   SystemProperty* prop;
4558   for (prop = pl; prop != NULL; prop = prop->next()) {
4559     if (strcmp(key, prop->key()) == 0) return prop->value();
4560   }
4561   return NULL;
4562 }
4563 
4564 // Return the value of the requested property provided that it is a readable property.
4565 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4566   assert(key != NULL, "just checking");
4567   SystemProperty* prop;
4568   // Return the property value if the keys match and the property is not internal or
4569   // it's the special internal property "jdk.boot.class.path.append".
4570   for (prop = pl; prop != NULL; prop = prop->next()) {
4571     if (strcmp(key, prop->key()) == 0) {
4572       if (!prop->internal()) {
4573         return prop->value();
4574       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4575         return prop->value();
4576       } else {
4577         // Property is internal and not jdk.boot.class.path.append so return NULL.
4578         return NULL;
4579       }
4580     }
4581   }
4582   return NULL;
4583 }
4584 
4585 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4586   int count = 0;
4587   const char* ret_val = NULL;
4588 
4589   while(pl != NULL) {
4590     if(count >= index) {
4591       ret_val = pl->key();
4592       break;
4593     }
4594     count++;
4595     pl = pl->next();
4596   }
4597 
4598   return ret_val;
4599 }
4600 
4601 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4602   int count = 0;
4603   char* ret_val = NULL;
4604 
4605   while(pl != NULL) {
4606     if(count >= index) {
4607       ret_val = pl->value();
4608       break;
4609     }
4610     count++;
4611     pl = pl->next();
4612   }
4613 
4614   return ret_val;
4615 }
4616 
4617 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4618   SystemProperty* p = *plist;
4619   if (p == NULL) {
4620     *plist = new_p;
4621   } else {
4622     while (p->next() != NULL) {
4623       p = p->next();
4624     }
4625     p->set_next(new_p);
4626   }
4627 }
4628 
4629 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4630                                  bool writeable, bool internal) {
4631   if (plist == NULL)
4632     return;
4633 
4634   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4635   PropertyList_add(plist, new_p);
4636 }
4637 
4638 void Arguments::PropertyList_add(SystemProperty *element) {
4639   PropertyList_add(&_system_properties, element);
4640 }
4641 
4642 // This add maintains unique property key in the list.
4643 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4644                                         PropertyAppendable append, PropertyWriteable writeable,
4645                                         PropertyInternal internal) {
4646   if (plist == NULL)
4647     return;
4648 
4649   // If property key exist then update with new value.
4650   SystemProperty* prop;
4651   for (prop = *plist; prop != NULL; prop = prop->next()) {
4652     if (strcmp(k, prop->key()) == 0) {
4653       if (append == AppendProperty) {
4654         prop->append_value(v);
4655       } else {
4656         prop->set_value(v);
4657       }
4658       return;
4659     }
4660   }
4661 
4662   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4663 }
4664 
4665 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4666 // Returns true if all of the source pointed by src has been copied over to
4667 // the destination buffer pointed by buf. Otherwise, returns false.
4668 // Notes:
4669 // 1. If the length (buflen) of the destination buffer excluding the
4670 // NULL terminator character is not long enough for holding the expanded
4671 // pid characters, it also returns false instead of returning the partially
4672 // expanded one.
4673 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4674 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4675                                 char* buf, size_t buflen) {
4676   const char* p = src;
4677   char* b = buf;
4678   const char* src_end = &src[srclen];
4679   char* buf_end = &buf[buflen - 1];
4680 
4681   while (p < src_end && b < buf_end) {
4682     if (*p == '%') {
4683       switch (*(++p)) {
4684       case '%':         // "%%" ==> "%"
4685         *b++ = *p++;
4686         break;
4687       case 'p':  {       //  "%p" ==> current process id
4688         // buf_end points to the character before the last character so
4689         // that we could write '\0' to the end of the buffer.
4690         size_t buf_sz = buf_end - b + 1;
4691         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4692 
4693         // if jio_snprintf fails or the buffer is not long enough to hold
4694         // the expanded pid, returns false.
4695         if (ret < 0 || ret >= (int)buf_sz) {
4696           return false;
4697         } else {
4698           b += ret;
4699           assert(*b == '\0', "fail in copy_expand_pid");
4700           if (p == src_end && b == buf_end + 1) {
4701             // reach the end of the buffer.
4702             return true;
4703           }
4704         }
4705         p++;
4706         break;
4707       }
4708       default :
4709         *b++ = '%';
4710       }
4711     } else {
4712       *b++ = *p++;
4713     }
4714   }
4715   *b = '\0';
4716   return (p == src_end); // return false if not all of the source was copied
4717 }