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