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 (CheckEndorsedAndExtDirs) {
3348     int nonEmptyDirs = 0;
3349     // check endorsed directory
3350     nonEmptyDirs += check_non_empty_dirs(path);
3351     // check the extension directories
3352     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3353     if (nonEmptyDirs > 0) {
3354       return JNI_ERR;
3355     }
3356   }
3357 
3358   DIR* dir = os::opendir(path);
3359   if (dir != NULL) {
3360     jio_fprintf(defaultStream::output_stream(),
3361       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3362       "in modular form will be supported via the concept of upgradeable modules.\n");
3363     os::closedir(dir);
3364     return JNI_ERR;
3365   }
3366 
3367   sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3368   dir = os::opendir(path);
3369   if (dir != NULL) {
3370     jio_fprintf(defaultStream::output_stream(),
3371       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3372       "Use -classpath instead.\n.");
3373     os::closedir(dir);
3374     return JNI_ERR;
3375   }
3376 
3377   if (scp_assembly_required) {
3378     // Assemble the bootclasspath elements into the final path.
3379     char *combined_path = scp_p->combined_path();
3380     Arguments::set_sysclasspath(combined_path);
3381     FREE_C_HEAP_ARRAY(char, combined_path);
3382   }
3383 
3384   // This must be done after all arguments have been processed.
3385   // java_compiler() true means set to "NONE" or empty.
3386   if (java_compiler() && !xdebug_mode()) {
3387     // For backwards compatibility, we switch to interpreted mode if
3388     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3389     // not specified.
3390     set_mode_flags(_int);
3391   }
3392 
3393   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3394   // but like -Xint, leave compilation thresholds unaffected.
3395   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3396   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3397     set_mode_flags(_int);
3398   }
3399 
3400   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3401   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3402     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3403   }
3404 
3405 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3406   // Don't degrade server performance for footprint
3407   if (FLAG_IS_DEFAULT(UseLargePages) &&
3408       MaxHeapSize < LargePageHeapSizeThreshold) {
3409     // No need for large granularity pages w/small heaps.
3410     // Note that large pages are enabled/disabled for both the
3411     // Java heap and the code cache.
3412     FLAG_SET_DEFAULT(UseLargePages, false);
3413   }
3414 
3415 #elif defined(COMPILER2)
3416   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3417     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3418   }
3419 #endif
3420 
3421 #ifndef TIERED
3422   // Tiered compilation is undefined.
3423   UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
3424 #endif
3425 
3426   // If we are running in a headless jre, force java.awt.headless property
3427   // to be true unless the property has already been set.
3428   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3429   if (os::is_headless_jre()) {
3430     const char* headless = Arguments::get_property("java.awt.headless");
3431     if (headless == NULL) {
3432       const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3433       if (headless_env == NULL) {
3434         if (!add_property("java.awt.headless=true")) {
3435           return JNI_ENOMEM;
3436         }
3437       } else {
3438         char buffer[256];
3439         jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3440         if (!add_property(buffer)) {
3441           return JNI_ENOMEM;
3442         }
3443       }
3444     }
3445   }
3446 
3447   if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3448     // CMS can only be used with ParNew
3449     FLAG_SET_ERGO(bool, UseParNewGC, true);
3450   }
3451 
3452   if (!check_vm_args_consistency()) {
3453     return JNI_ERR;
3454   }
3455 
3456   return JNI_OK;
3457 }
3458 
3459 // Helper class for controlling the lifetime of JavaVMInitArgs
3460 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3461 // deleted on the destruction of the ScopedVMInitArgs object.
3462 class ScopedVMInitArgs : public StackObj {
3463  private:
3464   JavaVMInitArgs _args;
3465   bool           _is_set;
3466 
3467  public:
3468   ScopedVMInitArgs() {
3469     _args.version = JNI_VERSION_1_2;
3470     _args.nOptions = 0;
3471     _args.options = NULL;
3472     _args.ignoreUnrecognized = false;
3473     _is_set = false;
3474   }
3475 
3476   // Populates the JavaVMInitArgs object represented by this
3477   // ScopedVMInitArgs object with the arguments in options.  The
3478   // allocated memory is deleted by the destructor.  If this method
3479   // returns anything other than JNI_OK, then this object is in a
3480   // partially constructed state, and should be abandoned.
3481   jint set_args(GrowableArray<JavaVMOption>* options) {
3482     _is_set = true;
3483     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3484         JavaVMOption, options->length(), mtInternal);
3485     if (options_arr == NULL) {
3486       return JNI_ENOMEM;
3487     }
3488     _args.options = options_arr;
3489 
3490     for (int i = 0; i < options->length(); i++) {
3491       options_arr[i] = options->at(i);
3492       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3493       if (options_arr[i].optionString == NULL) {
3494         // Rely on the destructor to do cleanup.
3495         _args.nOptions = i;
3496         return JNI_ENOMEM;
3497       }
3498     }
3499 
3500     _args.nOptions = options->length();
3501     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3502     return JNI_OK;
3503   }
3504 
3505   JavaVMInitArgs* get() { return &_args; }
3506   bool is_set()         { return _is_set; }
3507 
3508   ~ScopedVMInitArgs() {
3509     if (_args.options == NULL) return;
3510     for (int i = 0; i < _args.nOptions; i++) {
3511       os::free(_args.options[i].optionString);
3512     }
3513     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3514   }
3515 
3516   // Insert options into this option list, to replace option at
3517   // vm_options_file_pos (-XX:VMOptionsFile)
3518   jint insert(const JavaVMInitArgs* args,
3519               const JavaVMInitArgs* args_to_insert,
3520               const int vm_options_file_pos) {
3521     assert(_args.options == NULL, "shouldn't be set yet");
3522     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3523     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3524 
3525     int length = args->nOptions + args_to_insert->nOptions - 1;
3526     GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal)
3527               GrowableArray<JavaVMOption>(length, true);    // Construct new option array
3528     for (int i = 0; i < args->nOptions; i++) {
3529       if (i == vm_options_file_pos) {
3530         // insert the new options starting at the same place as the
3531         // -XX:VMOptionsFile option
3532         for (int j = 0; j < args_to_insert->nOptions; j++) {
3533           options->push(args_to_insert->options[j]);
3534         }
3535       } else {
3536         options->push(args->options[i]);
3537       }
3538     }
3539     // make into options array
3540     jint result = set_args(options);
3541     delete options;
3542     return result;
3543   }
3544 };
3545 
3546 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3547   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3548 }
3549 
3550 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3551   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3552 }
3553 
3554 jint Arguments::parse_options_environment_variable(const char* name,
3555                                                    ScopedVMInitArgs* vm_args) {
3556   char *buffer = ::getenv(name);
3557 
3558   // Don't check this environment variable if user has special privileges
3559   // (e.g. unix su command).
3560   if (buffer == NULL || os::have_special_privileges()) {
3561     return JNI_OK;
3562   }
3563 
3564   if ((buffer = os::strdup(buffer)) == NULL) {
3565     return JNI_ENOMEM;
3566   }
3567 
3568   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3569 
3570   os::free(buffer);
3571   return retcode;
3572 }
3573 
3574 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3575   // read file into buffer
3576   int fd = ::open(file_name, O_RDONLY);
3577   if (fd < 0) {
3578     jio_fprintf(defaultStream::error_stream(),
3579                 "Could not open options file '%s'\n",
3580                 file_name);
3581     return JNI_ERR;
3582   }
3583 
3584   struct stat stbuf;
3585   int retcode = os::stat(file_name, &stbuf);
3586   if (retcode != 0) {
3587     jio_fprintf(defaultStream::error_stream(),
3588                 "Could not stat options file '%s'\n",
3589                 file_name);
3590     os::close(fd);
3591     return JNI_ERR;
3592   }
3593 
3594   if (stbuf.st_size == 0) {
3595     // tell caller there is no option data and that is ok
3596     os::close(fd);
3597     return JNI_OK;
3598   }
3599 
3600   // '+ 1' for NULL termination even with max bytes
3601   size_t bytes_alloc = stbuf.st_size + 1;
3602 
3603   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtInternal);
3604   if (NULL == buf) {
3605     jio_fprintf(defaultStream::error_stream(),
3606                 "Could not allocate read buffer for options file parse\n");
3607     os::close(fd);
3608     return JNI_ENOMEM;
3609   }
3610 
3611   memset(buf, 0, bytes_alloc);
3612 
3613   // Fill buffer
3614   // Use ::read() instead of os::read because os::read()
3615   // might do a thread state transition
3616   // and it is too early for that here
3617 
3618   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3619   os::close(fd);
3620   if (bytes_read < 0) {
3621     FREE_C_HEAP_ARRAY(char, buf);
3622     jio_fprintf(defaultStream::error_stream(),
3623                 "Could not read options file '%s'\n", file_name);
3624     return JNI_ERR;
3625   }
3626 
3627   if (bytes_read == 0) {
3628     // tell caller there is no option data and that is ok
3629     FREE_C_HEAP_ARRAY(char, buf);
3630     return JNI_OK;
3631   }
3632 
3633   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3634 
3635   FREE_C_HEAP_ARRAY(char, buf);
3636   return retcode;
3637 }
3638 
3639 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3640   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3641 
3642   // some pointers to help with parsing
3643   char *buffer_end = buffer + buf_len;
3644   char *opt_hd = buffer;
3645   char *wrt = buffer;
3646   char *rd = buffer;
3647 
3648   // parse all options
3649   while (rd < buffer_end) {
3650     // skip leading white space from the input string
3651     while (rd < buffer_end && isspace(*rd)) {
3652       rd++;
3653     }
3654 
3655     if (rd >= buffer_end) {
3656       break;
3657     }
3658 
3659     // Remember this is where we found the head of the token.
3660     opt_hd = wrt;
3661 
3662     // Tokens are strings of non white space characters separated
3663     // by one or more white spaces.
3664     while (rd < buffer_end && !isspace(*rd)) {
3665       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3666         int quote = *rd;                    // matching quote to look for
3667         rd++;                               // don't copy open quote
3668         while (rd < buffer_end && *rd != quote) {
3669                                             // include everything (even spaces)
3670                                             // up until the close quote
3671           *wrt++ = *rd++;                   // copy to option string
3672         }
3673 
3674         if (rd < buffer_end) {
3675           rd++;                             // don't copy close quote
3676         } else {
3677                                             // did not see closing quote
3678           jio_fprintf(defaultStream::error_stream(),
3679                       "Unmatched quote in %s\n", name);
3680           delete options;
3681           return JNI_ERR;
3682         }
3683       } else {
3684         *wrt++ = *rd++;                     // copy to option string
3685       }
3686     }
3687 
3688     // steal a white space character and set it to NULL
3689     *wrt++ = '\0';
3690     // We now have a complete token
3691 
3692     JavaVMOption option;
3693     option.optionString = opt_hd;
3694     option.extraInfo = NULL;
3695 
3696     options->append(option);                // Fill in option
3697 
3698     rd++;  // Advance to next character
3699   }
3700 
3701   // Fill out JavaVMInitArgs structure.
3702   jint status = vm_args->set_args(options);
3703 
3704   delete options;
3705   return status;
3706 }
3707 
3708 void Arguments::set_shared_spaces_flags() {
3709   if (DumpSharedSpaces) {
3710     if (RequireSharedSpaces) {
3711       warning("Cannot dump shared archive while using shared archive");
3712     }
3713     UseSharedSpaces = false;
3714 #ifdef _LP64
3715     if (!UseCompressedOops || !UseCompressedClassPointers) {
3716       vm_exit_during_initialization(
3717         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3718     }
3719   } else {
3720     if (!UseCompressedOops || !UseCompressedClassPointers) {
3721       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3722     }
3723 #endif
3724   }
3725 }
3726 
3727 #if !INCLUDE_ALL_GCS
3728 static void force_serial_gc() {
3729   FLAG_SET_DEFAULT(UseSerialGC, true);
3730   UNSUPPORTED_GC_OPTION(UseG1GC);
3731   UNSUPPORTED_GC_OPTION(UseParallelGC);
3732   UNSUPPORTED_GC_OPTION(UseParallelOldGC);
3733   UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
3734   UNSUPPORTED_GC_OPTION(UseParNewGC);
3735 }
3736 #endif // INCLUDE_ALL_GCS
3737 
3738 // Sharing support
3739 // Construct the path to the archive
3740 static char* get_shared_archive_path() {
3741   char *shared_archive_path;
3742   if (SharedArchiveFile == NULL) {
3743     char jvm_path[JVM_MAXPATHLEN];
3744     os::jvm_path(jvm_path, sizeof(jvm_path));
3745     char *end = strrchr(jvm_path, *os::file_separator());
3746     if (end != NULL) *end = '\0';
3747     size_t jvm_path_len = strlen(jvm_path);
3748     size_t file_sep_len = strlen(os::file_separator());
3749     const size_t len = jvm_path_len + file_sep_len + 20;
3750     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtInternal);
3751     if (shared_archive_path != NULL) {
3752       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3753         jvm_path, os::file_separator());
3754     }
3755   } else {
3756     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtInternal);
3757   }
3758   return shared_archive_path;
3759 }
3760 
3761 #ifndef PRODUCT
3762 // Determine whether LogVMOutput should be implicitly turned on.
3763 static bool use_vm_log() {
3764   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3765       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3766       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3767       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3768       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3769     return true;
3770   }
3771 
3772 #ifdef COMPILER1
3773   if (PrintC1Statistics) {
3774     return true;
3775   }
3776 #endif // COMPILER1
3777 
3778 #ifdef COMPILER2
3779   if (PrintOptoAssembly || PrintOptoStatistics) {
3780     return true;
3781   }
3782 #endif // COMPILER2
3783 
3784   return false;
3785 }
3786 
3787 #endif // PRODUCT
3788 
3789 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3790                                        char** vm_options_file,
3791                                        const int vm_options_file_pos,
3792                                        ScopedVMInitArgs *vm_options_file_args,
3793                                        ScopedVMInitArgs* args_out) {
3794   jint code = parse_vm_options_file(*vm_options_file, vm_options_file_args);
3795   if (code != JNI_OK) {
3796     return code;
3797   }
3798 
3799   if (vm_options_file_args->get()->nOptions < 1) {
3800     return JNI_OK;
3801   }
3802 
3803   return args_out->insert(args, vm_options_file_args->get(),
3804                           vm_options_file_pos);
3805 }
3806 
3807 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3808                                              char ** vm_options_file,
3809                                              ScopedVMInitArgs* args_out) {
3810   // Remaining part of option string
3811   const char* tail;
3812   int   vm_options_file_pos = -1;
3813   ScopedVMInitArgs vm_options_file_args;
3814 
3815   for (int index = 0; index < args->nOptions; index++) {
3816     const JavaVMOption* option = args->options + index;
3817     if (ArgumentsExt::process_options(option)) {
3818       continue;
3819     }
3820     if (match_option(option, "-XX:Flags=", &tail)) {
3821       Arguments::set_jvm_flags_file(tail);
3822       continue;
3823     }
3824     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3825       if (vm_options_file != NULL) {
3826         // The caller accepts -XX:VMOptionsFile
3827         if (*vm_options_file != NULL) {
3828           jio_fprintf(defaultStream::error_stream(),
3829                       "The VM Options file can only be specified once and "
3830                       "only on the command line.\n");
3831           return JNI_EINVAL;
3832         }
3833 
3834         *vm_options_file = (char *) tail;
3835         vm_options_file_pos = index;  // save position of -XX:VMOptionsFile
3836         // If there's a VMOptionsFile, parse that (also can set flags_file)
3837         jint code = insert_vm_options_file(args, vm_options_file,
3838                                            vm_options_file_pos,
3839                                            &vm_options_file_args, args_out);
3840         if (code != JNI_OK) {
3841           return code;
3842         }
3843         if (args_out->is_set()) {
3844           // The VMOptions file inserted some options so switch 'args'
3845           // to the new set of options, and continue processing which
3846           // preserves "last option wins" semantics.
3847           args = args_out->get();
3848           // The first option from the VMOptionsFile replaces the
3849           // current option.  So we back track to process the
3850           // replacement option.
3851           index--;
3852         }
3853       } else {
3854         jio_fprintf(defaultStream::error_stream(),
3855                     "VM options file is only supported on the command line\n");
3856         return JNI_EINVAL;
3857       }
3858       continue;
3859     }
3860     if (match_option(option, "-XX:+PrintVMOptions")) {
3861       PrintVMOptions = true;
3862       continue;
3863     }
3864     if (match_option(option, "-XX:-PrintVMOptions")) {
3865       PrintVMOptions = false;
3866       continue;
3867     }
3868     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3869       IgnoreUnrecognizedVMOptions = true;
3870       continue;
3871     }
3872     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3873       IgnoreUnrecognizedVMOptions = false;
3874       continue;
3875     }
3876     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3877       CommandLineFlags::printFlags(tty, false);
3878       vm_exit(0);
3879     }
3880     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3881 #if INCLUDE_NMT
3882       // The launcher did not setup nmt environment variable properly.
3883       if (!MemTracker::check_launcher_nmt_support(tail)) {
3884         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3885       }
3886 
3887       // Verify if nmt option is valid.
3888       if (MemTracker::verify_nmt_option()) {
3889         // Late initialization, still in single-threaded mode.
3890         if (MemTracker::tracking_level() >= NMT_summary) {
3891           MemTracker::init();
3892         }
3893       } else {
3894         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3895       }
3896       continue;
3897 #else
3898       jio_fprintf(defaultStream::error_stream(),
3899         "Native Memory Tracking is not supported in this VM\n");
3900       return JNI_ERR;
3901 #endif
3902     }
3903 
3904 #ifndef PRODUCT
3905     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3906       CommandLineFlags::printFlags(tty, true);
3907       vm_exit(0);
3908     }
3909 #endif
3910   }
3911   return JNI_OK;
3912 }
3913 
3914 static void print_options(const JavaVMInitArgs *args) {
3915   const char* tail;
3916   for (int index = 0; index < args->nOptions; index++) {
3917     const JavaVMOption *option = args->options + index;
3918     if (match_option(option, "-XX:", &tail)) {
3919       logOption(tail);
3920     }
3921   }
3922 }
3923 
3924 // Parse entry point called from JNI_CreateJavaVM
3925 
3926 jint Arguments::parse(const JavaVMInitArgs* args) {
3927   assert(verify_special_jvm_flags(), "deprecated and obsolete flag table inconsistent");
3928 
3929   // Initialize ranges and constraints
3930   CommandLineFlagRangeList::init();
3931   CommandLineFlagConstraintList::init();
3932 
3933   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3934   const char* hotspotrc = ".hotspotrc";
3935   char* vm_options_file = NULL;
3936   bool settings_file_specified = false;
3937   bool needs_hotspotrc_warning = false;
3938   ScopedVMInitArgs java_tool_options_args;
3939   ScopedVMInitArgs java_options_args;
3940   ScopedVMInitArgs modified_cmd_line_args;
3941 
3942   jint code =
3943       parse_java_tool_options_environment_variable(&java_tool_options_args);
3944   if (code != JNI_OK) {
3945     return code;
3946   }
3947 
3948   code = parse_java_options_environment_variable(&java_options_args);
3949   if (code != JNI_OK) {
3950     return code;
3951   }
3952 
3953   code = match_special_option_and_act(java_tool_options_args.get(),
3954                                       NULL, NULL);
3955   if (code != JNI_OK) {
3956     return code;
3957   }
3958 
3959   code = match_special_option_and_act(args, &vm_options_file,
3960                                       &modified_cmd_line_args);
3961   if (code != JNI_OK) {
3962     return code;
3963   }
3964 
3965 
3966   // The command line arguments have been modified to include VMOptionsFile arguments.
3967   if (modified_cmd_line_args.is_set()) {
3968     args = modified_cmd_line_args.get();
3969   }
3970 
3971   code = match_special_option_and_act(java_options_args.get(),
3972                                       NULL, NULL);
3973   if (code != JNI_OK) {
3974     return code;
3975   }
3976 
3977   const char * flags_file = Arguments::get_jvm_flags_file();
3978   settings_file_specified = (flags_file != NULL);
3979 
3980   if (IgnoreUnrecognizedVMOptions) {
3981     // uncast const to modify the flag args->ignoreUnrecognized
3982     *(jboolean*)(&args->ignoreUnrecognized) = true;
3983     java_tool_options_args.get()->ignoreUnrecognized = true;
3984     java_options_args.get()->ignoreUnrecognized = true;
3985   }
3986 
3987   // Parse specified settings file
3988   if (settings_file_specified) {
3989     if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
3990       return JNI_EINVAL;
3991     }
3992   } else {
3993 #ifdef ASSERT
3994     // Parse default .hotspotrc settings file
3995     if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
3996       return JNI_EINVAL;
3997     }
3998 #else
3999     struct stat buf;
4000     if (os::stat(hotspotrc, &buf) == 0) {
4001       needs_hotspotrc_warning = true;
4002     }
4003 #endif
4004   }
4005 
4006   if (PrintVMOptions) {
4007     print_options(java_tool_options_args.get());
4008     print_options(args);
4009     print_options(java_options_args.get());
4010   }
4011 
4012   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
4013   jint result = parse_vm_init_args(java_tool_options_args.get(),
4014                                    java_options_args.get(),
4015                                    args);   // command line arguments
4016 
4017   if (result != JNI_OK) {
4018     return result;
4019   }
4020 
4021   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
4022   SharedArchivePath = get_shared_archive_path();
4023   if (SharedArchivePath == NULL) {
4024     return JNI_ENOMEM;
4025   }
4026 
4027   // Set up VerifySharedSpaces
4028   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
4029     VerifySharedSpaces = true;
4030   }
4031 
4032   // Delay warning until here so that we've had a chance to process
4033   // the -XX:-PrintWarnings flag
4034   if (needs_hotspotrc_warning) {
4035     warning("%s file is present but has been ignored.  "
4036             "Run with -XX:Flags=%s to load the file.",
4037             hotspotrc, hotspotrc);
4038   }
4039 
4040 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
4041   UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
4042 #endif
4043 
4044   ArgumentsExt::report_unsupported_options();
4045 
4046 #ifndef PRODUCT
4047   if (TraceBytecodesAt != 0) {
4048     TraceBytecodes = true;
4049   }
4050   if (CountCompiledCalls) {
4051     if (UseCounterDecay) {
4052       warning("UseCounterDecay disabled because CountCalls is set");
4053       UseCounterDecay = false;
4054     }
4055   }
4056 #endif // PRODUCT
4057 
4058   if (ScavengeRootsInCode == 0) {
4059     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4060       warning("Forcing ScavengeRootsInCode non-zero");
4061     }
4062     ScavengeRootsInCode = 1;
4063   }
4064 
4065   // Set object alignment values.
4066   set_object_alignment();
4067 
4068 #if !INCLUDE_ALL_GCS
4069   force_serial_gc();
4070 #endif // INCLUDE_ALL_GCS
4071 #if !INCLUDE_CDS
4072   if (DumpSharedSpaces || RequireSharedSpaces) {
4073     jio_fprintf(defaultStream::error_stream(),
4074       "Shared spaces are not supported in this VM\n");
4075     return JNI_ERR;
4076   }
4077   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
4078     warning("Shared spaces are not supported in this VM");
4079     FLAG_SET_DEFAULT(UseSharedSpaces, false);
4080     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
4081   }
4082   no_shared_spaces("CDS Disabled");
4083 #endif // INCLUDE_CDS
4084 
4085   return JNI_OK;
4086 }
4087 
4088 jint Arguments::apply_ergo() {
4089 
4090   // Set flags based on ergonomics.
4091   set_ergonomics_flags();
4092 
4093   set_shared_spaces_flags();
4094 
4095   // Check the GC selections again.
4096   if (!check_gc_consistency()) {
4097     return JNI_EINVAL;
4098   }
4099 
4100   if (TieredCompilation) {
4101     set_tiered_flags();
4102   } else {
4103     int max_compilation_policy_choice = 1;
4104 #ifdef COMPILER2
4105     max_compilation_policy_choice = 2;
4106 #endif
4107     // Check if the policy is valid.
4108     if (CompilationPolicyChoice >= max_compilation_policy_choice) {
4109       vm_exit_during_initialization(
4110         "Incompatible compilation policy selected", NULL);
4111     }
4112     // Scale CompileThreshold
4113     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
4114     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
4115       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
4116     }
4117   }
4118 
4119 #ifdef COMPILER2
4120 #ifndef PRODUCT
4121   if (PrintIdealGraphLevel > 0) {
4122     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
4123   }
4124 #endif
4125 #endif
4126 
4127   // Set heap size based on available physical memory
4128   set_heap_size();
4129 
4130   ArgumentsExt::set_gc_specific_flags();
4131 
4132   // Initialize Metaspace flags and alignments
4133   Metaspace::ergo_initialize();
4134 
4135   // Set bytecode rewriting flags
4136   set_bytecode_flags();
4137 
4138   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
4139   jint code = set_aggressive_opts_flags();
4140   if (code != JNI_OK) {
4141     return code;
4142   }
4143 
4144   // Turn off biased locking for locking debug mode flags,
4145   // which are subtly different from each other but neither works with
4146   // biased locking
4147   if (UseHeavyMonitors
4148 #ifdef COMPILER1
4149       || !UseFastLocking
4150 #endif // COMPILER1
4151 #if INCLUDE_JVMCI
4152       || !JVMCIUseFastLocking
4153 #endif
4154     ) {
4155     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4156       // flag set to true on command line; warn the user that they
4157       // can't enable biased locking here
4158       warning("Biased Locking is not supported with locking debug flags"
4159               "; ignoring UseBiasedLocking flag." );
4160     }
4161     UseBiasedLocking = false;
4162   }
4163 
4164 #ifdef ZERO
4165   // Clear flags not supported on zero.
4166   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4167   FLAG_SET_DEFAULT(UseBiasedLocking, false);
4168   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4169   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4170 #endif // CC_INTERP
4171 
4172 #ifdef COMPILER2
4173   if (!EliminateLocks) {
4174     EliminateNestedLocks = false;
4175   }
4176   if (!Inline) {
4177     IncrementalInline = false;
4178   }
4179 #ifndef PRODUCT
4180   if (!IncrementalInline) {
4181     AlwaysIncrementalInline = false;
4182   }
4183 #endif
4184   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
4185     // nothing to use the profiling, turn if off
4186     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
4187   }
4188 #endif
4189 
4190   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4191     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4192     DebugNonSafepoints = true;
4193   }
4194 
4195   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4196     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4197   }
4198 
4199 #ifndef PRODUCT
4200   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4201     if (use_vm_log()) {
4202       LogVMOutput = true;
4203     }
4204   }
4205 #endif // PRODUCT
4206 
4207   if (PrintCommandLineFlags) {
4208     CommandLineFlags::printSetFlags(tty);
4209   }
4210 
4211   // Apply CPU specific policy for the BiasedLocking
4212   if (UseBiasedLocking) {
4213     if (!VM_Version::use_biased_locking() &&
4214         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4215       UseBiasedLocking = false;
4216     }
4217   }
4218 #ifdef COMPILER2
4219   if (!UseBiasedLocking || EmitSync != 0) {
4220     UseOptoBiasInlining = false;
4221   }
4222 #endif
4223 
4224   return JNI_OK;
4225 }
4226 
4227 jint Arguments::adjust_after_os() {
4228   if (UseNUMA) {
4229     if (UseParallelGC || UseParallelOldGC) {
4230       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4231          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4232       }
4233     }
4234     // UseNUMAInterleaving is set to ON for all collectors and
4235     // platforms when UseNUMA is set to ON. NUMA-aware collectors
4236     // such as the parallel collector for Linux and Solaris will
4237     // interleave old gen and survivor spaces on top of NUMA
4238     // allocation policy for the eden space.
4239     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4240     // all platforms and ParallelGC on Windows will interleave all
4241     // of the heap spaces across NUMA nodes.
4242     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4243       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4244     }
4245   }
4246   return JNI_OK;
4247 }
4248 
4249 int Arguments::PropertyList_count(SystemProperty* pl) {
4250   int count = 0;
4251   while(pl != NULL) {
4252     count++;
4253     pl = pl->next();
4254   }
4255   return count;
4256 }
4257 
4258 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4259   assert(key != NULL, "just checking");
4260   SystemProperty* prop;
4261   for (prop = pl; prop != NULL; prop = prop->next()) {
4262     if (strcmp(key, prop->key()) == 0) return prop->value();
4263   }
4264   return NULL;
4265 }
4266 
4267 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4268   int count = 0;
4269   const char* ret_val = NULL;
4270 
4271   while(pl != NULL) {
4272     if(count >= index) {
4273       ret_val = pl->key();
4274       break;
4275     }
4276     count++;
4277     pl = pl->next();
4278   }
4279 
4280   return ret_val;
4281 }
4282 
4283 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4284   int count = 0;
4285   char* ret_val = NULL;
4286 
4287   while(pl != NULL) {
4288     if(count >= index) {
4289       ret_val = pl->value();
4290       break;
4291     }
4292     count++;
4293     pl = pl->next();
4294   }
4295 
4296   return ret_val;
4297 }
4298 
4299 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4300   SystemProperty* p = *plist;
4301   if (p == NULL) {
4302     *plist = new_p;
4303   } else {
4304     while (p->next() != NULL) {
4305       p = p->next();
4306     }
4307     p->set_next(new_p);
4308   }
4309 }
4310 
4311 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v) {
4312   if (plist == NULL)
4313     return;
4314 
4315   SystemProperty* new_p = new SystemProperty(k, v, true);
4316   PropertyList_add(plist, new_p);
4317 }
4318 
4319 void Arguments::PropertyList_add(SystemProperty *element) {
4320   PropertyList_add(&_system_properties, element);
4321 }
4322 
4323 // This add maintains unique property key in the list.
4324 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v, jboolean append) {
4325   if (plist == NULL)
4326     return;
4327 
4328   // If property key exist then update with new value.
4329   SystemProperty* prop;
4330   for (prop = *plist; prop != NULL; prop = prop->next()) {
4331     if (strcmp(k, prop->key()) == 0) {
4332       if (append) {
4333         prop->append_value(v);
4334       } else {
4335         prop->set_value(v);
4336       }
4337       return;
4338     }
4339   }
4340 
4341   PropertyList_add(plist, k, v);
4342 }
4343 
4344 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4345 // Returns true if all of the source pointed by src has been copied over to
4346 // the destination buffer pointed by buf. Otherwise, returns false.
4347 // Notes:
4348 // 1. If the length (buflen) of the destination buffer excluding the
4349 // NULL terminator character is not long enough for holding the expanded
4350 // pid characters, it also returns false instead of returning the partially
4351 // expanded one.
4352 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4353 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4354                                 char* buf, size_t buflen) {
4355   const char* p = src;
4356   char* b = buf;
4357   const char* src_end = &src[srclen];
4358   char* buf_end = &buf[buflen - 1];
4359 
4360   while (p < src_end && b < buf_end) {
4361     if (*p == '%') {
4362       switch (*(++p)) {
4363       case '%':         // "%%" ==> "%"
4364         *b++ = *p++;
4365         break;
4366       case 'p':  {       //  "%p" ==> current process id
4367         // buf_end points to the character before the last character so
4368         // that we could write '\0' to the end of the buffer.
4369         size_t buf_sz = buf_end - b + 1;
4370         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4371 
4372         // if jio_snprintf fails or the buffer is not long enough to hold
4373         // the expanded pid, returns false.
4374         if (ret < 0 || ret >= (int)buf_sz) {
4375           return false;
4376         } else {
4377           b += ret;
4378           assert(*b == '\0', "fail in copy_expand_pid");
4379           if (p == src_end && b == buf_end + 1) {
4380             // reach the end of the buffer.
4381             return true;
4382           }
4383         }
4384         p++;
4385         break;
4386       }
4387       default :
4388         *b++ = '%';
4389       }
4390     } else {
4391       *b++ = *p++;
4392     }
4393   }
4394   *b = '\0';
4395   return (p == src_end); // return false if not all of the source was copied
4396 }