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