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