rev 10538 : Tobias's loop opts patch
rev 10541 : remove -Xint from runtime tests + force TieredCompilation off

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