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