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