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