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