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