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