rev 8932 : 8046148

   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 "compiler/compilerOracle.hpp"
  32 #include "gc/shared/cardTableRS.hpp"
  33 #include "gc/shared/genCollectedHeap.hpp"
  34 #include "gc/shared/referenceProcessor.hpp"
  35 #include "gc/shared/taskqueue.hpp"

  36 #include "memory/allocation.inline.hpp"
  37 #include "memory/universe.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "prims/jvmtiExport.hpp"
  40 #include "runtime/arguments.hpp"
  41 #include "runtime/arguments_ext.hpp"
  42 #include "runtime/commandLineFlagConstraintList.hpp"
  43 #include "runtime/commandLineFlagRangeList.hpp"
  44 #include "runtime/globals.hpp"
  45 #include "runtime/globals_extension.hpp"
  46 #include "runtime/java.hpp"
  47 #include "runtime/os.hpp"
  48 #include "runtime/vm_version.hpp"
  49 #include "services/management.hpp"
  50 #include "services/memTracker.hpp"
  51 #include "utilities/defaultStream.hpp"
  52 #include "utilities/macros.hpp"
  53 #include "utilities/stringUtils.hpp"
  54 #if INCLUDE_ALL_GCS
  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 
1476   if (max_heap_size <= max_heap_for_compressed_oops()) {
1477 #if !defined(COMPILER1) || defined(TIERED)
1478     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1479       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1480     }
1481 #endif
1482   } else {
1483     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1484       warning("Max heap size too large for Compressed Oops");
1485       FLAG_SET_DEFAULT(UseCompressedOops, false);
1486       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1487     }
1488   }
1489 #endif // _LP64
1490 #endif // ZERO
1491 }
1492 
1493 
1494 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1495 // set_use_compressed_oops().
1496 void Arguments::set_use_compressed_klass_ptrs() {
1497 #ifndef ZERO
1498 #ifdef _LP64
1499   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1500   if (!UseCompressedOops) {
1501     if (UseCompressedClassPointers) {
1502       warning("UseCompressedClassPointers requires UseCompressedOops");
1503     }
1504     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1505   } else {
1506     // Turn on UseCompressedClassPointers too
1507     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1508       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1509     }
1510     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1511     if (UseCompressedClassPointers) {
1512       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1513         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1514         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1515       }
1516     }
1517   }
1518 #endif // _LP64
1519 #endif // !ZERO
1520 }
1521 
1522 void Arguments::set_conservative_max_heap_alignment() {
1523   // The conservative maximum required alignment for the heap is the maximum of
1524   // the alignments imposed by several sources: any requirements from the heap
1525   // itself, the collector policy and the maximum page size we may run the VM
1526   // with.
1527   size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
1528 #if INCLUDE_ALL_GCS
1529   if (UseParallelGC) {
1530     heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
1531   } else if (UseG1GC) {
1532     heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
1533   }
1534 #endif // INCLUDE_ALL_GCS
1535   _conservative_max_heap_alignment = MAX4(heap_alignment,
1536                                           (size_t)os::vm_allocation_granularity(),
1537                                           os::max_page_size(),
1538                                           CollectorPolicy::compute_heap_alignment());
1539 }
1540 
1541 void Arguments::select_gc_ergonomically() {
1542   if (os::is_server_class_machine()) {
1543     if (should_auto_select_low_pause_collector()) {
1544       FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
1545     } else {
1546 #if defined(JAVASE_EMBEDDED)
1547       FLAG_SET_ERGO(bool, UseParallelGC, true);
1548 #else
1549       FLAG_SET_ERGO(bool, UseG1GC, true);
1550 #endif
1551     }
1552   } else {
1553     FLAG_SET_ERGO(bool, UseSerialGC, true);
1554   }
1555 }
1556 
1557 void Arguments::select_gc() {
1558   if (!gc_selected()) {
1559     select_gc_ergonomically();
1560     guarantee(gc_selected(), "No GC selected");
1561   }
1562 }
1563 
1564 void Arguments::set_ergonomics_flags() {
1565   select_gc();
1566 
1567 #ifdef COMPILER2
1568   // Shared spaces work fine with other GCs but causes bytecode rewriting
1569   // to be disabled, which hurts interpreter performance and decreases
1570   // server performance.  When -server is specified, keep the default off
1571   // unless it is asked for.  Future work: either add bytecode rewriting
1572   // at link time, or rewrite bytecodes in non-shared methods.
1573   if (!DumpSharedSpaces && !RequireSharedSpaces &&
1574       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1575     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1576   }
1577 #endif
1578 
1579   set_conservative_max_heap_alignment();
1580 
1581 #ifndef ZERO
1582 #ifdef _LP64
1583   set_use_compressed_oops();
1584 
1585   // set_use_compressed_klass_ptrs() must be called after calling
1586   // set_use_compressed_oops().
1587   set_use_compressed_klass_ptrs();
1588 
1589   // Also checks that certain machines are slower with compressed oops
1590   // in vm_version initialization code.
1591 #endif // _LP64
1592 #endif // !ZERO
1593 
1594   CodeCacheExtensions::set_ergonomics_flags();
1595 }
1596 
1597 void Arguments::set_parallel_gc_flags() {
1598   assert(UseParallelGC || UseParallelOldGC, "Error");
1599   // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1600   if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1601     FLAG_SET_DEFAULT(UseParallelOldGC, true);
1602   }
1603   FLAG_SET_DEFAULT(UseParallelGC, true);
1604 
1605   // If no heap maximum was requested explicitly, use some reasonable fraction
1606   // of the physical memory, up to a maximum of 1GB.
1607   FLAG_SET_DEFAULT(ParallelGCThreads,
1608                    Abstract_VM_Version::parallel_worker_threads());
1609   if (ParallelGCThreads == 0) {
1610     jio_fprintf(defaultStream::error_stream(),
1611         "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1612     vm_exit(1);
1613   }
1614 
1615   if (UseAdaptiveSizePolicy) {
1616     // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1617     // unless the user actually sets these flags.
1618     if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1619       FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1620     }
1621     if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1622       FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1623     }
1624   }
1625 
1626   // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1627   // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1628   // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1629   // See CR 6362902 for details.
1630   if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1631     if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1632        FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1633     }
1634     if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1635       FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1636     }
1637   }
1638 
1639   if (UseParallelOldGC) {
1640     // Par compact uses lower default values since they are treated as
1641     // minimums.  These are different defaults because of the different
1642     // interpretation and are not ergonomically set.
1643     if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1644       FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1645     }
1646   }
1647 }
1648 
1649 void Arguments::set_g1_gc_flags() {
1650   assert(UseG1GC, "Error");
1651 #ifdef COMPILER1
1652   FastTLABRefill = false;
1653 #endif
1654   FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1655   if (ParallelGCThreads == 0) {
1656     assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
1657     vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1658   }
1659 
1660 #if INCLUDE_ALL_GCS
1661   if (G1ConcRefinementThreads == 0) {
1662     FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);
1663   }
1664 #endif
1665 
1666   // MarkStackSize will be set (if it hasn't been set by the user)
1667   // when concurrent marking is initialized.
1668   // Its value will be based upon the number of parallel marking threads.
1669   // But we do set the maximum mark stack size here.
1670   if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1671     FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1672   }
1673 
1674   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1675     // In G1, we want the default GC overhead goal to be higher than
1676     // say in PS. So we set it here to 10%. Otherwise the heap might
1677     // be expanded more aggressively than we would like it to. In
1678     // fact, even 10% seems to not be high enough in some cases
1679     // (especially small GC stress tests that the main thing they do
1680     // is allocation). We might consider increase it further.
1681     FLAG_SET_DEFAULT(GCTimeRatio, 9);
1682   }
1683 
1684   if (PrintGCDetails && Verbose) {
1685     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1686       (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1687     tty->print_cr("ConcGCThreads: %u", ConcGCThreads);
1688   }
1689 }
1690 
1691 #if !INCLUDE_ALL_GCS
1692 #ifdef ASSERT
1693 static bool verify_serial_gc_flags() {
1694   return (UseSerialGC &&
1695         !(UseParNewGC || (UseConcMarkSweepGC) || UseG1GC ||
1696           UseParallelGC || UseParallelOldGC));
1697 }
1698 #endif // ASSERT
1699 #endif // INCLUDE_ALL_GCS
1700 
1701 void Arguments::set_gc_specific_flags() {
1702 #if INCLUDE_ALL_GCS
1703   // Set per-collector flags
1704   if (UseParallelGC || UseParallelOldGC) {
1705     set_parallel_gc_flags();
1706   } else if (UseConcMarkSweepGC) {
1707     set_cms_and_parnew_gc_flags();
1708   } else if (UseG1GC) {
1709     set_g1_gc_flags();
1710   }
1711   check_deprecated_gc_flags();
1712   if (AssumeMP && !UseSerialGC) {
1713     if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
1714       warning("If the number of processors is expected to increase from one, then"
1715               " you should configure the number of parallel GC threads appropriately"
1716               " using -XX:ParallelGCThreads=N");
1717     }
1718   }
1719   if (MinHeapFreeRatio == 100) {
1720     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
1721     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
1722   }
1723 #else // INCLUDE_ALL_GCS
1724   assert(verify_serial_gc_flags(), "SerialGC unset");
1725 #endif // INCLUDE_ALL_GCS
1726 }
1727 
1728 julong Arguments::limit_by_allocatable_memory(julong limit) {
1729   julong max_allocatable;
1730   julong result = limit;
1731   if (os::has_allocatable_memory_limit(&max_allocatable)) {
1732     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
1733   }
1734   return result;
1735 }
1736 
1737 // Use static initialization to get the default before parsing
1738 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1739 
1740 void Arguments::set_heap_size() {
1741   if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
1742     // Deprecated flag
1743     FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
1744   }
1745 
1746   const julong phys_mem =
1747     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1748                             : (julong)MaxRAM;
1749 
1750   // If the maximum heap size has not been set with -Xmx,
1751   // then set it as fraction of the size of physical memory,
1752   // respecting the maximum and minimum sizes of the heap.
1753   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1754     julong reasonable_max = phys_mem / MaxRAMFraction;
1755 
1756     if (phys_mem <= MaxHeapSize * MinRAMFraction) {
1757       // Small physical memory, so use a minimum fraction of it for the heap
1758       reasonable_max = phys_mem / MinRAMFraction;
1759     } else {
1760       // Not-small physical memory, so require a heap at least
1761       // as large as MaxHeapSize
1762       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1763     }
1764     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1765       // Limit the heap size to ErgoHeapSizeLimit
1766       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1767     }
1768     if (UseCompressedOops) {
1769       // Limit the heap size to the maximum possible when using compressed oops
1770       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1771 
1772       // HeapBaseMinAddress can be greater than default but not less than.
1773       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1774         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1775           // matches compressed oops printing flags
1776           if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
1777             jio_fprintf(defaultStream::error_stream(),
1778                         "HeapBaseMinAddress must be at least " SIZE_FORMAT
1779                         " (" SIZE_FORMAT "G) which is greater than value given "
1780                         SIZE_FORMAT "\n",
1781                         DefaultHeapBaseMinAddress,
1782                         DefaultHeapBaseMinAddress/G,
1783                         HeapBaseMinAddress);
1784           }
1785           FLAG_SET_ERGO(size_t, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1786         }
1787       }
1788 
1789       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1790         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1791         // but it should be not less than default MaxHeapSize.
1792         max_coop_heap -= HeapBaseMinAddress;
1793       }
1794       reasonable_max = MIN2(reasonable_max, max_coop_heap);
1795     }
1796     reasonable_max = limit_by_allocatable_memory(reasonable_max);
1797 
1798     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1799       // An initial heap size was specified on the command line,
1800       // so be sure that the maximum size is consistent.  Done
1801       // after call to limit_by_allocatable_memory because that
1802       // method might reduce the allocation size.
1803       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1804     }
1805 
1806     if (PrintGCDetails && Verbose) {
1807       // Cannot use gclog_or_tty yet.
1808       tty->print_cr("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1809     }
1810     FLAG_SET_ERGO(size_t, MaxHeapSize, (size_t)reasonable_max);
1811   }
1812 
1813   // If the minimum or initial heap_size have not been set or requested to be set
1814   // ergonomically, set them accordingly.
1815   if (InitialHeapSize == 0 || min_heap_size() == 0) {
1816     julong reasonable_minimum = (julong)(OldSize + NewSize);
1817 
1818     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1819 
1820     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1821 
1822     if (InitialHeapSize == 0) {
1823       julong reasonable_initial = phys_mem / InitialRAMFraction;
1824 
1825       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
1826       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1827 
1828       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
1829 
1830       if (PrintGCDetails && Verbose) {
1831         // Cannot use gclog_or_tty yet.
1832         tty->print_cr("  Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
1833       }
1834       FLAG_SET_ERGO(size_t, InitialHeapSize, (size_t)reasonable_initial);
1835     }
1836     // If the minimum heap size has not been set (via -Xms),
1837     // synchronize with InitialHeapSize to avoid errors with the default value.
1838     if (min_heap_size() == 0) {
1839       set_min_heap_size(MIN2((size_t)reasonable_minimum, InitialHeapSize));
1840       if (PrintGCDetails && Verbose) {
1841         // Cannot use gclog_or_tty yet.
1842         tty->print_cr("  Minimum heap size " SIZE_FORMAT, min_heap_size());
1843       }
1844     }
1845   }
1846 }
1847 
1848 // This must be called after ergonomics.
1849 void Arguments::set_bytecode_flags() {
1850   if (!RewriteBytecodes) {
1851     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1852   }
1853 }
1854 
1855 // Aggressive optimization flags  -XX:+AggressiveOpts
1856 jint Arguments::set_aggressive_opts_flags() {
1857 #ifdef COMPILER2
1858   if (AggressiveUnboxing) {
1859     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1860       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1861     } else if (!EliminateAutoBox) {
1862       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
1863       AggressiveUnboxing = false;
1864     }
1865     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1866       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1867     } else if (!DoEscapeAnalysis) {
1868       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
1869       AggressiveUnboxing = false;
1870     }
1871   }
1872   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1873     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1874       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1875     }
1876     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1877       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
1878     }
1879 
1880     // Feed the cache size setting into the JDK
1881     char buffer[1024];
1882     sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
1883     if (!add_property(buffer)) {
1884       return JNI_ENOMEM;
1885     }
1886   }
1887   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
1888     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
1889   }
1890 #endif
1891 
1892   if (AggressiveOpts) {
1893 // Sample flag setting code
1894 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
1895 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
1896 //    }
1897   }
1898 
1899   return JNI_OK;
1900 }
1901 
1902 //===========================================================================================================
1903 // Parsing of java.compiler property
1904 
1905 void Arguments::process_java_compiler_argument(const char* arg) {
1906   // For backwards compatibility, Djava.compiler=NONE or ""
1907   // causes us to switch to -Xint mode UNLESS -Xdebug
1908   // is also specified.
1909   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
1910     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
1911   }
1912 }
1913 
1914 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1915   _sun_java_launcher = os::strdup_check_oom(launcher);
1916 }
1917 
1918 bool Arguments::created_by_java_launcher() {
1919   assert(_sun_java_launcher != NULL, "property must have value");
1920   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1921 }
1922 
1923 bool Arguments::sun_java_launcher_is_altjvm() {
1924   return _sun_java_launcher_is_altjvm;
1925 }
1926 
1927 //===========================================================================================================
1928 // Parsing of main arguments
1929 
1930 // check if do gclog rotation
1931 // +UseGCLogFileRotation is a must,
1932 // no gc log rotation when log file not supplied or
1933 // NumberOfGCLogFiles is 0
1934 void check_gclog_consistency() {
1935   if (UseGCLogFileRotation) {
1936     if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {
1937       jio_fprintf(defaultStream::output_stream(),
1938                   "To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"
1939                   "where num_of_file > 0\n"
1940                   "GC log rotation is turned off\n");
1941       UseGCLogFileRotation = false;
1942     }
1943   }
1944 
1945   if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {
1946     if (FLAG_SET_CMDLINE(size_t, GCLogFileSize, 8*K) == Flag::SUCCESS) {
1947       jio_fprintf(defaultStream::output_stream(),
1948                 "GCLogFileSize changed to minimum 8K\n");
1949     }
1950   }
1951 }
1952 
1953 // This function is called for -Xloggc:<filename>, it can be used
1954 // to check if a given file name(or string) conforms to the following
1955 // specification:
1956 // A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"
1957 // %p and %t only allowed once. We only limit usage of filename not path
1958 bool is_filename_valid(const char *file_name) {
1959   const char* p = file_name;
1960   char file_sep = os::file_separator()[0];
1961   const char* cp;
1962   // skip prefix path
1963   for (cp = file_name; *cp != '\0'; cp++) {
1964     if (*cp == '/' || *cp == file_sep) {
1965       p = cp + 1;
1966     }
1967   }
1968 
1969   int count_p = 0;
1970   int count_t = 0;
1971   while (*p != '\0') {
1972     if ((*p >= '0' && *p <= '9') ||
1973         (*p >= 'A' && *p <= 'Z') ||
1974         (*p >= 'a' && *p <= 'z') ||
1975          *p == '-'               ||
1976          *p == '_'               ||
1977          *p == '.') {
1978        p++;
1979        continue;
1980     }
1981     if (*p == '%') {
1982       if(*(p + 1) == 'p') {
1983         p += 2;
1984         count_p ++;
1985         continue;
1986       }
1987       if (*(p + 1) == 't') {
1988         p += 2;
1989         count_t ++;
1990         continue;
1991       }
1992     }
1993     return false;
1994   }
1995   return count_p < 2 && count_t < 2;
1996 }
1997 
1998 // Check consistency of GC selection
1999 bool Arguments::check_gc_consistency() {
2000   check_gclog_consistency();
2001   // Ensure that the user has not selected conflicting sets
2002   // of collectors.
2003   uint i = 0;
2004   if (UseSerialGC)                       i++;
2005   if (UseConcMarkSweepGC)                i++;
2006   if (UseParallelGC || UseParallelOldGC) i++;
2007   if (UseG1GC)                           i++;
2008   if (i > 1) {
2009     jio_fprintf(defaultStream::error_stream(),
2010                 "Conflicting collector combinations in option list; "
2011                 "please refer to the release notes for the combinations "
2012                 "allowed\n");
2013     return false;
2014   }
2015 
2016   if (UseConcMarkSweepGC && !UseParNewGC) {
2017     jio_fprintf(defaultStream::error_stream(),
2018         "It is not possible to combine the DefNew young collector with the CMS collector.\n");
2019     return false;
2020   }
2021 
2022   if (UseParNewGC && !UseConcMarkSweepGC) {
2023     jio_fprintf(defaultStream::error_stream(),
2024         "It is not possible to combine the ParNew young collector with any collector other than CMS.\n");
2025     return false;
2026   }
2027 
2028   return true;
2029 }
2030 
2031 void Arguments::check_deprecated_gc_flags() {
2032   if (FLAG_IS_CMDLINE(UseParNewGC)) {
2033     warning("The UseParNewGC flag is deprecated and will likely be removed in a future release");
2034   }
2035   if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {
2036     warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
2037             "and will likely be removed in future release");
2038   }
2039   if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {
2040     warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "
2041         "Use MaxRAMFraction instead.");
2042   }
2043 }
2044 
2045 // Check the consistency of vm_init_args
2046 bool Arguments::check_vm_args_consistency() {
2047   // Method for adding checks for flag consistency.
2048   // The intent is to warn the user of all possible conflicts,
2049   // before returning an error.
2050   // Note: Needs platform-dependent factoring.
2051   bool status = true;
2052 
2053   if (TLABRefillWasteFraction == 0) {
2054     jio_fprintf(defaultStream::error_stream(),
2055                 "TLABRefillWasteFraction should be a denominator, "
2056                 "not " SIZE_FORMAT "\n",
2057                 TLABRefillWasteFraction);
2058     status = false;
2059   }
2060 
2061   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2062     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
2063   }
2064 
2065   if (UseParallelOldGC && ParallelOldGCSplitALot) {
2066     // Settings to encourage splitting.
2067     if (!FLAG_IS_CMDLINE(NewRatio)) {
2068       if (FLAG_SET_CMDLINE(uintx, NewRatio, 2) != Flag::SUCCESS) {
2069         status = false;
2070       }
2071     }
2072     if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
2073       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2074         status = false;
2075       }
2076     }
2077   }
2078 
2079   if (!(UseParallelGC || UseParallelOldGC) && FLAG_IS_DEFAULT(ScavengeBeforeFullGC)) {
2080     FLAG_SET_DEFAULT(ScavengeBeforeFullGC, false);
2081   }
2082 
2083   if (GCTimeLimit == 100) {
2084     // Turn off gc-overhead-limit-exceeded checks
2085     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2086   }
2087 
2088   status = status && check_gc_consistency();
2089 
2090   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2091   // insists that we hold the requisite locks so that the iteration is
2092   // MT-safe. For the verification at start-up and shut-down, we don't
2093   // yet have a good way of acquiring and releasing these locks,
2094   // which are not visible at the CollectedHeap level. We want to
2095   // be able to acquire these locks and then do the iteration rather
2096   // than just disable the lock verification. This will be fixed under
2097   // bug 4788986.
2098   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2099     if (VerifyDuringStartup) {
2100       warning("Heap verification at start-up disabled "
2101               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2102       VerifyDuringStartup = false; // Disable verification at start-up
2103     }
2104 
2105     if (VerifyBeforeExit) {
2106       warning("Heap verification at shutdown disabled "
2107               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2108       VerifyBeforeExit = false; // Disable verification at shutdown
2109     }
2110   }
2111 
2112   // Note: only executed in non-PRODUCT mode
2113   if (!UseAsyncConcMarkSweepGC &&
2114       (ExplicitGCInvokesConcurrent ||
2115        ExplicitGCInvokesConcurrentAndUnloadsClasses)) {
2116     jio_fprintf(defaultStream::error_stream(),
2117                 "error: +ExplicitGCInvokesConcurrent[AndUnloadsClasses] conflicts"
2118                 " with -UseAsyncConcMarkSweepGC");
2119     status = false;
2120   }
2121 
2122   if (PrintNMTStatistics) {
2123 #if INCLUDE_NMT
2124     if (MemTracker::tracking_level() == NMT_off) {
2125 #endif // INCLUDE_NMT
2126       warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2127       PrintNMTStatistics = false;
2128 #if INCLUDE_NMT
2129     }
2130 #endif
2131   }
2132 
2133   // Check lower bounds of the code cache
2134   // Template Interpreter code is approximately 3X larger in debug builds.
2135   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2136   if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2137     jio_fprintf(defaultStream::error_stream(),
2138                 "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
2139                 os::vm_page_size()/K);
2140     status = false;
2141   } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2142     jio_fprintf(defaultStream::error_stream(),
2143                 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2144                 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2145     status = false;
2146   } else if (ReservedCodeCacheSize < min_code_cache_size) {
2147     jio_fprintf(defaultStream::error_stream(),
2148                 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2149                 min_code_cache_size/K);
2150     status = false;
2151   } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2152     // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2153     jio_fprintf(defaultStream::error_stream(),
2154                 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2155                 CODE_CACHE_SIZE_LIMIT/M);
2156     status = false;
2157   } else if (NonNMethodCodeHeapSize < min_code_cache_size){
2158     jio_fprintf(defaultStream::error_stream(),
2159                 "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2160                 min_code_cache_size/K);
2161     status = false;
2162   } else if ((!FLAG_IS_DEFAULT(NonNMethodCodeHeapSize) || !FLAG_IS_DEFAULT(ProfiledCodeHeapSize) || !FLAG_IS_DEFAULT(NonProfiledCodeHeapSize))
2163              && (NonNMethodCodeHeapSize + NonProfiledCodeHeapSize + ProfiledCodeHeapSize) != ReservedCodeCacheSize) {
2164     jio_fprintf(defaultStream::error_stream(),
2165                 "Invalid code heap sizes: NonNMethodCodeHeapSize(%dK) + ProfiledCodeHeapSize(%dK) + NonProfiledCodeHeapSize(%dK) = %dK. Must be equal to ReservedCodeCacheSize = %uK.\n",
2166                 NonNMethodCodeHeapSize/K, ProfiledCodeHeapSize/K, NonProfiledCodeHeapSize/K,
2167                 (NonNMethodCodeHeapSize + ProfiledCodeHeapSize + NonProfiledCodeHeapSize)/K, ReservedCodeCacheSize/K);
2168     status = false;
2169   }
2170 
2171   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2172     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2173   }
2174 
2175   return status;
2176 }
2177 
2178 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2179   const char* option_type) {
2180   if (ignore) return false;
2181 
2182   const char* spacer = " ";
2183   if (option_type == NULL) {
2184     option_type = ++spacer; // Set both to the empty string.
2185   }
2186 
2187   if (os::obsolete_option(option)) {
2188     jio_fprintf(defaultStream::error_stream(),
2189                 "Obsolete %s%soption: %s\n", option_type, spacer,
2190       option->optionString);
2191     return false;
2192   } else {
2193     jio_fprintf(defaultStream::error_stream(),
2194                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2195       option->optionString);
2196     return true;
2197   }
2198 }
2199 
2200 static const char* user_assertion_options[] = {
2201   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2202 };
2203 
2204 static const char* system_assertion_options[] = {
2205   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2206 };
2207 
2208 bool Arguments::parse_uintx(const char* value,
2209                             uintx* uintx_arg,
2210                             uintx min_size) {
2211 
2212   // Check the sign first since atomull() parses only unsigned values.
2213   bool value_is_positive = !(*value == '-');
2214 
2215   if (value_is_positive) {
2216     julong n;
2217     bool good_return = atomull(value, &n);
2218     if (good_return) {
2219       bool above_minimum = n >= min_size;
2220       bool value_is_too_large = n > max_uintx;
2221 
2222       if (above_minimum && !value_is_too_large) {
2223         *uintx_arg = n;
2224         return true;
2225       }
2226     }
2227   }
2228   return false;
2229 }
2230 
2231 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2232                                                   julong* long_arg,
2233                                                   julong min_size) {
2234   if (!atomull(s, long_arg)) return arg_unreadable;
2235   return check_memory_size(*long_arg, min_size);
2236 }
2237 
2238 // Parse JavaVMInitArgs structure
2239 
2240 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *java_tool_options_args,
2241                                    const JavaVMInitArgs *java_options_args,
2242                                    const JavaVMInitArgs *cmd_line_args) {
2243   // For components of the system classpath.
2244   SysClassPath scp(Arguments::get_sysclasspath());
2245   bool scp_assembly_required = false;
2246 
2247   // Save default settings for some mode flags
2248   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2249   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2250   Arguments::_ClipInlining             = ClipInlining;
2251   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2252   if (TieredCompilation) {
2253     Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2254     Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2255   }
2256 
2257   // Setup flags for mixed which is the default
2258   set_mode_flags(_mixed);
2259 
2260   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2261   // variable (if present).
2262   jint result = parse_each_vm_init_arg(
2263       java_tool_options_args, &scp, &scp_assembly_required, Flag::ENVIRON_VAR);
2264   if (result != JNI_OK) {
2265     return result;
2266   }
2267 
2268   // Parse args structure generated from the command line flags.
2269   result = parse_each_vm_init_arg(cmd_line_args, &scp, &scp_assembly_required,
2270                                   Flag::COMMAND_LINE);
2271   if (result != JNI_OK) {
2272     return result;
2273   }
2274 
2275   // Parse args structure generated from the _JAVA_OPTIONS environment
2276   // variable (if present) (mimics classic VM)
2277   result = parse_each_vm_init_arg(
2278       java_options_args, &scp, &scp_assembly_required, Flag::ENVIRON_VAR);
2279   if (result != JNI_OK) {
2280     return result;
2281   }
2282 
2283   // Do final processing now that all arguments have been parsed
2284   result = finalize_vm_init_args(&scp, scp_assembly_required);
2285   if (result != JNI_OK) {
2286     return result;
2287   }
2288 
2289   return JNI_OK;
2290 }
2291 
2292 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2293 // represents a valid JDWP agent.  is_path==true denotes that we
2294 // are dealing with -agentpath (case where name is a path), otherwise with
2295 // -agentlib
2296 bool valid_jdwp_agent(char *name, bool is_path) {
2297   char *_name;
2298   const char *_jdwp = "jdwp";
2299   size_t _len_jdwp, _len_prefix;
2300 
2301   if (is_path) {
2302     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2303       return false;
2304     }
2305 
2306     _name++;  // skip past last path separator
2307     _len_prefix = strlen(JNI_LIB_PREFIX);
2308 
2309     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2310       return false;
2311     }
2312 
2313     _name += _len_prefix;
2314     _len_jdwp = strlen(_jdwp);
2315 
2316     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2317       _name += _len_jdwp;
2318     }
2319     else {
2320       return false;
2321     }
2322 
2323     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2324       return false;
2325     }
2326 
2327     return true;
2328   }
2329 
2330   if (strcmp(name, _jdwp) == 0) {
2331     return true;
2332   }
2333 
2334   return false;
2335 }
2336 
2337 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2338                                        SysClassPath* scp_p,
2339                                        bool* scp_assembly_required_p,
2340                                        Flag::Flags origin) {
2341   // Remaining part of option string
2342   const char* tail;
2343 
2344   // iterate over arguments
2345   for (int index = 0; index < args->nOptions; index++) {
2346     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2347 
2348     const JavaVMOption* option = args->options + index;
2349 
2350     if (!match_option(option, "-Djava.class.path", &tail) &&
2351         !match_option(option, "-Dsun.java.command", &tail) &&
2352         !match_option(option, "-Dsun.java.launcher", &tail)) {
2353 
2354         // add all jvm options to the jvm_args string. This string
2355         // is used later to set the java.vm.args PerfData string constant.
2356         // the -Djava.class.path and the -Dsun.java.command options are
2357         // omitted from jvm_args string as each have their own PerfData
2358         // string constant object.
2359         build_jvm_args(option->optionString);
2360     }
2361 
2362     // -verbose:[class/gc/jni]
2363     if (match_option(option, "-verbose", &tail)) {
2364       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2365         if (FLAG_SET_CMDLINE(bool, TraceClassLoading, true) != Flag::SUCCESS) {
2366           return JNI_EINVAL;
2367         }
2368         if (FLAG_SET_CMDLINE(bool, TraceClassUnloading, true) != Flag::SUCCESS) {
2369           return JNI_EINVAL;
2370         }
2371       } else if (!strcmp(tail, ":gc")) {
2372         if (FLAG_SET_CMDLINE(bool, PrintGC, true) != Flag::SUCCESS) {
2373           return JNI_EINVAL;
2374         }
2375       } else if (!strcmp(tail, ":jni")) {
2376         if (FLAG_SET_CMDLINE(bool, PrintJNIResolving, true) != Flag::SUCCESS) {
2377           return JNI_EINVAL;
2378         }
2379       }
2380     // -da / -ea / -disableassertions / -enableassertions
2381     // These accept an optional class/package name separated by a colon, e.g.,
2382     // -da:java.lang.Thread.
2383     } else if (match_option(option, user_assertion_options, &tail, true)) {
2384       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2385       if (*tail == '\0') {
2386         JavaAssertions::setUserClassDefault(enable);
2387       } else {
2388         assert(*tail == ':', "bogus match by match_option()");
2389         JavaAssertions::addOption(tail + 1, enable);
2390       }
2391     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2392     } else if (match_option(option, system_assertion_options, &tail, false)) {
2393       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2394       JavaAssertions::setSystemClassDefault(enable);
2395     // -bootclasspath:
2396     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2397       scp_p->reset_path(tail);
2398       *scp_assembly_required_p = true;
2399     // -bootclasspath/a:
2400     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2401       scp_p->add_suffix(tail);
2402       *scp_assembly_required_p = true;
2403     // -bootclasspath/p:
2404     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2405       scp_p->add_prefix(tail);
2406       *scp_assembly_required_p = true;
2407     // -Xrun
2408     } else if (match_option(option, "-Xrun", &tail)) {
2409       if (tail != NULL) {
2410         const char* pos = strchr(tail, ':');
2411         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2412         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2413         name[len] = '\0';
2414 
2415         char *options = NULL;
2416         if(pos != NULL) {
2417           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2418           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
2419         }
2420 #if !INCLUDE_JVMTI
2421         if (strcmp(name, "jdwp") == 0) {
2422           jio_fprintf(defaultStream::error_stream(),
2423             "Debugging agents are not supported in this VM\n");
2424           return JNI_ERR;
2425         }
2426 #endif // !INCLUDE_JVMTI
2427         add_init_library(name, options);
2428       }
2429     // -agentlib and -agentpath
2430     } else if (match_option(option, "-agentlib:", &tail) ||
2431           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2432       if(tail != NULL) {
2433         const char* pos = strchr(tail, '=');
2434         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2435         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2436         name[len] = '\0';
2437 
2438         char *options = NULL;
2439         if(pos != NULL) {
2440           options = os::strdup_check_oom(pos + 1, mtInternal);
2441         }
2442 #if !INCLUDE_JVMTI
2443         if (valid_jdwp_agent(name, is_absolute_path)) {
2444           jio_fprintf(defaultStream::error_stream(),
2445             "Debugging agents are not supported in this VM\n");
2446           return JNI_ERR;
2447         }
2448 #endif // !INCLUDE_JVMTI
2449         add_init_agent(name, options, is_absolute_path);
2450       }
2451     // -javaagent
2452     } else if (match_option(option, "-javaagent:", &tail)) {
2453 #if !INCLUDE_JVMTI
2454       jio_fprintf(defaultStream::error_stream(),
2455         "Instrumentation agents are not supported in this VM\n");
2456       return JNI_ERR;
2457 #else
2458       if(tail != NULL) {
2459         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtInternal), tail);
2460         add_init_agent("instrument", options, false);
2461       }
2462 #endif // !INCLUDE_JVMTI
2463     // -Xnoclassgc
2464     } else if (match_option(option, "-Xnoclassgc")) {
2465       if (FLAG_SET_CMDLINE(bool, ClassUnloading, false) != Flag::SUCCESS) {
2466         return JNI_EINVAL;
2467       }
2468     // -Xconcgc
2469     } else if (match_option(option, "-Xconcgc")) {
2470       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true) != Flag::SUCCESS) {
2471         return JNI_EINVAL;
2472       }
2473     // -Xnoconcgc
2474     } else if (match_option(option, "-Xnoconcgc")) {
2475       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false) != Flag::SUCCESS) {
2476         return JNI_EINVAL;
2477       }
2478     // -Xbatch
2479     } else if (match_option(option, "-Xbatch")) {
2480       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2481         return JNI_EINVAL;
2482       }
2483     // -Xmn for compatibility with other JVM vendors
2484     } else if (match_option(option, "-Xmn", &tail)) {
2485       julong long_initial_young_size = 0;
2486       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2487       if (errcode != arg_in_range) {
2488         jio_fprintf(defaultStream::error_stream(),
2489                     "Invalid initial young generation size: %s\n", option->optionString);
2490         describe_range_error(errcode);
2491         return JNI_EINVAL;
2492       }
2493       if (FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2494         return JNI_EINVAL;
2495       }
2496       if (FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2497         return JNI_EINVAL;
2498       }
2499     // -Xms
2500     } else if (match_option(option, "-Xms", &tail)) {
2501       julong long_initial_heap_size = 0;
2502       // an initial heap size of 0 means automatically determine
2503       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2504       if (errcode != arg_in_range) {
2505         jio_fprintf(defaultStream::error_stream(),
2506                     "Invalid initial heap size: %s\n", option->optionString);
2507         describe_range_error(errcode);
2508         return JNI_EINVAL;
2509       }
2510       set_min_heap_size((size_t)long_initial_heap_size);
2511       // Currently the minimum size and the initial heap sizes are the same.
2512       // Can be overridden with -XX:InitialHeapSize.
2513       if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size) != Flag::SUCCESS) {
2514         return JNI_EINVAL;
2515       }
2516     // -Xmx
2517     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2518       julong long_max_heap_size = 0;
2519       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2520       if (errcode != arg_in_range) {
2521         jio_fprintf(defaultStream::error_stream(),
2522                     "Invalid maximum heap size: %s\n", option->optionString);
2523         describe_range_error(errcode);
2524         return JNI_EINVAL;
2525       }
2526       if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size) != Flag::SUCCESS) {
2527         return JNI_EINVAL;
2528       }
2529     // Xmaxf
2530     } else if (match_option(option, "-Xmaxf", &tail)) {
2531       char* err;
2532       int maxf = (int)(strtod(tail, &err) * 100);
2533       if (*err != '\0' || *tail == '\0') {
2534         jio_fprintf(defaultStream::error_stream(),
2535                     "Bad max heap free percentage size: %s\n",
2536                     option->optionString);
2537         return JNI_EINVAL;
2538       } else {
2539         if (FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf) != Flag::SUCCESS) {
2540             return JNI_EINVAL;
2541         }
2542       }
2543     // Xminf
2544     } else if (match_option(option, "-Xminf", &tail)) {
2545       char* err;
2546       int minf = (int)(strtod(tail, &err) * 100);
2547       if (*err != '\0' || *tail == '\0') {
2548         jio_fprintf(defaultStream::error_stream(),
2549                     "Bad min heap free percentage size: %s\n",
2550                     option->optionString);
2551         return JNI_EINVAL;
2552       } else {
2553         if (FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf) != Flag::SUCCESS) {
2554           return JNI_EINVAL;
2555         }
2556       }
2557     // -Xss
2558     } else if (match_option(option, "-Xss", &tail)) {
2559       julong long_ThreadStackSize = 0;
2560       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2561       if (errcode != arg_in_range) {
2562         jio_fprintf(defaultStream::error_stream(),
2563                     "Invalid thread stack size: %s\n", option->optionString);
2564         describe_range_error(errcode);
2565         return JNI_EINVAL;
2566       }
2567       // Internally track ThreadStackSize in units of 1024 bytes.
2568       if (FLAG_SET_CMDLINE(intx, ThreadStackSize,
2569                        round_to((int)long_ThreadStackSize, K) / K) != Flag::SUCCESS) {
2570         return JNI_EINVAL;
2571       }
2572     // -Xoss, -Xsqnopause, -Xoptimize, -Xboundthreads
2573     } else if (match_option(option, "-Xoss", &tail) ||
2574                match_option(option, "-Xsqnopause") ||
2575                match_option(option, "-Xoptimize") ||
2576                match_option(option, "-Xboundthreads")) {
2577       // All these options are deprecated in JDK 9 and will be removed in a future release
2578       char version[256];
2579       JDK_Version::jdk(9).to_string(version, sizeof(version));
2580       warning("ignoring option %s; support was removed in %s", option->optionString, version);
2581     } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
2582       julong long_CodeCacheExpansionSize = 0;
2583       ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
2584       if (errcode != arg_in_range) {
2585         jio_fprintf(defaultStream::error_stream(),
2586                    "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
2587                    os::vm_page_size()/K);
2588         return JNI_EINVAL;
2589       }
2590       if (FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize) != Flag::SUCCESS) {
2591         return JNI_EINVAL;
2592       }
2593     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2594                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2595       julong long_ReservedCodeCacheSize = 0;
2596 
2597       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2598       if (errcode != arg_in_range) {
2599         jio_fprintf(defaultStream::error_stream(),
2600                     "Invalid maximum code cache size: %s.\n", option->optionString);
2601         return JNI_EINVAL;
2602       }
2603       if (FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != Flag::SUCCESS) {
2604         return JNI_EINVAL;
2605       }
2606       // -XX:NonNMethodCodeHeapSize=
2607     } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
2608       julong long_NonNMethodCodeHeapSize = 0;
2609 
2610       ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
2611       if (errcode != arg_in_range) {
2612         jio_fprintf(defaultStream::error_stream(),
2613                     "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
2614         return JNI_EINVAL;
2615       }
2616       if (FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize) != Flag::SUCCESS) {
2617         return JNI_EINVAL;
2618       }
2619       // -XX:ProfiledCodeHeapSize=
2620     } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
2621       julong long_ProfiledCodeHeapSize = 0;
2622 
2623       ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
2624       if (errcode != arg_in_range) {
2625         jio_fprintf(defaultStream::error_stream(),
2626                     "Invalid maximum profiled code heap size: %s.\n", option->optionString);
2627         return JNI_EINVAL;
2628       }
2629       if (FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize) != Flag::SUCCESS) {
2630         return JNI_EINVAL;
2631       }
2632       // -XX:NonProfiledCodeHeapSizee=
2633     } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
2634       julong long_NonProfiledCodeHeapSize = 0;
2635 
2636       ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
2637       if (errcode != arg_in_range) {
2638         jio_fprintf(defaultStream::error_stream(),
2639                     "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
2640         return JNI_EINVAL;
2641       }
2642       if (FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize) != Flag::SUCCESS) {
2643         return JNI_EINVAL;
2644       }
2645     // -green
2646     } else if (match_option(option, "-green")) {
2647       jio_fprintf(defaultStream::error_stream(),
2648                   "Green threads support not available\n");
2649           return JNI_EINVAL;
2650     // -native
2651     } else if (match_option(option, "-native")) {
2652           // HotSpot always uses native threads, ignore silently for compatibility
2653     // -Xrs
2654     } else if (match_option(option, "-Xrs")) {
2655           // Classic/EVM option, new functionality
2656       if (FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true) != Flag::SUCCESS) {
2657         return JNI_EINVAL;
2658       }
2659     } else if (match_option(option, "-Xusealtsigs")) {
2660           // change default internal VM signals used - lower case for back compat
2661       if (FLAG_SET_CMDLINE(bool, UseAltSigs, true) != Flag::SUCCESS) {
2662         return JNI_EINVAL;
2663       }
2664     // -Xprof
2665     } else if (match_option(option, "-Xprof")) {
2666 #if INCLUDE_FPROF
2667       _has_profile = true;
2668 #else // INCLUDE_FPROF
2669       jio_fprintf(defaultStream::error_stream(),
2670         "Flat profiling is not supported in this VM.\n");
2671       return JNI_ERR;
2672 #endif // INCLUDE_FPROF
2673     // -Xconcurrentio
2674     } else if (match_option(option, "-Xconcurrentio")) {
2675       if (FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true) != Flag::SUCCESS) {
2676         return JNI_EINVAL;
2677       }
2678       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2679         return JNI_EINVAL;
2680       }
2681       if (FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1) != Flag::SUCCESS) {
2682         return JNI_EINVAL;
2683       }
2684       if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
2685         return JNI_EINVAL;
2686       }
2687       if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
2688         return JNI_EINVAL;
2689       }
2690 
2691       // -Xinternalversion
2692     } else if (match_option(option, "-Xinternalversion")) {
2693       jio_fprintf(defaultStream::output_stream(), "%s\n",
2694                   VM_Version::internal_vm_info_string());
2695       vm_exit(0);
2696 #ifndef PRODUCT
2697     // -Xprintflags
2698     } else if (match_option(option, "-Xprintflags")) {
2699       CommandLineFlags::printFlags(tty, false);
2700       vm_exit(0);
2701 #endif
2702     // -D
2703     } else if (match_option(option, "-D", &tail)) {
2704       const char* value;
2705       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2706             *value!= '\0' && strcmp(value, "\"\"") != 0) {
2707         // abort if -Djava.endorsed.dirs is set
2708         jio_fprintf(defaultStream::output_stream(),
2709           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2710           "in modular form will be supported via the concept of upgradeable modules.\n", value);
2711         return JNI_EINVAL;
2712       }
2713       if (match_option(option, "-Djava.ext.dirs=", &value) &&
2714             *value != '\0' && strcmp(value, "\"\"") != 0) {
2715         // abort if -Djava.ext.dirs is set
2716         jio_fprintf(defaultStream::output_stream(),
2717           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2718         return JNI_EINVAL;
2719       }
2720 
2721       if (!add_property(tail)) {
2722         return JNI_ENOMEM;
2723       }
2724       // Out of the box management support
2725       if (match_option(option, "-Dcom.sun.management", &tail)) {
2726 #if INCLUDE_MANAGEMENT
2727         if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
2728           return JNI_EINVAL;
2729         }
2730 #else
2731         jio_fprintf(defaultStream::output_stream(),
2732           "-Dcom.sun.management is not supported in this VM.\n");
2733         return JNI_ERR;
2734 #endif
2735       }
2736     // -Xint
2737     } else if (match_option(option, "-Xint")) {
2738           set_mode_flags(_int);
2739     // -Xmixed
2740     } else if (match_option(option, "-Xmixed")) {
2741           set_mode_flags(_mixed);
2742     // -Xcomp
2743     } else if (match_option(option, "-Xcomp")) {
2744       // for testing the compiler; turn off all flags that inhibit compilation
2745           set_mode_flags(_comp);
2746     // -Xshare:dump
2747     } else if (match_option(option, "-Xshare:dump")) {
2748       if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
2749         return JNI_EINVAL;
2750       }
2751       set_mode_flags(_int);     // Prevent compilation, which creates objects
2752     // -Xshare:on
2753     } else if (match_option(option, "-Xshare:on")) {
2754       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
2755         return JNI_EINVAL;
2756       }
2757       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
2758         return JNI_EINVAL;
2759       }
2760     // -Xshare:auto
2761     } else if (match_option(option, "-Xshare:auto")) {
2762       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
2763         return JNI_EINVAL;
2764       }
2765       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
2766         return JNI_EINVAL;
2767       }
2768     // -Xshare:off
2769     } else if (match_option(option, "-Xshare:off")) {
2770       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
2771         return JNI_EINVAL;
2772       }
2773       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
2774         return JNI_EINVAL;
2775       }
2776     // -Xverify
2777     } else if (match_option(option, "-Xverify", &tail)) {
2778       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
2779         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
2780           return JNI_EINVAL;
2781         }
2782         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
2783           return JNI_EINVAL;
2784         }
2785       } else if (strcmp(tail, ":remote") == 0) {
2786         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
2787           return JNI_EINVAL;
2788         }
2789         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
2790           return JNI_EINVAL;
2791         }
2792       } else if (strcmp(tail, ":none") == 0) {
2793         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
2794           return JNI_EINVAL;
2795         }
2796         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
2797           return JNI_EINVAL;
2798         }
2799       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
2800         return JNI_EINVAL;
2801       }
2802     // -Xdebug
2803     } else if (match_option(option, "-Xdebug")) {
2804       // note this flag has been used, then ignore
2805       set_xdebug_mode(true);
2806     // -Xnoagent
2807     } else if (match_option(option, "-Xnoagent")) {
2808       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
2809     } else if (match_option(option, "-Xloggc:", &tail)) {
2810       // Redirect GC output to the file. -Xloggc:<filename>
2811       // ostream_init_log(), when called will use this filename
2812       // to initialize a fileStream.
2813       _gc_log_filename = os::strdup_check_oom(tail);
2814      if (!is_filename_valid(_gc_log_filename)) {
2815        jio_fprintf(defaultStream::output_stream(),
2816                   "Invalid file name for use with -Xloggc: Filename can only contain the "
2817                   "characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"
2818                   "Note %%p or %%t can only be used once\n", _gc_log_filename);
2819         return JNI_EINVAL;
2820       }
2821       if (FLAG_SET_CMDLINE(bool, PrintGC, true) != Flag::SUCCESS) {
2822         return JNI_EINVAL;
2823       }
2824       if (FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true) != Flag::SUCCESS) {




















2825         return JNI_EINVAL;
2826       }
2827     // JNI hooks
2828     } else if (match_option(option, "-Xcheck", &tail)) {
2829       if (!strcmp(tail, ":jni")) {
2830 #if !INCLUDE_JNI_CHECK
2831         warning("JNI CHECKING is not supported in this VM");
2832 #else
2833         CheckJNICalls = true;
2834 #endif // INCLUDE_JNI_CHECK
2835       } else if (is_bad_option(option, args->ignoreUnrecognized,
2836                                      "check")) {
2837         return JNI_EINVAL;
2838       }
2839     } else if (match_option(option, "vfprintf")) {
2840       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
2841     } else if (match_option(option, "exit")) {
2842       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
2843     } else if (match_option(option, "abort")) {
2844       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
2845     // -XX:+AggressiveHeap
2846     } else if (match_option(option, "-XX:+AggressiveHeap")) {
2847 
2848       // This option inspects the machine and attempts to set various
2849       // parameters to be optimal for long-running, memory allocation
2850       // intensive jobs.  It is intended for machines with large
2851       // amounts of cpu and memory.
2852 
2853       // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
2854       // VM, but we may not be able to represent the total physical memory
2855       // available (like having 8gb of memory on a box but using a 32bit VM).
2856       // Thus, we need to make sure we're using a julong for intermediate
2857       // calculations.
2858       julong initHeapSize;
2859       julong total_memory = os::physical_memory();
2860 
2861       if (total_memory < (julong)256*M) {
2862         jio_fprintf(defaultStream::error_stream(),
2863                     "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
2864         vm_exit(1);
2865       }
2866 
2867       // The heap size is half of available memory, or (at most)
2868       // all of possible memory less 160mb (leaving room for the OS
2869       // when using ISM).  This is the maximum; because adaptive sizing
2870       // is turned on below, the actual space used may be smaller.
2871 
2872       initHeapSize = MIN2(total_memory / (julong)2,
2873                           total_memory - (julong)160*M);
2874 
2875       initHeapSize = limit_by_allocatable_memory(initHeapSize);
2876 
2877       if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2878          if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, initHeapSize) != Flag::SUCCESS) {
2879            return JNI_EINVAL;
2880          }
2881          if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, initHeapSize) != Flag::SUCCESS) {
2882            return JNI_EINVAL;
2883          }
2884          // Currently the minimum size and the initial heap sizes are the same.
2885          set_min_heap_size(initHeapSize);
2886       }
2887       if (FLAG_IS_DEFAULT(NewSize)) {
2888          // Make the young generation 3/8ths of the total heap.
2889          if (FLAG_SET_CMDLINE(size_t, NewSize,
2890                                 ((julong)MaxHeapSize / (julong)8) * (julong)3) != Flag::SUCCESS) {
2891            return JNI_EINVAL;
2892          }
2893          if (FLAG_SET_CMDLINE(size_t, MaxNewSize, NewSize) != Flag::SUCCESS) {
2894            return JNI_EINVAL;
2895          }
2896       }
2897 
2898 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
2899       FLAG_SET_DEFAULT(UseLargePages, true);
2900 #endif
2901 
2902       // Increase some data structure sizes for efficiency
2903       if (FLAG_SET_CMDLINE(size_t, BaseFootPrintEstimate, MaxHeapSize) != Flag::SUCCESS) {
2904         return JNI_EINVAL;
2905       }
2906       if (FLAG_SET_CMDLINE(bool, ResizeTLAB, false) != Flag::SUCCESS) {
2907         return JNI_EINVAL;
2908       }
2909       if (FLAG_SET_CMDLINE(size_t, TLABSize, 256*K) != Flag::SUCCESS) {
2910         return JNI_EINVAL;
2911       }
2912 
2913       // See the OldPLABSize comment below, but replace 'after promotion'
2914       // with 'after copying'.  YoungPLABSize is the size of the survivor
2915       // space per-gc-thread buffers.  The default is 4kw.
2916       if (FLAG_SET_CMDLINE(size_t, YoungPLABSize, 256*K) != Flag::SUCCESS) {      // Note: this is in words
2917         return JNI_EINVAL;
2918       }
2919 
2920       // OldPLABSize is the size of the buffers in the old gen that
2921       // UseParallelGC uses to promote live data that doesn't fit in the
2922       // survivor spaces.  At any given time, there's one for each gc thread.
2923       // The default size is 1kw. These buffers are rarely used, since the
2924       // survivor spaces are usually big enough.  For specjbb, however, there
2925       // are occasions when there's lots of live data in the young gen
2926       // and we end up promoting some of it.  We don't have a definite
2927       // explanation for why bumping OldPLABSize helps, but the theory
2928       // is that a bigger PLAB results in retaining something like the
2929       // original allocation order after promotion, which improves mutator
2930       // locality.  A minor effect may be that larger PLABs reduce the
2931       // number of PLAB allocation events during gc.  The value of 8kw
2932       // was arrived at by experimenting with specjbb.
2933       if (FLAG_SET_CMDLINE(size_t, OldPLABSize, 8*K) != Flag::SUCCESS) {  // Note: this is in words
2934         return JNI_EINVAL;
2935       }
2936 
2937       // Enable parallel GC and adaptive generation sizing
2938       if (FLAG_SET_CMDLINE(bool, UseParallelGC, true) != Flag::SUCCESS) {
2939         return JNI_EINVAL;
2940       }
2941       FLAG_SET_DEFAULT(ParallelGCThreads,
2942                        Abstract_VM_Version::parallel_worker_threads());
2943 
2944       // Encourage steady state memory management
2945       if (FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100) != Flag::SUCCESS) {
2946         return JNI_EINVAL;
2947       }
2948 
2949       // This appears to improve mutator locality
2950       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2951         return JNI_EINVAL;
2952       }
2953 
2954       // Get around early Solaris scheduling bug
2955       // (affinity vs other jobs on system)
2956       // but disallow DR and offlining (5008695).
2957       if (FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true) != Flag::SUCCESS) {
2958         return JNI_EINVAL;
2959       }
2960 
2961     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
2962     // and the last option wins.
2963     } else if (match_option(option, "-XX:+NeverTenure")) {
2964       if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
2965         return JNI_EINVAL;
2966       }
2967       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
2968         return JNI_EINVAL;
2969       }
2970       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
2971         return JNI_EINVAL;
2972       }
2973     } else if (match_option(option, "-XX:+AlwaysTenure")) {
2974       if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
2975         return JNI_EINVAL;
2976       }
2977       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
2978         return JNI_EINVAL;
2979       }
2980       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
2981         return JNI_EINVAL;
2982       }
2983     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
2984       uintx max_tenuring_thresh = 0;
2985       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
2986         jio_fprintf(defaultStream::error_stream(),
2987                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
2988         return JNI_EINVAL;
2989       }
2990 
2991       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
2992         return JNI_EINVAL;
2993       }
2994 
2995       if (MaxTenuringThreshold == 0) {
2996         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
2997           return JNI_EINVAL;
2998         }
2999         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3000           return JNI_EINVAL;
3001         }
3002       } else {
3003         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3004           return JNI_EINVAL;
3005         }
3006         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3007           return JNI_EINVAL;
3008         }
3009       }
3010     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3011       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
3012         return JNI_EINVAL;
3013       }
3014       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
3015         return JNI_EINVAL;
3016       }
3017     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3018       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
3019         return JNI_EINVAL;
3020       }
3021       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3022         return JNI_EINVAL;
3023       }
3024     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3025 #if defined(DTRACE_ENABLED)
3026       if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3027         return JNI_EINVAL;
3028       }
3029       if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3030         return JNI_EINVAL;
3031       }
3032       if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3033         return JNI_EINVAL;
3034       }
3035       if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3036         return JNI_EINVAL;
3037       }
3038 #else // defined(DTRACE_ENABLED)
3039       jio_fprintf(defaultStream::error_stream(),
3040                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3041       return JNI_EINVAL;
3042 #endif // defined(DTRACE_ENABLED)
3043 #ifdef ASSERT
3044     } else if (match_option(option, "-XX:+FullGCALot")) {
3045       if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3046         return JNI_EINVAL;
3047       }
3048       // disable scavenge before parallel mark-compact
3049       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3050         return JNI_EINVAL;
3051       }
3052 #endif
3053     } else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||
3054                match_option(option, "-XX:G1MarkStackSize=", &tail)) {
3055       julong stack_size = 0;
3056       ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);
3057       if (errcode != arg_in_range) {
3058         jio_fprintf(defaultStream::error_stream(),
3059                     "Invalid mark stack size: %s\n", option->optionString);
3060         describe_range_error(errcode);
3061         return JNI_EINVAL;
3062       }
3063       jio_fprintf(defaultStream::error_stream(),
3064         "Please use -XX:MarkStackSize in place of "
3065         "-XX:CMSMarkStackSize or -XX:G1MarkStackSize in the future\n");
3066       if (FLAG_SET_CMDLINE(size_t, MarkStackSize, stack_size) != Flag::SUCCESS) {
3067         return JNI_EINVAL;
3068       }
3069     } else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {
3070       julong max_stack_size = 0;
3071       ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);
3072       if (errcode != arg_in_range) {
3073         jio_fprintf(defaultStream::error_stream(),
3074                     "Invalid maximum mark stack size: %s\n",
3075                     option->optionString);
3076         describe_range_error(errcode);
3077         return JNI_EINVAL;
3078       }
3079       jio_fprintf(defaultStream::error_stream(),
3080          "Please use -XX:MarkStackSizeMax in place of "
3081          "-XX:CMSMarkStackSizeMax in the future\n");
3082       if (FLAG_SET_CMDLINE(size_t, MarkStackSizeMax, max_stack_size) != Flag::SUCCESS) {
3083         return JNI_EINVAL;
3084       }
3085     } else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||
3086                match_option(option, "-XX:ParallelCMSThreads=", &tail)) {
3087       uintx conc_threads = 0;
3088       if (!parse_uintx(tail, &conc_threads, 1)) {
3089         jio_fprintf(defaultStream::error_stream(),
3090                     "Invalid concurrent threads: %s\n", option->optionString);
3091         return JNI_EINVAL;
3092       }
3093       jio_fprintf(defaultStream::error_stream(),
3094         "Please use -XX:ConcGCThreads in place of "
3095         "-XX:ParallelMarkingThreads or -XX:ParallelCMSThreads in the future\n");
3096       if (FLAG_SET_CMDLINE(uint, ConcGCThreads, conc_threads) != Flag::SUCCESS) {
3097         return JNI_EINVAL;
3098       }
3099     } else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {
3100       julong max_direct_memory_size = 0;
3101       ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);
3102       if (errcode != arg_in_range) {
3103         jio_fprintf(defaultStream::error_stream(),
3104                     "Invalid maximum direct memory size: %s\n",
3105                     option->optionString);
3106         describe_range_error(errcode);
3107         return JNI_EINVAL;
3108       }
3109       if (FLAG_SET_CMDLINE(size_t, MaxDirectMemorySize, max_direct_memory_size) != Flag::SUCCESS) {
3110         return JNI_EINVAL;
3111       }
3112 #if !INCLUDE_MANAGEMENT
3113     } else if (match_option(option, "-XX:+ManagementServer")) {
3114         jio_fprintf(defaultStream::error_stream(),
3115           "ManagementServer is not supported in this VM.\n");
3116         return JNI_ERR;
3117 #endif // INCLUDE_MANAGEMENT
3118     // CreateMinidumpOnCrash is removed, and replaced by CreateCoredumpOnCrash
3119     } else if (match_option(option, "-XX:+CreateMinidumpOnCrash")) {
3120       if (FLAG_SET_CMDLINE(bool, CreateCoredumpOnCrash, true) != Flag::SUCCESS) {
3121         return JNI_EINVAL;
3122       }
3123       jio_fprintf(defaultStream::output_stream(),
3124           "CreateMinidumpOnCrash is replaced by CreateCoredumpOnCrash: CreateCoredumpOnCrash is on\n");
3125     } else if (match_option(option, "-XX:-CreateMinidumpOnCrash")) {
3126       if (FLAG_SET_CMDLINE(bool, CreateCoredumpOnCrash, false) != Flag::SUCCESS) {
3127         return JNI_EINVAL;
3128       }
3129       jio_fprintf(defaultStream::output_stream(),
3130           "CreateMinidumpOnCrash is replaced by CreateCoredumpOnCrash: CreateCoredumpOnCrash is off\n");
3131     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3132       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
3133       // already been handled
3134       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
3135           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
3136         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3137           return JNI_EINVAL;
3138         }
3139       }
3140     // Unknown option
3141     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3142       return JNI_ERR;
3143     }
3144   }
3145 
3146   // PrintSharedArchiveAndExit will turn on
3147   //   -Xshare:on
3148   //   -XX:+TraceClassPaths
3149   if (PrintSharedArchiveAndExit) {
3150     if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3151       return JNI_EINVAL;
3152     }
3153     if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3154       return JNI_EINVAL;
3155     }
3156     if (FLAG_SET_CMDLINE(bool, TraceClassPaths, true) != Flag::SUCCESS) {
3157       return JNI_EINVAL;
3158     }
3159   }
3160 
3161   // Change the default value for flags  which have different default values
3162   // when working with older JDKs.
3163 #ifdef LINUX
3164  if (JDK_Version::current().compare_major(6) <= 0 &&
3165       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3166     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3167   }
3168 #endif // LINUX
3169   fix_appclasspath();
3170   return JNI_OK;
3171 }
3172 
3173 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3174 //
3175 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3176 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3177 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3178 // path is treated as the current directory.
3179 //
3180 // This causes problems with CDS, which requires that all directories specified in the classpath
3181 // must be empty. In most cases, applications do NOT want to load classes from the current
3182 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3183 // scripts compatible with CDS.
3184 void Arguments::fix_appclasspath() {
3185   if (IgnoreEmptyClassPaths) {
3186     const char separator = *os::path_separator();
3187     const char* src = _java_class_path->value();
3188 
3189     // skip over all the leading empty paths
3190     while (*src == separator) {
3191       src ++;
3192     }
3193 
3194     char* copy = os::strdup_check_oom(src, mtInternal);
3195 
3196     // trim all trailing empty paths
3197     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3198       *tail = '\0';
3199     }
3200 
3201     char from[3] = {separator, separator, '\0'};
3202     char to  [2] = {separator, '\0'};
3203     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3204       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3205       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3206     }
3207 
3208     _java_class_path->set_value(copy);
3209     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3210   }
3211 
3212   if (!PrintSharedArchiveAndExit) {
3213     ClassLoader::trace_class_path("[classpath: ", _java_class_path->value());
3214   }
3215 }
3216 
3217 static bool has_jar_files(const char* directory) {
3218   DIR* dir = os::opendir(directory);
3219   if (dir == NULL) return false;
3220 
3221   struct dirent *entry;
3222   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
3223   bool hasJarFile = false;
3224   while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3225     const char* name = entry->d_name;
3226     const char* ext = name + strlen(name) - 4;
3227     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3228   }
3229   FREE_C_HEAP_ARRAY(char, dbuf);
3230   os::closedir(dir);
3231   return hasJarFile ;
3232 }
3233 
3234 static int check_non_empty_dirs(const char* path) {
3235   const char separator = *os::path_separator();
3236   const char* const end = path + strlen(path);
3237   int nonEmptyDirs = 0;
3238   while (path < end) {
3239     const char* tmp_end = strchr(path, separator);
3240     if (tmp_end == NULL) {
3241       if (has_jar_files(path)) {
3242         nonEmptyDirs++;
3243         jio_fprintf(defaultStream::output_stream(),
3244           "Non-empty directory: %s\n", path);
3245       }
3246       path = end;
3247     } else {
3248       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
3249       memcpy(dirpath, path, tmp_end - path);
3250       dirpath[tmp_end - path] = '\0';
3251       if (has_jar_files(dirpath)) {
3252         nonEmptyDirs++;
3253         jio_fprintf(defaultStream::output_stream(),
3254           "Non-empty directory: %s\n", dirpath);
3255       }
3256       FREE_C_HEAP_ARRAY(char, dirpath);
3257       path = tmp_end + 1;
3258     }
3259   }
3260   return nonEmptyDirs;
3261 }
3262 
3263 jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
3264   // check if the default lib/endorsed directory exists; if so, error
3265   char path[JVM_MAXPATHLEN];
3266   const char* fileSep = os::file_separator();
3267   sprintf(path, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3268 
3269   if (CheckEndorsedAndExtDirs) {
3270     int nonEmptyDirs = 0;
3271     // check endorsed directory
3272     nonEmptyDirs += check_non_empty_dirs(path);
3273     // check the extension directories
3274     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3275     if (nonEmptyDirs > 0) {
3276       return JNI_ERR;
3277     }
3278   }
3279 
3280   DIR* dir = os::opendir(path);
3281   if (dir != NULL) {
3282     jio_fprintf(defaultStream::output_stream(),
3283       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3284       "in modular form will be supported via the concept of upgradeable modules.\n");
3285     os::closedir(dir);
3286     return JNI_ERR;
3287   }
3288 
3289   sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3290   dir = os::opendir(path);
3291   if (dir != NULL) {
3292     jio_fprintf(defaultStream::output_stream(),
3293       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3294       "Use -classpath instead.\n.");
3295     os::closedir(dir);
3296     return JNI_ERR;
3297   }
3298 
3299   if (scp_assembly_required) {
3300     // Assemble the bootclasspath elements into the final path.
3301     char *combined_path = scp_p->combined_path();
3302     Arguments::set_sysclasspath(combined_path);
3303     FREE_C_HEAP_ARRAY(char, combined_path);
3304   }
3305 
3306   // This must be done after all arguments have been processed.
3307   // java_compiler() true means set to "NONE" or empty.
3308   if (java_compiler() && !xdebug_mode()) {
3309     // For backwards compatibility, we switch to interpreted mode if
3310     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3311     // not specified.
3312     set_mode_flags(_int);
3313   }
3314 
3315   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3316   // but like -Xint, leave compilation thresholds unaffected.
3317   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3318   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3319     set_mode_flags(_int);
3320   }
3321 
3322   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3323   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3324     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3325   }
3326 
3327 #ifndef COMPILER2
3328   // Don't degrade server performance for footprint
3329   if (FLAG_IS_DEFAULT(UseLargePages) &&
3330       MaxHeapSize < LargePageHeapSizeThreshold) {
3331     // No need for large granularity pages w/small heaps.
3332     // Note that large pages are enabled/disabled for both the
3333     // Java heap and the code cache.
3334     FLAG_SET_DEFAULT(UseLargePages, false);
3335   }
3336 
3337 #else
3338   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3339     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3340   }
3341 #endif
3342 
3343 #ifndef TIERED
3344   // Tiered compilation is undefined.
3345   UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
3346 #endif
3347 
3348   // If we are running in a headless jre, force java.awt.headless property
3349   // to be true unless the property has already been set.
3350   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3351   if (os::is_headless_jre()) {
3352     const char* headless = Arguments::get_property("java.awt.headless");
3353     if (headless == NULL) {
3354       const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3355       if (headless_env == NULL) {
3356         if (!add_property("java.awt.headless=true")) {
3357           return JNI_ENOMEM;
3358         }
3359       } else {
3360         char buffer[256];
3361         jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3362         if (!add_property(buffer)) {
3363           return JNI_ENOMEM;
3364         }
3365       }
3366     }
3367   }
3368 
3369   if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3370     // CMS can only be used with ParNew
3371     FLAG_SET_ERGO(bool, UseParNewGC, true);
3372   }
3373 
3374   if (!check_vm_args_consistency()) {
3375     return JNI_ERR;
3376   }
3377 
3378   return JNI_OK;
3379 }
3380 
3381 // Helper class for controlling the lifetime of JavaVMInitArgs
3382 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3383 // deleted on the destruction of the ScopedVMInitArgs object.
3384 class ScopedVMInitArgs : public StackObj {
3385  private:
3386   JavaVMInitArgs _args;
3387   bool           _is_set;
3388 
3389  public:
3390   ScopedVMInitArgs() {
3391     _args.version = JNI_VERSION_1_2;
3392     _args.nOptions = 0;
3393     _args.options = NULL;
3394     _args.ignoreUnrecognized = false;
3395     _is_set = false;
3396   }
3397 
3398   // Populates the JavaVMInitArgs object represented by this
3399   // ScopedVMInitArgs object with the arguments in options.  The
3400   // allocated memory is deleted by the destructor.  If this method
3401   // returns anything other than JNI_OK, then this object is in a
3402   // partially constructed state, and should be abandoned.
3403   jint set_args(GrowableArray<JavaVMOption>* options) {
3404     _is_set = true;
3405     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3406         JavaVMOption, options->length(), mtInternal);
3407     if (options_arr == NULL) {
3408       return JNI_ENOMEM;
3409     }
3410     _args.options = options_arr;
3411 
3412     for (int i = 0; i < options->length(); i++) {
3413       options_arr[i] = options->at(i);
3414       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3415       if (options_arr[i].optionString == NULL) {
3416         // Rely on the destructor to do cleanup.
3417         _args.nOptions = i;
3418         return JNI_ENOMEM;
3419       }
3420     }
3421 
3422     _args.nOptions = options->length();
3423     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3424     return JNI_OK;
3425   }
3426 
3427   JavaVMInitArgs* get() { return &_args; }
3428   bool is_set()         { return _is_set; }
3429 
3430   ~ScopedVMInitArgs() {
3431     if (_args.options == NULL) return;
3432     for (int i = 0; i < _args.nOptions; i++) {
3433       os::free(_args.options[i].optionString);
3434     }
3435     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3436   }
3437 
3438   // Insert options into this option list, to replace option at
3439   // vm_options_file_pos (-XX:VMOptionsFile)
3440   jint insert(const JavaVMInitArgs* args,
3441               const JavaVMInitArgs* args_to_insert,
3442               const int vm_options_file_pos) {
3443     assert(_args.options == NULL, "shouldn't be set yet");
3444     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3445     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3446 
3447     int length = args->nOptions + args_to_insert->nOptions - 1;
3448     GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal)
3449               GrowableArray<JavaVMOption>(length, true);    // Construct new option array
3450     for (int i = 0; i < args->nOptions; i++) {
3451       if (i == vm_options_file_pos) {
3452         // insert the new options starting at the same place as the
3453         // -XX:VMOptionsFile option
3454         for (int j = 0; j < args_to_insert->nOptions; j++) {
3455           options->push(args_to_insert->options[j]);
3456         }
3457       } else {
3458         options->push(args->options[i]);
3459       }
3460     }
3461     // make into options array
3462     jint result = set_args(options);
3463     delete options;
3464     return result;
3465   }
3466 };
3467 
3468 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3469   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3470 }
3471 
3472 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3473   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3474 }
3475 
3476 jint Arguments::parse_options_environment_variable(const char* name,
3477                                                    ScopedVMInitArgs* vm_args) {
3478   char *buffer = ::getenv(name);
3479 
3480   // Don't check this environment variable if user has special privileges
3481   // (e.g. unix su command).
3482   if (buffer == NULL || os::have_special_privileges()) {
3483     return JNI_OK;
3484   }
3485 
3486   if ((buffer = os::strdup(buffer)) == NULL) {
3487     return JNI_ENOMEM;
3488   }
3489 
3490   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3491 
3492   os::free(buffer);
3493   return retcode;
3494 }
3495 
3496 const int OPTION_BUFFER_SIZE = 1024;
3497 
3498 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3499   // read file into buffer
3500   int fd = ::open(file_name, O_RDONLY);
3501   if (fd < 0) {
3502     jio_fprintf(defaultStream::error_stream(),
3503                 "Could not open options file '%s'\n",
3504                 file_name);
3505     return JNI_ERR;
3506   }
3507 
3508   // '+ 1' for NULL termination even with max bytes
3509   int bytes_alloc = OPTION_BUFFER_SIZE + 1;
3510 
3511   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtInternal);
3512   if (NULL == buf) {
3513     jio_fprintf(defaultStream::error_stream(),
3514                 "Could not allocate read buffer for options file parse\n");
3515     os::close(fd);
3516     return JNI_ENOMEM;
3517   }
3518 
3519   memset(buf, 0, (unsigned)bytes_alloc);
3520 
3521   // Fill buffer
3522   // Use ::read() instead of os::read because os::read()
3523   // might do a thread state transition
3524   // and it is too early for that here
3525 
3526   int bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3527   os::close(fd);
3528   if (bytes_read < 0) {
3529     FREE_C_HEAP_ARRAY(char, buf);
3530     jio_fprintf(defaultStream::error_stream(),
3531                 "Could not read options file '%s'\n", file_name);
3532     return JNI_ERR;
3533   }
3534 
3535   if (bytes_read == 0) {
3536     // tell caller there is no option data and that is ok
3537     FREE_C_HEAP_ARRAY(char, buf);
3538     return JNI_OK;
3539   }
3540 
3541   // file is larger than OPTION_BUFFER_SIZE
3542   if (bytes_read > bytes_alloc - 1) {
3543     FREE_C_HEAP_ARRAY(char, buf);
3544     jio_fprintf(defaultStream::error_stream(),
3545                 "Options file '%s' is larger than %d bytes.\n",
3546                 file_name, bytes_alloc - 1);
3547     return JNI_EINVAL;
3548   }
3549 
3550   int retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3551 
3552   FREE_C_HEAP_ARRAY(char, buf);
3553   return retcode;
3554 }
3555 
3556 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3557   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3558 
3559   // some pointers to help with parsing
3560   char *buffer_end = buffer + buf_len;
3561   char *opt_hd = buffer;
3562   char *wrt = buffer;
3563   char *rd = buffer;
3564 
3565   // parse all options
3566   while (rd < buffer_end) {
3567     // skip leading white space from the input string
3568     while (rd < buffer_end && isspace(*rd)) {
3569       rd++;
3570     }
3571 
3572     if (rd >= buffer_end) {
3573       break;
3574     }
3575 
3576     // Remember this is where we found the head of the token.
3577     opt_hd = wrt;
3578 
3579     // Tokens are strings of non white space characters separated
3580     // by one or more white spaces.
3581     while (rd < buffer_end && !isspace(*rd)) {
3582       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3583         int quote = *rd;                    // matching quote to look for
3584         rd++;                               // don't copy open quote
3585         while (rd < buffer_end && *rd != quote) {
3586                                             // include everything (even spaces)
3587                                             // up until the close quote
3588           *wrt++ = *rd++;                   // copy to option string
3589         }
3590 
3591         if (rd < buffer_end) {
3592           rd++;                             // don't copy close quote
3593         } else {
3594                                             // did not see closing quote
3595           jio_fprintf(defaultStream::error_stream(),
3596                       "Unmatched quote in %s\n", name);
3597           delete options;
3598           return JNI_ERR;
3599         }
3600       } else {
3601         *wrt++ = *rd++;                     // copy to option string
3602       }
3603     }
3604 
3605     // steal a white space character and set it to NULL
3606     *wrt++ = '\0';
3607     // We now have a complete token
3608 
3609     JavaVMOption option;
3610     option.optionString = opt_hd;
3611 
3612     options->append(option);                // Fill in option
3613 
3614     rd++;  // Advance to next character
3615   }
3616 
3617   // Fill out JavaVMInitArgs structure.
3618   jint status = vm_args->set_args(options);
3619 
3620   delete options;
3621   return status;
3622 }
3623 
3624 void Arguments::set_shared_spaces_flags() {
3625   if (DumpSharedSpaces) {
3626     if (RequireSharedSpaces) {
3627       warning("cannot dump shared archive while using shared archive");
3628     }
3629     UseSharedSpaces = false;
3630 #ifdef _LP64
3631     if (!UseCompressedOops || !UseCompressedClassPointers) {
3632       vm_exit_during_initialization(
3633         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3634     }
3635   } else {
3636     if (!UseCompressedOops || !UseCompressedClassPointers) {
3637       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3638     }
3639 #endif
3640   }
3641 }
3642 
3643 #if !INCLUDE_ALL_GCS
3644 static void force_serial_gc() {
3645   FLAG_SET_DEFAULT(UseSerialGC, true);
3646   UNSUPPORTED_GC_OPTION(UseG1GC);
3647   UNSUPPORTED_GC_OPTION(UseParallelGC);
3648   UNSUPPORTED_GC_OPTION(UseParallelOldGC);
3649   UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
3650   UNSUPPORTED_GC_OPTION(UseParNewGC);
3651 }
3652 #endif // INCLUDE_ALL_GCS
3653 
3654 // Sharing support
3655 // Construct the path to the archive
3656 static char* get_shared_archive_path() {
3657   char *shared_archive_path;
3658   if (SharedArchiveFile == NULL) {
3659     char jvm_path[JVM_MAXPATHLEN];
3660     os::jvm_path(jvm_path, sizeof(jvm_path));
3661     char *end = strrchr(jvm_path, *os::file_separator());
3662     if (end != NULL) *end = '\0';
3663     size_t jvm_path_len = strlen(jvm_path);
3664     size_t file_sep_len = strlen(os::file_separator());
3665     const size_t len = jvm_path_len + file_sep_len + 20;
3666     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtInternal);
3667     if (shared_archive_path != NULL) {
3668       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3669         jvm_path, os::file_separator());
3670     }
3671   } else {
3672     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtInternal);
3673   }
3674   return shared_archive_path;
3675 }
3676 
3677 #ifndef PRODUCT
3678 // Determine whether LogVMOutput should be implicitly turned on.
3679 static bool use_vm_log() {
3680   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3681       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3682       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3683       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3684       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3685     return true;
3686   }
3687 
3688 #ifdef COMPILER1
3689   if (PrintC1Statistics) {
3690     return true;
3691   }
3692 #endif // COMPILER1
3693 
3694 #ifdef COMPILER2
3695   if (PrintOptoAssembly || PrintOptoStatistics) {
3696     return true;
3697   }
3698 #endif // COMPILER2
3699 
3700   return false;
3701 }
3702 
3703 #endif // PRODUCT
3704 
3705 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3706                                        char** flags_file,
3707                                        char** vm_options_file,
3708                                        const int vm_options_file_pos,
3709                                        ScopedVMInitArgs *vm_options_file_args,
3710                                        ScopedVMInitArgs* args_out) {
3711   jint code = parse_vm_options_file(*vm_options_file, vm_options_file_args);
3712   if (code != JNI_OK) {
3713     return code;
3714   }
3715 
3716   // Now set global settings from the vm_option file, giving an error if
3717   // it has VMOptionsFile in it
3718   code = match_special_option_and_act(vm_options_file_args->get(), flags_file,
3719                                       NULL, NULL, NULL);
3720   if (code != JNI_OK) {
3721     return code;
3722   }
3723 
3724   if (vm_options_file_args->get()->nOptions < 1) {
3725     return 0;
3726   }
3727 
3728   return args_out->insert(args, vm_options_file_args->get(),
3729                           vm_options_file_pos);
3730 }
3731 
3732 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3733                                              char ** flags_file,
3734                                              char ** vm_options_file,
3735                                              ScopedVMInitArgs* vm_options_file_args,
3736                                              ScopedVMInitArgs* args_out) {
3737   // Remaining part of option string
3738   const char* tail;
3739   int   vm_options_file_pos = -1;
3740 
3741   for (int index = 0; index < args->nOptions; index++) {
3742     const JavaVMOption* option = args->options + index;
3743     if (ArgumentsExt::process_options(option)) {
3744       continue;
3745     }
3746     if (match_option(option, "-XX:Flags=", &tail)) {
3747       *flags_file = (char *) tail;
3748       if (*flags_file == NULL) {
3749         jio_fprintf(defaultStream::error_stream(),
3750                     "Cannot copy flags_file name.\n");
3751         return JNI_ENOMEM;
3752       }
3753       continue;
3754     }
3755     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3756       if (vm_options_file != NULL) {
3757         // The caller accepts -XX:VMOptionsFile
3758         if (*vm_options_file != NULL) {
3759           jio_fprintf(defaultStream::error_stream(),
3760                       "Only one VM Options file is supported "
3761                       "on the command line\n");
3762           return JNI_EINVAL;
3763         }
3764 
3765         *vm_options_file = (char *) tail;
3766         vm_options_file_pos = index;  // save position of -XX:VMOptionsFile
3767         if (*vm_options_file == NULL) {
3768           jio_fprintf(defaultStream::error_stream(),
3769                       "Cannot copy vm_options_file name.\n");
3770           return JNI_ENOMEM;
3771         }
3772       } else {
3773         jio_fprintf(defaultStream::error_stream(),
3774                     "VM options file is only supported on the command line\n");
3775         return JNI_EINVAL;
3776       }
3777       continue;
3778     }
3779     if (match_option(option, "-XX:+PrintVMOptions")) {
3780       PrintVMOptions = true;
3781       continue;
3782     }
3783     if (match_option(option, "-XX:-PrintVMOptions")) {
3784       PrintVMOptions = false;
3785       continue;
3786     }
3787     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3788       IgnoreUnrecognizedVMOptions = true;
3789       continue;
3790     }
3791     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3792       IgnoreUnrecognizedVMOptions = false;
3793       continue;
3794     }
3795     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3796       CommandLineFlags::printFlags(tty, false);
3797       vm_exit(0);
3798     }
3799     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3800 #if INCLUDE_NMT
3801       // The launcher did not setup nmt environment variable properly.
3802       if (!MemTracker::check_launcher_nmt_support(tail)) {
3803         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3804       }
3805 
3806       // Verify if nmt option is valid.
3807       if (MemTracker::verify_nmt_option()) {
3808         // Late initialization, still in single-threaded mode.
3809         if (MemTracker::tracking_level() >= NMT_summary) {
3810           MemTracker::init();
3811         }
3812       } else {
3813         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3814       }
3815       continue;
3816 #else
3817       jio_fprintf(defaultStream::error_stream(),
3818         "Native Memory Tracking is not supported in this VM\n");
3819       return JNI_ERR;
3820 #endif
3821     }
3822 
3823 #ifndef PRODUCT
3824     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3825       CommandLineFlags::printFlags(tty, true);
3826       vm_exit(0);
3827     }
3828 #endif
3829   }
3830 
3831   // If there's a VMOptionsFile, parse that (also can set flags_file)
3832   if ((vm_options_file != NULL) && (*vm_options_file != NULL)) {
3833     return insert_vm_options_file(args, flags_file, vm_options_file,
3834                                   vm_options_file_pos, vm_options_file_args, args_out);
3835   }
3836   return JNI_OK;
3837 }
3838 
3839 static void print_options(const JavaVMInitArgs *args) {
3840   const char* tail;
3841   for (int index = 0; index < args->nOptions; index++) {
3842     const JavaVMOption *option = args->options + index;
3843     if (match_option(option, "-XX:", &tail)) {
3844       logOption(tail);
3845     }
3846   }
3847 }
3848 
3849 // Parse entry point called from JNI_CreateJavaVM
3850 
3851 jint Arguments::parse(const JavaVMInitArgs* args) {
3852 
3853   // Initialize ranges and constraints
3854   CommandLineFlagRangeList::init();
3855   CommandLineFlagConstraintList::init();
3856 
3857   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3858   const char* hotspotrc = ".hotspotrc";
3859   char* flags_file = NULL;
3860   char* vm_options_file = NULL;
3861   bool settings_file_specified = false;
3862   bool needs_hotspotrc_warning = false;
3863   ScopedVMInitArgs java_tool_options_args;
3864   ScopedVMInitArgs java_options_args;
3865   ScopedVMInitArgs modified_cmd_line_args;
3866   // Pass in vm_options_file_args to keep memory for flags_file from being
3867   // deallocated if found in the vm options file.
3868   ScopedVMInitArgs vm_options_file_args;
3869 
3870   jint code =
3871       parse_java_tool_options_environment_variable(&java_tool_options_args);
3872   if (code != JNI_OK) {
3873     return code;
3874   }
3875 
3876   code = parse_java_options_environment_variable(&java_options_args);
3877   if (code != JNI_OK) {
3878     return code;
3879   }
3880 
3881   code = match_special_option_and_act(java_tool_options_args.get(),
3882                                       &flags_file, NULL, NULL, NULL);
3883   if (code != JNI_OK) {
3884     return code;
3885   }
3886 
3887   code = match_special_option_and_act(args, &flags_file, &vm_options_file,
3888                                       &vm_options_file_args,
3889                                       &modified_cmd_line_args);
3890   if (code != JNI_OK) {
3891     return code;
3892   }
3893 
3894 
3895   // The command line arguments have been modified to include VMOptionsFile arguments.
3896   if (modified_cmd_line_args.is_set()) {
3897     args = modified_cmd_line_args.get();
3898   }
3899 
3900   code = match_special_option_and_act(java_options_args.get(), &flags_file,
3901                                       NULL, NULL, NULL);
3902   if (code != JNI_OK) {
3903     return code;
3904   }
3905 
3906   settings_file_specified = (flags_file != NULL);
3907 
3908   if (IgnoreUnrecognizedVMOptions) {
3909     // uncast const to modify the flag args->ignoreUnrecognized
3910     *(jboolean*)(&args->ignoreUnrecognized) = true;
3911     java_tool_options_args.get()->ignoreUnrecognized = true;
3912     java_options_args.get()->ignoreUnrecognized = true;
3913   }
3914 
3915   // Parse specified settings file
3916   if (settings_file_specified) {
3917     if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
3918       return JNI_EINVAL;
3919     }
3920   } else {
3921 #ifdef ASSERT
3922     // Parse default .hotspotrc settings file
3923     if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
3924       return JNI_EINVAL;
3925     }
3926 #else
3927     struct stat buf;
3928     if (os::stat(hotspotrc, &buf) == 0) {
3929       needs_hotspotrc_warning = true;
3930     }
3931 #endif
3932   }
3933 
3934   if (PrintVMOptions) {
3935     print_options(java_tool_options_args.get());
3936     print_options(args);
3937     print_options(java_options_args.get());
3938   }
3939 
3940   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
3941   jint result = parse_vm_init_args(java_tool_options_args.get(),
3942                                    java_options_args.get(),
3943                                    args);   // command line arguments
3944 
3945   if (result != JNI_OK) {
3946     return result;
3947   }
3948 
3949   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
3950   SharedArchivePath = get_shared_archive_path();
3951   if (SharedArchivePath == NULL) {
3952     return JNI_ENOMEM;
3953   }
3954 
3955   // Set up VerifySharedSpaces
3956   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
3957     VerifySharedSpaces = true;
3958   }
3959 
3960   // Delay warning until here so that we've had a chance to process
3961   // the -XX:-PrintWarnings flag
3962   if (needs_hotspotrc_warning) {
3963     warning("%s file is present but has been ignored.  "
3964             "Run with -XX:Flags=%s to load the file.",
3965             hotspotrc, hotspotrc);
3966   }
3967 
3968 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
3969   UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
3970 #endif
3971 
3972   ArgumentsExt::report_unsupported_options();
3973 
3974 #ifndef PRODUCT
3975   if (TraceBytecodesAt != 0) {
3976     TraceBytecodes = true;
3977   }
3978   if (CountCompiledCalls) {
3979     if (UseCounterDecay) {
3980       warning("UseCounterDecay disabled because CountCalls is set");
3981       UseCounterDecay = false;
3982     }
3983   }
3984 #endif // PRODUCT
3985 
3986   if (ScavengeRootsInCode == 0) {
3987     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3988       warning("forcing ScavengeRootsInCode non-zero");
3989     }
3990     ScavengeRootsInCode = 1;
3991   }
3992 
3993   if (PrintGCDetails) {
3994     // Turn on -verbose:gc options as well
3995     PrintGC = true;
3996   }
3997 
3998   // Set object alignment values.
3999   set_object_alignment();
4000 
4001 #if !INCLUDE_ALL_GCS
4002   force_serial_gc();
4003 #endif // INCLUDE_ALL_GCS
4004 #if !INCLUDE_CDS
4005   if (DumpSharedSpaces || RequireSharedSpaces) {
4006     jio_fprintf(defaultStream::error_stream(),
4007       "Shared spaces are not supported in this VM\n");
4008     return JNI_ERR;
4009   }
4010   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
4011     warning("Shared spaces are not supported in this VM");
4012     FLAG_SET_DEFAULT(UseSharedSpaces, false);
4013     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
4014   }
4015   no_shared_spaces("CDS Disabled");
4016 #endif // INCLUDE_CDS
4017 
4018   return JNI_OK;
4019 }
4020 
4021 jint Arguments::apply_ergo() {
4022 
4023   // Set flags based on ergonomics.
4024   set_ergonomics_flags();
4025 
4026   set_shared_spaces_flags();
4027 
4028   // Check the GC selections again.
4029   if (!check_gc_consistency()) {
4030     return JNI_EINVAL;
4031   }
4032 
4033   if (TieredCompilation) {
4034     set_tiered_flags();
4035   } else {
4036     int max_compilation_policy_choice = 1;
4037 #ifdef COMPILER2
4038     max_compilation_policy_choice = 2;
4039 #endif
4040     // Check if the policy is valid.
4041     if (CompilationPolicyChoice >= max_compilation_policy_choice) {
4042       vm_exit_during_initialization(
4043         "Incompatible compilation policy selected", NULL);
4044     }
4045     // Scale CompileThreshold
4046     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
4047     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
4048       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
4049     }
4050   }
4051 
4052 #ifdef COMPILER2
4053 #ifndef PRODUCT
4054   if (PrintIdealGraphLevel > 0) {
4055     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
4056   }
4057 #endif
4058 #endif
4059 
4060   // Set heap size based on available physical memory
4061   set_heap_size();
4062 
4063   ArgumentsExt::set_gc_specific_flags();
4064 
4065   // Initialize Metaspace flags and alignments
4066   Metaspace::ergo_initialize();
4067 
4068   // Set bytecode rewriting flags
4069   set_bytecode_flags();
4070 
4071   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
4072   jint code = set_aggressive_opts_flags();
4073   if (code != JNI_OK) {
4074     return code;
4075   }
4076 
4077   // Turn off biased locking for locking debug mode flags,
4078   // which are subtly different from each other but neither works with
4079   // biased locking
4080   if (UseHeavyMonitors
4081 #ifdef COMPILER1
4082       || !UseFastLocking
4083 #endif // COMPILER1
4084     ) {
4085     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4086       // flag set to true on command line; warn the user that they
4087       // can't enable biased locking here
4088       warning("Biased Locking is not supported with locking debug flags"
4089               "; ignoring UseBiasedLocking flag." );
4090     }
4091     UseBiasedLocking = false;
4092   }
4093 
4094 #ifdef ZERO
4095   // Clear flags not supported on zero.
4096   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4097   FLAG_SET_DEFAULT(UseBiasedLocking, false);
4098   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4099   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4100 #endif // CC_INTERP
4101 
4102 #ifdef COMPILER2
4103   if (!EliminateLocks) {
4104     EliminateNestedLocks = false;
4105   }
4106   if (!Inline) {
4107     IncrementalInline = false;
4108   }
4109 #ifndef PRODUCT
4110   if (!IncrementalInline) {
4111     AlwaysIncrementalInline = false;
4112   }
4113 #endif
4114   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
4115     // nothing to use the profiling, turn if off
4116     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
4117   }
4118 #endif
4119 
4120   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4121     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4122     DebugNonSafepoints = true;
4123   }
4124 
4125   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4126     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4127   }
4128 
4129 #ifndef PRODUCT
4130   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4131     if (use_vm_log()) {
4132       LogVMOutput = true;
4133     }
4134   }
4135 #endif // PRODUCT
4136 
4137   if (PrintCommandLineFlags) {
4138     CommandLineFlags::printSetFlags(tty);
4139   }
4140 
4141   // Apply CPU specific policy for the BiasedLocking
4142   if (UseBiasedLocking) {
4143     if (!VM_Version::use_biased_locking() &&
4144         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4145       UseBiasedLocking = false;
4146     }
4147   }
4148 #ifdef COMPILER2
4149   if (!UseBiasedLocking || EmitSync != 0) {
4150     UseOptoBiasInlining = false;
4151   }
4152 #endif
4153 
4154   return JNI_OK;
4155 }
4156 
4157 jint Arguments::adjust_after_os() {
4158   if (UseNUMA) {
4159     if (UseParallelGC || UseParallelOldGC) {
4160       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4161          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4162       }
4163     }
4164     // UseNUMAInterleaving is set to ON for all collectors and
4165     // platforms when UseNUMA is set to ON. NUMA-aware collectors
4166     // such as the parallel collector for Linux and Solaris will
4167     // interleave old gen and survivor spaces on top of NUMA
4168     // allocation policy for the eden space.
4169     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4170     // all platforms and ParallelGC on Windows will interleave all
4171     // of the heap spaces across NUMA nodes.
4172     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4173       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4174     }
4175   }
4176   return JNI_OK;
4177 }
4178 
4179 int Arguments::PropertyList_count(SystemProperty* pl) {
4180   int count = 0;
4181   while(pl != NULL) {
4182     count++;
4183     pl = pl->next();
4184   }
4185   return count;
4186 }
4187 
4188 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4189   assert(key != NULL, "just checking");
4190   SystemProperty* prop;
4191   for (prop = pl; prop != NULL; prop = prop->next()) {
4192     if (strcmp(key, prop->key()) == 0) return prop->value();
4193   }
4194   return NULL;
4195 }
4196 
4197 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4198   int count = 0;
4199   const char* ret_val = NULL;
4200 
4201   while(pl != NULL) {
4202     if(count >= index) {
4203       ret_val = pl->key();
4204       break;
4205     }
4206     count++;
4207     pl = pl->next();
4208   }
4209 
4210   return ret_val;
4211 }
4212 
4213 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4214   int count = 0;
4215   char* ret_val = NULL;
4216 
4217   while(pl != NULL) {
4218     if(count >= index) {
4219       ret_val = pl->value();
4220       break;
4221     }
4222     count++;
4223     pl = pl->next();
4224   }
4225 
4226   return ret_val;
4227 }
4228 
4229 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4230   SystemProperty* p = *plist;
4231   if (p == NULL) {
4232     *plist = new_p;
4233   } else {
4234     while (p->next() != NULL) {
4235       p = p->next();
4236     }
4237     p->set_next(new_p);
4238   }
4239 }
4240 
4241 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v) {
4242   if (plist == NULL)
4243     return;
4244 
4245   SystemProperty* new_p = new SystemProperty(k, v, true);
4246   PropertyList_add(plist, new_p);
4247 }
4248 
4249 void Arguments::PropertyList_add(SystemProperty *element) {
4250   PropertyList_add(&_system_properties, element);
4251 }
4252 
4253 // This add maintains unique property key in the list.
4254 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v, jboolean append) {
4255   if (plist == NULL)
4256     return;
4257 
4258   // If property key exist then update with new value.
4259   SystemProperty* prop;
4260   for (prop = *plist; prop != NULL; prop = prop->next()) {
4261     if (strcmp(k, prop->key()) == 0) {
4262       if (append) {
4263         prop->append_value(v);
4264       } else {
4265         prop->set_value(v);
4266       }
4267       return;
4268     }
4269   }
4270 
4271   PropertyList_add(plist, k, v);
4272 }
4273 
4274 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4275 // Returns true if all of the source pointed by src has been copied over to
4276 // the destination buffer pointed by buf. Otherwise, returns false.
4277 // Notes:
4278 // 1. If the length (buflen) of the destination buffer excluding the
4279 // NULL terminator character is not long enough for holding the expanded
4280 // pid characters, it also returns false instead of returning the partially
4281 // expanded one.
4282 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4283 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4284                                 char* buf, size_t buflen) {
4285   const char* p = src;
4286   char* b = buf;
4287   const char* src_end = &src[srclen];
4288   char* buf_end = &buf[buflen - 1];
4289 
4290   while (p < src_end && b < buf_end) {
4291     if (*p == '%') {
4292       switch (*(++p)) {
4293       case '%':         // "%%" ==> "%"
4294         *b++ = *p++;
4295         break;
4296       case 'p':  {       //  "%p" ==> current process id
4297         // buf_end points to the character before the last character so
4298         // that we could write '\0' to the end of the buffer.
4299         size_t buf_sz = buf_end - b + 1;
4300         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4301 
4302         // if jio_snprintf fails or the buffer is not long enough to hold
4303         // the expanded pid, returns false.
4304         if (ret < 0 || ret >= (int)buf_sz) {
4305           return false;
4306         } else {
4307           b += ret;
4308           assert(*b == '\0', "fail in copy_expand_pid");
4309           if (p == src_end && b == buf_end + 1) {
4310             // reach the end of the buffer.
4311             return true;
4312           }
4313         }
4314         p++;
4315         break;
4316       }
4317       default :
4318         *b++ = '%';
4319       }
4320     } else {
4321       *b++ = *p++;
4322     }
4323   }
4324   *b = '\0';
4325   return (p == src_end); // return false if not all of the source was copied
4326 }
--- EOF ---