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