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