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