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