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