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