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