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