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