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