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