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