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