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