1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classLoader.hpp"
  27 #include "classfile/javaAssertions.hpp"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "code/codeCacheExtensions.hpp"
  31 #include "compiler/compilerOracle.hpp"
  32 #include "gc/shared/cardTableRS.hpp"
  33 #include "gc/shared/genCollectedHeap.hpp"
  34 #include "gc/shared/referenceProcessor.hpp"
  35 #include "gc/shared/taskqueue.hpp"
  36 #include "memory/allocation.inline.hpp"
  37 #include "memory/universe.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "prims/jvmtiExport.hpp"
  40 #include "runtime/arguments.hpp"
  41 #include "runtime/arguments_ext.hpp"
  42 #include "runtime/commandLineFlagConstraintList.hpp"
  43 #include "runtime/commandLineFlagRangeList.hpp"
  44 #include "runtime/globals.hpp"
  45 #include "runtime/globals_extension.hpp"
  46 #include "runtime/java.hpp"
  47 #include "runtime/os.hpp"
  48 #include "runtime/vm_version.hpp"
  49 #include "services/management.hpp"
  50 #include "services/memTracker.hpp"
  51 #include "utilities/defaultStream.hpp"
  52 #include "utilities/macros.hpp"
  53 #include "utilities/stringUtils.hpp"
  54 #if INCLUDE_ALL_GCS
  55 #include "gc/cms/compactibleFreeListSpace.hpp"
  56 #include "gc/g1/g1CollectedHeap.inline.hpp"
  57 #include "gc/parallel/parallelScavengeHeap.hpp"
  58 #endif // INCLUDE_ALL_GCS
  59 
  60 // Note: This is a special bug reporting site for the JVM
  61 #define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
  62 #define DEFAULT_JAVA_LAUNCHER  "generic"
  63 
  64 #define UNSUPPORTED_GC_OPTION(gc)                                     \
  65 do {                                                                  \
  66   if (gc) {                                                           \
  67     if (FLAG_IS_CMDLINE(gc)) {                                        \
  68       warning(#gc " is not supported in this VM.  Using Serial GC."); \
  69     }                                                                 \
  70     FLAG_SET_DEFAULT(gc, false);                                      \
  71   }                                                                   \
  72 } while(0)
  73 
  74 char** Arguments::_jvm_flags_array              = NULL;
  75 int    Arguments::_num_jvm_flags                = 0;
  76 char** Arguments::_jvm_args_array               = NULL;
  77 int    Arguments::_num_jvm_args                 = 0;
  78 char*  Arguments::_java_command                 = NULL;
  79 SystemProperty* Arguments::_system_properties   = NULL;
  80 const char*  Arguments::_gc_log_filename        = NULL;
  81 bool   Arguments::_has_profile                  = false;
  82 size_t Arguments::_conservative_max_heap_alignment = 0;
  83 size_t Arguments::_min_heap_size                = 0;
  84 uintx  Arguments::_min_heap_free_ratio          = 0;
  85 uintx  Arguments::_max_heap_free_ratio          = 0;
  86 Arguments::Mode Arguments::_mode                = _mixed;
  87 bool   Arguments::_java_compiler                = false;
  88 bool   Arguments::_xdebug_mode                  = false;
  89 const char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
  90 const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
  91 int    Arguments::_sun_java_launcher_pid        = -1;
  92 bool   Arguments::_sun_java_launcher_is_altjvm  = false;
  93 
  94 // These parameters are reset in method parse_vm_init_args(JavaVMInitArgs*)
  95 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
  96 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
  97 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
  98 bool   Arguments::_ClipInlining                 = ClipInlining;
  99 intx   Arguments::_Tier3InvokeNotifyFreqLog     = Tier3InvokeNotifyFreqLog;
 100 intx   Arguments::_Tier4InvocationThreshold     = Tier4InvocationThreshold;
 101 
 102 char*  Arguments::SharedArchivePath             = NULL;
 103 
 104 AgentLibraryList Arguments::_libraryList;
 105 AgentLibraryList Arguments::_agentList;
 106 
 107 abort_hook_t     Arguments::_abort_hook         = NULL;
 108 exit_hook_t      Arguments::_exit_hook          = NULL;
 109 vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
 110 
 111 
 112 SystemProperty *Arguments::_sun_boot_library_path = NULL;
 113 SystemProperty *Arguments::_java_library_path = NULL;
 114 SystemProperty *Arguments::_java_home = NULL;
 115 SystemProperty *Arguments::_java_class_path = NULL;
 116 SystemProperty *Arguments::_sun_boot_class_path = NULL;
 117 
 118 char* Arguments::_ext_dirs = NULL;
 119 
 120 // Check if head of 'option' matches 'name', and sets 'tail' to the remaining
 121 // part of the option string.
 122 static bool match_option(const JavaVMOption *option, const char* name,
 123                          const char** tail) {
 124   int len = (int)strlen(name);
 125   if (strncmp(option->optionString, name, len) == 0) {
 126     *tail = option->optionString + len;
 127     return true;
 128   } else {
 129     return false;
 130   }
 131 }
 132 
 133 // Check if 'option' matches 'name'. No "tail" is allowed.
 134 static bool match_option(const JavaVMOption *option, const char* name) {
 135   const char* tail = NULL;
 136   bool result = match_option(option, name, &tail);
 137   if (tail != NULL && *tail == '\0') {
 138     return result;
 139   } else {
 140     return false;
 141   }
 142 }
 143 
 144 // Return true if any of the strings in null-terminated array 'names' matches.
 145 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
 146 // the option must match exactly.
 147 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
 148   bool tail_allowed) {
 149   for (/* empty */; *names != NULL; ++names) {
 150     if (match_option(option, *names, tail)) {
 151       if (**tail == '\0' || tail_allowed && **tail == ':') {
 152         return true;
 153       }
 154     }
 155   }
 156   return false;
 157 }
 158 
 159 static void logOption(const char* opt) {
 160   if (PrintVMOptions) {
 161     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
 162   }
 163 }
 164 
 165 // Process java launcher properties.
 166 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
 167   // See if sun.java.launcher, sun.java.launcher.is_altjvm or
 168   // sun.java.launcher.pid is defined.
 169   // Must do this before setting up other system properties,
 170   // as some of them may depend on launcher type.
 171   for (int index = 0; index < args->nOptions; index++) {
 172     const JavaVMOption* option = args->options + index;
 173     const char* tail;
 174 
 175     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
 176       process_java_launcher_argument(tail, option->extraInfo);
 177       continue;
 178     }
 179     if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
 180       if (strcmp(tail, "true") == 0) {
 181         _sun_java_launcher_is_altjvm = true;
 182       }
 183       continue;
 184     }
 185     if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
 186       _sun_java_launcher_pid = atoi(tail);
 187       continue;
 188     }
 189   }
 190 }
 191 
 192 // Initialize system properties key and value.
 193 void Arguments::init_system_properties() {
 194   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
 195                                                                  "Java Virtual Machine Specification",  false));
 196   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
 197   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
 198   PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
 199 
 200   // Following are JVMTI agent writable properties.
 201   // Properties values are set to NULL and they are
 202   // os specific they are initialized in os::init_system_properties_values().
 203   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
 204   _java_library_path = new SystemProperty("java.library.path", NULL,  true);
 205   _java_home =  new SystemProperty("java.home", NULL,  true);
 206   _sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL,  true);
 207 
 208   _java_class_path = new SystemProperty("java.class.path", "",  true);
 209 
 210   // Add to System Property list.
 211   PropertyList_add(&_system_properties, _sun_boot_library_path);
 212   PropertyList_add(&_system_properties, _java_library_path);
 213   PropertyList_add(&_system_properties, _java_home);
 214   PropertyList_add(&_system_properties, _java_class_path);
 215   PropertyList_add(&_system_properties, _sun_boot_class_path);
 216 
 217   // Set OS specific system properties values
 218   os::init_system_properties_values();
 219 }
 220 
 221 // Update/Initialize System properties after JDK version number is known
 222 void Arguments::init_version_specific_system_properties() {
 223   enum { bufsz = 16 };
 224   char buffer[bufsz];
 225   const char* spec_vendor = "Sun Microsystems Inc.";
 226   uint32_t spec_version = 0;
 227 
 228   spec_vendor = "Oracle Corporation";
 229   spec_version = JDK_Version::current().major_version();
 230   jio_snprintf(buffer, bufsz, "1." UINT32_FORMAT, spec_version);
 231 
 232   PropertyList_add(&_system_properties,
 233       new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
 234   PropertyList_add(&_system_properties,
 235       new SystemProperty("java.vm.specification.version", buffer, false));
 236   PropertyList_add(&_system_properties,
 237       new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
 238 }
 239 
 240 /**
 241  * Provide a slightly more user-friendly way of eliminating -XX flags.
 242  * When a flag is eliminated, it can be added to this list in order to
 243  * continue accepting this flag on the command-line, while issuing a warning
 244  * and ignoring the value.  Once the JDK version reaches the 'accept_until'
 245  * limit, we flatly refuse to admit the existence of the flag.  This allows
 246  * a flag to die correctly over JDK releases using HSX.
 247  * But now that HSX is no longer supported only options with a future
 248  * accept_until value need to be listed, and the list can be pruned
 249  * on each major release.
 250  */
 251 typedef struct {
 252   const char* name;
 253   JDK_Version obsoleted_in; // when the flag went away
 254   JDK_Version accept_until; // which version to start denying the existence
 255 } ObsoleteFlag;
 256 
 257 static ObsoleteFlag obsolete_jvm_flags[] = {
 258   { "UseOldInlining",                JDK_Version::jdk(9), JDK_Version::jdk(10) },
 259   { "SafepointPollOffset",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
 260   { "UseBoundThreads",               JDK_Version::jdk(9), JDK_Version::jdk(10) },
 261   { "DefaultThreadPriority",         JDK_Version::jdk(9), JDK_Version::jdk(10) },
 262   { "NoYieldsInMicrolock",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
 263   { "BackEdgeThreshold",             JDK_Version::jdk(9), JDK_Version::jdk(10) },
 264   { "UseNewReflection",              JDK_Version::jdk(9), JDK_Version::jdk(10) },
 265   { "ReflectionWrapResolutionErrors",JDK_Version::jdk(9), JDK_Version::jdk(10) },
 266   { "VerifyReflectionBytecodes",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
 267   { "AutoShutdownNMT",               JDK_Version::jdk(9), JDK_Version::jdk(10) },
 268   { "NmethodSweepFraction",          JDK_Version::jdk(9), JDK_Version::jdk(10) },
 269   { "NmethodSweepCheckInterval",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
 270   { "CodeCacheMinimumFreeSpace",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
 271 #ifndef ZERO
 272   { "UseFastAccessorMethods",        JDK_Version::jdk(9), JDK_Version::jdk(10) },
 273   { "UseFastEmptyMethods",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
 274 #endif // ZERO
 275   { "UseCompilerSafepoints",         JDK_Version::jdk(9), JDK_Version::jdk(10) },
 276   { "AdaptiveSizePausePolicy",       JDK_Version::jdk(9), JDK_Version::jdk(10) },
 277   { "ParallelGCRetainPLAB",          JDK_Version::jdk(9), JDK_Version::jdk(10) },
 278   { "ThreadSafetyMargin",            JDK_Version::jdk(9), JDK_Version::jdk(10) },
 279   { "LazyBootClassLoader",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
 280   { NULL, JDK_Version(0), JDK_Version(0) }
 281 };
 282 
 283 // Returns true if the flag is obsolete and fits into the range specified
 284 // for being ignored.  In the case that the flag is ignored, the 'version'
 285 // value is filled in with the version number when the flag became
 286 // obsolete so that that value can be displayed to the user.
 287 bool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {
 288   int i = 0;
 289   assert(version != NULL, "Must provide a version buffer");
 290   while (obsolete_jvm_flags[i].name != NULL) {
 291     const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];
 292     // <flag>=xxx form
 293     // [-|+]<flag> form
 294     size_t len = strlen(flag_status.name);
 295     if ((strncmp(flag_status.name, s, len) == 0) &&
 296         (strlen(s) == len)){
 297       if (JDK_Version::current().compare(flag_status.accept_until) == -1) {
 298           *version = flag_status.obsoleted_in;
 299           return true;
 300       }
 301     }
 302     i++;
 303   }
 304   return false;
 305 }
 306 
 307 // Constructs the system class path (aka boot class path) from the following
 308 // components, in order:
 309 //
 310 //     prefix           // from -Xbootclasspath/p:...
 311 //     base             // from os::get_system_properties() or -Xbootclasspath=
 312 //     suffix           // from -Xbootclasspath/a:...
 313 //
 314 // This could be AllStatic, but it isn't needed after argument processing is
 315 // complete.
 316 class SysClassPath: public StackObj {
 317 public:
 318   SysClassPath(const char* base);
 319   ~SysClassPath();
 320 
 321   inline void set_base(const char* base);
 322   inline void add_prefix(const char* prefix);
 323   inline void add_suffix_to_prefix(const char* suffix);
 324   inline void add_suffix(const char* suffix);
 325   inline void reset_path(const char* base);
 326 
 327   inline const char* get_base()     const { return _items[_scp_base]; }
 328   inline const char* get_prefix()   const { return _items[_scp_prefix]; }
 329   inline const char* get_suffix()   const { return _items[_scp_suffix]; }
 330 
 331   // Combine all the components into a single c-heap-allocated string; caller
 332   // must free the string if/when no longer needed.
 333   char* combined_path();
 334 
 335 private:
 336   // Utility routines.
 337   static char* add_to_path(const char* path, const char* str, bool prepend);
 338   static char* add_jars_to_path(char* path, const char* directory);
 339 
 340   inline void reset_item_at(int index);
 341 
 342   // Array indices for the items that make up the sysclasspath.  All except the
 343   // base are allocated in the C heap and freed by this class.
 344   enum {
 345     _scp_prefix,        // from -Xbootclasspath/p:...
 346     _scp_base,          // the default sysclasspath
 347     _scp_suffix,        // from -Xbootclasspath/a:...
 348     _scp_nitems         // the number of items, must be last.
 349   };
 350 
 351   const char* _items[_scp_nitems];
 352 };
 353 
 354 SysClassPath::SysClassPath(const char* base) {
 355   memset(_items, 0, sizeof(_items));
 356   _items[_scp_base] = base;
 357 }
 358 
 359 SysClassPath::~SysClassPath() {
 360   // Free everything except the base.
 361   for (int i = 0; i < _scp_nitems; ++i) {
 362     if (i != _scp_base) reset_item_at(i);
 363   }
 364 }
 365 
 366 inline void SysClassPath::set_base(const char* base) {
 367   _items[_scp_base] = base;
 368 }
 369 
 370 inline void SysClassPath::add_prefix(const char* prefix) {
 371   _items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);
 372 }
 373 
 374 inline void SysClassPath::add_suffix_to_prefix(const char* suffix) {
 375   _items[_scp_prefix] = add_to_path(_items[_scp_prefix], suffix, false);
 376 }
 377 
 378 inline void SysClassPath::add_suffix(const char* suffix) {
 379   _items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);
 380 }
 381 
 382 inline void SysClassPath::reset_item_at(int index) {
 383   assert(index < _scp_nitems && index != _scp_base, "just checking");
 384   if (_items[index] != NULL) {
 385     FREE_C_HEAP_ARRAY(char, _items[index]);
 386     _items[index] = NULL;
 387   }
 388 }
 389 
 390 inline void SysClassPath::reset_path(const char* base) {
 391   // Clear the prefix and suffix.
 392   reset_item_at(_scp_prefix);
 393   reset_item_at(_scp_suffix);
 394   set_base(base);
 395 }
 396 
 397 //------------------------------------------------------------------------------
 398 
 399 
 400 // Combine the bootclasspath elements, some of which may be null, into a single
 401 // c-heap-allocated string.
 402 char* SysClassPath::combined_path() {
 403   assert(_items[_scp_base] != NULL, "empty default sysclasspath");
 404 
 405   size_t lengths[_scp_nitems];
 406   size_t total_len = 0;
 407 
 408   const char separator = *os::path_separator();
 409 
 410   // Get the lengths.
 411   int i;
 412   for (i = 0; i < _scp_nitems; ++i) {
 413     if (_items[i] != NULL) {
 414       lengths[i] = strlen(_items[i]);
 415       // Include space for the separator char (or a NULL for the last item).
 416       total_len += lengths[i] + 1;
 417     }
 418   }
 419   assert(total_len > 0, "empty sysclasspath not allowed");
 420 
 421   // Copy the _items to a single string.
 422   char* cp = NEW_C_HEAP_ARRAY(char, total_len, mtInternal);
 423   char* cp_tmp = cp;
 424   for (i = 0; i < _scp_nitems; ++i) {
 425     if (_items[i] != NULL) {
 426       memcpy(cp_tmp, _items[i], lengths[i]);
 427       cp_tmp += lengths[i];
 428       *cp_tmp++ = separator;
 429     }
 430   }
 431   *--cp_tmp = '\0';     // Replace the extra separator.
 432   return cp;
 433 }
 434 
 435 // Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
 436 char*
 437 SysClassPath::add_to_path(const char* path, const char* str, bool prepend) {
 438   char *cp;
 439 
 440   assert(str != NULL, "just checking");
 441   if (path == NULL) {
 442     size_t len = strlen(str) + 1;
 443     cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
 444     memcpy(cp, str, len);                       // copy the trailing null
 445   } else {
 446     const char separator = *os::path_separator();
 447     size_t old_len = strlen(path);
 448     size_t str_len = strlen(str);
 449     size_t len = old_len + str_len + 2;
 450 
 451     if (prepend) {
 452       cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
 453       char* cp_tmp = cp;
 454       memcpy(cp_tmp, str, str_len);
 455       cp_tmp += str_len;
 456       *cp_tmp = separator;
 457       memcpy(++cp_tmp, path, old_len + 1);      // copy the trailing null
 458       FREE_C_HEAP_ARRAY(char, path);
 459     } else {
 460       cp = REALLOC_C_HEAP_ARRAY(char, path, len, mtInternal);
 461       char* cp_tmp = cp + old_len;
 462       *cp_tmp = separator;
 463       memcpy(++cp_tmp, str, str_len + 1);       // copy the trailing null
 464     }
 465   }
 466   return cp;
 467 }
 468 
 469 // Scan the directory and append any jar or zip files found to path.
 470 // Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
 471 char* SysClassPath::add_jars_to_path(char* path, const char* directory) {
 472   DIR* dir = os::opendir(directory);
 473   if (dir == NULL) return path;
 474 
 475   char dir_sep[2] = { '\0', '\0' };
 476   size_t directory_len = strlen(directory);
 477   const char fileSep = *os::file_separator();
 478   if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;
 479 
 480   /* Scan the directory for jars/zips, appending them to path. */
 481   struct dirent *entry;
 482   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
 483   while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
 484     const char* name = entry->d_name;
 485     const char* ext = name + strlen(name) - 4;
 486     bool isJarOrZip = ext > name &&
 487       (os::file_name_strcmp(ext, ".jar") == 0 ||
 488        os::file_name_strcmp(ext, ".zip") == 0);
 489     if (isJarOrZip) {
 490       char* jarpath = NEW_C_HEAP_ARRAY(char, directory_len + 2 + strlen(name), mtInternal);
 491       sprintf(jarpath, "%s%s%s", directory, dir_sep, name);
 492       path = add_to_path(path, jarpath, false);
 493       FREE_C_HEAP_ARRAY(char, jarpath);
 494     }
 495   }
 496   FREE_C_HEAP_ARRAY(char, dbuf);
 497   os::closedir(dir);
 498   return path;
 499 }
 500 
 501 // Parses a memory size specification string.
 502 static bool atomull(const char *s, julong* result) {
 503   julong n = 0;
 504   int args_read = 0;
 505   bool is_hex = false;
 506   // Skip leading 0[xX] for hexadecimal
 507   if (*s =='0' && (*(s+1) == 'x' || *(s+1) == 'X')) {
 508     s += 2;
 509     is_hex = true;
 510     args_read = sscanf(s, JULONG_FORMAT_X, &n);
 511   } else {
 512     args_read = sscanf(s, JULONG_FORMAT, &n);
 513   }
 514   if (args_read != 1) {
 515     return false;
 516   }
 517   while (*s != '\0' && (isdigit(*s) || (is_hex && isxdigit(*s)))) {
 518     s++;
 519   }
 520   // 4705540: illegal if more characters are found after the first non-digit
 521   if (strlen(s) > 1) {
 522     return false;
 523   }
 524   switch (*s) {
 525     case 'T': case 't':
 526       *result = n * G * K;
 527       // Check for overflow.
 528       if (*result/((julong)G * K) != n) return false;
 529       return true;
 530     case 'G': case 'g':
 531       *result = n * G;
 532       if (*result/G != n) return false;
 533       return true;
 534     case 'M': case 'm':
 535       *result = n * M;
 536       if (*result/M != n) return false;
 537       return true;
 538     case 'K': case 'k':
 539       *result = n * K;
 540       if (*result/K != n) return false;
 541       return true;
 542     case '\0':
 543       *result = n;
 544       return true;
 545     default:
 546       return false;
 547   }
 548 }
 549 
 550 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
 551   if (size < min_size) return arg_too_small;
 552   // Check that size will fit in a size_t (only relevant on 32-bit)
 553   if (size > max_uintx) return arg_too_big;
 554   return arg_in_range;
 555 }
 556 
 557 // Describe an argument out of range error
 558 void Arguments::describe_range_error(ArgsRange errcode) {
 559   switch(errcode) {
 560   case arg_too_big:
 561     jio_fprintf(defaultStream::error_stream(),
 562                 "The specified size exceeds the maximum "
 563                 "representable size.\n");
 564     break;
 565   case arg_too_small:
 566   case arg_unreadable:
 567   case arg_in_range:
 568     // do nothing for now
 569     break;
 570   default:
 571     ShouldNotReachHere();
 572   }
 573 }
 574 
 575 static bool set_bool_flag(char* name, bool value, Flag::Flags origin) {
 576   if (CommandLineFlags::boolAtPut(name, &value, origin) == Flag::SUCCESS) {
 577     return true;
 578   } else {
 579     return false;
 580   }
 581 }
 582 
 583 static bool set_fp_numeric_flag(char* name, char* value, Flag::Flags origin) {
 584   double v;
 585   if (sscanf(value, "%lf", &v) != 1) {
 586     return false;
 587   }
 588 
 589   if (CommandLineFlags::doubleAtPut(name, &v, origin) == Flag::SUCCESS) {
 590     return true;
 591   }
 592   return false;
 593 }
 594 
 595 static bool set_numeric_flag(char* name, char* value, Flag::Flags origin) {
 596   julong v;
 597   int int_v;
 598   intx intx_v;
 599   bool is_neg = false;
 600   // Check the sign first since atomull() parses only unsigned values.
 601   if (*value == '-') {
 602     if ((CommandLineFlags::intxAt(name, &intx_v) != Flag::SUCCESS) && (CommandLineFlags::intAt(name, &int_v) != Flag::SUCCESS)) {
 603       return false;
 604     }
 605     value++;
 606     is_neg = true;
 607   }
 608   if (!atomull(value, &v)) {
 609     return false;
 610   }
 611   int_v = (int) v;
 612   if (is_neg) {
 613     int_v = -int_v;
 614   }
 615   if (CommandLineFlags::intAtPut(name, &int_v, origin) == Flag::SUCCESS) {
 616     return true;
 617   }
 618   uint uint_v = (uint) v;
 619   if (!is_neg && CommandLineFlags::uintAtPut(name, &uint_v, origin) == Flag::SUCCESS) {
 620     return true;
 621   }
 622   intx_v = (intx) v;
 623   if (is_neg) {
 624     intx_v = -intx_v;
 625   }
 626   if (CommandLineFlags::intxAtPut(name, &intx_v, origin) == Flag::SUCCESS) {
 627     return true;
 628   }
 629   uintx uintx_v = (uintx) v;
 630   if (!is_neg && (CommandLineFlags::uintxAtPut(name, &uintx_v, origin) == Flag::SUCCESS)) {
 631     return true;
 632   }
 633   uint64_t uint64_t_v = (uint64_t) v;
 634   if (!is_neg && (CommandLineFlags::uint64_tAtPut(name, &uint64_t_v, origin) == Flag::SUCCESS)) {
 635     return true;
 636   }
 637   size_t size_t_v = (size_t) v;
 638   if (!is_neg && (CommandLineFlags::size_tAtPut(name, &size_t_v, origin) == Flag::SUCCESS)) {
 639     return true;
 640   }
 641   return false;
 642 }
 643 
 644 static bool set_string_flag(char* name, const char* value, Flag::Flags origin) {
 645   if (CommandLineFlags::ccstrAtPut(name, &value, origin) != Flag::SUCCESS) return false;
 646   // Contract:  CommandLineFlags always returns a pointer that needs freeing.
 647   FREE_C_HEAP_ARRAY(char, value);
 648   return true;
 649 }
 650 
 651 static bool append_to_string_flag(char* name, const char* new_value, Flag::Flags origin) {
 652   const char* old_value = "";
 653   if (CommandLineFlags::ccstrAt(name, &old_value) != Flag::SUCCESS) return false;
 654   size_t old_len = old_value != NULL ? strlen(old_value) : 0;
 655   size_t new_len = strlen(new_value);
 656   const char* value;
 657   char* free_this_too = NULL;
 658   if (old_len == 0) {
 659     value = new_value;
 660   } else if (new_len == 0) {
 661     value = old_value;
 662   } else {
 663     char* buf = NEW_C_HEAP_ARRAY(char, old_len + 1 + new_len + 1, mtInternal);
 664     // each new setting adds another LINE to the switch:
 665     sprintf(buf, "%s\n%s", old_value, new_value);
 666     value = buf;
 667     free_this_too = buf;
 668   }
 669   (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
 670   // CommandLineFlags always returns a pointer that needs freeing.
 671   FREE_C_HEAP_ARRAY(char, value);
 672   if (free_this_too != NULL) {
 673     // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
 674     FREE_C_HEAP_ARRAY(char, free_this_too);
 675   }
 676   return true;
 677 }
 678 
 679 bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
 680 
 681   // range of acceptable characters spelled out for portability reasons
 682 #define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
 683 #define BUFLEN 255
 684   char name[BUFLEN+1];
 685   char dummy;
 686 
 687   if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
 688     return set_bool_flag(name, false, origin);
 689   }
 690   if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
 691     return set_bool_flag(name, true, origin);
 692   }
 693 
 694   char punct;
 695   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
 696     const char* value = strchr(arg, '=') + 1;
 697     Flag* flag = Flag::find_flag(name, strlen(name));
 698     if (flag != NULL && flag->is_ccstr()) {
 699       if (flag->ccstr_accumulates()) {
 700         return append_to_string_flag(name, value, origin);
 701       } else {
 702         if (value[0] == '\0') {
 703           value = NULL;
 704         }
 705         return set_string_flag(name, value, origin);
 706       }
 707     }
 708   }
 709 
 710   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
 711     const char* value = strchr(arg, '=') + 1;
 712     // -XX:Foo:=xxx will reset the string flag to the given value.
 713     if (value[0] == '\0') {
 714       value = NULL;
 715     }
 716     return set_string_flag(name, value, origin);
 717   }
 718 
 719 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"
 720 #define SIGNED_NUMBER_RANGE    "[-0123456789]"
 721 #define        NUMBER_RANGE    "[0123456789]"
 722   char value[BUFLEN + 1];
 723   char value2[BUFLEN + 1];
 724   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
 725     // Looks like a floating-point number -- try again with more lenient format string
 726     if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
 727       return set_fp_numeric_flag(name, value, origin);
 728     }
 729   }
 730 
 731 #define VALUE_RANGE "[-kmgtxKMGTX0123456789abcdefABCDEF]"
 732   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
 733     return set_numeric_flag(name, value, origin);
 734   }
 735 
 736   return false;
 737 }
 738 
 739 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
 740   assert(bldarray != NULL, "illegal argument");
 741 
 742   if (arg == NULL) {
 743     return;
 744   }
 745 
 746   int new_count = *count + 1;
 747 
 748   // expand the array and add arg to the last element
 749   if (*bldarray == NULL) {
 750     *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtInternal);
 751   } else {
 752     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtInternal);
 753   }
 754   (*bldarray)[*count] = os::strdup_check_oom(arg);
 755   *count = new_count;
 756 }
 757 
 758 void Arguments::build_jvm_args(const char* arg) {
 759   add_string(&_jvm_args_array, &_num_jvm_args, arg);
 760 }
 761 
 762 void Arguments::build_jvm_flags(const char* arg) {
 763   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
 764 }
 765 
 766 // utility function to return a string that concatenates all
 767 // strings in a given char** array
 768 const char* Arguments::build_resource_string(char** args, int count) {
 769   if (args == NULL || count == 0) {
 770     return NULL;
 771   }
 772   size_t length = strlen(args[0]) + 1; // add 1 for the null terminator
 773   for (int i = 1; i < count; i++) {
 774     length += strlen(args[i]) + 1; // add 1 for a space
 775   }
 776   char* s = NEW_RESOURCE_ARRAY(char, length);
 777   strcpy(s, args[0]);
 778   for (int j = 1; j < count; j++) {
 779     strcat(s, " ");
 780     strcat(s, args[j]);
 781   }
 782   return (const char*) s;
 783 }
 784 
 785 void Arguments::print_on(outputStream* st) {
 786   st->print_cr("VM Arguments:");
 787   if (num_jvm_flags() > 0) {
 788     st->print("jvm_flags: "); print_jvm_flags_on(st);
 789   }
 790   if (num_jvm_args() > 0) {
 791     st->print("jvm_args: "); print_jvm_args_on(st);
 792   }
 793   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
 794   if (_java_class_path != NULL) {
 795     char* path = _java_class_path->value();
 796     st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
 797   }
 798   st->print_cr("Launcher Type: %s", _sun_java_launcher);
 799 }
 800 
 801 void Arguments::print_jvm_flags_on(outputStream* st) {
 802   if (_num_jvm_flags > 0) {
 803     for (int i=0; i < _num_jvm_flags; i++) {
 804       st->print("%s ", _jvm_flags_array[i]);
 805     }
 806     st->cr();
 807   }
 808 }
 809 
 810 void Arguments::print_jvm_args_on(outputStream* st) {
 811   if (_num_jvm_args > 0) {
 812     for (int i=0; i < _num_jvm_args; i++) {
 813       st->print("%s ", _jvm_args_array[i]);
 814     }
 815     st->cr();
 816   }
 817 }
 818 
 819 bool Arguments::process_argument(const char* arg,
 820     jboolean ignore_unrecognized, Flag::Flags origin) {
 821 
 822   JDK_Version since = JDK_Version();
 823 
 824   if (parse_argument(arg, origin) || ignore_unrecognized) {
 825     return true;
 826   }
 827 
 828   // Determine if the flag has '+', '-', or '=' characters.
 829   bool has_plus_minus = (*arg == '+' || *arg == '-');
 830   const char* const argname = has_plus_minus ? arg + 1 : arg;
 831 
 832   size_t arg_len;
 833   const char* equal_sign = strchr(argname, '=');
 834   if (equal_sign == NULL) {
 835     arg_len = strlen(argname);
 836   } else {
 837     arg_len = equal_sign - argname;
 838   }
 839 
 840   // Only make the obsolete check for valid arguments.
 841   if (arg_len <= BUFLEN) {
 842     // Construct a string which consists only of the argument name without '+', '-', or '='.
 843     char stripped_argname[BUFLEN+1];
 844     strncpy(stripped_argname, argname, arg_len);
 845     stripped_argname[arg_len] = '\0';  // strncpy may not null terminate.
 846 
 847     if (is_newly_obsolete(stripped_argname, &since)) {
 848       char version[256];
 849       since.to_string(version, sizeof(version));
 850       warning("ignoring option %s; support was removed in %s", stripped_argname, version);
 851       return true;
 852     }
 853   }
 854 
 855   // For locked flags, report a custom error message if available.
 856   // Otherwise, report the standard unrecognized VM option.
 857   Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
 858   if (found_flag != NULL) {
 859     char locked_message_buf[BUFLEN];
 860     found_flag->get_locked_message(locked_message_buf, BUFLEN);
 861     if (strlen(locked_message_buf) == 0) {
 862       if (found_flag->is_bool() && !has_plus_minus) {
 863         jio_fprintf(defaultStream::error_stream(),
 864           "Missing +/- setting for VM option '%s'\n", argname);
 865       } else if (!found_flag->is_bool() && has_plus_minus) {
 866         jio_fprintf(defaultStream::error_stream(),
 867           "Unexpected +/- setting in VM option '%s'\n", argname);
 868       } else {
 869         jio_fprintf(defaultStream::error_stream(),
 870           "Improperly specified VM option '%s'\n", argname);
 871       }
 872     } else {
 873       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
 874     }
 875   } else {
 876     jio_fprintf(defaultStream::error_stream(),
 877                 "Unrecognized VM option '%s'\n", argname);
 878     Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
 879     if (fuzzy_matched != NULL) {
 880       jio_fprintf(defaultStream::error_stream(),
 881                   "Did you mean '%s%s%s'? ",
 882                   (fuzzy_matched->is_bool()) ? "(+/-)" : "",
 883                   fuzzy_matched->_name,
 884                   (fuzzy_matched->is_bool()) ? "" : "=<value>");
 885     }
 886   }
 887 
 888   // allow for commandline "commenting out" options like -XX:#+Verbose
 889   return arg[0] == '#';
 890 }
 891 
 892 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
 893   FILE* stream = fopen(file_name, "rb");
 894   if (stream == NULL) {
 895     if (should_exist) {
 896       jio_fprintf(defaultStream::error_stream(),
 897                   "Could not open settings file %s\n", file_name);
 898       return false;
 899     } else {
 900       return true;
 901     }
 902   }
 903 
 904   char token[1024];
 905   int  pos = 0;
 906 
 907   bool in_white_space = true;
 908   bool in_comment     = false;
 909   bool in_quote       = false;
 910   char quote_c        = 0;
 911   bool result         = true;
 912 
 913   int c = getc(stream);
 914   while(c != EOF && pos < (int)(sizeof(token)-1)) {
 915     if (in_white_space) {
 916       if (in_comment) {
 917         if (c == '\n') in_comment = false;
 918       } else {
 919         if (c == '#') in_comment = true;
 920         else if (!isspace(c)) {
 921           in_white_space = false;
 922           token[pos++] = c;
 923         }
 924       }
 925     } else {
 926       if (c == '\n' || (!in_quote && isspace(c))) {
 927         // token ends at newline, or at unquoted whitespace
 928         // this allows a way to include spaces in string-valued options
 929         token[pos] = '\0';
 930         logOption(token);
 931         result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
 932         build_jvm_flags(token);
 933         pos = 0;
 934         in_white_space = true;
 935         in_quote = false;
 936       } else if (!in_quote && (c == '\'' || c == '"')) {
 937         in_quote = true;
 938         quote_c = c;
 939       } else if (in_quote && (c == quote_c)) {
 940         in_quote = false;
 941       } else {
 942         token[pos++] = c;
 943       }
 944     }
 945     c = getc(stream);
 946   }
 947   if (pos > 0) {
 948     token[pos] = '\0';
 949     result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
 950     build_jvm_flags(token);
 951   }
 952   fclose(stream);
 953   return result;
 954 }
 955 
 956 //=============================================================================================================
 957 // Parsing of properties (-D)
 958 
 959 const char* Arguments::get_property(const char* key) {
 960   return PropertyList_get_value(system_properties(), key);
 961 }
 962 
 963 bool Arguments::add_property(const char* prop) {
 964   const char* eq = strchr(prop, '=');
 965   char* key;
 966   // ns must be static--its address may be stored in a SystemProperty object.
 967   const static char ns[1] = {0};
 968   char* value = (char *)ns;
 969 
 970   size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);
 971   key = AllocateHeap(key_len + 1, mtInternal);
 972   strncpy(key, prop, key_len);
 973   key[key_len] = '\0';
 974 
 975   if (eq != NULL) {
 976     size_t value_len = strlen(prop) - key_len - 1;
 977     value = AllocateHeap(value_len + 1, mtInternal);
 978     strncpy(value, &prop[key_len + 1], value_len + 1);
 979   }
 980 
 981   if (strcmp(key, "java.compiler") == 0) {
 982     process_java_compiler_argument(value);
 983     FreeHeap(key);
 984     if (eq != NULL) {
 985       FreeHeap(value);
 986     }
 987     return true;
 988   } else if (strcmp(key, "sun.java.command") == 0) {
 989     _java_command = value;
 990 
 991     // Record value in Arguments, but let it get passed to Java.
 992   } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0 ||
 993              strcmp(key, "sun.java.launcher.pid") == 0) {
 994     // sun.java.launcher.is_altjvm and sun.java.launcher.pid property are
 995     // private and are processed in process_sun_java_launcher_properties();
 996     // the sun.java.launcher property is passed on to the java application
 997     FreeHeap(key);
 998     if (eq != NULL) {
 999       FreeHeap(value);
1000     }
1001     return true;
1002   } else if (strcmp(key, "java.vendor.url.bug") == 0) {
1003     // save it in _java_vendor_url_bug, so JVM fatal error handler can access
1004     // its value without going through the property list or making a Java call.
1005     _java_vendor_url_bug = value;
1006   } else if (strcmp(key, "sun.boot.library.path") == 0) {
1007     PropertyList_unique_add(&_system_properties, key, value, true);
1008     return true;
1009   }
1010   // Create new property and add at the end of the list
1011   PropertyList_unique_add(&_system_properties, key, value);
1012   return true;
1013 }
1014 
1015 //===========================================================================================================
1016 // Setting int/mixed/comp mode flags
1017 
1018 void Arguments::set_mode_flags(Mode mode) {
1019   // Set up default values for all flags.
1020   // If you add a flag to any of the branches below,
1021   // add a default value for it here.
1022   set_java_compiler(false);
1023   _mode                      = mode;
1024 
1025   // Ensure Agent_OnLoad has the correct initial values.
1026   // This may not be the final mode; mode may change later in onload phase.
1027   PropertyList_unique_add(&_system_properties, "java.vm.info",
1028                           (char*)VM_Version::vm_info_string(), false);
1029 
1030   UseInterpreter             = true;
1031   UseCompiler                = true;
1032   UseLoopCounter             = true;
1033 
1034   // Default values may be platform/compiler dependent -
1035   // use the saved values
1036   ClipInlining               = Arguments::_ClipInlining;
1037   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1038   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1039   BackgroundCompilation      = Arguments::_BackgroundCompilation;
1040   if (TieredCompilation) {
1041     if (FLAG_IS_DEFAULT(Tier3InvokeNotifyFreqLog)) {
1042       Tier3InvokeNotifyFreqLog = Arguments::_Tier3InvokeNotifyFreqLog;
1043     }
1044     if (FLAG_IS_DEFAULT(Tier4InvocationThreshold)) {
1045       Tier4InvocationThreshold = Arguments::_Tier4InvocationThreshold;
1046     }
1047   }
1048 
1049   // Change from defaults based on mode
1050   switch (mode) {
1051   default:
1052     ShouldNotReachHere();
1053     break;
1054   case _int:
1055     UseCompiler              = false;
1056     UseLoopCounter           = false;
1057     AlwaysCompileLoopMethods = false;
1058     UseOnStackReplacement    = false;
1059     break;
1060   case _mixed:
1061     // same as default
1062     break;
1063   case _comp:
1064     UseInterpreter           = false;
1065     BackgroundCompilation    = false;
1066     ClipInlining             = false;
1067     // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1068     // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1069     // compile a level 4 (C2) and then continue executing it.
1070     if (TieredCompilation) {
1071       Tier3InvokeNotifyFreqLog = 0;
1072       Tier4InvocationThreshold = 0;
1073     }
1074     break;
1075   }
1076 }
1077 
1078 #if defined(COMPILER2) || defined(_LP64) || !INCLUDE_CDS
1079 // Conflict: required to use shared spaces (-Xshare:on), but
1080 // incompatible command line options were chosen.
1081 
1082 static void no_shared_spaces(const char* message) {
1083   if (RequireSharedSpaces) {
1084     jio_fprintf(defaultStream::error_stream(),
1085       "Class data sharing is inconsistent with other specified options.\n");
1086     vm_exit_during_initialization("Unable to use shared archive.", message);
1087   } else {
1088     FLAG_SET_DEFAULT(UseSharedSpaces, false);
1089   }
1090 }
1091 #endif
1092 
1093 // Returns threshold scaled with the value of scale.
1094 // If scale < 0.0, threshold is returned without scaling.
1095 intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
1096   if (scale == 1.0 || scale < 0.0) {
1097     return threshold;
1098   } else {
1099     return (intx)(threshold * scale);
1100   }
1101 }
1102 
1103 // Returns freq_log scaled with the value of scale.
1104 // Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
1105 // If scale < 0.0, freq_log is returned without scaling.
1106 intx Arguments::scaled_freq_log(intx freq_log, double scale) {
1107   // Check if scaling is necessary or if negative value was specified.
1108   if (scale == 1.0 || scale < 0.0) {
1109     return freq_log;
1110   }
1111   // Check values to avoid calculating log2 of 0.
1112   if (scale == 0.0 || freq_log == 0) {
1113     return 0;
1114   }
1115   // Determine the maximum notification frequency value currently supported.
1116   // The largest mask value that the interpreter/C1 can handle is
1117   // of length InvocationCounter::number_of_count_bits. Mask values are always
1118   // one bit shorter then the value of the notification frequency. Set
1119   // max_freq_bits accordingly.
1120   intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
1121   intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
1122   if (scaled_freq == 0) {
1123     // Return 0 right away to avoid calculating log2 of 0.
1124     return 0;
1125   } else if (scaled_freq > nth_bit(max_freq_bits)) {
1126     return max_freq_bits;
1127   } else {
1128     return log2_intptr(scaled_freq);
1129   }
1130 }
1131 
1132 void Arguments::set_tiered_flags() {
1133   // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1134   if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1135     FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1136   }
1137   if (CompilationPolicyChoice < 2) {
1138     vm_exit_during_initialization(
1139       "Incompatible compilation policy selected", NULL);
1140   }
1141   // Increase the code cache size - tiered compiles a lot more.
1142   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1143     FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
1144                   MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1145   }
1146   // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
1147   if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
1148     FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
1149 
1150     if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1151       // Multiply sizes by 5 but fix NonNMethodCodeHeapSize (distribute among non-profiled and profiled code heap)
1152       if (FLAG_IS_DEFAULT(ProfiledCodeHeapSize)) {
1153         FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, ProfiledCodeHeapSize * 5 + NonNMethodCodeHeapSize * 2);
1154       }
1155       if (FLAG_IS_DEFAULT(NonProfiledCodeHeapSize)) {
1156         FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, NonProfiledCodeHeapSize * 5 + NonNMethodCodeHeapSize * 2);
1157       }
1158       // Check consistency of code heap sizes
1159       if ((NonNMethodCodeHeapSize + NonProfiledCodeHeapSize + ProfiledCodeHeapSize) != ReservedCodeCacheSize) {
1160         jio_fprintf(defaultStream::error_stream(),
1161                     "Invalid code heap sizes: NonNMethodCodeHeapSize(%dK) + ProfiledCodeHeapSize(%dK) + NonProfiledCodeHeapSize(%dK) = %dK. Must be equal to ReservedCodeCacheSize = %uK.\n",
1162                     NonNMethodCodeHeapSize/K, ProfiledCodeHeapSize/K, NonProfiledCodeHeapSize/K,
1163                     (NonNMethodCodeHeapSize + ProfiledCodeHeapSize + NonProfiledCodeHeapSize)/K, ReservedCodeCacheSize/K);
1164         vm_exit(1);
1165       }
1166     }
1167   }
1168   if (!UseInterpreter) { // -Xcomp
1169     Tier3InvokeNotifyFreqLog = 0;
1170     Tier4InvocationThreshold = 0;
1171   }
1172 
1173   if (CompileThresholdScaling < 0) {
1174     vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
1175   }
1176 
1177   // Scale tiered compilation thresholds.
1178   // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
1179   if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
1180     FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
1181     FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
1182 
1183     FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
1184     FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
1185     FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
1186     FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
1187 
1188     // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
1189     // once these thresholds become supported.
1190 
1191     FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
1192     FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
1193 
1194     FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
1195     FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
1196 
1197     FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
1198 
1199     FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
1200     FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
1201     FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
1202     FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
1203   }
1204 }
1205 
1206 /**
1207  * Returns the minimum number of compiler threads needed to run the JVM. The following
1208  * configurations are possible.
1209  *
1210  * 1) The JVM is build using an interpreter only. As a result, the minimum number of
1211  *    compiler threads is 0.
1212  * 2) The JVM is build using the compiler(s) and tiered compilation is disabled. As
1213  *    a result, either C1 or C2 is used, so the minimum number of compiler threads is 1.
1214  * 3) The JVM is build using the compiler(s) and tiered compilation is enabled. However,
1215  *    the option "TieredStopAtLevel < CompLevel_full_optimization". As a result, only
1216  *    C1 can be used, so the minimum number of compiler threads is 1.
1217  * 4) The JVM is build using the compilers and tiered compilation is enabled. The option
1218  *    'TieredStopAtLevel = CompLevel_full_optimization' (the default value). As a result,
1219  *    the minimum number of compiler threads is 2.
1220  */
1221 int Arguments::get_min_number_of_compiler_threads() {
1222 #if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)
1223   return 0;   // case 1
1224 #else
1225   if (!TieredCompilation || (TieredStopAtLevel < CompLevel_full_optimization)) {
1226     return 1; // case 2 or case 3
1227   }
1228   return 2;   // case 4 (tiered)
1229 #endif
1230 }
1231 
1232 #if INCLUDE_ALL_GCS
1233 static void disable_adaptive_size_policy(const char* collector_name) {
1234   if (UseAdaptiveSizePolicy) {
1235     if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
1236       warning("disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
1237               collector_name);
1238     }
1239     FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
1240   }
1241 }
1242 
1243 void Arguments::set_parnew_gc_flags() {
1244   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
1245          "control point invariant");
1246   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1247   assert(UseParNewGC, "ParNew should always be used with CMS");
1248 
1249   if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
1250     FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1251     assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
1252   } else if (ParallelGCThreads == 0) {
1253     jio_fprintf(defaultStream::error_stream(),
1254         "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
1255     vm_exit(1);
1256   }
1257 
1258   // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
1259   // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
1260   // we set them to 1024 and 1024.
1261   // See CR 6362902.
1262   if (FLAG_IS_DEFAULT(YoungPLABSize)) {
1263     FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
1264   }
1265   if (FLAG_IS_DEFAULT(OldPLABSize)) {
1266     FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
1267   }
1268 
1269   // When using compressed oops, we use local overflow stacks,
1270   // rather than using a global overflow list chained through
1271   // the klass word of the object's pre-image.
1272   if (UseCompressedOops && !ParGCUseLocalOverflow) {
1273     if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
1274       warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
1275     }
1276     FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
1277   }
1278   assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
1279 }
1280 
1281 // Adjust some sizes to suit CMS and/or ParNew needs; these work well on
1282 // sparc/solaris for certain applications, but would gain from
1283 // further optimization and tuning efforts, and would almost
1284 // certainly gain from analysis of platform and environment.
1285 void Arguments::set_cms_and_parnew_gc_flags() {
1286   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
1287   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1288   assert(UseParNewGC, "ParNew should always be used with CMS");
1289 
1290   // Turn off AdaptiveSizePolicy by default for cms until it is complete.
1291   disable_adaptive_size_policy("UseConcMarkSweepGC");
1292 
1293   set_parnew_gc_flags();
1294 
1295   size_t max_heap = align_size_down(MaxHeapSize,
1296                                     CardTableRS::ct_max_alignment_constraint());
1297 
1298   // Now make adjustments for CMS
1299   intx   tenuring_default = (intx)6;
1300   size_t young_gen_per_worker = CMSYoungGenPerWorker;
1301 
1302   // Preferred young gen size for "short" pauses:
1303   // upper bound depends on # of threads and NewRatio.
1304   const size_t preferred_max_new_size_unaligned =
1305     MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * ParallelGCThreads));
1306   size_t preferred_max_new_size =
1307     align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
1308 
1309   // Unless explicitly requested otherwise, size young gen
1310   // for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
1311 
1312   // If either MaxNewSize or NewRatio is set on the command line,
1313   // assume the user is trying to set the size of the young gen.
1314   if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
1315 
1316     // Set MaxNewSize to our calculated preferred_max_new_size unless
1317     // NewSize was set on the command line and it is larger than
1318     // preferred_max_new_size.
1319     if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
1320       FLAG_SET_ERGO(size_t, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
1321     } else {
1322       FLAG_SET_ERGO(size_t, MaxNewSize, preferred_max_new_size);
1323     }
1324     if (PrintGCDetails && Verbose) {
1325       // Too early to use gclog_or_tty
1326       tty->print_cr("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
1327     }
1328 
1329     // Code along this path potentially sets NewSize and OldSize
1330     if (PrintGCDetails && Verbose) {
1331       // Too early to use gclog_or_tty
1332       tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
1333            " initial_heap_size:  " SIZE_FORMAT
1334            " max_heap: " SIZE_FORMAT,
1335            min_heap_size(), InitialHeapSize, max_heap);
1336     }
1337     size_t min_new = preferred_max_new_size;
1338     if (FLAG_IS_CMDLINE(NewSize)) {
1339       min_new = NewSize;
1340     }
1341     if (max_heap > min_new && min_heap_size() > min_new) {
1342       // Unless explicitly requested otherwise, make young gen
1343       // at least min_new, and at most preferred_max_new_size.
1344       if (FLAG_IS_DEFAULT(NewSize)) {
1345         FLAG_SET_ERGO(size_t, NewSize, MAX2(NewSize, min_new));
1346         FLAG_SET_ERGO(size_t, NewSize, MIN2(preferred_max_new_size, NewSize));
1347         if (PrintGCDetails && Verbose) {
1348           // Too early to use gclog_or_tty
1349           tty->print_cr("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
1350         }
1351       }
1352       // Unless explicitly requested otherwise, size old gen
1353       // so it's NewRatio x of NewSize.
1354       if (FLAG_IS_DEFAULT(OldSize)) {
1355         if (max_heap > NewSize) {
1356           FLAG_SET_ERGO(size_t, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
1357           if (PrintGCDetails && Verbose) {
1358             // Too early to use gclog_or_tty
1359             tty->print_cr("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
1360           }
1361         }
1362       }
1363     }
1364   }
1365   // Unless explicitly requested otherwise, definitely
1366   // promote all objects surviving "tenuring_default" scavenges.
1367   if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
1368       FLAG_IS_DEFAULT(SurvivorRatio)) {
1369     FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
1370   }
1371   // If we decided above (or user explicitly requested)
1372   // `promote all' (via MaxTenuringThreshold := 0),
1373   // prefer minuscule survivor spaces so as not to waste
1374   // space for (non-existent) survivors
1375   if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
1376     FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
1377   }
1378 
1379   // OldPLABSize is interpreted in CMS as not the size of the PLAB in words,
1380   // but rather the number of free blocks of a given size that are used when
1381   // replenishing the local per-worker free list caches.
1382   if (FLAG_IS_DEFAULT(OldPLABSize)) {
1383     if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
1384       // OldPLAB sizing manually turned off: Use a larger default setting,
1385       // unless it was manually specified. This is because a too-low value
1386       // will slow down scavenges.
1387       FLAG_SET_ERGO(size_t, OldPLABSize, CFLS_LAB::_default_static_old_plab_size); // default value before 6631166
1388     } else {
1389       FLAG_SET_DEFAULT(OldPLABSize, CFLS_LAB::_default_dynamic_old_plab_size); // old CMSParPromoteBlocksToClaim default
1390     }
1391   }
1392 
1393   // If either of the static initialization defaults have changed, note this
1394   // modification.
1395   if (!FLAG_IS_DEFAULT(OldPLABSize) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
1396     CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
1397   }
1398 
1399   if (!ClassUnloading) {
1400     FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
1401     FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
1402   }
1403 
1404   if (PrintGCDetails && Verbose) {
1405     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1406       (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1407     tty->print_cr("ConcGCThreads: %u", ConcGCThreads);
1408   }
1409 }
1410 #endif // INCLUDE_ALL_GCS
1411 
1412 void set_object_alignment() {
1413   // Object alignment.
1414   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1415   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1416   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1417   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1418   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1419   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1420 
1421   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1422   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1423 
1424   // Oop encoding heap max
1425   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1426 
1427   if (SurvivorAlignmentInBytes == 0) {
1428     SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1429   }
1430 
1431 #if INCLUDE_ALL_GCS
1432   // Set CMS global values
1433   CompactibleFreeListSpace::set_cms_values();
1434 #endif // INCLUDE_ALL_GCS
1435 }
1436 
1437 size_t Arguments::max_heap_for_compressed_oops() {
1438   // Avoid sign flip.
1439   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1440   // We need to fit both the NULL page and the heap into the memory budget, while
1441   // keeping alignment constraints of the heap. To guarantee the latter, as the
1442   // NULL page is located before the heap, we pad the NULL page to the conservative
1443   // maximum alignment that the GC may ever impose upon the heap.
1444   size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
1445                                                         _conservative_max_heap_alignment);
1446 
1447   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1448   NOT_LP64(ShouldNotReachHere(); return 0);
1449 }
1450 
1451 bool Arguments::should_auto_select_low_pause_collector() {
1452   if (UseAutoGCSelectPolicy &&
1453       !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
1454       (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
1455     if (PrintGCDetails) {
1456       // Cannot use gclog_or_tty yet.
1457       tty->print_cr("Automatic selection of the low pause collector"
1458        " based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
1459     }
1460     return true;
1461   }
1462   return false;
1463 }
1464 
1465 void Arguments::set_use_compressed_oops() {
1466 #ifndef ZERO
1467 #ifdef _LP64
1468   // MaxHeapSize is not set up properly at this point, but
1469   // the only value that can override MaxHeapSize if we are
1470   // to use UseCompressedOops is InitialHeapSize.
1471   size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1472 
1473   if (max_heap_size <= max_heap_for_compressed_oops()) {
1474 #if !defined(COMPILER1) || defined(TIERED)
1475     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1476       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1477     }
1478 #endif
1479   } else {
1480     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1481       warning("Max heap size too large for Compressed Oops");
1482       FLAG_SET_DEFAULT(UseCompressedOops, false);
1483       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1484     }
1485   }
1486 #endif // _LP64
1487 #endif // ZERO
1488 }
1489 
1490 
1491 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1492 // set_use_compressed_oops().
1493 void Arguments::set_use_compressed_klass_ptrs() {
1494 #ifndef ZERO
1495 #ifdef _LP64
1496   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1497   if (!UseCompressedOops) {
1498     if (UseCompressedClassPointers) {
1499       warning("UseCompressedClassPointers requires UseCompressedOops");
1500     }
1501     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1502   } else {
1503     // Turn on UseCompressedClassPointers too
1504     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1505       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1506     }
1507     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1508     if (UseCompressedClassPointers) {
1509       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1510         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1511         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1512       }
1513     }
1514   }
1515 #endif // _LP64
1516 #endif // !ZERO
1517 }
1518 
1519 void Arguments::set_conservative_max_heap_alignment() {
1520   // The conservative maximum required alignment for the heap is the maximum of
1521   // the alignments imposed by several sources: any requirements from the heap
1522   // itself, the collector policy and the maximum page size we may run the VM
1523   // with.
1524   size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
1525 #if INCLUDE_ALL_GCS
1526   if (UseParallelGC) {
1527     heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
1528   } else if (UseG1GC) {
1529     heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
1530   }
1531 #endif // INCLUDE_ALL_GCS
1532   _conservative_max_heap_alignment = MAX4(heap_alignment,
1533                                           (size_t)os::vm_allocation_granularity(),
1534                                           os::max_page_size(),
1535                                           CollectorPolicy::compute_heap_alignment());
1536 }
1537 
1538 void Arguments::select_gc_ergonomically() {
1539   if (os::is_server_class_machine()) {
1540     if (should_auto_select_low_pause_collector()) {
1541       FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
1542     } else {
1543 #if defined(JAVASE_EMBEDDED)
1544       FLAG_SET_ERGO(bool, UseParallelGC, true);
1545 #else
1546       FLAG_SET_ERGO(bool, UseG1GC, true);
1547 #endif
1548     }
1549   } else {
1550     FLAG_SET_ERGO(bool, UseSerialGC, true);
1551   }
1552 }
1553 
1554 void Arguments::select_gc() {
1555   if (!gc_selected()) {
1556     select_gc_ergonomically();
1557     guarantee(gc_selected(), "No GC selected");
1558   }
1559 }
1560 
1561 void Arguments::set_ergonomics_flags() {
1562   select_gc();
1563 
1564 #ifdef COMPILER2
1565   // Shared spaces work fine with other GCs but causes bytecode rewriting
1566   // to be disabled, which hurts interpreter performance and decreases
1567   // server performance.  When -server is specified, keep the default off
1568   // unless it is asked for.  Future work: either add bytecode rewriting
1569   // at link time, or rewrite bytecodes in non-shared methods.
1570   if (!DumpSharedSpaces && !RequireSharedSpaces &&
1571       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1572     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1573   }
1574 #endif
1575 
1576   set_conservative_max_heap_alignment();
1577 
1578 #ifndef ZERO
1579 #ifdef _LP64
1580   set_use_compressed_oops();
1581 
1582   // set_use_compressed_klass_ptrs() must be called after calling
1583   // set_use_compressed_oops().
1584   set_use_compressed_klass_ptrs();
1585 
1586   // Also checks that certain machines are slower with compressed oops
1587   // in vm_version initialization code.
1588 #endif // _LP64
1589 #endif // !ZERO
1590 
1591   // Set up runtime image flags.
1592   set_runtime_image_flags();
1593 
1594   CodeCacheExtensions::set_ergonomics_flags();
1595 }
1596 
1597 void Arguments::set_parallel_gc_flags() {
1598   assert(UseParallelGC || UseParallelOldGC, "Error");
1599   // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1600   if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1601     FLAG_SET_DEFAULT(UseParallelOldGC, true);
1602   }
1603   FLAG_SET_DEFAULT(UseParallelGC, true);
1604 
1605   // If no heap maximum was requested explicitly, use some reasonable fraction
1606   // of the physical memory, up to a maximum of 1GB.
1607   FLAG_SET_DEFAULT(ParallelGCThreads,
1608                    Abstract_VM_Version::parallel_worker_threads());
1609   if (ParallelGCThreads == 0) {
1610     jio_fprintf(defaultStream::error_stream(),
1611         "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1612     vm_exit(1);
1613   }
1614 
1615   if (UseAdaptiveSizePolicy) {
1616     // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1617     // unless the user actually sets these flags.
1618     if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1619       FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1620       _min_heap_free_ratio = MinHeapFreeRatio;
1621     }
1622     if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1623       FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1624       _max_heap_free_ratio = MaxHeapFreeRatio;
1625     }
1626   }
1627 
1628   // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1629   // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1630   // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1631   // See CR 6362902 for details.
1632   if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1633     if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1634        FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1635     }
1636     if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1637       FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1638     }
1639   }
1640 
1641   if (UseParallelOldGC) {
1642     // Par compact uses lower default values since they are treated as
1643     // minimums.  These are different defaults because of the different
1644     // interpretation and are not ergonomically set.
1645     if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1646       FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1647     }
1648   }
1649 }
1650 
1651 void Arguments::set_g1_gc_flags() {
1652   assert(UseG1GC, "Error");
1653 #ifdef COMPILER1
1654   FastTLABRefill = false;
1655 #endif
1656   FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1657   if (ParallelGCThreads == 0) {
1658     assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
1659     vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1660   }
1661 
1662 #if INCLUDE_ALL_GCS
1663   if (G1ConcRefinementThreads == 0) {
1664     FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);
1665   }
1666 #endif
1667 
1668   // MarkStackSize will be set (if it hasn't been set by the user)
1669   // when concurrent marking is initialized.
1670   // Its value will be based upon the number of parallel marking threads.
1671   // But we do set the maximum mark stack size here.
1672   if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1673     FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1674   }
1675 
1676   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1677     // In G1, we want the default GC overhead goal to be higher than
1678     // say in PS. So we set it here to 10%. Otherwise the heap might
1679     // be expanded more aggressively than we would like it to. In
1680     // fact, even 10% seems to not be high enough in some cases
1681     // (especially small GC stress tests that the main thing they do
1682     // is allocation). We might consider increase it further.
1683     FLAG_SET_DEFAULT(GCTimeRatio, 9);
1684   }
1685 
1686   if (PrintGCDetails && Verbose) {
1687     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1688       (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1689     tty->print_cr("ConcGCThreads: %u", ConcGCThreads);
1690   }
1691 }
1692 
1693 #if !INCLUDE_ALL_GCS
1694 #ifdef ASSERT
1695 static bool verify_serial_gc_flags() {
1696   return (UseSerialGC &&
1697         !(UseParNewGC || (UseConcMarkSweepGC) || UseG1GC ||
1698           UseParallelGC || UseParallelOldGC));
1699 }
1700 #endif // ASSERT
1701 #endif // INCLUDE_ALL_GCS
1702 
1703 void Arguments::set_gc_specific_flags() {
1704 #if INCLUDE_ALL_GCS
1705   // Set per-collector flags
1706   if (UseParallelGC || UseParallelOldGC) {
1707     set_parallel_gc_flags();
1708   } else if (UseConcMarkSweepGC) {
1709     set_cms_and_parnew_gc_flags();
1710   } else if (UseG1GC) {
1711     set_g1_gc_flags();
1712   }
1713   check_deprecated_gc_flags();
1714   if (AssumeMP && !UseSerialGC) {
1715     if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
1716       warning("If the number of processors is expected to increase from one, then"
1717               " you should configure the number of parallel GC threads appropriately"
1718               " using -XX:ParallelGCThreads=N");
1719     }
1720   }
1721   if (MinHeapFreeRatio == 100) {
1722     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
1723     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
1724   }
1725 #else // INCLUDE_ALL_GCS
1726   assert(verify_serial_gc_flags(), "SerialGC unset");
1727 #endif // INCLUDE_ALL_GCS
1728 }
1729 
1730 julong Arguments::limit_by_allocatable_memory(julong limit) {
1731   julong max_allocatable;
1732   julong result = limit;
1733   if (os::has_allocatable_memory_limit(&max_allocatable)) {
1734     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
1735   }
1736   return result;
1737 }
1738 
1739 // Use static initialization to get the default before parsing
1740 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1741 
1742 void Arguments::set_heap_size() {
1743   if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
1744     // Deprecated flag
1745     FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
1746   }
1747 
1748   const julong phys_mem =
1749     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1750                             : (julong)MaxRAM;
1751 
1752   // If the maximum heap size has not been set with -Xmx,
1753   // then set it as fraction of the size of physical memory,
1754   // respecting the maximum and minimum sizes of the heap.
1755   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1756     julong reasonable_max = phys_mem / MaxRAMFraction;
1757 
1758     if (phys_mem <= MaxHeapSize * MinRAMFraction) {
1759       // Small physical memory, so use a minimum fraction of it for the heap
1760       reasonable_max = phys_mem / MinRAMFraction;
1761     } else {
1762       // Not-small physical memory, so require a heap at least
1763       // as large as MaxHeapSize
1764       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1765     }
1766     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1767       // Limit the heap size to ErgoHeapSizeLimit
1768       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1769     }
1770     if (UseCompressedOops) {
1771       // Limit the heap size to the maximum possible when using compressed oops
1772       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1773 
1774       // HeapBaseMinAddress can be greater than default but not less than.
1775       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1776         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1777           // matches compressed oops printing flags
1778           if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
1779             jio_fprintf(defaultStream::error_stream(),
1780                         "HeapBaseMinAddress must be at least " SIZE_FORMAT
1781                         " (" SIZE_FORMAT "G) which is greater than value given "
1782                         SIZE_FORMAT "\n",
1783                         DefaultHeapBaseMinAddress,
1784                         DefaultHeapBaseMinAddress/G,
1785                         HeapBaseMinAddress);
1786           }
1787           FLAG_SET_ERGO(size_t, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1788         }
1789       }
1790 
1791       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1792         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1793         // but it should be not less than default MaxHeapSize.
1794         max_coop_heap -= HeapBaseMinAddress;
1795       }
1796       reasonable_max = MIN2(reasonable_max, max_coop_heap);
1797     }
1798     reasonable_max = limit_by_allocatable_memory(reasonable_max);
1799 
1800     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1801       // An initial heap size was specified on the command line,
1802       // so be sure that the maximum size is consistent.  Done
1803       // after call to limit_by_allocatable_memory because that
1804       // method might reduce the allocation size.
1805       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1806     }
1807 
1808     if (PrintGCDetails && Verbose) {
1809       // Cannot use gclog_or_tty yet.
1810       tty->print_cr("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1811     }
1812     FLAG_SET_ERGO(size_t, MaxHeapSize, (size_t)reasonable_max);
1813   }
1814 
1815   // If the minimum or initial heap_size have not been set or requested to be set
1816   // ergonomically, set them accordingly.
1817   if (InitialHeapSize == 0 || min_heap_size() == 0) {
1818     julong reasonable_minimum = (julong)(OldSize + NewSize);
1819 
1820     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1821 
1822     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1823 
1824     if (InitialHeapSize == 0) {
1825       julong reasonable_initial = phys_mem / InitialRAMFraction;
1826 
1827       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
1828       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1829 
1830       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
1831 
1832       if (PrintGCDetails && Verbose) {
1833         // Cannot use gclog_or_tty yet.
1834         tty->print_cr("  Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
1835       }
1836       FLAG_SET_ERGO(size_t, InitialHeapSize, (size_t)reasonable_initial);
1837     }
1838     // If the minimum heap size has not been set (via -Xms),
1839     // synchronize with InitialHeapSize to avoid errors with the default value.
1840     if (min_heap_size() == 0) {
1841       set_min_heap_size(MIN2((size_t)reasonable_minimum, InitialHeapSize));
1842       if (PrintGCDetails && Verbose) {
1843         // Cannot use gclog_or_tty yet.
1844         tty->print_cr("  Minimum heap size " SIZE_FORMAT, min_heap_size());
1845       }
1846     }
1847   }
1848 }
1849 
1850   // Set up runtime image flags
1851 void Arguments::set_runtime_image_flags() {
1852 #ifdef _LP64
1853   // Memory map image file by default on 64 bit machines.
1854   if (FLAG_IS_DEFAULT(MemoryMapImage)) {
1855     FLAG_SET_ERGO(bool, MemoryMapImage, true);
1856   }
1857 #endif
1858 }
1859 
1860 // This must be called after ergonomics.
1861 void Arguments::set_bytecode_flags() {
1862   if (!RewriteBytecodes) {
1863     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1864   }
1865 }
1866 
1867 // Aggressive optimization flags  -XX:+AggressiveOpts
1868 void Arguments::set_aggressive_opts_flags() {
1869 #ifdef COMPILER2
1870   if (AggressiveUnboxing) {
1871     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1872       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1873     } else if (!EliminateAutoBox) {
1874       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
1875       AggressiveUnboxing = false;
1876     }
1877     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1878       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1879     } else if (!DoEscapeAnalysis) {
1880       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
1881       AggressiveUnboxing = false;
1882     }
1883   }
1884   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1885     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1886       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1887     }
1888     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1889       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
1890     }
1891 
1892     // Feed the cache size setting into the JDK
1893     char buffer[1024];
1894     sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
1895     add_property(buffer);
1896   }
1897   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
1898     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
1899   }
1900 #endif
1901 
1902   if (AggressiveOpts) {
1903 // Sample flag setting code
1904 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
1905 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
1906 //    }
1907   }
1908 }
1909 
1910 //===========================================================================================================
1911 // Parsing of java.compiler property
1912 
1913 void Arguments::process_java_compiler_argument(char* arg) {
1914   // For backwards compatibility, Djava.compiler=NONE or ""
1915   // causes us to switch to -Xint mode UNLESS -Xdebug
1916   // is also specified.
1917   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
1918     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
1919   }
1920 }
1921 
1922 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1923   _sun_java_launcher = os::strdup_check_oom(launcher);
1924 }
1925 
1926 bool Arguments::created_by_java_launcher() {
1927   assert(_sun_java_launcher != NULL, "property must have value");
1928   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1929 }
1930 
1931 bool Arguments::sun_java_launcher_is_altjvm() {
1932   return _sun_java_launcher_is_altjvm;
1933 }
1934 
1935 //===========================================================================================================
1936 // Parsing of main arguments
1937 
1938 // check if do gclog rotation
1939 // +UseGCLogFileRotation is a must,
1940 // no gc log rotation when log file not supplied or
1941 // NumberOfGCLogFiles is 0
1942 void check_gclog_consistency() {
1943   if (UseGCLogFileRotation) {
1944     if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {
1945       jio_fprintf(defaultStream::output_stream(),
1946                   "To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"
1947                   "where num_of_file > 0\n"
1948                   "GC log rotation is turned off\n");
1949       UseGCLogFileRotation = false;
1950     }
1951   }
1952 
1953   if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {
1954     if (FLAG_SET_CMDLINE(size_t, GCLogFileSize, 8*K) == Flag::SUCCESS) {
1955       jio_fprintf(defaultStream::output_stream(),
1956                 "GCLogFileSize changed to minimum 8K\n");
1957     }
1958   }
1959 }
1960 
1961 // This function is called for -Xloggc:<filename>, it can be used
1962 // to check if a given file name(or string) conforms to the following
1963 // specification:
1964 // A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"
1965 // %p and %t only allowed once. We only limit usage of filename not path
1966 bool is_filename_valid(const char *file_name) {
1967   const char* p = file_name;
1968   char file_sep = os::file_separator()[0];
1969   const char* cp;
1970   // skip prefix path
1971   for (cp = file_name; *cp != '\0'; cp++) {
1972     if (*cp == '/' || *cp == file_sep) {
1973       p = cp + 1;
1974     }
1975   }
1976 
1977   int count_p = 0;
1978   int count_t = 0;
1979   while (*p != '\0') {
1980     if ((*p >= '0' && *p <= '9') ||
1981         (*p >= 'A' && *p <= 'Z') ||
1982         (*p >= 'a' && *p <= 'z') ||
1983          *p == '-'               ||
1984          *p == '_'               ||
1985          *p == '.') {
1986        p++;
1987        continue;
1988     }
1989     if (*p == '%') {
1990       if(*(p + 1) == 'p') {
1991         p += 2;
1992         count_p ++;
1993         continue;
1994       }
1995       if (*(p + 1) == 't') {
1996         p += 2;
1997         count_t ++;
1998         continue;
1999       }
2000     }
2001     return false;
2002   }
2003   return count_p < 2 && count_t < 2;
2004 }
2005 
2006 // Check consistency of GC selection
2007 bool Arguments::check_gc_consistency() {
2008   check_gclog_consistency();
2009   // Ensure that the user has not selected conflicting sets
2010   // of collectors.
2011   uint i = 0;
2012   if (UseSerialGC)                       i++;
2013   if (UseConcMarkSweepGC)                i++;
2014   if (UseParallelGC || UseParallelOldGC) i++;
2015   if (UseG1GC)                           i++;
2016   if (i > 1) {
2017     jio_fprintf(defaultStream::error_stream(),
2018                 "Conflicting collector combinations in option list; "
2019                 "please refer to the release notes for the combinations "
2020                 "allowed\n");
2021     return false;
2022   }
2023 
2024   if (UseConcMarkSweepGC && !UseParNewGC) {
2025     jio_fprintf(defaultStream::error_stream(),
2026         "It is not possible to combine the DefNew young collector with the CMS collector.\n");
2027     return false;
2028   }
2029 
2030   if (UseParNewGC && !UseConcMarkSweepGC) {
2031     jio_fprintf(defaultStream::error_stream(),
2032         "It is not possible to combine the ParNew young collector with any collector other than CMS.\n");
2033     return false;
2034   }
2035 
2036   return true;
2037 }
2038 
2039 void Arguments::check_deprecated_gc_flags() {
2040   if (FLAG_IS_CMDLINE(UseParNewGC)) {
2041     warning("The UseParNewGC flag is deprecated and will likely be removed in a future release");
2042   }
2043   if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {
2044     warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
2045             "and will likely be removed in future release");
2046   }
2047   if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {
2048     warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "
2049         "Use MaxRAMFraction instead.");
2050   }
2051 }
2052 
2053 // Check the consistency of vm_init_args
2054 bool Arguments::check_vm_args_consistency() {
2055   // Method for adding checks for flag consistency.
2056   // The intent is to warn the user of all possible conflicts,
2057   // before returning an error.
2058   // Note: Needs platform-dependent factoring.
2059   bool status = true;
2060 
2061   if (TLABRefillWasteFraction == 0) {
2062     jio_fprintf(defaultStream::error_stream(),
2063                 "TLABRefillWasteFraction should be a denominator, "
2064                 "not " SIZE_FORMAT "\n",
2065                 TLABRefillWasteFraction);
2066     status = false;
2067   }
2068 
2069   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2070     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
2071   }
2072 
2073   if (UseParallelOldGC && ParallelOldGCSplitALot) {
2074     // Settings to encourage splitting.
2075     if (!FLAG_IS_CMDLINE(NewRatio)) {
2076       if (FLAG_SET_CMDLINE(uintx, NewRatio, 2) != Flag::SUCCESS) {
2077         status = false;
2078       }
2079     }
2080     if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
2081       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2082         status = false;
2083       }
2084     }
2085   }
2086 
2087   if (!(UseParallelGC || UseParallelOldGC) && FLAG_IS_DEFAULT(ScavengeBeforeFullGC)) {
2088     FLAG_SET_DEFAULT(ScavengeBeforeFullGC, false);
2089   }
2090 
2091   if (GCTimeLimit == 100) {
2092     // Turn off gc-overhead-limit-exceeded checks
2093     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2094   }
2095 
2096   status = status && check_gc_consistency();
2097 
2098   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2099   // insists that we hold the requisite locks so that the iteration is
2100   // MT-safe. For the verification at start-up and shut-down, we don't
2101   // yet have a good way of acquiring and releasing these locks,
2102   // which are not visible at the CollectedHeap level. We want to
2103   // be able to acquire these locks and then do the iteration rather
2104   // than just disable the lock verification. This will be fixed under
2105   // bug 4788986.
2106   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2107     if (VerifyDuringStartup) {
2108       warning("Heap verification at start-up disabled "
2109               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2110       VerifyDuringStartup = false; // Disable verification at start-up
2111     }
2112 
2113     if (VerifyBeforeExit) {
2114       warning("Heap verification at shutdown disabled "
2115               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2116       VerifyBeforeExit = false; // Disable verification at shutdown
2117     }
2118   }
2119 
2120   // Note: only executed in non-PRODUCT mode
2121   if (!UseAsyncConcMarkSweepGC &&
2122       (ExplicitGCInvokesConcurrent ||
2123        ExplicitGCInvokesConcurrentAndUnloadsClasses)) {
2124     jio_fprintf(defaultStream::error_stream(),
2125                 "error: +ExplicitGCInvokesConcurrent[AndUnloadsClasses] conflicts"
2126                 " with -UseAsyncConcMarkSweepGC");
2127     status = false;
2128   }
2129 
2130   if (PrintNMTStatistics) {
2131 #if INCLUDE_NMT
2132     if (MemTracker::tracking_level() == NMT_off) {
2133 #endif // INCLUDE_NMT
2134       warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2135       PrintNMTStatistics = false;
2136 #if INCLUDE_NMT
2137     }
2138 #endif
2139   }
2140 
2141   // Check lower bounds of the code cache
2142   // Template Interpreter code is approximately 3X larger in debug builds.
2143   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2144   if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2145     jio_fprintf(defaultStream::error_stream(),
2146                 "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
2147                 os::vm_page_size()/K);
2148     status = false;
2149   } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2150     jio_fprintf(defaultStream::error_stream(),
2151                 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2152                 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2153     status = false;
2154   } else if (ReservedCodeCacheSize < min_code_cache_size) {
2155     jio_fprintf(defaultStream::error_stream(),
2156                 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2157                 min_code_cache_size/K);
2158     status = false;
2159   } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2160     // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2161     jio_fprintf(defaultStream::error_stream(),
2162                 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2163                 CODE_CACHE_SIZE_LIMIT/M);
2164     status = false;
2165   } else if (NonNMethodCodeHeapSize < min_code_cache_size){
2166     jio_fprintf(defaultStream::error_stream(),
2167                 "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2168                 min_code_cache_size/K);
2169     status = false;
2170   } else if ((!FLAG_IS_DEFAULT(NonNMethodCodeHeapSize) || !FLAG_IS_DEFAULT(ProfiledCodeHeapSize) || !FLAG_IS_DEFAULT(NonProfiledCodeHeapSize))
2171              && (NonNMethodCodeHeapSize + NonProfiledCodeHeapSize + ProfiledCodeHeapSize) != ReservedCodeCacheSize) {
2172     jio_fprintf(defaultStream::error_stream(),
2173                 "Invalid code heap sizes: NonNMethodCodeHeapSize(%dK) + ProfiledCodeHeapSize(%dK) + NonProfiledCodeHeapSize(%dK) = %dK. Must be equal to ReservedCodeCacheSize = %uK.\n",
2174                 NonNMethodCodeHeapSize/K, ProfiledCodeHeapSize/K, NonProfiledCodeHeapSize/K,
2175                 (NonNMethodCodeHeapSize + ProfiledCodeHeapSize + NonProfiledCodeHeapSize)/K, ReservedCodeCacheSize/K);
2176     status = false;
2177   }
2178 
2179   int min_number_of_compiler_threads = get_min_number_of_compiler_threads();
2180   // The default CICompilerCount's value is CI_COMPILER_COUNT.
2181   assert(min_number_of_compiler_threads <= CI_COMPILER_COUNT, "minimum should be less or equal default number");
2182 
2183   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2184     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2185   }
2186 
2187   return status;
2188 }
2189 
2190 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2191   const char* option_type) {
2192   if (ignore) return false;
2193 
2194   const char* spacer = " ";
2195   if (option_type == NULL) {
2196     option_type = ++spacer; // Set both to the empty string.
2197   }
2198 
2199   if (os::obsolete_option(option)) {
2200     jio_fprintf(defaultStream::error_stream(),
2201                 "Obsolete %s%soption: %s\n", option_type, spacer,
2202       option->optionString);
2203     return false;
2204   } else {
2205     jio_fprintf(defaultStream::error_stream(),
2206                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2207       option->optionString);
2208     return true;
2209   }
2210 }
2211 
2212 static const char* user_assertion_options[] = {
2213   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2214 };
2215 
2216 static const char* system_assertion_options[] = {
2217   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2218 };
2219 
2220 bool Arguments::parse_uintx(const char* value,
2221                             uintx* uintx_arg,
2222                             uintx min_size) {
2223 
2224   // Check the sign first since atomull() parses only unsigned values.
2225   bool value_is_positive = !(*value == '-');
2226 
2227   if (value_is_positive) {
2228     julong n;
2229     bool good_return = atomull(value, &n);
2230     if (good_return) {
2231       bool above_minimum = n >= min_size;
2232       bool value_is_too_large = n > max_uintx;
2233 
2234       if (above_minimum && !value_is_too_large) {
2235         *uintx_arg = n;
2236         return true;
2237       }
2238     }
2239   }
2240   return false;
2241 }
2242 
2243 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2244                                                   julong* long_arg,
2245                                                   julong min_size) {
2246   if (!atomull(s, long_arg)) return arg_unreadable;
2247   return check_memory_size(*long_arg, min_size);
2248 }
2249 
2250 // Parse JavaVMInitArgs structure
2251 
2252 jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {


2253   // For components of the system classpath.
2254   SysClassPath scp(Arguments::get_sysclasspath());
2255   bool scp_assembly_required = false;
2256 
2257   // Save default settings for some mode flags
2258   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2259   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2260   Arguments::_ClipInlining             = ClipInlining;
2261   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2262   if (TieredCompilation) {
2263     Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2264     Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2265   }
2266 
2267   // Setup flags for mixed which is the default
2268   set_mode_flags(_mixed);
2269 
2270   // Parse JAVA_TOOL_OPTIONS environment variable (if present)
2271   jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);


2272   if (result != JNI_OK) {
2273     return result;
2274   }
2275 
2276   // Parse JavaVMInitArgs structure passed in
2277   result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, Flag::COMMAND_LINE);

2278   if (result != JNI_OK) {
2279     return result;
2280   }
2281 
2282   // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
2283   result = parse_java_options_environment_variable(&scp, &scp_assembly_required);


2284   if (result != JNI_OK) {
2285     return result;
2286   }
2287 
2288   // Do final processing now that all arguments have been parsed
2289   result = finalize_vm_init_args(&scp, scp_assembly_required);
2290   if (result != JNI_OK) {
2291     return result;
2292   }
2293 
2294   return JNI_OK;
2295 }
2296 
2297 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2298 // represents a valid HPROF of JDWP agent.  is_path==true denotes that we
2299 // are dealing with -agentpath (case where name is a path), otherwise with
2300 // -agentlib
2301 bool valid_hprof_or_jdwp_agent(char *name, bool is_path) {
2302   char *_name;
2303   const char *_hprof = "hprof", *_jdwp = "jdwp";
2304   size_t _len_hprof, _len_jdwp, _len_prefix;
2305 
2306   if (is_path) {
2307     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2308       return false;
2309     }
2310 
2311     _name++;  // skip past last path separator
2312     _len_prefix = strlen(JNI_LIB_PREFIX);
2313 
2314     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2315       return false;
2316     }
2317 
2318     _name += _len_prefix;
2319     _len_hprof = strlen(_hprof);
2320     _len_jdwp = strlen(_jdwp);
2321 
2322     if (strncmp(_name, _hprof, _len_hprof) == 0) {
2323       _name += _len_hprof;
2324     }
2325     else if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2326       _name += _len_jdwp;
2327     }
2328     else {
2329       return false;
2330     }
2331 
2332     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2333       return false;
2334     }
2335 
2336     return true;
2337   }
2338 
2339   if (strcmp(name, _hprof) == 0 || strcmp(name, _jdwp) == 0) {
2340     return true;
2341   }
2342 
2343   return false;
2344 }
2345 
2346 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2347                                        SysClassPath* scp_p,
2348                                        bool* scp_assembly_required_p,
2349                                        Flag::Flags origin) {
2350   // Remaining part of option string
2351   const char* tail;
2352 
2353   // iterate over arguments
2354   for (int index = 0; index < args->nOptions; index++) {
2355     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2356 
2357     const JavaVMOption* option = args->options + index;
2358 
2359     if (!match_option(option, "-Djava.class.path", &tail) &&
2360         !match_option(option, "-Dsun.java.command", &tail) &&
2361         !match_option(option, "-Dsun.java.launcher", &tail)) {
2362 
2363         // add all jvm options to the jvm_args string. This string
2364         // is used later to set the java.vm.args PerfData string constant.
2365         // the -Djava.class.path and the -Dsun.java.command options are
2366         // omitted from jvm_args string as each have their own PerfData
2367         // string constant object.
2368         build_jvm_args(option->optionString);
2369     }
2370 
2371     // -verbose:[class/gc/jni]
2372     if (match_option(option, "-verbose", &tail)) {
2373       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2374         if (FLAG_SET_CMDLINE(bool, TraceClassLoading, true) != Flag::SUCCESS) {
2375           return JNI_EINVAL;
2376         }
2377         if (FLAG_SET_CMDLINE(bool, TraceClassUnloading, true) != Flag::SUCCESS) {
2378           return JNI_EINVAL;
2379         }
2380       } else if (!strcmp(tail, ":gc")) {
2381         if (FLAG_SET_CMDLINE(bool, PrintGC, true) != Flag::SUCCESS) {
2382           return JNI_EINVAL;
2383         }
2384       } else if (!strcmp(tail, ":jni")) {
2385         if (FLAG_SET_CMDLINE(bool, PrintJNIResolving, true) != Flag::SUCCESS) {
2386           return JNI_EINVAL;
2387         }
2388       }
2389     // -da / -ea / -disableassertions / -enableassertions
2390     // These accept an optional class/package name separated by a colon, e.g.,
2391     // -da:java.lang.Thread.
2392     } else if (match_option(option, user_assertion_options, &tail, true)) {
2393       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2394       if (*tail == '\0') {
2395         JavaAssertions::setUserClassDefault(enable);
2396       } else {
2397         assert(*tail == ':', "bogus match by match_option()");
2398         JavaAssertions::addOption(tail + 1, enable);
2399       }
2400     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2401     } else if (match_option(option, system_assertion_options, &tail, false)) {
2402       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2403       JavaAssertions::setSystemClassDefault(enable);
2404     // -bootclasspath:
2405     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2406       scp_p->reset_path(tail);
2407       *scp_assembly_required_p = true;
2408     // -bootclasspath/a:
2409     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2410       scp_p->add_suffix(tail);
2411       *scp_assembly_required_p = true;
2412     // -bootclasspath/p:
2413     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2414       scp_p->add_prefix(tail);
2415       *scp_assembly_required_p = true;
2416     // -Xrun
2417     } else if (match_option(option, "-Xrun", &tail)) {
2418       if (tail != NULL) {
2419         const char* pos = strchr(tail, ':');
2420         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2421         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2422         name[len] = '\0';
2423 
2424         char *options = NULL;
2425         if(pos != NULL) {
2426           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2427           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
2428         }
2429 #if !INCLUDE_JVMTI
2430         if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
2431           jio_fprintf(defaultStream::error_stream(),
2432             "Profiling and debugging agents are not supported in this VM\n");
2433           return JNI_ERR;
2434         }
2435 #endif // !INCLUDE_JVMTI
2436         add_init_library(name, options);
2437       }
2438     // -agentlib and -agentpath
2439     } else if (match_option(option, "-agentlib:", &tail) ||
2440           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2441       if(tail != NULL) {
2442         const char* pos = strchr(tail, '=');
2443         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2444         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2445         name[len] = '\0';
2446 
2447         char *options = NULL;
2448         if(pos != NULL) {
2449           options = os::strdup_check_oom(pos + 1, mtInternal);
2450         }
2451 #if !INCLUDE_JVMTI
2452         if (valid_hprof_or_jdwp_agent(name, is_absolute_path)) {
2453           jio_fprintf(defaultStream::error_stream(),
2454             "Profiling and debugging agents are not supported in this VM\n");
2455           return JNI_ERR;
2456         }
2457 #endif // !INCLUDE_JVMTI
2458         add_init_agent(name, options, is_absolute_path);
2459       }
2460     // -javaagent
2461     } else if (match_option(option, "-javaagent:", &tail)) {
2462 #if !INCLUDE_JVMTI
2463       jio_fprintf(defaultStream::error_stream(),
2464         "Instrumentation agents are not supported in this VM\n");
2465       return JNI_ERR;
2466 #else
2467       if(tail != NULL) {
2468         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtInternal), tail);
2469         add_init_agent("instrument", options, false);
2470       }
2471 #endif // !INCLUDE_JVMTI
2472     // -Xnoclassgc
2473     } else if (match_option(option, "-Xnoclassgc")) {
2474       if (FLAG_SET_CMDLINE(bool, ClassUnloading, false) != Flag::SUCCESS) {
2475         return JNI_EINVAL;
2476       }
2477     // -Xconcgc
2478     } else if (match_option(option, "-Xconcgc")) {
2479       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true) != Flag::SUCCESS) {
2480         return JNI_EINVAL;
2481       }
2482     // -Xnoconcgc
2483     } else if (match_option(option, "-Xnoconcgc")) {
2484       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false) != Flag::SUCCESS) {
2485         return JNI_EINVAL;
2486       }
2487     // -Xbatch
2488     } else if (match_option(option, "-Xbatch")) {
2489       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2490         return JNI_EINVAL;
2491       }
2492     // -Xmn for compatibility with other JVM vendors
2493     } else if (match_option(option, "-Xmn", &tail)) {
2494       julong long_initial_young_size = 0;
2495       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2496       if (errcode != arg_in_range) {
2497         jio_fprintf(defaultStream::error_stream(),
2498                     "Invalid initial young generation size: %s\n", option->optionString);
2499         describe_range_error(errcode);
2500         return JNI_EINVAL;
2501       }
2502       if (FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2503         return JNI_EINVAL;
2504       }
2505       if (FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2506         return JNI_EINVAL;
2507       }
2508     // -Xms
2509     } else if (match_option(option, "-Xms", &tail)) {
2510       julong long_initial_heap_size = 0;
2511       // an initial heap size of 0 means automatically determine
2512       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2513       if (errcode != arg_in_range) {
2514         jio_fprintf(defaultStream::error_stream(),
2515                     "Invalid initial heap size: %s\n", option->optionString);
2516         describe_range_error(errcode);
2517         return JNI_EINVAL;
2518       }
2519       set_min_heap_size((size_t)long_initial_heap_size);
2520       // Currently the minimum size and the initial heap sizes are the same.
2521       // Can be overridden with -XX:InitialHeapSize.
2522       if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size) != Flag::SUCCESS) {
2523         return JNI_EINVAL;
2524       }
2525     // -Xmx
2526     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2527       julong long_max_heap_size = 0;
2528       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2529       if (errcode != arg_in_range) {
2530         jio_fprintf(defaultStream::error_stream(),
2531                     "Invalid maximum heap size: %s\n", option->optionString);
2532         describe_range_error(errcode);
2533         return JNI_EINVAL;
2534       }
2535       if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size) != Flag::SUCCESS) {
2536         return JNI_EINVAL;
2537       }
2538     // Xmaxf
2539     } else if (match_option(option, "-Xmaxf", &tail)) {
2540       char* err;
2541       int maxf = (int)(strtod(tail, &err) * 100);
2542       if (*err != '\0' || *tail == '\0') {
2543         jio_fprintf(defaultStream::error_stream(),
2544                     "Bad max heap free percentage size: %s\n",
2545                     option->optionString);
2546         return JNI_EINVAL;
2547       } else {
2548         if (FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf) != Flag::SUCCESS) {
2549             return JNI_EINVAL;
2550         }
2551       }
2552     // Xminf
2553     } else if (match_option(option, "-Xminf", &tail)) {
2554       char* err;
2555       int minf = (int)(strtod(tail, &err) * 100);
2556       if (*err != '\0' || *tail == '\0') {
2557         jio_fprintf(defaultStream::error_stream(),
2558                     "Bad min heap free percentage size: %s\n",
2559                     option->optionString);
2560         return JNI_EINVAL;
2561       } else {
2562         if (FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf) != Flag::SUCCESS) {
2563           return JNI_EINVAL;
2564         }
2565       }
2566     // -Xss
2567     } else if (match_option(option, "-Xss", &tail)) {
2568       julong long_ThreadStackSize = 0;
2569       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2570       if (errcode != arg_in_range) {
2571         jio_fprintf(defaultStream::error_stream(),
2572                     "Invalid thread stack size: %s\n", option->optionString);
2573         describe_range_error(errcode);
2574         return JNI_EINVAL;
2575       }
2576       // Internally track ThreadStackSize in units of 1024 bytes.
2577       if (FLAG_SET_CMDLINE(intx, ThreadStackSize,
2578                        round_to((int)long_ThreadStackSize, K) / K) != Flag::SUCCESS) {
2579         return JNI_EINVAL;
2580       }
2581     // -Xoss, -Xsqnopause, -Xoptimize, -Xboundthreads
2582     } else if (match_option(option, "-Xoss", &tail) ||
2583                match_option(option, "-Xsqnopause") ||
2584                match_option(option, "-Xoptimize") ||
2585                match_option(option, "-Xboundthreads")) {
2586       // All these options are deprecated in JDK 9 and will be removed in a future release
2587       char version[256];
2588       JDK_Version::jdk(9).to_string(version, sizeof(version));
2589       warning("ignoring option %s; support was removed in %s", option->optionString, version);
2590     } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
2591       julong long_CodeCacheExpansionSize = 0;
2592       ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
2593       if (errcode != arg_in_range) {
2594         jio_fprintf(defaultStream::error_stream(),
2595                    "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
2596                    os::vm_page_size()/K);
2597         return JNI_EINVAL;
2598       }
2599       if (FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize) != Flag::SUCCESS) {
2600         return JNI_EINVAL;
2601       }
2602     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2603                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2604       julong long_ReservedCodeCacheSize = 0;
2605 
2606       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2607       if (errcode != arg_in_range) {
2608         jio_fprintf(defaultStream::error_stream(),
2609                     "Invalid maximum code cache size: %s.\n", option->optionString);
2610         return JNI_EINVAL;
2611       }
2612       if (FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != Flag::SUCCESS) {
2613         return JNI_EINVAL;
2614       }
2615       // -XX:NonNMethodCodeHeapSize=
2616     } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
2617       julong long_NonNMethodCodeHeapSize = 0;
2618 
2619       ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
2620       if (errcode != arg_in_range) {
2621         jio_fprintf(defaultStream::error_stream(),
2622                     "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
2623         return JNI_EINVAL;
2624       }
2625       if (FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize) != Flag::SUCCESS) {
2626         return JNI_EINVAL;
2627       }
2628       // -XX:ProfiledCodeHeapSize=
2629     } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
2630       julong long_ProfiledCodeHeapSize = 0;
2631 
2632       ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
2633       if (errcode != arg_in_range) {
2634         jio_fprintf(defaultStream::error_stream(),
2635                     "Invalid maximum profiled code heap size: %s.\n", option->optionString);
2636         return JNI_EINVAL;
2637       }
2638       if (FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize) != Flag::SUCCESS) {
2639         return JNI_EINVAL;
2640       }
2641       // -XX:NonProfiledCodeHeapSizee=
2642     } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
2643       julong long_NonProfiledCodeHeapSize = 0;
2644 
2645       ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
2646       if (errcode != arg_in_range) {
2647         jio_fprintf(defaultStream::error_stream(),
2648                     "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
2649         return JNI_EINVAL;
2650       }
2651       if (FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize) != Flag::SUCCESS) {
2652         return JNI_EINVAL;
2653       }
2654     // -green
2655     } else if (match_option(option, "-green")) {
2656       jio_fprintf(defaultStream::error_stream(),
2657                   "Green threads support not available\n");
2658           return JNI_EINVAL;
2659     // -native
2660     } else if (match_option(option, "-native")) {
2661           // HotSpot always uses native threads, ignore silently for compatibility
2662     // -Xrs
2663     } else if (match_option(option, "-Xrs")) {
2664           // Classic/EVM option, new functionality
2665       if (FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true) != Flag::SUCCESS) {
2666         return JNI_EINVAL;
2667       }
2668     } else if (match_option(option, "-Xusealtsigs")) {
2669           // change default internal VM signals used - lower case for back compat
2670       if (FLAG_SET_CMDLINE(bool, UseAltSigs, true) != Flag::SUCCESS) {
2671         return JNI_EINVAL;
2672       }
2673     // -Xprof
2674     } else if (match_option(option, "-Xprof")) {
2675 #if INCLUDE_FPROF
2676       _has_profile = true;
2677 #else // INCLUDE_FPROF
2678       jio_fprintf(defaultStream::error_stream(),
2679         "Flat profiling is not supported in this VM.\n");
2680       return JNI_ERR;
2681 #endif // INCLUDE_FPROF
2682     // -Xconcurrentio
2683     } else if (match_option(option, "-Xconcurrentio")) {
2684       if (FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true) != Flag::SUCCESS) {
2685         return JNI_EINVAL;
2686       }
2687       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2688         return JNI_EINVAL;
2689       }
2690       if (FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1) != Flag::SUCCESS) {
2691         return JNI_EINVAL;
2692       }
2693       if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
2694         return JNI_EINVAL;
2695       }
2696       if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
2697         return JNI_EINVAL;
2698       }
2699 
2700       // -Xinternalversion
2701     } else if (match_option(option, "-Xinternalversion")) {
2702       jio_fprintf(defaultStream::output_stream(), "%s\n",
2703                   VM_Version::internal_vm_info_string());
2704       vm_exit(0);
2705 #ifndef PRODUCT
2706     // -Xprintflags
2707     } else if (match_option(option, "-Xprintflags")) {
2708       CommandLineFlags::printFlags(tty, false);
2709       vm_exit(0);
2710 #endif
2711     // -D
2712     } else if (match_option(option, "-D", &tail)) {
2713       const char* value;
2714       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2715             *value!= '\0' && strcmp(value, "\"\"") != 0) {
2716         // abort if -Djava.endorsed.dirs is set
2717         jio_fprintf(defaultStream::output_stream(),
2718           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2719           "in modular form will be supported via the concept of upgradeable modules.\n", value);
2720         return JNI_EINVAL;
2721       }
2722       if (match_option(option, "-Djava.ext.dirs=", &value) &&
2723             *value != '\0' && strcmp(value, "\"\"") != 0) {
2724         // abort if -Djava.ext.dirs is set
2725         jio_fprintf(defaultStream::output_stream(),
2726           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2727         return JNI_EINVAL;
2728       }
2729 
2730       if (!add_property(tail)) {
2731         return JNI_ENOMEM;
2732       }
2733       // Out of the box management support
2734       if (match_option(option, "-Dcom.sun.management", &tail)) {
2735 #if INCLUDE_MANAGEMENT
2736         if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
2737           return JNI_EINVAL;
2738         }
2739 #else
2740         jio_fprintf(defaultStream::output_stream(),
2741           "-Dcom.sun.management is not supported in this VM.\n");
2742         return JNI_ERR;
2743 #endif
2744       }
2745     // -Xint
2746     } else if (match_option(option, "-Xint")) {
2747           set_mode_flags(_int);
2748     // -Xmixed
2749     } else if (match_option(option, "-Xmixed")) {
2750           set_mode_flags(_mixed);
2751     // -Xcomp
2752     } else if (match_option(option, "-Xcomp")) {
2753       // for testing the compiler; turn off all flags that inhibit compilation
2754           set_mode_flags(_comp);
2755     // -Xshare:dump
2756     } else if (match_option(option, "-Xshare:dump")) {
2757       if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
2758         return JNI_EINVAL;
2759       }
2760       set_mode_flags(_int);     // Prevent compilation, which creates objects
2761     // -Xshare:on
2762     } else if (match_option(option, "-Xshare:on")) {
2763       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
2764         return JNI_EINVAL;
2765       }
2766       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
2767         return JNI_EINVAL;
2768       }
2769     // -Xshare:auto
2770     } else if (match_option(option, "-Xshare:auto")) {
2771       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
2772         return JNI_EINVAL;
2773       }
2774       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
2775         return JNI_EINVAL;
2776       }
2777     // -Xshare:off
2778     } else if (match_option(option, "-Xshare:off")) {
2779       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
2780         return JNI_EINVAL;
2781       }
2782       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
2783         return JNI_EINVAL;
2784       }
2785     // -Xverify
2786     } else if (match_option(option, "-Xverify", &tail)) {
2787       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
2788         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
2789           return JNI_EINVAL;
2790         }
2791         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
2792           return JNI_EINVAL;
2793         }
2794       } else if (strcmp(tail, ":remote") == 0) {
2795         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
2796           return JNI_EINVAL;
2797         }
2798         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
2799           return JNI_EINVAL;
2800         }
2801       } else if (strcmp(tail, ":none") == 0) {
2802         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
2803           return JNI_EINVAL;
2804         }
2805         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
2806           return JNI_EINVAL;
2807         }
2808       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
2809         return JNI_EINVAL;
2810       }
2811     // -Xdebug
2812     } else if (match_option(option, "-Xdebug")) {
2813       // note this flag has been used, then ignore
2814       set_xdebug_mode(true);
2815     // -Xnoagent
2816     } else if (match_option(option, "-Xnoagent")) {
2817       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
2818     } else if (match_option(option, "-Xloggc:", &tail)) {
2819       // Redirect GC output to the file. -Xloggc:<filename>
2820       // ostream_init_log(), when called will use this filename
2821       // to initialize a fileStream.
2822       _gc_log_filename = os::strdup_check_oom(tail);
2823      if (!is_filename_valid(_gc_log_filename)) {
2824        jio_fprintf(defaultStream::output_stream(),
2825                   "Invalid file name for use with -Xloggc: Filename can only contain the "
2826                   "characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"
2827                   "Note %%p or %%t can only be used once\n", _gc_log_filename);
2828         return JNI_EINVAL;
2829       }
2830       if (FLAG_SET_CMDLINE(bool, PrintGC, true) != Flag::SUCCESS) {
2831         return JNI_EINVAL;
2832       }
2833       if (FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true) != Flag::SUCCESS) {
2834         return JNI_EINVAL;
2835       }
2836     // JNI hooks
2837     } else if (match_option(option, "-Xcheck", &tail)) {
2838       if (!strcmp(tail, ":jni")) {
2839 #if !INCLUDE_JNI_CHECK
2840         warning("JNI CHECKING is not supported in this VM");
2841 #else
2842         CheckJNICalls = true;
2843 #endif // INCLUDE_JNI_CHECK
2844       } else if (is_bad_option(option, args->ignoreUnrecognized,
2845                                      "check")) {
2846         return JNI_EINVAL;
2847       }
2848     } else if (match_option(option, "vfprintf")) {
2849       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
2850     } else if (match_option(option, "exit")) {
2851       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
2852     } else if (match_option(option, "abort")) {
2853       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
2854     // -XX:+AggressiveHeap
2855     } else if (match_option(option, "-XX:+AggressiveHeap")) {
2856 
2857       // This option inspects the machine and attempts to set various
2858       // parameters to be optimal for long-running, memory allocation
2859       // intensive jobs.  It is intended for machines with large
2860       // amounts of cpu and memory.
2861 
2862       // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
2863       // VM, but we may not be able to represent the total physical memory
2864       // available (like having 8gb of memory on a box but using a 32bit VM).
2865       // Thus, we need to make sure we're using a julong for intermediate
2866       // calculations.
2867       julong initHeapSize;
2868       julong total_memory = os::physical_memory();
2869 
2870       if (total_memory < (julong)256*M) {
2871         jio_fprintf(defaultStream::error_stream(),
2872                     "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
2873         vm_exit(1);
2874       }
2875 
2876       // The heap size is half of available memory, or (at most)
2877       // all of possible memory less 160mb (leaving room for the OS
2878       // when using ISM).  This is the maximum; because adaptive sizing
2879       // is turned on below, the actual space used may be smaller.
2880 
2881       initHeapSize = MIN2(total_memory / (julong)2,
2882                           total_memory - (julong)160*M);
2883 
2884       initHeapSize = limit_by_allocatable_memory(initHeapSize);
2885 
2886       if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2887          if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, initHeapSize) != Flag::SUCCESS) {
2888            return JNI_EINVAL;
2889          }
2890          if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, initHeapSize) != Flag::SUCCESS) {
2891            return JNI_EINVAL;
2892          }
2893          // Currently the minimum size and the initial heap sizes are the same.
2894          set_min_heap_size(initHeapSize);
2895       }
2896       if (FLAG_IS_DEFAULT(NewSize)) {
2897          // Make the young generation 3/8ths of the total heap.
2898          if (FLAG_SET_CMDLINE(size_t, NewSize,
2899                                 ((julong)MaxHeapSize / (julong)8) * (julong)3) != Flag::SUCCESS) {
2900            return JNI_EINVAL;
2901          }
2902          if (FLAG_SET_CMDLINE(size_t, MaxNewSize, NewSize) != Flag::SUCCESS) {
2903            return JNI_EINVAL;
2904          }
2905       }
2906 
2907 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
2908       FLAG_SET_DEFAULT(UseLargePages, true);
2909 #endif
2910 
2911       // Increase some data structure sizes for efficiency
2912       if (FLAG_SET_CMDLINE(size_t, BaseFootPrintEstimate, MaxHeapSize) != Flag::SUCCESS) {
2913         return JNI_EINVAL;
2914       }
2915       if (FLAG_SET_CMDLINE(bool, ResizeTLAB, false) != Flag::SUCCESS) {
2916         return JNI_EINVAL;
2917       }
2918       if (FLAG_SET_CMDLINE(size_t, TLABSize, 256*K) != Flag::SUCCESS) {
2919         return JNI_EINVAL;
2920       }
2921 
2922       // See the OldPLABSize comment below, but replace 'after promotion'
2923       // with 'after copying'.  YoungPLABSize is the size of the survivor
2924       // space per-gc-thread buffers.  The default is 4kw.
2925       if (FLAG_SET_CMDLINE(size_t, YoungPLABSize, 256*K) != Flag::SUCCESS) {      // Note: this is in words
2926         return JNI_EINVAL;
2927       }
2928 
2929       // OldPLABSize is the size of the buffers in the old gen that
2930       // UseParallelGC uses to promote live data that doesn't fit in the
2931       // survivor spaces.  At any given time, there's one for each gc thread.
2932       // The default size is 1kw. These buffers are rarely used, since the
2933       // survivor spaces are usually big enough.  For specjbb, however, there
2934       // are occasions when there's lots of live data in the young gen
2935       // and we end up promoting some of it.  We don't have a definite
2936       // explanation for why bumping OldPLABSize helps, but the theory
2937       // is that a bigger PLAB results in retaining something like the
2938       // original allocation order after promotion, which improves mutator
2939       // locality.  A minor effect may be that larger PLABs reduce the
2940       // number of PLAB allocation events during gc.  The value of 8kw
2941       // was arrived at by experimenting with specjbb.
2942       if (FLAG_SET_CMDLINE(size_t, OldPLABSize, 8*K) != Flag::SUCCESS) {  // Note: this is in words
2943         return JNI_EINVAL;
2944       }
2945 
2946       // Enable parallel GC and adaptive generation sizing
2947       if (FLAG_SET_CMDLINE(bool, UseParallelGC, true) != Flag::SUCCESS) {
2948         return JNI_EINVAL;
2949       }
2950       FLAG_SET_DEFAULT(ParallelGCThreads,
2951                        Abstract_VM_Version::parallel_worker_threads());
2952 
2953       // Encourage steady state memory management
2954       if (FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100) != Flag::SUCCESS) {
2955         return JNI_EINVAL;
2956       }
2957 
2958       // This appears to improve mutator locality
2959       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2960         return JNI_EINVAL;
2961       }
2962 
2963       // Get around early Solaris scheduling bug
2964       // (affinity vs other jobs on system)
2965       // but disallow DR and offlining (5008695).
2966       if (FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true) != Flag::SUCCESS) {
2967         return JNI_EINVAL;
2968       }
2969 
2970     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
2971     // and the last option wins.
2972     } else if (match_option(option, "-XX:+NeverTenure")) {
2973       if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
2974         return JNI_EINVAL;
2975       }
2976       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
2977         return JNI_EINVAL;
2978       }
2979       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
2980         return JNI_EINVAL;
2981       }
2982     } else if (match_option(option, "-XX:+AlwaysTenure")) {
2983       if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
2984         return JNI_EINVAL;
2985       }
2986       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
2987         return JNI_EINVAL;
2988       }
2989       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
2990         return JNI_EINVAL;
2991       }
2992     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
2993       uintx max_tenuring_thresh = 0;
2994       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
2995         jio_fprintf(defaultStream::error_stream(),
2996                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
2997         return JNI_EINVAL;
2998       }
2999 
3000       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
3001         return JNI_EINVAL;
3002       }
3003 
3004       if (MaxTenuringThreshold == 0) {
3005         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3006           return JNI_EINVAL;
3007         }
3008         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3009           return JNI_EINVAL;
3010         }
3011       } else {
3012         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3013           return JNI_EINVAL;
3014         }
3015         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3016           return JNI_EINVAL;
3017         }
3018       }
3019     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3020       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
3021         return JNI_EINVAL;
3022       }
3023       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
3024         return JNI_EINVAL;
3025       }
3026     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3027       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
3028         return JNI_EINVAL;
3029       }
3030       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3031         return JNI_EINVAL;
3032       }
3033     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3034 #if defined(DTRACE_ENABLED)
3035       if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3036         return JNI_EINVAL;
3037       }
3038       if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3039         return JNI_EINVAL;
3040       }
3041       if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3042         return JNI_EINVAL;
3043       }
3044       if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3045         return JNI_EINVAL;
3046       }
3047 #else // defined(DTRACE_ENABLED)
3048       jio_fprintf(defaultStream::error_stream(),
3049                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3050       return JNI_EINVAL;
3051 #endif // defined(DTRACE_ENABLED)
3052 #ifdef ASSERT
3053     } else if (match_option(option, "-XX:+FullGCALot")) {
3054       if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3055         return JNI_EINVAL;
3056       }
3057       // disable scavenge before parallel mark-compact
3058       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3059         return JNI_EINVAL;
3060       }
3061 #endif
3062     } else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||
3063                match_option(option, "-XX:G1MarkStackSize=", &tail)) {
3064       julong stack_size = 0;
3065       ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);
3066       if (errcode != arg_in_range) {
3067         jio_fprintf(defaultStream::error_stream(),
3068                     "Invalid mark stack size: %s\n", option->optionString);
3069         describe_range_error(errcode);
3070         return JNI_EINVAL;
3071       }
3072       jio_fprintf(defaultStream::error_stream(),
3073         "Please use -XX:MarkStackSize in place of "
3074         "-XX:CMSMarkStackSize or -XX:G1MarkStackSize in the future\n");
3075       if (FLAG_SET_CMDLINE(size_t, MarkStackSize, stack_size) != Flag::SUCCESS) {
3076         return JNI_EINVAL;
3077       }
3078     } else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {
3079       julong max_stack_size = 0;
3080       ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);
3081       if (errcode != arg_in_range) {
3082         jio_fprintf(defaultStream::error_stream(),
3083                     "Invalid maximum mark stack size: %s\n",
3084                     option->optionString);
3085         describe_range_error(errcode);
3086         return JNI_EINVAL;
3087       }
3088       jio_fprintf(defaultStream::error_stream(),
3089          "Please use -XX:MarkStackSizeMax in place of "
3090          "-XX:CMSMarkStackSizeMax in the future\n");
3091       if (FLAG_SET_CMDLINE(size_t, MarkStackSizeMax, max_stack_size) != Flag::SUCCESS) {
3092         return JNI_EINVAL;
3093       }
3094     } else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||
3095                match_option(option, "-XX:ParallelCMSThreads=", &tail)) {
3096       uintx conc_threads = 0;
3097       if (!parse_uintx(tail, &conc_threads, 1)) {
3098         jio_fprintf(defaultStream::error_stream(),
3099                     "Invalid concurrent threads: %s\n", option->optionString);
3100         return JNI_EINVAL;
3101       }
3102       jio_fprintf(defaultStream::error_stream(),
3103         "Please use -XX:ConcGCThreads in place of "
3104         "-XX:ParallelMarkingThreads or -XX:ParallelCMSThreads in the future\n");
3105       if (FLAG_SET_CMDLINE(uint, ConcGCThreads, conc_threads) != Flag::SUCCESS) {
3106         return JNI_EINVAL;
3107       }
3108     } else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {
3109       julong max_direct_memory_size = 0;
3110       ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);
3111       if (errcode != arg_in_range) {
3112         jio_fprintf(defaultStream::error_stream(),
3113                     "Invalid maximum direct memory size: %s\n",
3114                     option->optionString);
3115         describe_range_error(errcode);
3116         return JNI_EINVAL;
3117       }
3118       if (FLAG_SET_CMDLINE(size_t, MaxDirectMemorySize, max_direct_memory_size) != Flag::SUCCESS) {
3119         return JNI_EINVAL;
3120       }
3121 #if !INCLUDE_MANAGEMENT
3122     } else if (match_option(option, "-XX:+ManagementServer")) {
3123         jio_fprintf(defaultStream::error_stream(),
3124           "ManagementServer is not supported in this VM.\n");
3125         return JNI_ERR;
3126 #endif // INCLUDE_MANAGEMENT
3127     // CreateMinidumpOnCrash is removed, and replaced by CreateCoredumpOnCrash
3128     } else if (match_option(option, "-XX:+CreateMinidumpOnCrash")) {
3129       if (FLAG_SET_CMDLINE(bool, CreateCoredumpOnCrash, true) != Flag::SUCCESS) {
3130         return JNI_EINVAL;
3131       }
3132       jio_fprintf(defaultStream::output_stream(),
3133           "CreateMinidumpOnCrash is replaced by CreateCoredumpOnCrash: CreateCoredumpOnCrash is on\n");
3134     } else if (match_option(option, "-XX:-CreateMinidumpOnCrash")) {
3135       if (FLAG_SET_CMDLINE(bool, CreateCoredumpOnCrash, false) != Flag::SUCCESS) {
3136         return JNI_EINVAL;
3137       }
3138       jio_fprintf(defaultStream::output_stream(),
3139           "CreateMinidumpOnCrash is replaced by CreateCoredumpOnCrash: CreateCoredumpOnCrash is off\n");
3140     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3141       // Skip -XX:Flags= since that case has already been handled
3142       if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
3143         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3144           return JNI_EINVAL;
3145         }
3146       }
3147     // Unknown option
3148     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3149       return JNI_ERR;
3150     }
3151   }
3152 
3153   // PrintSharedArchiveAndExit will turn on
3154   //   -Xshare:on
3155   //   -XX:+TraceClassPaths
3156   if (PrintSharedArchiveAndExit) {
3157     if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3158       return JNI_EINVAL;
3159     }
3160     if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3161       return JNI_EINVAL;
3162     }
3163     if (FLAG_SET_CMDLINE(bool, TraceClassPaths, true) != Flag::SUCCESS) {
3164       return JNI_EINVAL;
3165     }
3166   }
3167 
3168   // Change the default value for flags  which have different default values
3169   // when working with older JDKs.
3170 #ifdef LINUX
3171  if (JDK_Version::current().compare_major(6) <= 0 &&
3172       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3173     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3174   }
3175 #endif // LINUX
3176   fix_appclasspath();
3177   return JNI_OK;
3178 }
3179 
3180 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3181 //
3182 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3183 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3184 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3185 // path is treated as the current directory.
3186 //
3187 // This causes problems with CDS, which requires that all directories specified in the classpath
3188 // must be empty. In most cases, applications do NOT want to load classes from the current
3189 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3190 // scripts compatible with CDS.
3191 void Arguments::fix_appclasspath() {
3192   if (IgnoreEmptyClassPaths) {
3193     const char separator = *os::path_separator();
3194     const char* src = _java_class_path->value();
3195 
3196     // skip over all the leading empty paths
3197     while (*src == separator) {
3198       src ++;
3199     }
3200 
3201     char* copy = os::strdup_check_oom(src, mtInternal);
3202 
3203     // trim all trailing empty paths
3204     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3205       *tail = '\0';
3206     }
3207 
3208     char from[3] = {separator, separator, '\0'};
3209     char to  [2] = {separator, '\0'};
3210     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3211       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3212       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3213     }
3214 
3215     _java_class_path->set_value(copy);
3216     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3217   }
3218 
3219   if (!PrintSharedArchiveAndExit) {
3220     ClassLoader::trace_class_path("[classpath: ", _java_class_path->value());
3221   }
3222 }
3223 
3224 static bool has_jar_files(const char* directory) {
3225   DIR* dir = os::opendir(directory);
3226   if (dir == NULL) return false;
3227 
3228   struct dirent *entry;
3229   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
3230   bool hasJarFile = false;
3231   while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3232     const char* name = entry->d_name;
3233     const char* ext = name + strlen(name) - 4;
3234     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3235   }
3236   FREE_C_HEAP_ARRAY(char, dbuf);
3237   os::closedir(dir);
3238   return hasJarFile ;
3239 }
3240 
3241 static int check_non_empty_dirs(const char* path) {
3242   const char separator = *os::path_separator();
3243   const char* const end = path + strlen(path);
3244   int nonEmptyDirs = 0;
3245   while (path < end) {
3246     const char* tmp_end = strchr(path, separator);
3247     if (tmp_end == NULL) {
3248       if (has_jar_files(path)) {
3249         nonEmptyDirs++;
3250         jio_fprintf(defaultStream::output_stream(),
3251           "Non-empty directory: %s\n", path);
3252       }
3253       path = end;
3254     } else {
3255       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
3256       memcpy(dirpath, path, tmp_end - path);
3257       dirpath[tmp_end - path] = '\0';
3258       if (has_jar_files(dirpath)) {
3259         nonEmptyDirs++;
3260         jio_fprintf(defaultStream::output_stream(),
3261           "Non-empty directory: %s\n", dirpath);
3262       }
3263       FREE_C_HEAP_ARRAY(char, dirpath);
3264       path = tmp_end + 1;
3265     }
3266   }
3267   return nonEmptyDirs;
3268 }
3269 
3270 jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
3271   // check if the default lib/endorsed directory exists; if so, error
3272   char path[JVM_MAXPATHLEN];
3273   const char* fileSep = os::file_separator();
3274   sprintf(path, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3275 
3276   if (CheckEndorsedAndExtDirs) {
3277     int nonEmptyDirs = 0;
3278     // check endorsed directory
3279     nonEmptyDirs += check_non_empty_dirs(path);
3280     // check the extension directories
3281     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3282     if (nonEmptyDirs > 0) {
3283       return JNI_ERR;
3284     }
3285   }
3286 
3287   DIR* dir = os::opendir(path);
3288   if (dir != NULL) {
3289     jio_fprintf(defaultStream::output_stream(),
3290       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3291       "in modular form will be supported via the concept of upgradeable modules.\n");
3292     os::closedir(dir);
3293     return JNI_ERR;
3294   }
3295 
3296   sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3297   dir = os::opendir(path);
3298   if (dir != NULL) {
3299     jio_fprintf(defaultStream::output_stream(),
3300       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3301       "Use -classpath instead.\n.");
3302     os::closedir(dir);
3303     return JNI_ERR;
3304   }
3305 
3306   if (scp_assembly_required) {
3307     // Assemble the bootclasspath elements into the final path.
3308     Arguments::set_sysclasspath(scp_p->combined_path());
3309   }
3310 
3311   // This must be done after all arguments have been processed.
3312   // java_compiler() true means set to "NONE" or empty.
3313   if (java_compiler() && !xdebug_mode()) {
3314     // For backwards compatibility, we switch to interpreted mode if
3315     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3316     // not specified.
3317     set_mode_flags(_int);
3318   }
3319 
3320   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3321   // but like -Xint, leave compilation thresholds unaffected.
3322   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3323   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3324     set_mode_flags(_int);
3325   }
3326 
3327   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3328   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3329     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3330   }
3331 
3332 #ifndef COMPILER2
3333   // Don't degrade server performance for footprint
3334   if (FLAG_IS_DEFAULT(UseLargePages) &&
3335       MaxHeapSize < LargePageHeapSizeThreshold) {
3336     // No need for large granularity pages w/small heaps.
3337     // Note that large pages are enabled/disabled for both the
3338     // Java heap and the code cache.
3339     FLAG_SET_DEFAULT(UseLargePages, false);
3340   }
3341 
3342 #else
3343   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3344     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3345   }
3346 #endif
3347 
3348 #ifndef TIERED
3349   // Tiered compilation is undefined.
3350   UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
3351 #endif
3352 
3353   // If we are running in a headless jre, force java.awt.headless property
3354   // to be true unless the property has already been set.
3355   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3356   if (os::is_headless_jre()) {
3357     const char* headless = Arguments::get_property("java.awt.headless");
3358     if (headless == NULL) {
3359       const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3360       if (headless_env == NULL) {
3361         if (!add_property("java.awt.headless=true")) {
3362           return JNI_ENOMEM;
3363         }
3364       } else {
3365         char buffer[256];
3366         jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3367         if (!add_property(buffer)) {
3368           return JNI_ENOMEM;
3369         }
3370       }
3371     }
3372   }
3373 
3374   if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3375     // CMS can only be used with ParNew
3376     FLAG_SET_ERGO(bool, UseParNewGC, true);
3377   }
3378 
3379   if (!check_vm_args_consistency()) {
3380     return JNI_ERR;
3381   }
3382 
3383   return JNI_OK;
3384 }
3385 
3386 jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3387   return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,
3388                                             scp_assembly_required_p);
3389 }
3390 
3391 jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3392   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,
3393                                             scp_assembly_required_p);
3394 }
3395 
3396 jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {
3397   char *buffer = ::getenv(name);
3398 
3399   // Don't check this variable if user has special privileges





3400   // (e.g. unix su command).
3401   if (buffer == NULL || os::have_special_privileges()) {
3402     return JNI_OK;
3403   }
3404 
3405   if ((buffer = os::strdup(buffer)) == NULL) {
3406     return JNI_ENOMEM;
3407   }
3408 
3409   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3410   jio_fprintf(defaultStream::error_stream(),
3411               "Picked up %s: %s\n", name, buffer);
3412   char* rd = buffer;                        // pointer to the input string (rd)
3413   while (true) {                            // repeat for all options in the input string
3414     while (isspace(*rd)) rd++;              // skip whitespace
3415     if (*rd == 0) break;                    // we re done when the input string is read completely
3416 
3417     // The output, option string, overwrites the input string.
3418     // Because of quoting, the pointer to the option string (wrt) may lag the pointer to
3419     // input string (rd).
3420     char* wrt = rd;
3421 
3422     JavaVMOption option;
3423     option.optionString = wrt;
3424     options->append(option);                // Fill in option
3425     while (*rd != 0 && !isspace(*rd)) {     // unquoted strings terminate with a space or NULL
3426       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3427         int quote = *rd;                    // matching quote to look for
3428         rd++;                               // don't copy open quote
3429         while (*rd != quote) {              // include everything (even spaces) up until quote
3430           if (*rd == 0) {                   // string termination means unmatched string
3431             jio_fprintf(defaultStream::error_stream(),
3432                         "Unmatched quote in %s\n", name);
3433             delete options;
3434             os::free(buffer);
3435             return JNI_ERR;
3436           }
3437           *wrt++ = *rd++;                   // copy to option string
3438         }
3439         rd++;                               // don't copy close quote
3440       } else {
3441         *wrt++ = *rd++;                     // copy to option string
3442       }
3443     }
3444     // Need to check if we're done before writing a NULL,
3445     // because the write could be to the byte that rd is pointing to.
3446     if (*rd++ == 0) {
3447       *wrt = 0;
3448       break;
3449     }
3450     *wrt = 0;                               // Zero terminate option
3451   }


3452   JavaVMOption* options_arr =
3453       NEW_C_HEAP_ARRAY_RETURN_NULL(JavaVMOption, options->length(), mtInternal);
3454   if (options_arr == NULL) {
3455     delete options;
3456     os::free(buffer);
3457     return JNI_ENOMEM;
3458   }
3459   for (int i = 0; i < options->length(); i++) {
3460     options_arr[i] = options->at(i);
3461   }
3462 
3463   // Construct JavaVMInitArgs structure and parse as if it was part of the command line
3464   JavaVMInitArgs vm_args;
3465   vm_args.version = JNI_VERSION_1_2;
3466   vm_args.options = options_arr;
3467   vm_args.nOptions = options->length();
3468   vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3469 
3470   if (PrintVMOptions) {
3471     const char* tail;
3472     for (int i = 0; i < vm_args.nOptions; i++) {
3473       const JavaVMOption *option = vm_args.options + i;
3474       if (match_option(option, "-XX:", &tail)) {
3475         logOption(tail);
3476       }
3477     }
3478   }
3479 
3480   jint result = parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p,
3481                                        Flag::ENVIRON_VAR);
3482   FREE_C_HEAP_ARRAY(JavaVMOption, options_arr);
3483   delete options;
3484   os::free(buffer);
3485   return result;
3486 }
3487 
3488 void Arguments::set_shared_spaces_flags() {
3489   if (DumpSharedSpaces) {
3490     if (RequireSharedSpaces) {
3491       warning("cannot dump shared archive while using shared archive");
3492     }
3493     UseSharedSpaces = false;
3494 #ifdef _LP64
3495     if (!UseCompressedOops || !UseCompressedClassPointers) {
3496       vm_exit_during_initialization(
3497         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3498     }
3499   } else {
3500     if (!UseCompressedOops || !UseCompressedClassPointers) {
3501       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3502     }
3503 #endif
3504   }
3505 }
3506 
3507 #if !INCLUDE_ALL_GCS
3508 static void force_serial_gc() {
3509   FLAG_SET_DEFAULT(UseSerialGC, true);
3510   UNSUPPORTED_GC_OPTION(UseG1GC);
3511   UNSUPPORTED_GC_OPTION(UseParallelGC);
3512   UNSUPPORTED_GC_OPTION(UseParallelOldGC);
3513   UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
3514   UNSUPPORTED_GC_OPTION(UseParNewGC);
3515 }
3516 #endif // INCLUDE_ALL_GCS
3517 
3518 // Sharing support
3519 // Construct the path to the archive
3520 static char* get_shared_archive_path() {
3521   char *shared_archive_path;
3522   if (SharedArchiveFile == NULL) {
3523     char jvm_path[JVM_MAXPATHLEN];
3524     os::jvm_path(jvm_path, sizeof(jvm_path));
3525     char *end = strrchr(jvm_path, *os::file_separator());
3526     if (end != NULL) *end = '\0';
3527     size_t jvm_path_len = strlen(jvm_path);
3528     size_t file_sep_len = strlen(os::file_separator());
3529     const size_t len = jvm_path_len + file_sep_len + 20;
3530     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtInternal);
3531     if (shared_archive_path != NULL) {
3532       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3533         jvm_path, os::file_separator());
3534     }
3535   } else {
3536     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtInternal);
3537   }
3538   return shared_archive_path;
3539 }
3540 
3541 #ifndef PRODUCT
3542 // Determine whether LogVMOutput should be implicitly turned on.
3543 static bool use_vm_log() {
3544   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3545       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3546       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3547       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3548       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3549     return true;
3550   }
3551 
3552 #ifdef COMPILER1
3553   if (PrintC1Statistics) {
3554     return true;
3555   }
3556 #endif // COMPILER1
3557 
3558 #ifdef COMPILER2
3559   if (PrintOptoAssembly || PrintOptoStatistics) {
3560     return true;
3561   }
3562 #endif // COMPILER2
3563 
3564   return false;
3565 }
3566 #endif // PRODUCT
3567 
3568 // Parse entry point called from JNI_CreateJavaVM
3569 
3570 jint Arguments::parse(const JavaVMInitArgs* args) {
3571 
3572   // Initialize ranges and constraints
3573   CommandLineFlagRangeList::init();
3574   CommandLineFlagConstraintList::init();
3575 
3576   // Remaining part of option string
3577   const char* tail;
3578 
3579   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3580   const char* hotspotrc = ".hotspotrc";
3581   bool settings_file_specified = false;
3582   bool needs_hotspotrc_warning = false;
3583 
3584   const char* flags_file;
3585   int index;
3586   for (index = 0; index < args->nOptions; index++) {
3587     const JavaVMOption *option = args->options + index;
3588     if (ArgumentsExt::process_options(option)) {
3589       continue;
3590     }
3591     if (match_option(option, "-XX:Flags=", &tail)) {
3592       flags_file = tail;
3593       settings_file_specified = true;
3594       continue;
3595     }
3596     if (match_option(option, "-XX:+PrintVMOptions")) {
3597       PrintVMOptions = true;
3598       continue;
3599     }
3600     if (match_option(option, "-XX:-PrintVMOptions")) {
3601       PrintVMOptions = false;
3602       continue;
3603     }
3604     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3605       IgnoreUnrecognizedVMOptions = true;
3606       continue;
3607     }
3608     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3609       IgnoreUnrecognizedVMOptions = false;
3610       continue;
3611     }
3612     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3613       CommandLineFlags::printFlags(tty, false);
3614       vm_exit(0);
3615     }
3616     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3617 #if INCLUDE_NMT
3618       // The launcher did not setup nmt environment variable properly.
3619       if (!MemTracker::check_launcher_nmt_support(tail)) {
3620         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3621       }
3622 
3623       // Verify if nmt option is valid.
3624       if (MemTracker::verify_nmt_option()) {
3625         // Late initialization, still in single-threaded mode.
3626         if (MemTracker::tracking_level() >= NMT_summary) {
3627           MemTracker::init();
3628         }
3629       } else {
3630         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3631       }
3632       continue;
3633 #else
3634       jio_fprintf(defaultStream::error_stream(),
3635         "Native Memory Tracking is not supported in this VM\n");
3636       return JNI_ERR;
3637 #endif
3638     }
3639 
3640 #ifndef PRODUCT
3641     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3642       CommandLineFlags::printFlags(tty, true);
3643       vm_exit(0);
3644     }
3645 #endif
3646   }







































3647 
3648   if (IgnoreUnrecognizedVMOptions) {
3649     // uncast const to modify the flag args->ignoreUnrecognized
3650     *(jboolean*)(&args->ignoreUnrecognized) = true;


3651   }
3652 
3653   // Parse specified settings file
3654   if (settings_file_specified) {
3655     if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
3656       return JNI_EINVAL;
3657     }
3658   } else {
3659 #ifdef ASSERT
3660     // Parse default .hotspotrc settings file
3661     if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
3662       return JNI_EINVAL;
3663     }
3664 #else
3665     struct stat buf;
3666     if (os::stat(hotspotrc, &buf) == 0) {
3667       needs_hotspotrc_warning = true;
3668     }
3669 #endif
3670   }
3671 
3672   if (PrintVMOptions) {
3673     for (index = 0; index < args->nOptions; index++) {
3674       const JavaVMOption *option = args->options + index;
3675       if (match_option(option, "-XX:", &tail)) {
3676         logOption(tail);
3677       }
3678     }
3679   }
3680 
3681   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
3682   jint result = parse_vm_init_args(args);





3683   if (result != JNI_OK) {
3684     return result;
3685   }
3686 
3687   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
3688   SharedArchivePath = get_shared_archive_path();
3689   if (SharedArchivePath == NULL) {
3690     return JNI_ENOMEM;
3691   }
3692 
3693   // Set up VerifySharedSpaces
3694   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
3695     VerifySharedSpaces = true;
3696   }
3697 
3698   // Delay warning until here so that we've had a chance to process
3699   // the -XX:-PrintWarnings flag
3700   if (needs_hotspotrc_warning) {
3701     warning("%s file is present but has been ignored.  "
3702             "Run with -XX:Flags=%s to load the file.",
3703             hotspotrc, hotspotrc);
3704   }
3705 
3706 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
3707   UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
3708 #endif
3709 
3710   ArgumentsExt::report_unsupported_options();
3711 
3712 #ifndef PRODUCT
3713   if (TraceBytecodesAt != 0) {
3714     TraceBytecodes = true;
3715   }
3716   if (CountCompiledCalls) {
3717     if (UseCounterDecay) {
3718       warning("UseCounterDecay disabled because CountCalls is set");
3719       UseCounterDecay = false;
3720     }
3721   }
3722 #endif // PRODUCT
3723 
3724   if (ScavengeRootsInCode == 0) {
3725     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3726       warning("forcing ScavengeRootsInCode non-zero");
3727     }
3728     ScavengeRootsInCode = 1;
3729   }
3730 
3731   if (PrintGCDetails) {
3732     // Turn on -verbose:gc options as well
3733     PrintGC = true;
3734   }
3735 
3736   // Set object alignment values.
3737   set_object_alignment();
3738 
3739 #if !INCLUDE_ALL_GCS
3740   force_serial_gc();
3741 #endif // INCLUDE_ALL_GCS
3742 #if !INCLUDE_CDS
3743   if (DumpSharedSpaces || RequireSharedSpaces) {
3744     jio_fprintf(defaultStream::error_stream(),
3745       "Shared spaces are not supported in this VM\n");
3746     return JNI_ERR;
3747   }
3748   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
3749     warning("Shared spaces are not supported in this VM");
3750     FLAG_SET_DEFAULT(UseSharedSpaces, false);
3751     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
3752   }
3753   no_shared_spaces("CDS Disabled");
3754 #endif // INCLUDE_CDS
3755 
3756   return JNI_OK;
3757 }
3758 
3759 jint Arguments::apply_ergo() {
3760 
3761   // Set flags based on ergonomics.
3762   set_ergonomics_flags();
3763 
3764   set_shared_spaces_flags();
3765 
3766   // Check the GC selections again.
3767   if (!check_gc_consistency()) {
3768     return JNI_EINVAL;
3769   }
3770 
3771   if (TieredCompilation) {
3772     set_tiered_flags();
3773   } else {
3774     int max_compilation_policy_choice = 1;
3775 #ifdef COMPILER2
3776     max_compilation_policy_choice = 2;
3777 #endif
3778     // Check if the policy is valid.
3779     if (CompilationPolicyChoice >= max_compilation_policy_choice) {
3780       vm_exit_during_initialization(
3781         "Incompatible compilation policy selected", NULL);
3782     }
3783     // Scale CompileThreshold
3784     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
3785     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
3786       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
3787     }
3788   }
3789 
3790 #ifdef COMPILER2
3791 #ifndef PRODUCT
3792   if (PrintIdealGraphLevel > 0) {
3793     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
3794   }
3795 #endif
3796 #endif
3797 
3798   // Set heap size based on available physical memory
3799   set_heap_size();
3800 
3801   ArgumentsExt::set_gc_specific_flags();
3802 
3803   // Initialize Metaspace flags and alignments
3804   Metaspace::ergo_initialize();
3805 
3806   // Set bytecode rewriting flags
3807   set_bytecode_flags();
3808 
3809   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
3810   set_aggressive_opts_flags();
3811 
3812   // Turn off biased locking for locking debug mode flags,
3813   // which are subtly different from each other but neither works with
3814   // biased locking
3815   if (UseHeavyMonitors
3816 #ifdef COMPILER1
3817       || !UseFastLocking
3818 #endif // COMPILER1
3819     ) {
3820     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
3821       // flag set to true on command line; warn the user that they
3822       // can't enable biased locking here
3823       warning("Biased Locking is not supported with locking debug flags"
3824               "; ignoring UseBiasedLocking flag." );
3825     }
3826     UseBiasedLocking = false;
3827   }
3828 
3829 #ifdef ZERO
3830   // Clear flags not supported on zero.
3831   FLAG_SET_DEFAULT(ProfileInterpreter, false);
3832   FLAG_SET_DEFAULT(UseBiasedLocking, false);
3833   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
3834   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
3835 #endif // CC_INTERP
3836 
3837 #ifdef COMPILER2
3838   if (!EliminateLocks) {
3839     EliminateNestedLocks = false;
3840   }
3841   if (!Inline) {
3842     IncrementalInline = false;
3843   }
3844 #ifndef PRODUCT
3845   if (!IncrementalInline) {
3846     AlwaysIncrementalInline = false;
3847   }
3848 #endif
3849   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
3850     // nothing to use the profiling, turn if off
3851     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
3852   }
3853 #endif
3854 
3855   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
3856     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
3857     DebugNonSafepoints = true;
3858   }
3859 
3860   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
3861     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
3862   }
3863 
3864 #ifndef PRODUCT
3865   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
3866     if (use_vm_log()) {
3867       LogVMOutput = true;
3868     }
3869   }
3870 #endif // PRODUCT
3871 
3872   if (PrintCommandLineFlags) {
3873     CommandLineFlags::printSetFlags(tty);
3874   }
3875 
3876   // Apply CPU specific policy for the BiasedLocking
3877   if (UseBiasedLocking) {
3878     if (!VM_Version::use_biased_locking() &&
3879         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
3880       UseBiasedLocking = false;
3881     }
3882   }
3883 #ifdef COMPILER2
3884   if (!UseBiasedLocking || EmitSync != 0) {
3885     UseOptoBiasInlining = false;
3886   }
3887 #endif
3888 
3889   return JNI_OK;
3890 }
3891 
3892 jint Arguments::adjust_after_os() {
3893   if (UseNUMA) {
3894     if (UseParallelGC || UseParallelOldGC) {
3895       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
3896          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
3897       }
3898     }
3899     // UseNUMAInterleaving is set to ON for all collectors and
3900     // platforms when UseNUMA is set to ON. NUMA-aware collectors
3901     // such as the parallel collector for Linux and Solaris will
3902     // interleave old gen and survivor spaces on top of NUMA
3903     // allocation policy for the eden space.
3904     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
3905     // all platforms and ParallelGC on Windows will interleave all
3906     // of the heap spaces across NUMA nodes.
3907     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
3908       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
3909     }
3910   }
3911   return JNI_OK;
3912 }
3913 
3914 // Any custom code post the final range and constraint check
3915 // can be done here. We pass a flag that specifies whether
3916 // the check passed successfully
3917 void Arguments::post_final_range_and_constraint_check(bool check_passed) {
3918   // This does not set the flag itself, but stores the value in a safe place for later usage.
3919   _min_heap_free_ratio = MinHeapFreeRatio;
3920   _max_heap_free_ratio = MaxHeapFreeRatio;
3921 }
3922 
3923 int Arguments::PropertyList_count(SystemProperty* pl) {
3924   int count = 0;
3925   while(pl != NULL) {
3926     count++;
3927     pl = pl->next();
3928   }
3929   return count;
3930 }
3931 
3932 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
3933   assert(key != NULL, "just checking");
3934   SystemProperty* prop;
3935   for (prop = pl; prop != NULL; prop = prop->next()) {
3936     if (strcmp(key, prop->key()) == 0) return prop->value();
3937   }
3938   return NULL;
3939 }
3940 
3941 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
3942   int count = 0;
3943   const char* ret_val = NULL;
3944 
3945   while(pl != NULL) {
3946     if(count >= index) {
3947       ret_val = pl->key();
3948       break;
3949     }
3950     count++;
3951     pl = pl->next();
3952   }
3953 
3954   return ret_val;
3955 }
3956 
3957 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
3958   int count = 0;
3959   char* ret_val = NULL;
3960 
3961   while(pl != NULL) {
3962     if(count >= index) {
3963       ret_val = pl->value();
3964       break;
3965     }
3966     count++;
3967     pl = pl->next();
3968   }
3969 
3970   return ret_val;
3971 }
3972 
3973 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
3974   SystemProperty* p = *plist;
3975   if (p == NULL) {
3976     *plist = new_p;
3977   } else {
3978     while (p->next() != NULL) {
3979       p = p->next();
3980     }
3981     p->set_next(new_p);
3982   }
3983 }
3984 
3985 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {
3986   if (plist == NULL)
3987     return;
3988 
3989   SystemProperty* new_p = new SystemProperty(k, v, true);
3990   PropertyList_add(plist, new_p);
3991 }
3992 
3993 void Arguments::PropertyList_add(SystemProperty *element) {
3994   PropertyList_add(&_system_properties, element);
3995 }
3996 
3997 // This add maintains unique property key in the list.
3998 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {
3999   if (plist == NULL)
4000     return;
4001 
4002   // If property key exist then update with new value.
4003   SystemProperty* prop;
4004   for (prop = *plist; prop != NULL; prop = prop->next()) {
4005     if (strcmp(k, prop->key()) == 0) {
4006       if (append) {
4007         prop->append_value(v);
4008       } else {
4009         prop->set_value(v);
4010       }
4011       return;
4012     }
4013   }
4014 
4015   PropertyList_add(plist, k, v);
4016 }
4017 
4018 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4019 // Returns true if all of the source pointed by src has been copied over to
4020 // the destination buffer pointed by buf. Otherwise, returns false.
4021 // Notes:
4022 // 1. If the length (buflen) of the destination buffer excluding the
4023 // NULL terminator character is not long enough for holding the expanded
4024 // pid characters, it also returns false instead of returning the partially
4025 // expanded one.
4026 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4027 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4028                                 char* buf, size_t buflen) {
4029   const char* p = src;
4030   char* b = buf;
4031   const char* src_end = &src[srclen];
4032   char* buf_end = &buf[buflen - 1];
4033 
4034   while (p < src_end && b < buf_end) {
4035     if (*p == '%') {
4036       switch (*(++p)) {
4037       case '%':         // "%%" ==> "%"
4038         *b++ = *p++;
4039         break;
4040       case 'p':  {       //  "%p" ==> current process id
4041         // buf_end points to the character before the last character so
4042         // that we could write '\0' to the end of the buffer.
4043         size_t buf_sz = buf_end - b + 1;
4044         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4045 
4046         // if jio_snprintf fails or the buffer is not long enough to hold
4047         // the expanded pid, returns false.
4048         if (ret < 0 || ret >= (int)buf_sz) {
4049           return false;
4050         } else {
4051           b += ret;
4052           assert(*b == '\0', "fail in copy_expand_pid");
4053           if (p == src_end && b == buf_end + 1) {
4054             // reach the end of the buffer.
4055             return true;
4056           }
4057         }
4058         p++;
4059         break;
4060       }
4061       default :
4062         *b++ = '%';
4063       }
4064     } else {
4065       *b++ = *p++;
4066     }
4067   }
4068   *b = '\0';
4069   return (p == src_end); // return false if not all of the source was copied
4070 }
--- EOF ---