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