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