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