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