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