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