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