1 /*
   2  * Copyright (c) 1997, 2010, 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 "incls/_precompiled.incl"
  26 #include "incls/_arguments.cpp.incl"
  27 
  28 #define DEFAULT_VENDOR_URL_BUG "http://java.sun.com/webapps/bugreport/crash.jsp"
  29 #define DEFAULT_JAVA_LAUNCHER  "generic"
  30 
  31 char**  Arguments::_jvm_flags_array             = NULL;
  32 int     Arguments::_num_jvm_flags               = 0;
  33 char**  Arguments::_jvm_args_array              = NULL;
  34 int     Arguments::_num_jvm_args                = 0;
  35 char*  Arguments::_java_command                 = NULL;
  36 SystemProperty* Arguments::_system_properties   = NULL;
  37 const char*  Arguments::_gc_log_filename        = NULL;
  38 bool   Arguments::_has_profile                  = false;
  39 bool   Arguments::_has_alloc_profile            = false;
  40 uintx  Arguments::_min_heap_size                = 0;
  41 Arguments::Mode Arguments::_mode                = _mixed;
  42 bool   Arguments::_java_compiler                = false;
  43 bool   Arguments::_xdebug_mode                  = false;
  44 const char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
  45 const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
  46 int    Arguments::_sun_java_launcher_pid        = -1;
  47 
  48 // These parameters are reset in method parse_vm_init_args(JavaVMInitArgs*)
  49 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
  50 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
  51 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
  52 bool   Arguments::_ClipInlining                 = ClipInlining;
  53 
  54 char*  Arguments::SharedArchivePath             = NULL;
  55 
  56 AgentLibraryList Arguments::_libraryList;
  57 AgentLibraryList Arguments::_agentList;
  58 
  59 abort_hook_t     Arguments::_abort_hook         = NULL;
  60 exit_hook_t      Arguments::_exit_hook          = NULL;
  61 vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
  62 
  63 
  64 SystemProperty *Arguments::_java_ext_dirs = NULL;
  65 SystemProperty *Arguments::_java_endorsed_dirs = NULL;
  66 SystemProperty *Arguments::_sun_boot_library_path = NULL;
  67 SystemProperty *Arguments::_java_library_path = NULL;
  68 SystemProperty *Arguments::_java_home = NULL;
  69 SystemProperty *Arguments::_java_class_path = NULL;
  70 SystemProperty *Arguments::_sun_boot_class_path = NULL;
  71 
  72 char* Arguments::_meta_index_path = NULL;
  73 char* Arguments::_meta_index_dir = NULL;
  74 
  75 static bool force_client_mode = false;
  76 
  77 // Check if head of 'option' matches 'name', and sets 'tail' remaining part of option string
  78 
  79 static bool match_option(const JavaVMOption *option, const char* name,
  80                          const char** tail) {
  81   int len = (int)strlen(name);
  82   if (strncmp(option->optionString, name, len) == 0) {
  83     *tail = option->optionString + len;
  84     return true;
  85   } else {
  86     return false;
  87   }
  88 }
  89 
  90 static void logOption(const char* opt) {
  91   if (PrintVMOptions) {
  92     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
  93   }
  94 }
  95 
  96 // Process java launcher properties.
  97 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
  98   // See if sun.java.launcher or sun.java.launcher.pid is defined.
  99   // Must do this before setting up other system properties,
 100   // as some of them may depend on launcher type.
 101   for (int index = 0; index < args->nOptions; index++) {
 102     const JavaVMOption* option = args->options + index;
 103     const char* tail;
 104 
 105     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
 106       process_java_launcher_argument(tail, option->extraInfo);
 107       continue;
 108     }
 109     if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
 110       _sun_java_launcher_pid = atoi(tail);
 111       continue;
 112     }
 113   }
 114 }
 115 
 116 // Initialize system properties key and value.
 117 void Arguments::init_system_properties() {
 118 
 119   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.version", "1.0", false));
 120   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
 121                                                                  "Java Virtual Machine Specification",  false));
 122   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
 123   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
 124   PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
 125 
 126   // following are JVMTI agent writeable properties.
 127   // Properties values are set to NULL and they are
 128   // os specific they are initialized in os::init_system_properties_values().
 129   _java_ext_dirs = new SystemProperty("java.ext.dirs", NULL,  true);
 130   _java_endorsed_dirs = new SystemProperty("java.endorsed.dirs", NULL,  true);
 131   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
 132   _java_library_path = new SystemProperty("java.library.path", NULL,  true);
 133   _java_home =  new SystemProperty("java.home", NULL,  true);
 134   _sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL,  true);
 135 
 136   _java_class_path = new SystemProperty("java.class.path", "",  true);
 137 
 138   // Add to System Property list.
 139   PropertyList_add(&_system_properties, _java_ext_dirs);
 140   PropertyList_add(&_system_properties, _java_endorsed_dirs);
 141   PropertyList_add(&_system_properties, _sun_boot_library_path);
 142   PropertyList_add(&_system_properties, _java_library_path);
 143   PropertyList_add(&_system_properties, _java_home);
 144   PropertyList_add(&_system_properties, _java_class_path);
 145   PropertyList_add(&_system_properties, _sun_boot_class_path);
 146 
 147   // Set OS specific system properties values
 148   os::init_system_properties_values();
 149 }
 150 
 151 
 152   // Update/Initialize System properties after JDK version number is known
 153 void Arguments::init_version_specific_system_properties() {
 154   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.vendor",
 155         JDK_Version::is_gte_jdk17x_version() ? "Oracle Corporation" : "Sun Microsystems Inc.", false));
 156   PropertyList_add(&_system_properties, new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
 157 }
 158 
 159 /**
 160  * Provide a slightly more user-friendly way of eliminating -XX flags.
 161  * When a flag is eliminated, it can be added to this list in order to
 162  * continue accepting this flag on the command-line, while issuing a warning
 163  * and ignoring the value.  Once the JDK version reaches the 'accept_until'
 164  * limit, we flatly refuse to admit the existence of the flag.  This allows
 165  * a flag to die correctly over JDK releases using HSX.
 166  */
 167 typedef struct {
 168   const char* name;
 169   JDK_Version obsoleted_in; // when the flag went away
 170   JDK_Version accept_until; // which version to start denying the existence
 171 } ObsoleteFlag;
 172 
 173 static ObsoleteFlag obsolete_jvm_flags[] = {
 174   { "UseTrainGC",                    JDK_Version::jdk(5), JDK_Version::jdk(7) },
 175   { "UseSpecialLargeObjectHandling", JDK_Version::jdk(5), JDK_Version::jdk(7) },
 176   { "UseOversizedCarHandling",       JDK_Version::jdk(5), JDK_Version::jdk(7) },
 177   { "TraceCarAllocation",            JDK_Version::jdk(5), JDK_Version::jdk(7) },
 178   { "PrintTrainGCProcessingStats",   JDK_Version::jdk(5), JDK_Version::jdk(7) },
 179   { "LogOfCarSpaceSize",             JDK_Version::jdk(5), JDK_Version::jdk(7) },
 180   { "OversizedCarThreshold",         JDK_Version::jdk(5), JDK_Version::jdk(7) },
 181   { "MinTickInterval",               JDK_Version::jdk(5), JDK_Version::jdk(7) },
 182   { "DefaultTickInterval",           JDK_Version::jdk(5), JDK_Version::jdk(7) },
 183   { "MaxTickInterval",               JDK_Version::jdk(5), JDK_Version::jdk(7) },
 184   { "DelayTickAdjustment",           JDK_Version::jdk(5), JDK_Version::jdk(7) },
 185   { "ProcessingToTenuringRatio",     JDK_Version::jdk(5), JDK_Version::jdk(7) },
 186   { "MinTrainLength",                JDK_Version::jdk(5), JDK_Version::jdk(7) },
 187   { "AppendRatio",         JDK_Version::jdk_update(6,10), JDK_Version::jdk(7) },
 188   { "DefaultMaxRAM",       JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },
 189   { "DefaultInitialRAMFraction",
 190                            JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },
 191   { "UseDepthFirstScavengeOrder",
 192                            JDK_Version::jdk_update(6,22), JDK_Version::jdk(7) },
 193   { NULL, JDK_Version(0), JDK_Version(0) }
 194 };
 195 
 196 // Returns true if the flag is obsolete and fits into the range specified
 197 // for being ignored.  In the case that the flag is ignored, the 'version'
 198 // value is filled in with the version number when the flag became
 199 // obsolete so that that value can be displayed to the user.
 200 bool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {
 201   int i = 0;
 202   assert(version != NULL, "Must provide a version buffer");
 203   while (obsolete_jvm_flags[i].name != NULL) {
 204     const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];
 205     // <flag>=xxx form
 206     // [-|+]<flag> form
 207     if ((strncmp(flag_status.name, s, strlen(flag_status.name)) == 0) ||
 208         ((s[0] == '+' || s[0] == '-') &&
 209         (strncmp(flag_status.name, &s[1], strlen(flag_status.name)) == 0))) {
 210       if (JDK_Version::current().compare(flag_status.accept_until) == -1) {
 211           *version = flag_status.obsoleted_in;
 212           return true;
 213       }
 214     }
 215     i++;
 216   }
 217   return false;
 218 }
 219 
 220 // Constructs the system class path (aka boot class path) from the following
 221 // components, in order:
 222 //
 223 //     prefix           // from -Xbootclasspath/p:...
 224 //     endorsed         // the expansion of -Djava.endorsed.dirs=...
 225 //     base             // from os::get_system_properties() or -Xbootclasspath=
 226 //     suffix           // from -Xbootclasspath/a:...
 227 //
 228 // java.endorsed.dirs is a list of directories; any jar or zip files in the
 229 // directories are added to the sysclasspath just before the base.
 230 //
 231 // This could be AllStatic, but it isn't needed after argument processing is
 232 // complete.
 233 class SysClassPath: public StackObj {
 234 public:
 235   SysClassPath(const char* base);
 236   ~SysClassPath();
 237 
 238   inline void set_base(const char* base);
 239   inline void add_prefix(const char* prefix);
 240   inline void add_suffix_to_prefix(const char* suffix);
 241   inline void add_suffix(const char* suffix);
 242   inline void reset_path(const char* base);
 243 
 244   // Expand the jar/zip files in each directory listed by the java.endorsed.dirs
 245   // property.  Must be called after all command-line arguments have been
 246   // processed (in particular, -Djava.endorsed.dirs=...) and before calling
 247   // combined_path().
 248   void expand_endorsed();
 249 
 250   inline const char* get_base()     const { return _items[_scp_base]; }
 251   inline const char* get_prefix()   const { return _items[_scp_prefix]; }
 252   inline const char* get_suffix()   const { return _items[_scp_suffix]; }
 253   inline const char* get_endorsed() const { return _items[_scp_endorsed]; }
 254 
 255   // Combine all the components into a single c-heap-allocated string; caller
 256   // must free the string if/when no longer needed.
 257   char* combined_path();
 258 
 259 private:
 260   // Utility routines.
 261   static char* add_to_path(const char* path, const char* str, bool prepend);
 262   static char* add_jars_to_path(char* path, const char* directory);
 263 
 264   inline void reset_item_at(int index);
 265 
 266   // Array indices for the items that make up the sysclasspath.  All except the
 267   // base are allocated in the C heap and freed by this class.
 268   enum {
 269     _scp_prefix,        // from -Xbootclasspath/p:...
 270     _scp_endorsed,      // the expansion of -Djava.endorsed.dirs=...
 271     _scp_base,          // the default sysclasspath
 272     _scp_suffix,        // from -Xbootclasspath/a:...
 273     _scp_nitems         // the number of items, must be last.
 274   };
 275 
 276   const char* _items[_scp_nitems];
 277   DEBUG_ONLY(bool _expansion_done;)
 278 };
 279 
 280 SysClassPath::SysClassPath(const char* base) {
 281   memset(_items, 0, sizeof(_items));
 282   _items[_scp_base] = base;
 283   DEBUG_ONLY(_expansion_done = false;)
 284 }
 285 
 286 SysClassPath::~SysClassPath() {
 287   // Free everything except the base.
 288   for (int i = 0; i < _scp_nitems; ++i) {
 289     if (i != _scp_base) reset_item_at(i);
 290   }
 291   DEBUG_ONLY(_expansion_done = false;)
 292 }
 293 
 294 inline void SysClassPath::set_base(const char* base) {
 295   _items[_scp_base] = base;
 296 }
 297 
 298 inline void SysClassPath::add_prefix(const char* prefix) {
 299   _items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);
 300 }
 301 
 302 inline void SysClassPath::add_suffix_to_prefix(const char* suffix) {
 303   _items[_scp_prefix] = add_to_path(_items[_scp_prefix], suffix, false);
 304 }
 305 
 306 inline void SysClassPath::add_suffix(const char* suffix) {
 307   _items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);
 308 }
 309 
 310 inline void SysClassPath::reset_item_at(int index) {
 311   assert(index < _scp_nitems && index != _scp_base, "just checking");
 312   if (_items[index] != NULL) {
 313     FREE_C_HEAP_ARRAY(char, _items[index]);
 314     _items[index] = NULL;
 315   }
 316 }
 317 
 318 inline void SysClassPath::reset_path(const char* base) {
 319   // Clear the prefix and suffix.
 320   reset_item_at(_scp_prefix);
 321   reset_item_at(_scp_suffix);
 322   set_base(base);
 323 }
 324 
 325 //------------------------------------------------------------------------------
 326 
 327 void SysClassPath::expand_endorsed() {
 328   assert(_items[_scp_endorsed] == NULL, "can only be called once.");
 329 
 330   const char* path = Arguments::get_property("java.endorsed.dirs");
 331   if (path == NULL) {
 332     path = Arguments::get_endorsed_dir();
 333     assert(path != NULL, "no default for java.endorsed.dirs");
 334   }
 335 
 336   char* expanded_path = NULL;
 337   const char separator = *os::path_separator();
 338   const char* const end = path + strlen(path);
 339   while (path < end) {
 340     const char* tmp_end = strchr(path, separator);
 341     if (tmp_end == NULL) {
 342       expanded_path = add_jars_to_path(expanded_path, path);
 343       path = end;
 344     } else {
 345       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1);
 346       memcpy(dirpath, path, tmp_end - path);
 347       dirpath[tmp_end - path] = '\0';
 348       expanded_path = add_jars_to_path(expanded_path, dirpath);
 349       FREE_C_HEAP_ARRAY(char, dirpath);
 350       path = tmp_end + 1;
 351     }
 352   }
 353   _items[_scp_endorsed] = expanded_path;
 354   DEBUG_ONLY(_expansion_done = true;)
 355 }
 356 
 357 // Combine the bootclasspath elements, some of which may be null, into a single
 358 // c-heap-allocated string.
 359 char* SysClassPath::combined_path() {
 360   assert(_items[_scp_base] != NULL, "empty default sysclasspath");
 361   assert(_expansion_done, "must call expand_endorsed() first.");
 362 
 363   size_t lengths[_scp_nitems];
 364   size_t total_len = 0;
 365 
 366   const char separator = *os::path_separator();
 367 
 368   // Get the lengths.
 369   int i;
 370   for (i = 0; i < _scp_nitems; ++i) {
 371     if (_items[i] != NULL) {
 372       lengths[i] = strlen(_items[i]);
 373       // Include space for the separator char (or a NULL for the last item).
 374       total_len += lengths[i] + 1;
 375     }
 376   }
 377   assert(total_len > 0, "empty sysclasspath not allowed");
 378 
 379   // Copy the _items to a single string.
 380   char* cp = NEW_C_HEAP_ARRAY(char, total_len);
 381   char* cp_tmp = cp;
 382   for (i = 0; i < _scp_nitems; ++i) {
 383     if (_items[i] != NULL) {
 384       memcpy(cp_tmp, _items[i], lengths[i]);
 385       cp_tmp += lengths[i];
 386       *cp_tmp++ = separator;
 387     }
 388   }
 389   *--cp_tmp = '\0';     // Replace the extra separator.
 390   return cp;
 391 }
 392 
 393 // Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
 394 char*
 395 SysClassPath::add_to_path(const char* path, const char* str, bool prepend) {
 396   char *cp;
 397 
 398   assert(str != NULL, "just checking");
 399   if (path == NULL) {
 400     size_t len = strlen(str) + 1;
 401     cp = NEW_C_HEAP_ARRAY(char, len);
 402     memcpy(cp, str, len);                       // copy the trailing null
 403   } else {
 404     const char separator = *os::path_separator();
 405     size_t old_len = strlen(path);
 406     size_t str_len = strlen(str);
 407     size_t len = old_len + str_len + 2;
 408 
 409     if (prepend) {
 410       cp = NEW_C_HEAP_ARRAY(char, len);
 411       char* cp_tmp = cp;
 412       memcpy(cp_tmp, str, str_len);
 413       cp_tmp += str_len;
 414       *cp_tmp = separator;
 415       memcpy(++cp_tmp, path, old_len + 1);      // copy the trailing null
 416       FREE_C_HEAP_ARRAY(char, path);
 417     } else {
 418       cp = REALLOC_C_HEAP_ARRAY(char, path, len);
 419       char* cp_tmp = cp + old_len;
 420       *cp_tmp = separator;
 421       memcpy(++cp_tmp, str, str_len + 1);       // copy the trailing null
 422     }
 423   }
 424   return cp;
 425 }
 426 
 427 // Scan the directory and append any jar or zip files found to path.
 428 // Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
 429 char* SysClassPath::add_jars_to_path(char* path, const char* directory) {
 430   DIR* dir = os::opendir(directory);
 431   if (dir == NULL) return path;
 432 
 433   char dir_sep[2] = { '\0', '\0' };
 434   size_t directory_len = strlen(directory);
 435   const char fileSep = *os::file_separator();
 436   if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;
 437 
 438   /* Scan the directory for jars/zips, appending them to path. */
 439   struct dirent *entry;
 440   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory));
 441   while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
 442     const char* name = entry->d_name;
 443     const char* ext = name + strlen(name) - 4;
 444     bool isJarOrZip = ext > name &&
 445       (os::file_name_strcmp(ext, ".jar") == 0 ||
 446        os::file_name_strcmp(ext, ".zip") == 0);
 447     if (isJarOrZip) {
 448       char* jarpath = NEW_C_HEAP_ARRAY(char, directory_len + 2 + strlen(name));
 449       sprintf(jarpath, "%s%s%s", directory, dir_sep, name);
 450       path = add_to_path(path, jarpath, false);
 451       FREE_C_HEAP_ARRAY(char, jarpath);
 452     }
 453   }
 454   FREE_C_HEAP_ARRAY(char, dbuf);
 455   os::closedir(dir);
 456   return path;
 457 }
 458 
 459 // Parses a memory size specification string.
 460 static bool atomull(const char *s, julong* result) {
 461   julong n = 0;
 462   int args_read = sscanf(s, os::julong_format_specifier(), &n);
 463   if (args_read != 1) {
 464     return false;
 465   }
 466   while (*s != '\0' && isdigit(*s)) {
 467     s++;
 468   }
 469   // 4705540: illegal if more characters are found after the first non-digit
 470   if (strlen(s) > 1) {
 471     return false;
 472   }
 473   switch (*s) {
 474     case 'T': case 't':
 475       *result = n * G * K;
 476       // Check for overflow.
 477       if (*result/((julong)G * K) != n) return false;
 478       return true;
 479     case 'G': case 'g':
 480       *result = n * G;
 481       if (*result/G != n) return false;
 482       return true;
 483     case 'M': case 'm':
 484       *result = n * M;
 485       if (*result/M != n) return false;
 486       return true;
 487     case 'K': case 'k':
 488       *result = n * K;
 489       if (*result/K != n) return false;
 490       return true;
 491     case '\0':
 492       *result = n;
 493       return true;
 494     default:
 495       return false;
 496   }
 497 }
 498 
 499 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
 500   if (size < min_size) return arg_too_small;
 501   // Check that size will fit in a size_t (only relevant on 32-bit)
 502   if (size > max_uintx) return arg_too_big;
 503   return arg_in_range;
 504 }
 505 
 506 // Describe an argument out of range error
 507 void Arguments::describe_range_error(ArgsRange errcode) {
 508   switch(errcode) {
 509   case arg_too_big:
 510     jio_fprintf(defaultStream::error_stream(),
 511                 "The specified size exceeds the maximum "
 512                 "representable size.\n");
 513     break;
 514   case arg_too_small:
 515   case arg_unreadable:
 516   case arg_in_range:
 517     // do nothing for now
 518     break;
 519   default:
 520     ShouldNotReachHere();
 521   }
 522 }
 523 
 524 static bool set_bool_flag(char* name, bool value, FlagValueOrigin origin) {
 525   return CommandLineFlags::boolAtPut(name, &value, origin);
 526 }
 527 
 528 static bool set_fp_numeric_flag(char* name, char* value, FlagValueOrigin origin) {
 529   double v;
 530   if (sscanf(value, "%lf", &v) != 1) {
 531     return false;
 532   }
 533 
 534   if (CommandLineFlags::doubleAtPut(name, &v, origin)) {
 535     return true;
 536   }
 537   return false;
 538 }
 539 
 540 static bool set_numeric_flag(char* name, char* value, FlagValueOrigin origin) {
 541   julong v;
 542   intx intx_v;
 543   bool is_neg = false;
 544   // Check the sign first since atomull() parses only unsigned values.
 545   if (*value == '-') {
 546     if (!CommandLineFlags::intxAt(name, &intx_v)) {
 547       return false;
 548     }
 549     value++;
 550     is_neg = true;
 551   }
 552   if (!atomull(value, &v)) {
 553     return false;
 554   }
 555   intx_v = (intx) v;
 556   if (is_neg) {
 557     intx_v = -intx_v;
 558   }
 559   if (CommandLineFlags::intxAtPut(name, &intx_v, origin)) {
 560     return true;
 561   }
 562   uintx uintx_v = (uintx) v;
 563   if (!is_neg && CommandLineFlags::uintxAtPut(name, &uintx_v, origin)) {
 564     return true;
 565   }
 566   uint64_t uint64_t_v = (uint64_t) v;
 567   if (!is_neg && CommandLineFlags::uint64_tAtPut(name, &uint64_t_v, origin)) {
 568     return true;
 569   }
 570   return false;
 571 }
 572 
 573 static bool set_string_flag(char* name, const char* value, FlagValueOrigin origin) {
 574   if (!CommandLineFlags::ccstrAtPut(name, &value, origin))  return false;
 575   // Contract:  CommandLineFlags always returns a pointer that needs freeing.
 576   FREE_C_HEAP_ARRAY(char, value);
 577   return true;
 578 }
 579 
 580 static bool append_to_string_flag(char* name, const char* new_value, FlagValueOrigin origin) {
 581   const char* old_value = "";
 582   if (!CommandLineFlags::ccstrAt(name, &old_value))  return false;
 583   size_t old_len = old_value != NULL ? strlen(old_value) : 0;
 584   size_t new_len = strlen(new_value);
 585   const char* value;
 586   char* free_this_too = NULL;
 587   if (old_len == 0) {
 588     value = new_value;
 589   } else if (new_len == 0) {
 590     value = old_value;
 591   } else {
 592     char* buf = NEW_C_HEAP_ARRAY(char, old_len + 1 + new_len + 1);
 593     // each new setting adds another LINE to the switch:
 594     sprintf(buf, "%s\n%s", old_value, new_value);
 595     value = buf;
 596     free_this_too = buf;
 597   }
 598   (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
 599   // CommandLineFlags always returns a pointer that needs freeing.
 600   FREE_C_HEAP_ARRAY(char, value);
 601   if (free_this_too != NULL) {
 602     // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
 603     FREE_C_HEAP_ARRAY(char, free_this_too);
 604   }
 605   return true;
 606 }
 607 
 608 bool Arguments::parse_argument(const char* arg, FlagValueOrigin origin) {
 609 
 610   // range of acceptable characters spelled out for portability reasons
 611 #define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
 612 #define BUFLEN 255
 613   char name[BUFLEN+1];
 614   char dummy;
 615 
 616   if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
 617     return set_bool_flag(name, false, origin);
 618   }
 619   if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
 620     return set_bool_flag(name, true, origin);
 621   }
 622 
 623   char punct;
 624   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
 625     const char* value = strchr(arg, '=') + 1;
 626     Flag* flag = Flag::find_flag(name, strlen(name));
 627     if (flag != NULL && flag->is_ccstr()) {
 628       if (flag->ccstr_accumulates()) {
 629         return append_to_string_flag(name, value, origin);
 630       } else {
 631         if (value[0] == '\0') {
 632           value = NULL;
 633         }
 634         return set_string_flag(name, value, origin);
 635       }
 636     }
 637   }
 638 
 639   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
 640     const char* value = strchr(arg, '=') + 1;
 641     // -XX:Foo:=xxx will reset the string flag to the given value.
 642     if (value[0] == '\0') {
 643       value = NULL;
 644     }
 645     return set_string_flag(name, value, origin);
 646   }
 647 
 648 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"
 649 #define SIGNED_NUMBER_RANGE    "[-0123456789]"
 650 #define        NUMBER_RANGE    "[0123456789]"
 651   char value[BUFLEN + 1];
 652   char value2[BUFLEN + 1];
 653   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
 654     // Looks like a floating-point number -- try again with more lenient format string
 655     if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
 656       return set_fp_numeric_flag(name, value, origin);
 657     }
 658   }
 659 
 660 #define VALUE_RANGE "[-kmgtKMGT0123456789]"
 661   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
 662     return set_numeric_flag(name, value, origin);
 663   }
 664 
 665   return false;
 666 }
 667 
 668 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
 669   assert(bldarray != NULL, "illegal argument");
 670 
 671   if (arg == NULL) {
 672     return;
 673   }
 674 
 675   int index = *count;
 676 
 677   // expand the array and add arg to the last element
 678   (*count)++;
 679   if (*bldarray == NULL) {
 680     *bldarray = NEW_C_HEAP_ARRAY(char*, *count);
 681   } else {
 682     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, *count);
 683   }
 684   (*bldarray)[index] = strdup(arg);
 685 }
 686 
 687 void Arguments::build_jvm_args(const char* arg) {
 688   add_string(&_jvm_args_array, &_num_jvm_args, arg);
 689 }
 690 
 691 void Arguments::build_jvm_flags(const char* arg) {
 692   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
 693 }
 694 
 695 // utility function to return a string that concatenates all
 696 // strings in a given char** array
 697 const char* Arguments::build_resource_string(char** args, int count) {
 698   if (args == NULL || count == 0) {
 699     return NULL;
 700   }
 701   size_t length = strlen(args[0]) + 1; // add 1 for the null terminator
 702   for (int i = 1; i < count; i++) {
 703     length += strlen(args[i]) + 1; // add 1 for a space
 704   }
 705   char* s = NEW_RESOURCE_ARRAY(char, length);
 706   strcpy(s, args[0]);
 707   for (int j = 1; j < count; j++) {
 708     strcat(s, " ");
 709     strcat(s, args[j]);
 710   }
 711   return (const char*) s;
 712 }
 713 
 714 void Arguments::print_on(outputStream* st) {
 715   st->print_cr("VM Arguments:");
 716   if (num_jvm_flags() > 0) {
 717     st->print("jvm_flags: "); print_jvm_flags_on(st);
 718   }
 719   if (num_jvm_args() > 0) {
 720     st->print("jvm_args: "); print_jvm_args_on(st);
 721   }
 722   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
 723   st->print_cr("Launcher Type: %s", _sun_java_launcher);
 724 }
 725 
 726 void Arguments::print_jvm_flags_on(outputStream* st) {
 727   if (_num_jvm_flags > 0) {
 728     for (int i=0; i < _num_jvm_flags; i++) {
 729       st->print("%s ", _jvm_flags_array[i]);
 730     }
 731     st->print_cr("");
 732   }
 733 }
 734 
 735 void Arguments::print_jvm_args_on(outputStream* st) {
 736   if (_num_jvm_args > 0) {
 737     for (int i=0; i < _num_jvm_args; i++) {
 738       st->print("%s ", _jvm_args_array[i]);
 739     }
 740     st->print_cr("");
 741   }
 742 }
 743 
 744 bool Arguments::process_argument(const char* arg,
 745     jboolean ignore_unrecognized, FlagValueOrigin origin) {
 746 
 747   JDK_Version since = JDK_Version();
 748 
 749   if (parse_argument(arg, origin)) {
 750     // do nothing
 751   } else if (is_newly_obsolete(arg, &since)) {
 752     enum { bufsize = 256 };
 753     char buffer[bufsize];
 754     since.to_string(buffer, bufsize);
 755     jio_fprintf(defaultStream::error_stream(),
 756       "Warning: The flag %s has been EOL'd as of %s and will"
 757       " be ignored\n", arg, buffer);
 758   } else {
 759     if (!ignore_unrecognized) {
 760       jio_fprintf(defaultStream::error_stream(),
 761                   "Unrecognized VM option '%s'\n", arg);
 762       // allow for commandline "commenting out" options like -XX:#+Verbose
 763       if (strlen(arg) == 0 || arg[0] != '#') {
 764         return false;
 765       }
 766     }
 767   }
 768   return true;
 769 }
 770 
 771 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
 772   FILE* stream = fopen(file_name, "rb");
 773   if (stream == NULL) {
 774     if (should_exist) {
 775       jio_fprintf(defaultStream::error_stream(),
 776                   "Could not open settings file %s\n", file_name);
 777       return false;
 778     } else {
 779       return true;
 780     }
 781   }
 782 
 783   char token[1024];
 784   int  pos = 0;
 785 
 786   bool in_white_space = true;
 787   bool in_comment     = false;
 788   bool in_quote       = false;
 789   char quote_c        = 0;
 790   bool result         = true;
 791 
 792   int c = getc(stream);
 793   while(c != EOF) {
 794     if (in_white_space) {
 795       if (in_comment) {
 796         if (c == '\n') in_comment = false;
 797       } else {
 798         if (c == '#') in_comment = true;
 799         else if (!isspace(c)) {
 800           in_white_space = false;
 801           token[pos++] = c;
 802         }
 803       }
 804     } else {
 805       if (c == '\n' || (!in_quote && isspace(c))) {
 806         // token ends at newline, or at unquoted whitespace
 807         // this allows a way to include spaces in string-valued options
 808         token[pos] = '\0';
 809         logOption(token);
 810         result &= process_argument(token, ignore_unrecognized, CONFIG_FILE);
 811         build_jvm_flags(token);
 812         pos = 0;
 813         in_white_space = true;
 814         in_quote = false;
 815       } else if (!in_quote && (c == '\'' || c == '"')) {
 816         in_quote = true;
 817         quote_c = c;
 818       } else if (in_quote && (c == quote_c)) {
 819         in_quote = false;
 820       } else {
 821         token[pos++] = c;
 822       }
 823     }
 824     c = getc(stream);
 825   }
 826   if (pos > 0) {
 827     token[pos] = '\0';
 828     result &= process_argument(token, ignore_unrecognized, CONFIG_FILE);
 829     build_jvm_flags(token);
 830   }
 831   fclose(stream);
 832   return result;
 833 }
 834 
 835 //=============================================================================================================
 836 // Parsing of properties (-D)
 837 
 838 const char* Arguments::get_property(const char* key) {
 839   return PropertyList_get_value(system_properties(), key);
 840 }
 841 
 842 bool Arguments::add_property(const char* prop) {
 843   const char* eq = strchr(prop, '=');
 844   char* key;
 845   // ns must be static--its address may be stored in a SystemProperty object.
 846   const static char ns[1] = {0};
 847   char* value = (char *)ns;
 848 
 849   size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);
 850   key = AllocateHeap(key_len + 1, "add_property");
 851   strncpy(key, prop, key_len);
 852   key[key_len] = '\0';
 853 
 854   if (eq != NULL) {
 855     size_t value_len = strlen(prop) - key_len - 1;
 856     value = AllocateHeap(value_len + 1, "add_property");
 857     strncpy(value, &prop[key_len + 1], value_len + 1);
 858   }
 859 
 860   if (strcmp(key, "java.compiler") == 0) {
 861     process_java_compiler_argument(value);
 862     FreeHeap(key);
 863     if (eq != NULL) {
 864       FreeHeap(value);
 865     }
 866     return true;
 867   } else if (strcmp(key, "sun.java.command") == 0) {
 868     _java_command = value;
 869 
 870     // don't add this property to the properties exposed to the java application
 871     FreeHeap(key);
 872     return true;
 873   } else if (strcmp(key, "sun.java.launcher.pid") == 0) {
 874     // launcher.pid property is private and is processed
 875     // in process_sun_java_launcher_properties();
 876     // the sun.java.launcher property is passed on to the java application
 877     FreeHeap(key);
 878     if (eq != NULL) {
 879       FreeHeap(value);
 880     }
 881     return true;
 882   } else if (strcmp(key, "java.vendor.url.bug") == 0) {
 883     // save it in _java_vendor_url_bug, so JVM fatal error handler can access
 884     // its value without going through the property list or making a Java call.
 885     _java_vendor_url_bug = value;
 886   } else if (strcmp(key, "sun.boot.library.path") == 0) {
 887     PropertyList_unique_add(&_system_properties, key, value, true);
 888     return true;
 889   }
 890   // Create new property and add at the end of the list
 891   PropertyList_unique_add(&_system_properties, key, value);
 892   return true;
 893 }
 894 
 895 //===========================================================================================================
 896 // Setting int/mixed/comp mode flags
 897 
 898 void Arguments::set_mode_flags(Mode mode) {
 899   // Set up default values for all flags.
 900   // If you add a flag to any of the branches below,
 901   // add a default value for it here.
 902   set_java_compiler(false);
 903   _mode                      = mode;
 904 
 905   // Ensure Agent_OnLoad has the correct initial values.
 906   // This may not be the final mode; mode may change later in onload phase.
 907   PropertyList_unique_add(&_system_properties, "java.vm.info",
 908                           (char*)Abstract_VM_Version::vm_info_string(), false);
 909 
 910   UseInterpreter             = true;
 911   UseCompiler                = true;
 912   UseLoopCounter             = true;
 913 
 914   // Default values may be platform/compiler dependent -
 915   // use the saved values
 916   ClipInlining               = Arguments::_ClipInlining;
 917   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
 918   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
 919   BackgroundCompilation      = Arguments::_BackgroundCompilation;
 920 
 921   // Change from defaults based on mode
 922   switch (mode) {
 923   default:
 924     ShouldNotReachHere();
 925     break;
 926   case _int:
 927     UseCompiler              = false;
 928     UseLoopCounter           = false;
 929     AlwaysCompileLoopMethods = false;
 930     UseOnStackReplacement    = false;
 931     break;
 932   case _mixed:
 933     // same as default
 934     break;
 935   case _comp:
 936     UseInterpreter           = false;
 937     BackgroundCompilation    = false;
 938     ClipInlining             = false;
 939     break;
 940   }
 941 }
 942 
 943 // Conflict: required to use shared spaces (-Xshare:on), but
 944 // incompatible command line options were chosen.
 945 
 946 static void no_shared_spaces() {
 947   if (RequireSharedSpaces) {
 948     jio_fprintf(defaultStream::error_stream(),
 949       "Class data sharing is inconsistent with other specified options.\n");
 950     vm_exit_during_initialization("Unable to use shared archive.", NULL);
 951   } else {
 952     FLAG_SET_DEFAULT(UseSharedSpaces, false);
 953   }
 954 }
 955 
 956 void Arguments::set_tiered_flags() {
 957   if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
 958     FLAG_SET_DEFAULT(CompilationPolicyChoice, 2);
 959   }
 960 
 961   if (CompilationPolicyChoice < 2) {
 962     vm_exit_during_initialization(
 963       "Incompatible compilation policy selected", NULL);
 964   }
 965 
 966 #ifdef _LP64
 967   if (FLAG_IS_DEFAULT(UseCompressedOops) || FLAG_IS_ERGO(UseCompressedOops)) {
 968     UseCompressedOops = false;
 969   }
 970   if (UseCompressedOops) {
 971     vm_exit_during_initialization(
 972       "Tiered compilation is not supported with compressed oops yet", NULL);
 973   }
 974 #endif
 975  // Increase the code cache size - tiered compiles a lot more.
 976   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
 977     FLAG_SET_DEFAULT(ReservedCodeCacheSize, ReservedCodeCacheSize * 2);
 978   }
 979 }
 980 
 981 #ifndef KERNEL
 982 // If the user has chosen ParallelGCThreads > 0, we set UseParNewGC
 983 // if it's not explictly set or unset. If the user has chosen
 984 // UseParNewGC and not explicitly set ParallelGCThreads we
 985 // set it, unless this is a single cpu machine.
 986 void Arguments::set_parnew_gc_flags() {
 987   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
 988          "control point invariant");
 989   assert(UseParNewGC, "Error");
 990 
 991   // Turn off AdaptiveSizePolicy by default for parnew until it is
 992   // complete.
 993   if (FLAG_IS_DEFAULT(UseAdaptiveSizePolicy)) {
 994     FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
 995   }
 996 
 997   if (ParallelGCThreads == 0) {
 998     FLAG_SET_DEFAULT(ParallelGCThreads,
 999                      Abstract_VM_Version::parallel_worker_threads());
1000     if (ParallelGCThreads == 1) {
1001       FLAG_SET_DEFAULT(UseParNewGC, false);
1002       FLAG_SET_DEFAULT(ParallelGCThreads, 0);
1003     }
1004   }
1005   if (UseParNewGC) {
1006     // CDS doesn't work with ParNew yet
1007     no_shared_spaces();
1008 
1009     // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
1010     // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
1011     // we set them to 1024 and 1024.
1012     // See CR 6362902.
1013     if (FLAG_IS_DEFAULT(YoungPLABSize)) {
1014       FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
1015     }
1016     if (FLAG_IS_DEFAULT(OldPLABSize)) {
1017       FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
1018     }
1019 
1020     // AlwaysTenure flag should make ParNew promote all at first collection.
1021     // See CR 6362902.
1022     if (AlwaysTenure) {
1023       FLAG_SET_CMDLINE(intx, MaxTenuringThreshold, 0);
1024     }
1025     // When using compressed oops, we use local overflow stacks,
1026     // rather than using a global overflow list chained through
1027     // the klass word of the object's pre-image.
1028     if (UseCompressedOops && !ParGCUseLocalOverflow) {
1029       if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
1030         warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
1031       }
1032       FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
1033     }
1034     assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
1035   }
1036 }
1037 
1038 // Adjust some sizes to suit CMS and/or ParNew needs; these work well on
1039 // sparc/solaris for certain applications, but would gain from
1040 // further optimization and tuning efforts, and would almost
1041 // certainly gain from analysis of platform and environment.
1042 void Arguments::set_cms_and_parnew_gc_flags() {
1043   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
1044   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1045 
1046   // If we are using CMS, we prefer to UseParNewGC,
1047   // unless explicitly forbidden.
1048   if (FLAG_IS_DEFAULT(UseParNewGC)) {
1049     FLAG_SET_ERGO(bool, UseParNewGC, true);
1050   }
1051 
1052   // Turn off AdaptiveSizePolicy by default for cms until it is
1053   // complete.
1054   if (FLAG_IS_DEFAULT(UseAdaptiveSizePolicy)) {
1055     FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
1056   }
1057 
1058   // In either case, adjust ParallelGCThreads and/or UseParNewGC
1059   // as needed.
1060   if (UseParNewGC) {
1061     set_parnew_gc_flags();
1062   }
1063 
1064   // Now make adjustments for CMS
1065   size_t young_gen_per_worker;
1066   intx new_ratio;
1067   size_t min_new_default;
1068   intx tenuring_default;
1069   if (CMSUseOldDefaults) {  // old defaults: "old" as of 6.0
1070     if FLAG_IS_DEFAULT(CMSYoungGenPerWorker) {
1071       FLAG_SET_ERGO(intx, CMSYoungGenPerWorker, 4*M);
1072     }
1073     young_gen_per_worker = 4*M;
1074     new_ratio = (intx)15;
1075     min_new_default = 4*M;
1076     tenuring_default = (intx)0;
1077   } else { // new defaults: "new" as of 6.0
1078     young_gen_per_worker = CMSYoungGenPerWorker;
1079     new_ratio = (intx)7;
1080     min_new_default = 16*M;
1081     tenuring_default = (intx)4;
1082   }
1083 
1084   // Preferred young gen size for "short" pauses
1085   const uintx parallel_gc_threads =
1086     (ParallelGCThreads == 0 ? 1 : ParallelGCThreads);
1087   const size_t preferred_max_new_size_unaligned =
1088     ScaleForWordSize(young_gen_per_worker * parallel_gc_threads);
1089   const size_t preferred_max_new_size =
1090     align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
1091 
1092   // Unless explicitly requested otherwise, size young gen
1093   // for "short" pauses ~ 4M*ParallelGCThreads
1094 
1095   // If either MaxNewSize or NewRatio is set on the command line,
1096   // assume the user is trying to set the size of the young gen.
1097 
1098   if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
1099 
1100     // Set MaxNewSize to our calculated preferred_max_new_size unless
1101     // NewSize was set on the command line and it is larger than
1102     // preferred_max_new_size.
1103     if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
1104       FLAG_SET_ERGO(uintx, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
1105     } else {
1106       FLAG_SET_ERGO(uintx, MaxNewSize, preferred_max_new_size);
1107     }
1108     if (PrintGCDetails && Verbose) {
1109       // Too early to use gclog_or_tty
1110       tty->print_cr("Ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
1111     }
1112 
1113     // Unless explicitly requested otherwise, prefer a large
1114     // Old to Young gen size so as to shift the collection load
1115     // to the old generation concurrent collector
1116 
1117     // If this is only guarded by FLAG_IS_DEFAULT(NewRatio)
1118     // then NewSize and OldSize may be calculated.  That would
1119     // generally lead to some differences with ParNewGC for which
1120     // there was no obvious reason.  Also limit to the case where
1121     // MaxNewSize has not been set.
1122 
1123     FLAG_SET_ERGO(intx, NewRatio, MAX2(NewRatio, new_ratio));
1124 
1125     // Code along this path potentially sets NewSize and OldSize
1126 
1127     // Calculate the desired minimum size of the young gen but if
1128     // NewSize has been set on the command line, use it here since
1129     // it should be the final value.
1130     size_t min_new;
1131     if (FLAG_IS_DEFAULT(NewSize)) {
1132       min_new = align_size_up(ScaleForWordSize(min_new_default),
1133                               os::vm_page_size());
1134     } else {
1135       min_new = NewSize;
1136     }
1137     size_t prev_initial_size = InitialHeapSize;
1138     if (prev_initial_size != 0 && prev_initial_size < min_new + OldSize) {
1139       FLAG_SET_ERGO(uintx, InitialHeapSize, min_new + OldSize);
1140       // Currently minimum size and the initial heap sizes are the same.
1141       set_min_heap_size(InitialHeapSize);
1142       if (PrintGCDetails && Verbose) {
1143         warning("Initial heap size increased to " SIZE_FORMAT " M from "
1144                 SIZE_FORMAT " M; use -XX:NewSize=... for finer control.",
1145                 InitialHeapSize/M, prev_initial_size/M);
1146       }
1147     }
1148 
1149     // MaxHeapSize is aligned down in collectorPolicy
1150     size_t max_heap =
1151       align_size_down(MaxHeapSize,
1152                       CardTableRS::ct_max_alignment_constraint());
1153 
1154     if (PrintGCDetails && Verbose) {
1155       // Too early to use gclog_or_tty
1156       tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
1157            " initial_heap_size:  " SIZE_FORMAT
1158            " max_heap: " SIZE_FORMAT,
1159            min_heap_size(), InitialHeapSize, max_heap);
1160     }
1161     if (max_heap > min_new) {
1162       // Unless explicitly requested otherwise, make young gen
1163       // at least min_new, and at most preferred_max_new_size.
1164       if (FLAG_IS_DEFAULT(NewSize)) {
1165         FLAG_SET_ERGO(uintx, NewSize, MAX2(NewSize, min_new));
1166         FLAG_SET_ERGO(uintx, NewSize, MIN2(preferred_max_new_size, NewSize));
1167         if (PrintGCDetails && Verbose) {
1168           // Too early to use gclog_or_tty
1169           tty->print_cr("Ergo set NewSize: " SIZE_FORMAT, NewSize);
1170         }
1171       }
1172       // Unless explicitly requested otherwise, size old gen
1173       // so that it's at least 3X of NewSize to begin with;
1174       // later NewRatio will decide how it grows; see above.
1175       if (FLAG_IS_DEFAULT(OldSize)) {
1176         if (max_heap > NewSize) {
1177           FLAG_SET_ERGO(uintx, OldSize, MIN2(3*NewSize, max_heap - NewSize));
1178           if (PrintGCDetails && Verbose) {
1179             // Too early to use gclog_or_tty
1180             tty->print_cr("Ergo set OldSize: " SIZE_FORMAT, OldSize);
1181           }
1182         }
1183       }
1184     }
1185   }
1186   // Unless explicitly requested otherwise, definitely
1187   // promote all objects surviving "tenuring_default" scavenges.
1188   if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
1189       FLAG_IS_DEFAULT(SurvivorRatio)) {
1190     FLAG_SET_ERGO(intx, MaxTenuringThreshold, tenuring_default);
1191   }
1192   // If we decided above (or user explicitly requested)
1193   // `promote all' (via MaxTenuringThreshold := 0),
1194   // prefer minuscule survivor spaces so as not to waste
1195   // space for (non-existent) survivors
1196   if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
1197     FLAG_SET_ERGO(intx, SurvivorRatio, MAX2((intx)1024, SurvivorRatio));
1198   }
1199   // If OldPLABSize is set and CMSParPromoteBlocksToClaim is not,
1200   // set CMSParPromoteBlocksToClaim equal to OldPLABSize.
1201   // This is done in order to make ParNew+CMS configuration to work
1202   // with YoungPLABSize and OldPLABSize options.
1203   // See CR 6362902.
1204   if (!FLAG_IS_DEFAULT(OldPLABSize)) {
1205     if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {
1206       // OldPLABSize is not the default value but CMSParPromoteBlocksToClaim
1207       // is.  In this situtation let CMSParPromoteBlocksToClaim follow
1208       // the value (either from the command line or ergonomics) of
1209       // OldPLABSize.  Following OldPLABSize is an ergonomics decision.
1210       FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, OldPLABSize);
1211     } else {
1212       // OldPLABSize and CMSParPromoteBlocksToClaim are both set.
1213       // CMSParPromoteBlocksToClaim is a collector-specific flag, so
1214       // we'll let it to take precedence.
1215       jio_fprintf(defaultStream::error_stream(),
1216                   "Both OldPLABSize and CMSParPromoteBlocksToClaim"
1217                   " options are specified for the CMS collector."
1218                   " CMSParPromoteBlocksToClaim will take precedence.\n");
1219     }
1220   }
1221   if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
1222     // OldPLAB sizing manually turned off: Use a larger default setting,
1223     // unless it was manually specified. This is because a too-low value
1224     // will slow down scavenges.
1225     if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {
1226       FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, 50); // default value before 6631166
1227     }
1228   }
1229   // Overwrite OldPLABSize which is the variable we will internally use everywhere.
1230   FLAG_SET_ERGO(uintx, OldPLABSize, CMSParPromoteBlocksToClaim);
1231   // If either of the static initialization defaults have changed, note this
1232   // modification.
1233   if (!FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
1234     CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
1235   }
1236   if (PrintGCDetails && Verbose) {
1237     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1238       MarkStackSize / K, MarkStackSizeMax / K);
1239     tty->print_cr("ConcGCThreads: %u", ConcGCThreads);
1240   }
1241 }
1242 #endif // KERNEL
1243 
1244 void set_object_alignment() {
1245   // Object alignment.
1246   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1247   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1248   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1249   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1250   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1251   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1252 
1253   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1254   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1255 
1256   // Oop encoding heap max
1257   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1258 
1259 #ifndef KERNEL
1260   // Set CMS global values
1261   CompactibleFreeListSpace::set_cms_values();
1262 #endif // KERNEL
1263 }
1264 
1265 bool verify_object_alignment() {
1266   // Object alignment.
1267   if (!is_power_of_2(ObjectAlignmentInBytes)) {
1268     jio_fprintf(defaultStream::error_stream(),
1269                 "error: ObjectAlignmentInBytes=%d must be power of 2", (int)ObjectAlignmentInBytes);
1270     return false;
1271   }
1272   if ((int)ObjectAlignmentInBytes < BytesPerLong) {
1273     jio_fprintf(defaultStream::error_stream(),
1274                 "error: ObjectAlignmentInBytes=%d must be greater or equal %d", (int)ObjectAlignmentInBytes, BytesPerLong);
1275     return false;
1276   }
1277   return true;
1278 }
1279 
1280 inline uintx max_heap_for_compressed_oops() {
1281   // Heap should be above HeapBaseMinAddress to get zero based compressed oops.
1282   LP64_ONLY(return OopEncodingHeapMax - MaxPermSize - os::vm_page_size() - HeapBaseMinAddress);
1283   NOT_LP64(ShouldNotReachHere(); return 0);
1284 }
1285 
1286 bool Arguments::should_auto_select_low_pause_collector() {
1287   if (UseAutoGCSelectPolicy &&
1288       !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
1289       (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
1290     if (PrintGCDetails) {
1291       // Cannot use gclog_or_tty yet.
1292       tty->print_cr("Automatic selection of the low pause collector"
1293        " based on pause goal of %d (ms)", MaxGCPauseMillis);
1294     }
1295     return true;
1296   }
1297   return false;
1298 }
1299 
1300 void Arguments::set_ergonomics_flags() {
1301   // Parallel GC is not compatible with sharing. If one specifies
1302   // that they want sharing explicitly, do not set ergonomics flags.
1303   if (DumpSharedSpaces || ForceSharedSpaces) {
1304     return;
1305   }
1306 
1307   if (os::is_server_class_machine() && !force_client_mode ) {
1308     // If no other collector is requested explicitly,
1309     // let the VM select the collector based on
1310     // machine class and automatic selection policy.
1311     if (!UseSerialGC &&
1312         !UseConcMarkSweepGC &&
1313         !UseG1GC &&
1314         !UseParNewGC &&
1315         !DumpSharedSpaces &&
1316         FLAG_IS_DEFAULT(UseParallelGC)) {
1317       if (should_auto_select_low_pause_collector()) {
1318         FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
1319       } else {
1320         FLAG_SET_ERGO(bool, UseParallelGC, true);
1321       }
1322       no_shared_spaces();
1323     }
1324   }
1325 
1326 #ifndef ZERO
1327 #ifdef _LP64
1328   // Check that UseCompressedOops can be set with the max heap size allocated
1329   // by ergonomics.
1330   if (MaxHeapSize <= max_heap_for_compressed_oops()) {
1331 #if !defined(COMPILER1) || defined(TIERED)
1332     if (FLAG_IS_DEFAULT(UseCompressedOops) && !UseG1GC) {
1333       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1334     }
1335 #endif
1336 #ifdef _WIN64
1337     if (UseLargePages && UseCompressedOops) {
1338       // Cannot allocate guard pages for implicit checks in indexed addressing
1339       // mode, when large pages are specified on windows.
1340       // This flag could be switched ON if narrow oop base address is set to 0,
1341       // see code in Universe::initialize_heap().
1342       Universe::set_narrow_oop_use_implicit_null_checks(false);
1343     }
1344 #endif //  _WIN64
1345   } else {
1346     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1347       warning("Max heap size too large for Compressed Oops");
1348       FLAG_SET_DEFAULT(UseCompressedOops, false);
1349     }
1350   }
1351   // Also checks that certain machines are slower with compressed oops
1352   // in vm_version initialization code.
1353 #endif // _LP64
1354 #endif // !ZERO
1355 }
1356 
1357 void Arguments::set_parallel_gc_flags() {
1358   assert(UseParallelGC || UseParallelOldGC, "Error");
1359   // If parallel old was requested, automatically enable parallel scavenge.
1360   if (UseParallelOldGC && !UseParallelGC && FLAG_IS_DEFAULT(UseParallelGC)) {
1361     FLAG_SET_DEFAULT(UseParallelGC, true);
1362   }
1363 
1364   // If no heap maximum was requested explicitly, use some reasonable fraction
1365   // of the physical memory, up to a maximum of 1GB.
1366   if (UseParallelGC) {
1367     FLAG_SET_ERGO(uintx, ParallelGCThreads,
1368                   Abstract_VM_Version::parallel_worker_threads());
1369 
1370     // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1371     // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1372     // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1373     // See CR 6362902 for details.
1374     if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1375       if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1376          FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1377       }
1378       if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1379         FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1380       }
1381     }
1382 
1383     if (UseParallelOldGC) {
1384       // Par compact uses lower default values since they are treated as
1385       // minimums.  These are different defaults because of the different
1386       // interpretation and are not ergonomically set.
1387       if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1388         FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1389       }
1390       if (FLAG_IS_DEFAULT(PermMarkSweepDeadRatio)) {
1391         FLAG_SET_DEFAULT(PermMarkSweepDeadRatio, 5);
1392       }
1393     }
1394   }
1395 }
1396 
1397 void Arguments::set_g1_gc_flags() {
1398   assert(UseG1GC, "Error");
1399 #ifdef COMPILER1
1400   FastTLABRefill = false;
1401 #endif
1402   FLAG_SET_DEFAULT(ParallelGCThreads,
1403                      Abstract_VM_Version::parallel_worker_threads());
1404   if (ParallelGCThreads == 0) {
1405     FLAG_SET_DEFAULT(ParallelGCThreads,
1406                      Abstract_VM_Version::parallel_worker_threads());
1407   }
1408   no_shared_spaces();
1409 
1410   if (FLAG_IS_DEFAULT(MarkStackSize)) {
1411     FLAG_SET_DEFAULT(MarkStackSize, 128 * TASKQUEUE_SIZE);
1412   }
1413   if (PrintGCDetails && Verbose) {
1414     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1415       MarkStackSize / K, MarkStackSizeMax / K);
1416     tty->print_cr("ConcGCThreads: %u", ConcGCThreads);
1417   }
1418 
1419   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1420     // In G1, we want the default GC overhead goal to be higher than
1421     // say in PS. So we set it here to 10%. Otherwise the heap might
1422     // be expanded more aggressively than we would like it to. In
1423     // fact, even 10% seems to not be high enough in some cases
1424     // (especially small GC stress tests that the main thing they do
1425     // is allocation). We might consider increase it further.
1426     FLAG_SET_DEFAULT(GCTimeRatio, 9);
1427   }
1428 }
1429 
1430 void Arguments::set_heap_size() {
1431   if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
1432     // Deprecated flag
1433     FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
1434   }
1435 
1436   const julong phys_mem =
1437     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1438                             : (julong)MaxRAM;
1439 
1440   // If the maximum heap size has not been set with -Xmx,
1441   // then set it as fraction of the size of physical memory,
1442   // respecting the maximum and minimum sizes of the heap.
1443   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1444     julong reasonable_max = phys_mem / MaxRAMFraction;
1445 
1446     if (phys_mem <= MaxHeapSize * MinRAMFraction) {
1447       // Small physical memory, so use a minimum fraction of it for the heap
1448       reasonable_max = phys_mem / MinRAMFraction;
1449     } else {
1450       // Not-small physical memory, so require a heap at least
1451       // as large as MaxHeapSize
1452       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1453     }
1454     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1455       // Limit the heap size to ErgoHeapSizeLimit
1456       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1457     }
1458     if (UseCompressedOops) {
1459       // Limit the heap size to the maximum possible when using compressed oops
1460       reasonable_max = MIN2(reasonable_max, (julong)max_heap_for_compressed_oops());
1461     }
1462     reasonable_max = os::allocatable_physical_memory(reasonable_max);
1463 
1464     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1465       // An initial heap size was specified on the command line,
1466       // so be sure that the maximum size is consistent.  Done
1467       // after call to allocatable_physical_memory because that
1468       // method might reduce the allocation size.
1469       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1470     }
1471 
1472     if (PrintGCDetails && Verbose) {
1473       // Cannot use gclog_or_tty yet.
1474       tty->print_cr("  Maximum heap size " SIZE_FORMAT, reasonable_max);
1475     }
1476     FLAG_SET_ERGO(uintx, MaxHeapSize, (uintx)reasonable_max);
1477   }
1478 
1479   // If the initial_heap_size has not been set with InitialHeapSize
1480   // or -Xms, then set it as fraction of the size of physical memory,
1481   // respecting the maximum and minimum sizes of the heap.
1482   if (FLAG_IS_DEFAULT(InitialHeapSize)) {
1483     julong reasonable_minimum = (julong)(OldSize + NewSize);
1484 
1485     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1486 
1487     reasonable_minimum = os::allocatable_physical_memory(reasonable_minimum);
1488 
1489     julong reasonable_initial = phys_mem / InitialRAMFraction;
1490 
1491     reasonable_initial = MAX2(reasonable_initial, reasonable_minimum);
1492     reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1493 
1494     reasonable_initial = os::allocatable_physical_memory(reasonable_initial);
1495 
1496     if (PrintGCDetails && Verbose) {
1497       // Cannot use gclog_or_tty yet.
1498       tty->print_cr("  Initial heap size " SIZE_FORMAT, (uintx)reasonable_initial);
1499       tty->print_cr("  Minimum heap size " SIZE_FORMAT, (uintx)reasonable_minimum);
1500     }
1501     FLAG_SET_ERGO(uintx, InitialHeapSize, (uintx)reasonable_initial);
1502     set_min_heap_size((uintx)reasonable_minimum);
1503   }
1504 }
1505 
1506 // This must be called after ergonomics because we want bytecode rewriting
1507 // if the server compiler is used, or if UseSharedSpaces is disabled.
1508 void Arguments::set_bytecode_flags() {
1509   // Better not attempt to store into a read-only space.
1510   if (UseSharedSpaces) {
1511     FLAG_SET_DEFAULT(RewriteBytecodes, false);
1512     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1513   }
1514 
1515   if (!RewriteBytecodes) {
1516     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1517   }
1518 }
1519 
1520 // Aggressive optimization flags  -XX:+AggressiveOpts
1521 void Arguments::set_aggressive_opts_flags() {
1522 #ifdef COMPILER2
1523   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1524     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1525       FLAG_SET_DEFAULT(EliminateAutoBox, true);
1526     }
1527     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1528       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
1529     }
1530 
1531     // Feed the cache size setting into the JDK
1532     char buffer[1024];
1533     sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
1534     add_property(buffer);
1535   }
1536   if (AggressiveOpts && FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1537     FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1538   }
1539   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
1540     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
1541   }
1542   if (AggressiveOpts && FLAG_IS_DEFAULT(OptimizeStringConcat)) {
1543     FLAG_SET_DEFAULT(OptimizeStringConcat, true);
1544   }
1545   if (AggressiveOpts && FLAG_IS_DEFAULT(OptimizeFill)) {
1546     FLAG_SET_DEFAULT(OptimizeFill, true);
1547   }
1548 #endif
1549 
1550   if (AggressiveOpts) {
1551 // Sample flag setting code
1552 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
1553 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
1554 //    }
1555   }
1556 }
1557 
1558 //===========================================================================================================
1559 // Parsing of java.compiler property
1560 
1561 void Arguments::process_java_compiler_argument(char* arg) {
1562   // For backwards compatibility, Djava.compiler=NONE or ""
1563   // causes us to switch to -Xint mode UNLESS -Xdebug
1564   // is also specified.
1565   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
1566     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
1567   }
1568 }
1569 
1570 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1571   _sun_java_launcher = strdup(launcher);
1572 }
1573 
1574 bool Arguments::created_by_java_launcher() {
1575   assert(_sun_java_launcher != NULL, "property must have value");
1576   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1577 }
1578 
1579 //===========================================================================================================
1580 // Parsing of main arguments
1581 
1582 bool Arguments::verify_interval(uintx val, uintx min,
1583                                 uintx max, const char* name) {
1584   // Returns true iff value is in the inclusive interval [min..max]
1585   // false, otherwise.
1586   if (val >= min && val <= max) {
1587     return true;
1588   }
1589   jio_fprintf(defaultStream::error_stream(),
1590               "%s of " UINTX_FORMAT " is invalid; must be between " UINTX_FORMAT
1591               " and " UINTX_FORMAT "\n",
1592               name, val, min, max);
1593   return false;
1594 }
1595 
1596 bool Arguments::verify_min_value(intx val, intx min, const char* name) {
1597   // Returns true if given value is greater than specified min threshold
1598   // false, otherwise.
1599   if (val >= min ) {
1600       return true;
1601   }
1602   jio_fprintf(defaultStream::error_stream(),
1603               "%s of " INTX_FORMAT " is invalid; must be greater than " INTX_FORMAT "\n",
1604               name, val, min);
1605   return false;
1606 }
1607 
1608 bool Arguments::verify_percentage(uintx value, const char* name) {
1609   if (value <= 100) {
1610     return true;
1611   }
1612   jio_fprintf(defaultStream::error_stream(),
1613               "%s of " UINTX_FORMAT " is invalid; must be between 0 and 100\n",
1614               name, value);
1615   return false;
1616 }
1617 
1618 static void force_serial_gc() {
1619   FLAG_SET_DEFAULT(UseSerialGC, true);
1620   FLAG_SET_DEFAULT(UseParNewGC, false);
1621   FLAG_SET_DEFAULT(UseConcMarkSweepGC, false);
1622   FLAG_SET_DEFAULT(CMSIncrementalMode, false);  // special CMS suboption
1623   FLAG_SET_DEFAULT(UseParallelGC, false);
1624   FLAG_SET_DEFAULT(UseParallelOldGC, false);
1625   FLAG_SET_DEFAULT(UseG1GC, false);
1626 }
1627 
1628 static bool verify_serial_gc_flags() {
1629   return (UseSerialGC &&
1630         !(UseParNewGC || (UseConcMarkSweepGC || CMSIncrementalMode) || UseG1GC ||
1631           UseParallelGC || UseParallelOldGC));
1632 }
1633 
1634 // Check consistency of GC selection
1635 bool Arguments::check_gc_consistency() {
1636   bool status = true;
1637   // Ensure that the user has not selected conflicting sets
1638   // of collectors. [Note: this check is merely a user convenience;
1639   // collectors over-ride each other so that only a non-conflicting
1640   // set is selected; however what the user gets is not what they
1641   // may have expected from the combination they asked for. It's
1642   // better to reduce user confusion by not allowing them to
1643   // select conflicting combinations.
1644   uint i = 0;
1645   if (UseSerialGC)                       i++;
1646   if (UseConcMarkSweepGC || UseParNewGC) i++;
1647   if (UseParallelGC || UseParallelOldGC) i++;
1648   if (UseG1GC)                           i++;
1649   if (i > 1) {
1650     jio_fprintf(defaultStream::error_stream(),
1651                 "Conflicting collector combinations in option list; "
1652                 "please refer to the release notes for the combinations "
1653                 "allowed\n");
1654     status = false;
1655   }
1656 
1657   return status;
1658 }
1659 
1660 // Check stack pages settings
1661 bool Arguments::check_stack_pages()
1662 {
1663   bool status = true;
1664   status = status && verify_min_value(StackYellowPages, 1, "StackYellowPages");
1665   status = status && verify_min_value(StackRedPages, 1, "StackRedPages");
1666   status = status && verify_min_value(StackShadowPages, 1, "StackShadowPages");
1667   return status;
1668 }
1669 
1670 // Check the consistency of vm_init_args
1671 bool Arguments::check_vm_args_consistency() {
1672   // Method for adding checks for flag consistency.
1673   // The intent is to warn the user of all possible conflicts,
1674   // before returning an error.
1675   // Note: Needs platform-dependent factoring.
1676   bool status = true;
1677 
1678 #if ( (defined(COMPILER2) && defined(SPARC)))
1679   // NOTE: The call to VM_Version_init depends on the fact that VM_Version_init
1680   // on sparc doesn't require generation of a stub as is the case on, e.g.,
1681   // x86.  Normally, VM_Version_init must be called from init_globals in
1682   // init.cpp, which is called by the initial java thread *after* arguments
1683   // have been parsed.  VM_Version_init gets called twice on sparc.
1684   extern void VM_Version_init();
1685   VM_Version_init();
1686   if (!VM_Version::has_v9()) {
1687     jio_fprintf(defaultStream::error_stream(),
1688                 "V8 Machine detected, Server requires V9\n");
1689     status = false;
1690   }
1691 #endif /* COMPILER2 && SPARC */
1692 
1693   // Allow both -XX:-UseStackBanging and -XX:-UseBoundThreads in non-product
1694   // builds so the cost of stack banging can be measured.
1695 #if (defined(PRODUCT) && defined(SOLARIS))
1696   if (!UseBoundThreads && !UseStackBanging) {
1697     jio_fprintf(defaultStream::error_stream(),
1698                 "-UseStackBanging conflicts with -UseBoundThreads\n");
1699 
1700      status = false;
1701   }
1702 #endif
1703 
1704   if (TLABRefillWasteFraction == 0) {
1705     jio_fprintf(defaultStream::error_stream(),
1706                 "TLABRefillWasteFraction should be a denominator, "
1707                 "not " SIZE_FORMAT "\n",
1708                 TLABRefillWasteFraction);
1709     status = false;
1710   }
1711 
1712   status = status && verify_percentage(MaxLiveObjectEvacuationRatio,
1713                               "MaxLiveObjectEvacuationRatio");
1714   status = status && verify_percentage(AdaptiveSizePolicyWeight,
1715                               "AdaptiveSizePolicyWeight");
1716   status = status && verify_percentage(AdaptivePermSizeWeight, "AdaptivePermSizeWeight");
1717   status = status && verify_percentage(ThresholdTolerance, "ThresholdTolerance");
1718   status = status && verify_percentage(MinHeapFreeRatio, "MinHeapFreeRatio");
1719   status = status && verify_percentage(MaxHeapFreeRatio, "MaxHeapFreeRatio");
1720 
1721   if (MinHeapFreeRatio > MaxHeapFreeRatio) {
1722     jio_fprintf(defaultStream::error_stream(),
1723                 "MinHeapFreeRatio (" UINTX_FORMAT ") must be less than or "
1724                 "equal to MaxHeapFreeRatio (" UINTX_FORMAT ")\n",
1725                 MinHeapFreeRatio, MaxHeapFreeRatio);
1726     status = false;
1727   }
1728   // Keeping the heap 100% free is hard ;-) so limit it to 99%.
1729   MinHeapFreeRatio = MIN2(MinHeapFreeRatio, (uintx) 99);
1730 
1731   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
1732     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
1733   }
1734 
1735   if (UseParallelOldGC && ParallelOldGCSplitALot) {
1736     // Settings to encourage splitting.
1737     if (!FLAG_IS_CMDLINE(NewRatio)) {
1738       FLAG_SET_CMDLINE(intx, NewRatio, 2);
1739     }
1740     if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
1741       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
1742     }
1743   }
1744 
1745   status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit");
1746   status = status && verify_percentage(GCTimeLimit, "GCTimeLimit");
1747   if (GCTimeLimit == 100) {
1748     // Turn off gc-overhead-limit-exceeded checks
1749     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
1750   }
1751 
1752   status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit");
1753 
1754   // Check whether user-specified sharing option conflicts with GC or page size.
1755   // Both sharing and large pages are enabled by default on some platforms;
1756   // large pages override sharing only if explicitly set on the command line.
1757   const bool cannot_share = UseConcMarkSweepGC || CMSIncrementalMode ||
1758           UseG1GC || UseParNewGC || UseParallelGC || UseParallelOldGC ||
1759           UseLargePages && FLAG_IS_CMDLINE(UseLargePages);
1760   if (cannot_share) {
1761     // Either force sharing on by forcing the other options off, or
1762     // force sharing off.
1763     if (DumpSharedSpaces || ForceSharedSpaces) {
1764       jio_fprintf(defaultStream::error_stream(),
1765                   "Using Serial GC and default page size because of %s\n",
1766                   ForceSharedSpaces ? "-Xshare:on" : "-Xshare:dump");
1767       force_serial_gc();
1768       FLAG_SET_DEFAULT(UseLargePages, false);
1769     } else {
1770       if (UseSharedSpaces && Verbose) {
1771         jio_fprintf(defaultStream::error_stream(),
1772                     "Turning off use of shared archive because of "
1773                     "choice of garbage collector or large pages\n");
1774       }
1775       no_shared_spaces();
1776     }
1777   } else if (UseLargePages && (UseSharedSpaces || DumpSharedSpaces)) {
1778     FLAG_SET_DEFAULT(UseLargePages, false);
1779   }
1780 
1781   status = status && check_gc_consistency();
1782   status = status && check_stack_pages();
1783 
1784   if (_has_alloc_profile) {
1785     if (UseParallelGC || UseParallelOldGC) {
1786       jio_fprintf(defaultStream::error_stream(),
1787                   "error:  invalid argument combination.\n"
1788                   "Allocation profiling (-Xaprof) cannot be used together with "
1789                   "Parallel GC (-XX:+UseParallelGC or -XX:+UseParallelOldGC).\n");
1790       status = false;
1791     }
1792     if (UseConcMarkSweepGC) {
1793       jio_fprintf(defaultStream::error_stream(),
1794                   "error:  invalid argument combination.\n"
1795                   "Allocation profiling (-Xaprof) cannot be used together with "
1796                   "the CMS collector (-XX:+UseConcMarkSweepGC).\n");
1797       status = false;
1798     }
1799   }
1800 
1801   if (CMSIncrementalMode) {
1802     if (!UseConcMarkSweepGC) {
1803       jio_fprintf(defaultStream::error_stream(),
1804                   "error:  invalid argument combination.\n"
1805                   "The CMS collector (-XX:+UseConcMarkSweepGC) must be "
1806                   "selected in order\nto use CMSIncrementalMode.\n");
1807       status = false;
1808     } else {
1809       status = status && verify_percentage(CMSIncrementalDutyCycle,
1810                                   "CMSIncrementalDutyCycle");
1811       status = status && verify_percentage(CMSIncrementalDutyCycleMin,
1812                                   "CMSIncrementalDutyCycleMin");
1813       status = status && verify_percentage(CMSIncrementalSafetyFactor,
1814                                   "CMSIncrementalSafetyFactor");
1815       status = status && verify_percentage(CMSIncrementalOffset,
1816                                   "CMSIncrementalOffset");
1817       status = status && verify_percentage(CMSExpAvgFactor,
1818                                   "CMSExpAvgFactor");
1819       // If it was not set on the command line, set
1820       // CMSInitiatingOccupancyFraction to 1 so icms can initiate cycles early.
1821       if (CMSInitiatingOccupancyFraction < 0) {
1822         FLAG_SET_DEFAULT(CMSInitiatingOccupancyFraction, 1);
1823       }
1824     }
1825   }
1826 
1827   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
1828   // insists that we hold the requisite locks so that the iteration is
1829   // MT-safe. For the verification at start-up and shut-down, we don't
1830   // yet have a good way of acquiring and releasing these locks,
1831   // which are not visible at the CollectedHeap level. We want to
1832   // be able to acquire these locks and then do the iteration rather
1833   // than just disable the lock verification. This will be fixed under
1834   // bug 4788986.
1835   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
1836     if (VerifyGCStartAt == 0) {
1837       warning("Heap verification at start-up disabled "
1838               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
1839       VerifyGCStartAt = 1;      // Disable verification at start-up
1840     }
1841     if (VerifyBeforeExit) {
1842       warning("Heap verification at shutdown disabled "
1843               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
1844       VerifyBeforeExit = false; // Disable verification at shutdown
1845     }
1846   }
1847 
1848   // Note: only executed in non-PRODUCT mode
1849   if (!UseAsyncConcMarkSweepGC &&
1850       (ExplicitGCInvokesConcurrent ||
1851        ExplicitGCInvokesConcurrentAndUnloadsClasses)) {
1852     jio_fprintf(defaultStream::error_stream(),
1853                 "error: +ExplictGCInvokesConcurrent[AndUnloadsClasses] conflicts"
1854                 " with -UseAsyncConcMarkSweepGC");
1855     status = false;
1856   }
1857 
1858   if (UseG1GC) {
1859     status = status && verify_percentage(InitiatingHeapOccupancyPercent,
1860                                          "InitiatingHeapOccupancyPercent");
1861   }
1862 
1863   status = status && verify_interval(RefDiscoveryPolicy,
1864                                      ReferenceProcessor::DiscoveryPolicyMin,
1865                                      ReferenceProcessor::DiscoveryPolicyMax,
1866                                      "RefDiscoveryPolicy");
1867 
1868   // Limit the lower bound of this flag to 1 as it is used in a division
1869   // expression.
1870   status = status && verify_interval(TLABWasteTargetPercent,
1871                                      1, 100, "TLABWasteTargetPercent");
1872 
1873   status = status && verify_object_alignment();
1874 
1875   return status;
1876 }
1877 
1878 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
1879   const char* option_type) {
1880   if (ignore) return false;
1881 
1882   const char* spacer = " ";
1883   if (option_type == NULL) {
1884     option_type = ++spacer; // Set both to the empty string.
1885   }
1886 
1887   if (os::obsolete_option(option)) {
1888     jio_fprintf(defaultStream::error_stream(),
1889                 "Obsolete %s%soption: %s\n", option_type, spacer,
1890       option->optionString);
1891     return false;
1892   } else {
1893     jio_fprintf(defaultStream::error_stream(),
1894                 "Unrecognized %s%soption: %s\n", option_type, spacer,
1895       option->optionString);
1896     return true;
1897   }
1898 }
1899 
1900 static const char* user_assertion_options[] = {
1901   "-da", "-ea", "-disableassertions", "-enableassertions", 0
1902 };
1903 
1904 static const char* system_assertion_options[] = {
1905   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
1906 };
1907 
1908 // Return true if any of the strings in null-terminated array 'names' matches.
1909 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
1910 // the option must match exactly.
1911 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
1912   bool tail_allowed) {
1913   for (/* empty */; *names != NULL; ++names) {
1914     if (match_option(option, *names, tail)) {
1915       if (**tail == '\0' || tail_allowed && **tail == ':') {
1916         return true;
1917       }
1918     }
1919   }
1920   return false;
1921 }
1922 
1923 bool Arguments::parse_uintx(const char* value,
1924                             uintx* uintx_arg,
1925                             uintx min_size) {
1926 
1927   // Check the sign first since atomull() parses only unsigned values.
1928   bool value_is_positive = !(*value == '-');
1929 
1930   if (value_is_positive) {
1931     julong n;
1932     bool good_return = atomull(value, &n);
1933     if (good_return) {
1934       bool above_minimum = n >= min_size;
1935       bool value_is_too_large = n > max_uintx;
1936 
1937       if (above_minimum && !value_is_too_large) {
1938         *uintx_arg = n;
1939         return true;
1940       }
1941     }
1942   }
1943   return false;
1944 }
1945 
1946 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
1947                                                   julong* long_arg,
1948                                                   julong min_size) {
1949   if (!atomull(s, long_arg)) return arg_unreadable;
1950   return check_memory_size(*long_arg, min_size);
1951 }
1952 
1953 // Parse JavaVMInitArgs structure
1954 
1955 jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {
1956   // For components of the system classpath.
1957   SysClassPath scp(Arguments::get_sysclasspath());
1958   bool scp_assembly_required = false;
1959 
1960   // Save default settings for some mode flags
1961   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
1962   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
1963   Arguments::_ClipInlining             = ClipInlining;
1964   Arguments::_BackgroundCompilation    = BackgroundCompilation;
1965 
1966   // Parse JAVA_TOOL_OPTIONS environment variable (if present)
1967   jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);
1968   if (result != JNI_OK) {
1969     return result;
1970   }
1971 
1972   // Parse JavaVMInitArgs structure passed in
1973   result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, COMMAND_LINE);
1974   if (result != JNI_OK) {
1975     return result;
1976   }
1977 
1978   if (AggressiveOpts) {
1979     // Insert alt-rt.jar between user-specified bootclasspath
1980     // prefix and the default bootclasspath.  os::set_boot_path()
1981     // uses meta_index_dir as the default bootclasspath directory.
1982     const char* altclasses_jar = "alt-rt.jar";
1983     size_t altclasses_path_len = strlen(get_meta_index_dir()) + 1 +
1984                                  strlen(altclasses_jar);
1985     char* altclasses_path = NEW_C_HEAP_ARRAY(char, altclasses_path_len);
1986     strcpy(altclasses_path, get_meta_index_dir());
1987     strcat(altclasses_path, altclasses_jar);
1988     scp.add_suffix_to_prefix(altclasses_path);
1989     scp_assembly_required = true;
1990     FREE_C_HEAP_ARRAY(char, altclasses_path);
1991   }
1992 
1993   // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
1994   result = parse_java_options_environment_variable(&scp, &scp_assembly_required);
1995   if (result != JNI_OK) {
1996     return result;
1997   }
1998 
1999   // Do final processing now that all arguments have been parsed
2000   result = finalize_vm_init_args(&scp, scp_assembly_required);
2001   if (result != JNI_OK) {
2002     return result;
2003   }
2004 
2005   return JNI_OK;
2006 }
2007 
2008 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2009                                        SysClassPath* scp_p,
2010                                        bool* scp_assembly_required_p,
2011                                        FlagValueOrigin origin) {
2012   // Remaining part of option string
2013   const char* tail;
2014 
2015   // iterate over arguments
2016   for (int index = 0; index < args->nOptions; index++) {
2017     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2018 
2019     const JavaVMOption* option = args->options + index;
2020 
2021     if (!match_option(option, "-Djava.class.path", &tail) &&
2022         !match_option(option, "-Dsun.java.command", &tail) &&
2023         !match_option(option, "-Dsun.java.launcher", &tail)) {
2024 
2025         // add all jvm options to the jvm_args string. This string
2026         // is used later to set the java.vm.args PerfData string constant.
2027         // the -Djava.class.path and the -Dsun.java.command options are
2028         // omitted from jvm_args string as each have their own PerfData
2029         // string constant object.
2030         build_jvm_args(option->optionString);
2031     }
2032 
2033     // -verbose:[class/gc/jni]
2034     if (match_option(option, "-verbose", &tail)) {
2035       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2036         FLAG_SET_CMDLINE(bool, TraceClassLoading, true);
2037         FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);
2038       } else if (!strcmp(tail, ":gc")) {
2039         FLAG_SET_CMDLINE(bool, PrintGC, true);
2040       } else if (!strcmp(tail, ":jni")) {
2041         FLAG_SET_CMDLINE(bool, PrintJNIResolving, true);
2042       }
2043     // -da / -ea / -disableassertions / -enableassertions
2044     // These accept an optional class/package name separated by a colon, e.g.,
2045     // -da:java.lang.Thread.
2046     } else if (match_option(option, user_assertion_options, &tail, true)) {
2047       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2048       if (*tail == '\0') {
2049         JavaAssertions::setUserClassDefault(enable);
2050       } else {
2051         assert(*tail == ':', "bogus match by match_option()");
2052         JavaAssertions::addOption(tail + 1, enable);
2053       }
2054     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2055     } else if (match_option(option, system_assertion_options, &tail, false)) {
2056       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2057       JavaAssertions::setSystemClassDefault(enable);
2058     // -bootclasspath:
2059     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2060       scp_p->reset_path(tail);
2061       *scp_assembly_required_p = true;
2062     // -bootclasspath/a:
2063     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2064       scp_p->add_suffix(tail);
2065       *scp_assembly_required_p = true;
2066     // -bootclasspath/p:
2067     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2068       scp_p->add_prefix(tail);
2069       *scp_assembly_required_p = true;
2070     // -Xrun
2071     } else if (match_option(option, "-Xrun", &tail)) {
2072       if (tail != NULL) {
2073         const char* pos = strchr(tail, ':');
2074         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2075         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1), tail, len);
2076         name[len] = '\0';
2077 
2078         char *options = NULL;
2079         if(pos != NULL) {
2080           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2081           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2), pos+1, len2);
2082         }
2083 #ifdef JVMTI_KERNEL
2084         if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
2085           warning("profiling and debugging agents are not supported with Kernel VM");
2086         } else
2087 #endif // JVMTI_KERNEL
2088         add_init_library(name, options);
2089       }
2090     // -agentlib and -agentpath
2091     } else if (match_option(option, "-agentlib:", &tail) ||
2092           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2093       if(tail != NULL) {
2094         const char* pos = strchr(tail, '=');
2095         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2096         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1), tail, len);
2097         name[len] = '\0';
2098 
2099         char *options = NULL;
2100         if(pos != NULL) {
2101           options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(pos + 1) + 1), pos + 1);
2102         }
2103 #ifdef JVMTI_KERNEL
2104         if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
2105           warning("profiling and debugging agents are not supported with Kernel VM");
2106         } else
2107 #endif // JVMTI_KERNEL
2108         add_init_agent(name, options, is_absolute_path);
2109 
2110       }
2111     // -javaagent
2112     } else if (match_option(option, "-javaagent:", &tail)) {
2113       if(tail != NULL) {
2114         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1), tail);
2115         add_init_agent("instrument", options, false);
2116       }
2117     // -Xnoclassgc
2118     } else if (match_option(option, "-Xnoclassgc", &tail)) {
2119       FLAG_SET_CMDLINE(bool, ClassUnloading, false);
2120     // -Xincgc: i-CMS
2121     } else if (match_option(option, "-Xincgc", &tail)) {
2122       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
2123       FLAG_SET_CMDLINE(bool, CMSIncrementalMode, true);
2124     // -Xnoincgc: no i-CMS
2125     } else if (match_option(option, "-Xnoincgc", &tail)) {
2126       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
2127       FLAG_SET_CMDLINE(bool, CMSIncrementalMode, false);
2128     // -Xconcgc
2129     } else if (match_option(option, "-Xconcgc", &tail)) {
2130       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
2131     // -Xnoconcgc
2132     } else if (match_option(option, "-Xnoconcgc", &tail)) {
2133       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
2134     // -Xbatch
2135     } else if (match_option(option, "-Xbatch", &tail)) {
2136       FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2137     // -Xmn for compatibility with other JVM vendors
2138     } else if (match_option(option, "-Xmn", &tail)) {
2139       julong long_initial_eden_size = 0;
2140       ArgsRange errcode = parse_memory_size(tail, &long_initial_eden_size, 1);
2141       if (errcode != arg_in_range) {
2142         jio_fprintf(defaultStream::error_stream(),
2143                     "Invalid initial eden size: %s\n", option->optionString);
2144         describe_range_error(errcode);
2145         return JNI_EINVAL;
2146       }
2147       FLAG_SET_CMDLINE(uintx, MaxNewSize, (uintx)long_initial_eden_size);
2148       FLAG_SET_CMDLINE(uintx, NewSize, (uintx)long_initial_eden_size);
2149     // -Xms
2150     } else if (match_option(option, "-Xms", &tail)) {
2151       julong long_initial_heap_size = 0;
2152       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 1);
2153       if (errcode != arg_in_range) {
2154         jio_fprintf(defaultStream::error_stream(),
2155                     "Invalid initial heap size: %s\n", option->optionString);
2156         describe_range_error(errcode);
2157         return JNI_EINVAL;
2158       }
2159       FLAG_SET_CMDLINE(uintx, InitialHeapSize, (uintx)long_initial_heap_size);
2160       // Currently the minimum size and the initial heap sizes are the same.
2161       set_min_heap_size(InitialHeapSize);
2162     // -Xmx
2163     } else if (match_option(option, "-Xmx", &tail)) {
2164       julong long_max_heap_size = 0;
2165       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2166       if (errcode != arg_in_range) {
2167         jio_fprintf(defaultStream::error_stream(),
2168                     "Invalid maximum heap size: %s\n", option->optionString);
2169         describe_range_error(errcode);
2170         return JNI_EINVAL;
2171       }
2172       FLAG_SET_CMDLINE(uintx, MaxHeapSize, (uintx)long_max_heap_size);
2173     // Xmaxf
2174     } else if (match_option(option, "-Xmaxf", &tail)) {
2175       int maxf = (int)(atof(tail) * 100);
2176       if (maxf < 0 || maxf > 100) {
2177         jio_fprintf(defaultStream::error_stream(),
2178                     "Bad max heap free percentage size: %s\n",
2179                     option->optionString);
2180         return JNI_EINVAL;
2181       } else {
2182         FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf);
2183       }
2184     // Xminf
2185     } else if (match_option(option, "-Xminf", &tail)) {
2186       int minf = (int)(atof(tail) * 100);
2187       if (minf < 0 || minf > 100) {
2188         jio_fprintf(defaultStream::error_stream(),
2189                     "Bad min heap free percentage size: %s\n",
2190                     option->optionString);
2191         return JNI_EINVAL;
2192       } else {
2193         FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf);
2194       }
2195     // -Xss
2196     } else if (match_option(option, "-Xss", &tail)) {
2197       julong long_ThreadStackSize = 0;
2198       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2199       if (errcode != arg_in_range) {
2200         jio_fprintf(defaultStream::error_stream(),
2201                     "Invalid thread stack size: %s\n", option->optionString);
2202         describe_range_error(errcode);
2203         return JNI_EINVAL;
2204       }
2205       // Internally track ThreadStackSize in units of 1024 bytes.
2206       FLAG_SET_CMDLINE(intx, ThreadStackSize,
2207                               round_to((int)long_ThreadStackSize, K) / K);
2208     // -Xoss
2209     } else if (match_option(option, "-Xoss", &tail)) {
2210           // HotSpot does not have separate native and Java stacks, ignore silently for compatibility
2211     // -Xmaxjitcodesize
2212     } else if (match_option(option, "-Xmaxjitcodesize", &tail)) {
2213       julong long_ReservedCodeCacheSize = 0;
2214       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize,
2215                                             (size_t)InitialCodeCacheSize);
2216       if (errcode != arg_in_range) {
2217         jio_fprintf(defaultStream::error_stream(),
2218                     "Invalid maximum code cache size: %s\n",
2219                     option->optionString);
2220         describe_range_error(errcode);
2221         return JNI_EINVAL;
2222       }
2223       FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize);
2224     // -green
2225     } else if (match_option(option, "-green", &tail)) {
2226       jio_fprintf(defaultStream::error_stream(),
2227                   "Green threads support not available\n");
2228           return JNI_EINVAL;
2229     // -native
2230     } else if (match_option(option, "-native", &tail)) {
2231           // HotSpot always uses native threads, ignore silently for compatibility
2232     // -Xsqnopause
2233     } else if (match_option(option, "-Xsqnopause", &tail)) {
2234           // EVM option, ignore silently for compatibility
2235     // -Xrs
2236     } else if (match_option(option, "-Xrs", &tail)) {
2237           // Classic/EVM option, new functionality
2238       FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true);
2239     } else if (match_option(option, "-Xusealtsigs", &tail)) {
2240           // change default internal VM signals used - lower case for back compat
2241       FLAG_SET_CMDLINE(bool, UseAltSigs, true);
2242     // -Xoptimize
2243     } else if (match_option(option, "-Xoptimize", &tail)) {
2244           // EVM option, ignore silently for compatibility
2245     // -Xprof
2246     } else if (match_option(option, "-Xprof", &tail)) {
2247 #ifndef FPROF_KERNEL
2248       _has_profile = true;
2249 #else // FPROF_KERNEL
2250       // do we have to exit?
2251       warning("Kernel VM does not support flat profiling.");
2252 #endif // FPROF_KERNEL
2253     // -Xaprof
2254     } else if (match_option(option, "-Xaprof", &tail)) {
2255       _has_alloc_profile = true;
2256     // -Xconcurrentio
2257     } else if (match_option(option, "-Xconcurrentio", &tail)) {
2258       FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true);
2259       FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2260       FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1);
2261       FLAG_SET_CMDLINE(bool, UseTLAB, false);
2262       FLAG_SET_CMDLINE(uintx, NewSizeThreadIncrease, 16 * K);  // 20Kb per thread added to new generation
2263 
2264       // -Xinternalversion
2265     } else if (match_option(option, "-Xinternalversion", &tail)) {
2266       jio_fprintf(defaultStream::output_stream(), "%s\n",
2267                   VM_Version::internal_vm_info_string());
2268       vm_exit(0);
2269 #ifndef PRODUCT
2270     // -Xprintflags
2271     } else if (match_option(option, "-Xprintflags", &tail)) {
2272       CommandLineFlags::printFlags();
2273       vm_exit(0);
2274 #endif
2275     // -D
2276     } else if (match_option(option, "-D", &tail)) {
2277       if (!add_property(tail)) {
2278         return JNI_ENOMEM;
2279       }
2280       // Out of the box management support
2281       if (match_option(option, "-Dcom.sun.management", &tail)) {
2282         FLAG_SET_CMDLINE(bool, ManagementServer, true);
2283       }
2284     // -Xint
2285     } else if (match_option(option, "-Xint", &tail)) {
2286           set_mode_flags(_int);
2287     // -Xmixed
2288     } else if (match_option(option, "-Xmixed", &tail)) {
2289           set_mode_flags(_mixed);
2290     // -Xcomp
2291     } else if (match_option(option, "-Xcomp", &tail)) {
2292       // for testing the compiler; turn off all flags that inhibit compilation
2293           set_mode_flags(_comp);
2294 
2295     // -Xshare:dump
2296     } else if (match_option(option, "-Xshare:dump", &tail)) {
2297 #ifdef TIERED
2298       FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);
2299       set_mode_flags(_int);     // Prevent compilation, which creates objects
2300 #elif defined(COMPILER2)
2301       vm_exit_during_initialization(
2302           "Dumping a shared archive is not supported on the Server JVM.", NULL);
2303 #elif defined(KERNEL)
2304       vm_exit_during_initialization(
2305           "Dumping a shared archive is not supported on the Kernel JVM.", NULL);
2306 #else
2307       FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);
2308       set_mode_flags(_int);     // Prevent compilation, which creates objects
2309 #endif
2310     // -Xshare:on
2311     } else if (match_option(option, "-Xshare:on", &tail)) {
2312       FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
2313       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
2314 #ifdef TIERED
2315       FLAG_SET_CMDLINE(bool, ForceSharedSpaces, true);
2316 #endif // TIERED
2317     // -Xshare:auto
2318     } else if (match_option(option, "-Xshare:auto", &tail)) {
2319       FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
2320       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
2321     // -Xshare:off
2322     } else if (match_option(option, "-Xshare:off", &tail)) {
2323       FLAG_SET_CMDLINE(bool, UseSharedSpaces, false);
2324       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
2325 
2326     // -Xverify
2327     } else if (match_option(option, "-Xverify", &tail)) {
2328       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
2329         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true);
2330         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
2331       } else if (strcmp(tail, ":remote") == 0) {
2332         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
2333         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
2334       } else if (strcmp(tail, ":none") == 0) {
2335         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
2336         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false);
2337       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
2338         return JNI_EINVAL;
2339       }
2340     // -Xdebug
2341     } else if (match_option(option, "-Xdebug", &tail)) {
2342       // note this flag has been used, then ignore
2343       set_xdebug_mode(true);
2344     // -Xnoagent
2345     } else if (match_option(option, "-Xnoagent", &tail)) {
2346       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
2347     } else if (match_option(option, "-Xboundthreads", &tail)) {
2348       // Bind user level threads to kernel threads (Solaris only)
2349       FLAG_SET_CMDLINE(bool, UseBoundThreads, true);
2350     } else if (match_option(option, "-Xloggc:", &tail)) {
2351       // Redirect GC output to the file. -Xloggc:<filename>
2352       // ostream_init_log(), when called will use this filename
2353       // to initialize a fileStream.
2354       _gc_log_filename = strdup(tail);
2355       FLAG_SET_CMDLINE(bool, PrintGC, true);
2356       FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true);
2357       FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);
2358 
2359     // JNI hooks
2360     } else if (match_option(option, "-Xcheck", &tail)) {
2361       if (!strcmp(tail, ":jni")) {
2362         CheckJNICalls = true;
2363       } else if (is_bad_option(option, args->ignoreUnrecognized,
2364                                      "check")) {
2365         return JNI_EINVAL;
2366       }
2367     } else if (match_option(option, "vfprintf", &tail)) {
2368       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
2369     } else if (match_option(option, "exit", &tail)) {
2370       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
2371     } else if (match_option(option, "abort", &tail)) {
2372       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
2373     // -XX:+AggressiveHeap
2374     } else if (match_option(option, "-XX:+AggressiveHeap", &tail)) {
2375 
2376       // This option inspects the machine and attempts to set various
2377       // parameters to be optimal for long-running, memory allocation
2378       // intensive jobs.  It is intended for machines with large
2379       // amounts of cpu and memory.
2380 
2381       // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
2382       // VM, but we may not be able to represent the total physical memory
2383       // available (like having 8gb of memory on a box but using a 32bit VM).
2384       // Thus, we need to make sure we're using a julong for intermediate
2385       // calculations.
2386       julong initHeapSize;
2387       julong total_memory = os::physical_memory();
2388 
2389       if (total_memory < (julong)256*M) {
2390         jio_fprintf(defaultStream::error_stream(),
2391                     "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
2392         vm_exit(1);
2393       }
2394 
2395       // The heap size is half of available memory, or (at most)
2396       // all of possible memory less 160mb (leaving room for the OS
2397       // when using ISM).  This is the maximum; because adaptive sizing
2398       // is turned on below, the actual space used may be smaller.
2399 
2400       initHeapSize = MIN2(total_memory / (julong)2,
2401                           total_memory - (julong)160*M);
2402 
2403       // Make sure that if we have a lot of memory we cap the 32 bit
2404       // process space.  The 64bit VM version of this function is a nop.
2405       initHeapSize = os::allocatable_physical_memory(initHeapSize);
2406 
2407       // The perm gen is separate but contiguous with the
2408       // object heap (and is reserved with it) so subtract it
2409       // from the heap size.
2410       if (initHeapSize > MaxPermSize) {
2411         initHeapSize = initHeapSize - MaxPermSize;
2412       } else {
2413         warning("AggressiveHeap and MaxPermSize values may conflict");
2414       }
2415 
2416       if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2417          FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);
2418          FLAG_SET_CMDLINE(uintx, InitialHeapSize, initHeapSize);
2419          // Currently the minimum size and the initial heap sizes are the same.
2420          set_min_heap_size(initHeapSize);
2421       }
2422       if (FLAG_IS_DEFAULT(NewSize)) {
2423          // Make the young generation 3/8ths of the total heap.
2424          FLAG_SET_CMDLINE(uintx, NewSize,
2425                                 ((julong)MaxHeapSize / (julong)8) * (julong)3);
2426          FLAG_SET_CMDLINE(uintx, MaxNewSize, NewSize);
2427       }
2428 
2429       FLAG_SET_DEFAULT(UseLargePages, true);
2430 
2431       // Increase some data structure sizes for efficiency
2432       FLAG_SET_CMDLINE(uintx, BaseFootPrintEstimate, MaxHeapSize);
2433       FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
2434       FLAG_SET_CMDLINE(uintx, TLABSize, 256*K);
2435 
2436       // See the OldPLABSize comment below, but replace 'after promotion'
2437       // with 'after copying'.  YoungPLABSize is the size of the survivor
2438       // space per-gc-thread buffers.  The default is 4kw.
2439       FLAG_SET_CMDLINE(uintx, YoungPLABSize, 256*K);      // Note: this is in words
2440 
2441       // OldPLABSize is the size of the buffers in the old gen that
2442       // UseParallelGC uses to promote live data that doesn't fit in the
2443       // survivor spaces.  At any given time, there's one for each gc thread.
2444       // The default size is 1kw. These buffers are rarely used, since the
2445       // survivor spaces are usually big enough.  For specjbb, however, there
2446       // are occasions when there's lots of live data in the young gen
2447       // and we end up promoting some of it.  We don't have a definite
2448       // explanation for why bumping OldPLABSize helps, but the theory
2449       // is that a bigger PLAB results in retaining something like the
2450       // original allocation order after promotion, which improves mutator
2451       // locality.  A minor effect may be that larger PLABs reduce the
2452       // number of PLAB allocation events during gc.  The value of 8kw
2453       // was arrived at by experimenting with specjbb.
2454       FLAG_SET_CMDLINE(uintx, OldPLABSize, 8*K);  // Note: this is in words
2455 
2456       // CompilationPolicyChoice=0 causes the server compiler to adopt
2457       // a more conservative which-method-do-I-compile policy when one
2458       // of the counters maintained by the interpreter trips.  The
2459       // result is reduced startup time and improved specjbb and
2460       // alacrity performance.  Zero is the default, but we set it
2461       // explicitly here in case the default changes.
2462       // See runtime/compilationPolicy.*.
2463       FLAG_SET_CMDLINE(intx, CompilationPolicyChoice, 0);
2464 
2465       // Enable parallel GC and adaptive generation sizing
2466       FLAG_SET_CMDLINE(bool, UseParallelGC, true);
2467       FLAG_SET_DEFAULT(ParallelGCThreads,
2468                        Abstract_VM_Version::parallel_worker_threads());
2469 
2470       // Encourage steady state memory management
2471       FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);
2472 
2473       // This appears to improve mutator locality
2474       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
2475 
2476       // Get around early Solaris scheduling bug
2477       // (affinity vs other jobs on system)
2478       // but disallow DR and offlining (5008695).
2479       FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);
2480 
2481     } else if (match_option(option, "-XX:+NeverTenure", &tail)) {
2482       // The last option must always win.
2483       FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
2484       FLAG_SET_CMDLINE(bool, NeverTenure, true);
2485     } else if (match_option(option, "-XX:+AlwaysTenure", &tail)) {
2486       // The last option must always win.
2487       FLAG_SET_CMDLINE(bool, NeverTenure, false);
2488       FLAG_SET_CMDLINE(bool, AlwaysTenure, true);
2489     } else if (match_option(option, "-XX:+CMSPermGenSweepingEnabled", &tail) ||
2490                match_option(option, "-XX:-CMSPermGenSweepingEnabled", &tail)) {
2491       jio_fprintf(defaultStream::error_stream(),
2492         "Please use CMSClassUnloadingEnabled in place of "
2493         "CMSPermGenSweepingEnabled in the future\n");
2494     } else if (match_option(option, "-XX:+UseGCTimeLimit", &tail)) {
2495       FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, true);
2496       jio_fprintf(defaultStream::error_stream(),
2497         "Please use -XX:+UseGCOverheadLimit in place of "
2498         "-XX:+UseGCTimeLimit in the future\n");
2499     } else if (match_option(option, "-XX:-UseGCTimeLimit", &tail)) {
2500       FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, false);
2501       jio_fprintf(defaultStream::error_stream(),
2502         "Please use -XX:-UseGCOverheadLimit in place of "
2503         "-XX:-UseGCTimeLimit in the future\n");
2504     // The TLE options are for compatibility with 1.3 and will be
2505     // removed without notice in a future release.  These options
2506     // are not to be documented.
2507     } else if (match_option(option, "-XX:MaxTLERatio=", &tail)) {
2508       // No longer used.
2509     } else if (match_option(option, "-XX:+ResizeTLE", &tail)) {
2510       FLAG_SET_CMDLINE(bool, ResizeTLAB, true);
2511     } else if (match_option(option, "-XX:-ResizeTLE", &tail)) {
2512       FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
2513     } else if (match_option(option, "-XX:+PrintTLE", &tail)) {
2514       FLAG_SET_CMDLINE(bool, PrintTLAB, true);
2515     } else if (match_option(option, "-XX:-PrintTLE", &tail)) {
2516       FLAG_SET_CMDLINE(bool, PrintTLAB, false);
2517     } else if (match_option(option, "-XX:TLEFragmentationRatio=", &tail)) {
2518       // No longer used.
2519     } else if (match_option(option, "-XX:TLESize=", &tail)) {
2520       julong long_tlab_size = 0;
2521       ArgsRange errcode = parse_memory_size(tail, &long_tlab_size, 1);
2522       if (errcode != arg_in_range) {
2523         jio_fprintf(defaultStream::error_stream(),
2524                     "Invalid TLAB size: %s\n", option->optionString);
2525         describe_range_error(errcode);
2526         return JNI_EINVAL;
2527       }
2528       FLAG_SET_CMDLINE(uintx, TLABSize, long_tlab_size);
2529     } else if (match_option(option, "-XX:TLEThreadRatio=", &tail)) {
2530       // No longer used.
2531     } else if (match_option(option, "-XX:+UseTLE", &tail)) {
2532       FLAG_SET_CMDLINE(bool, UseTLAB, true);
2533     } else if (match_option(option, "-XX:-UseTLE", &tail)) {
2534       FLAG_SET_CMDLINE(bool, UseTLAB, false);
2535 SOLARIS_ONLY(
2536     } else if (match_option(option, "-XX:+UsePermISM", &tail)) {
2537       warning("-XX:+UsePermISM is obsolete.");
2538       FLAG_SET_CMDLINE(bool, UseISM, true);
2539     } else if (match_option(option, "-XX:-UsePermISM", &tail)) {
2540       FLAG_SET_CMDLINE(bool, UseISM, false);
2541 )
2542     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr", &tail)) {
2543       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false);
2544       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true);
2545     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout", &tail)) {
2546       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false);
2547       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true);
2548     } else if (match_option(option, "-XX:+ExtendedDTraceProbes", &tail)) {
2549 #ifdef SOLARIS
2550       FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true);
2551       FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true);
2552       FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true);
2553       FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true);
2554 #else // ndef SOLARIS
2555       jio_fprintf(defaultStream::error_stream(),
2556                   "ExtendedDTraceProbes flag is only applicable on Solaris\n");
2557       return JNI_EINVAL;
2558 #endif // ndef SOLARIS
2559 #ifdef ASSERT
2560     } else if (match_option(option, "-XX:+FullGCALot", &tail)) {
2561       FLAG_SET_CMDLINE(bool, FullGCALot, true);
2562       // disable scavenge before parallel mark-compact
2563       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
2564 #endif
2565     } else if (match_option(option, "-XX:CMSParPromoteBlocksToClaim=", &tail)) {
2566       julong cms_blocks_to_claim = (julong)atol(tail);
2567       FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);
2568       jio_fprintf(defaultStream::error_stream(),
2569         "Please use -XX:OldPLABSize in place of "
2570         "-XX:CMSParPromoteBlocksToClaim in the future\n");
2571     } else if (match_option(option, "-XX:ParCMSPromoteBlocksToClaim=", &tail)) {
2572       julong cms_blocks_to_claim = (julong)atol(tail);
2573       FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);
2574       jio_fprintf(defaultStream::error_stream(),
2575         "Please use -XX:OldPLABSize in place of "
2576         "-XX:ParCMSPromoteBlocksToClaim in the future\n");
2577     } else if (match_option(option, "-XX:ParallelGCOldGenAllocBufferSize=", &tail)) {
2578       julong old_plab_size = 0;
2579       ArgsRange errcode = parse_memory_size(tail, &old_plab_size, 1);
2580       if (errcode != arg_in_range) {
2581         jio_fprintf(defaultStream::error_stream(),
2582                     "Invalid old PLAB size: %s\n", option->optionString);
2583         describe_range_error(errcode);
2584         return JNI_EINVAL;
2585       }
2586       FLAG_SET_CMDLINE(uintx, OldPLABSize, old_plab_size);
2587       jio_fprintf(defaultStream::error_stream(),
2588                   "Please use -XX:OldPLABSize in place of "
2589                   "-XX:ParallelGCOldGenAllocBufferSize in the future\n");
2590     } else if (match_option(option, "-XX:ParallelGCToSpaceAllocBufferSize=", &tail)) {
2591       julong young_plab_size = 0;
2592       ArgsRange errcode = parse_memory_size(tail, &young_plab_size, 1);
2593       if (errcode != arg_in_range) {
2594         jio_fprintf(defaultStream::error_stream(),
2595                     "Invalid young PLAB size: %s\n", option->optionString);
2596         describe_range_error(errcode);
2597         return JNI_EINVAL;
2598       }
2599       FLAG_SET_CMDLINE(uintx, YoungPLABSize, young_plab_size);
2600       jio_fprintf(defaultStream::error_stream(),
2601                   "Please use -XX:YoungPLABSize in place of "
2602                   "-XX:ParallelGCToSpaceAllocBufferSize in the future\n");
2603     } else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||
2604                match_option(option, "-XX:G1MarkStackSize=", &tail)) {
2605       julong stack_size = 0;
2606       ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);
2607       if (errcode != arg_in_range) {
2608         jio_fprintf(defaultStream::error_stream(),
2609                     "Invalid mark stack size: %s\n", option->optionString);
2610         describe_range_error(errcode);
2611         return JNI_EINVAL;
2612       }
2613       FLAG_SET_CMDLINE(uintx, MarkStackSize, stack_size);
2614     } else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {
2615       julong max_stack_size = 0;
2616       ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);
2617       if (errcode != arg_in_range) {
2618         jio_fprintf(defaultStream::error_stream(),
2619                     "Invalid maximum mark stack size: %s\n",
2620                     option->optionString);
2621         describe_range_error(errcode);
2622         return JNI_EINVAL;
2623       }
2624       FLAG_SET_CMDLINE(uintx, MarkStackSizeMax, max_stack_size);
2625     } else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||
2626                match_option(option, "-XX:ParallelCMSThreads=", &tail)) {
2627       uintx conc_threads = 0;
2628       if (!parse_uintx(tail, &conc_threads, 1)) {
2629         jio_fprintf(defaultStream::error_stream(),
2630                     "Invalid concurrent threads: %s\n", option->optionString);
2631         return JNI_EINVAL;
2632       }
2633       FLAG_SET_CMDLINE(uintx, ConcGCThreads, conc_threads);
2634     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
2635       // Skip -XX:Flags= since that case has already been handled
2636       if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
2637         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
2638           return JNI_EINVAL;
2639         }
2640       }
2641     // Unknown option
2642     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
2643       return JNI_ERR;
2644     }
2645   }
2646   // Change the default value for flags  which have different default values
2647   // when working with older JDKs.
2648   if (JDK_Version::current().compare_major(6) <= 0 &&
2649       FLAG_IS_DEFAULT(UseVMInterruptibleIO)) {
2650     FLAG_SET_DEFAULT(UseVMInterruptibleIO, true);
2651   }
2652 #ifdef LINUX
2653  if (JDK_Version::current().compare_major(6) <= 0 &&
2654       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
2655     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
2656   }
2657 #endif // LINUX
2658   return JNI_OK;
2659 }
2660 
2661 jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
2662   // This must be done after all -D arguments have been processed.
2663   scp_p->expand_endorsed();
2664 
2665   if (scp_assembly_required || scp_p->get_endorsed() != NULL) {
2666     // Assemble the bootclasspath elements into the final path.
2667     Arguments::set_sysclasspath(scp_p->combined_path());
2668   }
2669 
2670   // This must be done after all arguments have been processed.
2671   // java_compiler() true means set to "NONE" or empty.
2672   if (java_compiler() && !xdebug_mode()) {
2673     // For backwards compatibility, we switch to interpreted mode if
2674     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
2675     // not specified.
2676     set_mode_flags(_int);
2677   }
2678   if (CompileThreshold == 0) {
2679     set_mode_flags(_int);
2680   }
2681 
2682 #ifndef COMPILER2
2683   // Don't degrade server performance for footprint
2684   if (FLAG_IS_DEFAULT(UseLargePages) &&
2685       MaxHeapSize < LargePageHeapSizeThreshold) {
2686     // No need for large granularity pages w/small heaps.
2687     // Note that large pages are enabled/disabled for both the
2688     // Java heap and the code cache.
2689     FLAG_SET_DEFAULT(UseLargePages, false);
2690     SOLARIS_ONLY(FLAG_SET_DEFAULT(UseMPSS, false));
2691     SOLARIS_ONLY(FLAG_SET_DEFAULT(UseISM, false));
2692   }
2693 
2694   // Tiered compilation is undefined with C1.
2695   TieredCompilation = false;
2696 #else
2697   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
2698     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
2699   }
2700   // Temporary disable bulk zeroing reduction with G1. See CR 6627983.
2701   if (UseG1GC) {
2702     FLAG_SET_DEFAULT(ReduceBulkZeroing, false);
2703   }
2704 #endif
2705 
2706   // If we are running in a headless jre, force java.awt.headless property
2707   // to be true unless the property has already been set.
2708   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
2709   if (os::is_headless_jre()) {
2710     const char* headless = Arguments::get_property("java.awt.headless");
2711     if (headless == NULL) {
2712       char envbuffer[128];
2713       if (!os::getenv("JAVA_AWT_HEADLESS", envbuffer, sizeof(envbuffer))) {
2714         if (!add_property("java.awt.headless=true")) {
2715           return JNI_ENOMEM;
2716         }
2717       } else {
2718         char buffer[256];
2719         strcpy(buffer, "java.awt.headless=");
2720         strcat(buffer, envbuffer);
2721         if (!add_property(buffer)) {
2722           return JNI_ENOMEM;
2723         }
2724       }
2725     }
2726   }
2727 
2728   if (!check_vm_args_consistency()) {
2729     return JNI_ERR;
2730   }
2731 
2732   return JNI_OK;
2733 }
2734 
2735 jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
2736   return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,
2737                                             scp_assembly_required_p);
2738 }
2739 
2740 jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
2741   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,
2742                                             scp_assembly_required_p);
2743 }
2744 
2745 jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {
2746   const int N_MAX_OPTIONS = 64;
2747   const int OPTION_BUFFER_SIZE = 1024;
2748   char buffer[OPTION_BUFFER_SIZE];
2749 
2750   // The variable will be ignored if it exceeds the length of the buffer.
2751   // Don't check this variable if user has special privileges
2752   // (e.g. unix su command).
2753   if (os::getenv(name, buffer, sizeof(buffer)) &&
2754       !os::have_special_privileges()) {
2755     JavaVMOption options[N_MAX_OPTIONS];      // Construct option array
2756     jio_fprintf(defaultStream::error_stream(),
2757                 "Picked up %s: %s\n", name, buffer);
2758     char* rd = buffer;                        // pointer to the input string (rd)
2759     int i;
2760     for (i = 0; i < N_MAX_OPTIONS;) {         // repeat for all options in the input string
2761       while (isspace(*rd)) rd++;              // skip whitespace
2762       if (*rd == 0) break;                    // we re done when the input string is read completely
2763 
2764       // The output, option string, overwrites the input string.
2765       // Because of quoting, the pointer to the option string (wrt) may lag the pointer to
2766       // input string (rd).
2767       char* wrt = rd;
2768 
2769       options[i++].optionString = wrt;        // Fill in option
2770       while (*rd != 0 && !isspace(*rd)) {     // unquoted strings terminate with a space or NULL
2771         if (*rd == '\'' || *rd == '"') {      // handle a quoted string
2772           int quote = *rd;                    // matching quote to look for
2773           rd++;                               // don't copy open quote
2774           while (*rd != quote) {              // include everything (even spaces) up until quote
2775             if (*rd == 0) {                   // string termination means unmatched string
2776               jio_fprintf(defaultStream::error_stream(),
2777                           "Unmatched quote in %s\n", name);
2778               return JNI_ERR;
2779             }
2780             *wrt++ = *rd++;                   // copy to option string
2781           }
2782           rd++;                               // don't copy close quote
2783         } else {
2784           *wrt++ = *rd++;                     // copy to option string
2785         }
2786       }
2787       // Need to check if we're done before writing a NULL,
2788       // because the write could be to the byte that rd is pointing to.
2789       if (*rd++ == 0) {
2790         *wrt = 0;
2791         break;
2792       }
2793       *wrt = 0;                               // Zero terminate option
2794     }
2795     // Construct JavaVMInitArgs structure and parse as if it was part of the command line
2796     JavaVMInitArgs vm_args;
2797     vm_args.version = JNI_VERSION_1_2;
2798     vm_args.options = options;
2799     vm_args.nOptions = i;
2800     vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
2801 
2802     if (PrintVMOptions) {
2803       const char* tail;
2804       for (int i = 0; i < vm_args.nOptions; i++) {
2805         const JavaVMOption *option = vm_args.options + i;
2806         if (match_option(option, "-XX:", &tail)) {
2807           logOption(tail);
2808         }
2809       }
2810     }
2811 
2812     return(parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p, ENVIRON_VAR));
2813   }
2814   return JNI_OK;
2815 }
2816 
2817 // Parse entry point called from JNI_CreateJavaVM
2818 
2819 jint Arguments::parse(const JavaVMInitArgs* args) {
2820 
2821   // Sharing support
2822   // Construct the path to the archive
2823   char jvm_path[JVM_MAXPATHLEN];
2824   os::jvm_path(jvm_path, sizeof(jvm_path));
2825 #ifdef TIERED
2826   if (strstr(jvm_path, "client") != NULL) {
2827     force_client_mode = true;
2828   }
2829 #endif // TIERED
2830   char *end = strrchr(jvm_path, *os::file_separator());
2831   if (end != NULL) *end = '\0';
2832   char *shared_archive_path = NEW_C_HEAP_ARRAY(char, strlen(jvm_path) +
2833                                         strlen(os::file_separator()) + 20);
2834   if (shared_archive_path == NULL) return JNI_ENOMEM;
2835   strcpy(shared_archive_path, jvm_path);
2836   strcat(shared_archive_path, os::file_separator());
2837   strcat(shared_archive_path, "classes");
2838   DEBUG_ONLY(strcat(shared_archive_path, "_g");)
2839   strcat(shared_archive_path, ".jsa");
2840   SharedArchivePath = shared_archive_path;
2841 
2842   // Remaining part of option string
2843   const char* tail;
2844 
2845   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
2846   bool settings_file_specified = false;
2847   const char* flags_file;
2848   int index;
2849   for (index = 0; index < args->nOptions; index++) {
2850     const JavaVMOption *option = args->options + index;
2851     if (match_option(option, "-XX:Flags=", &tail)) {
2852       flags_file = tail;
2853       settings_file_specified = true;
2854     }
2855     if (match_option(option, "-XX:+PrintVMOptions", &tail)) {
2856       PrintVMOptions = true;
2857     }
2858     if (match_option(option, "-XX:-PrintVMOptions", &tail)) {
2859       PrintVMOptions = false;
2860     }
2861     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions", &tail)) {
2862       IgnoreUnrecognizedVMOptions = true;
2863     }
2864     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions", &tail)) {
2865       IgnoreUnrecognizedVMOptions = false;
2866     }
2867     if (match_option(option, "-XX:+PrintFlagsInitial", &tail)) {
2868       CommandLineFlags::printFlags();
2869       vm_exit(0);
2870     }
2871 
2872 #ifndef PRODUCT
2873     if (match_option(option, "-XX:+PrintFlagsWithComments", &tail)) {
2874       CommandLineFlags::printFlags(true);
2875       vm_exit(0);
2876     }
2877 #endif
2878   }
2879 
2880   if (IgnoreUnrecognizedVMOptions) {
2881     // uncast const to modify the flag args->ignoreUnrecognized
2882     *(jboolean*)(&args->ignoreUnrecognized) = true;
2883   }
2884 
2885   // Parse specified settings file
2886   if (settings_file_specified) {
2887     if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
2888       return JNI_EINVAL;
2889     }
2890   }
2891 
2892   // Parse default .hotspotrc settings file
2893   if (!settings_file_specified) {
2894     if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
2895       return JNI_EINVAL;
2896     }
2897   }
2898 
2899   if (PrintVMOptions) {
2900     for (index = 0; index < args->nOptions; index++) {
2901       const JavaVMOption *option = args->options + index;
2902       if (match_option(option, "-XX:", &tail)) {
2903         logOption(tail);
2904       }
2905     }
2906   }
2907 
2908   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
2909   jint result = parse_vm_init_args(args);
2910   if (result != JNI_OK) {
2911     return result;
2912   }
2913 
2914 #ifndef PRODUCT
2915   if (TraceBytecodesAt != 0) {
2916     TraceBytecodes = true;
2917   }
2918   if (CountCompiledCalls) {
2919     if (UseCounterDecay) {
2920       warning("UseCounterDecay disabled because CountCalls is set");
2921       UseCounterDecay = false;
2922     }
2923   }
2924 #endif // PRODUCT
2925 
2926   if (EnableInvokeDynamic && !EnableMethodHandles) {
2927     if (!FLAG_IS_DEFAULT(EnableMethodHandles)) {
2928       warning("forcing EnableMethodHandles true because EnableInvokeDynamic is true");
2929     }
2930     EnableMethodHandles = true;
2931   }
2932   if (EnableMethodHandles && !AnonymousClasses) {
2933     if (!FLAG_IS_DEFAULT(AnonymousClasses)) {
2934       warning("forcing AnonymousClasses true because EnableMethodHandles is true");
2935     }
2936     AnonymousClasses = true;
2937   }
2938   if ((EnableMethodHandles || AnonymousClasses) && ScavengeRootsInCode == 0) {
2939     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
2940       warning("forcing ScavengeRootsInCode non-zero because EnableMethodHandles or AnonymousClasses is true");
2941     }
2942     ScavengeRootsInCode = 1;
2943   }
2944 #ifdef COMPILER2
2945   if (EnableInvokeDynamic && DoEscapeAnalysis) {
2946     // TODO: We need to find rules for invokedynamic and EA.  For now,
2947     // simply disable EA by default.
2948     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
2949       DoEscapeAnalysis = false;
2950     }
2951   }
2952 #endif
2953 
2954   if (PrintGCDetails) {
2955     // Turn on -verbose:gc options as well
2956     PrintGC = true;
2957   }
2958 
2959 #if defined(_LP64) && defined(COMPILER1) && !defined(TIERED)
2960   UseCompressedOops = false;
2961 #endif
2962 
2963   // Set object alignment values.
2964   set_object_alignment();
2965 
2966 #ifdef SERIALGC
2967   force_serial_gc();
2968 #endif // SERIALGC
2969 #ifdef KERNEL
2970   no_shared_spaces();
2971 #endif // KERNEL
2972 
2973   // Set flags based on ergonomics.
2974   set_ergonomics_flags();
2975 
2976 #ifdef _LP64
2977   // XXX JSR 292 currently does not support compressed oops.
2978   if (EnableMethodHandles && UseCompressedOops) {
2979     if (FLAG_IS_DEFAULT(UseCompressedOops) || FLAG_IS_ERGO(UseCompressedOops)) {
2980       UseCompressedOops = false;
2981     }
2982   }
2983 #endif // _LP64
2984 
2985   // Check the GC selections again.
2986   if (!check_gc_consistency()) {
2987     return JNI_EINVAL;
2988   }
2989 
2990   if (TieredCompilation) {
2991     set_tiered_flags();
2992   } else {
2993     // Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup.
2994     if (CompilationPolicyChoice >= 2) {
2995       vm_exit_during_initialization(
2996         "Incompatible compilation policy selected", NULL);
2997     }
2998   }
2999 
3000 #ifndef KERNEL
3001   if (UseConcMarkSweepGC) {
3002     // Set flags for CMS and ParNew.  Check UseConcMarkSweep first
3003     // to ensure that when both UseConcMarkSweepGC and UseParNewGC
3004     // are true, we don't call set_parnew_gc_flags() as well.
3005     set_cms_and_parnew_gc_flags();
3006   } else {
3007     // Set heap size based on available physical memory
3008     set_heap_size();
3009     // Set per-collector flags
3010     if (UseParallelGC || UseParallelOldGC) {
3011       set_parallel_gc_flags();
3012     } else if (UseParNewGC) {
3013       set_parnew_gc_flags();
3014     } else if (UseG1GC) {
3015       set_g1_gc_flags();
3016     }
3017   }
3018 #endif // KERNEL
3019 
3020 #ifdef SERIALGC
3021   assert(verify_serial_gc_flags(), "SerialGC unset");
3022 #endif // SERIALGC
3023 
3024   // Set bytecode rewriting flags
3025   set_bytecode_flags();
3026 
3027   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled.
3028   set_aggressive_opts_flags();
3029 
3030 #ifdef CC_INTERP
3031   // Clear flags not supported by the C++ interpreter
3032   FLAG_SET_DEFAULT(ProfileInterpreter, false);
3033   FLAG_SET_DEFAULT(UseBiasedLocking, false);
3034   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
3035 #endif // CC_INTERP
3036 
3037 #ifdef COMPILER2
3038   if (!UseBiasedLocking || EmitSync != 0) {
3039     UseOptoBiasInlining = false;
3040   }
3041 #endif
3042 
3043   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
3044     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
3045     DebugNonSafepoints = true;
3046   }
3047 
3048 #ifndef PRODUCT
3049   if (CompileTheWorld) {
3050     // Force NmethodSweeper to sweep whole CodeCache each time.
3051     if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {
3052       NmethodSweepFraction = 1;
3053     }
3054   }
3055 #endif
3056 
3057   if (PrintCommandLineFlags) {
3058     CommandLineFlags::printSetFlags();
3059   }
3060 
3061   // Apply CPU specific policy for the BiasedLocking
3062   if (UseBiasedLocking) {
3063     if (!VM_Version::use_biased_locking() &&
3064         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
3065       UseBiasedLocking = false;
3066     }
3067   }
3068 
3069   return JNI_OK;
3070 }
3071 
3072 int Arguments::PropertyList_count(SystemProperty* pl) {
3073   int count = 0;
3074   while(pl != NULL) {
3075     count++;
3076     pl = pl->next();
3077   }
3078   return count;
3079 }
3080 
3081 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
3082   assert(key != NULL, "just checking");
3083   SystemProperty* prop;
3084   for (prop = pl; prop != NULL; prop = prop->next()) {
3085     if (strcmp(key, prop->key()) == 0) return prop->value();
3086   }
3087   return NULL;
3088 }
3089 
3090 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
3091   int count = 0;
3092   const char* ret_val = NULL;
3093 
3094   while(pl != NULL) {
3095     if(count >= index) {
3096       ret_val = pl->key();
3097       break;
3098     }
3099     count++;
3100     pl = pl->next();
3101   }
3102 
3103   return ret_val;
3104 }
3105 
3106 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
3107   int count = 0;
3108   char* ret_val = NULL;
3109 
3110   while(pl != NULL) {
3111     if(count >= index) {
3112       ret_val = pl->value();
3113       break;
3114     }
3115     count++;
3116     pl = pl->next();
3117   }
3118 
3119   return ret_val;
3120 }
3121 
3122 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
3123   SystemProperty* p = *plist;
3124   if (p == NULL) {
3125     *plist = new_p;
3126   } else {
3127     while (p->next() != NULL) {
3128       p = p->next();
3129     }
3130     p->set_next(new_p);
3131   }
3132 }
3133 
3134 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {
3135   if (plist == NULL)
3136     return;
3137 
3138   SystemProperty* new_p = new SystemProperty(k, v, true);
3139   PropertyList_add(plist, new_p);
3140 }
3141 
3142 // This add maintains unique property key in the list.
3143 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {
3144   if (plist == NULL)
3145     return;
3146 
3147   // If property key exist then update with new value.
3148   SystemProperty* prop;
3149   for (prop = *plist; prop != NULL; prop = prop->next()) {
3150     if (strcmp(k, prop->key()) == 0) {
3151       if (append) {
3152         prop->append_value(v);
3153       } else {
3154         prop->set_value(v);
3155       }
3156       return;
3157     }
3158   }
3159 
3160   PropertyList_add(plist, k, v);
3161 }
3162 
3163 #ifdef KERNEL
3164 char *Arguments::get_kernel_properties() {
3165   // Find properties starting with kernel and append them to string
3166   // We need to find out how long they are first because the URL's that they
3167   // might point to could get long.
3168   int length = 0;
3169   SystemProperty* prop;
3170   for (prop = _system_properties; prop != NULL; prop = prop->next()) {
3171     if (strncmp(prop->key(), "kernel.", 7 ) == 0) {
3172       length += (strlen(prop->key()) + strlen(prop->value()) + 5);  // "-D ="
3173     }
3174   }
3175   // Add one for null terminator.
3176   char *props = AllocateHeap(length + 1, "get_kernel_properties");
3177   if (length != 0) {
3178     int pos = 0;
3179     for (prop = _system_properties; prop != NULL; prop = prop->next()) {
3180       if (strncmp(prop->key(), "kernel.", 7 ) == 0) {
3181         jio_snprintf(&props[pos], length-pos,
3182                      "-D%s=%s ", prop->key(), prop->value());
3183         pos = strlen(props);
3184       }
3185     }
3186   }
3187   // null terminate props in case of null
3188   props[length] = '\0';
3189   return props;
3190 }
3191 #endif // KERNEL
3192 
3193 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
3194 // Returns true if all of the source pointed by src has been copied over to
3195 // the destination buffer pointed by buf. Otherwise, returns false.
3196 // Notes:
3197 // 1. If the length (buflen) of the destination buffer excluding the
3198 // NULL terminator character is not long enough for holding the expanded
3199 // pid characters, it also returns false instead of returning the partially
3200 // expanded one.
3201 // 2. The passed in "buflen" should be large enough to hold the null terminator.
3202 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
3203                                 char* buf, size_t buflen) {
3204   const char* p = src;
3205   char* b = buf;
3206   const char* src_end = &src[srclen];
3207   char* buf_end = &buf[buflen - 1];
3208 
3209   while (p < src_end && b < buf_end) {
3210     if (*p == '%') {
3211       switch (*(++p)) {
3212       case '%':         // "%%" ==> "%"
3213         *b++ = *p++;
3214         break;
3215       case 'p':  {       //  "%p" ==> current process id
3216         // buf_end points to the character before the last character so
3217         // that we could write '\0' to the end of the buffer.
3218         size_t buf_sz = buf_end - b + 1;
3219         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
3220 
3221         // if jio_snprintf fails or the buffer is not long enough to hold
3222         // the expanded pid, returns false.
3223         if (ret < 0 || ret >= (int)buf_sz) {
3224           return false;
3225         } else {
3226           b += ret;
3227           assert(*b == '\0', "fail in copy_expand_pid");
3228           if (p == src_end && b == buf_end + 1) {
3229             // reach the end of the buffer.
3230             return true;
3231           }
3232         }
3233         p++;
3234         break;
3235       }
3236       default :
3237         *b++ = '%';
3238       }
3239     } else {
3240       *b++ = *p++;
3241     }
3242   }
3243   *b = '\0';
3244   return (p == src_end); // return false if not all of the source was copied
3245 }