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 uintx  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 
  96 char*  Arguments::SharedArchivePath             = NULL;
  97 
  98 AgentLibraryList Arguments::_libraryList;
  99 AgentLibraryList Arguments::_agentList;
 100 
 101 abort_hook_t     Arguments::_abort_hook         = NULL;
 102 exit_hook_t      Arguments::_exit_hook          = NULL;
 103 vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
 104 
 105 
 106 SystemProperty *Arguments::_sun_boot_library_path = NULL;
 107 SystemProperty *Arguments::_java_library_path = NULL;
 108 SystemProperty *Arguments::_java_home = NULL;
 109 SystemProperty *Arguments::_java_class_path = NULL;
 110 SystemProperty *Arguments::_sun_boot_class_path = NULL;
 111 
 112 char* Arguments::_ext_dirs = NULL;
 113 
 114 // Check if head of 'option' matches 'name', and sets 'tail' to the remaining
 115 // part of the option string.
 116 static bool match_option(const JavaVMOption *option, const char* name,
 117                          const char** tail) {
 118   int len = (int)strlen(name);
 119   if (strncmp(option->optionString, name, len) == 0) {
 120     *tail = option->optionString + len;
 121     return true;
 122   } else {
 123     return false;
 124   }
 125 }
 126 
 127 // Check if 'option' matches 'name'. No "tail" is allowed.
 128 static bool match_option(const JavaVMOption *option, const char* name) {
 129   const char* tail = NULL;
 130   bool result = match_option(option, name, &tail);
 131   if (tail != NULL && *tail == '\0') {
 132     return result;
 133   } else {
 134     return false;
 135   }
 136 }
 137 
 138 // Return true if any of the strings in null-terminated array 'names' matches.
 139 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
 140 // the option must match exactly.
 141 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
 142   bool tail_allowed) {
 143   for (/* empty */; *names != NULL; ++names) {
 144     if (match_option(option, *names, tail)) {
 145       if (**tail == '\0' || tail_allowed && **tail == ':') {
 146         return true;
 147       }
 148     }
 149   }
 150   return false;
 151 }
 152 
 153 static void logOption(const char* opt) {
 154   if (PrintVMOptions) {
 155     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
 156   }
 157 }
 158 
 159 // Process java launcher properties.
 160 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
 161   // See if sun.java.launcher, sun.java.launcher.is_altjvm or
 162   // sun.java.launcher.pid is defined.
 163   // Must do this before setting up other system properties,
 164   // as some of them may depend on launcher type.
 165   for (int index = 0; index < args->nOptions; index++) {
 166     const JavaVMOption* option = args->options + index;
 167     const char* tail;
 168 
 169     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
 170       process_java_launcher_argument(tail, option->extraInfo);
 171       continue;
 172     }
 173     if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
 174       if (strcmp(tail, "true") == 0) {
 175         _sun_java_launcher_is_altjvm = true;
 176       }
 177       continue;
 178     }
 179     if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
 180       _sun_java_launcher_pid = atoi(tail);
 181       continue;
 182     }
 183   }
 184 }
 185 
 186 // Initialize system properties key and value.
 187 void Arguments::init_system_properties() {
 188 
 189   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
 190                                                                  "Java Virtual Machine Specification",  false));
 191   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
 192   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
 193   PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
 194 
 195   // Following are JVMTI agent writable properties.
 196   // Properties values are set to NULL and they are
 197   // os specific they are initialized in os::init_system_properties_values().
 198   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
 199   _java_library_path = new SystemProperty("java.library.path", NULL,  true);
 200   _java_home =  new SystemProperty("java.home", NULL,  true);
 201   _sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL,  true);
 202 
 203   _java_class_path = new SystemProperty("java.class.path", "",  true);
 204 
 205   // Add to System Property list.
 206   PropertyList_add(&_system_properties, _sun_boot_library_path);
 207   PropertyList_add(&_system_properties, _java_library_path);
 208   PropertyList_add(&_system_properties, _java_home);
 209   PropertyList_add(&_system_properties, _java_class_path);
 210   PropertyList_add(&_system_properties, _sun_boot_class_path);
 211 
 212   // Set OS specific system properties values
 213   os::init_system_properties_values();
 214 }
 215 
 216 
 217   // Update/Initialize System properties after JDK version number is known
 218 void Arguments::init_version_specific_system_properties() {
 219   enum { bufsz = 16 };
 220   char buffer[bufsz];
 221   const char* spec_vendor = "Sun Microsystems Inc.";
 222   uint32_t spec_version = 0;
 223 
 224   spec_vendor = "Oracle Corporation";
 225   spec_version = JDK_Version::current().major_version();
 226   jio_snprintf(buffer, bufsz, "1." UINT32_FORMAT, spec_version);
 227 
 228   PropertyList_add(&_system_properties,
 229       new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
 230   PropertyList_add(&_system_properties,
 231       new SystemProperty("java.vm.specification.version", buffer, false));
 232   PropertyList_add(&_system_properties,
 233       new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
 234 }
 235 
 236 /**
 237  * Provide a slightly more user-friendly way of eliminating -XX flags.
 238  * When a flag is eliminated, it can be added to this list in order to
 239  * continue accepting this flag on the command-line, while issuing a warning
 240  * and ignoring the value.  Once the JDK version reaches the 'accept_until'
 241  * limit, we flatly refuse to admit the existence of the flag.  This allows
 242  * a flag to die correctly over JDK releases using HSX.
 243  * But now that HSX is no longer supported only options with a future
 244  * accept_until value need to be listed, and the list can be pruned
 245  * on each major release.
 246  */
 247 typedef struct {
 248   const char* name;
 249   JDK_Version obsoleted_in; // when the flag went away
 250   JDK_Version accept_until; // which version to start denying the existence
 251 } ObsoleteFlag;
 252 
 253 static ObsoleteFlag obsolete_jvm_flags[] = {
 254   { "UseOldInlining",                JDK_Version::jdk(9), JDK_Version::jdk(10) },
 255   { "SafepointPollOffset",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
 256   { "UseBoundThreads",               JDK_Version::jdk(9), JDK_Version::jdk(10) },
 257   { "DefaultThreadPriority",         JDK_Version::jdk(9), JDK_Version::jdk(10) },
 258   { "NoYieldsInMicrolock",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
 259   { "BackEdgeThreshold",             JDK_Version::jdk(9), JDK_Version::jdk(10) },
 260   { "UseNewReflection",              JDK_Version::jdk(9), JDK_Version::jdk(10) },
 261   { "ReflectionWrapResolutionErrors",JDK_Version::jdk(9), JDK_Version::jdk(10) },
 262   { "VerifyReflectionBytecodes",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
 263   { "AutoShutdownNMT",               JDK_Version::jdk(9), JDK_Version::jdk(10) },
 264   { "NmethodSweepFraction",          JDK_Version::jdk(9), JDK_Version::jdk(10) },
 265   { "NmethodSweepCheckInterval",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
 266   { "CodeCacheMinimumFreeSpace",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
 267 #ifndef ZERO
 268   { "UseFastAccessorMethods",        JDK_Version::jdk(9), JDK_Version::jdk(10) },
 269   { "UseFastEmptyMethods",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
 270 #endif // ZERO
 271   { "UseCompilerSafepoints",         JDK_Version::jdk(9), JDK_Version::jdk(10) },
 272   { "AdaptiveSizePausePolicy",       JDK_Version::jdk(9), JDK_Version::jdk(10) },
 273   { "ParallelGCRetainPLAB",          JDK_Version::jdk(9), JDK_Version::jdk(10) },
 274   { NULL, JDK_Version(0), JDK_Version(0) }
 275 };
 276 
 277 // Returns true if the flag is obsolete and fits into the range specified
 278 // for being ignored.  In the case that the flag is ignored, the 'version'
 279 // value is filled in with the version number when the flag became
 280 // obsolete so that that value can be displayed to the user.
 281 bool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {
 282   int i = 0;
 283   assert(version != NULL, "Must provide a version buffer");
 284   while (obsolete_jvm_flags[i].name != NULL) {
 285     const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];
 286     // <flag>=xxx form
 287     // [-|+]<flag> form
 288     size_t len = strlen(flag_status.name);
 289     if (((strncmp(flag_status.name, s, len) == 0) &&
 290          (strlen(s) == len)) ||
 291         ((s[0] == '+' || s[0] == '-') &&
 292          (strncmp(flag_status.name, &s[1], len) == 0) &&
 293          (strlen(&s[1]) == 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   bool has_plus_minus = (*arg == '+' || *arg == '-');
 810   const char* const argname = has_plus_minus ? arg + 1 : arg;
 811   if (is_newly_obsolete(arg, &since)) {
 812     char version[256];
 813     since.to_string(version, sizeof(version));
 814     warning("ignoring option %s; support was removed in %s", argname, version);
 815     return true;
 816   }
 817 
 818   // For locked flags, report a custom error message if available.
 819   // Otherwise, report the standard unrecognized VM option.
 820 
 821   size_t arg_len;
 822   const char* equal_sign = strchr(argname, '=');
 823   if (equal_sign == NULL) {
 824     arg_len = strlen(argname);
 825   } else {
 826     arg_len = equal_sign - argname;
 827   }
 828 
 829   Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
 830   if (found_flag != NULL) {
 831     char locked_message_buf[BUFLEN];
 832     found_flag->get_locked_message(locked_message_buf, BUFLEN);
 833     if (strlen(locked_message_buf) == 0) {
 834       if (found_flag->is_bool() && !has_plus_minus) {
 835         jio_fprintf(defaultStream::error_stream(),
 836           "Missing +/- setting for VM option '%s'\n", argname);
 837       } else if (!found_flag->is_bool() && has_plus_minus) {
 838         jio_fprintf(defaultStream::error_stream(),
 839           "Unexpected +/- setting in VM option '%s'\n", argname);
 840       } else {
 841         jio_fprintf(defaultStream::error_stream(),
 842           "Improperly specified VM option '%s'\n", argname);
 843       }
 844     } else {
 845       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
 846     }
 847   } else {
 848     jio_fprintf(defaultStream::error_stream(),
 849                 "Unrecognized VM option '%s'\n", argname);
 850     Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
 851     if (fuzzy_matched != NULL) {
 852       jio_fprintf(defaultStream::error_stream(),
 853                   "Did you mean '%s%s%s'? ",
 854                   (fuzzy_matched->is_bool()) ? "(+/-)" : "",
 855                   fuzzy_matched->_name,
 856                   (fuzzy_matched->is_bool()) ? "" : "=<value>");
 857       if (is_newly_obsolete(fuzzy_matched->_name, &since)) {
 858         char version[256];
 859         since.to_string(version, sizeof(version));
 860         jio_fprintf(defaultStream::error_stream(),
 861                     "Warning: support for %s was removed in %s\n",
 862                     fuzzy_matched->_name,
 863                     version);
 864     }
 865   }
 866   }
 867 
 868   // allow for commandline "commenting out" options like -XX:#+Verbose
 869   return arg[0] == '#';
 870 }
 871 
 872 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
 873   FILE* stream = fopen(file_name, "rb");
 874   if (stream == NULL) {
 875     if (should_exist) {
 876       jio_fprintf(defaultStream::error_stream(),
 877                   "Could not open settings file %s\n", file_name);
 878       return false;
 879     } else {
 880       return true;
 881     }
 882   }
 883 
 884   char token[1024];
 885   int  pos = 0;
 886 
 887   bool in_white_space = true;
 888   bool in_comment     = false;
 889   bool in_quote       = false;
 890   char quote_c        = 0;
 891   bool result         = true;
 892 
 893   int c = getc(stream);
 894   while(c != EOF && pos < (int)(sizeof(token)-1)) {
 895     if (in_white_space) {
 896       if (in_comment) {
 897         if (c == '\n') in_comment = false;
 898       } else {
 899         if (c == '#') in_comment = true;
 900         else if (!isspace(c)) {
 901           in_white_space = false;
 902           token[pos++] = c;
 903         }
 904       }
 905     } else {
 906       if (c == '\n' || (!in_quote && isspace(c))) {
 907         // token ends at newline, or at unquoted whitespace
 908         // this allows a way to include spaces in string-valued options
 909         token[pos] = '\0';
 910         logOption(token);
 911         result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
 912         build_jvm_flags(token);
 913         pos = 0;
 914         in_white_space = true;
 915         in_quote = false;
 916       } else if (!in_quote && (c == '\'' || c == '"')) {
 917         in_quote = true;
 918         quote_c = c;
 919       } else if (in_quote && (c == quote_c)) {
 920         in_quote = false;
 921       } else {
 922         token[pos++] = c;
 923       }
 924     }
 925     c = getc(stream);
 926   }
 927   if (pos > 0) {
 928     token[pos] = '\0';
 929     result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
 930     build_jvm_flags(token);
 931   }
 932   fclose(stream);
 933   return result;
 934 }
 935 
 936 //=============================================================================================================
 937 // Parsing of properties (-D)
 938 
 939 const char* Arguments::get_property(const char* key) {
 940   return PropertyList_get_value(system_properties(), key);
 941 }
 942 
 943 bool Arguments::add_property(const char* prop) {
 944   const char* eq = strchr(prop, '=');
 945   char* key;
 946   // ns must be static--its address may be stored in a SystemProperty object.
 947   const static char ns[1] = {0};
 948   char* value = (char *)ns;
 949 
 950   size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);
 951   key = AllocateHeap(key_len + 1, mtInternal);
 952   strncpy(key, prop, key_len);
 953   key[key_len] = '\0';
 954 
 955   if (eq != NULL) {
 956     size_t value_len = strlen(prop) - key_len - 1;
 957     value = AllocateHeap(value_len + 1, mtInternal);
 958     strncpy(value, &prop[key_len + 1], value_len + 1);
 959   }
 960 
 961   if (strcmp(key, "java.compiler") == 0) {
 962     process_java_compiler_argument(value);
 963     FreeHeap(key);
 964     if (eq != NULL) {
 965       FreeHeap(value);
 966     }
 967     return true;
 968   } else if (strcmp(key, "sun.java.command") == 0) {
 969     _java_command = value;
 970 
 971     // Record value in Arguments, but let it get passed to Java.
 972   } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0 ||
 973              strcmp(key, "sun.java.launcher.pid") == 0) {
 974     // sun.java.launcher.is_altjvm and sun.java.launcher.pid property are
 975     // private and are processed in process_sun_java_launcher_properties();
 976     // the sun.java.launcher property is passed on to the java application
 977     FreeHeap(key);
 978     if (eq != NULL) {
 979       FreeHeap(value);
 980     }
 981     return true;
 982   } else if (strcmp(key, "java.vendor.url.bug") == 0) {
 983     // save it in _java_vendor_url_bug, so JVM fatal error handler can access
 984     // its value without going through the property list or making a Java call.
 985     _java_vendor_url_bug = value;
 986   } else if (strcmp(key, "sun.boot.library.path") == 0) {
 987     PropertyList_unique_add(&_system_properties, key, value, true);
 988     return true;
 989   }
 990   // Create new property and add at the end of the list
 991   PropertyList_unique_add(&_system_properties, key, value);
 992   return true;
 993 }
 994 
 995 //===========================================================================================================
 996 // Setting int/mixed/comp mode flags
 997 
 998 void Arguments::set_mode_flags(Mode mode) {
 999   // Set up default values for all flags.
1000   // If you add a flag to any of the branches below,
1001   // add a default value for it here.
1002   set_java_compiler(false);
1003   _mode                      = mode;
1004 
1005   // Ensure Agent_OnLoad has the correct initial values.
1006   // This may not be the final mode; mode may change later in onload phase.
1007   PropertyList_unique_add(&_system_properties, "java.vm.info",
1008                           (char*)VM_Version::vm_info_string(), false);
1009 
1010   UseInterpreter             = true;
1011   UseCompiler                = true;
1012   UseLoopCounter             = true;
1013 
1014   // Default values may be platform/compiler dependent -
1015   // use the saved values
1016   ClipInlining               = Arguments::_ClipInlining;
1017   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1018   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1019   BackgroundCompilation      = Arguments::_BackgroundCompilation;
1020 
1021   // Change from defaults based on mode
1022   switch (mode) {
1023   default:
1024     ShouldNotReachHere();
1025     break;
1026   case _int:
1027     UseCompiler              = false;
1028     UseLoopCounter           = false;
1029     AlwaysCompileLoopMethods = false;
1030     UseOnStackReplacement    = false;
1031     break;
1032   case _mixed:
1033     // same as default
1034     break;
1035   case _comp:
1036     UseInterpreter           = false;
1037     BackgroundCompilation    = false;
1038     ClipInlining             = false;
1039     // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1040     // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1041     // compile a level 4 (C2) and then continue executing it.
1042     if (TieredCompilation) {
1043       Tier3InvokeNotifyFreqLog = 0;
1044       Tier4InvocationThreshold = 0;
1045     }
1046     break;
1047   }
1048 }
1049 
1050 #if defined(COMPILER2) || defined(_LP64) || !INCLUDE_CDS
1051 // Conflict: required to use shared spaces (-Xshare:on), but
1052 // incompatible command line options were chosen.
1053 
1054 static void no_shared_spaces(const char* message) {
1055   if (RequireSharedSpaces) {
1056     jio_fprintf(defaultStream::error_stream(),
1057       "Class data sharing is inconsistent with other specified options.\n");
1058     vm_exit_during_initialization("Unable to use shared archive.", message);
1059   } else {
1060     FLAG_SET_DEFAULT(UseSharedSpaces, false);
1061   }
1062 }
1063 #endif
1064 
1065 // Returns threshold scaled with the value of scale.
1066 // If scale < 0.0, threshold is returned without scaling.
1067 intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
1068   if (scale == 1.0 || scale < 0.0) {
1069     return threshold;
1070   } else {
1071     return (intx)(threshold * scale);
1072   }
1073 }
1074 
1075 // Returns freq_log scaled with the value of scale.
1076 // Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
1077 // If scale < 0.0, freq_log is returned without scaling.
1078 intx Arguments::scaled_freq_log(intx freq_log, double scale) {
1079   // Check if scaling is necessary or if negative value was specified.
1080   if (scale == 1.0 || scale < 0.0) {
1081     return freq_log;
1082   }
1083   // Check values to avoid calculating log2 of 0.
1084   if (scale == 0.0 || freq_log == 0) {
1085     return 0;
1086   }
1087   // Determine the maximum notification frequency value currently supported.
1088   // The largest mask value that the interpreter/C1 can handle is
1089   // of length InvocationCounter::number_of_count_bits. Mask values are always
1090   // one bit shorter then the value of the notification frequency. Set
1091   // max_freq_bits accordingly.
1092   intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
1093   intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
1094   if (scaled_freq == 0) {
1095     // Return 0 right away to avoid calculating log2 of 0.
1096     return 0;
1097   } else if (scaled_freq > nth_bit(max_freq_bits)) {
1098     return max_freq_bits;
1099   } else {
1100     return log2_intptr(scaled_freq);
1101   }
1102 }
1103 
1104 void Arguments::set_tiered_flags() {
1105   // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1106   if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1107     FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1108   }
1109   if (CompilationPolicyChoice < 2) {
1110     vm_exit_during_initialization(
1111       "Incompatible compilation policy selected", NULL);
1112   }
1113   // Increase the code cache size - tiered compiles a lot more.
1114   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1115     FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
1116                   MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1117   }
1118   // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
1119   if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
1120     FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
1121 
1122     if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1123       // Multiply sizes by 5 but fix NonNMethodCodeHeapSize (distribute among non-profiled and profiled code heap)
1124       if (FLAG_IS_DEFAULT(ProfiledCodeHeapSize)) {
1125         FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, ProfiledCodeHeapSize * 5 + NonNMethodCodeHeapSize * 2);
1126       }
1127       if (FLAG_IS_DEFAULT(NonProfiledCodeHeapSize)) {
1128         FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, NonProfiledCodeHeapSize * 5 + NonNMethodCodeHeapSize * 2);
1129       }
1130       // Check consistency of code heap sizes
1131       if ((NonNMethodCodeHeapSize + NonProfiledCodeHeapSize + ProfiledCodeHeapSize) != ReservedCodeCacheSize) {
1132         jio_fprintf(defaultStream::error_stream(),
1133                     "Invalid code heap sizes: NonNMethodCodeHeapSize(%dK) + ProfiledCodeHeapSize(%dK) + NonProfiledCodeHeapSize(%dK) = %dK. Must be equal to ReservedCodeCacheSize = %uK.\n",
1134                     NonNMethodCodeHeapSize/K, ProfiledCodeHeapSize/K, NonProfiledCodeHeapSize/K,
1135                     (NonNMethodCodeHeapSize + ProfiledCodeHeapSize + NonProfiledCodeHeapSize)/K, ReservedCodeCacheSize/K);
1136         vm_exit(1);
1137       }
1138     }
1139   }
1140   if (!UseInterpreter) { // -Xcomp
1141     Tier3InvokeNotifyFreqLog = 0;
1142     Tier4InvocationThreshold = 0;
1143   }
1144 
1145   if (CompileThresholdScaling < 0) {
1146     vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
1147   }
1148 
1149   // Scale tiered compilation thresholds.
1150   // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
1151   if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
1152     FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
1153     FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
1154 
1155     FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
1156     FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
1157     FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
1158     FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
1159 
1160     // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
1161     // once these thresholds become supported.
1162 
1163     FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
1164     FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
1165 
1166     FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
1167     FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
1168 
1169     FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
1170 
1171     FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
1172     FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
1173     FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
1174     FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
1175   }
1176 }
1177 
1178 /**
1179  * Returns the minimum number of compiler threads needed to run the JVM. The following
1180  * configurations are possible.
1181  *
1182  * 1) The JVM is build using an interpreter only. As a result, the minimum number of
1183  *    compiler threads is 0.
1184  * 2) The JVM is build using the compiler(s) and tiered compilation is disabled. As
1185  *    a result, either C1 or C2 is used, so the minimum number of compiler threads is 1.
1186  * 3) The JVM is build using the compiler(s) and tiered compilation is enabled. However,
1187  *    the option "TieredStopAtLevel < CompLevel_full_optimization". As a result, only
1188  *    C1 can be used, so the minimum number of compiler threads is 1.
1189  * 4) The JVM is build using the compilers and tiered compilation is enabled. The option
1190  *    'TieredStopAtLevel = CompLevel_full_optimization' (the default value). As a result,
1191  *    the minimum number of compiler threads is 2.
1192  */
1193 int Arguments::get_min_number_of_compiler_threads() {
1194 #if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)
1195   return 0;   // case 1
1196 #else
1197   if (!TieredCompilation || (TieredStopAtLevel < CompLevel_full_optimization)) {
1198     return 1; // case 2 or case 3
1199   }
1200   return 2;   // case 4 (tiered)
1201 #endif
1202 }
1203 
1204 #if INCLUDE_ALL_GCS
1205 static void disable_adaptive_size_policy(const char* collector_name) {
1206   if (UseAdaptiveSizePolicy) {
1207     if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
1208       warning("disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
1209               collector_name);
1210     }
1211     FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
1212   }
1213 }
1214 
1215 void Arguments::set_parnew_gc_flags() {
1216   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
1217          "control point invariant");
1218   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1219   assert(UseParNewGC, "ParNew should always be used with CMS");
1220 
1221   if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
1222     FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1223     assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
1224   } else if (ParallelGCThreads == 0) {
1225     jio_fprintf(defaultStream::error_stream(),
1226         "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
1227     vm_exit(1);
1228   }
1229 
1230   // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
1231   // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
1232   // we set them to 1024 and 1024.
1233   // See CR 6362902.
1234   if (FLAG_IS_DEFAULT(YoungPLABSize)) {
1235     FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
1236   }
1237   if (FLAG_IS_DEFAULT(OldPLABSize)) {
1238     FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
1239   }
1240 
1241   // When using compressed oops, we use local overflow stacks,
1242   // rather than using a global overflow list chained through
1243   // the klass word of the object's pre-image.
1244   if (UseCompressedOops && !ParGCUseLocalOverflow) {
1245     if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
1246       warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
1247     }
1248     FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
1249   }
1250   assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
1251 }
1252 
1253 // Adjust some sizes to suit CMS and/or ParNew needs; these work well on
1254 // sparc/solaris for certain applications, but would gain from
1255 // further optimization and tuning efforts, and would almost
1256 // certainly gain from analysis of platform and environment.
1257 void Arguments::set_cms_and_parnew_gc_flags() {
1258   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
1259   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1260   assert(UseParNewGC, "ParNew should always be used with CMS");
1261 
1262   // Turn off AdaptiveSizePolicy by default for cms until it is complete.
1263   disable_adaptive_size_policy("UseConcMarkSweepGC");
1264 
1265   set_parnew_gc_flags();
1266 
1267   size_t max_heap = align_size_down(MaxHeapSize,
1268                                     CardTableRS::ct_max_alignment_constraint());
1269 
1270   // Now make adjustments for CMS
1271   intx   tenuring_default = (intx)6;
1272   size_t young_gen_per_worker = CMSYoungGenPerWorker;
1273 
1274   // Preferred young gen size for "short" pauses:
1275   // upper bound depends on # of threads and NewRatio.
1276   const uintx parallel_gc_threads =
1277     (ParallelGCThreads == 0 ? 1 : ParallelGCThreads);
1278   const size_t preferred_max_new_size_unaligned =
1279     MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * parallel_gc_threads));
1280   size_t preferred_max_new_size =
1281     align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
1282 
1283   // Unless explicitly requested otherwise, size young gen
1284   // for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
1285 
1286   // If either MaxNewSize or NewRatio is set on the command line,
1287   // assume the user is trying to set the size of the young gen.
1288   if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
1289 
1290     // Set MaxNewSize to our calculated preferred_max_new_size unless
1291     // NewSize was set on the command line and it is larger than
1292     // preferred_max_new_size.
1293     if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
1294       FLAG_SET_ERGO(uintx, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
1295     } else {
1296       FLAG_SET_ERGO(uintx, MaxNewSize, preferred_max_new_size);
1297     }
1298     if (PrintGCDetails && Verbose) {
1299       // Too early to use gclog_or_tty
1300       tty->print_cr("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
1301     }
1302 
1303     // Code along this path potentially sets NewSize and OldSize
1304     if (PrintGCDetails && Verbose) {
1305       // Too early to use gclog_or_tty
1306       tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
1307            " initial_heap_size:  " SIZE_FORMAT
1308            " max_heap: " SIZE_FORMAT,
1309            min_heap_size(), InitialHeapSize, max_heap);
1310     }
1311     size_t min_new = preferred_max_new_size;
1312     if (FLAG_IS_CMDLINE(NewSize)) {
1313       min_new = NewSize;
1314     }
1315     if (max_heap > min_new && min_heap_size() > min_new) {
1316       // Unless explicitly requested otherwise, make young gen
1317       // at least min_new, and at most preferred_max_new_size.
1318       if (FLAG_IS_DEFAULT(NewSize)) {
1319         FLAG_SET_ERGO(uintx, NewSize, MAX2(NewSize, min_new));
1320         FLAG_SET_ERGO(uintx, NewSize, MIN2(preferred_max_new_size, NewSize));
1321         if (PrintGCDetails && Verbose) {
1322           // Too early to use gclog_or_tty
1323           tty->print_cr("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
1324         }
1325       }
1326       // Unless explicitly requested otherwise, size old gen
1327       // so it's NewRatio x of NewSize.
1328       if (FLAG_IS_DEFAULT(OldSize)) {
1329         if (max_heap > NewSize) {
1330           FLAG_SET_ERGO(uintx, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
1331           if (PrintGCDetails && Verbose) {
1332             // Too early to use gclog_or_tty
1333             tty->print_cr("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
1334           }
1335         }
1336       }
1337     }
1338   }
1339   // Unless explicitly requested otherwise, definitely
1340   // promote all objects surviving "tenuring_default" scavenges.
1341   if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
1342       FLAG_IS_DEFAULT(SurvivorRatio)) {
1343     FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
1344   }
1345   // If we decided above (or user explicitly requested)
1346   // `promote all' (via MaxTenuringThreshold := 0),
1347   // prefer minuscule survivor spaces so as not to waste
1348   // space for (non-existent) survivors
1349   if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
1350     FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
1351   }
1352 
1353   // OldPLABSize is interpreted in CMS as not the size of the PLAB in words,
1354   // but rather the number of free blocks of a given size that are used when
1355   // replenishing the local per-worker free list caches.
1356   if (FLAG_IS_DEFAULT(OldPLABSize)) {
1357     if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
1358       // OldPLAB sizing manually turned off: Use a larger default setting,
1359       // unless it was manually specified. This is because a too-low value
1360       // will slow down scavenges.
1361       FLAG_SET_ERGO(uintx, OldPLABSize, CFLS_LAB::_default_static_old_plab_size); // default value before 6631166
1362     } else {
1363       FLAG_SET_DEFAULT(OldPLABSize, CFLS_LAB::_default_dynamic_old_plab_size); // old CMSParPromoteBlocksToClaim default
1364     }
1365   }
1366 
1367   // If either of the static initialization defaults have changed, note this
1368   // modification.
1369   if (!FLAG_IS_DEFAULT(OldPLABSize) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
1370     CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
1371   }
1372   if (PrintGCDetails && Verbose) {
1373     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1374       (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1375     tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
1376   }
1377 }
1378 #endif // INCLUDE_ALL_GCS
1379 
1380 void set_object_alignment() {
1381   // Object alignment.
1382   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1383   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1384   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1385   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1386   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1387   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1388 
1389   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1390   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1391 
1392   // Oop encoding heap max
1393   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1394 
1395 #if INCLUDE_ALL_GCS
1396   // Set CMS global values
1397   CompactibleFreeListSpace::set_cms_values();
1398 #endif // INCLUDE_ALL_GCS
1399 }
1400 
1401 bool verify_object_alignment() {
1402   // Object alignment.
1403   if (!is_power_of_2(ObjectAlignmentInBytes)) {
1404     jio_fprintf(defaultStream::error_stream(),
1405                 "error: ObjectAlignmentInBytes=%d must be power of 2\n",
1406                 (int)ObjectAlignmentInBytes);
1407     return false;
1408   }
1409   if ((int)ObjectAlignmentInBytes < BytesPerLong) {
1410     jio_fprintf(defaultStream::error_stream(),
1411                 "error: ObjectAlignmentInBytes=%d must be greater or equal %d\n",
1412                 (int)ObjectAlignmentInBytes, BytesPerLong);
1413     return false;
1414   }
1415   // It does not make sense to have big object alignment
1416   // since a space lost due to alignment will be greater
1417   // then a saved space from compressed oops.
1418   if ((int)ObjectAlignmentInBytes > 256) {
1419     jio_fprintf(defaultStream::error_stream(),
1420                 "error: ObjectAlignmentInBytes=%d must not be greater than 256\n",
1421                 (int)ObjectAlignmentInBytes);
1422     return false;
1423   }
1424   // In case page size is very small.
1425   if ((int)ObjectAlignmentInBytes >= os::vm_page_size()) {
1426     jio_fprintf(defaultStream::error_stream(),
1427                 "error: ObjectAlignmentInBytes=%d must be less than page size %d\n",
1428                 (int)ObjectAlignmentInBytes, os::vm_page_size());
1429     return false;
1430   }
1431   if(SurvivorAlignmentInBytes == 0) {
1432     SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1433   } else {
1434     if (!is_power_of_2(SurvivorAlignmentInBytes)) {
1435       jio_fprintf(defaultStream::error_stream(),
1436             "error: SurvivorAlignmentInBytes=%d must be power of 2\n",
1437             (int)SurvivorAlignmentInBytes);
1438       return false;
1439     }
1440     if (SurvivorAlignmentInBytes < ObjectAlignmentInBytes) {
1441       jio_fprintf(defaultStream::error_stream(),
1442           "error: SurvivorAlignmentInBytes=%d must be greater than ObjectAlignmentInBytes=%d \n",
1443           (int)SurvivorAlignmentInBytes, (int)ObjectAlignmentInBytes);
1444       return false;
1445     }
1446   }
1447   return true;
1448 }
1449 
1450 size_t Arguments::max_heap_for_compressed_oops() {
1451   // Avoid sign flip.
1452   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1453   // We need to fit both the NULL page and the heap into the memory budget, while
1454   // keeping alignment constraints of the heap. To guarantee the latter, as the
1455   // NULL page is located before the heap, we pad the NULL page to the conservative
1456   // maximum alignment that the GC may ever impose upon the heap.
1457   size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
1458                                                         _conservative_max_heap_alignment);
1459 
1460   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1461   NOT_LP64(ShouldNotReachHere(); return 0);
1462 }
1463 
1464 bool Arguments::should_auto_select_low_pause_collector() {
1465   if (UseAutoGCSelectPolicy &&
1466       !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
1467       (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
1468     if (PrintGCDetails) {
1469       // Cannot use gclog_or_tty yet.
1470       tty->print_cr("Automatic selection of the low pause collector"
1471        " based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
1472     }
1473     return true;
1474   }
1475   return false;
1476 }
1477 
1478 void Arguments::set_use_compressed_oops() {
1479 #ifndef ZERO
1480 #ifdef _LP64
1481   // MaxHeapSize is not set up properly at this point, but
1482   // the only value that can override MaxHeapSize if we are
1483   // to use UseCompressedOops is InitialHeapSize.
1484   size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1485 
1486   if (max_heap_size <= max_heap_for_compressed_oops()) {
1487 #if !defined(COMPILER1) || defined(TIERED)
1488     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1489       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1490     }
1491 #endif
1492   } else {
1493     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1494       warning("Max heap size too large for Compressed Oops");
1495       FLAG_SET_DEFAULT(UseCompressedOops, false);
1496       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1497     }
1498   }
1499 #endif // _LP64
1500 #endif // ZERO
1501 }
1502 
1503 
1504 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1505 // set_use_compressed_oops().
1506 void Arguments::set_use_compressed_klass_ptrs() {
1507 #ifndef ZERO
1508 #ifdef _LP64
1509   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1510   if (!UseCompressedOops) {
1511     if (UseCompressedClassPointers) {
1512       warning("UseCompressedClassPointers requires UseCompressedOops");
1513     }
1514     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1515   } else {
1516     // Turn on UseCompressedClassPointers too
1517     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1518       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1519     }
1520     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1521     if (UseCompressedClassPointers) {
1522       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1523         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1524         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1525       }
1526     }
1527   }
1528 #endif // _LP64
1529 #endif // !ZERO
1530 }
1531 
1532 void Arguments::set_conservative_max_heap_alignment() {
1533   // The conservative maximum required alignment for the heap is the maximum of
1534   // the alignments imposed by several sources: any requirements from the heap
1535   // itself, the collector policy and the maximum page size we may run the VM
1536   // with.
1537   size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
1538 #if INCLUDE_ALL_GCS
1539   if (UseParallelGC) {
1540     heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
1541   } else if (UseG1GC) {
1542     heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
1543   }
1544 #endif // INCLUDE_ALL_GCS
1545   _conservative_max_heap_alignment = MAX4(heap_alignment,
1546                                           (size_t)os::vm_allocation_granularity(),
1547                                           os::max_page_size(),
1548                                           CollectorPolicy::compute_heap_alignment());
1549 }
1550 
1551 void Arguments::select_gc_ergonomically() {
1552   if (os::is_server_class_machine()) {
1553     if (should_auto_select_low_pause_collector()) {
1554       FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
1555     } else {
1556       FLAG_SET_ERGO(bool, UseParallelGC, true);
1557     }
1558   }
1559 }
1560 
1561 void Arguments::select_gc() {
1562   if (!gc_selected()) {
1563     ArgumentsExt::select_gc_ergonomically();
1564   }
1565 }
1566 
1567 void Arguments::set_ergonomics_flags() {
1568   select_gc();
1569 
1570 #ifdef COMPILER2
1571   // Shared spaces work fine with other GCs but causes bytecode rewriting
1572   // to be disabled, which hurts interpreter performance and decreases
1573   // server performance.  When -server is specified, keep the default off
1574   // unless it is asked for.  Future work: either add bytecode rewriting
1575   // at link time, or rewrite bytecodes in non-shared methods.
1576   if (!DumpSharedSpaces && !RequireSharedSpaces &&
1577       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1578     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1579   }
1580 #endif
1581 
1582   set_conservative_max_heap_alignment();
1583 
1584 #ifndef ZERO
1585 #ifdef _LP64
1586   set_use_compressed_oops();
1587 
1588   // set_use_compressed_klass_ptrs() must be called after calling
1589   // set_use_compressed_oops().
1590   set_use_compressed_klass_ptrs();
1591 
1592   // Also checks that certain machines are slower with compressed oops
1593   // in vm_version initialization code.
1594 #endif // _LP64
1595 #endif // !ZERO
1596 }
1597 
1598 void Arguments::set_parallel_gc_flags() {
1599   assert(UseParallelGC || UseParallelOldGC, "Error");
1600   // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1601   if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1602     FLAG_SET_DEFAULT(UseParallelOldGC, true);
1603   }
1604   FLAG_SET_DEFAULT(UseParallelGC, true);
1605 
1606   // If no heap maximum was requested explicitly, use some reasonable fraction
1607   // of the physical memory, up to a maximum of 1GB.
1608   FLAG_SET_DEFAULT(ParallelGCThreads,
1609                    Abstract_VM_Version::parallel_worker_threads());
1610   if (ParallelGCThreads == 0) {
1611     jio_fprintf(defaultStream::error_stream(),
1612         "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1613     vm_exit(1);
1614   }
1615 
1616   if (UseAdaptiveSizePolicy) {
1617     // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1618     // unless the user actually sets these flags.
1619     if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1620       FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1621       _min_heap_free_ratio = MinHeapFreeRatio;
1622     }
1623     if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1624       FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1625       _max_heap_free_ratio = MaxHeapFreeRatio;
1626     }
1627   }
1628 
1629   // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1630   // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1631   // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1632   // See CR 6362902 for details.
1633   if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1634     if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1635        FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1636     }
1637     if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1638       FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1639     }
1640   }
1641 
1642   if (UseParallelOldGC) {
1643     // Par compact uses lower default values since they are treated as
1644     // minimums.  These are different defaults because of the different
1645     // interpretation and are not ergonomically set.
1646     if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1647       FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1648     }
1649   }
1650 }
1651 
1652 void Arguments::set_g1_gc_flags() {
1653   assert(UseG1GC, "Error");
1654 #ifdef COMPILER1
1655   FastTLABRefill = false;
1656 #endif
1657   FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1658   if (ParallelGCThreads == 0) {
1659     assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
1660     vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1661   }
1662 
1663 #if INCLUDE_ALL_GCS
1664   if (G1ConcRefinementThreads == 0) {
1665     FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);
1666   }
1667 #endif
1668 
1669   // MarkStackSize will be set (if it hasn't been set by the user)
1670   // when concurrent marking is initialized.
1671   // Its value will be based upon the number of parallel marking threads.
1672   // But we do set the maximum mark stack size here.
1673   if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1674     FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1675   }
1676 
1677   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1678     // In G1, we want the default GC overhead goal to be higher than
1679     // say in PS. So we set it here to 10%. Otherwise the heap might
1680     // be expanded more aggressively than we would like it to. In
1681     // fact, even 10% seems to not be high enough in some cases
1682     // (especially small GC stress tests that the main thing they do
1683     // is allocation). We might consider increase it further.
1684     FLAG_SET_DEFAULT(GCTimeRatio, 9);
1685   }
1686 
1687   if (PrintGCDetails && Verbose) {
1688     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1689       (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1690     tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
1691   }
1692 }
1693 
1694 #if !INCLUDE_ALL_GCS
1695 #ifdef ASSERT
1696 static bool verify_serial_gc_flags() {
1697   return (UseSerialGC &&
1698         !(UseParNewGC || (UseConcMarkSweepGC) || UseG1GC ||
1699           UseParallelGC || UseParallelOldGC));
1700 }
1701 #endif // ASSERT
1702 #endif // INCLUDE_ALL_GCS
1703 
1704 void Arguments::set_gc_specific_flags() {
1705 #if INCLUDE_ALL_GCS
1706   // Set per-collector flags
1707   if (UseParallelGC || UseParallelOldGC) {
1708     set_parallel_gc_flags();
1709   } else if (UseConcMarkSweepGC) {
1710     set_cms_and_parnew_gc_flags();
1711   } else if (UseG1GC) {
1712     set_g1_gc_flags();
1713   }
1714   check_deprecated_gc_flags();
1715   if (AssumeMP && !UseSerialGC) {
1716     if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
1717       warning("If the number of processors is expected to increase from one, then"
1718               " you should configure the number of parallel GC threads appropriately"
1719               " using -XX:ParallelGCThreads=N");
1720     }
1721   }
1722   if (MinHeapFreeRatio == 100) {
1723     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
1724     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
1725   }
1726 #else // INCLUDE_ALL_GCS
1727   assert(verify_serial_gc_flags(), "SerialGC unset");
1728 #endif // INCLUDE_ALL_GCS
1729 }
1730 
1731 julong Arguments::limit_by_allocatable_memory(julong limit) {
1732   julong max_allocatable;
1733   julong result = limit;
1734   if (os::has_allocatable_memory_limit(&max_allocatable)) {
1735     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
1736   }
1737   return result;
1738 }
1739 
1740 // Use static initialization to get the default before parsing
1741 static const uintx DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1742 
1743 void Arguments::set_heap_size() {
1744   if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
1745     // Deprecated flag
1746     FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
1747   }
1748 
1749   const julong phys_mem =
1750     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1751                             : (julong)MaxRAM;
1752 
1753   // If the maximum heap size has not been set with -Xmx,
1754   // then set it as fraction of the size of physical memory,
1755   // respecting the maximum and minimum sizes of the heap.
1756   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1757     julong reasonable_max = phys_mem / MaxRAMFraction;
1758 
1759     if (phys_mem <= MaxHeapSize * MinRAMFraction) {
1760       // Small physical memory, so use a minimum fraction of it for the heap
1761       reasonable_max = phys_mem / MinRAMFraction;
1762     } else {
1763       // Not-small physical memory, so require a heap at least
1764       // as large as MaxHeapSize
1765       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1766     }
1767     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1768       // Limit the heap size to ErgoHeapSizeLimit
1769       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1770     }
1771     if (UseCompressedOops) {
1772       // Limit the heap size to the maximum possible when using compressed oops
1773       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1774 
1775       // HeapBaseMinAddress can be greater than default but not less than.
1776       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1777         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1778           // matches compressed oops printing flags
1779           if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
1780             jio_fprintf(defaultStream::error_stream(),
1781                         "HeapBaseMinAddress must be at least " UINTX_FORMAT
1782                         " (" UINTX_FORMAT "G) which is greater than value given "
1783                         UINTX_FORMAT "\n",
1784                         DefaultHeapBaseMinAddress,
1785                         DefaultHeapBaseMinAddress/G,
1786                         HeapBaseMinAddress);
1787           }
1788           FLAG_SET_ERGO(uintx, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1789         }
1790       }
1791 
1792       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1793         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1794         // but it should be not less than default MaxHeapSize.
1795         max_coop_heap -= HeapBaseMinAddress;
1796       }
1797       reasonable_max = MIN2(reasonable_max, max_coop_heap);
1798     }
1799     reasonable_max = limit_by_allocatable_memory(reasonable_max);
1800 
1801     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1802       // An initial heap size was specified on the command line,
1803       // so be sure that the maximum size is consistent.  Done
1804       // after call to limit_by_allocatable_memory because that
1805       // method might reduce the allocation size.
1806       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1807     }
1808 
1809     if (PrintGCDetails && Verbose) {
1810       // Cannot use gclog_or_tty yet.
1811       tty->print_cr("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1812     }
1813     FLAG_SET_ERGO(uintx, MaxHeapSize, (uintx)reasonable_max);
1814   }
1815 
1816   // If the minimum or initial heap_size have not been set or requested to be set
1817   // ergonomically, set them accordingly.
1818   if (InitialHeapSize == 0 || min_heap_size() == 0) {
1819     julong reasonable_minimum = (julong)(OldSize + NewSize);
1820 
1821     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1822 
1823     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1824 
1825     if (InitialHeapSize == 0) {
1826       julong reasonable_initial = phys_mem / InitialRAMFraction;
1827 
1828       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
1829       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1830 
1831       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
1832 
1833       if (PrintGCDetails && Verbose) {
1834         // Cannot use gclog_or_tty yet.
1835         tty->print_cr("  Initial heap size " SIZE_FORMAT, (uintx)reasonable_initial);
1836       }
1837       FLAG_SET_ERGO(uintx, InitialHeapSize, (uintx)reasonable_initial);
1838     }
1839     // If the minimum heap size has not been set (via -Xms),
1840     // synchronize with InitialHeapSize to avoid errors with the default value.
1841     if (min_heap_size() == 0) {
1842       set_min_heap_size(MIN2((uintx)reasonable_minimum, InitialHeapSize));
1843       if (PrintGCDetails && Verbose) {
1844         // Cannot use gclog_or_tty yet.
1845         tty->print_cr("  Minimum heap size " SIZE_FORMAT, min_heap_size());
1846       }
1847     }
1848   }
1849 }
1850 
1851 // This must be called after ergonomics because we want bytecode rewriting
1852 // if the server compiler is used, or if UseSharedSpaces is disabled.
1853 void Arguments::set_bytecode_flags() {
1854   // Better not attempt to store into a read-only space.
1855   if (UseSharedSpaces) {
1856     FLAG_SET_DEFAULT(RewriteBytecodes, false);
1857     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1858   }
1859 
1860   if (!RewriteBytecodes) {
1861     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1862   }
1863 }
1864 
1865 // Aggressive optimization flags  -XX:+AggressiveOpts
1866 void Arguments::set_aggressive_opts_flags() {
1867 #ifdef COMPILER2
1868   if (AggressiveUnboxing) {
1869     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1870       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1871     } else if (!EliminateAutoBox) {
1872       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
1873       AggressiveUnboxing = false;
1874     }
1875     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1876       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1877     } else if (!DoEscapeAnalysis) {
1878       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
1879       AggressiveUnboxing = false;
1880     }
1881   }
1882   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1883     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1884       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1885     }
1886     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1887       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
1888     }
1889 
1890     // Feed the cache size setting into the JDK
1891     char buffer[1024];
1892     sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
1893     add_property(buffer);
1894   }
1895   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
1896     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
1897   }
1898 #endif
1899 
1900   if (AggressiveOpts) {
1901 // Sample flag setting code
1902 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
1903 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
1904 //    }
1905   }
1906 }
1907 
1908 //===========================================================================================================
1909 // Parsing of java.compiler property
1910 
1911 void Arguments::process_java_compiler_argument(char* arg) {
1912   // For backwards compatibility, Djava.compiler=NONE or ""
1913   // causes us to switch to -Xint mode UNLESS -Xdebug
1914   // is also specified.
1915   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
1916     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
1917   }
1918 }
1919 
1920 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1921   _sun_java_launcher = os::strdup_check_oom(launcher);
1922 }
1923 
1924 bool Arguments::created_by_java_launcher() {
1925   assert(_sun_java_launcher != NULL, "property must have value");
1926   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1927 }
1928 
1929 bool Arguments::sun_java_launcher_is_altjvm() {
1930   return _sun_java_launcher_is_altjvm;
1931 }
1932 
1933 //===========================================================================================================
1934 // Parsing of main arguments
1935 
1936 bool Arguments::verify_interval(uintx val, uintx min,
1937                                 uintx max, const char* name) {
1938   // Returns true iff value is in the inclusive interval [min..max]
1939   // false, otherwise.
1940   if (val >= min && val <= max) {
1941     return true;
1942   }
1943   jio_fprintf(defaultStream::error_stream(),
1944               "%s of " UINTX_FORMAT " is invalid; must be between " UINTX_FORMAT
1945               " and " UINTX_FORMAT "\n",
1946               name, val, min, max);
1947   return false;
1948 }
1949 
1950 bool Arguments::verify_min_value(intx val, intx min, const char* name) {
1951   // Returns true if given value is at least specified min threshold
1952   // false, otherwise.
1953   if (val >= min ) {
1954       return true;
1955   }
1956   jio_fprintf(defaultStream::error_stream(),
1957               "%s of " INTX_FORMAT " is invalid; must be at least " INTX_FORMAT "\n",
1958               name, val, min);
1959   return false;
1960 }
1961 
1962 bool Arguments::verify_percentage(uintx value, const char* name) {
1963   if (is_percentage(value)) {
1964     return true;
1965   }
1966   jio_fprintf(defaultStream::error_stream(),
1967               "%s of " UINTX_FORMAT " is invalid; must be between 0 and 100\n",
1968               name, value);
1969   return false;
1970 }
1971 
1972 // check if do gclog rotation
1973 // +UseGCLogFileRotation is a must,
1974 // no gc log rotation when log file not supplied or
1975 // NumberOfGCLogFiles is 0
1976 void check_gclog_consistency() {
1977   if (UseGCLogFileRotation) {
1978     if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {
1979       jio_fprintf(defaultStream::output_stream(),
1980                   "To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"
1981                   "where num_of_file > 0\n"
1982                   "GC log rotation is turned off\n");
1983       UseGCLogFileRotation = false;
1984     }
1985   }
1986 
1987   if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {
1988     FLAG_SET_CMDLINE(uintx, GCLogFileSize, 8*K);
1989     jio_fprintf(defaultStream::output_stream(),
1990                 "GCLogFileSize changed to minimum 8K\n");
1991   }
1992 }
1993 
1994 // This function is called for -Xloggc:<filename>, it can be used
1995 // to check if a given file name(or string) conforms to the following
1996 // specification:
1997 // A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"
1998 // %p and %t only allowed once. We only limit usage of filename not path
1999 bool is_filename_valid(const char *file_name) {
2000   const char* p = file_name;
2001   char file_sep = os::file_separator()[0];
2002   const char* cp;
2003   // skip prefix path
2004   for (cp = file_name; *cp != '\0'; cp++) {
2005     if (*cp == '/' || *cp == file_sep) {
2006       p = cp + 1;
2007     }
2008   }
2009 
2010   int count_p = 0;
2011   int count_t = 0;
2012   while (*p != '\0') {
2013     if ((*p >= '0' && *p <= '9') ||
2014         (*p >= 'A' && *p <= 'Z') ||
2015         (*p >= 'a' && *p <= 'z') ||
2016          *p == '-'               ||
2017          *p == '_'               ||
2018          *p == '.') {
2019        p++;
2020        continue;
2021     }
2022     if (*p == '%') {
2023       if(*(p + 1) == 'p') {
2024         p += 2;
2025         count_p ++;
2026         continue;
2027       }
2028       if (*(p + 1) == 't') {
2029         p += 2;
2030         count_t ++;
2031         continue;
2032       }
2033     }
2034     return false;
2035   }
2036   return count_p < 2 && count_t < 2;
2037 }
2038 
2039 bool Arguments::verify_MinHeapFreeRatio(FormatBuffer<80>& err_msg, uintx min_heap_free_ratio) {
2040   if (!is_percentage(min_heap_free_ratio)) {
2041     err_msg.print("MinHeapFreeRatio must have a value between 0 and 100");
2042     return false;
2043   }
2044   if (min_heap_free_ratio > MaxHeapFreeRatio) {
2045     err_msg.print("MinHeapFreeRatio (" UINTX_FORMAT ") must be less than or "
2046                   "equal to MaxHeapFreeRatio (" UINTX_FORMAT ")", min_heap_free_ratio,
2047                   MaxHeapFreeRatio);
2048     return false;
2049   }
2050   // This does not set the flag itself, but stores the value in a safe place for later usage.
2051   _min_heap_free_ratio = min_heap_free_ratio;
2052   return true;
2053 }
2054 
2055 bool Arguments::verify_MaxHeapFreeRatio(FormatBuffer<80>& err_msg, uintx max_heap_free_ratio) {
2056   if (!is_percentage(max_heap_free_ratio)) {
2057     err_msg.print("MaxHeapFreeRatio must have a value between 0 and 100");
2058     return false;
2059   }
2060   if (max_heap_free_ratio < MinHeapFreeRatio) {
2061     err_msg.print("MaxHeapFreeRatio (" UINTX_FORMAT ") must be greater than or "
2062                   "equal to MinHeapFreeRatio (" UINTX_FORMAT ")", max_heap_free_ratio,
2063                   MinHeapFreeRatio);
2064     return false;
2065   }
2066   // This does not set the flag itself, but stores the value in a safe place for later usage.
2067   _max_heap_free_ratio = max_heap_free_ratio;
2068   return true;
2069 }
2070 
2071 // Check consistency of GC selection
2072 bool Arguments::check_gc_consistency_user() {
2073   check_gclog_consistency();
2074   // Ensure that the user has not selected conflicting sets
2075   // of collectors.
2076   uint i = 0;
2077   if (UseSerialGC)                       i++;
2078   if (UseConcMarkSweepGC)                i++;
2079   if (UseParallelGC || UseParallelOldGC) i++;
2080   if (UseG1GC)                           i++;
2081   if (i > 1) {
2082     jio_fprintf(defaultStream::error_stream(),
2083                 "Conflicting collector combinations in option list; "
2084                 "please refer to the release notes for the combinations "
2085                 "allowed\n");
2086     return false;
2087   }
2088 
2089   if (UseConcMarkSweepGC && !UseParNewGC) {
2090     jio_fprintf(defaultStream::error_stream(),
2091         "It is not possible to combine the DefNew young collector with the CMS collector.\n");
2092     return false;
2093   }
2094 
2095   if (UseParNewGC && !UseConcMarkSweepGC) {
2096     // !UseConcMarkSweepGC means that we are using serial old gc. Unfortunately we don't
2097     // set up UseSerialGC properly, so that can't be used in the check here.
2098     jio_fprintf(defaultStream::error_stream(),
2099         "It is not possible to combine the ParNew young collector with the Serial old collector.\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_user();
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, 31,
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, (uintx) 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 
2541   // Setup flags for mixed which is the default
2542   set_mode_flags(_mixed);
2543 
2544   // Parse JAVA_TOOL_OPTIONS environment variable (if present)
2545   jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);
2546   if (result != JNI_OK) {
2547     return result;
2548   }
2549 
2550   // Parse JavaVMInitArgs structure passed in
2551   result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, Flag::COMMAND_LINE);
2552   if (result != JNI_OK) {
2553     return result;
2554   }
2555 
2556   // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
2557   result = parse_java_options_environment_variable(&scp, &scp_assembly_required);
2558   if (result != JNI_OK) {
2559     return result;
2560   }
2561 
2562   // Do final processing now that all arguments have been parsed
2563   result = finalize_vm_init_args(&scp, scp_assembly_required);
2564   if (result != JNI_OK) {
2565     return result;
2566   }
2567 
2568   return JNI_OK;
2569 }
2570 
2571 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2572 // represents a valid HPROF of JDWP agent.  is_path==true denotes that we
2573 // are dealing with -agentpath (case where name is a path), otherwise with
2574 // -agentlib
2575 bool valid_hprof_or_jdwp_agent(char *name, bool is_path) {
2576   char *_name;
2577   const char *_hprof = "hprof", *_jdwp = "jdwp";
2578   size_t _len_hprof, _len_jdwp, _len_prefix;
2579 
2580   if (is_path) {
2581     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2582       return false;
2583     }
2584 
2585     _name++;  // skip past last path separator
2586     _len_prefix = strlen(JNI_LIB_PREFIX);
2587 
2588     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2589       return false;
2590     }
2591 
2592     _name += _len_prefix;
2593     _len_hprof = strlen(_hprof);
2594     _len_jdwp = strlen(_jdwp);
2595 
2596     if (strncmp(_name, _hprof, _len_hprof) == 0) {
2597       _name += _len_hprof;
2598     }
2599     else if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2600       _name += _len_jdwp;
2601     }
2602     else {
2603       return false;
2604     }
2605 
2606     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2607       return false;
2608     }
2609 
2610     return true;
2611   }
2612 
2613   if (strcmp(name, _hprof) == 0 || strcmp(name, _jdwp) == 0) {
2614     return true;
2615   }
2616 
2617   return false;
2618 }
2619 
2620 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2621                                        SysClassPath* scp_p,
2622                                        bool* scp_assembly_required_p,
2623                                        Flag::Flags origin) {
2624   // Remaining part of option string
2625   const char* tail;
2626 
2627   // iterate over arguments
2628   for (int index = 0; index < args->nOptions; index++) {
2629     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2630 
2631     const JavaVMOption* option = args->options + index;
2632 
2633     if (!match_option(option, "-Djava.class.path", &tail) &&
2634         !match_option(option, "-Dsun.java.command", &tail) &&
2635         !match_option(option, "-Dsun.java.launcher", &tail)) {
2636 
2637         // add all jvm options to the jvm_args string. This string
2638         // is used later to set the java.vm.args PerfData string constant.
2639         // the -Djava.class.path and the -Dsun.java.command options are
2640         // omitted from jvm_args string as each have their own PerfData
2641         // string constant object.
2642         build_jvm_args(option->optionString);
2643     }
2644 
2645     // -verbose:[class/gc/jni]
2646     if (match_option(option, "-verbose", &tail)) {
2647       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2648         FLAG_SET_CMDLINE(bool, TraceClassLoading, true);
2649         FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);
2650       } else if (!strcmp(tail, ":gc")) {
2651         FLAG_SET_CMDLINE(bool, PrintGC, true);
2652       } else if (!strcmp(tail, ":jni")) {
2653         FLAG_SET_CMDLINE(bool, PrintJNIResolving, true);
2654       }
2655     // -da / -ea / -disableassertions / -enableassertions
2656     // These accept an optional class/package name separated by a colon, e.g.,
2657     // -da:java.lang.Thread.
2658     } else if (match_option(option, user_assertion_options, &tail, true)) {
2659       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2660       if (*tail == '\0') {
2661         JavaAssertions::setUserClassDefault(enable);
2662       } else {
2663         assert(*tail == ':', "bogus match by match_option()");
2664         JavaAssertions::addOption(tail + 1, enable);
2665       }
2666     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2667     } else if (match_option(option, system_assertion_options, &tail, false)) {
2668       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2669       JavaAssertions::setSystemClassDefault(enable);
2670     // -bootclasspath:
2671     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2672       scp_p->reset_path(tail);
2673       *scp_assembly_required_p = true;
2674     // -bootclasspath/a:
2675     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2676       scp_p->add_suffix(tail);
2677       *scp_assembly_required_p = true;
2678     // -bootclasspath/p:
2679     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2680       scp_p->add_prefix(tail);
2681       *scp_assembly_required_p = true;
2682     // -Xrun
2683     } else if (match_option(option, "-Xrun", &tail)) {
2684       if (tail != NULL) {
2685         const char* pos = strchr(tail, ':');
2686         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2687         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2688         name[len] = '\0';
2689 
2690         char *options = NULL;
2691         if(pos != NULL) {
2692           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2693           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
2694         }
2695 #if !INCLUDE_JVMTI
2696         if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
2697           jio_fprintf(defaultStream::error_stream(),
2698             "Profiling and debugging agents are not supported in this VM\n");
2699           return JNI_ERR;
2700         }
2701 #endif // !INCLUDE_JVMTI
2702         add_init_library(name, options);
2703       }
2704     // -agentlib and -agentpath
2705     } else if (match_option(option, "-agentlib:", &tail) ||
2706           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2707       if(tail != NULL) {
2708         const char* pos = strchr(tail, '=');
2709         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2710         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2711         name[len] = '\0';
2712 
2713         char *options = NULL;
2714         if(pos != NULL) {
2715           options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(pos + 1) + 1, mtInternal), pos + 1);
2716         }
2717 #if !INCLUDE_JVMTI
2718         if (valid_hprof_or_jdwp_agent(name, is_absolute_path)) {
2719           jio_fprintf(defaultStream::error_stream(),
2720             "Profiling and debugging agents are not supported in this VM\n");
2721           return JNI_ERR;
2722         }
2723 #endif // !INCLUDE_JVMTI
2724         add_init_agent(name, options, is_absolute_path);
2725       }
2726     // -javaagent
2727     } else if (match_option(option, "-javaagent:", &tail)) {
2728 #if !INCLUDE_JVMTI
2729       jio_fprintf(defaultStream::error_stream(),
2730         "Instrumentation agents are not supported in this VM\n");
2731       return JNI_ERR;
2732 #else
2733       if(tail != NULL) {
2734         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtInternal), tail);
2735         add_init_agent("instrument", options, false);
2736       }
2737 #endif // !INCLUDE_JVMTI
2738     // -Xnoclassgc
2739     } else if (match_option(option, "-Xnoclassgc")) {
2740       FLAG_SET_CMDLINE(bool, ClassUnloading, false);
2741     // -Xconcgc
2742     } else if (match_option(option, "-Xconcgc")) {
2743       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
2744     // -Xnoconcgc
2745     } else if (match_option(option, "-Xnoconcgc")) {
2746       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
2747     // -Xbatch
2748     } else if (match_option(option, "-Xbatch")) {
2749       FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2750     // -Xmn for compatibility with other JVM vendors
2751     } else if (match_option(option, "-Xmn", &tail)) {
2752       julong long_initial_young_size = 0;
2753       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2754       if (errcode != arg_in_range) {
2755         jio_fprintf(defaultStream::error_stream(),
2756                     "Invalid initial young generation size: %s\n", option->optionString);
2757         describe_range_error(errcode);
2758         return JNI_EINVAL;
2759       }
2760       FLAG_SET_CMDLINE(uintx, MaxNewSize, (uintx)long_initial_young_size);
2761       FLAG_SET_CMDLINE(uintx, NewSize, (uintx)long_initial_young_size);
2762     // -Xms
2763     } else if (match_option(option, "-Xms", &tail)) {
2764       julong long_initial_heap_size = 0;
2765       // an initial heap size of 0 means automatically determine
2766       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2767       if (errcode != arg_in_range) {
2768         jio_fprintf(defaultStream::error_stream(),
2769                     "Invalid initial heap size: %s\n", option->optionString);
2770         describe_range_error(errcode);
2771         return JNI_EINVAL;
2772       }
2773       set_min_heap_size((uintx)long_initial_heap_size);
2774       // Currently the minimum size and the initial heap sizes are the same.
2775       // Can be overridden with -XX:InitialHeapSize.
2776       FLAG_SET_CMDLINE(uintx, InitialHeapSize, (uintx)long_initial_heap_size);
2777     // -Xmx
2778     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2779       julong long_max_heap_size = 0;
2780       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2781       if (errcode != arg_in_range) {
2782         jio_fprintf(defaultStream::error_stream(),
2783                     "Invalid maximum heap size: %s\n", option->optionString);
2784         describe_range_error(errcode);
2785         return JNI_EINVAL;
2786       }
2787       FLAG_SET_CMDLINE(uintx, MaxHeapSize, (uintx)long_max_heap_size);
2788     // Xmaxf
2789     } else if (match_option(option, "-Xmaxf", &tail)) {
2790       char* err;
2791       int maxf = (int)(strtod(tail, &err) * 100);
2792       if (*err != '\0' || *tail == '\0' || maxf < 0 || maxf > 100) {
2793         jio_fprintf(defaultStream::error_stream(),
2794                     "Bad max heap free percentage size: %s\n",
2795                     option->optionString);
2796         return JNI_EINVAL;
2797       } else {
2798         FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf);
2799       }
2800     // Xminf
2801     } else if (match_option(option, "-Xminf", &tail)) {
2802       char* err;
2803       int minf = (int)(strtod(tail, &err) * 100);
2804       if (*err != '\0' || *tail == '\0' || minf < 0 || minf > 100) {
2805         jio_fprintf(defaultStream::error_stream(),
2806                     "Bad min heap free percentage size: %s\n",
2807                     option->optionString);
2808         return JNI_EINVAL;
2809       } else {
2810         FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf);
2811       }
2812     // -Xss
2813     } else if (match_option(option, "-Xss", &tail)) {
2814       julong long_ThreadStackSize = 0;
2815       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2816       if (errcode != arg_in_range) {
2817         jio_fprintf(defaultStream::error_stream(),
2818                     "Invalid thread stack size: %s\n", option->optionString);
2819         describe_range_error(errcode);
2820         return JNI_EINVAL;
2821       }
2822       // Internally track ThreadStackSize in units of 1024 bytes.
2823       FLAG_SET_CMDLINE(intx, ThreadStackSize,
2824                               round_to((int)long_ThreadStackSize, K) / K);
2825     // -Xoss
2826     } else if (match_option(option, "-Xoss", &tail)) {
2827           // HotSpot does not have separate native and Java stacks, ignore silently for compatibility
2828     } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
2829       julong long_CodeCacheExpansionSize = 0;
2830       ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
2831       if (errcode != arg_in_range) {
2832         jio_fprintf(defaultStream::error_stream(),
2833                    "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
2834                    os::vm_page_size()/K);
2835         return JNI_EINVAL;
2836       }
2837       FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize);
2838     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2839                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2840       julong long_ReservedCodeCacheSize = 0;
2841 
2842       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2843       if (errcode != arg_in_range) {
2844         jio_fprintf(defaultStream::error_stream(),
2845                     "Invalid maximum code cache size: %s.\n", option->optionString);
2846         return JNI_EINVAL;
2847       }
2848       FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize);
2849       // -XX:NonNMethodCodeHeapSize=
2850     } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
2851       julong long_NonNMethodCodeHeapSize = 0;
2852 
2853       ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
2854       if (errcode != arg_in_range) {
2855         jio_fprintf(defaultStream::error_stream(),
2856                     "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
2857         return JNI_EINVAL;
2858       }
2859       FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize);
2860       // -XX:ProfiledCodeHeapSize=
2861     } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
2862       julong long_ProfiledCodeHeapSize = 0;
2863 
2864       ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
2865       if (errcode != arg_in_range) {
2866         jio_fprintf(defaultStream::error_stream(),
2867                     "Invalid maximum profiled code heap size: %s.\n", option->optionString);
2868         return JNI_EINVAL;
2869       }
2870       FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize);
2871       // -XX:NonProfiledCodeHeapSizee=
2872     } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
2873       julong long_NonProfiledCodeHeapSize = 0;
2874 
2875       ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
2876       if (errcode != arg_in_range) {
2877         jio_fprintf(defaultStream::error_stream(),
2878                     "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
2879         return JNI_EINVAL;
2880       }
2881       FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize);
2882       //-XX:IncreaseFirstTierCompileThresholdAt=
2883     } else if (match_option(option, "-XX:IncreaseFirstTierCompileThresholdAt=", &tail)) {
2884         uintx uint_IncreaseFirstTierCompileThresholdAt = 0;
2885         if (!parse_uintx(tail, &uint_IncreaseFirstTierCompileThresholdAt, 0) || uint_IncreaseFirstTierCompileThresholdAt > 99) {
2886           jio_fprintf(defaultStream::error_stream(),
2887                       "Invalid value for IncreaseFirstTierCompileThresholdAt: %s. Should be between 0 and 99.\n",
2888                       option->optionString);
2889           return JNI_EINVAL;
2890         }
2891         FLAG_SET_CMDLINE(uintx, IncreaseFirstTierCompileThresholdAt, (uintx)uint_IncreaseFirstTierCompileThresholdAt);
2892     // -green
2893     } else if (match_option(option, "-green")) {
2894       jio_fprintf(defaultStream::error_stream(),
2895                   "Green threads support not available\n");
2896           return JNI_EINVAL;
2897     // -native
2898     } else if (match_option(option, "-native")) {
2899           // HotSpot always uses native threads, ignore silently for compatibility
2900     // -Xsqnopause
2901     } else if (match_option(option, "-Xsqnopause")) {
2902           // EVM option, ignore silently for compatibility
2903     // -Xrs
2904     } else if (match_option(option, "-Xrs")) {
2905           // Classic/EVM option, new functionality
2906       FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true);
2907     } else if (match_option(option, "-Xusealtsigs")) {
2908           // change default internal VM signals used - lower case for back compat
2909       FLAG_SET_CMDLINE(bool, UseAltSigs, true);
2910     // -Xoptimize
2911     } else if (match_option(option, "-Xoptimize")) {
2912           // EVM option, ignore silently for compatibility
2913     // -Xprof
2914     } else if (match_option(option, "-Xprof")) {
2915 #if INCLUDE_FPROF
2916       _has_profile = true;
2917 #else // INCLUDE_FPROF
2918       jio_fprintf(defaultStream::error_stream(),
2919         "Flat profiling is not supported in this VM.\n");
2920       return JNI_ERR;
2921 #endif // INCLUDE_FPROF
2922     // -Xconcurrentio
2923     } else if (match_option(option, "-Xconcurrentio")) {
2924       FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true);
2925       FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2926       FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1);
2927       FLAG_SET_CMDLINE(bool, UseTLAB, false);
2928       FLAG_SET_CMDLINE(uintx, NewSizeThreadIncrease, 16 * K);  // 20Kb per thread added to new generation
2929 
2930       // -Xinternalversion
2931     } else if (match_option(option, "-Xinternalversion")) {
2932       jio_fprintf(defaultStream::output_stream(), "%s\n",
2933                   VM_Version::internal_vm_info_string());
2934       vm_exit(0);
2935 #ifndef PRODUCT
2936     // -Xprintflags
2937     } else if (match_option(option, "-Xprintflags")) {
2938       CommandLineFlags::printFlags(tty, false);
2939       vm_exit(0);
2940 #endif
2941     // -D
2942     } else if (match_option(option, "-D", &tail)) {
2943       const char* value;
2944       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2945             *value!= '\0' && strcmp(value, "\"\"") != 0) {
2946         // abort if -Djava.endorsed.dirs is set
2947         jio_fprintf(defaultStream::output_stream(),
2948           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2949           "in modular form will be supported via the concept of upgradeable modules.\n", value);
2950         return JNI_EINVAL;
2951       }
2952       if (match_option(option, "-Djava.ext.dirs=", &value) &&
2953             *value != '\0' && strcmp(value, "\"\"") != 0) {
2954         // abort if -Djava.ext.dirs is set
2955         jio_fprintf(defaultStream::output_stream(),
2956           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2957         return JNI_EINVAL;
2958       }
2959 
2960       if (!add_property(tail)) {
2961         return JNI_ENOMEM;
2962       }
2963       // Out of the box management support
2964       if (match_option(option, "-Dcom.sun.management", &tail)) {
2965 #if INCLUDE_MANAGEMENT
2966         FLAG_SET_CMDLINE(bool, ManagementServer, true);
2967 #else
2968         jio_fprintf(defaultStream::output_stream(),
2969           "-Dcom.sun.management is not supported in this VM.\n");
2970         return JNI_ERR;
2971 #endif
2972       }
2973     // -Xint
2974     } else if (match_option(option, "-Xint")) {
2975           set_mode_flags(_int);
2976     // -Xmixed
2977     } else if (match_option(option, "-Xmixed")) {
2978           set_mode_flags(_mixed);
2979     // -Xcomp
2980     } else if (match_option(option, "-Xcomp")) {
2981       // for testing the compiler; turn off all flags that inhibit compilation
2982           set_mode_flags(_comp);
2983     // -Xshare:dump
2984     } else if (match_option(option, "-Xshare:dump")) {
2985       FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);
2986       set_mode_flags(_int);     // Prevent compilation, which creates objects
2987     // -Xshare:on
2988     } else if (match_option(option, "-Xshare:on")) {
2989       FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
2990       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
2991     // -Xshare:auto
2992     } else if (match_option(option, "-Xshare:auto")) {
2993       FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
2994       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
2995     // -Xshare:off
2996     } else if (match_option(option, "-Xshare:off")) {
2997       FLAG_SET_CMDLINE(bool, UseSharedSpaces, false);
2998       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
2999     // -Xverify
3000     } else if (match_option(option, "-Xverify", &tail)) {
3001       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
3002         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true);
3003         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
3004       } else if (strcmp(tail, ":remote") == 0) {
3005         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
3006         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
3007       } else if (strcmp(tail, ":none") == 0) {
3008         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
3009         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false);
3010       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3011         return JNI_EINVAL;
3012       }
3013     // -Xdebug
3014     } else if (match_option(option, "-Xdebug")) {
3015       // note this flag has been used, then ignore
3016       set_xdebug_mode(true);
3017     // -Xnoagent
3018     } else if (match_option(option, "-Xnoagent")) {
3019       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3020     } else if (match_option(option, "-Xboundthreads")) {
3021       // Bind user level threads to kernel threads (Solaris only)
3022       FLAG_SET_CMDLINE(bool, UseBoundThreads, true);
3023     } else if (match_option(option, "-Xloggc:", &tail)) {
3024       // Redirect GC output to the file. -Xloggc:<filename>
3025       // ostream_init_log(), when called will use this filename
3026       // to initialize a fileStream.
3027       _gc_log_filename = os::strdup_check_oom(tail);
3028      if (!is_filename_valid(_gc_log_filename)) {
3029        jio_fprintf(defaultStream::output_stream(),
3030                   "Invalid file name for use with -Xloggc: Filename can only contain the "
3031                   "characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"
3032                   "Note %%p or %%t can only be used once\n", _gc_log_filename);
3033         return JNI_EINVAL;
3034       }
3035       FLAG_SET_CMDLINE(bool, PrintGC, true);
3036       FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true);
3037 
3038     // JNI hooks
3039     } else if (match_option(option, "-Xcheck", &tail)) {
3040       if (!strcmp(tail, ":jni")) {
3041 #if !INCLUDE_JNI_CHECK
3042         warning("JNI CHECKING is not supported in this VM");
3043 #else
3044         CheckJNICalls = true;
3045 #endif // INCLUDE_JNI_CHECK
3046       } else if (is_bad_option(option, args->ignoreUnrecognized,
3047                                      "check")) {
3048         return JNI_EINVAL;
3049       }
3050     } else if (match_option(option, "vfprintf")) {
3051       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3052     } else if (match_option(option, "exit")) {
3053       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3054     } else if (match_option(option, "abort")) {
3055       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3056     // -XX:+AggressiveHeap
3057     } else if (match_option(option, "-XX:+AggressiveHeap")) {
3058 
3059       // This option inspects the machine and attempts to set various
3060       // parameters to be optimal for long-running, memory allocation
3061       // intensive jobs.  It is intended for machines with large
3062       // amounts of cpu and memory.
3063 
3064       // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
3065       // VM, but we may not be able to represent the total physical memory
3066       // available (like having 8gb of memory on a box but using a 32bit VM).
3067       // Thus, we need to make sure we're using a julong for intermediate
3068       // calculations.
3069       julong initHeapSize;
3070       julong total_memory = os::physical_memory();
3071 
3072       if (total_memory < (julong)256*M) {
3073         jio_fprintf(defaultStream::error_stream(),
3074                     "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
3075         vm_exit(1);
3076       }
3077 
3078       // The heap size is half of available memory, or (at most)
3079       // all of possible memory less 160mb (leaving room for the OS
3080       // when using ISM).  This is the maximum; because adaptive sizing
3081       // is turned on below, the actual space used may be smaller.
3082 
3083       initHeapSize = MIN2(total_memory / (julong)2,
3084                           total_memory - (julong)160*M);
3085 
3086       initHeapSize = limit_by_allocatable_memory(initHeapSize);
3087 
3088       if (FLAG_IS_DEFAULT(MaxHeapSize)) {
3089          FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);
3090          FLAG_SET_CMDLINE(uintx, InitialHeapSize, initHeapSize);
3091          // Currently the minimum size and the initial heap sizes are the same.
3092          set_min_heap_size(initHeapSize);
3093       }
3094       if (FLAG_IS_DEFAULT(NewSize)) {
3095          // Make the young generation 3/8ths of the total heap.
3096          FLAG_SET_CMDLINE(uintx, NewSize,
3097                                 ((julong)MaxHeapSize / (julong)8) * (julong)3);
3098          FLAG_SET_CMDLINE(uintx, MaxNewSize, NewSize);
3099       }
3100 
3101 #ifndef _ALLBSD_SOURCE  // UseLargePages is not yet supported on BSD.
3102       FLAG_SET_DEFAULT(UseLargePages, true);
3103 #endif
3104 
3105       // Increase some data structure sizes for efficiency
3106       FLAG_SET_CMDLINE(uintx, BaseFootPrintEstimate, MaxHeapSize);
3107       FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
3108       FLAG_SET_CMDLINE(uintx, TLABSize, 256*K);
3109 
3110       // See the OldPLABSize comment below, but replace 'after promotion'
3111       // with 'after copying'.  YoungPLABSize is the size of the survivor
3112       // space per-gc-thread buffers.  The default is 4kw.
3113       FLAG_SET_CMDLINE(uintx, YoungPLABSize, 256*K);      // Note: this is in words
3114 
3115       // OldPLABSize is the size of the buffers in the old gen that
3116       // UseParallelGC uses to promote live data that doesn't fit in the
3117       // survivor spaces.  At any given time, there's one for each gc thread.
3118       // The default size is 1kw. These buffers are rarely used, since the
3119       // survivor spaces are usually big enough.  For specjbb, however, there
3120       // are occasions when there's lots of live data in the young gen
3121       // and we end up promoting some of it.  We don't have a definite
3122       // explanation for why bumping OldPLABSize helps, but the theory
3123       // is that a bigger PLAB results in retaining something like the
3124       // original allocation order after promotion, which improves mutator
3125       // locality.  A minor effect may be that larger PLABs reduce the
3126       // number of PLAB allocation events during gc.  The value of 8kw
3127       // was arrived at by experimenting with specjbb.
3128       FLAG_SET_CMDLINE(uintx, OldPLABSize, 8*K);  // Note: this is in words
3129 
3130       // Enable parallel GC and adaptive generation sizing
3131       FLAG_SET_CMDLINE(bool, UseParallelGC, true);
3132       FLAG_SET_DEFAULT(ParallelGCThreads,
3133                        Abstract_VM_Version::parallel_worker_threads());
3134 
3135       // Encourage steady state memory management
3136       FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);
3137 
3138       // This appears to improve mutator locality
3139       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
3140 
3141       // Get around early Solaris scheduling bug
3142       // (affinity vs other jobs on system)
3143       // but disallow DR and offlining (5008695).
3144       FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);
3145 
3146     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
3147     // and the last option wins.
3148     } else if (match_option(option, "-XX:+NeverTenure")) {
3149       FLAG_SET_CMDLINE(bool, NeverTenure, true);
3150       FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
3151       FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1);
3152     } else if (match_option(option, "-XX:+AlwaysTenure")) {
3153       FLAG_SET_CMDLINE(bool, NeverTenure, false);
3154       FLAG_SET_CMDLINE(bool, AlwaysTenure, true);
3155       FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0);
3156     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
3157       uintx max_tenuring_thresh = 0;
3158       if(!parse_uintx(tail, &max_tenuring_thresh, 0)) {
3159         jio_fprintf(defaultStream::error_stream(),
3160                     "Invalid MaxTenuringThreshold: %s\n", option->optionString);
3161       }
3162       FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh);
3163 
3164       if (MaxTenuringThreshold == 0) {
3165         FLAG_SET_CMDLINE(bool, NeverTenure, false);
3166         FLAG_SET_CMDLINE(bool, AlwaysTenure, true);
3167       } else {
3168         FLAG_SET_CMDLINE(bool, NeverTenure, false);
3169         FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
3170       }
3171     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3172       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false);
3173       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true);
3174     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3175       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false);
3176       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true);
3177     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3178 #if defined(DTRACE_ENABLED)
3179       FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true);
3180       FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true);
3181       FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true);
3182       FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true);
3183 #else // defined(DTRACE_ENABLED)
3184       jio_fprintf(defaultStream::error_stream(),
3185                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3186       return JNI_EINVAL;
3187 #endif // defined(DTRACE_ENABLED)
3188 #ifdef ASSERT
3189     } else if (match_option(option, "-XX:+FullGCALot")) {
3190       FLAG_SET_CMDLINE(bool, FullGCALot, true);
3191       // disable scavenge before parallel mark-compact
3192       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
3193 #endif
3194     } else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||
3195                match_option(option, "-XX:G1MarkStackSize=", &tail)) {
3196       julong stack_size = 0;
3197       ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);
3198       if (errcode != arg_in_range) {
3199         jio_fprintf(defaultStream::error_stream(),
3200                     "Invalid mark stack size: %s\n", option->optionString);
3201         describe_range_error(errcode);
3202         return JNI_EINVAL;
3203       }
3204       jio_fprintf(defaultStream::error_stream(),
3205         "Please use -XX:MarkStackSize in place of "
3206         "-XX:CMSMarkStackSize or -XX:G1MarkStackSize in the future\n");
3207       FLAG_SET_CMDLINE(uintx, MarkStackSize, stack_size);
3208     } else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {
3209       julong max_stack_size = 0;
3210       ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);
3211       if (errcode != arg_in_range) {
3212         jio_fprintf(defaultStream::error_stream(),
3213                     "Invalid maximum mark stack size: %s\n",
3214                     option->optionString);
3215         describe_range_error(errcode);
3216         return JNI_EINVAL;
3217       }
3218       jio_fprintf(defaultStream::error_stream(),
3219          "Please use -XX:MarkStackSizeMax in place of "
3220          "-XX:CMSMarkStackSizeMax in the future\n");
3221       FLAG_SET_CMDLINE(uintx, MarkStackSizeMax, max_stack_size);
3222     } else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||
3223                match_option(option, "-XX:ParallelCMSThreads=", &tail)) {
3224       uintx conc_threads = 0;
3225       if (!parse_uintx(tail, &conc_threads, 1)) {
3226         jio_fprintf(defaultStream::error_stream(),
3227                     "Invalid concurrent threads: %s\n", option->optionString);
3228         return JNI_EINVAL;
3229       }
3230       jio_fprintf(defaultStream::error_stream(),
3231         "Please use -XX:ConcGCThreads in place of "
3232         "-XX:ParallelMarkingThreads or -XX:ParallelCMSThreads in the future\n");
3233       FLAG_SET_CMDLINE(uintx, ConcGCThreads, conc_threads);
3234     } else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {
3235       julong max_direct_memory_size = 0;
3236       ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);
3237       if (errcode != arg_in_range) {
3238         jio_fprintf(defaultStream::error_stream(),
3239                     "Invalid maximum direct memory size: %s\n",
3240                     option->optionString);
3241         describe_range_error(errcode);
3242         return JNI_EINVAL;
3243       }
3244       FLAG_SET_CMDLINE(uintx, MaxDirectMemorySize, max_direct_memory_size);
3245 #if !INCLUDE_MANAGEMENT
3246     } else if (match_option(option, "-XX:+ManagementServer")) {
3247         jio_fprintf(defaultStream::error_stream(),
3248           "ManagementServer is not supported in this VM.\n");
3249         return JNI_ERR;
3250 #endif // INCLUDE_MANAGEMENT
3251     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3252       // Skip -XX:Flags= since that case has already been handled
3253       if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
3254         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3255           return JNI_EINVAL;
3256         }
3257       }
3258     // Unknown option
3259     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3260       return JNI_ERR;
3261     }
3262   }
3263 
3264   // PrintSharedArchiveAndExit will turn on
3265   //   -Xshare:on
3266   //   -XX:+TraceClassPaths
3267   if (PrintSharedArchiveAndExit) {
3268     FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
3269     FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
3270     FLAG_SET_CMDLINE(bool, TraceClassPaths, true);
3271   }
3272 
3273   // Change the default value for flags  which have different default values
3274   // when working with older JDKs.
3275 #ifdef LINUX
3276  if (JDK_Version::current().compare_major(6) <= 0 &&
3277       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3278     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3279   }
3280 #endif // LINUX
3281   fix_appclasspath();
3282   return JNI_OK;
3283 }
3284 
3285 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3286 //
3287 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3288 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3289 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3290 // path is treated as the current directory.
3291 //
3292 // This causes problems with CDS, which requires that all directories specified in the classpath
3293 // must be empty. In most cases, applications do NOT want to load classes from the current
3294 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3295 // scripts compatible with CDS.
3296 void Arguments::fix_appclasspath() {
3297   if (IgnoreEmptyClassPaths) {
3298     const char separator = *os::path_separator();
3299     const char* src = _java_class_path->value();
3300 
3301     // skip over all the leading empty paths
3302     while (*src == separator) {
3303       src ++;
3304     }
3305 
3306     char* copy = AllocateHeap(strlen(src) + 1, mtInternal);
3307     strncpy(copy, src, strlen(src) + 1);
3308 
3309     // trim all trailing empty paths
3310     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3311       *tail = '\0';
3312     }
3313 
3314     char from[3] = {separator, separator, '\0'};
3315     char to  [2] = {separator, '\0'};
3316     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3317       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3318       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3319     }
3320 
3321     _java_class_path->set_value(copy);
3322     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3323   }
3324 
3325   if (!PrintSharedArchiveAndExit) {
3326     ClassLoader::trace_class_path("[classpath: ", _java_class_path->value());
3327   }
3328 }
3329 
3330 static bool has_jar_files(const char* directory) {
3331   DIR* dir = os::opendir(directory);
3332   if (dir == NULL) return false;
3333 
3334   struct dirent *entry;
3335   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
3336   bool hasJarFile = false;
3337   while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3338     const char* name = entry->d_name;
3339     const char* ext = name + strlen(name) - 4;
3340     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3341   }
3342   FREE_C_HEAP_ARRAY(char, dbuf);
3343   os::closedir(dir);
3344   return hasJarFile ;
3345 }
3346 
3347 static int check_non_empty_dirs(const char* path) {
3348   const char separator = *os::path_separator();
3349   const char* const end = path + strlen(path);
3350   int nonEmptyDirs = 0;
3351   while (path < end) {
3352     const char* tmp_end = strchr(path, separator);
3353     if (tmp_end == NULL) {
3354       if (has_jar_files(path)) {
3355         nonEmptyDirs++;
3356         jio_fprintf(defaultStream::output_stream(),
3357           "Non-empty directory: %s\n", path);
3358       }
3359       path = end;
3360     } else {
3361       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
3362       memcpy(dirpath, path, tmp_end - path);
3363       dirpath[tmp_end - path] = '\0';
3364       if (has_jar_files(dirpath)) {
3365         nonEmptyDirs++;
3366         jio_fprintf(defaultStream::output_stream(),
3367           "Non-empty directory: %s\n", dirpath);
3368       }
3369       FREE_C_HEAP_ARRAY(char, dirpath);
3370       path = tmp_end + 1;
3371     }
3372   }
3373   return nonEmptyDirs;
3374 }
3375 
3376 jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
3377   // check if the default lib/endorsed directory exists; if so, error
3378   char path[JVM_MAXPATHLEN];
3379   const char* fileSep = os::file_separator();
3380   sprintf(path, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3381 
3382   if (CheckEndorsedAndExtDirs) {
3383     int nonEmptyDirs = 0;
3384     // check endorsed directory
3385     nonEmptyDirs += check_non_empty_dirs(path);
3386     // check the extension directories
3387     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3388     if (nonEmptyDirs > 0) {
3389       return JNI_ERR;
3390     }
3391   }
3392 
3393   DIR* dir = os::opendir(path);
3394   if (dir != NULL) {
3395     jio_fprintf(defaultStream::output_stream(),
3396       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3397       "in modular form will be supported via the concept of upgradeable modules.\n");
3398     os::closedir(dir);
3399     return JNI_ERR;
3400   }
3401 
3402   sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3403   dir = os::opendir(path);
3404   if (dir != NULL) {
3405     jio_fprintf(defaultStream::output_stream(),
3406       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3407       "Use -classpath instead.\n.");
3408     os::closedir(dir);
3409     return JNI_ERR;
3410   }
3411 
3412   if (scp_assembly_required) {
3413     // Assemble the bootclasspath elements into the final path.
3414     Arguments::set_sysclasspath(scp_p->combined_path());
3415   }
3416 
3417   // This must be done after all arguments have been processed.
3418   // java_compiler() true means set to "NONE" or empty.
3419   if (java_compiler() && !xdebug_mode()) {
3420     // For backwards compatibility, we switch to interpreted mode if
3421     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3422     // not specified.
3423     set_mode_flags(_int);
3424   }
3425 
3426   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3427   // but like -Xint, leave compilation thresholds unaffected.
3428   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3429   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3430     set_mode_flags(_int);
3431   }
3432 
3433   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3434   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3435     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3436   }
3437 
3438 #ifndef COMPILER2
3439   // Don't degrade server performance for footprint
3440   if (FLAG_IS_DEFAULT(UseLargePages) &&
3441       MaxHeapSize < LargePageHeapSizeThreshold) {
3442     // No need for large granularity pages w/small heaps.
3443     // Note that large pages are enabled/disabled for both the
3444     // Java heap and the code cache.
3445     FLAG_SET_DEFAULT(UseLargePages, false);
3446   }
3447 
3448 #else
3449   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3450     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3451   }
3452 #endif
3453 
3454 #ifndef TIERED
3455   // Tiered compilation is undefined.
3456   UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
3457 #endif
3458 
3459   // If we are running in a headless jre, force java.awt.headless property
3460   // to be true unless the property has already been set.
3461   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3462   if (os::is_headless_jre()) {
3463     const char* headless = Arguments::get_property("java.awt.headless");
3464     if (headless == NULL) {
3465       char envbuffer[128];
3466       if (!os::getenv("JAVA_AWT_HEADLESS", envbuffer, sizeof(envbuffer))) {
3467         if (!add_property("java.awt.headless=true")) {
3468           return JNI_ENOMEM;
3469         }
3470       } else {
3471         char buffer[256];
3472         strcpy(buffer, "java.awt.headless=");
3473         strcat(buffer, envbuffer);
3474         if (!add_property(buffer)) {
3475           return JNI_ENOMEM;
3476         }
3477       }
3478     }
3479   }
3480 
3481   if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3482     // CMS can only be used with ParNew
3483     FLAG_SET_ERGO(bool, UseParNewGC, true);
3484   }
3485 
3486   if (!check_vm_args_consistency()) {
3487     return JNI_ERR;
3488   }
3489 
3490   return JNI_OK;
3491 }
3492 
3493 jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3494   return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,
3495                                             scp_assembly_required_p);
3496 }
3497 
3498 jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3499   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,
3500                                             scp_assembly_required_p);
3501 }
3502 
3503 jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {
3504   const int N_MAX_OPTIONS = 64;
3505   const int OPTION_BUFFER_SIZE = 1024;
3506   char buffer[OPTION_BUFFER_SIZE];
3507 
3508   // The variable will be ignored if it exceeds the length of the buffer.
3509   // Don't check this variable if user has special privileges
3510   // (e.g. unix su command).
3511   if (os::getenv(name, buffer, sizeof(buffer)) &&
3512       !os::have_special_privileges()) {
3513     JavaVMOption options[N_MAX_OPTIONS];      // Construct option array
3514     jio_fprintf(defaultStream::error_stream(),
3515                 "Picked up %s: %s\n", name, buffer);
3516     char* rd = buffer;                        // pointer to the input string (rd)
3517     int i;
3518     for (i = 0; i < N_MAX_OPTIONS;) {         // repeat for all options in the input string
3519       while (isspace(*rd)) rd++;              // skip whitespace
3520       if (*rd == 0) break;                    // we re done when the input string is read completely
3521 
3522       // The output, option string, overwrites the input string.
3523       // Because of quoting, the pointer to the option string (wrt) may lag the pointer to
3524       // input string (rd).
3525       char* wrt = rd;
3526 
3527       options[i++].optionString = wrt;        // Fill in option
3528       while (*rd != 0 && !isspace(*rd)) {     // unquoted strings terminate with a space or NULL
3529         if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3530           int quote = *rd;                    // matching quote to look for
3531           rd++;                               // don't copy open quote
3532           while (*rd != quote) {              // include everything (even spaces) up until quote
3533             if (*rd == 0) {                   // string termination means unmatched string
3534               jio_fprintf(defaultStream::error_stream(),
3535                           "Unmatched quote in %s\n", name);
3536               return JNI_ERR;
3537             }
3538             *wrt++ = *rd++;                   // copy to option string
3539           }
3540           rd++;                               // don't copy close quote
3541         } else {
3542           *wrt++ = *rd++;                     // copy to option string
3543         }
3544       }
3545       // Need to check if we're done before writing a NULL,
3546       // because the write could be to the byte that rd is pointing to.
3547       if (*rd++ == 0) {
3548         *wrt = 0;
3549         break;
3550       }
3551       *wrt = 0;                               // Zero terminate option
3552     }
3553     // Construct JavaVMInitArgs structure and parse as if it was part of the command line
3554     JavaVMInitArgs vm_args;
3555     vm_args.version = JNI_VERSION_1_2;
3556     vm_args.options = options;
3557     vm_args.nOptions = i;
3558     vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3559 
3560     if (PrintVMOptions) {
3561       const char* tail;
3562       for (int i = 0; i < vm_args.nOptions; i++) {
3563         const JavaVMOption *option = vm_args.options + i;
3564         if (match_option(option, "-XX:", &tail)) {
3565           logOption(tail);
3566         }
3567       }
3568     }
3569 
3570     return(parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p, Flag::ENVIRON_VAR));
3571   }
3572   return JNI_OK;
3573 }
3574 
3575 void Arguments::set_shared_spaces_flags() {
3576   if (DumpSharedSpaces) {
3577     if (RequireSharedSpaces) {
3578       warning("cannot dump shared archive while using shared archive");
3579     }
3580     UseSharedSpaces = false;
3581 #ifdef _LP64
3582     if (!UseCompressedOops || !UseCompressedClassPointers) {
3583       vm_exit_during_initialization(
3584         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3585     }
3586   } else {
3587     if (!UseCompressedOops || !UseCompressedClassPointers) {
3588       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3589     }
3590 #endif
3591   }
3592 }
3593 
3594 #if !INCLUDE_ALL_GCS
3595 static void force_serial_gc() {
3596   FLAG_SET_DEFAULT(UseSerialGC, true);
3597   UNSUPPORTED_GC_OPTION(UseG1GC);
3598   UNSUPPORTED_GC_OPTION(UseParallelGC);
3599   UNSUPPORTED_GC_OPTION(UseParallelOldGC);
3600   UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
3601   UNSUPPORTED_GC_OPTION(UseParNewGC);
3602 }
3603 #endif // INCLUDE_ALL_GCS
3604 
3605 // Sharing support
3606 // Construct the path to the archive
3607 static char* get_shared_archive_path() {
3608   char *shared_archive_path;
3609   if (SharedArchiveFile == NULL) {
3610     char jvm_path[JVM_MAXPATHLEN];
3611     os::jvm_path(jvm_path, sizeof(jvm_path));
3612     char *end = strrchr(jvm_path, *os::file_separator());
3613     if (end != NULL) *end = '\0';
3614     size_t jvm_path_len = strlen(jvm_path);
3615     size_t file_sep_len = strlen(os::file_separator());
3616     shared_archive_path = NEW_C_HEAP_ARRAY(char, jvm_path_len +
3617         file_sep_len + 20, mtInternal);
3618     if (shared_archive_path != NULL) {
3619       strncpy(shared_archive_path, jvm_path, jvm_path_len + 1);
3620       strncat(shared_archive_path, os::file_separator(), file_sep_len);
3621       strncat(shared_archive_path, "classes.jsa", 11);
3622     }
3623   } else {
3624     shared_archive_path = NEW_C_HEAP_ARRAY(char, strlen(SharedArchiveFile) + 1, mtInternal);
3625     if (shared_archive_path != NULL) {
3626       strncpy(shared_archive_path, SharedArchiveFile, strlen(SharedArchiveFile) + 1);
3627     }
3628   }
3629   return shared_archive_path;
3630 }
3631 
3632 #ifndef PRODUCT
3633 // Determine whether LogVMOutput should be implicitly turned on.
3634 static bool use_vm_log() {
3635   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3636       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3637       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3638       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3639       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3640     return true;
3641   }
3642 
3643 #ifdef COMPILER1
3644   if (PrintC1Statistics) {
3645     return true;
3646   }
3647 #endif // COMPILER1
3648 
3649 #ifdef COMPILER2
3650   if (PrintOptoAssembly || PrintOptoStatistics) {
3651     return true;
3652   }
3653 #endif // COMPILER2
3654 
3655   return false;
3656 }
3657 #endif // PRODUCT
3658 
3659 // Parse entry point called from JNI_CreateJavaVM
3660 
3661 jint Arguments::parse(const JavaVMInitArgs* args) {
3662 
3663   // Remaining part of option string
3664   const char* tail;
3665 
3666   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3667   const char* hotspotrc = ".hotspotrc";
3668   bool settings_file_specified = false;
3669   bool needs_hotspotrc_warning = false;
3670 
3671   const char* flags_file;
3672   int index;
3673   for (index = 0; index < args->nOptions; index++) {
3674     const JavaVMOption *option = args->options + index;
3675     if (ArgumentsExt::process_options(option)) {
3676       continue;
3677     }
3678     if (match_option(option, "-XX:Flags=", &tail)) {
3679       flags_file = tail;
3680       settings_file_specified = true;
3681       continue;
3682     }
3683     if (match_option(option, "-XX:+PrintVMOptions")) {
3684       PrintVMOptions = true;
3685       continue;
3686     }
3687     if (match_option(option, "-XX:-PrintVMOptions")) {
3688       PrintVMOptions = false;
3689       continue;
3690     }
3691     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3692       IgnoreUnrecognizedVMOptions = true;
3693       continue;
3694     }
3695     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3696       IgnoreUnrecognizedVMOptions = false;
3697       continue;
3698     }
3699     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3700       CommandLineFlags::printFlags(tty, false);
3701       vm_exit(0);
3702     }
3703 #if INCLUDE_NMT
3704     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3705       // The launcher did not setup nmt environment variable properly.
3706       if (!MemTracker::check_launcher_nmt_support(tail)) {
3707         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3708       }
3709 
3710       // Verify if nmt option is valid.
3711       if (MemTracker::verify_nmt_option()) {
3712         // Late initialization, still in single-threaded mode.
3713         if (MemTracker::tracking_level() >= NMT_summary) {
3714           MemTracker::init();
3715         }
3716       } else {
3717         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3718       }
3719       continue;
3720     }
3721 #endif
3722 
3723 
3724 #ifndef PRODUCT
3725     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3726       CommandLineFlags::printFlags(tty, true);
3727       vm_exit(0);
3728     }
3729 #endif
3730   }
3731 
3732   if (IgnoreUnrecognizedVMOptions) {
3733     // uncast const to modify the flag args->ignoreUnrecognized
3734     *(jboolean*)(&args->ignoreUnrecognized) = true;
3735   }
3736 
3737   // Parse specified settings file
3738   if (settings_file_specified) {
3739     if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
3740       return JNI_EINVAL;
3741     }
3742   } else {
3743 #ifdef ASSERT
3744     // Parse default .hotspotrc settings file
3745     if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
3746       return JNI_EINVAL;
3747     }
3748 #else
3749     struct stat buf;
3750     if (os::stat(hotspotrc, &buf) == 0) {
3751       needs_hotspotrc_warning = true;
3752     }
3753 #endif
3754   }
3755 
3756   if (PrintVMOptions) {
3757     for (index = 0; index < args->nOptions; index++) {
3758       const JavaVMOption *option = args->options + index;
3759       if (match_option(option, "-XX:", &tail)) {
3760         logOption(tail);
3761       }
3762     }
3763   }
3764 
3765   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
3766   jint result = parse_vm_init_args(args);
3767   if (result != JNI_OK) {
3768     return result;
3769   }
3770 
3771   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
3772   SharedArchivePath = get_shared_archive_path();
3773   if (SharedArchivePath == NULL) {
3774     return JNI_ENOMEM;
3775   }
3776 
3777   // Set up VerifySharedSpaces
3778   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
3779     VerifySharedSpaces = true;
3780   }
3781 
3782   // Delay warning until here so that we've had a chance to process
3783   // the -XX:-PrintWarnings flag
3784   if (needs_hotspotrc_warning) {
3785     warning("%s file is present but has been ignored.  "
3786             "Run with -XX:Flags=%s to load the file.",
3787             hotspotrc, hotspotrc);
3788   }
3789 
3790 #ifdef _ALLBSD_SOURCE  // UseLargePages is not yet supported on BSD.
3791   UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
3792 #endif
3793 
3794   ArgumentsExt::report_unsupported_options();
3795 
3796 #ifndef PRODUCT
3797   if (TraceBytecodesAt != 0) {
3798     TraceBytecodes = true;
3799   }
3800   if (CountCompiledCalls) {
3801     if (UseCounterDecay) {
3802       warning("UseCounterDecay disabled because CountCalls is set");
3803       UseCounterDecay = false;
3804     }
3805   }
3806 #endif // PRODUCT
3807 
3808   if (ScavengeRootsInCode == 0) {
3809     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3810       warning("forcing ScavengeRootsInCode non-zero");
3811     }
3812     ScavengeRootsInCode = 1;
3813   }
3814 
3815   if (PrintGCDetails) {
3816     // Turn on -verbose:gc options as well
3817     PrintGC = true;
3818   }
3819 
3820   // Set object alignment values.
3821   set_object_alignment();
3822 
3823 #if !INCLUDE_ALL_GCS
3824   force_serial_gc();
3825 #endif // INCLUDE_ALL_GCS
3826 #if !INCLUDE_CDS
3827   if (DumpSharedSpaces || RequireSharedSpaces) {
3828     jio_fprintf(defaultStream::error_stream(),
3829       "Shared spaces are not supported in this VM\n");
3830     return JNI_ERR;
3831   }
3832   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
3833     warning("Shared spaces are not supported in this VM");
3834     FLAG_SET_DEFAULT(UseSharedSpaces, false);
3835     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
3836   }
3837   no_shared_spaces("CDS Disabled");
3838 #endif // INCLUDE_CDS
3839 
3840   return JNI_OK;
3841 }
3842 
3843 jint Arguments::apply_ergo() {
3844 
3845   // Set flags based on ergonomics.
3846   set_ergonomics_flags();
3847 
3848   set_shared_spaces_flags();
3849 
3850   // Check the GC selections again.
3851   if (!ArgumentsExt::check_gc_consistency_ergo()) {
3852     return JNI_EINVAL;
3853   }
3854 
3855   if (TieredCompilation) {
3856     set_tiered_flags();
3857   } else {
3858     // Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup.
3859     if (CompilationPolicyChoice >= 2) {
3860       vm_exit_during_initialization(
3861         "Incompatible compilation policy selected", NULL);
3862     }
3863     // Scale CompileThreshold
3864     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
3865     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
3866       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
3867     }
3868   }
3869 
3870 #ifdef COMPILER2
3871 #ifndef PRODUCT
3872   if (PrintIdealGraphLevel > 0) {
3873     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
3874   }
3875 #endif
3876 #endif
3877 
3878   // Set heap size based on available physical memory
3879   set_heap_size();
3880 
3881   ArgumentsExt::set_gc_specific_flags();
3882 
3883   // Initialize Metaspace flags and alignments
3884   Metaspace::ergo_initialize();
3885 
3886   // Set bytecode rewriting flags
3887   set_bytecode_flags();
3888 
3889   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
3890   set_aggressive_opts_flags();
3891 
3892   // Turn off biased locking for locking debug mode flags,
3893   // which are subtly different from each other but neither works with
3894   // biased locking
3895   if (UseHeavyMonitors
3896 #ifdef COMPILER1
3897       || !UseFastLocking
3898 #endif // COMPILER1
3899     ) {
3900     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
3901       // flag set to true on command line; warn the user that they
3902       // can't enable biased locking here
3903       warning("Biased Locking is not supported with locking debug flags"
3904               "; ignoring UseBiasedLocking flag." );
3905     }
3906     UseBiasedLocking = false;
3907   }
3908 
3909 #ifdef ZERO
3910   // Clear flags not supported on zero.
3911   FLAG_SET_DEFAULT(ProfileInterpreter, false);
3912   FLAG_SET_DEFAULT(UseBiasedLocking, false);
3913   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
3914   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
3915 #endif // CC_INTERP
3916 
3917 #ifdef COMPILER2
3918   if (!EliminateLocks) {
3919     EliminateNestedLocks = false;
3920   }
3921   if (!Inline) {
3922     IncrementalInline = false;
3923   }
3924 #ifndef PRODUCT
3925   if (!IncrementalInline) {
3926     AlwaysIncrementalInline = false;
3927   }
3928 #endif
3929   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
3930     // nothing to use the profiling, turn if off
3931     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
3932   }
3933 #endif
3934 
3935   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
3936     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
3937     DebugNonSafepoints = true;
3938   }
3939 
3940   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
3941     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
3942   }
3943 
3944 #ifndef PRODUCT
3945   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
3946     if (use_vm_log()) {
3947       LogVMOutput = true;
3948     }
3949   }
3950 #endif // PRODUCT
3951 
3952   if (PrintCommandLineFlags) {
3953     CommandLineFlags::printSetFlags(tty);
3954   }
3955 
3956   // Apply CPU specific policy for the BiasedLocking
3957   if (UseBiasedLocking) {
3958     if (!VM_Version::use_biased_locking() &&
3959         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
3960       UseBiasedLocking = false;
3961     }
3962   }
3963 #ifdef COMPILER2
3964   if (!UseBiasedLocking || EmitSync != 0) {
3965     UseOptoBiasInlining = false;
3966   }
3967 #endif
3968 
3969   return JNI_OK;
3970 }
3971 
3972 jint Arguments::adjust_after_os() {
3973   if (UseNUMA) {
3974     if (UseParallelGC || UseParallelOldGC) {
3975       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
3976          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
3977       }
3978     }
3979     // UseNUMAInterleaving is set to ON for all collectors and
3980     // platforms when UseNUMA is set to ON. NUMA-aware collectors
3981     // such as the parallel collector for Linux and Solaris will
3982     // interleave old gen and survivor spaces on top of NUMA
3983     // allocation policy for the eden space.
3984     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
3985     // all platforms and ParallelGC on Windows will interleave all
3986     // of the heap spaces across NUMA nodes.
3987     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
3988       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
3989     }
3990   }
3991   return JNI_OK;
3992 }
3993 
3994 int Arguments::PropertyList_count(SystemProperty* pl) {
3995   int count = 0;
3996   while(pl != NULL) {
3997     count++;
3998     pl = pl->next();
3999   }
4000   return count;
4001 }
4002 
4003 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4004   assert(key != NULL, "just checking");
4005   SystemProperty* prop;
4006   for (prop = pl; prop != NULL; prop = prop->next()) {
4007     if (strcmp(key, prop->key()) == 0) return prop->value();
4008   }
4009   return NULL;
4010 }
4011 
4012 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4013   int count = 0;
4014   const char* ret_val = NULL;
4015 
4016   while(pl != NULL) {
4017     if(count >= index) {
4018       ret_val = pl->key();
4019       break;
4020     }
4021     count++;
4022     pl = pl->next();
4023   }
4024 
4025   return ret_val;
4026 }
4027 
4028 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4029   int count = 0;
4030   char* ret_val = NULL;
4031 
4032   while(pl != NULL) {
4033     if(count >= index) {
4034       ret_val = pl->value();
4035       break;
4036     }
4037     count++;
4038     pl = pl->next();
4039   }
4040 
4041   return ret_val;
4042 }
4043 
4044 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4045   SystemProperty* p = *plist;
4046   if (p == NULL) {
4047     *plist = new_p;
4048   } else {
4049     while (p->next() != NULL) {
4050       p = p->next();
4051     }
4052     p->set_next(new_p);
4053   }
4054 }
4055 
4056 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {
4057   if (plist == NULL)
4058     return;
4059 
4060   SystemProperty* new_p = new SystemProperty(k, v, true);
4061   PropertyList_add(plist, new_p);
4062 }
4063 
4064 void Arguments::PropertyList_add(SystemProperty *element) {
4065   PropertyList_add(&_system_properties, element);
4066 }
4067 
4068 // This add maintains unique property key in the list.
4069 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {
4070   if (plist == NULL)
4071     return;
4072 
4073   // If property key exist then update with new value.
4074   SystemProperty* prop;
4075   for (prop = *plist; prop != NULL; prop = prop->next()) {
4076     if (strcmp(k, prop->key()) == 0) {
4077       if (append) {
4078         prop->append_value(v);
4079       } else {
4080         prop->set_value(v);
4081       }
4082       return;
4083     }
4084   }
4085 
4086   PropertyList_add(plist, k, v);
4087 }
4088 
4089 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4090 // Returns true if all of the source pointed by src has been copied over to
4091 // the destination buffer pointed by buf. Otherwise, returns false.
4092 // Notes:
4093 // 1. If the length (buflen) of the destination buffer excluding the
4094 // NULL terminator character is not long enough for holding the expanded
4095 // pid characters, it also returns false instead of returning the partially
4096 // expanded one.
4097 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4098 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4099                                 char* buf, size_t buflen) {
4100   const char* p = src;
4101   char* b = buf;
4102   const char* src_end = &src[srclen];
4103   char* buf_end = &buf[buflen - 1];
4104 
4105   while (p < src_end && b < buf_end) {
4106     if (*p == '%') {
4107       switch (*(++p)) {
4108       case '%':         // "%%" ==> "%"
4109         *b++ = *p++;
4110         break;
4111       case 'p':  {       //  "%p" ==> current process id
4112         // buf_end points to the character before the last character so
4113         // that we could write '\0' to the end of the buffer.
4114         size_t buf_sz = buf_end - b + 1;
4115         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4116 
4117         // if jio_snprintf fails or the buffer is not long enough to hold
4118         // the expanded pid, returns false.
4119         if (ret < 0 || ret >= (int)buf_sz) {
4120           return false;
4121         } else {
4122           b += ret;
4123           assert(*b == '\0', "fail in copy_expand_pid");
4124           if (p == src_end && b == buf_end + 1) {
4125             // reach the end of the buffer.
4126             return true;
4127           }
4128         }
4129         p++;
4130         break;
4131       }
4132       default :
4133         *b++ = '%';
4134       }
4135     } else {
4136       *b++ = *p++;
4137     }
4138   }
4139   *b = '\0';
4140   return (p == src_end); // return false if not all of the source was copied
4141 }