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