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