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