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       FLAG_SET_ERGO(bool, UseParallelGC, true);
1539     }
1540   } else {
1541     FLAG_SET_ERGO(bool, UseSerialGC, true);
1542   }
1543 }
1544 
1545 void Arguments::select_gc() {
1546   if (!gc_selected()) {
1547     select_gc_ergonomically();
1548     guarantee(gc_selected(), "No GC selected");
1549   }
1550 }
1551 
1552 void Arguments::set_ergonomics_flags() {
1553   select_gc();
1554 
1555 #ifdef COMPILER2
1556   // Shared spaces work fine with other GCs but causes bytecode rewriting
1557   // to be disabled, which hurts interpreter performance and decreases
1558   // server performance.  When -server is specified, keep the default off
1559   // unless it is asked for.  Future work: either add bytecode rewriting
1560   // at link time, or rewrite bytecodes in non-shared methods.
1561   if (!DumpSharedSpaces && !RequireSharedSpaces &&
1562       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1563     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1564   }
1565 #endif
1566 
1567   set_conservative_max_heap_alignment();
1568 
1569 #ifndef ZERO
1570 #ifdef _LP64
1571   set_use_compressed_oops();
1572 
1573   // set_use_compressed_klass_ptrs() must be called after calling
1574   // set_use_compressed_oops().
1575   set_use_compressed_klass_ptrs();
1576 
1577   // Also checks that certain machines are slower with compressed oops
1578   // in vm_version initialization code.
1579 #endif // _LP64
1580 #endif // !ZERO
1581 }
1582 
1583 void Arguments::set_parallel_gc_flags() {
1584   assert(UseParallelGC || UseParallelOldGC, "Error");
1585   // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1586   if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1587     FLAG_SET_DEFAULT(UseParallelOldGC, true);
1588   }
1589   FLAG_SET_DEFAULT(UseParallelGC, true);
1590 
1591   // If no heap maximum was requested explicitly, use some reasonable fraction
1592   // of the physical memory, up to a maximum of 1GB.
1593   FLAG_SET_DEFAULT(ParallelGCThreads,
1594                    Abstract_VM_Version::parallel_worker_threads());
1595   if (ParallelGCThreads == 0) {
1596     jio_fprintf(defaultStream::error_stream(),
1597         "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1598     vm_exit(1);
1599   }
1600 
1601   if (UseAdaptiveSizePolicy) {
1602     // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1603     // unless the user actually sets these flags.
1604     if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1605       FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1606       _min_heap_free_ratio = MinHeapFreeRatio;
1607     }
1608     if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1609       FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1610       _max_heap_free_ratio = MaxHeapFreeRatio;
1611     }
1612   }
1613 
1614   // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1615   // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1616   // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1617   // See CR 6362902 for details.
1618   if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1619     if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1620        FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1621     }
1622     if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1623       FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1624     }
1625   }
1626 
1627   if (UseParallelOldGC) {
1628     // Par compact uses lower default values since they are treated as
1629     // minimums.  These are different defaults because of the different
1630     // interpretation and are not ergonomically set.
1631     if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1632       FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1633     }
1634   }
1635 }
1636 
1637 void Arguments::set_g1_gc_flags() {
1638   assert(UseG1GC, "Error");
1639 #ifdef COMPILER1
1640   FastTLABRefill = false;
1641 #endif
1642   FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1643   if (ParallelGCThreads == 0) {
1644     assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
1645     vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1646   }
1647 
1648 #if INCLUDE_ALL_GCS
1649   if (G1ConcRefinementThreads == 0) {
1650     FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);
1651   }
1652 #endif
1653 
1654   // MarkStackSize will be set (if it hasn't been set by the user)
1655   // when concurrent marking is initialized.
1656   // Its value will be based upon the number of parallel marking threads.
1657   // But we do set the maximum mark stack size here.
1658   if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1659     FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1660   }
1661 
1662   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1663     // In G1, we want the default GC overhead goal to be higher than
1664     // say in PS. So we set it here to 10%. Otherwise the heap might
1665     // be expanded more aggressively than we would like it to. In
1666     // fact, even 10% seems to not be high enough in some cases
1667     // (especially small GC stress tests that the main thing they do
1668     // is allocation). We might consider increase it further.
1669     FLAG_SET_DEFAULT(GCTimeRatio, 9);
1670   }
1671 
1672   if (PrintGCDetails && Verbose) {
1673     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1674       (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1675     tty->print_cr("ConcGCThreads: %u", ConcGCThreads);
1676   }
1677 }
1678 
1679 #if !INCLUDE_ALL_GCS
1680 #ifdef ASSERT
1681 static bool verify_serial_gc_flags() {
1682   return (UseSerialGC &&
1683         !(UseParNewGC || (UseConcMarkSweepGC) || UseG1GC ||
1684           UseParallelGC || UseParallelOldGC));
1685 }
1686 #endif // ASSERT
1687 #endif // INCLUDE_ALL_GCS
1688 
1689 void Arguments::set_gc_specific_flags() {
1690 #if INCLUDE_ALL_GCS
1691   // Set per-collector flags
1692   if (UseParallelGC || UseParallelOldGC) {
1693     set_parallel_gc_flags();
1694   } else if (UseConcMarkSweepGC) {
1695     set_cms_and_parnew_gc_flags();
1696   } else if (UseG1GC) {
1697     set_g1_gc_flags();
1698   }
1699   check_deprecated_gc_flags();
1700   if (AssumeMP && !UseSerialGC) {
1701     if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
1702       warning("If the number of processors is expected to increase from one, then"
1703               " you should configure the number of parallel GC threads appropriately"
1704               " using -XX:ParallelGCThreads=N");
1705     }
1706   }
1707   if (MinHeapFreeRatio == 100) {
1708     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
1709     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
1710   }
1711 #else // INCLUDE_ALL_GCS
1712   assert(verify_serial_gc_flags(), "SerialGC unset");
1713 #endif // INCLUDE_ALL_GCS
1714 }
1715 
1716 julong Arguments::limit_by_allocatable_memory(julong limit) {
1717   julong max_allocatable;
1718   julong result = limit;
1719   if (os::has_allocatable_memory_limit(&max_allocatable)) {
1720     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
1721   }
1722   return result;
1723 }
1724 
1725 // Use static initialization to get the default before parsing
1726 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1727 
1728 void Arguments::set_heap_size() {
1729   if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
1730     // Deprecated flag
1731     FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
1732   }
1733 
1734   const julong phys_mem =
1735     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1736                             : (julong)MaxRAM;
1737 
1738   // If the maximum heap size has not been set with -Xmx,
1739   // then set it as fraction of the size of physical memory,
1740   // respecting the maximum and minimum sizes of the heap.
1741   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1742     julong reasonable_max = phys_mem / MaxRAMFraction;
1743 
1744     if (phys_mem <= MaxHeapSize * MinRAMFraction) {
1745       // Small physical memory, so use a minimum fraction of it for the heap
1746       reasonable_max = phys_mem / MinRAMFraction;
1747     } else {
1748       // Not-small physical memory, so require a heap at least
1749       // as large as MaxHeapSize
1750       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1751     }
1752     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1753       // Limit the heap size to ErgoHeapSizeLimit
1754       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1755     }
1756     if (UseCompressedOops) {
1757       // Limit the heap size to the maximum possible when using compressed oops
1758       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1759 
1760       // HeapBaseMinAddress can be greater than default but not less than.
1761       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1762         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1763           // matches compressed oops printing flags
1764           if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
1765             jio_fprintf(defaultStream::error_stream(),
1766                         "HeapBaseMinAddress must be at least " SIZE_FORMAT
1767                         " (" SIZE_FORMAT "G) which is greater than value given "
1768                         SIZE_FORMAT "\n",
1769                         DefaultHeapBaseMinAddress,
1770                         DefaultHeapBaseMinAddress/G,
1771                         HeapBaseMinAddress);
1772           }
1773           FLAG_SET_ERGO(size_t, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1774         }
1775       }
1776 
1777       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1778         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1779         // but it should be not less than default MaxHeapSize.
1780         max_coop_heap -= HeapBaseMinAddress;
1781       }
1782       reasonable_max = MIN2(reasonable_max, max_coop_heap);
1783     }
1784     reasonable_max = limit_by_allocatable_memory(reasonable_max);
1785 
1786     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1787       // An initial heap size was specified on the command line,
1788       // so be sure that the maximum size is consistent.  Done
1789       // after call to limit_by_allocatable_memory because that
1790       // method might reduce the allocation size.
1791       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1792     }
1793 
1794     if (PrintGCDetails && Verbose) {
1795       // Cannot use gclog_or_tty yet.
1796       tty->print_cr("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1797     }
1798     FLAG_SET_ERGO(size_t, MaxHeapSize, (size_t)reasonable_max);
1799   }
1800 
1801   // If the minimum or initial heap_size have not been set or requested to be set
1802   // ergonomically, set them accordingly.
1803   if (InitialHeapSize == 0 || min_heap_size() == 0) {
1804     julong reasonable_minimum = (julong)(OldSize + NewSize);
1805 
1806     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1807 
1808     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1809 
1810     if (InitialHeapSize == 0) {
1811       julong reasonable_initial = phys_mem / InitialRAMFraction;
1812 
1813       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
1814       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1815 
1816       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
1817 
1818       if (PrintGCDetails && Verbose) {
1819         // Cannot use gclog_or_tty yet.
1820         tty->print_cr("  Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
1821       }
1822       FLAG_SET_ERGO(size_t, InitialHeapSize, (size_t)reasonable_initial);
1823     }
1824     // If the minimum heap size has not been set (via -Xms),
1825     // synchronize with InitialHeapSize to avoid errors with the default value.
1826     if (min_heap_size() == 0) {
1827       set_min_heap_size(MIN2((size_t)reasonable_minimum, InitialHeapSize));
1828       if (PrintGCDetails && Verbose) {
1829         // Cannot use gclog_or_tty yet.
1830         tty->print_cr("  Minimum heap size " SIZE_FORMAT, min_heap_size());
1831       }
1832     }
1833   }
1834 }
1835 
1836 // This must be called after ergonomics.
1837 void Arguments::set_bytecode_flags() {
1838   if (!RewriteBytecodes) {
1839     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1840   }
1841 }
1842 
1843 // Aggressive optimization flags  -XX:+AggressiveOpts
1844 void Arguments::set_aggressive_opts_flags() {
1845 #ifdef COMPILER2
1846   if (AggressiveUnboxing) {
1847     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1848       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1849     } else if (!EliminateAutoBox) {
1850       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
1851       AggressiveUnboxing = false;
1852     }
1853     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1854       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1855     } else if (!DoEscapeAnalysis) {
1856       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
1857       AggressiveUnboxing = false;
1858     }
1859   }
1860   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1861     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1862       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1863     }
1864     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1865       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
1866     }
1867 
1868     // Feed the cache size setting into the JDK
1869     char buffer[1024];
1870     sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
1871     add_property(buffer);
1872   }
1873   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
1874     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
1875   }
1876 #endif
1877 
1878   if (AggressiveOpts) {
1879 // Sample flag setting code
1880 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
1881 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
1882 //    }
1883   }
1884 }
1885 
1886 //===========================================================================================================
1887 // Parsing of java.compiler property
1888 
1889 void Arguments::process_java_compiler_argument(char* arg) {
1890   // For backwards compatibility, Djava.compiler=NONE or ""
1891   // causes us to switch to -Xint mode UNLESS -Xdebug
1892   // is also specified.
1893   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
1894     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
1895   }
1896 }
1897 
1898 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1899   _sun_java_launcher = os::strdup_check_oom(launcher);
1900 }
1901 
1902 bool Arguments::created_by_java_launcher() {
1903   assert(_sun_java_launcher != NULL, "property must have value");
1904   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1905 }
1906 
1907 bool Arguments::sun_java_launcher_is_altjvm() {
1908   return _sun_java_launcher_is_altjvm;
1909 }
1910 
1911 //===========================================================================================================
1912 // Parsing of main arguments
1913 
1914 // check if do gclog rotation
1915 // +UseGCLogFileRotation is a must,
1916 // no gc log rotation when log file not supplied or
1917 // NumberOfGCLogFiles is 0
1918 void check_gclog_consistency() {
1919   if (UseGCLogFileRotation) {
1920     if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {
1921       jio_fprintf(defaultStream::output_stream(),
1922                   "To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"
1923                   "where num_of_file > 0\n"
1924                   "GC log rotation is turned off\n");
1925       UseGCLogFileRotation = false;
1926     }
1927   }
1928 
1929   if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {
1930     if (FLAG_SET_CMDLINE(size_t, GCLogFileSize, 8*K) == Flag::SUCCESS) {
1931       jio_fprintf(defaultStream::output_stream(),
1932                 "GCLogFileSize changed to minimum 8K\n");
1933     }
1934   }
1935 }
1936 
1937 // This function is called for -Xloggc:<filename>, it can be used
1938 // to check if a given file name(or string) conforms to the following
1939 // specification:
1940 // A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"
1941 // %p and %t only allowed once. We only limit usage of filename not path
1942 bool is_filename_valid(const char *file_name) {
1943   const char* p = file_name;
1944   char file_sep = os::file_separator()[0];
1945   const char* cp;
1946   // skip prefix path
1947   for (cp = file_name; *cp != '\0'; cp++) {
1948     if (*cp == '/' || *cp == file_sep) {
1949       p = cp + 1;
1950     }
1951   }
1952 
1953   int count_p = 0;
1954   int count_t = 0;
1955   while (*p != '\0') {
1956     if ((*p >= '0' && *p <= '9') ||
1957         (*p >= 'A' && *p <= 'Z') ||
1958         (*p >= 'a' && *p <= 'z') ||
1959          *p == '-'               ||
1960          *p == '_'               ||
1961          *p == '.') {
1962        p++;
1963        continue;
1964     }
1965     if (*p == '%') {
1966       if(*(p + 1) == 'p') {
1967         p += 2;
1968         count_p ++;
1969         continue;
1970       }
1971       if (*(p + 1) == 't') {
1972         p += 2;
1973         count_t ++;
1974         continue;
1975       }
1976     }
1977     return false;
1978   }
1979   return count_p < 2 && count_t < 2;
1980 }
1981 
1982 // Check consistency of GC selection
1983 bool Arguments::check_gc_consistency() {
1984   check_gclog_consistency();
1985   // Ensure that the user has not selected conflicting sets
1986   // of collectors.
1987   uint i = 0;
1988   if (UseSerialGC)                       i++;
1989   if (UseConcMarkSweepGC)                i++;
1990   if (UseParallelGC || UseParallelOldGC) i++;
1991   if (UseG1GC)                           i++;
1992   if (i > 1) {
1993     jio_fprintf(defaultStream::error_stream(),
1994                 "Conflicting collector combinations in option list; "
1995                 "please refer to the release notes for the combinations "
1996                 "allowed\n");
1997     return false;
1998   }
1999 
2000   if (UseConcMarkSweepGC && !UseParNewGC) {
2001     jio_fprintf(defaultStream::error_stream(),
2002         "It is not possible to combine the DefNew young collector with the CMS collector.\n");
2003     return false;
2004   }
2005 
2006   if (UseParNewGC && !UseConcMarkSweepGC) {
2007     jio_fprintf(defaultStream::error_stream(),
2008         "It is not possible to combine the ParNew young collector with any collector other than CMS.\n");
2009     return false;
2010   }
2011 
2012   return true;
2013 }
2014 
2015 void Arguments::check_deprecated_gc_flags() {
2016   if (FLAG_IS_CMDLINE(UseParNewGC)) {
2017     warning("The UseParNewGC flag is deprecated and will likely be removed in a future release");
2018   }
2019   if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {
2020     warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
2021             "and will likely be removed in future release");
2022   }
2023   if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {
2024     warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "
2025         "Use MaxRAMFraction instead.");
2026   }
2027 }
2028 
2029 // Check the consistency of vm_init_args
2030 bool Arguments::check_vm_args_consistency() {
2031   // Method for adding checks for flag consistency.
2032   // The intent is to warn the user of all possible conflicts,
2033   // before returning an error.
2034   // Note: Needs platform-dependent factoring.
2035   bool status = true;
2036 
2037   if (TLABRefillWasteFraction == 0) {
2038     jio_fprintf(defaultStream::error_stream(),
2039                 "TLABRefillWasteFraction should be a denominator, "
2040                 "not " SIZE_FORMAT "\n",
2041                 TLABRefillWasteFraction);
2042     status = false;
2043   }
2044 
2045   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2046     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
2047   }
2048 
2049   if (UseParallelOldGC && ParallelOldGCSplitALot) {
2050     // Settings to encourage splitting.
2051     if (!FLAG_IS_CMDLINE(NewRatio)) {
2052       if (FLAG_SET_CMDLINE(uintx, NewRatio, 2) != Flag::SUCCESS) {
2053         status = false;
2054       }
2055     }
2056     if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
2057       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2058         status = false;
2059       }
2060     }
2061   }
2062 
2063   if (!(UseParallelGC || UseParallelOldGC) && FLAG_IS_DEFAULT(ScavengeBeforeFullGC)) {
2064     FLAG_SET_DEFAULT(ScavengeBeforeFullGC, false);
2065   }
2066 
2067   if (GCTimeLimit == 100) {
2068     // Turn off gc-overhead-limit-exceeded checks
2069     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2070   }
2071 
2072   status = status && check_gc_consistency();
2073 
2074   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2075   // insists that we hold the requisite locks so that the iteration is
2076   // MT-safe. For the verification at start-up and shut-down, we don't
2077   // yet have a good way of acquiring and releasing these locks,
2078   // which are not visible at the CollectedHeap level. We want to
2079   // be able to acquire these locks and then do the iteration rather
2080   // than just disable the lock verification. This will be fixed under
2081   // bug 4788986.
2082   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2083     if (VerifyDuringStartup) {
2084       warning("Heap verification at start-up disabled "
2085               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2086       VerifyDuringStartup = false; // Disable verification at start-up
2087     }
2088 
2089     if (VerifyBeforeExit) {
2090       warning("Heap verification at shutdown disabled "
2091               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2092       VerifyBeforeExit = false; // Disable verification at shutdown
2093     }
2094   }
2095 
2096   // Note: only executed in non-PRODUCT mode
2097   if (!UseAsyncConcMarkSweepGC &&
2098       (ExplicitGCInvokesConcurrent ||
2099        ExplicitGCInvokesConcurrentAndUnloadsClasses)) {
2100     jio_fprintf(defaultStream::error_stream(),
2101                 "error: +ExplicitGCInvokesConcurrent[AndUnloadsClasses] conflicts"
2102                 " with -UseAsyncConcMarkSweepGC");
2103     status = false;
2104   }
2105 
2106   if (PrintNMTStatistics) {
2107 #if INCLUDE_NMT
2108     if (MemTracker::tracking_level() == NMT_off) {
2109 #endif // INCLUDE_NMT
2110       warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2111       PrintNMTStatistics = false;
2112 #if INCLUDE_NMT
2113     }
2114 #endif
2115   }
2116 
2117   // Check lower bounds of the code cache
2118   // Template Interpreter code is approximately 3X larger in debug builds.
2119   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2120   if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2121     jio_fprintf(defaultStream::error_stream(),
2122                 "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
2123                 os::vm_page_size()/K);
2124     status = false;
2125   } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2126     jio_fprintf(defaultStream::error_stream(),
2127                 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2128                 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2129     status = false;
2130   } else if (ReservedCodeCacheSize < min_code_cache_size) {
2131     jio_fprintf(defaultStream::error_stream(),
2132                 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2133                 min_code_cache_size/K);
2134     status = false;
2135   } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2136     // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2137     jio_fprintf(defaultStream::error_stream(),
2138                 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2139                 CODE_CACHE_SIZE_LIMIT/M);
2140     status = false;
2141   } else if (NonNMethodCodeHeapSize < min_code_cache_size){
2142     jio_fprintf(defaultStream::error_stream(),
2143                 "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2144                 min_code_cache_size/K);
2145     status = false;
2146   } else if ((!FLAG_IS_DEFAULT(NonNMethodCodeHeapSize) || !FLAG_IS_DEFAULT(ProfiledCodeHeapSize) || !FLAG_IS_DEFAULT(NonProfiledCodeHeapSize))
2147              && (NonNMethodCodeHeapSize + NonProfiledCodeHeapSize + ProfiledCodeHeapSize) != ReservedCodeCacheSize) {
2148     jio_fprintf(defaultStream::error_stream(),
2149                 "Invalid code heap sizes: NonNMethodCodeHeapSize(%dK) + ProfiledCodeHeapSize(%dK) + NonProfiledCodeHeapSize(%dK) = %dK. Must be equal to ReservedCodeCacheSize = %uK.\n",
2150                 NonNMethodCodeHeapSize/K, ProfiledCodeHeapSize/K, NonProfiledCodeHeapSize/K,
2151                 (NonNMethodCodeHeapSize + ProfiledCodeHeapSize + NonProfiledCodeHeapSize)/K, ReservedCodeCacheSize/K);
2152     status = false;
2153   }
2154 
2155   int min_number_of_compiler_threads = get_min_number_of_compiler_threads();
2156   // The default CICompilerCount's value is CI_COMPILER_COUNT.
2157   assert(min_number_of_compiler_threads <= CI_COMPILER_COUNT, "minimum should be less or equal default number");
2158 
2159   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2160     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2161   }
2162 
2163   return status;
2164 }
2165 
2166 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2167   const char* option_type) {
2168   if (ignore) return false;
2169 
2170   const char* spacer = " ";
2171   if (option_type == NULL) {
2172     option_type = ++spacer; // Set both to the empty string.
2173   }
2174 
2175   if (os::obsolete_option(option)) {
2176     jio_fprintf(defaultStream::error_stream(),
2177                 "Obsolete %s%soption: %s\n", option_type, spacer,
2178       option->optionString);
2179     return false;
2180   } else {
2181     jio_fprintf(defaultStream::error_stream(),
2182                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2183       option->optionString);
2184     return true;
2185   }
2186 }
2187 
2188 static const char* user_assertion_options[] = {
2189   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2190 };
2191 
2192 static const char* system_assertion_options[] = {
2193   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2194 };
2195 
2196 bool Arguments::parse_uintx(const char* value,
2197                             uintx* uintx_arg,
2198                             uintx min_size) {
2199 
2200   // Check the sign first since atomull() parses only unsigned values.
2201   bool value_is_positive = !(*value == '-');
2202 
2203   if (value_is_positive) {
2204     julong n;
2205     bool good_return = atomull(value, &n);
2206     if (good_return) {
2207       bool above_minimum = n >= min_size;
2208       bool value_is_too_large = n > max_uintx;
2209 
2210       if (above_minimum && !value_is_too_large) {
2211         *uintx_arg = n;
2212         return true;
2213       }
2214     }
2215   }
2216   return false;
2217 }
2218 
2219 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2220                                                   julong* long_arg,
2221                                                   julong min_size) {
2222   if (!atomull(s, long_arg)) return arg_unreadable;
2223   return check_memory_size(*long_arg, min_size);
2224 }
2225 
2226 // Parse JavaVMInitArgs structure
2227 
2228 jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {
2229   // For components of the system classpath.
2230   SysClassPath scp(Arguments::get_sysclasspath());
2231   bool scp_assembly_required = false;
2232 
2233   // Save default settings for some mode flags
2234   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2235   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2236   Arguments::_ClipInlining             = ClipInlining;
2237   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2238   if (TieredCompilation) {
2239     Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2240     Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2241   }
2242 
2243   // Setup flags for mixed which is the default
2244   set_mode_flags(_mixed);
2245 
2246   // Parse JAVA_TOOL_OPTIONS environment variable (if present)
2247   jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);
2248   if (result != JNI_OK) {
2249     return result;
2250   }
2251 
2252   // Parse JavaVMInitArgs structure passed in
2253   result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, Flag::COMMAND_LINE);
2254   if (result != JNI_OK) {
2255     return result;
2256   }
2257 
2258   // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
2259   result = parse_java_options_environment_variable(&scp, &scp_assembly_required);
2260   if (result != JNI_OK) {
2261     return result;
2262   }
2263 
2264   // Do final processing now that all arguments have been parsed
2265   result = finalize_vm_init_args(&scp, scp_assembly_required);
2266   if (result != JNI_OK) {
2267     return result;
2268   }
2269 
2270   return JNI_OK;
2271 }
2272 
2273 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2274 // represents a valid HPROF of JDWP agent.  is_path==true denotes that we
2275 // are dealing with -agentpath (case where name is a path), otherwise with
2276 // -agentlib
2277 bool valid_hprof_or_jdwp_agent(char *name, bool is_path) {
2278   char *_name;
2279   const char *_hprof = "hprof", *_jdwp = "jdwp";
2280   size_t _len_hprof, _len_jdwp, _len_prefix;
2281 
2282   if (is_path) {
2283     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2284       return false;
2285     }
2286 
2287     _name++;  // skip past last path separator
2288     _len_prefix = strlen(JNI_LIB_PREFIX);
2289 
2290     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2291       return false;
2292     }
2293 
2294     _name += _len_prefix;
2295     _len_hprof = strlen(_hprof);
2296     _len_jdwp = strlen(_jdwp);
2297 
2298     if (strncmp(_name, _hprof, _len_hprof) == 0) {
2299       _name += _len_hprof;
2300     }
2301     else if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2302       _name += _len_jdwp;
2303     }
2304     else {
2305       return false;
2306     }
2307 
2308     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2309       return false;
2310     }
2311 
2312     return true;
2313   }
2314 
2315   if (strcmp(name, _hprof) == 0 || strcmp(name, _jdwp) == 0) {
2316     return true;
2317   }
2318 
2319   return false;
2320 }
2321 
2322 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2323                                        SysClassPath* scp_p,
2324                                        bool* scp_assembly_required_p,
2325                                        Flag::Flags origin) {
2326   // Remaining part of option string
2327   const char* tail;
2328 
2329   // iterate over arguments
2330   for (int index = 0; index < args->nOptions; index++) {
2331     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2332 
2333     const JavaVMOption* option = args->options + index;
2334 
2335     if (!match_option(option, "-Djava.class.path", &tail) &&
2336         !match_option(option, "-Dsun.java.command", &tail) &&
2337         !match_option(option, "-Dsun.java.launcher", &tail)) {
2338 
2339         // add all jvm options to the jvm_args string. This string
2340         // is used later to set the java.vm.args PerfData string constant.
2341         // the -Djava.class.path and the -Dsun.java.command options are
2342         // omitted from jvm_args string as each have their own PerfData
2343         // string constant object.
2344         build_jvm_args(option->optionString);
2345     }
2346 
2347     // -verbose:[class/gc/jni]
2348     if (match_option(option, "-verbose", &tail)) {
2349       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2350         if (FLAG_SET_CMDLINE(bool, TraceClassLoading, true) != Flag::SUCCESS) {
2351           return JNI_EINVAL;
2352         }
2353         if (FLAG_SET_CMDLINE(bool, TraceClassUnloading, true) != Flag::SUCCESS) {
2354           return JNI_EINVAL;
2355         }
2356       } else if (!strcmp(tail, ":gc")) {
2357         if (FLAG_SET_CMDLINE(bool, PrintGC, true) != Flag::SUCCESS) {
2358           return JNI_EINVAL;
2359         }
2360       } else if (!strcmp(tail, ":jni")) {
2361         if (FLAG_SET_CMDLINE(bool, PrintJNIResolving, true) != Flag::SUCCESS) {
2362           return JNI_EINVAL;
2363         }
2364       }
2365     // -da / -ea / -disableassertions / -enableassertions
2366     // These accept an optional class/package name separated by a colon, e.g.,
2367     // -da:java.lang.Thread.
2368     } else if (match_option(option, user_assertion_options, &tail, true)) {
2369       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2370       if (*tail == '\0') {
2371         JavaAssertions::setUserClassDefault(enable);
2372       } else {
2373         assert(*tail == ':', "bogus match by match_option()");
2374         JavaAssertions::addOption(tail + 1, enable);
2375       }
2376     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2377     } else if (match_option(option, system_assertion_options, &tail, false)) {
2378       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2379       JavaAssertions::setSystemClassDefault(enable);
2380     // -bootclasspath:
2381     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2382       scp_p->reset_path(tail);
2383       *scp_assembly_required_p = true;
2384     // -bootclasspath/a:
2385     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2386       scp_p->add_suffix(tail);
2387       *scp_assembly_required_p = true;
2388     // -bootclasspath/p:
2389     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2390       scp_p->add_prefix(tail);
2391       *scp_assembly_required_p = true;
2392     // -Xrun
2393     } else if (match_option(option, "-Xrun", &tail)) {
2394       if (tail != NULL) {
2395         const char* pos = strchr(tail, ':');
2396         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2397         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2398         name[len] = '\0';
2399 
2400         char *options = NULL;
2401         if(pos != NULL) {
2402           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2403           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
2404         }
2405 #if !INCLUDE_JVMTI
2406         if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
2407           jio_fprintf(defaultStream::error_stream(),
2408             "Profiling and debugging agents are not supported in this VM\n");
2409           return JNI_ERR;
2410         }
2411 #endif // !INCLUDE_JVMTI
2412         add_init_library(name, options);
2413       }
2414     // -agentlib and -agentpath
2415     } else if (match_option(option, "-agentlib:", &tail) ||
2416           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2417       if(tail != NULL) {
2418         const char* pos = strchr(tail, '=');
2419         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2420         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2421         name[len] = '\0';
2422 
2423         char *options = NULL;
2424         if(pos != NULL) {
2425           options = os::strdup_check_oom(pos + 1, mtInternal);
2426         }
2427 #if !INCLUDE_JVMTI
2428         if (valid_hprof_or_jdwp_agent(name, is_absolute_path)) {
2429           jio_fprintf(defaultStream::error_stream(),
2430             "Profiling and debugging agents are not supported in this VM\n");
2431           return JNI_ERR;
2432         }
2433 #endif // !INCLUDE_JVMTI
2434         add_init_agent(name, options, is_absolute_path);
2435       }
2436     // -javaagent
2437     } else if (match_option(option, "-javaagent:", &tail)) {
2438 #if !INCLUDE_JVMTI
2439       jio_fprintf(defaultStream::error_stream(),
2440         "Instrumentation agents are not supported in this VM\n");
2441       return JNI_ERR;
2442 #else
2443       if(tail != NULL) {
2444         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtInternal), tail);
2445         add_init_agent("instrument", options, false);
2446       }
2447 #endif // !INCLUDE_JVMTI
2448     // -Xnoclassgc
2449     } else if (match_option(option, "-Xnoclassgc")) {
2450       if (FLAG_SET_CMDLINE(bool, ClassUnloading, false) != Flag::SUCCESS) {
2451         return JNI_EINVAL;
2452       }
2453     // -Xconcgc
2454     } else if (match_option(option, "-Xconcgc")) {
2455       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true) != Flag::SUCCESS) {
2456         return JNI_EINVAL;
2457       }
2458     // -Xnoconcgc
2459     } else if (match_option(option, "-Xnoconcgc")) {
2460       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false) != Flag::SUCCESS) {
2461         return JNI_EINVAL;
2462       }
2463     // -Xbatch
2464     } else if (match_option(option, "-Xbatch")) {
2465       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2466         return JNI_EINVAL;
2467       }
2468     // -Xmn for compatibility with other JVM vendors
2469     } else if (match_option(option, "-Xmn", &tail)) {
2470       julong long_initial_young_size = 0;
2471       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2472       if (errcode != arg_in_range) {
2473         jio_fprintf(defaultStream::error_stream(),
2474                     "Invalid initial young generation size: %s\n", option->optionString);
2475         describe_range_error(errcode);
2476         return JNI_EINVAL;
2477       }
2478       if (FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2479         return JNI_EINVAL;
2480       }
2481       if (FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2482         return JNI_EINVAL;
2483       }
2484     // -Xms
2485     } else if (match_option(option, "-Xms", &tail)) {
2486       julong long_initial_heap_size = 0;
2487       // an initial heap size of 0 means automatically determine
2488       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2489       if (errcode != arg_in_range) {
2490         jio_fprintf(defaultStream::error_stream(),
2491                     "Invalid initial heap size: %s\n", option->optionString);
2492         describe_range_error(errcode);
2493         return JNI_EINVAL;
2494       }
2495       set_min_heap_size((size_t)long_initial_heap_size);
2496       // Currently the minimum size and the initial heap sizes are the same.
2497       // Can be overridden with -XX:InitialHeapSize.
2498       if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size) != Flag::SUCCESS) {
2499         return JNI_EINVAL;
2500       }
2501     // -Xmx
2502     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2503       julong long_max_heap_size = 0;
2504       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2505       if (errcode != arg_in_range) {
2506         jio_fprintf(defaultStream::error_stream(),
2507                     "Invalid maximum heap size: %s\n", option->optionString);
2508         describe_range_error(errcode);
2509         return JNI_EINVAL;
2510       }
2511       if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size) != Flag::SUCCESS) {
2512         return JNI_EINVAL;
2513       }
2514     // Xmaxf
2515     } else if (match_option(option, "-Xmaxf", &tail)) {
2516       char* err;
2517       int maxf = (int)(strtod(tail, &err) * 100);
2518       if (*err != '\0' || *tail == '\0') {
2519         jio_fprintf(defaultStream::error_stream(),
2520                     "Bad max heap free percentage size: %s\n",
2521                     option->optionString);
2522         return JNI_EINVAL;
2523       } else {
2524         if (FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf) != Flag::SUCCESS) {
2525             return JNI_EINVAL;
2526         }
2527       }
2528     // Xminf
2529     } else if (match_option(option, "-Xminf", &tail)) {
2530       char* err;
2531       int minf = (int)(strtod(tail, &err) * 100);
2532       if (*err != '\0' || *tail == '\0') {
2533         jio_fprintf(defaultStream::error_stream(),
2534                     "Bad min heap free percentage size: %s\n",
2535                     option->optionString);
2536         return JNI_EINVAL;
2537       } else {
2538         if (FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf) != Flag::SUCCESS) {
2539           return JNI_EINVAL;
2540         }
2541       }
2542     // -Xss
2543     } else if (match_option(option, "-Xss", &tail)) {
2544       julong long_ThreadStackSize = 0;
2545       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2546       if (errcode != arg_in_range) {
2547         jio_fprintf(defaultStream::error_stream(),
2548                     "Invalid thread stack size: %s\n", option->optionString);
2549         describe_range_error(errcode);
2550         return JNI_EINVAL;
2551       }
2552       // Internally track ThreadStackSize in units of 1024 bytes.
2553       if (FLAG_SET_CMDLINE(intx, ThreadStackSize,
2554                        round_to((int)long_ThreadStackSize, K) / K) != Flag::SUCCESS) {
2555         return JNI_EINVAL;
2556       }
2557     // -Xoss, -Xsqnopause, -Xoptimize, -Xboundthreads
2558     } else if (match_option(option, "-Xoss", &tail) ||
2559                match_option(option, "-Xsqnopause") ||
2560                match_option(option, "-Xoptimize") ||
2561                match_option(option, "-Xboundthreads")) {
2562       // All these options are deprecated in JDK 9 and will be removed in a future release
2563       warning("Option %s was deprecated in version 9.0 and will likely be removed in a future release.",
2564                       option->optionString);
2565     } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
2566       julong long_CodeCacheExpansionSize = 0;
2567       ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
2568       if (errcode != arg_in_range) {
2569         jio_fprintf(defaultStream::error_stream(),
2570                    "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
2571                    os::vm_page_size()/K);
2572         return JNI_EINVAL;
2573       }
2574       if (FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize) != Flag::SUCCESS) {
2575         return JNI_EINVAL;
2576       }
2577     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2578                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2579       julong long_ReservedCodeCacheSize = 0;
2580 
2581       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2582       if (errcode != arg_in_range) {
2583         jio_fprintf(defaultStream::error_stream(),
2584                     "Invalid maximum code cache size: %s.\n", option->optionString);
2585         return JNI_EINVAL;
2586       }
2587       if (FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != Flag::SUCCESS) {
2588         return JNI_EINVAL;
2589       }
2590       // -XX:NonNMethodCodeHeapSize=
2591     } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
2592       julong long_NonNMethodCodeHeapSize = 0;
2593 
2594       ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
2595       if (errcode != arg_in_range) {
2596         jio_fprintf(defaultStream::error_stream(),
2597                     "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
2598         return JNI_EINVAL;
2599       }
2600       if (FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize) != Flag::SUCCESS) {
2601         return JNI_EINVAL;
2602       }
2603       // -XX:ProfiledCodeHeapSize=
2604     } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
2605       julong long_ProfiledCodeHeapSize = 0;
2606 
2607       ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
2608       if (errcode != arg_in_range) {
2609         jio_fprintf(defaultStream::error_stream(),
2610                     "Invalid maximum profiled code heap size: %s.\n", option->optionString);
2611         return JNI_EINVAL;
2612       }
2613       if (FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize) != Flag::SUCCESS) {
2614         return JNI_EINVAL;
2615       }
2616       // -XX:NonProfiledCodeHeapSizee=
2617     } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
2618       julong long_NonProfiledCodeHeapSize = 0;
2619 
2620       ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
2621       if (errcode != arg_in_range) {
2622         jio_fprintf(defaultStream::error_stream(),
2623                     "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
2624         return JNI_EINVAL;
2625       }
2626       if (FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize) != Flag::SUCCESS) {
2627         return JNI_EINVAL;
2628       }
2629     // -green
2630     } else if (match_option(option, "-green")) {
2631       jio_fprintf(defaultStream::error_stream(),
2632                   "Green threads support not available\n");
2633           return JNI_EINVAL;
2634     // -native
2635     } else if (match_option(option, "-native")) {
2636           // HotSpot always uses native threads, ignore silently for compatibility
2637     // -Xrs
2638     } else if (match_option(option, "-Xrs")) {
2639           // Classic/EVM option, new functionality
2640       if (FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true) != Flag::SUCCESS) {
2641         return JNI_EINVAL;
2642       }
2643     } else if (match_option(option, "-Xusealtsigs")) {
2644           // change default internal VM signals used - lower case for back compat
2645       if (FLAG_SET_CMDLINE(bool, UseAltSigs, true) != Flag::SUCCESS) {
2646         return JNI_EINVAL;
2647       }
2648     // -Xprof
2649     } else if (match_option(option, "-Xprof")) {
2650 #if INCLUDE_FPROF
2651       _has_profile = true;
2652 #else // INCLUDE_FPROF
2653       jio_fprintf(defaultStream::error_stream(),
2654         "Flat profiling is not supported in this VM.\n");
2655       return JNI_ERR;
2656 #endif // INCLUDE_FPROF
2657     // -Xconcurrentio
2658     } else if (match_option(option, "-Xconcurrentio")) {
2659       if (FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true) != Flag::SUCCESS) {
2660         return JNI_EINVAL;
2661       }
2662       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2663         return JNI_EINVAL;
2664       }
2665       if (FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1) != Flag::SUCCESS) {
2666         return JNI_EINVAL;
2667       }
2668       if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
2669         return JNI_EINVAL;
2670       }
2671       if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
2672         return JNI_EINVAL;
2673       }
2674 
2675       // -Xinternalversion
2676     } else if (match_option(option, "-Xinternalversion")) {
2677       jio_fprintf(defaultStream::output_stream(), "%s\n",
2678                   VM_Version::internal_vm_info_string());
2679       vm_exit(0);
2680 #ifndef PRODUCT
2681     // -Xprintflags
2682     } else if (match_option(option, "-Xprintflags")) {
2683       CommandLineFlags::printFlags(tty, false);
2684       vm_exit(0);
2685 #endif
2686     // -D
2687     } else if (match_option(option, "-D", &tail)) {
2688       const char* value;
2689       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2690             *value!= '\0' && strcmp(value, "\"\"") != 0) {
2691         // abort if -Djava.endorsed.dirs is set
2692         jio_fprintf(defaultStream::output_stream(),
2693           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2694           "in modular form will be supported via the concept of upgradeable modules.\n", value);
2695         return JNI_EINVAL;
2696       }
2697       if (match_option(option, "-Djava.ext.dirs=", &value) &&
2698             *value != '\0' && strcmp(value, "\"\"") != 0) {
2699         // abort if -Djava.ext.dirs is set
2700         jio_fprintf(defaultStream::output_stream(),
2701           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2702         return JNI_EINVAL;
2703       }
2704 
2705       if (!add_property(tail)) {
2706         return JNI_ENOMEM;
2707       }
2708       // Out of the box management support
2709       if (match_option(option, "-Dcom.sun.management", &tail)) {
2710 #if INCLUDE_MANAGEMENT
2711         if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
2712           return JNI_EINVAL;
2713         }
2714 #else
2715         jio_fprintf(defaultStream::output_stream(),
2716           "-Dcom.sun.management is not supported in this VM.\n");
2717         return JNI_ERR;
2718 #endif
2719       }
2720     // -Xint
2721     } else if (match_option(option, "-Xint")) {
2722           set_mode_flags(_int);
2723     // -Xmixed
2724     } else if (match_option(option, "-Xmixed")) {
2725           set_mode_flags(_mixed);
2726     // -Xcomp
2727     } else if (match_option(option, "-Xcomp")) {
2728       // for testing the compiler; turn off all flags that inhibit compilation
2729           set_mode_flags(_comp);
2730     // -Xshare:dump
2731     } else if (match_option(option, "-Xshare:dump")) {
2732       if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
2733         return JNI_EINVAL;
2734       }
2735       set_mode_flags(_int);     // Prevent compilation, which creates objects
2736     // -Xshare:on
2737     } else if (match_option(option, "-Xshare:on")) {
2738       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
2739         return JNI_EINVAL;
2740       }
2741       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
2742         return JNI_EINVAL;
2743       }
2744     // -Xshare:auto
2745     } else if (match_option(option, "-Xshare:auto")) {
2746       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
2747         return JNI_EINVAL;
2748       }
2749       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
2750         return JNI_EINVAL;
2751       }
2752     // -Xshare:off
2753     } else if (match_option(option, "-Xshare:off")) {
2754       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
2755         return JNI_EINVAL;
2756       }
2757       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
2758         return JNI_EINVAL;
2759       }
2760     // -Xverify
2761     } else if (match_option(option, "-Xverify", &tail)) {
2762       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
2763         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
2764           return JNI_EINVAL;
2765         }
2766         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
2767           return JNI_EINVAL;
2768         }
2769       } else if (strcmp(tail, ":remote") == 0) {
2770         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
2771           return JNI_EINVAL;
2772         }
2773         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
2774           return JNI_EINVAL;
2775         }
2776       } else if (strcmp(tail, ":none") == 0) {
2777         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
2778           return JNI_EINVAL;
2779         }
2780         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
2781           return JNI_EINVAL;
2782         }
2783       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
2784         return JNI_EINVAL;
2785       }
2786     // -Xdebug
2787     } else if (match_option(option, "-Xdebug")) {
2788       // note this flag has been used, then ignore
2789       set_xdebug_mode(true);
2790     // -Xnoagent
2791     } else if (match_option(option, "-Xnoagent")) {
2792       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
2793     } else if (match_option(option, "-Xloggc:", &tail)) {
2794       // Redirect GC output to the file. -Xloggc:<filename>
2795       // ostream_init_log(), when called will use this filename
2796       // to initialize a fileStream.
2797       _gc_log_filename = os::strdup_check_oom(tail);
2798      if (!is_filename_valid(_gc_log_filename)) {
2799        jio_fprintf(defaultStream::output_stream(),
2800                   "Invalid file name for use with -Xloggc: Filename can only contain the "
2801                   "characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"
2802                   "Note %%p or %%t can only be used once\n", _gc_log_filename);
2803         return JNI_EINVAL;
2804       }
2805       if (FLAG_SET_CMDLINE(bool, PrintGC, true) != Flag::SUCCESS) {
2806         return JNI_EINVAL;
2807       }
2808       if (FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true) != Flag::SUCCESS) {
2809         return JNI_EINVAL;
2810       }
2811     // JNI hooks
2812     } else if (match_option(option, "-Xcheck", &tail)) {
2813       if (!strcmp(tail, ":jni")) {
2814 #if !INCLUDE_JNI_CHECK
2815         warning("JNI CHECKING is not supported in this VM");
2816 #else
2817         CheckJNICalls = true;
2818 #endif // INCLUDE_JNI_CHECK
2819       } else if (is_bad_option(option, args->ignoreUnrecognized,
2820                                      "check")) {
2821         return JNI_EINVAL;
2822       }
2823     } else if (match_option(option, "vfprintf")) {
2824       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
2825     } else if (match_option(option, "exit")) {
2826       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
2827     } else if (match_option(option, "abort")) {
2828       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
2829     // -XX:+AggressiveHeap
2830     } else if (match_option(option, "-XX:+AggressiveHeap")) {
2831 
2832       // This option inspects the machine and attempts to set various
2833       // parameters to be optimal for long-running, memory allocation
2834       // intensive jobs.  It is intended for machines with large
2835       // amounts of cpu and memory.
2836 
2837       // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
2838       // VM, but we may not be able to represent the total physical memory
2839       // available (like having 8gb of memory on a box but using a 32bit VM).
2840       // Thus, we need to make sure we're using a julong for intermediate
2841       // calculations.
2842       julong initHeapSize;
2843       julong total_memory = os::physical_memory();
2844 
2845       if (total_memory < (julong)256*M) {
2846         jio_fprintf(defaultStream::error_stream(),
2847                     "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
2848         vm_exit(1);
2849       }
2850 
2851       // The heap size is half of available memory, or (at most)
2852       // all of possible memory less 160mb (leaving room for the OS
2853       // when using ISM).  This is the maximum; because adaptive sizing
2854       // is turned on below, the actual space used may be smaller.
2855 
2856       initHeapSize = MIN2(total_memory / (julong)2,
2857                           total_memory - (julong)160*M);
2858 
2859       initHeapSize = limit_by_allocatable_memory(initHeapSize);
2860 
2861       if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2862          if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, initHeapSize) != Flag::SUCCESS) {
2863            return JNI_EINVAL;
2864          }
2865          if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, initHeapSize) != Flag::SUCCESS) {
2866            return JNI_EINVAL;
2867          }
2868          // Currently the minimum size and the initial heap sizes are the same.
2869          set_min_heap_size(initHeapSize);
2870       }
2871       if (FLAG_IS_DEFAULT(NewSize)) {
2872          // Make the young generation 3/8ths of the total heap.
2873          if (FLAG_SET_CMDLINE(size_t, NewSize,
2874                                 ((julong)MaxHeapSize / (julong)8) * (julong)3) != Flag::SUCCESS) {
2875            return JNI_EINVAL;
2876          }
2877          if (FLAG_SET_CMDLINE(size_t, MaxNewSize, NewSize) != Flag::SUCCESS) {
2878            return JNI_EINVAL;
2879          }
2880       }
2881 
2882 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
2883       FLAG_SET_DEFAULT(UseLargePages, true);
2884 #endif
2885 
2886       // Increase some data structure sizes for efficiency
2887       if (FLAG_SET_CMDLINE(size_t, BaseFootPrintEstimate, MaxHeapSize) != Flag::SUCCESS) {
2888         return JNI_EINVAL;
2889       }
2890       if (FLAG_SET_CMDLINE(bool, ResizeTLAB, false) != Flag::SUCCESS) {
2891         return JNI_EINVAL;
2892       }
2893       if (FLAG_SET_CMDLINE(size_t, TLABSize, 256*K) != Flag::SUCCESS) {
2894         return JNI_EINVAL;
2895       }
2896 
2897       // See the OldPLABSize comment below, but replace 'after promotion'
2898       // with 'after copying'.  YoungPLABSize is the size of the survivor
2899       // space per-gc-thread buffers.  The default is 4kw.
2900       if (FLAG_SET_CMDLINE(size_t, YoungPLABSize, 256*K) != Flag::SUCCESS) {      // Note: this is in words
2901         return JNI_EINVAL;
2902       }
2903 
2904       // OldPLABSize is the size of the buffers in the old gen that
2905       // UseParallelGC uses to promote live data that doesn't fit in the
2906       // survivor spaces.  At any given time, there's one for each gc thread.
2907       // The default size is 1kw. These buffers are rarely used, since the
2908       // survivor spaces are usually big enough.  For specjbb, however, there
2909       // are occasions when there's lots of live data in the young gen
2910       // and we end up promoting some of it.  We don't have a definite
2911       // explanation for why bumping OldPLABSize helps, but the theory
2912       // is that a bigger PLAB results in retaining something like the
2913       // original allocation order after promotion, which improves mutator
2914       // locality.  A minor effect may be that larger PLABs reduce the
2915       // number of PLAB allocation events during gc.  The value of 8kw
2916       // was arrived at by experimenting with specjbb.
2917       if (FLAG_SET_CMDLINE(size_t, OldPLABSize, 8*K) != Flag::SUCCESS) {  // Note: this is in words
2918         return JNI_EINVAL;
2919       }
2920 
2921       // Enable parallel GC and adaptive generation sizing
2922       if (FLAG_SET_CMDLINE(bool, UseParallelGC, true) != Flag::SUCCESS) {
2923         return JNI_EINVAL;
2924       }
2925       FLAG_SET_DEFAULT(ParallelGCThreads,
2926                        Abstract_VM_Version::parallel_worker_threads());
2927 
2928       // Encourage steady state memory management
2929       if (FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100) != Flag::SUCCESS) {
2930         return JNI_EINVAL;
2931       }
2932 
2933       // This appears to improve mutator locality
2934       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2935         return JNI_EINVAL;
2936       }
2937 
2938       // Get around early Solaris scheduling bug
2939       // (affinity vs other jobs on system)
2940       // but disallow DR and offlining (5008695).
2941       if (FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true) != Flag::SUCCESS) {
2942         return JNI_EINVAL;
2943       }
2944 
2945     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
2946     // and the last option wins.
2947     } else if (match_option(option, "-XX:+NeverTenure")) {
2948       if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
2949         return JNI_EINVAL;
2950       }
2951       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
2952         return JNI_EINVAL;
2953       }
2954       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
2955         return JNI_EINVAL;
2956       }
2957     } else if (match_option(option, "-XX:+AlwaysTenure")) {
2958       if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
2959         return JNI_EINVAL;
2960       }
2961       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
2962         return JNI_EINVAL;
2963       }
2964       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
2965         return JNI_EINVAL;
2966       }
2967     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
2968       uintx max_tenuring_thresh = 0;
2969       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
2970         jio_fprintf(defaultStream::error_stream(),
2971                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
2972         return JNI_EINVAL;
2973       }
2974 
2975       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
2976         return JNI_EINVAL;
2977       }
2978 
2979       if (MaxTenuringThreshold == 0) {
2980         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
2981           return JNI_EINVAL;
2982         }
2983         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
2984           return JNI_EINVAL;
2985         }
2986       } else {
2987         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
2988           return JNI_EINVAL;
2989         }
2990         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
2991           return JNI_EINVAL;
2992         }
2993       }
2994     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
2995       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
2996         return JNI_EINVAL;
2997       }
2998       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
2999         return JNI_EINVAL;
3000       }
3001     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3002       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
3003         return JNI_EINVAL;
3004       }
3005       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3006         return JNI_EINVAL;
3007       }
3008     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3009 #if defined(DTRACE_ENABLED)
3010       if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3011         return JNI_EINVAL;
3012       }
3013       if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3014         return JNI_EINVAL;
3015       }
3016       if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3017         return JNI_EINVAL;
3018       }
3019       if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3020         return JNI_EINVAL;
3021       }
3022 #else // defined(DTRACE_ENABLED)
3023       jio_fprintf(defaultStream::error_stream(),
3024                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3025       return JNI_EINVAL;
3026 #endif // defined(DTRACE_ENABLED)
3027 #ifdef ASSERT
3028     } else if (match_option(option, "-XX:+FullGCALot")) {
3029       if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3030         return JNI_EINVAL;
3031       }
3032       // disable scavenge before parallel mark-compact
3033       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3034         return JNI_EINVAL;
3035       }
3036 #endif
3037     } else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||
3038                match_option(option, "-XX:G1MarkStackSize=", &tail)) {
3039       julong stack_size = 0;
3040       ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);
3041       if (errcode != arg_in_range) {
3042         jio_fprintf(defaultStream::error_stream(),
3043                     "Invalid mark stack size: %s\n", option->optionString);
3044         describe_range_error(errcode);
3045         return JNI_EINVAL;
3046       }
3047       jio_fprintf(defaultStream::error_stream(),
3048         "Please use -XX:MarkStackSize in place of "
3049         "-XX:CMSMarkStackSize or -XX:G1MarkStackSize in the future\n");
3050       if (FLAG_SET_CMDLINE(size_t, MarkStackSize, stack_size) != Flag::SUCCESS) {
3051         return JNI_EINVAL;
3052       }
3053     } else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {
3054       julong max_stack_size = 0;
3055       ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);
3056       if (errcode != arg_in_range) {
3057         jio_fprintf(defaultStream::error_stream(),
3058                     "Invalid maximum mark stack size: %s\n",
3059                     option->optionString);
3060         describe_range_error(errcode);
3061         return JNI_EINVAL;
3062       }
3063       jio_fprintf(defaultStream::error_stream(),
3064          "Please use -XX:MarkStackSizeMax in place of "
3065          "-XX:CMSMarkStackSizeMax in the future\n");
3066       if (FLAG_SET_CMDLINE(size_t, MarkStackSizeMax, max_stack_size) != Flag::SUCCESS) {
3067         return JNI_EINVAL;
3068       }
3069     } else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||
3070                match_option(option, "-XX:ParallelCMSThreads=", &tail)) {
3071       uintx conc_threads = 0;
3072       if (!parse_uintx(tail, &conc_threads, 1)) {
3073         jio_fprintf(defaultStream::error_stream(),
3074                     "Invalid concurrent threads: %s\n", option->optionString);
3075         return JNI_EINVAL;
3076       }
3077       jio_fprintf(defaultStream::error_stream(),
3078         "Please use -XX:ConcGCThreads in place of "
3079         "-XX:ParallelMarkingThreads or -XX:ParallelCMSThreads in the future\n");
3080       if (FLAG_SET_CMDLINE(uint, ConcGCThreads, conc_threads) != Flag::SUCCESS) {
3081         return JNI_EINVAL;
3082       }
3083     } else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {
3084       julong max_direct_memory_size = 0;
3085       ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);
3086       if (errcode != arg_in_range) {
3087         jio_fprintf(defaultStream::error_stream(),
3088                     "Invalid maximum direct memory size: %s\n",
3089                     option->optionString);
3090         describe_range_error(errcode);
3091         return JNI_EINVAL;
3092       }
3093       if (FLAG_SET_CMDLINE(size_t, MaxDirectMemorySize, max_direct_memory_size) != Flag::SUCCESS) {
3094         return JNI_EINVAL;
3095       }
3096 #if !INCLUDE_MANAGEMENT
3097     } else if (match_option(option, "-XX:+ManagementServer")) {
3098         jio_fprintf(defaultStream::error_stream(),
3099           "ManagementServer is not supported in this VM.\n");
3100         return JNI_ERR;
3101 #endif // INCLUDE_MANAGEMENT
3102     // CreateMinidumpOnCrash is removed, and replaced by CreateCoredumpOnCrash
3103     } else if (match_option(option, "-XX:+CreateMinidumpOnCrash")) {
3104       if (FLAG_SET_CMDLINE(bool, CreateCoredumpOnCrash, true) != Flag::SUCCESS) {
3105         return JNI_EINVAL;
3106       }
3107       jio_fprintf(defaultStream::output_stream(),
3108           "CreateMinidumpOnCrash is replaced by CreateCoredumpOnCrash: CreateCoredumpOnCrash is on\n");
3109     } else if (match_option(option, "-XX:-CreateMinidumpOnCrash")) {
3110       if (FLAG_SET_CMDLINE(bool, CreateCoredumpOnCrash, false) != Flag::SUCCESS) {
3111         return JNI_EINVAL;
3112       }
3113       jio_fprintf(defaultStream::output_stream(),
3114           "CreateMinidumpOnCrash is replaced by CreateCoredumpOnCrash: CreateCoredumpOnCrash is off\n");
3115     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3116       // Skip -XX:Flags= since that case has already been handled
3117       if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
3118         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3119           return JNI_EINVAL;
3120         }
3121       }
3122     // Unknown option
3123     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3124       return JNI_ERR;
3125     }
3126   }
3127 
3128   // PrintSharedArchiveAndExit will turn on
3129   //   -Xshare:on
3130   //   -XX:+TraceClassPaths
3131   if (PrintSharedArchiveAndExit) {
3132     if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3133       return JNI_EINVAL;
3134     }
3135     if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3136       return JNI_EINVAL;
3137     }
3138     if (FLAG_SET_CMDLINE(bool, TraceClassPaths, true) != Flag::SUCCESS) {
3139       return JNI_EINVAL;
3140     }
3141   }
3142 
3143   // Change the default value for flags  which have different default values
3144   // when working with older JDKs.
3145 #ifdef LINUX
3146  if (JDK_Version::current().compare_major(6) <= 0 &&
3147       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3148     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3149   }
3150 #endif // LINUX
3151   fix_appclasspath();
3152   return JNI_OK;
3153 }
3154 
3155 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3156 //
3157 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3158 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3159 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3160 // path is treated as the current directory.
3161 //
3162 // This causes problems with CDS, which requires that all directories specified in the classpath
3163 // must be empty. In most cases, applications do NOT want to load classes from the current
3164 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3165 // scripts compatible with CDS.
3166 void Arguments::fix_appclasspath() {
3167   if (IgnoreEmptyClassPaths) {
3168     const char separator = *os::path_separator();
3169     const char* src = _java_class_path->value();
3170 
3171     // skip over all the leading empty paths
3172     while (*src == separator) {
3173       src ++;
3174     }
3175 
3176     char* copy = os::strdup_check_oom(src, mtInternal);
3177 
3178     // trim all trailing empty paths
3179     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3180       *tail = '\0';
3181     }
3182 
3183     char from[3] = {separator, separator, '\0'};
3184     char to  [2] = {separator, '\0'};
3185     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3186       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3187       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3188     }
3189 
3190     _java_class_path->set_value(copy);
3191     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3192   }
3193 
3194   if (!PrintSharedArchiveAndExit) {
3195     ClassLoader::trace_class_path("[classpath: ", _java_class_path->value());
3196   }
3197 }
3198 
3199 static bool has_jar_files(const char* directory) {
3200   DIR* dir = os::opendir(directory);
3201   if (dir == NULL) return false;
3202 
3203   struct dirent *entry;
3204   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
3205   bool hasJarFile = false;
3206   while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3207     const char* name = entry->d_name;
3208     const char* ext = name + strlen(name) - 4;
3209     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3210   }
3211   FREE_C_HEAP_ARRAY(char, dbuf);
3212   os::closedir(dir);
3213   return hasJarFile ;
3214 }
3215 
3216 static int check_non_empty_dirs(const char* path) {
3217   const char separator = *os::path_separator();
3218   const char* const end = path + strlen(path);
3219   int nonEmptyDirs = 0;
3220   while (path < end) {
3221     const char* tmp_end = strchr(path, separator);
3222     if (tmp_end == NULL) {
3223       if (has_jar_files(path)) {
3224         nonEmptyDirs++;
3225         jio_fprintf(defaultStream::output_stream(),
3226           "Non-empty directory: %s\n", path);
3227       }
3228       path = end;
3229     } else {
3230       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
3231       memcpy(dirpath, path, tmp_end - path);
3232       dirpath[tmp_end - path] = '\0';
3233       if (has_jar_files(dirpath)) {
3234         nonEmptyDirs++;
3235         jio_fprintf(defaultStream::output_stream(),
3236           "Non-empty directory: %s\n", dirpath);
3237       }
3238       FREE_C_HEAP_ARRAY(char, dirpath);
3239       path = tmp_end + 1;
3240     }
3241   }
3242   return nonEmptyDirs;
3243 }
3244 
3245 jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
3246   // check if the default lib/endorsed directory exists; if so, error
3247   char path[JVM_MAXPATHLEN];
3248   const char* fileSep = os::file_separator();
3249   sprintf(path, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3250 
3251   if (CheckEndorsedAndExtDirs) {
3252     int nonEmptyDirs = 0;
3253     // check endorsed directory
3254     nonEmptyDirs += check_non_empty_dirs(path);
3255     // check the extension directories
3256     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3257     if (nonEmptyDirs > 0) {
3258       return JNI_ERR;
3259     }
3260   }
3261 
3262   DIR* dir = os::opendir(path);
3263   if (dir != NULL) {
3264     jio_fprintf(defaultStream::output_stream(),
3265       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3266       "in modular form will be supported via the concept of upgradeable modules.\n");
3267     os::closedir(dir);
3268     return JNI_ERR;
3269   }
3270 
3271   sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3272   dir = os::opendir(path);
3273   if (dir != NULL) {
3274     jio_fprintf(defaultStream::output_stream(),
3275       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3276       "Use -classpath instead.\n.");
3277     os::closedir(dir);
3278     return JNI_ERR;
3279   }
3280 
3281   if (scp_assembly_required) {
3282     // Assemble the bootclasspath elements into the final path.
3283     Arguments::set_sysclasspath(scp_p->combined_path());
3284   }
3285 
3286   // This must be done after all arguments have been processed.
3287   // java_compiler() true means set to "NONE" or empty.
3288   if (java_compiler() && !xdebug_mode()) {
3289     // For backwards compatibility, we switch to interpreted mode if
3290     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3291     // not specified.
3292     set_mode_flags(_int);
3293   }
3294 
3295   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3296   // but like -Xint, leave compilation thresholds unaffected.
3297   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3298   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3299     set_mode_flags(_int);
3300   }
3301 
3302   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3303   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3304     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3305   }
3306 
3307 #ifndef COMPILER2
3308   // Don't degrade server performance for footprint
3309   if (FLAG_IS_DEFAULT(UseLargePages) &&
3310       MaxHeapSize < LargePageHeapSizeThreshold) {
3311     // No need for large granularity pages w/small heaps.
3312     // Note that large pages are enabled/disabled for both the
3313     // Java heap and the code cache.
3314     FLAG_SET_DEFAULT(UseLargePages, false);
3315   }
3316 
3317 #else
3318   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3319     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3320   }
3321 #endif
3322 
3323 #ifndef TIERED
3324   // Tiered compilation is undefined.
3325   UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
3326 #endif
3327 
3328   // If we are running in a headless jre, force java.awt.headless property
3329   // to be true unless the property has already been set.
3330   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3331   if (os::is_headless_jre()) {
3332     const char* headless = Arguments::get_property("java.awt.headless");
3333     if (headless == NULL) {
3334       const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3335       if (headless_env == NULL) {
3336         if (!add_property("java.awt.headless=true")) {
3337           return JNI_ENOMEM;
3338         }
3339       } else {
3340         char buffer[256];
3341         jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3342         if (!add_property(buffer)) {
3343           return JNI_ENOMEM;
3344         }
3345       }
3346     }
3347   }
3348 
3349   if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3350     // CMS can only be used with ParNew
3351     FLAG_SET_ERGO(bool, UseParNewGC, true);
3352   }
3353 
3354   if (!check_vm_args_consistency()) {
3355     return JNI_ERR;
3356   }
3357 
3358   return JNI_OK;
3359 }
3360 
3361 jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3362   return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,
3363                                             scp_assembly_required_p);
3364 }
3365 
3366 jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3367   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,
3368                                             scp_assembly_required_p);
3369 }
3370 
3371 jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {
3372   char *buffer = ::getenv(name);
3373 
3374   // Don't check this variable if user has special privileges
3375   // (e.g. unix su command).
3376   if (buffer == NULL || os::have_special_privileges()) {
3377     return JNI_OK;
3378   }
3379 
3380   if ((buffer = os::strdup(buffer)) == NULL) {
3381     return JNI_ENOMEM;
3382   }
3383 
3384   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3385   jio_fprintf(defaultStream::error_stream(),
3386               "Picked up %s: %s\n", name, buffer);
3387   char* rd = buffer;                        // pointer to the input string (rd)
3388   while (true) {                            // repeat for all options in the input string
3389     while (isspace(*rd)) rd++;              // skip whitespace
3390     if (*rd == 0) break;                    // we re done when the input string is read completely
3391 
3392     // The output, option string, overwrites the input string.
3393     // Because of quoting, the pointer to the option string (wrt) may lag the pointer to
3394     // input string (rd).
3395     char* wrt = rd;
3396 
3397     JavaVMOption option;
3398     option.optionString = wrt;
3399     options->append(option);                // Fill in option
3400     while (*rd != 0 && !isspace(*rd)) {     // unquoted strings terminate with a space or NULL
3401       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3402         int quote = *rd;                    // matching quote to look for
3403         rd++;                               // don't copy open quote
3404         while (*rd != quote) {              // include everything (even spaces) up until quote
3405           if (*rd == 0) {                   // string termination means unmatched string
3406             jio_fprintf(defaultStream::error_stream(),
3407                         "Unmatched quote in %s\n", name);
3408             delete options;
3409             os::free(buffer);
3410             return JNI_ERR;
3411           }
3412           *wrt++ = *rd++;                   // copy to option string
3413         }
3414         rd++;                               // don't copy close quote
3415       } else {
3416         *wrt++ = *rd++;                     // copy to option string
3417       }
3418     }
3419     // Need to check if we're done before writing a NULL,
3420     // because the write could be to the byte that rd is pointing to.
3421     if (*rd++ == 0) {
3422       *wrt = 0;
3423       break;
3424     }
3425     *wrt = 0;                               // Zero terminate option
3426   }
3427   JavaVMOption* options_arr =
3428       NEW_C_HEAP_ARRAY_RETURN_NULL(JavaVMOption, options->length(), mtInternal);
3429   if (options_arr == NULL) {
3430     delete options;
3431     os::free(buffer);
3432     return JNI_ENOMEM;
3433   }
3434   for (int i = 0; i < options->length(); i++) {
3435     options_arr[i] = options->at(i);
3436   }
3437 
3438   // Construct JavaVMInitArgs structure and parse as if it was part of the command line
3439   JavaVMInitArgs vm_args;
3440   vm_args.version = JNI_VERSION_1_2;
3441   vm_args.options = options_arr;
3442   vm_args.nOptions = options->length();
3443   vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3444 
3445   if (PrintVMOptions) {
3446     const char* tail;
3447     for (int i = 0; i < vm_args.nOptions; i++) {
3448       const JavaVMOption *option = vm_args.options + i;
3449       if (match_option(option, "-XX:", &tail)) {
3450         logOption(tail);
3451       }
3452     }
3453   }
3454 
3455   jint result = parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p,
3456                                        Flag::ENVIRON_VAR);
3457   FREE_C_HEAP_ARRAY(JavaVMOption, options_arr);
3458   delete options;
3459   os::free(buffer);
3460   return result;
3461 }
3462 
3463 void Arguments::set_shared_spaces_flags() {
3464   if (DumpSharedSpaces) {
3465     if (RequireSharedSpaces) {
3466       warning("cannot dump shared archive while using shared archive");
3467     }
3468     UseSharedSpaces = false;
3469 #ifdef _LP64
3470     if (!UseCompressedOops || !UseCompressedClassPointers) {
3471       vm_exit_during_initialization(
3472         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3473     }
3474   } else {
3475     if (!UseCompressedOops || !UseCompressedClassPointers) {
3476       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3477     }
3478 #endif
3479   }
3480 }
3481 
3482 #if !INCLUDE_ALL_GCS
3483 static void force_serial_gc() {
3484   FLAG_SET_DEFAULT(UseSerialGC, true);
3485   UNSUPPORTED_GC_OPTION(UseG1GC);
3486   UNSUPPORTED_GC_OPTION(UseParallelGC);
3487   UNSUPPORTED_GC_OPTION(UseParallelOldGC);
3488   UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
3489   UNSUPPORTED_GC_OPTION(UseParNewGC);
3490 }
3491 #endif // INCLUDE_ALL_GCS
3492 
3493 // Sharing support
3494 // Construct the path to the archive
3495 static char* get_shared_archive_path() {
3496   char *shared_archive_path;
3497   if (SharedArchiveFile == NULL) {
3498     char jvm_path[JVM_MAXPATHLEN];
3499     os::jvm_path(jvm_path, sizeof(jvm_path));
3500     char *end = strrchr(jvm_path, *os::file_separator());
3501     if (end != NULL) *end = '\0';
3502     size_t jvm_path_len = strlen(jvm_path);
3503     size_t file_sep_len = strlen(os::file_separator());
3504     const size_t len = jvm_path_len + file_sep_len + 20;
3505     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtInternal);
3506     if (shared_archive_path != NULL) {
3507       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3508         jvm_path, os::file_separator());
3509     }
3510   } else {
3511     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtInternal);
3512   }
3513   return shared_archive_path;
3514 }
3515 
3516 #ifndef PRODUCT
3517 // Determine whether LogVMOutput should be implicitly turned on.
3518 static bool use_vm_log() {
3519   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3520       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3521       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3522       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3523       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3524     return true;
3525   }
3526 
3527 #ifdef COMPILER1
3528   if (PrintC1Statistics) {
3529     return true;
3530   }
3531 #endif // COMPILER1
3532 
3533 #ifdef COMPILER2
3534   if (PrintOptoAssembly || PrintOptoStatistics) {
3535     return true;
3536   }
3537 #endif // COMPILER2
3538 
3539   return false;
3540 }
3541 #endif // PRODUCT
3542 
3543 // Parse entry point called from JNI_CreateJavaVM
3544 
3545 jint Arguments::parse(const JavaVMInitArgs* args) {
3546 
3547   // Initialize ranges and constraints
3548   CommandLineFlagRangeList::init();
3549   CommandLineFlagConstraintList::init();
3550 
3551   // Remaining part of option string
3552   const char* tail;
3553 
3554   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3555   const char* hotspotrc = ".hotspotrc";
3556   bool settings_file_specified = false;
3557   bool needs_hotspotrc_warning = false;
3558 
3559   const char* flags_file;
3560   int index;
3561   for (index = 0; index < args->nOptions; index++) {
3562     const JavaVMOption *option = args->options + index;
3563     if (ArgumentsExt::process_options(option)) {
3564       continue;
3565     }
3566     if (match_option(option, "-XX:Flags=", &tail)) {
3567       flags_file = tail;
3568       settings_file_specified = true;
3569       continue;
3570     }
3571     if (match_option(option, "-XX:+PrintVMOptions")) {
3572       PrintVMOptions = true;
3573       continue;
3574     }
3575     if (match_option(option, "-XX:-PrintVMOptions")) {
3576       PrintVMOptions = false;
3577       continue;
3578     }
3579     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3580       IgnoreUnrecognizedVMOptions = true;
3581       continue;
3582     }
3583     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3584       IgnoreUnrecognizedVMOptions = false;
3585       continue;
3586     }
3587     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3588       CommandLineFlags::printFlags(tty, false);
3589       vm_exit(0);
3590     }
3591     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3592 #if INCLUDE_NMT
3593       // The launcher did not setup nmt environment variable properly.
3594       if (!MemTracker::check_launcher_nmt_support(tail)) {
3595         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3596       }
3597 
3598       // Verify if nmt option is valid.
3599       if (MemTracker::verify_nmt_option()) {
3600         // Late initialization, still in single-threaded mode.
3601         if (MemTracker::tracking_level() >= NMT_summary) {
3602           MemTracker::init();
3603         }
3604       } else {
3605         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3606       }
3607       continue;
3608 #else
3609       jio_fprintf(defaultStream::error_stream(),
3610         "Native Memory Tracking is not supported in this VM\n");
3611       return JNI_ERR;
3612 #endif
3613     }
3614 
3615 #ifndef PRODUCT
3616     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3617       CommandLineFlags::printFlags(tty, true);
3618       vm_exit(0);
3619     }
3620 #endif
3621   }
3622 
3623   if (IgnoreUnrecognizedVMOptions) {
3624     // uncast const to modify the flag args->ignoreUnrecognized
3625     *(jboolean*)(&args->ignoreUnrecognized) = true;
3626   }
3627 
3628   // Parse specified settings file
3629   if (settings_file_specified) {
3630     if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
3631       return JNI_EINVAL;
3632     }
3633   } else {
3634 #ifdef ASSERT
3635     // Parse default .hotspotrc settings file
3636     if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
3637       return JNI_EINVAL;
3638     }
3639 #else
3640     struct stat buf;
3641     if (os::stat(hotspotrc, &buf) == 0) {
3642       needs_hotspotrc_warning = true;
3643     }
3644 #endif
3645   }
3646 
3647   if (PrintVMOptions) {
3648     for (index = 0; index < args->nOptions; index++) {
3649       const JavaVMOption *option = args->options + index;
3650       if (match_option(option, "-XX:", &tail)) {
3651         logOption(tail);
3652       }
3653     }
3654   }
3655 
3656   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
3657   jint result = parse_vm_init_args(args);
3658   if (result != JNI_OK) {
3659     return result;
3660   }
3661 
3662   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
3663   SharedArchivePath = get_shared_archive_path();
3664   if (SharedArchivePath == NULL) {
3665     return JNI_ENOMEM;
3666   }
3667 
3668   // Set up VerifySharedSpaces
3669   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
3670     VerifySharedSpaces = true;
3671   }
3672 
3673   // Delay warning until here so that we've had a chance to process
3674   // the -XX:-PrintWarnings flag
3675   if (needs_hotspotrc_warning) {
3676     warning("%s file is present but has been ignored.  "
3677             "Run with -XX:Flags=%s to load the file.",
3678             hotspotrc, hotspotrc);
3679   }
3680 
3681 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
3682   UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
3683 #endif
3684 
3685   ArgumentsExt::report_unsupported_options();
3686 
3687 #ifndef PRODUCT
3688   if (TraceBytecodesAt != 0) {
3689     TraceBytecodes = true;
3690   }
3691   if (CountCompiledCalls) {
3692     if (UseCounterDecay) {
3693       warning("UseCounterDecay disabled because CountCalls is set");
3694       UseCounterDecay = false;
3695     }
3696   }
3697 #endif // PRODUCT
3698 
3699   if (ScavengeRootsInCode == 0) {
3700     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3701       warning("forcing ScavengeRootsInCode non-zero");
3702     }
3703     ScavengeRootsInCode = 1;
3704   }
3705 
3706   if (PrintGCDetails) {
3707     // Turn on -verbose:gc options as well
3708     PrintGC = true;
3709   }
3710 
3711   // Set object alignment values.
3712   set_object_alignment();
3713 
3714 #if !INCLUDE_ALL_GCS
3715   force_serial_gc();
3716 #endif // INCLUDE_ALL_GCS
3717 #if !INCLUDE_CDS
3718   if (DumpSharedSpaces || RequireSharedSpaces) {
3719     jio_fprintf(defaultStream::error_stream(),
3720       "Shared spaces are not supported in this VM\n");
3721     return JNI_ERR;
3722   }
3723   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
3724     warning("Shared spaces are not supported in this VM");
3725     FLAG_SET_DEFAULT(UseSharedSpaces, false);
3726     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
3727   }
3728   no_shared_spaces("CDS Disabled");
3729 #endif // INCLUDE_CDS
3730 
3731   return JNI_OK;
3732 }
3733 
3734 jint Arguments::apply_ergo() {
3735 
3736   // Set flags based on ergonomics.
3737   set_ergonomics_flags();
3738 
3739   set_shared_spaces_flags();
3740 
3741   // Check the GC selections again.
3742   if (!check_gc_consistency()) {
3743     return JNI_EINVAL;
3744   }
3745 
3746   if (TieredCompilation) {
3747     set_tiered_flags();
3748   } else {
3749     // Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup.
3750     if (CompilationPolicyChoice >= 2) {
3751       vm_exit_during_initialization(
3752         "Incompatible compilation policy selected", NULL);
3753     }
3754     // Scale CompileThreshold
3755     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
3756     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
3757       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
3758     }
3759   }
3760 
3761 #ifdef COMPILER2
3762 #ifndef PRODUCT
3763   if (PrintIdealGraphLevel > 0) {
3764     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
3765   }
3766 #endif
3767 #endif
3768 
3769   // Set heap size based on available physical memory
3770   set_heap_size();
3771 
3772   ArgumentsExt::set_gc_specific_flags();
3773 
3774   // Initialize Metaspace flags and alignments
3775   Metaspace::ergo_initialize();
3776 
3777   // Set bytecode rewriting flags
3778   set_bytecode_flags();
3779 
3780   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
3781   set_aggressive_opts_flags();
3782 
3783   // Turn off biased locking for locking debug mode flags,
3784   // which are subtly different from each other but neither works with
3785   // biased locking
3786   if (UseHeavyMonitors
3787 #ifdef COMPILER1
3788       || !UseFastLocking
3789 #endif // COMPILER1
3790     ) {
3791     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
3792       // flag set to true on command line; warn the user that they
3793       // can't enable biased locking here
3794       warning("Biased Locking is not supported with locking debug flags"
3795               "; ignoring UseBiasedLocking flag." );
3796     }
3797     UseBiasedLocking = false;
3798   }
3799 
3800 #ifdef ZERO
3801   // Clear flags not supported on zero.
3802   FLAG_SET_DEFAULT(ProfileInterpreter, false);
3803   FLAG_SET_DEFAULT(UseBiasedLocking, false);
3804   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
3805   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
3806 #endif // CC_INTERP
3807 
3808 #ifdef COMPILER2
3809   if (!EliminateLocks) {
3810     EliminateNestedLocks = false;
3811   }
3812   if (!Inline) {
3813     IncrementalInline = false;
3814   }
3815 #ifndef PRODUCT
3816   if (!IncrementalInline) {
3817     AlwaysIncrementalInline = false;
3818   }
3819 #endif
3820   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
3821     // nothing to use the profiling, turn if off
3822     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
3823   }
3824 #endif
3825 
3826   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
3827     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
3828     DebugNonSafepoints = true;
3829   }
3830 
3831   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
3832     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
3833   }
3834 
3835 #ifndef PRODUCT
3836   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
3837     if (use_vm_log()) {
3838       LogVMOutput = true;
3839     }
3840   }
3841 #endif // PRODUCT
3842 
3843   if (PrintCommandLineFlags) {
3844     CommandLineFlags::printSetFlags(tty);
3845   }
3846 
3847   // Apply CPU specific policy for the BiasedLocking
3848   if (UseBiasedLocking) {
3849     if (!VM_Version::use_biased_locking() &&
3850         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
3851       UseBiasedLocking = false;
3852     }
3853   }
3854 #ifdef COMPILER2
3855   if (!UseBiasedLocking || EmitSync != 0) {
3856     UseOptoBiasInlining = false;
3857   }
3858 #endif
3859 
3860   return JNI_OK;
3861 }
3862 
3863 jint Arguments::adjust_after_os() {
3864   if (UseNUMA) {
3865     if (UseParallelGC || UseParallelOldGC) {
3866       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
3867          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
3868       }
3869     }
3870     // UseNUMAInterleaving is set to ON for all collectors and
3871     // platforms when UseNUMA is set to ON. NUMA-aware collectors
3872     // such as the parallel collector for Linux and Solaris will
3873     // interleave old gen and survivor spaces on top of NUMA
3874     // allocation policy for the eden space.
3875     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
3876     // all platforms and ParallelGC on Windows will interleave all
3877     // of the heap spaces across NUMA nodes.
3878     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
3879       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
3880     }
3881   }
3882   return JNI_OK;
3883 }
3884 
3885 // Any custom code post the final range and constraint check
3886 // can be done here. We pass a flag that specifies whether
3887 // the check passed successfully
3888 void Arguments::post_final_range_and_constraint_check(bool check_passed) {
3889   // This does not set the flag itself, but stores the value in a safe place for later usage.
3890   _min_heap_free_ratio = MinHeapFreeRatio;
3891   _max_heap_free_ratio = MaxHeapFreeRatio;
3892 }
3893 
3894 int Arguments::PropertyList_count(SystemProperty* pl) {
3895   int count = 0;
3896   while(pl != NULL) {
3897     count++;
3898     pl = pl->next();
3899   }
3900   return count;
3901 }
3902 
3903 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
3904   assert(key != NULL, "just checking");
3905   SystemProperty* prop;
3906   for (prop = pl; prop != NULL; prop = prop->next()) {
3907     if (strcmp(key, prop->key()) == 0) return prop->value();
3908   }
3909   return NULL;
3910 }
3911 
3912 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
3913   int count = 0;
3914   const char* ret_val = NULL;
3915 
3916   while(pl != NULL) {
3917     if(count >= index) {
3918       ret_val = pl->key();
3919       break;
3920     }
3921     count++;
3922     pl = pl->next();
3923   }
3924 
3925   return ret_val;
3926 }
3927 
3928 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
3929   int count = 0;
3930   char* ret_val = NULL;
3931 
3932   while(pl != NULL) {
3933     if(count >= index) {
3934       ret_val = pl->value();
3935       break;
3936     }
3937     count++;
3938     pl = pl->next();
3939   }
3940 
3941   return ret_val;
3942 }
3943 
3944 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
3945   SystemProperty* p = *plist;
3946   if (p == NULL) {
3947     *plist = new_p;
3948   } else {
3949     while (p->next() != NULL) {
3950       p = p->next();
3951     }
3952     p->set_next(new_p);
3953   }
3954 }
3955 
3956 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {
3957   if (plist == NULL)
3958     return;
3959 
3960   SystemProperty* new_p = new SystemProperty(k, v, true);
3961   PropertyList_add(plist, new_p);
3962 }
3963 
3964 void Arguments::PropertyList_add(SystemProperty *element) {
3965   PropertyList_add(&_system_properties, element);
3966 }
3967 
3968 // This add maintains unique property key in the list.
3969 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {
3970   if (plist == NULL)
3971     return;
3972 
3973   // If property key exist then update with new value.
3974   SystemProperty* prop;
3975   for (prop = *plist; prop != NULL; prop = prop->next()) {
3976     if (strcmp(k, prop->key()) == 0) {
3977       if (append) {
3978         prop->append_value(v);
3979       } else {
3980         prop->set_value(v);
3981       }
3982       return;
3983     }
3984   }
3985 
3986   PropertyList_add(plist, k, v);
3987 }
3988 
3989 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
3990 // Returns true if all of the source pointed by src has been copied over to
3991 // the destination buffer pointed by buf. Otherwise, returns false.
3992 // Notes:
3993 // 1. If the length (buflen) of the destination buffer excluding the
3994 // NULL terminator character is not long enough for holding the expanded
3995 // pid characters, it also returns false instead of returning the partially
3996 // expanded one.
3997 // 2. The passed in "buflen" should be large enough to hold the null terminator.
3998 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
3999                                 char* buf, size_t buflen) {
4000   const char* p = src;
4001   char* b = buf;
4002   const char* src_end = &src[srclen];
4003   char* buf_end = &buf[buflen - 1];
4004 
4005   while (p < src_end && b < buf_end) {
4006     if (*p == '%') {
4007       switch (*(++p)) {
4008       case '%':         // "%%" ==> "%"
4009         *b++ = *p++;
4010         break;
4011       case 'p':  {       //  "%p" ==> current process id
4012         // buf_end points to the character before the last character so
4013         // that we could write '\0' to the end of the buffer.
4014         size_t buf_sz = buf_end - b + 1;
4015         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4016 
4017         // if jio_snprintf fails or the buffer is not long enough to hold
4018         // the expanded pid, returns false.
4019         if (ret < 0 || ret >= (int)buf_sz) {
4020           return false;
4021         } else {
4022           b += ret;
4023           assert(*b == '\0', "fail in copy_expand_pid");
4024           if (p == src_end && b == buf_end + 1) {
4025             // reach the end of the buffer.
4026             return true;
4027           }
4028         }
4029         p++;
4030         break;
4031       }
4032       default :
4033         *b++ = '%';
4034       }
4035     } else {
4036       *b++ = *p++;
4037     }
4038   }
4039   *b = '\0';
4040   return (p == src_end); // return false if not all of the source was copied
4041 }