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   return status;
2552 }
2553 
2554 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2555   const char* option_type) {
2556   if (ignore) return false;
2557 
2558   const char* spacer = " ";
2559   if (option_type == NULL) {
2560     option_type = ++spacer; // Set both to the empty string.
2561   }
2562 
2563   if (os::obsolete_option(option)) {
2564     jio_fprintf(defaultStream::error_stream(),
2565                 "Obsolete %s%soption: %s\n", option_type, spacer,
2566       option->optionString);
2567     return false;
2568   } else {
2569     jio_fprintf(defaultStream::error_stream(),
2570                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2571       option->optionString);
2572     return true;
2573   }
2574 }
2575 
2576 static const char* user_assertion_options[] = {
2577   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2578 };
2579 
2580 static const char* system_assertion_options[] = {
2581   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2582 };
2583 
2584 bool Arguments::parse_uintx(const char* value,
2585                             uintx* uintx_arg,
2586                             uintx min_size) {
2587 
2588   // Check the sign first since atomull() parses only unsigned values.
2589   bool value_is_positive = !(*value == '-');
2590 
2591   if (value_is_positive) {
2592     julong n;
2593     bool good_return = atomull(value, &n);
2594     if (good_return) {
2595       bool above_minimum = n >= min_size;
2596       bool value_is_too_large = n > max_uintx;
2597 
2598       if (above_minimum && !value_is_too_large) {
2599         *uintx_arg = n;
2600         return true;
2601       }
2602     }
2603   }
2604   return false;
2605 }
2606 
2607 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2608                                                   julong* long_arg,
2609                                                   julong min_size) {
2610   if (!atomull(s, long_arg)) return arg_unreadable;
2611   return check_memory_size(*long_arg, min_size);
2612 }
2613 
2614 // Parse JavaVMInitArgs structure
2615 
2616 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *java_tool_options_args,
2617                                    const JavaVMInitArgs *java_options_args,
2618                                    const JavaVMInitArgs *cmd_line_args) {
2619   // For components of the system classpath.
2620   SysClassPath scp(Arguments::get_sysclasspath());
2621   bool scp_assembly_required = false;
2622 
2623   // Save default settings for some mode flags
2624   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2625   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2626   Arguments::_ClipInlining             = ClipInlining;
2627   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2628   if (TieredCompilation) {
2629     Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2630     Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2631   }
2632 
2633   // Setup flags for mixed which is the default
2634   set_mode_flags(_mixed);
2635 
2636   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2637   // variable (if present).
2638   jint result = parse_each_vm_init_arg(
2639       java_tool_options_args, &scp, &scp_assembly_required, Flag::ENVIRON_VAR);
2640   if (result != JNI_OK) {
2641     return result;
2642   }
2643 
2644   // Parse args structure generated from the command line flags.
2645   result = parse_each_vm_init_arg(cmd_line_args, &scp, &scp_assembly_required,
2646                                   Flag::COMMAND_LINE);
2647   if (result != JNI_OK) {
2648     return result;
2649   }
2650 
2651   // Parse args structure generated from the _JAVA_OPTIONS environment
2652   // variable (if present) (mimics classic VM)
2653   result = parse_each_vm_init_arg(
2654       java_options_args, &scp, &scp_assembly_required, Flag::ENVIRON_VAR);
2655   if (result != JNI_OK) {
2656     return result;
2657   }
2658 
2659   // Do final processing now that all arguments have been parsed
2660   result = finalize_vm_init_args(&scp, scp_assembly_required);
2661   if (result != JNI_OK) {
2662     return result;
2663   }
2664 
2665   return JNI_OK;
2666 }
2667 
2668 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2669 // represents a valid JDWP agent.  is_path==true denotes that we
2670 // are dealing with -agentpath (case where name is a path), otherwise with
2671 // -agentlib
2672 bool valid_jdwp_agent(char *name, bool is_path) {
2673   char *_name;
2674   const char *_jdwp = "jdwp";
2675   size_t _len_jdwp, _len_prefix;
2676 
2677   if (is_path) {
2678     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2679       return false;
2680     }
2681 
2682     _name++;  // skip past last path separator
2683     _len_prefix = strlen(JNI_LIB_PREFIX);
2684 
2685     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2686       return false;
2687     }
2688 
2689     _name += _len_prefix;
2690     _len_jdwp = strlen(_jdwp);
2691 
2692     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2693       _name += _len_jdwp;
2694     }
2695     else {
2696       return false;
2697     }
2698 
2699     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2700       return false;
2701     }
2702 
2703     return true;
2704   }
2705 
2706   if (strcmp(name, _jdwp) == 0) {
2707     return true;
2708   }
2709 
2710   return false;
2711 }
2712 
2713 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2714                                        SysClassPath* scp_p,
2715                                        bool* scp_assembly_required_p,
2716                                        Flag::Flags origin) {
2717   // Remaining part of option string
2718   const char* tail;
2719 
2720   // iterate over arguments
2721   for (int index = 0; index < args->nOptions; index++) {
2722     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2723 
2724     const JavaVMOption* option = args->options + index;
2725 
2726     if (!match_option(option, "-Djava.class.path", &tail) &&
2727         !match_option(option, "-Dsun.java.command", &tail) &&
2728         !match_option(option, "-Dsun.java.launcher", &tail)) {
2729 
2730         // add all jvm options to the jvm_args string. This string
2731         // is used later to set the java.vm.args PerfData string constant.
2732         // the -Djava.class.path and the -Dsun.java.command options are
2733         // omitted from jvm_args string as each have their own PerfData
2734         // string constant object.
2735         build_jvm_args(option->optionString);
2736     }
2737 
2738     // -verbose:[class/gc/jni]
2739     if (match_option(option, "-verbose", &tail)) {
2740       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2741         if (FLAG_SET_CMDLINE(bool, TraceClassLoading, true) != Flag::SUCCESS) {
2742           return JNI_EINVAL;
2743         }
2744         if (FLAG_SET_CMDLINE(bool, TraceClassUnloading, true) != Flag::SUCCESS) {
2745           return JNI_EINVAL;
2746         }
2747       } else if (!strcmp(tail, ":gc")) {
2748         if (FLAG_SET_CMDLINE(bool, PrintGC, true) != Flag::SUCCESS) {
2749           return JNI_EINVAL;
2750         }
2751       } else if (!strcmp(tail, ":jni")) {
2752         if (FLAG_SET_CMDLINE(bool, PrintJNIResolving, true) != Flag::SUCCESS) {
2753           return JNI_EINVAL;
2754         }
2755       }
2756     // -da / -ea / -disableassertions / -enableassertions
2757     // These accept an optional class/package name separated by a colon, e.g.,
2758     // -da:java.lang.Thread.
2759     } else if (match_option(option, user_assertion_options, &tail, true)) {
2760       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2761       if (*tail == '\0') {
2762         JavaAssertions::setUserClassDefault(enable);
2763       } else {
2764         assert(*tail == ':', "bogus match by match_option()");
2765         JavaAssertions::addOption(tail + 1, enable);
2766       }
2767     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2768     } else if (match_option(option, system_assertion_options, &tail, false)) {
2769       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2770       JavaAssertions::setSystemClassDefault(enable);
2771     // -bootclasspath:
2772     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2773       scp_p->reset_path(tail);
2774       *scp_assembly_required_p = true;
2775     // -bootclasspath/a:
2776     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2777       scp_p->add_suffix(tail);
2778       *scp_assembly_required_p = true;
2779     // -bootclasspath/p:
2780     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2781       scp_p->add_prefix(tail);
2782       *scp_assembly_required_p = true;
2783     // -Xrun
2784     } else if (match_option(option, "-Xrun", &tail)) {
2785       if (tail != NULL) {
2786         const char* pos = strchr(tail, ':');
2787         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2788         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2789         name[len] = '\0';
2790 
2791         char *options = NULL;
2792         if(pos != NULL) {
2793           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2794           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
2795         }
2796 #if !INCLUDE_JVMTI
2797         if (strcmp(name, "jdwp") == 0) {
2798           jio_fprintf(defaultStream::error_stream(),
2799             "Debugging agents are not supported in this VM\n");
2800           return JNI_ERR;
2801         }
2802 #endif // !INCLUDE_JVMTI
2803         add_init_library(name, options);
2804       }
2805     // -agentlib and -agentpath
2806     } else if (match_option(option, "-agentlib:", &tail) ||
2807           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2808       if(tail != NULL) {
2809         const char* pos = strchr(tail, '=');
2810         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2811         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2812         name[len] = '\0';
2813 
2814         char *options = NULL;
2815         if(pos != NULL) {
2816           options = os::strdup_check_oom(pos + 1, mtInternal);
2817         }
2818 #if !INCLUDE_JVMTI
2819         if (valid_jdwp_agent(name, is_absolute_path)) {
2820           jio_fprintf(defaultStream::error_stream(),
2821             "Debugging agents are not supported in this VM\n");
2822           return JNI_ERR;
2823         }
2824 #endif // !INCLUDE_JVMTI
2825         add_init_agent(name, options, is_absolute_path);
2826       }
2827     // -javaagent
2828     } else if (match_option(option, "-javaagent:", &tail)) {
2829 #if !INCLUDE_JVMTI
2830       jio_fprintf(defaultStream::error_stream(),
2831         "Instrumentation agents are not supported in this VM\n");
2832       return JNI_ERR;
2833 #else
2834       if(tail != NULL) {
2835         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtInternal), tail);
2836         add_init_agent("instrument", options, false);
2837       }
2838 #endif // !INCLUDE_JVMTI
2839     // -Xnoclassgc
2840     } else if (match_option(option, "-Xnoclassgc")) {
2841       if (FLAG_SET_CMDLINE(bool, ClassUnloading, false) != Flag::SUCCESS) {
2842         return JNI_EINVAL;
2843       }
2844     // -Xconcgc
2845     } else if (match_option(option, "-Xconcgc")) {
2846       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true) != Flag::SUCCESS) {
2847         return JNI_EINVAL;
2848       }
2849     // -Xnoconcgc
2850     } else if (match_option(option, "-Xnoconcgc")) {
2851       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false) != Flag::SUCCESS) {
2852         return JNI_EINVAL;
2853       }
2854     // -Xbatch
2855     } else if (match_option(option, "-Xbatch")) {
2856       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2857         return JNI_EINVAL;
2858       }
2859     // -Xmn for compatibility with other JVM vendors
2860     } else if (match_option(option, "-Xmn", &tail)) {
2861       julong long_initial_young_size = 0;
2862       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2863       if (errcode != arg_in_range) {
2864         jio_fprintf(defaultStream::error_stream(),
2865                     "Invalid initial young generation size: %s\n", option->optionString);
2866         describe_range_error(errcode);
2867         return JNI_EINVAL;
2868       }
2869       if (FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2870         return JNI_EINVAL;
2871       }
2872       if (FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2873         return JNI_EINVAL;
2874       }
2875     // -Xms
2876     } else if (match_option(option, "-Xms", &tail)) {
2877       julong long_initial_heap_size = 0;
2878       // an initial heap size of 0 means automatically determine
2879       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2880       if (errcode != arg_in_range) {
2881         jio_fprintf(defaultStream::error_stream(),
2882                     "Invalid initial heap size: %s\n", option->optionString);
2883         describe_range_error(errcode);
2884         return JNI_EINVAL;
2885       }
2886       set_min_heap_size((size_t)long_initial_heap_size);
2887       // Currently the minimum size and the initial heap sizes are the same.
2888       // Can be overridden with -XX:InitialHeapSize.
2889       if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size) != Flag::SUCCESS) {
2890         return JNI_EINVAL;
2891       }
2892     // -Xmx
2893     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2894       julong long_max_heap_size = 0;
2895       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2896       if (errcode != arg_in_range) {
2897         jio_fprintf(defaultStream::error_stream(),
2898                     "Invalid maximum heap size: %s\n", option->optionString);
2899         describe_range_error(errcode);
2900         return JNI_EINVAL;
2901       }
2902       if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size) != Flag::SUCCESS) {
2903         return JNI_EINVAL;
2904       }
2905     // Xmaxf
2906     } else if (match_option(option, "-Xmaxf", &tail)) {
2907       char* err;
2908       int maxf = (int)(strtod(tail, &err) * 100);
2909       if (*err != '\0' || *tail == '\0') {
2910         jio_fprintf(defaultStream::error_stream(),
2911                     "Bad max heap free percentage size: %s\n",
2912                     option->optionString);
2913         return JNI_EINVAL;
2914       } else {
2915         if (FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf) != Flag::SUCCESS) {
2916             return JNI_EINVAL;
2917         }
2918       }
2919     // Xminf
2920     } else if (match_option(option, "-Xminf", &tail)) {
2921       char* err;
2922       int minf = (int)(strtod(tail, &err) * 100);
2923       if (*err != '\0' || *tail == '\0') {
2924         jio_fprintf(defaultStream::error_stream(),
2925                     "Bad min heap free percentage size: %s\n",
2926                     option->optionString);
2927         return JNI_EINVAL;
2928       } else {
2929         if (FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf) != Flag::SUCCESS) {
2930           return JNI_EINVAL;
2931         }
2932       }
2933     // -Xss
2934     } else if (match_option(option, "-Xss", &tail)) {
2935       julong long_ThreadStackSize = 0;
2936       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2937       if (errcode != arg_in_range) {
2938         jio_fprintf(defaultStream::error_stream(),
2939                     "Invalid thread stack size: %s\n", option->optionString);
2940         describe_range_error(errcode);
2941         return JNI_EINVAL;
2942       }
2943       // Internally track ThreadStackSize in units of 1024 bytes.
2944       if (FLAG_SET_CMDLINE(intx, ThreadStackSize,
2945                        round_to((int)long_ThreadStackSize, K) / K) != Flag::SUCCESS) {
2946         return JNI_EINVAL;
2947       }
2948     // -Xoss, -Xsqnopause, -Xoptimize, -Xboundthreads
2949     } else if (match_option(option, "-Xoss", &tail) ||
2950                match_option(option, "-Xsqnopause") ||
2951                match_option(option, "-Xoptimize") ||
2952                match_option(option, "-Xboundthreads")) {
2953       // All these options are deprecated in JDK 9 and will be removed in a future release
2954       char version[256];
2955       JDK_Version::jdk(9).to_string(version, sizeof(version));
2956       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2957     } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
2958       julong long_CodeCacheExpansionSize = 0;
2959       ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
2960       if (errcode != arg_in_range) {
2961         jio_fprintf(defaultStream::error_stream(),
2962                    "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
2963                    os::vm_page_size()/K);
2964         return JNI_EINVAL;
2965       }
2966       if (FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize) != Flag::SUCCESS) {
2967         return JNI_EINVAL;
2968       }
2969     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2970                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2971       julong long_ReservedCodeCacheSize = 0;
2972 
2973       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2974       if (errcode != arg_in_range) {
2975         jio_fprintf(defaultStream::error_stream(),
2976                     "Invalid maximum code cache size: %s.\n", option->optionString);
2977         return JNI_EINVAL;
2978       }
2979       if (FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != Flag::SUCCESS) {
2980         return JNI_EINVAL;
2981       }
2982       // -XX:NonNMethodCodeHeapSize=
2983     } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
2984       julong long_NonNMethodCodeHeapSize = 0;
2985 
2986       ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
2987       if (errcode != arg_in_range) {
2988         jio_fprintf(defaultStream::error_stream(),
2989                     "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
2990         return JNI_EINVAL;
2991       }
2992       if (FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize) != Flag::SUCCESS) {
2993         return JNI_EINVAL;
2994       }
2995       // -XX:ProfiledCodeHeapSize=
2996     } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
2997       julong long_ProfiledCodeHeapSize = 0;
2998 
2999       ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
3000       if (errcode != arg_in_range) {
3001         jio_fprintf(defaultStream::error_stream(),
3002                     "Invalid maximum profiled code heap size: %s.\n", option->optionString);
3003         return JNI_EINVAL;
3004       }
3005       if (FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize) != Flag::SUCCESS) {
3006         return JNI_EINVAL;
3007       }
3008       // -XX:NonProfiledCodeHeapSizee=
3009     } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
3010       julong long_NonProfiledCodeHeapSize = 0;
3011 
3012       ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
3013       if (errcode != arg_in_range) {
3014         jio_fprintf(defaultStream::error_stream(),
3015                     "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
3016         return JNI_EINVAL;
3017       }
3018       if (FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize) != Flag::SUCCESS) {
3019         return JNI_EINVAL;
3020       }
3021     // -green
3022     } else if (match_option(option, "-green")) {
3023       jio_fprintf(defaultStream::error_stream(),
3024                   "Green threads support not available\n");
3025           return JNI_EINVAL;
3026     // -native
3027     } else if (match_option(option, "-native")) {
3028           // HotSpot always uses native threads, ignore silently for compatibility
3029     // -Xrs
3030     } else if (match_option(option, "-Xrs")) {
3031           // Classic/EVM option, new functionality
3032       if (FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true) != Flag::SUCCESS) {
3033         return JNI_EINVAL;
3034       }
3035     } else if (match_option(option, "-Xusealtsigs")) {
3036           // change default internal VM signals used - lower case for back compat
3037       if (FLAG_SET_CMDLINE(bool, UseAltSigs, true) != Flag::SUCCESS) {
3038         return JNI_EINVAL;
3039       }
3040     // -Xprof
3041     } else if (match_option(option, "-Xprof")) {
3042 #if INCLUDE_FPROF
3043       _has_profile = true;
3044 #else // INCLUDE_FPROF
3045       jio_fprintf(defaultStream::error_stream(),
3046         "Flat profiling is not supported in this VM.\n");
3047       return JNI_ERR;
3048 #endif // INCLUDE_FPROF
3049     // -Xconcurrentio
3050     } else if (match_option(option, "-Xconcurrentio")) {
3051       if (FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true) != Flag::SUCCESS) {
3052         return JNI_EINVAL;
3053       }
3054       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
3055         return JNI_EINVAL;
3056       }
3057       if (FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1) != Flag::SUCCESS) {
3058         return JNI_EINVAL;
3059       }
3060       if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
3061         return JNI_EINVAL;
3062       }
3063       if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
3064         return JNI_EINVAL;
3065       }
3066 
3067       // -Xinternalversion
3068     } else if (match_option(option, "-Xinternalversion")) {
3069       jio_fprintf(defaultStream::output_stream(), "%s\n",
3070                   VM_Version::internal_vm_info_string());
3071       vm_exit(0);
3072 #ifndef PRODUCT
3073     // -Xprintflags
3074     } else if (match_option(option, "-Xprintflags")) {
3075       CommandLineFlags::printFlags(tty, false);
3076       vm_exit(0);
3077 #endif
3078     // -D
3079     } else if (match_option(option, "-D", &tail)) {
3080       const char* value;
3081       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
3082             *value!= '\0' && strcmp(value, "\"\"") != 0) {
3083         // abort if -Djava.endorsed.dirs is set
3084         jio_fprintf(defaultStream::output_stream(),
3085           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
3086           "in modular form will be supported via the concept of upgradeable modules.\n", value);
3087         return JNI_EINVAL;
3088       }
3089       if (match_option(option, "-Djava.ext.dirs=", &value) &&
3090             *value != '\0' && strcmp(value, "\"\"") != 0) {
3091         // abort if -Djava.ext.dirs is set
3092         jio_fprintf(defaultStream::output_stream(),
3093           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
3094         return JNI_EINVAL;
3095       }
3096 
3097       if (!add_property(tail)) {
3098         return JNI_ENOMEM;
3099       }
3100       // Out of the box management support
3101       if (match_option(option, "-Dcom.sun.management", &tail)) {
3102 #if INCLUDE_MANAGEMENT
3103         if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
3104           return JNI_EINVAL;
3105         }
3106 #else
3107         jio_fprintf(defaultStream::output_stream(),
3108           "-Dcom.sun.management is not supported in this VM.\n");
3109         return JNI_ERR;
3110 #endif
3111       }
3112     // -Xint
3113     } else if (match_option(option, "-Xint")) {
3114           set_mode_flags(_int);
3115     // -Xmixed
3116     } else if (match_option(option, "-Xmixed")) {
3117           set_mode_flags(_mixed);
3118     // -Xcomp
3119     } else if (match_option(option, "-Xcomp")) {
3120       // for testing the compiler; turn off all flags that inhibit compilation
3121           set_mode_flags(_comp);
3122     // -Xshare:dump
3123     } else if (match_option(option, "-Xshare:dump")) {
3124       if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
3125         return JNI_EINVAL;
3126       }
3127       set_mode_flags(_int);     // Prevent compilation, which creates objects
3128     // -Xshare:on
3129     } else if (match_option(option, "-Xshare:on")) {
3130       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3131         return JNI_EINVAL;
3132       }
3133       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3134         return JNI_EINVAL;
3135       }
3136     // -Xshare:auto
3137     } else if (match_option(option, "-Xshare:auto")) {
3138       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3139         return JNI_EINVAL;
3140       }
3141       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3142         return JNI_EINVAL;
3143       }
3144     // -Xshare:off
3145     } else if (match_option(option, "-Xshare:off")) {
3146       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
3147         return JNI_EINVAL;
3148       }
3149       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3150         return JNI_EINVAL;
3151       }
3152     // -Xverify
3153     } else if (match_option(option, "-Xverify", &tail)) {
3154       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
3155         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
3156           return JNI_EINVAL;
3157         }
3158         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3159           return JNI_EINVAL;
3160         }
3161       } else if (strcmp(tail, ":remote") == 0) {
3162         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3163           return JNI_EINVAL;
3164         }
3165         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3166           return JNI_EINVAL;
3167         }
3168       } else if (strcmp(tail, ":none") == 0) {
3169         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3170           return JNI_EINVAL;
3171         }
3172         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
3173           return JNI_EINVAL;
3174         }
3175       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3176         return JNI_EINVAL;
3177       }
3178     // -Xdebug
3179     } else if (match_option(option, "-Xdebug")) {
3180       // note this flag has been used, then ignore
3181       set_xdebug_mode(true);
3182     // -Xnoagent
3183     } else if (match_option(option, "-Xnoagent")) {
3184       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3185     } else if (match_option(option, "-Xloggc:", &tail)) {
3186       // Redirect GC output to the file. -Xloggc:<filename>
3187       // ostream_init_log(), when called will use this filename
3188       // to initialize a fileStream.
3189       _gc_log_filename = os::strdup_check_oom(tail);
3190      if (!is_filename_valid(_gc_log_filename)) {
3191        jio_fprintf(defaultStream::output_stream(),
3192                   "Invalid file name for use with -Xloggc: Filename can only contain the "
3193                   "characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"
3194                   "Note %%p or %%t can only be used once\n", _gc_log_filename);
3195         return JNI_EINVAL;
3196       }
3197       if (FLAG_SET_CMDLINE(bool, PrintGC, true) != Flag::SUCCESS) {
3198         return JNI_EINVAL;
3199       }
3200       if (FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true) != Flag::SUCCESS) {
3201         return JNI_EINVAL;
3202       }
3203     } else if (match_option(option, "-Xlog", &tail)) {
3204       bool ret = false;
3205       if (strcmp(tail, ":help") == 0) {
3206         LogConfiguration::print_command_line_help(defaultStream::output_stream());
3207         vm_exit(0);
3208       } else if (strcmp(tail, ":disable") == 0) {
3209         LogConfiguration::disable_logging();
3210         ret = true;
3211       } else if (*tail == '\0') {
3212         ret = LogConfiguration::parse_command_line_arguments();
3213         assert(ret, "-Xlog without arguments should never fail to parse");
3214       } else if (*tail == ':') {
3215         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
3216       }
3217       if (ret == false) {
3218         jio_fprintf(defaultStream::error_stream(),
3219                     "Invalid -Xlog option '-Xlog%s'\n",
3220                     tail);
3221         return JNI_EINVAL;
3222       }
3223     // JNI hooks
3224     } else if (match_option(option, "-Xcheck", &tail)) {
3225       if (!strcmp(tail, ":jni")) {
3226 #if !INCLUDE_JNI_CHECK
3227         warning("JNI CHECKING is not supported in this VM");
3228 #else
3229         CheckJNICalls = true;
3230 #endif // INCLUDE_JNI_CHECK
3231       } else if (is_bad_option(option, args->ignoreUnrecognized,
3232                                      "check")) {
3233         return JNI_EINVAL;
3234       }
3235     } else if (match_option(option, "vfprintf")) {
3236       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3237     } else if (match_option(option, "exit")) {
3238       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3239     } else if (match_option(option, "abort")) {
3240       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3241     // -XX:+AggressiveHeap
3242     } else if (match_option(option, "-XX:+AggressiveHeap")) {
3243       jint result = set_aggressive_heap_flags();
3244       if (result != JNI_OK) {
3245           return result;
3246       }
3247     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
3248     // and the last option wins.
3249     } else if (match_option(option, "-XX:+NeverTenure")) {
3250       if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
3251         return JNI_EINVAL;
3252       }
3253       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3254         return JNI_EINVAL;
3255       }
3256       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
3257         return JNI_EINVAL;
3258       }
3259     } else if (match_option(option, "-XX:+AlwaysTenure")) {
3260       if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3261         return JNI_EINVAL;
3262       }
3263       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3264         return JNI_EINVAL;
3265       }
3266       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
3267         return JNI_EINVAL;
3268       }
3269     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
3270       uintx max_tenuring_thresh = 0;
3271       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
3272         jio_fprintf(defaultStream::error_stream(),
3273                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
3274         return JNI_EINVAL;
3275       }
3276 
3277       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
3278         return JNI_EINVAL;
3279       }
3280 
3281       if (MaxTenuringThreshold == 0) {
3282         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3283           return JNI_EINVAL;
3284         }
3285         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3286           return JNI_EINVAL;
3287         }
3288       } else {
3289         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3290           return JNI_EINVAL;
3291         }
3292         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3293           return JNI_EINVAL;
3294         }
3295       }
3296     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3297       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
3298         return JNI_EINVAL;
3299       }
3300       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
3301         return JNI_EINVAL;
3302       }
3303     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3304       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
3305         return JNI_EINVAL;
3306       }
3307       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3308         return JNI_EINVAL;
3309       }
3310     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3311 #if defined(DTRACE_ENABLED)
3312       if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3313         return JNI_EINVAL;
3314       }
3315       if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3316         return JNI_EINVAL;
3317       }
3318       if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3319         return JNI_EINVAL;
3320       }
3321       if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3322         return JNI_EINVAL;
3323       }
3324 #else // defined(DTRACE_ENABLED)
3325       jio_fprintf(defaultStream::error_stream(),
3326                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3327       return JNI_EINVAL;
3328 #endif // defined(DTRACE_ENABLED)
3329 #ifdef ASSERT
3330     } else if (match_option(option, "-XX:+FullGCALot")) {
3331       if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3332         return JNI_EINVAL;
3333       }
3334       // disable scavenge before parallel mark-compact
3335       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3336         return JNI_EINVAL;
3337       }
3338 #endif
3339 #if !INCLUDE_MANAGEMENT
3340     } else if (match_option(option, "-XX:+ManagementServer")) {
3341         jio_fprintf(defaultStream::error_stream(),
3342           "ManagementServer is not supported in this VM.\n");
3343         return JNI_ERR;
3344 #endif // INCLUDE_MANAGEMENT
3345     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3346       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
3347       // already been handled
3348       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
3349           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
3350         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3351           return JNI_EINVAL;
3352         }
3353       }
3354     // Unknown option
3355     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3356       return JNI_ERR;
3357     }
3358   }
3359 
3360   // PrintSharedArchiveAndExit will turn on
3361   //   -Xshare:on
3362   //   -XX:+TraceClassPaths
3363   if (PrintSharedArchiveAndExit) {
3364     if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3365       return JNI_EINVAL;
3366     }
3367     if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3368       return JNI_EINVAL;
3369     }
3370     if (FLAG_SET_CMDLINE(bool, TraceClassPaths, true) != Flag::SUCCESS) {
3371       return JNI_EINVAL;
3372     }
3373   }
3374 
3375   // Change the default value for flags  which have different default values
3376   // when working with older JDKs.
3377 #ifdef LINUX
3378  if (JDK_Version::current().compare_major(6) <= 0 &&
3379       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3380     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3381   }
3382 #endif // LINUX
3383   fix_appclasspath();
3384   return JNI_OK;
3385 }
3386 
3387 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3388 //
3389 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3390 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3391 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3392 // path is treated as the current directory.
3393 //
3394 // This causes problems with CDS, which requires that all directories specified in the classpath
3395 // must be empty. In most cases, applications do NOT want to load classes from the current
3396 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3397 // scripts compatible with CDS.
3398 void Arguments::fix_appclasspath() {
3399   if (IgnoreEmptyClassPaths) {
3400     const char separator = *os::path_separator();
3401     const char* src = _java_class_path->value();
3402 
3403     // skip over all the leading empty paths
3404     while (*src == separator) {
3405       src ++;
3406     }
3407 
3408     char* copy = os::strdup_check_oom(src, mtInternal);
3409 
3410     // trim all trailing empty paths
3411     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3412       *tail = '\0';
3413     }
3414 
3415     char from[3] = {separator, separator, '\0'};
3416     char to  [2] = {separator, '\0'};
3417     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3418       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3419       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3420     }
3421 
3422     _java_class_path->set_value(copy);
3423     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3424   }
3425 
3426   if (!PrintSharedArchiveAndExit) {
3427     ClassLoader::trace_class_path("[classpath: ", _java_class_path->value());
3428   }
3429 }
3430 
3431 static bool has_jar_files(const char* directory) {
3432   DIR* dir = os::opendir(directory);
3433   if (dir == NULL) return false;
3434 
3435   struct dirent *entry;
3436   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
3437   bool hasJarFile = false;
3438   while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3439     const char* name = entry->d_name;
3440     const char* ext = name + strlen(name) - 4;
3441     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3442   }
3443   FREE_C_HEAP_ARRAY(char, dbuf);
3444   os::closedir(dir);
3445   return hasJarFile ;
3446 }
3447 
3448 static int check_non_empty_dirs(const char* path) {
3449   const char separator = *os::path_separator();
3450   const char* const end = path + strlen(path);
3451   int nonEmptyDirs = 0;
3452   while (path < end) {
3453     const char* tmp_end = strchr(path, separator);
3454     if (tmp_end == NULL) {
3455       if (has_jar_files(path)) {
3456         nonEmptyDirs++;
3457         jio_fprintf(defaultStream::output_stream(),
3458           "Non-empty directory: %s\n", path);
3459       }
3460       path = end;
3461     } else {
3462       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
3463       memcpy(dirpath, path, tmp_end - path);
3464       dirpath[tmp_end - path] = '\0';
3465       if (has_jar_files(dirpath)) {
3466         nonEmptyDirs++;
3467         jio_fprintf(defaultStream::output_stream(),
3468           "Non-empty directory: %s\n", dirpath);
3469       }
3470       FREE_C_HEAP_ARRAY(char, dirpath);
3471       path = tmp_end + 1;
3472     }
3473   }
3474   return nonEmptyDirs;
3475 }
3476 
3477 jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
3478   // check if the default lib/endorsed directory exists; if so, error
3479   char path[JVM_MAXPATHLEN];
3480   const char* fileSep = os::file_separator();
3481   sprintf(path, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3482 
3483 #if INCLUDE_JVMCI
3484   if (EnableJVMCI) {
3485     JVMCIRuntime::save_options(_system_properties);
3486   }
3487 #endif // INCLUDE_JVMCI
3488 
3489   if (CheckEndorsedAndExtDirs) {
3490     int nonEmptyDirs = 0;
3491     // check endorsed directory
3492     nonEmptyDirs += check_non_empty_dirs(path);
3493     // check the extension directories
3494     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3495     if (nonEmptyDirs > 0) {
3496       return JNI_ERR;
3497     }
3498   }
3499 
3500   DIR* dir = os::opendir(path);
3501   if (dir != NULL) {
3502     jio_fprintf(defaultStream::output_stream(),
3503       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3504       "in modular form will be supported via the concept of upgradeable modules.\n");
3505     os::closedir(dir);
3506     return JNI_ERR;
3507   }
3508 
3509   sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3510   dir = os::opendir(path);
3511   if (dir != NULL) {
3512     jio_fprintf(defaultStream::output_stream(),
3513       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3514       "Use -classpath instead.\n.");
3515     os::closedir(dir);
3516     return JNI_ERR;
3517   }
3518 
3519   if (scp_assembly_required) {
3520     // Assemble the bootclasspath elements into the final path.
3521     char *combined_path = scp_p->combined_path();
3522     Arguments::set_sysclasspath(combined_path);
3523     FREE_C_HEAP_ARRAY(char, combined_path);
3524   }
3525 
3526   // This must be done after all arguments have been processed.
3527   // java_compiler() true means set to "NONE" or empty.
3528   if (java_compiler() && !xdebug_mode()) {
3529     // For backwards compatibility, we switch to interpreted mode if
3530     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3531     // not specified.
3532     set_mode_flags(_int);
3533   }
3534 
3535   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3536   // but like -Xint, leave compilation thresholds unaffected.
3537   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3538   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3539     set_mode_flags(_int);
3540   }
3541 
3542   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3543   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3544     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3545   }
3546 
3547 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3548   // Don't degrade server performance for footprint
3549   if (FLAG_IS_DEFAULT(UseLargePages) &&
3550       MaxHeapSize < LargePageHeapSizeThreshold) {
3551     // No need for large granularity pages w/small heaps.
3552     // Note that large pages are enabled/disabled for both the
3553     // Java heap and the code cache.
3554     FLAG_SET_DEFAULT(UseLargePages, false);
3555   }
3556 
3557 #elif defined(COMPILER2)
3558   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3559     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3560   }
3561 #endif
3562 
3563 #ifndef TIERED
3564   // Tiered compilation is undefined.
3565   UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
3566 #endif
3567 
3568   // If we are running in a headless jre, force java.awt.headless property
3569   // to be true unless the property has already been set.
3570   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3571   if (os::is_headless_jre()) {
3572     const char* headless = Arguments::get_property("java.awt.headless");
3573     if (headless == NULL) {
3574       const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3575       if (headless_env == NULL) {
3576         if (!add_property("java.awt.headless=true")) {
3577           return JNI_ENOMEM;
3578         }
3579       } else {
3580         char buffer[256];
3581         jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3582         if (!add_property(buffer)) {
3583           return JNI_ENOMEM;
3584         }
3585       }
3586     }
3587   }
3588 
3589   if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3590     // CMS can only be used with ParNew
3591     FLAG_SET_ERGO(bool, UseParNewGC, true);
3592   }
3593 
3594   if (!check_vm_args_consistency()) {
3595     return JNI_ERR;
3596   }
3597 
3598   return JNI_OK;
3599 }
3600 
3601 // Helper class for controlling the lifetime of JavaVMInitArgs
3602 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3603 // deleted on the destruction of the ScopedVMInitArgs object.
3604 class ScopedVMInitArgs : public StackObj {
3605  private:
3606   JavaVMInitArgs _args;
3607   bool           _is_set;
3608 
3609  public:
3610   ScopedVMInitArgs() {
3611     _args.version = JNI_VERSION_1_2;
3612     _args.nOptions = 0;
3613     _args.options = NULL;
3614     _args.ignoreUnrecognized = false;
3615     _is_set = false;
3616   }
3617 
3618   // Populates the JavaVMInitArgs object represented by this
3619   // ScopedVMInitArgs object with the arguments in options.  The
3620   // allocated memory is deleted by the destructor.  If this method
3621   // returns anything other than JNI_OK, then this object is in a
3622   // partially constructed state, and should be abandoned.
3623   jint set_args(GrowableArray<JavaVMOption>* options) {
3624     _is_set = true;
3625     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3626         JavaVMOption, options->length(), mtInternal);
3627     if (options_arr == NULL) {
3628       return JNI_ENOMEM;
3629     }
3630     _args.options = options_arr;
3631 
3632     for (int i = 0; i < options->length(); i++) {
3633       options_arr[i] = options->at(i);
3634       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3635       if (options_arr[i].optionString == NULL) {
3636         // Rely on the destructor to do cleanup.
3637         _args.nOptions = i;
3638         return JNI_ENOMEM;
3639       }
3640     }
3641 
3642     _args.nOptions = options->length();
3643     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3644     return JNI_OK;
3645   }
3646 
3647   JavaVMInitArgs* get() { return &_args; }
3648   bool is_set()         { return _is_set; }
3649 
3650   ~ScopedVMInitArgs() {
3651     if (_args.options == NULL) return;
3652     for (int i = 0; i < _args.nOptions; i++) {
3653       os::free(_args.options[i].optionString);
3654     }
3655     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3656   }
3657 
3658   // Insert options into this option list, to replace option at
3659   // vm_options_file_pos (-XX:VMOptionsFile)
3660   jint insert(const JavaVMInitArgs* args,
3661               const JavaVMInitArgs* args_to_insert,
3662               const int vm_options_file_pos) {
3663     assert(_args.options == NULL, "shouldn't be set yet");
3664     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3665     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3666 
3667     int length = args->nOptions + args_to_insert->nOptions - 1;
3668     GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal)
3669               GrowableArray<JavaVMOption>(length, true);    // Construct new option array
3670     for (int i = 0; i < args->nOptions; i++) {
3671       if (i == vm_options_file_pos) {
3672         // insert the new options starting at the same place as the
3673         // -XX:VMOptionsFile option
3674         for (int j = 0; j < args_to_insert->nOptions; j++) {
3675           options->push(args_to_insert->options[j]);
3676         }
3677       } else {
3678         options->push(args->options[i]);
3679       }
3680     }
3681     // make into options array
3682     jint result = set_args(options);
3683     delete options;
3684     return result;
3685   }
3686 };
3687 
3688 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3689   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3690 }
3691 
3692 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3693   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3694 }
3695 
3696 jint Arguments::parse_options_environment_variable(const char* name,
3697                                                    ScopedVMInitArgs* vm_args) {
3698   char *buffer = ::getenv(name);
3699 
3700   // Don't check this environment variable if user has special privileges
3701   // (e.g. unix su command).
3702   if (buffer == NULL || os::have_special_privileges()) {
3703     return JNI_OK;
3704   }
3705 
3706   if ((buffer = os::strdup(buffer)) == NULL) {
3707     return JNI_ENOMEM;
3708   }
3709 
3710   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3711 
3712   os::free(buffer);
3713   return retcode;
3714 }
3715 
3716 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3717   // read file into buffer
3718   int fd = ::open(file_name, O_RDONLY);
3719   if (fd < 0) {
3720     jio_fprintf(defaultStream::error_stream(),
3721                 "Could not open options file '%s'\n",
3722                 file_name);
3723     return JNI_ERR;
3724   }
3725 
3726   struct stat stbuf;
3727   int retcode = os::stat(file_name, &stbuf);
3728   if (retcode != 0) {
3729     jio_fprintf(defaultStream::error_stream(),
3730                 "Could not stat options file '%s'\n",
3731                 file_name);
3732     os::close(fd);
3733     return JNI_ERR;
3734   }
3735 
3736   if (stbuf.st_size == 0) {
3737     // tell caller there is no option data and that is ok
3738     os::close(fd);
3739     return JNI_OK;
3740   }
3741 
3742   // '+ 1' for NULL termination even with max bytes
3743   size_t bytes_alloc = stbuf.st_size + 1;
3744 
3745   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtInternal);
3746   if (NULL == buf) {
3747     jio_fprintf(defaultStream::error_stream(),
3748                 "Could not allocate read buffer for options file parse\n");
3749     os::close(fd);
3750     return JNI_ENOMEM;
3751   }
3752 
3753   memset(buf, 0, bytes_alloc);
3754 
3755   // Fill buffer
3756   // Use ::read() instead of os::read because os::read()
3757   // might do a thread state transition
3758   // and it is too early for that here
3759 
3760   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3761   os::close(fd);
3762   if (bytes_read < 0) {
3763     FREE_C_HEAP_ARRAY(char, buf);
3764     jio_fprintf(defaultStream::error_stream(),
3765                 "Could not read options file '%s'\n", file_name);
3766     return JNI_ERR;
3767   }
3768 
3769   if (bytes_read == 0) {
3770     // tell caller there is no option data and that is ok
3771     FREE_C_HEAP_ARRAY(char, buf);
3772     return JNI_OK;
3773   }
3774 
3775   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3776 
3777   FREE_C_HEAP_ARRAY(char, buf);
3778   return retcode;
3779 }
3780 
3781 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3782   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3783 
3784   // some pointers to help with parsing
3785   char *buffer_end = buffer + buf_len;
3786   char *opt_hd = buffer;
3787   char *wrt = buffer;
3788   char *rd = buffer;
3789 
3790   // parse all options
3791   while (rd < buffer_end) {
3792     // skip leading white space from the input string
3793     while (rd < buffer_end && isspace(*rd)) {
3794       rd++;
3795     }
3796 
3797     if (rd >= buffer_end) {
3798       break;
3799     }
3800 
3801     // Remember this is where we found the head of the token.
3802     opt_hd = wrt;
3803 
3804     // Tokens are strings of non white space characters separated
3805     // by one or more white spaces.
3806     while (rd < buffer_end && !isspace(*rd)) {
3807       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3808         int quote = *rd;                    // matching quote to look for
3809         rd++;                               // don't copy open quote
3810         while (rd < buffer_end && *rd != quote) {
3811                                             // include everything (even spaces)
3812                                             // up until the close quote
3813           *wrt++ = *rd++;                   // copy to option string
3814         }
3815 
3816         if (rd < buffer_end) {
3817           rd++;                             // don't copy close quote
3818         } else {
3819                                             // did not see closing quote
3820           jio_fprintf(defaultStream::error_stream(),
3821                       "Unmatched quote in %s\n", name);
3822           delete options;
3823           return JNI_ERR;
3824         }
3825       } else {
3826         *wrt++ = *rd++;                     // copy to option string
3827       }
3828     }
3829 
3830     // steal a white space character and set it to NULL
3831     *wrt++ = '\0';
3832     // We now have a complete token
3833 
3834     JavaVMOption option;
3835     option.optionString = opt_hd;
3836 
3837     options->append(option);                // Fill in option
3838 
3839     rd++;  // Advance to next character
3840   }
3841 
3842   // Fill out JavaVMInitArgs structure.
3843   jint status = vm_args->set_args(options);
3844 
3845   delete options;
3846   return status;
3847 }
3848 
3849 void Arguments::set_shared_spaces_flags() {
3850   if (DumpSharedSpaces) {
3851     if (RequireSharedSpaces) {
3852       warning("Cannot dump shared archive while using shared archive");
3853     }
3854     UseSharedSpaces = false;
3855 #ifdef _LP64
3856     if (!UseCompressedOops || !UseCompressedClassPointers) {
3857       vm_exit_during_initialization(
3858         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3859     }
3860   } else {
3861     if (!UseCompressedOops || !UseCompressedClassPointers) {
3862       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3863     }
3864 #endif
3865   }
3866 }
3867 
3868 #if !INCLUDE_ALL_GCS
3869 static void force_serial_gc() {
3870   FLAG_SET_DEFAULT(UseSerialGC, true);
3871   UNSUPPORTED_GC_OPTION(UseG1GC);
3872   UNSUPPORTED_GC_OPTION(UseParallelGC);
3873   UNSUPPORTED_GC_OPTION(UseParallelOldGC);
3874   UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
3875   UNSUPPORTED_GC_OPTION(UseParNewGC);
3876 }
3877 #endif // INCLUDE_ALL_GCS
3878 
3879 // Sharing support
3880 // Construct the path to the archive
3881 static char* get_shared_archive_path() {
3882   char *shared_archive_path;
3883   if (SharedArchiveFile == NULL) {
3884     char jvm_path[JVM_MAXPATHLEN];
3885     os::jvm_path(jvm_path, sizeof(jvm_path));
3886     char *end = strrchr(jvm_path, *os::file_separator());
3887     if (end != NULL) *end = '\0';
3888     size_t jvm_path_len = strlen(jvm_path);
3889     size_t file_sep_len = strlen(os::file_separator());
3890     const size_t len = jvm_path_len + file_sep_len + 20;
3891     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtInternal);
3892     if (shared_archive_path != NULL) {
3893       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3894         jvm_path, os::file_separator());
3895     }
3896   } else {
3897     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtInternal);
3898   }
3899   return shared_archive_path;
3900 }
3901 
3902 #ifndef PRODUCT
3903 // Determine whether LogVMOutput should be implicitly turned on.
3904 static bool use_vm_log() {
3905   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3906       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3907       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3908       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3909       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3910     return true;
3911   }
3912 
3913 #ifdef COMPILER1
3914   if (PrintC1Statistics) {
3915     return true;
3916   }
3917 #endif // COMPILER1
3918 
3919 #ifdef COMPILER2
3920   if (PrintOptoAssembly || PrintOptoStatistics) {
3921     return true;
3922   }
3923 #endif // COMPILER2
3924 
3925   return false;
3926 }
3927 
3928 #endif // PRODUCT
3929 
3930 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3931                                        char** flags_file,
3932                                        char** vm_options_file,
3933                                        const int vm_options_file_pos,
3934                                        ScopedVMInitArgs *vm_options_file_args,
3935                                        ScopedVMInitArgs* args_out) {
3936   jint code = parse_vm_options_file(*vm_options_file, vm_options_file_args);
3937   if (code != JNI_OK) {
3938     return code;
3939   }
3940 
3941   if (vm_options_file_args->get()->nOptions < 1) {
3942     return JNI_OK;
3943   }
3944 
3945   return args_out->insert(args, vm_options_file_args->get(),
3946                           vm_options_file_pos);
3947 }
3948 
3949 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3950                                              char ** flags_file,
3951                                              char ** vm_options_file,
3952                                              ScopedVMInitArgs* vm_options_file_args,
3953                                              ScopedVMInitArgs* args_out) {
3954   // Remaining part of option string
3955   const char* tail;
3956   int   vm_options_file_pos = -1;
3957 
3958   for (int index = 0; index < args->nOptions; index++) {
3959     const JavaVMOption* option = args->options + index;
3960     if (ArgumentsExt::process_options(option)) {
3961       continue;
3962     }
3963     if (match_option(option, "-XX:Flags=", &tail)) {
3964       *flags_file = (char *) tail;
3965       if (*flags_file == NULL) {
3966         jio_fprintf(defaultStream::error_stream(),
3967                     "Cannot copy flags_file name.\n");
3968         return JNI_ENOMEM;
3969       }
3970       continue;
3971     }
3972     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3973       if (vm_options_file != NULL) {
3974         // The caller accepts -XX:VMOptionsFile
3975         if (*vm_options_file != NULL) {
3976           jio_fprintf(defaultStream::error_stream(),
3977                       "The VM Options file can only be specified once and "
3978                       "only on the command line.\n");
3979           return JNI_EINVAL;
3980         }
3981 
3982         *vm_options_file = (char *) tail;
3983         vm_options_file_pos = index;  // save position of -XX:VMOptionsFile
3984         // If there's a VMOptionsFile, parse that (also can set flags_file)
3985         jint code = insert_vm_options_file(args, flags_file, vm_options_file,
3986                                            vm_options_file_pos,
3987                                            vm_options_file_args, args_out);
3988         if (code != JNI_OK) {
3989           return code;
3990         }
3991         if (args_out->is_set()) {
3992           // The VMOptions file inserted some options so switch 'args'
3993           // to the new set of options, and continue processing which
3994           // preserves "last option wins" semantics.
3995           args = args_out->get();
3996           // The first option from the VMOptionsFile replaces the
3997           // current option.  So we back track to process the
3998           // replacement option.
3999           index--;
4000         }
4001       } else {
4002         jio_fprintf(defaultStream::error_stream(),
4003                     "VM options file is only supported on the command line\n");
4004         return JNI_EINVAL;
4005       }
4006       continue;
4007     }
4008     if (match_option(option, "-XX:+PrintVMOptions")) {
4009       PrintVMOptions = true;
4010       continue;
4011     }
4012     if (match_option(option, "-XX:-PrintVMOptions")) {
4013       PrintVMOptions = false;
4014       continue;
4015     }
4016     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
4017       IgnoreUnrecognizedVMOptions = true;
4018       continue;
4019     }
4020     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
4021       IgnoreUnrecognizedVMOptions = false;
4022       continue;
4023     }
4024     if (match_option(option, "-XX:+PrintFlagsInitial")) {
4025       CommandLineFlags::printFlags(tty, false);
4026       vm_exit(0);
4027     }
4028     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
4029 #if INCLUDE_NMT
4030       // The launcher did not setup nmt environment variable properly.
4031       if (!MemTracker::check_launcher_nmt_support(tail)) {
4032         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
4033       }
4034 
4035       // Verify if nmt option is valid.
4036       if (MemTracker::verify_nmt_option()) {
4037         // Late initialization, still in single-threaded mode.
4038         if (MemTracker::tracking_level() >= NMT_summary) {
4039           MemTracker::init();
4040         }
4041       } else {
4042         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
4043       }
4044       continue;
4045 #else
4046       jio_fprintf(defaultStream::error_stream(),
4047         "Native Memory Tracking is not supported in this VM\n");
4048       return JNI_ERR;
4049 #endif
4050     }
4051 
4052 #ifndef PRODUCT
4053     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
4054       CommandLineFlags::printFlags(tty, true);
4055       vm_exit(0);
4056     }
4057 #endif
4058   }
4059   return JNI_OK;
4060 }
4061 
4062 static void print_options(const JavaVMInitArgs *args) {
4063   const char* tail;
4064   for (int index = 0; index < args->nOptions; index++) {
4065     const JavaVMOption *option = args->options + index;
4066     if (match_option(option, "-XX:", &tail)) {
4067       logOption(tail);
4068     }
4069   }
4070 }
4071 
4072 // Parse entry point called from JNI_CreateJavaVM
4073 
4074 jint Arguments::parse(const JavaVMInitArgs* args) {
4075   assert(verify_special_jvm_flags(), "deprecated and obsolete flag table inconsistent");
4076 
4077   // Initialize ranges and constraints
4078   CommandLineFlagRangeList::init();
4079   CommandLineFlagConstraintList::init();
4080 
4081   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
4082   const char* hotspotrc = ".hotspotrc";
4083   char* flags_file = NULL;
4084   char* vm_options_file = NULL;
4085   bool settings_file_specified = false;
4086   bool needs_hotspotrc_warning = false;
4087   ScopedVMInitArgs java_tool_options_args;
4088   ScopedVMInitArgs java_options_args;
4089   ScopedVMInitArgs modified_cmd_line_args;
4090   // Pass in vm_options_file_args to keep memory for flags_file from being
4091   // deallocated if found in the vm options file.
4092   ScopedVMInitArgs vm_options_file_args;
4093 
4094   jint code =
4095       parse_java_tool_options_environment_variable(&java_tool_options_args);
4096   if (code != JNI_OK) {
4097     return code;
4098   }
4099 
4100   code = parse_java_options_environment_variable(&java_options_args);
4101   if (code != JNI_OK) {
4102     return code;
4103   }
4104 
4105   code = match_special_option_and_act(java_tool_options_args.get(),
4106                                       &flags_file, NULL, NULL, NULL);
4107   if (code != JNI_OK) {
4108     return code;
4109   }
4110 
4111   code = match_special_option_and_act(args, &flags_file, &vm_options_file,
4112                                       &vm_options_file_args,
4113                                       &modified_cmd_line_args);
4114   if (code != JNI_OK) {
4115     return code;
4116   }
4117 
4118 
4119   // The command line arguments have been modified to include VMOptionsFile arguments.
4120   if (modified_cmd_line_args.is_set()) {
4121     args = modified_cmd_line_args.get();
4122   }
4123 
4124   code = match_special_option_and_act(java_options_args.get(), &flags_file,
4125                                       NULL, NULL, NULL);
4126   if (code != JNI_OK) {
4127     return code;
4128   }
4129 
4130   settings_file_specified = (flags_file != NULL);
4131 
4132   if (IgnoreUnrecognizedVMOptions) {
4133     // uncast const to modify the flag args->ignoreUnrecognized
4134     *(jboolean*)(&args->ignoreUnrecognized) = true;
4135     java_tool_options_args.get()->ignoreUnrecognized = true;
4136     java_options_args.get()->ignoreUnrecognized = true;
4137   }
4138 
4139   // Parse specified settings file
4140   if (settings_file_specified) {
4141     if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
4142       return JNI_EINVAL;
4143     }
4144   } else {
4145 #ifdef ASSERT
4146     // Parse default .hotspotrc settings file
4147     if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
4148       return JNI_EINVAL;
4149     }
4150 #else
4151     struct stat buf;
4152     if (os::stat(hotspotrc, &buf) == 0) {
4153       needs_hotspotrc_warning = true;
4154     }
4155 #endif
4156   }
4157 
4158   if (PrintVMOptions) {
4159     print_options(java_tool_options_args.get());
4160     print_options(args);
4161     print_options(java_options_args.get());
4162   }
4163 
4164   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
4165   jint result = parse_vm_init_args(java_tool_options_args.get(),
4166                                    java_options_args.get(),
4167                                    args);   // command line arguments
4168 
4169   if (result != JNI_OK) {
4170     return result;
4171   }
4172 
4173   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
4174   SharedArchivePath = get_shared_archive_path();
4175   if (SharedArchivePath == NULL) {
4176     return JNI_ENOMEM;
4177   }
4178 
4179   // Set up VerifySharedSpaces
4180   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
4181     VerifySharedSpaces = true;
4182   }
4183 
4184   // Delay warning until here so that we've had a chance to process
4185   // the -XX:-PrintWarnings flag
4186   if (needs_hotspotrc_warning) {
4187     warning("%s file is present but has been ignored.  "
4188             "Run with -XX:Flags=%s to load the file.",
4189             hotspotrc, hotspotrc);
4190   }
4191 
4192 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
4193   UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
4194 #endif
4195 
4196   ArgumentsExt::report_unsupported_options();
4197 
4198 #ifndef PRODUCT
4199   if (TraceBytecodesAt != 0) {
4200     TraceBytecodes = true;
4201   }
4202   if (CountCompiledCalls) {
4203     if (UseCounterDecay) {
4204       warning("UseCounterDecay disabled because CountCalls is set");
4205       UseCounterDecay = false;
4206     }
4207   }
4208 #endif // PRODUCT
4209 
4210   if (ScavengeRootsInCode == 0) {
4211     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4212       warning("Forcing ScavengeRootsInCode non-zero");
4213     }
4214     ScavengeRootsInCode = 1;
4215   }
4216 
4217   if (PrintGCDetails) {
4218     // Turn on -verbose:gc options as well
4219     PrintGC = true;
4220   }
4221 
4222   // Set object alignment values.
4223   set_object_alignment();
4224 
4225 #if !INCLUDE_ALL_GCS
4226   force_serial_gc();
4227 #endif // INCLUDE_ALL_GCS
4228 #if !INCLUDE_CDS
4229   if (DumpSharedSpaces || RequireSharedSpaces) {
4230     jio_fprintf(defaultStream::error_stream(),
4231       "Shared spaces are not supported in this VM\n");
4232     return JNI_ERR;
4233   }
4234   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
4235     warning("Shared spaces are not supported in this VM");
4236     FLAG_SET_DEFAULT(UseSharedSpaces, false);
4237     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
4238   }
4239   no_shared_spaces("CDS Disabled");
4240 #endif // INCLUDE_CDS
4241 
4242   return JNI_OK;
4243 }
4244 
4245 jint Arguments::apply_ergo() {
4246 
4247   // Set flags based on ergonomics.
4248   set_ergonomics_flags();
4249 
4250   set_shared_spaces_flags();
4251 
4252   // Check the GC selections again.
4253   if (!check_gc_consistency()) {
4254     return JNI_EINVAL;
4255   }
4256 
4257   if (TieredCompilation) {
4258     set_tiered_flags();
4259   } else {
4260     int max_compilation_policy_choice = 1;
4261 #ifdef COMPILER2
4262     max_compilation_policy_choice = 2;
4263 #endif
4264     // Check if the policy is valid.
4265     if (CompilationPolicyChoice >= max_compilation_policy_choice) {
4266       vm_exit_during_initialization(
4267         "Incompatible compilation policy selected", NULL);
4268     }
4269     // Scale CompileThreshold
4270     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
4271     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
4272       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
4273     }
4274   }
4275 
4276 #ifdef COMPILER2
4277 #ifndef PRODUCT
4278   if (PrintIdealGraphLevel > 0) {
4279     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
4280   }
4281 #endif
4282 #endif
4283 
4284   // Set heap size based on available physical memory
4285   set_heap_size();
4286 
4287   ArgumentsExt::set_gc_specific_flags();
4288 
4289   // Initialize Metaspace flags and alignments
4290   Metaspace::ergo_initialize();
4291 
4292   // Set bytecode rewriting flags
4293   set_bytecode_flags();
4294 
4295   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
4296   jint code = set_aggressive_opts_flags();
4297   if (code != JNI_OK) {
4298     return code;
4299   }
4300 
4301   // Turn off biased locking for locking debug mode flags,
4302   // which are subtly different from each other but neither works with
4303   // biased locking
4304   if (UseHeavyMonitors
4305 #ifdef COMPILER1
4306       || !UseFastLocking
4307 #endif // COMPILER1
4308 #if INCLUDE_JVMCI
4309       || !JVMCIUseFastLocking
4310 #endif
4311     ) {
4312     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4313       // flag set to true on command line; warn the user that they
4314       // can't enable biased locking here
4315       warning("Biased Locking is not supported with locking debug flags"
4316               "; ignoring UseBiasedLocking flag." );
4317     }
4318     UseBiasedLocking = false;
4319   }
4320 
4321 #ifdef ZERO
4322   // Clear flags not supported on zero.
4323   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4324   FLAG_SET_DEFAULT(UseBiasedLocking, false);
4325   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4326   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4327 #endif // CC_INTERP
4328 
4329 #ifdef COMPILER2
4330   if (!EliminateLocks) {
4331     EliminateNestedLocks = false;
4332   }
4333   if (!Inline) {
4334     IncrementalInline = false;
4335   }
4336 #ifndef PRODUCT
4337   if (!IncrementalInline) {
4338     AlwaysIncrementalInline = false;
4339   }
4340 #endif
4341   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
4342     // nothing to use the profiling, turn if off
4343     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
4344   }
4345 #endif
4346 
4347   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4348     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4349     DebugNonSafepoints = true;
4350   }
4351 
4352   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4353     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4354   }
4355 
4356 #ifndef PRODUCT
4357   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4358     if (use_vm_log()) {
4359       LogVMOutput = true;
4360     }
4361   }
4362 #endif // PRODUCT
4363 
4364   if (PrintCommandLineFlags) {
4365     CommandLineFlags::printSetFlags(tty);
4366   }
4367 
4368   // Apply CPU specific policy for the BiasedLocking
4369   if (UseBiasedLocking) {
4370     if (!VM_Version::use_biased_locking() &&
4371         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4372       UseBiasedLocking = false;
4373     }
4374   }
4375 #ifdef COMPILER2
4376   if (!UseBiasedLocking || EmitSync != 0) {
4377     UseOptoBiasInlining = false;
4378   }
4379 #endif
4380 
4381   return JNI_OK;
4382 }
4383 
4384 jint Arguments::adjust_after_os() {
4385   if (UseNUMA) {
4386     if (UseParallelGC || UseParallelOldGC) {
4387       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4388          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4389       }
4390     }
4391     // UseNUMAInterleaving is set to ON for all collectors and
4392     // platforms when UseNUMA is set to ON. NUMA-aware collectors
4393     // such as the parallel collector for Linux and Solaris will
4394     // interleave old gen and survivor spaces on top of NUMA
4395     // allocation policy for the eden space.
4396     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4397     // all platforms and ParallelGC on Windows will interleave all
4398     // of the heap spaces across NUMA nodes.
4399     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4400       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4401     }
4402   }
4403   return JNI_OK;
4404 }
4405 
4406 int Arguments::PropertyList_count(SystemProperty* pl) {
4407   int count = 0;
4408   while(pl != NULL) {
4409     count++;
4410     pl = pl->next();
4411   }
4412   return count;
4413 }
4414 
4415 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4416   assert(key != NULL, "just checking");
4417   SystemProperty* prop;
4418   for (prop = pl; prop != NULL; prop = prop->next()) {
4419     if (strcmp(key, prop->key()) == 0) return prop->value();
4420   }
4421   return NULL;
4422 }
4423 
4424 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4425   int count = 0;
4426   const char* ret_val = NULL;
4427 
4428   while(pl != NULL) {
4429     if(count >= index) {
4430       ret_val = pl->key();
4431       break;
4432     }
4433     count++;
4434     pl = pl->next();
4435   }
4436 
4437   return ret_val;
4438 }
4439 
4440 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4441   int count = 0;
4442   char* ret_val = NULL;
4443 
4444   while(pl != NULL) {
4445     if(count >= index) {
4446       ret_val = pl->value();
4447       break;
4448     }
4449     count++;
4450     pl = pl->next();
4451   }
4452 
4453   return ret_val;
4454 }
4455 
4456 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4457   SystemProperty* p = *plist;
4458   if (p == NULL) {
4459     *plist = new_p;
4460   } else {
4461     while (p->next() != NULL) {
4462       p = p->next();
4463     }
4464     p->set_next(new_p);
4465   }
4466 }
4467 
4468 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v) {
4469   if (plist == NULL)
4470     return;
4471 
4472   SystemProperty* new_p = new SystemProperty(k, v, true);
4473   PropertyList_add(plist, new_p);
4474 }
4475 
4476 void Arguments::PropertyList_add(SystemProperty *element) {
4477   PropertyList_add(&_system_properties, element);
4478 }
4479 
4480 // This add maintains unique property key in the list.
4481 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v, jboolean append) {
4482   if (plist == NULL)
4483     return;
4484 
4485   // If property key exist then update with new value.
4486   SystemProperty* prop;
4487   for (prop = *plist; prop != NULL; prop = prop->next()) {
4488     if (strcmp(k, prop->key()) == 0) {
4489       if (append) {
4490         prop->append_value(v);
4491       } else {
4492         prop->set_value(v);
4493       }
4494       return;
4495     }
4496   }
4497 
4498   PropertyList_add(plist, k, v);
4499 }
4500 
4501 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4502 // Returns true if all of the source pointed by src has been copied over to
4503 // the destination buffer pointed by buf. Otherwise, returns false.
4504 // Notes:
4505 // 1. If the length (buflen) of the destination buffer excluding the
4506 // NULL terminator character is not long enough for holding the expanded
4507 // pid characters, it also returns false instead of returning the partially
4508 // expanded one.
4509 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4510 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4511                                 char* buf, size_t buflen) {
4512   const char* p = src;
4513   char* b = buf;
4514   const char* src_end = &src[srclen];
4515   char* buf_end = &buf[buflen - 1];
4516 
4517   while (p < src_end && b < buf_end) {
4518     if (*p == '%') {
4519       switch (*(++p)) {
4520       case '%':         // "%%" ==> "%"
4521         *b++ = *p++;
4522         break;
4523       case 'p':  {       //  "%p" ==> current process id
4524         // buf_end points to the character before the last character so
4525         // that we could write '\0' to the end of the buffer.
4526         size_t buf_sz = buf_end - b + 1;
4527         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4528 
4529         // if jio_snprintf fails or the buffer is not long enough to hold
4530         // the expanded pid, returns false.
4531         if (ret < 0 || ret >= (int)buf_sz) {
4532           return false;
4533         } else {
4534           b += ret;
4535           assert(*b == '\0', "fail in copy_expand_pid");
4536           if (p == src_end && b == buf_end + 1) {
4537             // reach the end of the buffer.
4538             return true;
4539           }
4540         }
4541         p++;
4542         break;
4543       }
4544       default :
4545         *b++ = '%';
4546       }
4547     } else {
4548       *b++ = *p++;
4549     }
4550   }
4551   *b = '\0';
4552   return (p == src_end); // return false if not all of the source was copied
4553 }