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