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