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