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