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