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