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