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