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