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