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