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/logConfiguration.hpp"
  37 #include "memory/allocation.inline.hpp"
  38 #include "memory/universe.inline.hpp"
  39 #include "oops/oop.inline.hpp"
  40 #include "prims/jvmtiExport.hpp"
  41 #include "runtime/arguments.hpp"
  42 #include "runtime/arguments_ext.hpp"
  43 #include "runtime/commandLineFlagConstraintList.hpp"
  44 #include "runtime/commandLineFlagRangeList.hpp"
  45 #include "runtime/globals.hpp"
  46 #include "runtime/globals_extension.hpp"
  47 #include "runtime/java.hpp"
  48 #include "runtime/os.hpp"
  49 #include "runtime/vm_version.hpp"
  50 #include "services/management.hpp"
  51 #include "services/memTracker.hpp"
  52 #include "utilities/defaultStream.hpp"
  53 #include "utilities/macros.hpp"
  54 #include "utilities/stringUtils.hpp"
  55 #if INCLUDE_JVMCI
  56 #include "jvmci/jvmciRuntime.hpp"
  57 #endif
  58 #if INCLUDE_ALL_GCS
  59 #include "gc/cms/compactibleFreeListSpace.hpp"
  60 #include "gc/g1/g1CollectedHeap.inline.hpp"
  61 #include "gc/parallel/parallelScavengeHeap.hpp"
  62 #endif // INCLUDE_ALL_GCS
  63 
  64 // Note: This is a special bug reporting site for the JVM
  65 #define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
  66 #define DEFAULT_JAVA_LAUNCHER  "generic"
  67 
  68 #define UNSUPPORTED_GC_OPTION(gc)                                     \
  69 do {                                                                  \
  70   if (gc) {                                                           \
  71     if (FLAG_IS_CMDLINE(gc)) {                                        \
  72       warning(#gc " is not supported in this VM.  Using Serial GC."); \
  73     }                                                                 \
  74     FLAG_SET_DEFAULT(gc, false);                                      \
  75   }                                                                   \
  76 } while(0)
  77 
  78 char*  Arguments::_jvm_flags_file               = NULL;
  79 char** Arguments::_jvm_flags_array              = NULL;
  80 int    Arguments::_num_jvm_flags                = 0;
  81 char** Arguments::_jvm_args_array               = NULL;
  82 int    Arguments::_num_jvm_args                 = 0;
  83 char*  Arguments::_java_command                 = NULL;
  84 SystemProperty* Arguments::_system_properties   = NULL;
  85 bool   Arguments::_has_profile                  = false;
  86 size_t Arguments::_conservative_max_heap_alignment = 0;
  87 size_t Arguments::_min_heap_size                = 0;
  88 Arguments::Mode Arguments::_mode                = _mixed;
  89 bool   Arguments::_java_compiler                = false;
  90 bool   Arguments::_xdebug_mode                  = false;
  91 const char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
  92 const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
  93 int    Arguments::_sun_java_launcher_pid        = -1;
  94 bool   Arguments::_sun_java_launcher_is_altjvm  = false;
  95 
  96 // These parameters are reset in method parse_vm_init_args()
  97 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
  98 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
  99 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
 100 bool   Arguments::_ClipInlining                 = ClipInlining;
 101 intx   Arguments::_Tier3InvokeNotifyFreqLog     = Tier3InvokeNotifyFreqLog;
 102 intx   Arguments::_Tier4InvocationThreshold     = Tier4InvocationThreshold;
 103 
 104 char*  Arguments::SharedArchivePath             = NULL;
 105 
 106 AgentLibraryList Arguments::_libraryList;
 107 AgentLibraryList Arguments::_agentList;
 108 
 109 abort_hook_t     Arguments::_abort_hook         = NULL;
 110 exit_hook_t      Arguments::_exit_hook          = NULL;
 111 vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
 112 
 113 
 114 SystemProperty *Arguments::_sun_boot_library_path = NULL;
 115 SystemProperty *Arguments::_java_library_path = NULL;
 116 SystemProperty *Arguments::_java_home = NULL;
 117 SystemProperty *Arguments::_java_class_path = NULL;
 118 SystemProperty *Arguments::_sun_boot_class_path = NULL;
 119 
 120 char* Arguments::_ext_dirs = NULL;
 121 
 122 // Check if head of 'option' matches 'name', and sets 'tail' to the remaining
 123 // part of the option string.
 124 static bool match_option(const JavaVMOption *option, const char* name,
 125                          const char** tail) {
 126   size_t len = strlen(name);
 127   if (strncmp(option->optionString, name, len) == 0) {
 128     *tail = option->optionString + len;
 129     return true;
 130   } else {
 131     return false;
 132   }
 133 }
 134 
 135 // Check if 'option' matches 'name'. No "tail" is allowed.
 136 static bool match_option(const JavaVMOption *option, const char* name) {
 137   const char* tail = NULL;
 138   bool result = match_option(option, name, &tail);
 139   if (tail != NULL && *tail == '\0') {
 140     return result;
 141   } else {
 142     return false;
 143   }
 144 }
 145 
 146 // Return true if any of the strings in null-terminated array 'names' matches.
 147 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
 148 // the option must match exactly.
 149 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
 150   bool tail_allowed) {
 151   for (/* empty */; *names != NULL; ++names) {
 152     if (match_option(option, *names, tail)) {
 153       if (**tail == '\0' || tail_allowed && **tail == ':') {
 154         return true;
 155       }
 156     }
 157   }
 158   return false;
 159 }
 160 
 161 static void logOption(const char* opt) {
 162   if (PrintVMOptions) {
 163     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
 164   }
 165 }
 166 
 167 // Process java launcher properties.
 168 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
 169   // See if sun.java.launcher, sun.java.launcher.is_altjvm or
 170   // sun.java.launcher.pid is defined.
 171   // Must do this before setting up other system properties,
 172   // as some of them may depend on launcher type.
 173   for (int index = 0; index < args->nOptions; index++) {
 174     const JavaVMOption* option = args->options + index;
 175     const char* tail;
 176 
 177     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
 178       process_java_launcher_argument(tail, option->extraInfo);
 179       continue;
 180     }
 181     if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
 182       if (strcmp(tail, "true") == 0) {
 183         _sun_java_launcher_is_altjvm = true;
 184       }
 185       continue;
 186     }
 187     if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
 188       _sun_java_launcher_pid = atoi(tail);
 189       continue;
 190     }
 191   }
 192 }
 193 
 194 // Initialize system properties key and value.
 195 void Arguments::init_system_properties() {
 196   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
 197                                                                  "Java Virtual Machine Specification",  false));
 198   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
 199   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
 200   PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
 201   PropertyList_add(&_system_properties, new SystemProperty("jdk.debug", VM_Version::jdk_debug_level(),  false));
 202 
 203   // Following are JVMTI agent writable properties.
 204   // Properties values are set to NULL and they are
 205   // os specific they are initialized in os::init_system_properties_values().
 206   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
 207   _java_library_path = new SystemProperty("java.library.path", NULL,  true);
 208   _java_home =  new SystemProperty("java.home", NULL,  true);
 209   _sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL,  true);
 210 
 211   _java_class_path = new SystemProperty("java.class.path", "",  true);
 212 
 213   // Add to System Property list.
 214   PropertyList_add(&_system_properties, _sun_boot_library_path);
 215   PropertyList_add(&_system_properties, _java_library_path);
 216   PropertyList_add(&_system_properties, _java_home);
 217   PropertyList_add(&_system_properties, _java_class_path);
 218   PropertyList_add(&_system_properties, _sun_boot_class_path);
 219 
 220   // Set OS specific system properties values
 221   os::init_system_properties_values();
 222 
 223   JVMCI_ONLY(JVMCIRuntime::init_system_properties(&_system_properties);)
 224 }
 225 
 226 // Update/Initialize System properties after JDK version number is known
 227 void Arguments::init_version_specific_system_properties() {
 228   enum { bufsz = 16 };
 229   char buffer[bufsz];
 230   const char* spec_vendor = "Oracle Corporation";
 231   uint32_t spec_version = JDK_Version::current().major_version();
 232 
 233   jio_snprintf(buffer, bufsz, UINT32_FORMAT, spec_version);
 234 
 235   PropertyList_add(&_system_properties,
 236       new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
 237   PropertyList_add(&_system_properties,
 238       new SystemProperty("java.vm.specification.version", buffer, false));
 239   PropertyList_add(&_system_properties,
 240       new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
 241 }
 242 
 243 /*
 244  *  -XX argument processing:
 245  *
 246  *  -XX arguments are defined in several places, such as:
 247  *      globals.hpp, globals_<cpu>.hpp, globals_<os>.hpp, <compiler>_globals.hpp, or <gc>_globals.hpp.
 248  *  -XX arguments are parsed in parse_argument().
 249  *  -XX argument bounds checking is done in check_vm_args_consistency().
 250  *
 251  * Over time -XX arguments may change. There are mechanisms to handle common cases:
 252  *
 253  *      ALIASED: An option that is simply another name for another option. This is often
 254  *               part of the process of deprecating a flag, but not all aliases need
 255  *               to be deprecated.
 256  *
 257  *               Create an alias for an option by adding the old and new option names to the
 258  *               "aliased_jvm_flags" table. Delete the old variable from globals.hpp (etc).
 259  *
 260  *   DEPRECATED: An option that is supported, but a warning is printed to let the user know that
 261  *               support may be removed in the future. Both regular and aliased options may be
 262  *               deprecated.
 263  *
 264  *               Add a deprecation warning for an option (or alias) by adding an entry in the
 265  *               "special_jvm_flags" table and setting the "deprecated_in" field.
 266  *               Often an option "deprecated" in one major release will
 267  *               be made "obsolete" in the next. In this case the entry should also have it's
 268  *               "obsolete_in" field set.
 269  *
 270  *     OBSOLETE: An option that has been removed (and deleted from globals.hpp), but is still accepted
 271  *               on the command line. A warning is printed to let the user know that option might not
 272  *               be accepted in the future.
 273  *
 274  *               Add an obsolete warning for an option by adding an entry in the "special_jvm_flags"
 275  *               table and setting the "obsolete_in" field.
 276  *
 277  *      EXPIRED: A deprecated or obsolete option that has an "accept_until" version less than or equal
 278  *               to the current JDK version. The system will flatly refuse to admit the existence of
 279  *               the flag. This allows a flag to die automatically over JDK releases.
 280  *
 281  *               Note that manual cleanup of expired options should be done at major JDK version upgrades:
 282  *                  - Newly expired options should be removed from the special_jvm_flags and aliased_jvm_flags tables.
 283  *                  - Newly obsolete or expired deprecated options should have their global variable
 284  *                    definitions removed (from globals.hpp, etc) and related implementations removed.
 285  *
 286  * Recommended approach for removing options:
 287  *
 288  * To remove options commonly used by customers (e.g. product, commercial -XX options), use
 289  * the 3-step model adding major release numbers to the deprecate, obsolete and expire columns.
 290  *
 291  * To remove internal options (e.g. diagnostic, experimental, develop options), use
 292  * a 2-step model adding major release numbers to the obsolete and expire columns.
 293  *
 294  * To change the name of an option, use the alias table as well as a 2-step
 295  * model adding major release numbers to the deprecate and expire columns.
 296  * Think twice about aliasing commonly used customer options.
 297  *
 298  * There are times when it is appropriate to leave a future release number as undefined.
 299  *
 300  * Tests:  Aliases should be tested in VMAliasOptions.java.
 301  *         Deprecated options should be tested in VMDeprecatedOptions.java.
 302  */
 303 
 304 // Obsolete or deprecated -XX flag.
 305 typedef struct {
 306   const char* name;
 307   JDK_Version deprecated_in; // When the deprecation warning started (or "undefined").
 308   JDK_Version obsolete_in;   // When the obsolete warning started (or "undefined").
 309   JDK_Version expired_in;    // When the option expires (or "undefined").
 310 } SpecialFlag;
 311 
 312 // The special_jvm_flags table declares options that are being deprecated and/or obsoleted. The
 313 // "deprecated_in" or "obsolete_in" fields may be set to "undefined", but not both.
 314 // When the JDK version reaches 'deprecated_in' limit, the JVM will process this flag on
 315 // the command-line as usual, but will issue a warning.
 316 // When the JDK version reaches 'obsolete_in' limit, the JVM will continue accepting this flag on
 317 // the command-line, while issuing a warning and ignoring the flag value.
 318 // Once the JDK version reaches 'expired_in' limit, the JVM will flatly refuse to admit the
 319 // existence of the flag.
 320 //
 321 // MANUAL CLEANUP ON JDK VERSION UPDATES:
 322 // This table ensures that the handling of options will update automatically when the JDK
 323 // version is incremented, but the source code needs to be cleanup up manually:
 324 // - As "deprecated" options age into "obsolete" or "expired" options, the associated "globals"
 325 //   variable should be removed, as well as users of the variable.
 326 // - As "deprecated" options age into "obsolete" options, move the entry into the
 327 //   "Obsolete Flags" section of the table.
 328 // - All expired options should be removed from the table.
 329 static SpecialFlag const special_jvm_flags[] = {
 330   // -------------- Deprecated Flags --------------
 331   // --- Non-alias flags - sorted by obsolete_in then expired_in:
 332   { "MaxGCMinorPauseMillis",        JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
 333   { "UseParNewGC",                  JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 334 
 335   // --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in:
 336   { "DefaultMaxRAMFraction",        JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
 337   { "CreateMinidumpOnCrash",        JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 338   { "CMSMarkStackSizeMax",          JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 339   { "CMSMarkStackSize",             JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 340   { "G1MarkStackSize",              JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 341   { "ParallelMarkingThreads",       JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 342   { "ParallelCMSThreads",           JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 343 
 344   // -------------- Obsolete Flags - sorted by expired_in --------------
 345   { "UseOldInlining",                JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 346   { "SafepointPollOffset",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 347   { "UseBoundThreads",               JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 348   { "DefaultThreadPriority",         JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 349   { "NoYieldsInMicrolock",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 350   { "BackEdgeThreshold",             JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 351   { "UseNewReflection",              JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 352   { "ReflectionWrapResolutionErrors",JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 353   { "VerifyReflectionBytecodes",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 354   { "AutoShutdownNMT",               JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 355   { "NmethodSweepFraction",          JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 356   { "NmethodSweepCheckInterval",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 357   { "CodeCacheMinimumFreeSpace",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 358 #ifndef ZERO
 359   { "UseFastAccessorMethods",        JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 360   { "UseFastEmptyMethods",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 361 #endif // ZERO
 362   { "UseCompilerSafepoints",         JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 363   { "AdaptiveSizePausePolicy",       JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 364   { "ParallelGCRetainPLAB",          JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 365   { "ThreadSafetyMargin",            JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 366   { "LazyBootClassLoader",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 367   { "StarvationMonitorInterval",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 368   { "PreInflateSpin",                JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 369   { "JNIDetachReleasesMonitors",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 370   { "UseAltSigs",                    JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
 371 
 372 #ifdef TEST_VERIFY_SPECIAL_JVM_FLAGS
 373   { "dep > obs",                    JDK_Version::jdk(9), JDK_Version::jdk(8), JDK_Version::undefined() },
 374   { "dep > exp ",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(8) },
 375   { "obs > exp ",                   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(8) },
 376   { "not deprecated or obsolete",   JDK_Version::undefined(), JDK_Version::undefined(), JDK_Version::jdk(9) },
 377   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 378   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 379   { "BytecodeVerificationRemote",   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::undefined() },
 380 #endif
 381 
 382   { NULL, JDK_Version(0), JDK_Version(0) }
 383 };
 384 
 385 // Flags that are aliases for other flags.
 386 typedef struct {
 387   const char* alias_name;
 388   const char* real_name;
 389 } AliasedFlag;
 390 
 391 static AliasedFlag const aliased_jvm_flags[] = {
 392   { "DefaultMaxRAMFraction",    "MaxRAMFraction"    },
 393   { "CMSMarkStackSizeMax",      "MarkStackSizeMax"  },
 394   { "CMSMarkStackSize",         "MarkStackSize"     },
 395   { "G1MarkStackSize",          "MarkStackSize"     },
 396   { "ParallelMarkingThreads",   "ConcGCThreads"     },
 397   { "ParallelCMSThreads",       "ConcGCThreads"     },
 398   { "CreateMinidumpOnCrash",    "CreateCoredumpOnCrash" },
 399   { NULL, NULL}
 400 };
 401 
 402 static AliasedFlag const aliased_jvm_logging_flags[] = {
 403   { "-XX:+TraceMonitorInflation", "-Xlog:monitorinflation=debug" },
 404   { "-XX:-TraceMonitorInflation", "-Xlog:monitorinflation=off" },
 405   { NULL, NULL }
 406 };
 407 
 408 // Return true if "v" is less than "other", where "other" may be "undefined".
 409 static bool version_less_than(JDK_Version v, JDK_Version other) {
 410   assert(!v.is_undefined(), "must be defined");
 411   if (!other.is_undefined() && v.compare(other) >= 0) {
 412     return false;
 413   } else {
 414     return true;
 415   }
 416 }
 417 
 418 static bool lookup_special_flag(const char *flag_name, SpecialFlag& flag) {
 419   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 420     if ((strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 421       flag = special_jvm_flags[i];
 422       return true;
 423     }
 424   }
 425   return false;
 426 }
 427 
 428 bool Arguments::is_obsolete_flag(const char *flag_name, JDK_Version* version) {
 429   assert(version != NULL, "Must provide a version buffer");
 430   SpecialFlag flag;
 431   if (lookup_special_flag(flag_name, flag)) {
 432     if (!flag.obsolete_in.is_undefined()) {
 433       if (version_less_than(JDK_Version::current(), flag.expired_in)) {
 434         *version = flag.obsolete_in;
 435         return true;
 436       }
 437     }
 438   }
 439   return false;
 440 }
 441 
 442 int Arguments::is_deprecated_flag(const char *flag_name, JDK_Version* version) {
 443   assert(version != NULL, "Must provide a version buffer");
 444   SpecialFlag flag;
 445   if (lookup_special_flag(flag_name, flag)) {
 446     if (!flag.deprecated_in.is_undefined()) {
 447       if (version_less_than(JDK_Version::current(), flag.obsolete_in) &&
 448           version_less_than(JDK_Version::current(), flag.expired_in)) {
 449         *version = flag.deprecated_in;
 450         return 1;
 451       } else {
 452         return -1;
 453       }
 454     }
 455   }
 456   return 0;
 457 }
 458 
 459 const char* Arguments::real_flag_name(const char *flag_name) {
 460   for (size_t i = 0; aliased_jvm_flags[i].alias_name != NULL; i++) {
 461     const AliasedFlag& flag_status = aliased_jvm_flags[i];
 462     if (strcmp(flag_status.alias_name, flag_name) == 0) {
 463         return flag_status.real_name;
 464     }
 465   }
 466   return flag_name;
 467 }
 468 
 469 #ifdef ASSERT
 470 static bool lookup_special_flag(const char *flag_name, size_t skip_index) {
 471   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 472     if ((i != skip_index) && (strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 473       return true;
 474     }
 475   }
 476   return false;
 477 }
 478 
 479 static bool verify_special_jvm_flags() {
 480   bool success = true;
 481   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 482     const SpecialFlag& flag = special_jvm_flags[i];
 483     if (lookup_special_flag(flag.name, i)) {
 484       warning("Duplicate special flag declaration \"%s\"", flag.name);
 485       success = false;
 486     }
 487     if (flag.deprecated_in.is_undefined() &&
 488         flag.obsolete_in.is_undefined()) {
 489       warning("Special flag entry \"%s\" must declare version deprecated and/or obsoleted in.", flag.name);
 490       success = false;
 491     }
 492 
 493     if (!flag.deprecated_in.is_undefined()) {
 494       if (!version_less_than(flag.deprecated_in, flag.obsolete_in)) {
 495         warning("Special flag entry \"%s\" must be deprecated before obsoleted.", flag.name);
 496         success = false;
 497       }
 498 
 499       if (!version_less_than(flag.deprecated_in, flag.expired_in)) {
 500         warning("Special flag entry \"%s\" must be deprecated before expired.", flag.name);
 501         success = false;
 502       }
 503     }
 504 
 505     if (!flag.obsolete_in.is_undefined()) {
 506       if (!version_less_than(flag.obsolete_in, flag.expired_in)) {
 507         warning("Special flag entry \"%s\" must be obsoleted before expired.", flag.name);
 508         success = false;
 509       }
 510 
 511       // if flag has become obsolete it should not have a "globals" flag defined anymore.
 512       if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 513         if (Flag::find_flag(flag.name) != NULL) {
 514           warning("Global variable for obsolete special flag entry \"%s\" should be removed", flag.name);
 515           success = false;
 516         }
 517       }
 518     }
 519 
 520     if (!flag.expired_in.is_undefined()) {
 521       // if flag has become expired it should not have a "globals" flag defined anymore.
 522       if (!version_less_than(JDK_Version::current(), flag.expired_in)) {
 523         if (Flag::find_flag(flag.name) != NULL) {
 524           warning("Global variable for expired flag entry \"%s\" should be removed", flag.name);
 525           success = false;
 526         }
 527       }
 528     }
 529 
 530   }
 531   return success;
 532 }
 533 #endif
 534 
 535 // Constructs the system class path (aka boot class path) from the following
 536 // components, in order:
 537 //
 538 //     prefix           // from -Xbootclasspath/p:...
 539 //     base             // from os::get_system_properties() or -Xbootclasspath=
 540 //     suffix           // from -Xbootclasspath/a:...
 541 //
 542 // This could be AllStatic, but it isn't needed after argument processing is
 543 // complete.
 544 class SysClassPath: public StackObj {
 545 public:
 546   SysClassPath(const char* base);
 547   ~SysClassPath();
 548 
 549   inline void set_base(const char* base);
 550   inline void add_prefix(const char* prefix);
 551   inline void add_suffix_to_prefix(const char* suffix);
 552   inline void add_suffix(const char* suffix);
 553   inline void reset_path(const char* base);
 554 
 555   inline const char* get_base()     const { return _items[_scp_base]; }
 556   inline const char* get_prefix()   const { return _items[_scp_prefix]; }
 557   inline const char* get_suffix()   const { return _items[_scp_suffix]; }
 558 
 559   // Combine all the components into a single c-heap-allocated string; caller
 560   // must free the string if/when no longer needed.
 561   char* combined_path();
 562 
 563 private:
 564   // Utility routines.
 565   static char* add_to_path(const char* path, const char* str, bool prepend);
 566   static char* add_jars_to_path(char* path, const char* directory);
 567 
 568   inline void reset_item_at(int index);
 569 
 570   // Array indices for the items that make up the sysclasspath.  All except the
 571   // base are allocated in the C heap and freed by this class.
 572   enum {
 573     _scp_prefix,        // from -Xbootclasspath/p:...
 574     _scp_base,          // the default sysclasspath
 575     _scp_suffix,        // from -Xbootclasspath/a:...
 576     _scp_nitems         // the number of items, must be last.
 577   };
 578 
 579   const char* _items[_scp_nitems];
 580 };
 581 
 582 SysClassPath::SysClassPath(const char* base) {
 583   memset(_items, 0, sizeof(_items));
 584   _items[_scp_base] = base;
 585 }
 586 
 587 SysClassPath::~SysClassPath() {
 588   // Free everything except the base.
 589   for (int i = 0; i < _scp_nitems; ++i) {
 590     if (i != _scp_base) reset_item_at(i);
 591   }
 592 }
 593 
 594 inline void SysClassPath::set_base(const char* base) {
 595   _items[_scp_base] = base;
 596 }
 597 
 598 inline void SysClassPath::add_prefix(const char* prefix) {
 599   _items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);
 600 }
 601 
 602 inline void SysClassPath::add_suffix_to_prefix(const char* suffix) {
 603   _items[_scp_prefix] = add_to_path(_items[_scp_prefix], suffix, false);
 604 }
 605 
 606 inline void SysClassPath::add_suffix(const char* suffix) {
 607   _items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);
 608 }
 609 
 610 inline void SysClassPath::reset_item_at(int index) {
 611   assert(index < _scp_nitems && index != _scp_base, "just checking");
 612   if (_items[index] != NULL) {
 613     FREE_C_HEAP_ARRAY(char, _items[index]);
 614     _items[index] = NULL;
 615   }
 616 }
 617 
 618 inline void SysClassPath::reset_path(const char* base) {
 619   // Clear the prefix and suffix.
 620   reset_item_at(_scp_prefix);
 621   reset_item_at(_scp_suffix);
 622   set_base(base);
 623 }
 624 
 625 //------------------------------------------------------------------------------
 626 
 627 
 628 // Combine the bootclasspath elements, some of which may be null, into a single
 629 // c-heap-allocated string.
 630 char* SysClassPath::combined_path() {
 631   assert(_items[_scp_base] != NULL, "empty default sysclasspath");
 632 
 633   size_t lengths[_scp_nitems];
 634   size_t total_len = 0;
 635 
 636   const char separator = *os::path_separator();
 637 
 638   // Get the lengths.
 639   int i;
 640   for (i = 0; i < _scp_nitems; ++i) {
 641     if (_items[i] != NULL) {
 642       lengths[i] = strlen(_items[i]);
 643       // Include space for the separator char (or a NULL for the last item).
 644       total_len += lengths[i] + 1;
 645     }
 646   }
 647   assert(total_len > 0, "empty sysclasspath not allowed");
 648 
 649   // Copy the _items to a single string.
 650   char* cp = NEW_C_HEAP_ARRAY(char, total_len, mtInternal);
 651   char* cp_tmp = cp;
 652   for (i = 0; i < _scp_nitems; ++i) {
 653     if (_items[i] != NULL) {
 654       memcpy(cp_tmp, _items[i], lengths[i]);
 655       cp_tmp += lengths[i];
 656       *cp_tmp++ = separator;
 657     }
 658   }
 659   *--cp_tmp = '\0';     // Replace the extra separator.
 660   return cp;
 661 }
 662 
 663 // Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
 664 char*
 665 SysClassPath::add_to_path(const char* path, const char* str, bool prepend) {
 666   char *cp;
 667 
 668   assert(str != NULL, "just checking");
 669   if (path == NULL) {
 670     size_t len = strlen(str) + 1;
 671     cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
 672     memcpy(cp, str, len);                       // copy the trailing null
 673   } else {
 674     const char separator = *os::path_separator();
 675     size_t old_len = strlen(path);
 676     size_t str_len = strlen(str);
 677     size_t len = old_len + str_len + 2;
 678 
 679     if (prepend) {
 680       cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
 681       char* cp_tmp = cp;
 682       memcpy(cp_tmp, str, str_len);
 683       cp_tmp += str_len;
 684       *cp_tmp = separator;
 685       memcpy(++cp_tmp, path, old_len + 1);      // copy the trailing null
 686       FREE_C_HEAP_ARRAY(char, path);
 687     } else {
 688       cp = REALLOC_C_HEAP_ARRAY(char, path, len, mtInternal);
 689       char* cp_tmp = cp + old_len;
 690       *cp_tmp = separator;
 691       memcpy(++cp_tmp, str, str_len + 1);       // copy the trailing null
 692     }
 693   }
 694   return cp;
 695 }
 696 
 697 // Scan the directory and append any jar or zip files found to path.
 698 // Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
 699 char* SysClassPath::add_jars_to_path(char* path, const char* directory) {
 700   DIR* dir = os::opendir(directory);
 701   if (dir == NULL) return path;
 702 
 703   char dir_sep[2] = { '\0', '\0' };
 704   size_t directory_len = strlen(directory);
 705   const char fileSep = *os::file_separator();
 706   if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;
 707 
 708   /* Scan the directory for jars/zips, appending them to path. */
 709   struct dirent *entry;
 710   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
 711   while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
 712     const char* name = entry->d_name;
 713     const char* ext = name + strlen(name) - 4;
 714     bool isJarOrZip = ext > name &&
 715       (os::file_name_strcmp(ext, ".jar") == 0 ||
 716        os::file_name_strcmp(ext, ".zip") == 0);
 717     if (isJarOrZip) {
 718       char* jarpath = NEW_C_HEAP_ARRAY(char, directory_len + 2 + strlen(name), mtInternal);
 719       sprintf(jarpath, "%s%s%s", directory, dir_sep, name);
 720       path = add_to_path(path, jarpath, false);
 721       FREE_C_HEAP_ARRAY(char, jarpath);
 722     }
 723   }
 724   FREE_C_HEAP_ARRAY(char, dbuf);
 725   os::closedir(dir);
 726   return path;
 727 }
 728 
 729 // Parses a memory size specification string.
 730 static bool atomull(const char *s, julong* result) {
 731   julong n = 0;
 732   int args_read = 0;
 733   bool is_hex = false;
 734   // Skip leading 0[xX] for hexadecimal
 735   if (*s =='0' && (*(s+1) == 'x' || *(s+1) == 'X')) {
 736     s += 2;
 737     is_hex = true;
 738     args_read = sscanf(s, JULONG_FORMAT_X, &n);
 739   } else {
 740     args_read = sscanf(s, JULONG_FORMAT, &n);
 741   }
 742   if (args_read != 1) {
 743     return false;
 744   }
 745   while (*s != '\0' && (isdigit(*s) || (is_hex && isxdigit(*s)))) {
 746     s++;
 747   }
 748   // 4705540: illegal if more characters are found after the first non-digit
 749   if (strlen(s) > 1) {
 750     return false;
 751   }
 752   switch (*s) {
 753     case 'T': case 't':
 754       *result = n * G * K;
 755       // Check for overflow.
 756       if (*result/((julong)G * K) != n) return false;
 757       return true;
 758     case 'G': case 'g':
 759       *result = n * G;
 760       if (*result/G != n) return false;
 761       return true;
 762     case 'M': case 'm':
 763       *result = n * M;
 764       if (*result/M != n) return false;
 765       return true;
 766     case 'K': case 'k':
 767       *result = n * K;
 768       if (*result/K != n) return false;
 769       return true;
 770     case '\0':
 771       *result = n;
 772       return true;
 773     default:
 774       return false;
 775   }
 776 }
 777 
 778 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
 779   if (size < min_size) return arg_too_small;
 780   // Check that size will fit in a size_t (only relevant on 32-bit)
 781   if (size > max_uintx) return arg_too_big;
 782   return arg_in_range;
 783 }
 784 
 785 // Describe an argument out of range error
 786 void Arguments::describe_range_error(ArgsRange errcode) {
 787   switch(errcode) {
 788   case arg_too_big:
 789     jio_fprintf(defaultStream::error_stream(),
 790                 "The specified size exceeds the maximum "
 791                 "representable size.\n");
 792     break;
 793   case arg_too_small:
 794   case arg_unreadable:
 795   case arg_in_range:
 796     // do nothing for now
 797     break;
 798   default:
 799     ShouldNotReachHere();
 800   }
 801 }
 802 
 803 static bool set_bool_flag(const char* name, bool value, Flag::Flags origin) {
 804   if (CommandLineFlags::boolAtPut(name, &value, origin) == Flag::SUCCESS) {
 805     return true;
 806   } else {
 807     return false;
 808   }
 809 }
 810 
 811 static bool set_fp_numeric_flag(const char* name, char* value, Flag::Flags origin) {
 812   char* end;
 813   errno = 0;
 814   double v = strtod(value, &end);
 815   if ((errno != 0) || (*end != 0)) {
 816     return false;
 817   }
 818 
 819   if (CommandLineFlags::doubleAtPut(name, &v, origin) == Flag::SUCCESS) {
 820     return true;
 821   }
 822   return false;
 823 }
 824 
 825 static bool set_numeric_flag(const char* name, char* value, Flag::Flags origin) {
 826   julong v;
 827   int int_v;
 828   intx intx_v;
 829   bool is_neg = false;
 830   Flag* result = Flag::find_flag(name, strlen(name));
 831 
 832   if (result == NULL) {
 833     return false;
 834   }
 835 
 836   // Check the sign first since atomull() parses only unsigned values.
 837   if (*value == '-') {
 838     if (!result->is_intx() && !result->is_int()) {
 839       return false;
 840     }
 841     value++;
 842     is_neg = true;
 843   }
 844   if (!atomull(value, &v)) {
 845     return false;
 846   }
 847   if (result->is_int()) {
 848     int_v = (int) v;
 849     if (is_neg) {
 850       int_v = -int_v;
 851     }
 852     return CommandLineFlags::intAtPut(result, &int_v, origin) == Flag::SUCCESS;
 853   } else if (result->is_uint()) {
 854     uint uint_v = (uint) v;
 855     return CommandLineFlags::uintAtPut(result, &uint_v, origin) == Flag::SUCCESS;
 856   } else if (result->is_intx()) {
 857     intx_v = (intx) v;
 858     if (is_neg) {
 859       intx_v = -intx_v;
 860     }
 861     return CommandLineFlags::intxAtPut(result, &intx_v, origin) == Flag::SUCCESS;
 862   } else if (result->is_uintx()) {
 863     uintx uintx_v = (uintx) v;
 864     return CommandLineFlags::uintxAtPut(result, &uintx_v, origin) == Flag::SUCCESS;
 865   } else if (result->is_uint64_t()) {
 866     uint64_t uint64_t_v = (uint64_t) v;
 867     return CommandLineFlags::uint64_tAtPut(result, &uint64_t_v, origin) == Flag::SUCCESS;
 868   } else if (result->is_size_t()) {
 869     size_t size_t_v = (size_t) v;
 870     return CommandLineFlags::size_tAtPut(result, &size_t_v, origin) == Flag::SUCCESS;
 871   } else {
 872     return false;
 873   }
 874 }
 875 
 876 static bool set_string_flag(const char* name, const char* value, Flag::Flags origin) {
 877   if (CommandLineFlags::ccstrAtPut(name, &value, origin) != Flag::SUCCESS) return false;
 878   // Contract:  CommandLineFlags always returns a pointer that needs freeing.
 879   FREE_C_HEAP_ARRAY(char, value);
 880   return true;
 881 }
 882 
 883 static bool append_to_string_flag(const char* name, const char* new_value, Flag::Flags origin) {
 884   const char* old_value = "";
 885   if (CommandLineFlags::ccstrAt(name, &old_value) != Flag::SUCCESS) return false;
 886   size_t old_len = old_value != NULL ? strlen(old_value) : 0;
 887   size_t new_len = strlen(new_value);
 888   const char* value;
 889   char* free_this_too = NULL;
 890   if (old_len == 0) {
 891     value = new_value;
 892   } else if (new_len == 0) {
 893     value = old_value;
 894   } else {
 895     char* buf = NEW_C_HEAP_ARRAY(char, old_len + 1 + new_len + 1, mtInternal);
 896     // each new setting adds another LINE to the switch:
 897     sprintf(buf, "%s\n%s", old_value, new_value);
 898     value = buf;
 899     free_this_too = buf;
 900   }
 901   (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
 902   // CommandLineFlags always returns a pointer that needs freeing.
 903   FREE_C_HEAP_ARRAY(char, value);
 904   if (free_this_too != NULL) {
 905     // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
 906     FREE_C_HEAP_ARRAY(char, free_this_too);
 907   }
 908   return true;
 909 }
 910 
 911 const char* Arguments::handle_aliases_and_deprecation(const char* arg, bool warn) {
 912   const char* real_name = real_flag_name(arg);
 913   JDK_Version since = JDK_Version();
 914   switch (is_deprecated_flag(arg, &since)) {
 915     case -1:
 916       return NULL; // obsolete or expired, don't process normally
 917     case 0:
 918       return real_name;
 919     case 1: {
 920       if (warn) {
 921         char version[256];
 922         since.to_string(version, sizeof(version));
 923         if (real_name != arg) {
 924           warning("Option %s was deprecated in version %s and will likely be removed in a future release. Use option %s instead.",
 925                   arg, version, real_name);
 926         } else {
 927           warning("Option %s was deprecated in version %s and will likely be removed in a future release.",
 928                   arg, version);
 929         }
 930       }
 931       return real_name;
 932     }
 933   }
 934   ShouldNotReachHere();
 935   return NULL;
 936 }
 937 
 938 // lookup_logging_aliases
 939 // Called from parse_each_vm_init_arg(). Should be called on -XX options before specific cases are checked.
 940 // If arg matches any aliased_jvm_logging_flags entry, look up the real name and copy it into buffer.
 941 bool Arguments::lookup_logging_aliases(const char* arg, char* buffer) {
 942   for (size_t i = 0; aliased_jvm_logging_flags[i].alias_name != NULL; i++) {
 943     const AliasedFlag& flag_status = aliased_jvm_logging_flags[i];
 944     if (strcmp(flag_status.alias_name, arg) == 0) {
 945       strcpy(buffer, flag_status.real_name);
 946       return true;
 947     }
 948   }
 949   return false;
 950 }
 951 
 952 bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
 953 
 954   // range of acceptable characters spelled out for portability reasons
 955 #define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
 956 #define BUFLEN 255
 957   char name[BUFLEN+1];
 958   char dummy;
 959   const char* real_name;
 960   bool warn_if_deprecated = true;
 961 
 962   if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
 963     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
 964     if (real_name == NULL) {
 965       return false;
 966     }
 967     return set_bool_flag(real_name, false, origin);
 968   }
 969   if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
 970     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
 971     if (real_name == NULL) {
 972       return false;
 973     }
 974     return set_bool_flag(real_name, true, origin);
 975   }
 976 
 977   char punct;
 978   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
 979     const char* value = strchr(arg, '=') + 1;
 980     Flag* flag;
 981 
 982     // this scanf pattern matches both strings (handled here) and numbers (handled later))
 983     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
 984     if (real_name == NULL) {
 985       return false;
 986     }
 987     flag = Flag::find_flag(real_name);
 988     if (flag != NULL && flag->is_ccstr()) {
 989       if (flag->ccstr_accumulates()) {
 990         return append_to_string_flag(real_name, value, origin);
 991       } else {
 992         if (value[0] == '\0') {
 993           value = NULL;
 994         }
 995         return set_string_flag(real_name, value, origin);
 996       }
 997     } else {
 998       warn_if_deprecated = false; // if arg is deprecated, we've already done warning...
 999     }
1000   }
1001 
1002   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
1003     const char* value = strchr(arg, '=') + 1;
1004     // -XX:Foo:=xxx will reset the string flag to the given value.
1005     if (value[0] == '\0') {
1006       value = NULL;
1007     }
1008     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1009     if (real_name == NULL) {
1010       return false;
1011     }
1012     return set_string_flag(real_name, value, origin);
1013   }
1014 
1015 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.eE+]"
1016 #define SIGNED_NUMBER_RANGE    "[-0123456789]"
1017 #define        NUMBER_RANGE    "[0123456789eE+-]"
1018   char value[BUFLEN + 1];
1019   char value2[BUFLEN + 1];
1020   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
1021     // Looks like a floating-point number -- try again with more lenient format string
1022     if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
1023       real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1024       if (real_name == NULL) {
1025         return false;
1026       }
1027       return set_fp_numeric_flag(real_name, value, origin);
1028     }
1029   }
1030 
1031 #define VALUE_RANGE "[-kmgtxKMGTX0123456789abcdefABCDEF]"
1032   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_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_numeric_flag(real_name, value, origin);
1038   }
1039 
1040   return false;
1041 }
1042 
1043 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
1044   assert(bldarray != NULL, "illegal argument");
1045 
1046   if (arg == NULL) {
1047     return;
1048   }
1049 
1050   int new_count = *count + 1;
1051 
1052   // expand the array and add arg to the last element
1053   if (*bldarray == NULL) {
1054     *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtInternal);
1055   } else {
1056     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtInternal);
1057   }
1058   (*bldarray)[*count] = os::strdup_check_oom(arg);
1059   *count = new_count;
1060 }
1061 
1062 void Arguments::build_jvm_args(const char* arg) {
1063   add_string(&_jvm_args_array, &_num_jvm_args, arg);
1064 }
1065 
1066 void Arguments::build_jvm_flags(const char* arg) {
1067   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
1068 }
1069 
1070 // utility function to return a string that concatenates all
1071 // strings in a given char** array
1072 const char* Arguments::build_resource_string(char** args, int count) {
1073   if (args == NULL || count == 0) {
1074     return NULL;
1075   }
1076   size_t length = strlen(args[0]) + 1; // add 1 for the null terminator
1077   for (int i = 1; i < count; i++) {
1078     length += strlen(args[i]) + 1; // add 1 for a space
1079   }
1080   char* s = NEW_RESOURCE_ARRAY(char, length);
1081   strcpy(s, args[0]);
1082   for (int j = 1; j < count; j++) {
1083     strcat(s, " ");
1084     strcat(s, args[j]);
1085   }
1086   return (const char*) s;
1087 }
1088 
1089 void Arguments::print_on(outputStream* st) {
1090   st->print_cr("VM Arguments:");
1091   if (num_jvm_flags() > 0) {
1092     st->print("jvm_flags: "); print_jvm_flags_on(st);
1093     st->cr();
1094   }
1095   if (num_jvm_args() > 0) {
1096     st->print("jvm_args: "); print_jvm_args_on(st);
1097     st->cr();
1098   }
1099   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
1100   if (_java_class_path != NULL) {
1101     char* path = _java_class_path->value();
1102     st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
1103   }
1104   st->print_cr("Launcher Type: %s", _sun_java_launcher);
1105 }
1106 
1107 void Arguments::print_summary_on(outputStream* st) {
1108   // Print the command line.  Environment variables that are helpful for
1109   // reproducing the problem are written later in the hs_err file.
1110   // flags are from setting file
1111   if (num_jvm_flags() > 0) {
1112     st->print_raw("Settings File: ");
1113     print_jvm_flags_on(st);
1114     st->cr();
1115   }
1116   // args are the command line and environment variable arguments.
1117   st->print_raw("Command Line: ");
1118   if (num_jvm_args() > 0) {
1119     print_jvm_args_on(st);
1120   }
1121   // this is the classfile and any arguments to the java program
1122   if (java_command() != NULL) {
1123     st->print("%s", java_command());
1124   }
1125   st->cr();
1126 }
1127 
1128 void Arguments::print_jvm_flags_on(outputStream* st) {
1129   if (_num_jvm_flags > 0) {
1130     for (int i=0; i < _num_jvm_flags; i++) {
1131       st->print("%s ", _jvm_flags_array[i]);
1132     }
1133   }
1134 }
1135 
1136 void Arguments::print_jvm_args_on(outputStream* st) {
1137   if (_num_jvm_args > 0) {
1138     for (int i=0; i < _num_jvm_args; i++) {
1139       st->print("%s ", _jvm_args_array[i]);
1140     }
1141   }
1142 }
1143 
1144 bool Arguments::process_argument(const char* arg,
1145                                  jboolean ignore_unrecognized,
1146                                  Flag::Flags origin) {
1147   JDK_Version since = JDK_Version();
1148 
1149   if (parse_argument(arg, origin)) {
1150     return true;
1151   }
1152 
1153   // Determine if the flag has '+', '-', or '=' characters.
1154   bool has_plus_minus = (*arg == '+' || *arg == '-');
1155   const char* const argname = has_plus_minus ? arg + 1 : arg;
1156 
1157   size_t arg_len;
1158   const char* equal_sign = strchr(argname, '=');
1159   if (equal_sign == NULL) {
1160     arg_len = strlen(argname);
1161   } else {
1162     arg_len = equal_sign - argname;
1163   }
1164 
1165   // Only make the obsolete check for valid arguments.
1166   if (arg_len <= BUFLEN) {
1167     // Construct a string which consists only of the argument name without '+', '-', or '='.
1168     char stripped_argname[BUFLEN+1];
1169     strncpy(stripped_argname, argname, arg_len);
1170     stripped_argname[arg_len] = '\0';  // strncpy may not null terminate.
1171 
1172     if (is_obsolete_flag(stripped_argname, &since)) {
1173       char version[256];
1174       since.to_string(version, sizeof(version));
1175       warning("Ignoring option %s; support was removed in %s", stripped_argname, version);
1176       return true;
1177     }
1178   }
1179 
1180   // For locked flags, report a custom error message if available.
1181   // Otherwise, report the standard unrecognized VM option.
1182   Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
1183   if (found_flag != NULL) {
1184     char locked_message_buf[BUFLEN];
1185     Flag::MsgType msg_type = found_flag->get_locked_message(locked_message_buf, BUFLEN);
1186     if (strlen(locked_message_buf) == 0) {
1187       if (found_flag->is_bool() && !has_plus_minus) {
1188         jio_fprintf(defaultStream::error_stream(),
1189           "Missing +/- setting for VM option '%s'\n", argname);
1190       } else if (!found_flag->is_bool() && has_plus_minus) {
1191         jio_fprintf(defaultStream::error_stream(),
1192           "Unexpected +/- setting in VM option '%s'\n", argname);
1193       } else {
1194         jio_fprintf(defaultStream::error_stream(),
1195           "Improperly specified VM option '%s'\n", argname);
1196       }
1197     } else {
1198 #ifdef PRODUCT
1199       bool mismatched = ((msg_type == Flag::NOTPRODUCT_FLAG_BUT_PRODUCT_BUILD) ||
1200                          (msg_type == Flag::DEVELOPER_FLAG_BUT_PRODUCT_BUILD));
1201       if (ignore_unrecognized && mismatched) {
1202         return true;
1203       }
1204 #endif
1205       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
1206     }
1207   } else {
1208     if (ignore_unrecognized) {
1209       return true;
1210     }
1211     jio_fprintf(defaultStream::error_stream(),
1212                 "Unrecognized VM option '%s'\n", argname);
1213     Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
1214     if (fuzzy_matched != NULL) {
1215       jio_fprintf(defaultStream::error_stream(),
1216                   "Did you mean '%s%s%s'? ",
1217                   (fuzzy_matched->is_bool()) ? "(+/-)" : "",
1218                   fuzzy_matched->_name,
1219                   (fuzzy_matched->is_bool()) ? "" : "=<value>");
1220     }
1221   }
1222 
1223   // allow for commandline "commenting out" options like -XX:#+Verbose
1224   return arg[0] == '#';
1225 }
1226 
1227 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
1228   FILE* stream = fopen(file_name, "rb");
1229   if (stream == NULL) {
1230     if (should_exist) {
1231       jio_fprintf(defaultStream::error_stream(),
1232                   "Could not open settings file %s\n", file_name);
1233       return false;
1234     } else {
1235       return true;
1236     }
1237   }
1238 
1239   char token[1024];
1240   int  pos = 0;
1241 
1242   bool in_white_space = true;
1243   bool in_comment     = false;
1244   bool in_quote       = false;
1245   char quote_c        = 0;
1246   bool result         = true;
1247 
1248   int c = getc(stream);
1249   while(c != EOF && pos < (int)(sizeof(token)-1)) {
1250     if (in_white_space) {
1251       if (in_comment) {
1252         if (c == '\n') in_comment = false;
1253       } else {
1254         if (c == '#') in_comment = true;
1255         else if (!isspace(c)) {
1256           in_white_space = false;
1257           token[pos++] = c;
1258         }
1259       }
1260     } else {
1261       if (c == '\n' || (!in_quote && isspace(c))) {
1262         // token ends at newline, or at unquoted whitespace
1263         // this allows a way to include spaces in string-valued options
1264         token[pos] = '\0';
1265         logOption(token);
1266         result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
1267         build_jvm_flags(token);
1268         pos = 0;
1269         in_white_space = true;
1270         in_quote = false;
1271       } else if (!in_quote && (c == '\'' || c == '"')) {
1272         in_quote = true;
1273         quote_c = c;
1274       } else if (in_quote && (c == quote_c)) {
1275         in_quote = false;
1276       } else {
1277         token[pos++] = c;
1278       }
1279     }
1280     c = getc(stream);
1281   }
1282   if (pos > 0) {
1283     token[pos] = '\0';
1284     result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
1285     build_jvm_flags(token);
1286   }
1287   fclose(stream);
1288   return result;
1289 }
1290 
1291 //=============================================================================================================
1292 // Parsing of properties (-D)
1293 
1294 const char* Arguments::get_property(const char* key) {
1295   return PropertyList_get_value(system_properties(), key);
1296 }
1297 
1298 bool Arguments::add_property(const char* prop) {
1299   const char* eq = strchr(prop, '=');
1300   const char* key;
1301   const char* value = "";
1302 
1303   if (eq == NULL) {
1304     // property doesn't have a value, thus use passed string
1305     key = prop;
1306   } else {
1307     // property have a value, thus extract it and save to the
1308     // allocated string
1309     size_t key_len = eq - prop;
1310     char* tmp_key = AllocateHeap(key_len + 1, mtInternal);
1311 
1312     strncpy(tmp_key, prop, key_len);
1313     tmp_key[key_len] = '\0';
1314     key = tmp_key;
1315 
1316     value = &prop[key_len + 1];
1317   }
1318 
1319   if (strcmp(key, "java.compiler") == 0) {
1320     process_java_compiler_argument(value);
1321     // Record value in Arguments, but let it get passed to Java.
1322   } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0 ||
1323              strcmp(key, "sun.java.launcher.pid") == 0) {
1324     // sun.java.launcher.is_altjvm and sun.java.launcher.pid property are
1325     // private and are processed in process_sun_java_launcher_properties();
1326     // the sun.java.launcher property is passed on to the java application
1327   } else if (strcmp(key, "sun.boot.library.path") == 0) {
1328     PropertyList_unique_add(&_system_properties, key, value, true);
1329   } else {
1330     if (strcmp(key, "sun.java.command") == 0) {
1331       char *old_java_command = _java_command;
1332       _java_command = os::strdup_check_oom(value, mtInternal);
1333       if (old_java_command != NULL) {
1334         os::free(old_java_command);
1335       }
1336     } else if (strcmp(key, "java.vendor.url.bug") == 0) {
1337       const char* old_java_vendor_url_bug = _java_vendor_url_bug;
1338       // save it in _java_vendor_url_bug, so JVM fatal error handler can access
1339       // its value without going through the property list or making a Java call.
1340       _java_vendor_url_bug = os::strdup_check_oom(value, mtInternal);
1341       if (old_java_vendor_url_bug != DEFAULT_VENDOR_URL_BUG) {
1342         assert(old_java_vendor_url_bug != NULL, "_java_vendor_url_bug is NULL");
1343         os::free((void *)old_java_vendor_url_bug);
1344       }
1345     }
1346 
1347     // Create new property and add at the end of the list
1348     PropertyList_unique_add(&_system_properties, key, value);
1349   }
1350 
1351   if (key != prop) {
1352     // SystemProperty copy passed value, thus free previously allocated
1353     // memory
1354     FreeHeap((void *)key);
1355   }
1356 
1357   return true;
1358 }
1359 
1360 //===========================================================================================================
1361 // Setting int/mixed/comp mode flags
1362 
1363 void Arguments::set_mode_flags(Mode mode) {
1364   // Set up default values for all flags.
1365   // If you add a flag to any of the branches below,
1366   // add a default value for it here.
1367   set_java_compiler(false);
1368   _mode                      = mode;
1369 
1370   // Ensure Agent_OnLoad has the correct initial values.
1371   // This may not be the final mode; mode may change later in onload phase.
1372   PropertyList_unique_add(&_system_properties, "java.vm.info",
1373                           VM_Version::vm_info_string(), false);
1374 
1375   UseInterpreter             = true;
1376   UseCompiler                = true;
1377   UseLoopCounter             = true;
1378 
1379   // Default values may be platform/compiler dependent -
1380   // use the saved values
1381   ClipInlining               = Arguments::_ClipInlining;
1382   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1383   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1384   BackgroundCompilation      = Arguments::_BackgroundCompilation;
1385   if (TieredCompilation) {
1386     if (FLAG_IS_DEFAULT(Tier3InvokeNotifyFreqLog)) {
1387       Tier3InvokeNotifyFreqLog = Arguments::_Tier3InvokeNotifyFreqLog;
1388     }
1389     if (FLAG_IS_DEFAULT(Tier4InvocationThreshold)) {
1390       Tier4InvocationThreshold = Arguments::_Tier4InvocationThreshold;
1391     }
1392   }
1393 
1394   // Change from defaults based on mode
1395   switch (mode) {
1396   default:
1397     ShouldNotReachHere();
1398     break;
1399   case _int:
1400     UseCompiler              = false;
1401     UseLoopCounter           = false;
1402     AlwaysCompileLoopMethods = false;
1403     UseOnStackReplacement    = false;
1404     break;
1405   case _mixed:
1406     // same as default
1407     break;
1408   case _comp:
1409     UseInterpreter           = false;
1410     BackgroundCompilation    = false;
1411     ClipInlining             = false;
1412     // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1413     // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1414     // compile a level 4 (C2) and then continue executing it.
1415     if (TieredCompilation) {
1416       Tier3InvokeNotifyFreqLog = 0;
1417       Tier4InvocationThreshold = 0;
1418     }
1419     break;
1420   }
1421 }
1422 
1423 #if defined(COMPILER2) || INCLUDE_JVMCI || defined(_LP64) || !INCLUDE_CDS
1424 // Conflict: required to use shared spaces (-Xshare:on), but
1425 // incompatible command line options were chosen.
1426 
1427 static void no_shared_spaces(const char* message) {
1428   if (RequireSharedSpaces) {
1429     jio_fprintf(defaultStream::error_stream(),
1430       "Class data sharing is inconsistent with other specified options.\n");
1431     vm_exit_during_initialization("Unable to use shared archive.", message);
1432   } else {
1433     FLAG_SET_DEFAULT(UseSharedSpaces, false);
1434   }
1435 }
1436 #endif
1437 
1438 // Returns threshold scaled with the value of scale.
1439 // If scale < 0.0, threshold is returned without scaling.
1440 intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
1441   if (scale == 1.0 || scale < 0.0) {
1442     return threshold;
1443   } else {
1444     return (intx)(threshold * scale);
1445   }
1446 }
1447 
1448 // Returns freq_log scaled with the value of scale.
1449 // Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
1450 // If scale < 0.0, freq_log is returned without scaling.
1451 intx Arguments::scaled_freq_log(intx freq_log, double scale) {
1452   // Check if scaling is necessary or if negative value was specified.
1453   if (scale == 1.0 || scale < 0.0) {
1454     return freq_log;
1455   }
1456   // Check values to avoid calculating log2 of 0.
1457   if (scale == 0.0 || freq_log == 0) {
1458     return 0;
1459   }
1460   // Determine the maximum notification frequency value currently supported.
1461   // The largest mask value that the interpreter/C1 can handle is
1462   // of length InvocationCounter::number_of_count_bits. Mask values are always
1463   // one bit shorter then the value of the notification frequency. Set
1464   // max_freq_bits accordingly.
1465   intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
1466   intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
1467   if (scaled_freq == 0) {
1468     // Return 0 right away to avoid calculating log2 of 0.
1469     return 0;
1470   } else if (scaled_freq > nth_bit(max_freq_bits)) {
1471     return max_freq_bits;
1472   } else {
1473     return log2_intptr(scaled_freq);
1474   }
1475 }
1476 
1477 void Arguments::set_tiered_flags() {
1478   // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1479   if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1480     FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1481   }
1482   if (CompilationPolicyChoice < 2) {
1483     vm_exit_during_initialization(
1484       "Incompatible compilation policy selected", NULL);
1485   }
1486   // Increase the code cache size - tiered compiles a lot more.
1487   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1488     FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
1489                   MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1490   }
1491   // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
1492   if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
1493     FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
1494   }
1495   if (!UseInterpreter) { // -Xcomp
1496     Tier3InvokeNotifyFreqLog = 0;
1497     Tier4InvocationThreshold = 0;
1498   }
1499 
1500   if (CompileThresholdScaling < 0) {
1501     vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
1502   }
1503 
1504   // Scale tiered compilation thresholds.
1505   // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
1506   if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
1507     FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
1508     FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
1509 
1510     FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
1511     FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
1512     FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
1513     FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
1514 
1515     // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
1516     // once these thresholds become supported.
1517 
1518     FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
1519     FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
1520 
1521     FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
1522     FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
1523 
1524     FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
1525 
1526     FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
1527     FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
1528     FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
1529     FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
1530   }
1531 }
1532 
1533 #if INCLUDE_ALL_GCS
1534 static void disable_adaptive_size_policy(const char* collector_name) {
1535   if (UseAdaptiveSizePolicy) {
1536     if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
1537       warning("Disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
1538               collector_name);
1539     }
1540     FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
1541   }
1542 }
1543 
1544 void Arguments::set_parnew_gc_flags() {
1545   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
1546          "control point invariant");
1547   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1548   assert(UseParNewGC, "ParNew should always be used with CMS");
1549 
1550   if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
1551     FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1552     assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
1553   } else if (ParallelGCThreads == 0) {
1554     jio_fprintf(defaultStream::error_stream(),
1555         "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
1556     vm_exit(1);
1557   }
1558 
1559   // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
1560   // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
1561   // we set them to 1024 and 1024.
1562   // See CR 6362902.
1563   if (FLAG_IS_DEFAULT(YoungPLABSize)) {
1564     FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
1565   }
1566   if (FLAG_IS_DEFAULT(OldPLABSize)) {
1567     FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
1568   }
1569 
1570   // When using compressed oops, we use local overflow stacks,
1571   // rather than using a global overflow list chained through
1572   // the klass word of the object's pre-image.
1573   if (UseCompressedOops && !ParGCUseLocalOverflow) {
1574     if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
1575       warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
1576     }
1577     FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
1578   }
1579   assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
1580 }
1581 
1582 // Adjust some sizes to suit CMS and/or ParNew needs; these work well on
1583 // sparc/solaris for certain applications, but would gain from
1584 // further optimization and tuning efforts, and would almost
1585 // certainly gain from analysis of platform and environment.
1586 void Arguments::set_cms_and_parnew_gc_flags() {
1587   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
1588   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1589   assert(UseParNewGC, "ParNew should always be used with CMS");
1590 
1591   // Turn off AdaptiveSizePolicy by default for cms until it is complete.
1592   disable_adaptive_size_policy("UseConcMarkSweepGC");
1593 
1594   set_parnew_gc_flags();
1595 
1596   size_t max_heap = align_size_down(MaxHeapSize,
1597                                     CardTableRS::ct_max_alignment_constraint());
1598 
1599   // Now make adjustments for CMS
1600   intx   tenuring_default = (intx)6;
1601   size_t young_gen_per_worker = CMSYoungGenPerWorker;
1602 
1603   // Preferred young gen size for "short" pauses:
1604   // upper bound depends on # of threads and NewRatio.
1605   const size_t preferred_max_new_size_unaligned =
1606     MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * ParallelGCThreads));
1607   size_t preferred_max_new_size =
1608     align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
1609 
1610   // Unless explicitly requested otherwise, size young gen
1611   // for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
1612 
1613   // If either MaxNewSize or NewRatio is set on the command line,
1614   // assume the user is trying to set the size of the young gen.
1615   if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
1616 
1617     // Set MaxNewSize to our calculated preferred_max_new_size unless
1618     // NewSize was set on the command line and it is larger than
1619     // preferred_max_new_size.
1620     if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
1621       FLAG_SET_ERGO(size_t, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
1622     } else {
1623       FLAG_SET_ERGO(size_t, MaxNewSize, preferred_max_new_size);
1624     }
1625     log_trace(gc, heap)("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
1626 
1627     // Code along this path potentially sets NewSize and OldSize
1628     log_trace(gc, heap)("CMS set min_heap_size: " SIZE_FORMAT " initial_heap_size:  " SIZE_FORMAT " max_heap: " SIZE_FORMAT,
1629                         min_heap_size(), InitialHeapSize, max_heap);
1630     size_t min_new = preferred_max_new_size;
1631     if (FLAG_IS_CMDLINE(NewSize)) {
1632       min_new = NewSize;
1633     }
1634     if (max_heap > min_new && min_heap_size() > min_new) {
1635       // Unless explicitly requested otherwise, make young gen
1636       // at least min_new, and at most preferred_max_new_size.
1637       if (FLAG_IS_DEFAULT(NewSize)) {
1638         FLAG_SET_ERGO(size_t, NewSize, MAX2(NewSize, min_new));
1639         FLAG_SET_ERGO(size_t, NewSize, MIN2(preferred_max_new_size, NewSize));
1640         log_trace(gc, heap)("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
1641       }
1642       // Unless explicitly requested otherwise, size old gen
1643       // so it's NewRatio x of NewSize.
1644       if (FLAG_IS_DEFAULT(OldSize)) {
1645         if (max_heap > NewSize) {
1646           FLAG_SET_ERGO(size_t, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
1647           log_trace(gc, heap)("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
1648         }
1649       }
1650     }
1651   }
1652   // Unless explicitly requested otherwise, definitely
1653   // promote all objects surviving "tenuring_default" scavenges.
1654   if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
1655       FLAG_IS_DEFAULT(SurvivorRatio)) {
1656     FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
1657   }
1658   // If we decided above (or user explicitly requested)
1659   // `promote all' (via MaxTenuringThreshold := 0),
1660   // prefer minuscule survivor spaces so as not to waste
1661   // space for (non-existent) survivors
1662   if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
1663     FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
1664   }
1665 
1666   // OldPLABSize is interpreted in CMS as not the size of the PLAB in words,
1667   // but rather the number of free blocks of a given size that are used when
1668   // replenishing the local per-worker free list caches.
1669   if (FLAG_IS_DEFAULT(OldPLABSize)) {
1670     if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
1671       // OldPLAB sizing manually turned off: Use a larger default setting,
1672       // unless it was manually specified. This is because a too-low value
1673       // will slow down scavenges.
1674       FLAG_SET_ERGO(size_t, OldPLABSize, CFLS_LAB::_default_static_old_plab_size); // default value before 6631166
1675     } else {
1676       FLAG_SET_DEFAULT(OldPLABSize, CFLS_LAB::_default_dynamic_old_plab_size); // old CMSParPromoteBlocksToClaim default
1677     }
1678   }
1679 
1680   // If either of the static initialization defaults have changed, note this
1681   // modification.
1682   if (!FLAG_IS_DEFAULT(OldPLABSize) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
1683     CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
1684   }
1685 
1686   if (!ClassUnloading) {
1687     FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
1688     FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
1689   }
1690 
1691   log_trace(gc)("MarkStackSize: %uk  MarkStackSizeMax: %uk", (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1692   log_trace(gc)("ConcGCThreads: %u", ConcGCThreads);
1693 }
1694 #endif // INCLUDE_ALL_GCS
1695 
1696 void set_object_alignment() {
1697   // Object alignment.
1698   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1699   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1700   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1701   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1702   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1703   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1704 
1705   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1706   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1707 
1708   // Oop encoding heap max
1709   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1710 
1711   if (SurvivorAlignmentInBytes == 0) {
1712     SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1713   }
1714 
1715 #if INCLUDE_ALL_GCS
1716   // Set CMS global values
1717   CompactibleFreeListSpace::set_cms_values();
1718 #endif // INCLUDE_ALL_GCS
1719 }
1720 
1721 size_t Arguments::max_heap_for_compressed_oops() {
1722   // Avoid sign flip.
1723   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1724   // We need to fit both the NULL page and the heap into the memory budget, while
1725   // keeping alignment constraints of the heap. To guarantee the latter, as the
1726   // NULL page is located before the heap, we pad the NULL page to the conservative
1727   // maximum alignment that the GC may ever impose upon the heap.
1728   size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
1729                                                         _conservative_max_heap_alignment);
1730 
1731   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1732   NOT_LP64(ShouldNotReachHere(); return 0);
1733 }
1734 
1735 bool Arguments::should_auto_select_low_pause_collector() {
1736   if (UseAutoGCSelectPolicy &&
1737       !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
1738       (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
1739     log_trace(gc)("Automatic selection of the low pause collector based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
1740     return true;
1741   }
1742   return false;
1743 }
1744 
1745 void Arguments::set_use_compressed_oops() {
1746 #ifndef ZERO
1747 #ifdef _LP64
1748   // MaxHeapSize is not set up properly at this point, but
1749   // the only value that can override MaxHeapSize if we are
1750   // to use UseCompressedOops is InitialHeapSize.
1751   size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1752 
1753   if (max_heap_size <= max_heap_for_compressed_oops()) {
1754 #if !defined(COMPILER1) || defined(TIERED)
1755     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1756       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1757     }
1758 #endif
1759   } else {
1760     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1761       warning("Max heap size too large for Compressed Oops");
1762       FLAG_SET_DEFAULT(UseCompressedOops, false);
1763       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1764     }
1765   }
1766 #endif // _LP64
1767 #endif // ZERO
1768 }
1769 
1770 
1771 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1772 // set_use_compressed_oops().
1773 void Arguments::set_use_compressed_klass_ptrs() {
1774 #ifndef ZERO
1775 #ifdef _LP64
1776   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1777   if (!UseCompressedOops) {
1778     if (UseCompressedClassPointers) {
1779       warning("UseCompressedClassPointers requires UseCompressedOops");
1780     }
1781     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1782   } else {
1783     // Turn on UseCompressedClassPointers too
1784     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1785       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1786     }
1787     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1788     if (UseCompressedClassPointers) {
1789       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1790         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1791         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1792       }
1793     }
1794   }
1795 #endif // _LP64
1796 #endif // !ZERO
1797 }
1798 
1799 void Arguments::set_conservative_max_heap_alignment() {
1800   // The conservative maximum required alignment for the heap is the maximum of
1801   // the alignments imposed by several sources: any requirements from the heap
1802   // itself, the collector policy and the maximum page size we may run the VM
1803   // with.
1804   size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
1805 #if INCLUDE_ALL_GCS
1806   if (UseParallelGC) {
1807     heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
1808   } else if (UseG1GC) {
1809     heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
1810   }
1811 #endif // INCLUDE_ALL_GCS
1812   _conservative_max_heap_alignment = MAX4(heap_alignment,
1813                                           (size_t)os::vm_allocation_granularity(),
1814                                           os::max_page_size(),
1815                                           CollectorPolicy::compute_heap_alignment());
1816 }
1817 
1818 void Arguments::select_gc_ergonomically() {
1819   if (os::is_server_class_machine()) {
1820     if (should_auto_select_low_pause_collector()) {
1821       FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
1822     } else {
1823 #if defined(JAVASE_EMBEDDED)
1824       FLAG_SET_ERGO(bool, UseParallelGC, true);
1825 #else
1826       FLAG_SET_ERGO(bool, UseG1GC, true);
1827 #endif
1828     }
1829   } else {
1830     FLAG_SET_ERGO(bool, UseSerialGC, true);
1831   }
1832 }
1833 
1834 void Arguments::select_gc() {
1835   if (!gc_selected()) {
1836     select_gc_ergonomically();
1837     guarantee(gc_selected(), "No GC selected");
1838   }
1839 }
1840 
1841 void Arguments::set_ergonomics_flags() {
1842   select_gc();
1843 
1844 #if defined(COMPILER2) || INCLUDE_JVMCI
1845   // Shared spaces work fine with other GCs but causes bytecode rewriting
1846   // to be disabled, which hurts interpreter performance and decreases
1847   // server performance.  When -server is specified, keep the default off
1848   // unless it is asked for.  Future work: either add bytecode rewriting
1849   // at link time, or rewrite bytecodes in non-shared methods.
1850   if (!DumpSharedSpaces && !RequireSharedSpaces &&
1851       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1852     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1853   }
1854 #endif
1855 
1856   set_conservative_max_heap_alignment();
1857 
1858 #ifndef ZERO
1859 #ifdef _LP64
1860   set_use_compressed_oops();
1861 
1862   // set_use_compressed_klass_ptrs() must be called after calling
1863   // set_use_compressed_oops().
1864   set_use_compressed_klass_ptrs();
1865 
1866   // Also checks that certain machines are slower with compressed oops
1867   // in vm_version initialization code.
1868 #endif // _LP64
1869 #endif // !ZERO
1870 
1871   CodeCacheExtensions::set_ergonomics_flags();
1872 }
1873 
1874 void Arguments::set_parallel_gc_flags() {
1875   assert(UseParallelGC || UseParallelOldGC, "Error");
1876   // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1877   if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1878     FLAG_SET_DEFAULT(UseParallelOldGC, true);
1879   }
1880   FLAG_SET_DEFAULT(UseParallelGC, true);
1881 
1882   // If no heap maximum was requested explicitly, use some reasonable fraction
1883   // of the physical memory, up to a maximum of 1GB.
1884   FLAG_SET_DEFAULT(ParallelGCThreads,
1885                    Abstract_VM_Version::parallel_worker_threads());
1886   if (ParallelGCThreads == 0) {
1887     jio_fprintf(defaultStream::error_stream(),
1888         "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1889     vm_exit(1);
1890   }
1891 
1892   if (UseAdaptiveSizePolicy) {
1893     // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1894     // unless the user actually sets these flags.
1895     if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1896       FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1897     }
1898     if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1899       FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1900     }
1901   }
1902 
1903   // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1904   // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1905   // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1906   // See CR 6362902 for details.
1907   if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1908     if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1909        FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1910     }
1911     if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1912       FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1913     }
1914   }
1915 
1916   if (UseParallelOldGC) {
1917     // Par compact uses lower default values since they are treated as
1918     // minimums.  These are different defaults because of the different
1919     // interpretation and are not ergonomically set.
1920     if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1921       FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1922     }
1923   }
1924 }
1925 
1926 void Arguments::set_g1_gc_flags() {
1927   assert(UseG1GC, "Error");
1928 #if defined(COMPILER1) || INCLUDE_JVMCI
1929   FastTLABRefill = false;
1930 #endif
1931   FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1932   if (ParallelGCThreads == 0) {
1933     assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
1934     vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1935   }
1936 
1937 #if INCLUDE_ALL_GCS
1938   if (G1ConcRefinementThreads == 0) {
1939     FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);
1940   }
1941 #endif
1942 
1943   // MarkStackSize will be set (if it hasn't been set by the user)
1944   // when concurrent marking is initialized.
1945   // Its value will be based upon the number of parallel marking threads.
1946   // But we do set the maximum mark stack size here.
1947   if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1948     FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1949   }
1950 
1951   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1952     // In G1, we want the default GC overhead goal to be higher than
1953     // it is for PS, or the heap might be expanded too aggressively.
1954     // We set it here to ~8%.
1955     FLAG_SET_DEFAULT(GCTimeRatio, 12);
1956   }
1957 
1958   log_trace(gc)("MarkStackSize: %uk  MarkStackSizeMax: %uk", (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1959   log_trace(gc)("ConcGCThreads: %u", ConcGCThreads);
1960 }
1961 
1962 #if !INCLUDE_ALL_GCS
1963 #ifdef ASSERT
1964 static bool verify_serial_gc_flags() {
1965   return (UseSerialGC &&
1966         !(UseParNewGC || (UseConcMarkSweepGC) || UseG1GC ||
1967           UseParallelGC || UseParallelOldGC));
1968 }
1969 #endif // ASSERT
1970 #endif // INCLUDE_ALL_GCS
1971 
1972 void Arguments::set_gc_specific_flags() {
1973 #if INCLUDE_ALL_GCS
1974   // Set per-collector flags
1975   if (UseParallelGC || UseParallelOldGC) {
1976     set_parallel_gc_flags();
1977   } else if (UseConcMarkSweepGC) {
1978     set_cms_and_parnew_gc_flags();
1979   } else if (UseG1GC) {
1980     set_g1_gc_flags();
1981   }
1982   if (AssumeMP && !UseSerialGC) {
1983     if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
1984       warning("If the number of processors is expected to increase from one, then"
1985               " you should configure the number of parallel GC threads appropriately"
1986               " using -XX:ParallelGCThreads=N");
1987     }
1988   }
1989   if (MinHeapFreeRatio == 100) {
1990     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
1991     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
1992   }
1993 #else // INCLUDE_ALL_GCS
1994   assert(verify_serial_gc_flags(), "SerialGC unset");
1995 #endif // INCLUDE_ALL_GCS
1996 }
1997 
1998 julong Arguments::limit_by_allocatable_memory(julong limit) {
1999   julong max_allocatable;
2000   julong result = limit;
2001   if (os::has_allocatable_memory_limit(&max_allocatable)) {
2002     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
2003   }
2004   return result;
2005 }
2006 
2007 // Use static initialization to get the default before parsing
2008 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
2009 
2010 void Arguments::set_heap_size() {
2011   const julong phys_mem =
2012     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
2013                             : (julong)MaxRAM;
2014 
2015   // If the maximum heap size has not been set with -Xmx,
2016   // then set it as fraction of the size of physical memory,
2017   // respecting the maximum and minimum sizes of the heap.
2018   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2019     julong reasonable_max = phys_mem / MaxRAMFraction;
2020 
2021     if (phys_mem <= MaxHeapSize * MinRAMFraction) {
2022       // Small physical memory, so use a minimum fraction of it for the heap
2023       reasonable_max = phys_mem / MinRAMFraction;
2024     } else {
2025       // Not-small physical memory, so require a heap at least
2026       // as large as MaxHeapSize
2027       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
2028     }
2029     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
2030       // Limit the heap size to ErgoHeapSizeLimit
2031       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
2032     }
2033     if (UseCompressedOops) {
2034       // Limit the heap size to the maximum possible when using compressed oops
2035       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
2036 
2037       // HeapBaseMinAddress can be greater than default but not less than.
2038       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
2039         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
2040           // matches compressed oops printing flags
2041           if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
2042             jio_fprintf(defaultStream::error_stream(),
2043                         "HeapBaseMinAddress must be at least " SIZE_FORMAT
2044                         " (" SIZE_FORMAT "G) which is greater than value given "
2045                         SIZE_FORMAT "\n",
2046                         DefaultHeapBaseMinAddress,
2047                         DefaultHeapBaseMinAddress/G,
2048                         HeapBaseMinAddress);
2049           }
2050           FLAG_SET_ERGO(size_t, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
2051         }
2052       }
2053 
2054       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
2055         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
2056         // but it should be not less than default MaxHeapSize.
2057         max_coop_heap -= HeapBaseMinAddress;
2058       }
2059       reasonable_max = MIN2(reasonable_max, max_coop_heap);
2060     }
2061     reasonable_max = limit_by_allocatable_memory(reasonable_max);
2062 
2063     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
2064       // An initial heap size was specified on the command line,
2065       // so be sure that the maximum size is consistent.  Done
2066       // after call to limit_by_allocatable_memory because that
2067       // method might reduce the allocation size.
2068       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
2069     }
2070 
2071     log_trace(gc, heap)("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
2072     FLAG_SET_ERGO(size_t, MaxHeapSize, (size_t)reasonable_max);
2073   }
2074 
2075   // If the minimum or initial heap_size have not been set or requested to be set
2076   // ergonomically, set them accordingly.
2077   if (InitialHeapSize == 0 || min_heap_size() == 0) {
2078     julong reasonable_minimum = (julong)(OldSize + NewSize);
2079 
2080     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
2081 
2082     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
2083 
2084     if (InitialHeapSize == 0) {
2085       julong reasonable_initial = phys_mem / InitialRAMFraction;
2086 
2087       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
2088       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
2089 
2090       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
2091 
2092       log_trace(gc, heap)("  Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
2093       FLAG_SET_ERGO(size_t, InitialHeapSize, (size_t)reasonable_initial);
2094     }
2095     // If the minimum heap size has not been set (via -Xms),
2096     // synchronize with InitialHeapSize to avoid errors with the default value.
2097     if (min_heap_size() == 0) {
2098       set_min_heap_size(MIN2((size_t)reasonable_minimum, InitialHeapSize));
2099       log_trace(gc, heap)("  Minimum heap size " SIZE_FORMAT, min_heap_size());
2100     }
2101   }
2102 }
2103 
2104 // This option inspects the machine and attempts to set various
2105 // parameters to be optimal for long-running, memory allocation
2106 // intensive jobs.  It is intended for machines with large
2107 // amounts of cpu and memory.
2108 jint Arguments::set_aggressive_heap_flags() {
2109   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
2110   // VM, but we may not be able to represent the total physical memory
2111   // available (like having 8gb of memory on a box but using a 32bit VM).
2112   // Thus, we need to make sure we're using a julong for intermediate
2113   // calculations.
2114   julong initHeapSize;
2115   julong total_memory = os::physical_memory();
2116 
2117   if (total_memory < (julong) 256 * M) {
2118     jio_fprintf(defaultStream::error_stream(),
2119             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
2120     vm_exit(1);
2121   }
2122 
2123   // The heap size is half of available memory, or (at most)
2124   // all of possible memory less 160mb (leaving room for the OS
2125   // when using ISM).  This is the maximum; because adaptive sizing
2126   // is turned on below, the actual space used may be smaller.
2127 
2128   initHeapSize = MIN2(total_memory / (julong) 2,
2129           total_memory - (julong) 160 * M);
2130 
2131   initHeapSize = limit_by_allocatable_memory(initHeapSize);
2132 
2133   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2134     if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, initHeapSize) != Flag::SUCCESS) {
2135       return JNI_EINVAL;
2136     }
2137     if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, initHeapSize) != Flag::SUCCESS) {
2138       return JNI_EINVAL;
2139     }
2140     // Currently the minimum size and the initial heap sizes are the same.
2141     set_min_heap_size(initHeapSize);
2142   }
2143   if (FLAG_IS_DEFAULT(NewSize)) {
2144     // Make the young generation 3/8ths of the total heap.
2145     if (FLAG_SET_CMDLINE(size_t, NewSize,
2146             ((julong) MaxHeapSize / (julong) 8) * (julong) 3) != Flag::SUCCESS) {
2147       return JNI_EINVAL;
2148     }
2149     if (FLAG_SET_CMDLINE(size_t, MaxNewSize, NewSize) != Flag::SUCCESS) {
2150       return JNI_EINVAL;
2151     }
2152   }
2153 
2154 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
2155   FLAG_SET_DEFAULT(UseLargePages, true);
2156 #endif
2157 
2158   // Increase some data structure sizes for efficiency
2159   if (FLAG_SET_CMDLINE(size_t, BaseFootPrintEstimate, MaxHeapSize) != Flag::SUCCESS) {
2160     return JNI_EINVAL;
2161   }
2162   if (FLAG_SET_CMDLINE(bool, ResizeTLAB, false) != Flag::SUCCESS) {
2163     return JNI_EINVAL;
2164   }
2165   if (FLAG_SET_CMDLINE(size_t, TLABSize, 256 * K) != Flag::SUCCESS) {
2166     return JNI_EINVAL;
2167   }
2168 
2169   // See the OldPLABSize comment below, but replace 'after promotion'
2170   // with 'after copying'.  YoungPLABSize is the size of the survivor
2171   // space per-gc-thread buffers.  The default is 4kw.
2172   if (FLAG_SET_CMDLINE(size_t, YoungPLABSize, 256 * K) != Flag::SUCCESS) { // Note: this is in words
2173     return JNI_EINVAL;
2174   }
2175 
2176   // OldPLABSize is the size of the buffers in the old gen that
2177   // UseParallelGC uses to promote live data that doesn't fit in the
2178   // survivor spaces.  At any given time, there's one for each gc thread.
2179   // The default size is 1kw. These buffers are rarely used, since the
2180   // survivor spaces are usually big enough.  For specjbb, however, there
2181   // are occasions when there's lots of live data in the young gen
2182   // and we end up promoting some of it.  We don't have a definite
2183   // explanation for why bumping OldPLABSize helps, but the theory
2184   // is that a bigger PLAB results in retaining something like the
2185   // original allocation order after promotion, which improves mutator
2186   // locality.  A minor effect may be that larger PLABs reduce the
2187   // number of PLAB allocation events during gc.  The value of 8kw
2188   // was arrived at by experimenting with specjbb.
2189   if (FLAG_SET_CMDLINE(size_t, OldPLABSize, 8 * K) != Flag::SUCCESS) { // Note: this is in words
2190     return JNI_EINVAL;
2191   }
2192 
2193   // Enable parallel GC and adaptive generation sizing
2194   if (FLAG_SET_CMDLINE(bool, UseParallelGC, true) != Flag::SUCCESS) {
2195     return JNI_EINVAL;
2196   }
2197   FLAG_SET_DEFAULT(ParallelGCThreads,
2198           Abstract_VM_Version::parallel_worker_threads());
2199 
2200   // Encourage steady state memory management
2201   if (FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100) != Flag::SUCCESS) {
2202     return JNI_EINVAL;
2203   }
2204 
2205   // This appears to improve mutator locality
2206   if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2207     return JNI_EINVAL;
2208   }
2209 
2210   // Get around early Solaris scheduling bug
2211   // (affinity vs other jobs on system)
2212   // but disallow DR and offlining (5008695).
2213   if (FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true) != Flag::SUCCESS) {
2214     return JNI_EINVAL;
2215   }
2216 
2217   return JNI_OK;
2218 }
2219 
2220 // This must be called after ergonomics.
2221 void Arguments::set_bytecode_flags() {
2222   if (!RewriteBytecodes) {
2223     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
2224   }
2225 }
2226 
2227 // Aggressive optimization flags  -XX:+AggressiveOpts
2228 jint Arguments::set_aggressive_opts_flags() {
2229 #ifdef COMPILER2
2230   if (AggressiveUnboxing) {
2231     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2232       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2233     } else if (!EliminateAutoBox) {
2234       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
2235       AggressiveUnboxing = false;
2236     }
2237     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
2238       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
2239     } else if (!DoEscapeAnalysis) {
2240       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
2241       AggressiveUnboxing = false;
2242     }
2243   }
2244   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2245     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2246       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2247     }
2248     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2249       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
2250     }
2251 
2252     // Feed the cache size setting into the JDK
2253     char buffer[1024];
2254     sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
2255     if (!add_property(buffer)) {
2256       return JNI_ENOMEM;
2257     }
2258   }
2259   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
2260     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
2261   }
2262 #endif
2263 
2264   if (AggressiveOpts) {
2265 // Sample flag setting code
2266 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
2267 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
2268 //    }
2269   }
2270 
2271   return JNI_OK;
2272 }
2273 
2274 //===========================================================================================================
2275 // Parsing of java.compiler property
2276 
2277 void Arguments::process_java_compiler_argument(const char* arg) {
2278   // For backwards compatibility, Djava.compiler=NONE or ""
2279   // causes us to switch to -Xint mode UNLESS -Xdebug
2280   // is also specified.
2281   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
2282     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
2283   }
2284 }
2285 
2286 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
2287   _sun_java_launcher = os::strdup_check_oom(launcher);
2288 }
2289 
2290 bool Arguments::created_by_java_launcher() {
2291   assert(_sun_java_launcher != NULL, "property must have value");
2292   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
2293 }
2294 
2295 bool Arguments::sun_java_launcher_is_altjvm() {
2296   return _sun_java_launcher_is_altjvm;
2297 }
2298 
2299 //===========================================================================================================
2300 // Parsing of main arguments
2301 
2302 // Check consistency of GC selection
2303 bool Arguments::check_gc_consistency() {
2304   // Ensure that the user has not selected conflicting sets
2305   // of collectors.
2306   uint i = 0;
2307   if (UseSerialGC)                       i++;
2308   if (UseConcMarkSweepGC)                i++;
2309   if (UseParallelGC || UseParallelOldGC) i++;
2310   if (UseG1GC)                           i++;
2311   if (i > 1) {
2312     jio_fprintf(defaultStream::error_stream(),
2313                 "Conflicting collector combinations in option list; "
2314                 "please refer to the release notes for the combinations "
2315                 "allowed\n");
2316     return false;
2317   }
2318 
2319   if (UseConcMarkSweepGC && !UseParNewGC) {
2320     jio_fprintf(defaultStream::error_stream(),
2321         "It is not possible to combine the DefNew young collector with the CMS collector.\n");
2322     return false;
2323   }
2324 
2325   if (UseParNewGC && !UseConcMarkSweepGC) {
2326     jio_fprintf(defaultStream::error_stream(),
2327         "It is not possible to combine the ParNew young collector with any collector other than CMS.\n");
2328     return false;
2329   }
2330 
2331   return true;
2332 }
2333 
2334 // Check the consistency of vm_init_args
2335 bool Arguments::check_vm_args_consistency() {
2336   // Method for adding checks for flag consistency.
2337   // The intent is to warn the user of all possible conflicts,
2338   // before returning an error.
2339   // Note: Needs platform-dependent factoring.
2340   bool status = true;
2341 
2342   if (TLABRefillWasteFraction == 0) {
2343     jio_fprintf(defaultStream::error_stream(),
2344                 "TLABRefillWasteFraction should be a denominator, "
2345                 "not " SIZE_FORMAT "\n",
2346                 TLABRefillWasteFraction);
2347     status = false;
2348   }
2349 
2350   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2351     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
2352   }
2353 
2354   if (!(UseParallelGC || UseParallelOldGC) && FLAG_IS_DEFAULT(ScavengeBeforeFullGC)) {
2355     FLAG_SET_DEFAULT(ScavengeBeforeFullGC, false);
2356   }
2357 
2358   if (GCTimeLimit == 100) {
2359     // Turn off gc-overhead-limit-exceeded checks
2360     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2361   }
2362 
2363   status = status && check_gc_consistency();
2364 
2365   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2366   // insists that we hold the requisite locks so that the iteration is
2367   // MT-safe. For the verification at start-up and shut-down, we don't
2368   // yet have a good way of acquiring and releasing these locks,
2369   // which are not visible at the CollectedHeap level. We want to
2370   // be able to acquire these locks and then do the iteration rather
2371   // than just disable the lock verification. This will be fixed under
2372   // bug 4788986.
2373   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2374     if (VerifyDuringStartup) {
2375       warning("Heap verification at start-up disabled "
2376               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2377       VerifyDuringStartup = false; // Disable verification at start-up
2378     }
2379 
2380     if (VerifyBeforeExit) {
2381       warning("Heap verification at shutdown disabled "
2382               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2383       VerifyBeforeExit = false; // Disable verification at shutdown
2384     }
2385   }
2386 
2387   if (PrintNMTStatistics) {
2388 #if INCLUDE_NMT
2389     if (MemTracker::tracking_level() == NMT_off) {
2390 #endif // INCLUDE_NMT
2391       warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2392       PrintNMTStatistics = false;
2393 #if INCLUDE_NMT
2394     }
2395 #endif
2396   }
2397 #if INCLUDE_JVMCI
2398   if (EnableJVMCI) {
2399     if (!ScavengeRootsInCode) {
2400       warning("forcing ScavengeRootsInCode non-zero because JVMCI is enabled");
2401       ScavengeRootsInCode = 1;
2402     }
2403     if (FLAG_IS_DEFAULT(TypeProfileLevel)) {
2404       TypeProfileLevel = 0;
2405     }
2406     if (UseJVMCICompiler) {
2407       if (FLAG_IS_DEFAULT(TypeProfileWidth)) {
2408         TypeProfileWidth = 8;
2409       }
2410     }
2411   }
2412 #endif
2413 
2414   // Check lower bounds of the code cache
2415   // Template Interpreter code is approximately 3X larger in debug builds.
2416   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2417   if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2418     jio_fprintf(defaultStream::error_stream(),
2419                 "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
2420                 os::vm_page_size()/K);
2421     status = false;
2422   } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2423     jio_fprintf(defaultStream::error_stream(),
2424                 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2425                 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2426     status = false;
2427   } else if (ReservedCodeCacheSize < min_code_cache_size) {
2428     jio_fprintf(defaultStream::error_stream(),
2429                 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2430                 min_code_cache_size/K);
2431     status = false;
2432   } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2433     // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2434     jio_fprintf(defaultStream::error_stream(),
2435                 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2436                 CODE_CACHE_SIZE_LIMIT/M);
2437     status = false;
2438   } else if (NonNMethodCodeHeapSize < min_code_cache_size) {
2439     jio_fprintf(defaultStream::error_stream(),
2440                 "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2441                 min_code_cache_size/K);
2442     status = false;
2443   }
2444 
2445   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2446     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2447   }
2448 
2449 #ifndef SUPPORT_RESERVED_STACK_AREA
2450   if (StackReservedPages != 0) {
2451     FLAG_SET_CMDLINE(intx, StackReservedPages, 0);
2452     warning("Reserved Stack Area not supported on this platform");
2453   }
2454 #endif
2455   return status;
2456 }
2457 
2458 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2459   const char* option_type) {
2460   if (ignore) return false;
2461 
2462   const char* spacer = " ";
2463   if (option_type == NULL) {
2464     option_type = ++spacer; // Set both to the empty string.
2465   }
2466 
2467   if (os::obsolete_option(option)) {
2468     jio_fprintf(defaultStream::error_stream(),
2469                 "Obsolete %s%soption: %s\n", option_type, spacer,
2470       option->optionString);
2471     return false;
2472   } else {
2473     jio_fprintf(defaultStream::error_stream(),
2474                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2475       option->optionString);
2476     return true;
2477   }
2478 }
2479 
2480 static const char* user_assertion_options[] = {
2481   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2482 };
2483 
2484 static const char* system_assertion_options[] = {
2485   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2486 };
2487 
2488 bool Arguments::parse_uintx(const char* value,
2489                             uintx* uintx_arg,
2490                             uintx min_size) {
2491 
2492   // Check the sign first since atomull() parses only unsigned values.
2493   bool value_is_positive = !(*value == '-');
2494 
2495   if (value_is_positive) {
2496     julong n;
2497     bool good_return = atomull(value, &n);
2498     if (good_return) {
2499       bool above_minimum = n >= min_size;
2500       bool value_is_too_large = n > max_uintx;
2501 
2502       if (above_minimum && !value_is_too_large) {
2503         *uintx_arg = n;
2504         return true;
2505       }
2506     }
2507   }
2508   return false;
2509 }
2510 
2511 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2512                                                   julong* long_arg,
2513                                                   julong min_size) {
2514   if (!atomull(s, long_arg)) return arg_unreadable;
2515   return check_memory_size(*long_arg, min_size);
2516 }
2517 
2518 // Parse JavaVMInitArgs structure
2519 
2520 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *java_tool_options_args,
2521                                    const JavaVMInitArgs *java_options_args,
2522                                    const JavaVMInitArgs *cmd_line_args) {
2523   // For components of the system classpath.
2524   SysClassPath scp(Arguments::get_sysclasspath());
2525   bool scp_assembly_required = false;
2526 
2527   // Save default settings for some mode flags
2528   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2529   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2530   Arguments::_ClipInlining             = ClipInlining;
2531   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2532   if (TieredCompilation) {
2533     Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2534     Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2535   }
2536 
2537   // Setup flags for mixed which is the default
2538   set_mode_flags(_mixed);
2539 
2540   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2541   // variable (if present).
2542   jint result = parse_each_vm_init_arg(
2543       java_tool_options_args, &scp, &scp_assembly_required, Flag::ENVIRON_VAR);
2544   if (result != JNI_OK) {
2545     return result;
2546   }
2547 
2548   // Parse args structure generated from the command line flags.
2549   result = parse_each_vm_init_arg(cmd_line_args, &scp, &scp_assembly_required,
2550                                   Flag::COMMAND_LINE);
2551   if (result != JNI_OK) {
2552     return result;
2553   }
2554 
2555   // Parse args structure generated from the _JAVA_OPTIONS environment
2556   // variable (if present) (mimics classic VM)
2557   result = parse_each_vm_init_arg(
2558       java_options_args, &scp, &scp_assembly_required, Flag::ENVIRON_VAR);
2559   if (result != JNI_OK) {
2560     return result;
2561   }
2562 
2563   // Do final processing now that all arguments have been parsed
2564   result = finalize_vm_init_args(&scp, scp_assembly_required);
2565   if (result != JNI_OK) {
2566     return result;
2567   }
2568 
2569   return JNI_OK;
2570 }
2571 
2572 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2573 // represents a valid JDWP agent.  is_path==true denotes that we
2574 // are dealing with -agentpath (case where name is a path), otherwise with
2575 // -agentlib
2576 bool valid_jdwp_agent(char *name, bool is_path) {
2577   char *_name;
2578   const char *_jdwp = "jdwp";
2579   size_t _len_jdwp, _len_prefix;
2580 
2581   if (is_path) {
2582     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2583       return false;
2584     }
2585 
2586     _name++;  // skip past last path separator
2587     _len_prefix = strlen(JNI_LIB_PREFIX);
2588 
2589     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2590       return false;
2591     }
2592 
2593     _name += _len_prefix;
2594     _len_jdwp = strlen(_jdwp);
2595 
2596     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2597       _name += _len_jdwp;
2598     }
2599     else {
2600       return false;
2601     }
2602 
2603     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2604       return false;
2605     }
2606 
2607     return true;
2608   }
2609 
2610   if (strcmp(name, _jdwp) == 0) {
2611     return true;
2612   }
2613 
2614   return false;
2615 }
2616 
2617 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2618                                        SysClassPath* scp_p,
2619                                        bool* scp_assembly_required_p,
2620                                        Flag::Flags origin) {
2621   // Remaining part of option string
2622   const char* tail;
2623 
2624   // iterate over arguments
2625   for (int index = 0; index < args->nOptions; index++) {
2626     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2627 
2628     JavaVMOption* option = args->options + index;
2629 
2630     if (!match_option(option, "-Djava.class.path", &tail) &&
2631         !match_option(option, "-Dsun.java.command", &tail) &&
2632         !match_option(option, "-Dsun.java.launcher", &tail)) {
2633 
2634         // add all jvm options to the jvm_args string. This string
2635         // is used later to set the java.vm.args PerfData string constant.
2636         // the -Djava.class.path and the -Dsun.java.command options are
2637         // omitted from jvm_args string as each have their own PerfData
2638         // string constant object.
2639         build_jvm_args(option->optionString);
2640     }
2641 
2642     // char buffer to store looked up logging option.
2643     char aliased_logging_option[256];
2644 
2645     // Catch -XX options which are aliased to Unified logging commands.
2646     if (match_option(option, "-XX:", &tail)) {
2647       if (lookup_logging_aliases(option->optionString, aliased_logging_option)) {
2648         option->optionString = aliased_logging_option;
2649       }
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 }