src/share/vm/runtime/arguments.cpp

Mon, 15 Dec 2008 13:58:57 -0800

author
swamyv
date
Mon, 15 Dec 2008 13:58:57 -0800
changeset 924
2494ab195856
parent 918
0f773163217d
child 948
2328d1d3f8cf
child 999
323728917cf4
permissions
-rw-r--r--

6653214: MemoryPoolMXBean.setUsageThreshold() does not support large heap sizes.
Reviewed-by: ysr, mchung

     1 /*
     2  * Copyright 1997-2008 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 #include "incls/_precompiled.incl"
    26 #include "incls/_arguments.cpp.incl"
    28 #define DEFAULT_VENDOR_URL_BUG "http://java.sun.com/webapps/bugreport/crash.jsp"
    29 #define DEFAULT_JAVA_LAUNCHER  "generic"
    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::_initial_heap_size            = 0;
    41 uintx  Arguments::_min_heap_size                = 0;
    42 Arguments::Mode Arguments::_mode                = _mixed;
    43 bool   Arguments::_java_compiler                = false;
    44 bool   Arguments::_xdebug_mode                  = false;
    45 const char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
    46 const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
    47 int    Arguments::_sun_java_launcher_pid        = -1;
    49 // These parameters are reset in method parse_vm_init_args(JavaVMInitArgs*)
    50 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
    51 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
    52 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
    53 bool   Arguments::_ClipInlining                 = ClipInlining;
    54 intx   Arguments::_Tier2CompileThreshold        = Tier2CompileThreshold;
    56 char*  Arguments::SharedArchivePath             = NULL;
    58 AgentLibraryList Arguments::_libraryList;
    59 AgentLibraryList Arguments::_agentList;
    61 abort_hook_t     Arguments::_abort_hook         = NULL;
    62 exit_hook_t      Arguments::_exit_hook          = NULL;
    63 vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
    66 SystemProperty *Arguments::_java_ext_dirs = NULL;
    67 SystemProperty *Arguments::_java_endorsed_dirs = NULL;
    68 SystemProperty *Arguments::_sun_boot_library_path = NULL;
    69 SystemProperty *Arguments::_java_library_path = NULL;
    70 SystemProperty *Arguments::_java_home = NULL;
    71 SystemProperty *Arguments::_java_class_path = NULL;
    72 SystemProperty *Arguments::_sun_boot_class_path = NULL;
    74 char* Arguments::_meta_index_path = NULL;
    75 char* Arguments::_meta_index_dir = NULL;
    77 static bool force_client_mode = false;
    79 // Check if head of 'option' matches 'name', and sets 'tail' remaining part of option string
    81 static bool match_option(const JavaVMOption *option, const char* name,
    82                          const char** tail) {
    83   int len = (int)strlen(name);
    84   if (strncmp(option->optionString, name, len) == 0) {
    85     *tail = option->optionString + len;
    86     return true;
    87   } else {
    88     return false;
    89   }
    90 }
    92 static void logOption(const char* opt) {
    93   if (PrintVMOptions) {
    94     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
    95   }
    96 }
    98 // Process java launcher properties.
    99 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
   100   // See if sun.java.launcher or sun.java.launcher.pid is defined.
   101   // Must do this before setting up other system properties,
   102   // as some of them may depend on launcher type.
   103   for (int index = 0; index < args->nOptions; index++) {
   104     const JavaVMOption* option = args->options + index;
   105     const char* tail;
   107     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
   108       process_java_launcher_argument(tail, option->extraInfo);
   109       continue;
   110     }
   111     if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
   112       _sun_java_launcher_pid = atoi(tail);
   113       continue;
   114     }
   115   }
   116 }
   118 // Initialize system properties key and value.
   119 void Arguments::init_system_properties() {
   121   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.version", "1.0", false));
   122   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
   123                                                                  "Java Virtual Machine Specification",  false));
   124   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.vendor",
   125                                                                  "Sun Microsystems Inc.",  false));
   126   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
   127   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
   128   PropertyList_add(&_system_properties, new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
   129   PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
   131   // following are JVMTI agent writeable properties.
   132   // Properties values are set to NULL and they are
   133   // os specific they are initialized in os::init_system_properties_values().
   134   _java_ext_dirs = new SystemProperty("java.ext.dirs", NULL,  true);
   135   _java_endorsed_dirs = new SystemProperty("java.endorsed.dirs", NULL,  true);
   136   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
   137   _java_library_path = new SystemProperty("java.library.path", NULL,  true);
   138   _java_home =  new SystemProperty("java.home", NULL,  true);
   139   _sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL,  true);
   141   _java_class_path = new SystemProperty("java.class.path", "",  true);
   143   // Add to System Property list.
   144   PropertyList_add(&_system_properties, _java_ext_dirs);
   145   PropertyList_add(&_system_properties, _java_endorsed_dirs);
   146   PropertyList_add(&_system_properties, _sun_boot_library_path);
   147   PropertyList_add(&_system_properties, _java_library_path);
   148   PropertyList_add(&_system_properties, _java_home);
   149   PropertyList_add(&_system_properties, _java_class_path);
   150   PropertyList_add(&_system_properties, _sun_boot_class_path);
   152   // Set OS specific system properties values
   153   os::init_system_properties_values();
   154 }
   156 /**
   157  * Provide a slightly more user-friendly way of eliminating -XX flags.
   158  * When a flag is eliminated, it can be added to this list in order to
   159  * continue accepting this flag on the command-line, while issuing a warning
   160  * and ignoring the value.  Once the JDK version reaches the 'accept_until'
   161  * limit, we flatly refuse to admit the existence of the flag.  This allows
   162  * a flag to die correctly over JDK releases using HSX.
   163  */
   164 typedef struct {
   165   const char* name;
   166   JDK_Version obsoleted_in; // when the flag went away
   167   JDK_Version accept_until; // which version to start denying the existence
   168 } ObsoleteFlag;
   170 static ObsoleteFlag obsolete_jvm_flags[] = {
   171   { "UseTrainGC",                    JDK_Version::jdk(5), JDK_Version::jdk(7) },
   172   { "UseSpecialLargeObjectHandling", JDK_Version::jdk(5), JDK_Version::jdk(7) },
   173   { "UseOversizedCarHandling",       JDK_Version::jdk(5), JDK_Version::jdk(7) },
   174   { "TraceCarAllocation",            JDK_Version::jdk(5), JDK_Version::jdk(7) },
   175   { "PrintTrainGCProcessingStats",   JDK_Version::jdk(5), JDK_Version::jdk(7) },
   176   { "LogOfCarSpaceSize",             JDK_Version::jdk(5), JDK_Version::jdk(7) },
   177   { "OversizedCarThreshold",         JDK_Version::jdk(5), JDK_Version::jdk(7) },
   178   { "MinTickInterval",               JDK_Version::jdk(5), JDK_Version::jdk(7) },
   179   { "DefaultTickInterval",           JDK_Version::jdk(5), JDK_Version::jdk(7) },
   180   { "MaxTickInterval",               JDK_Version::jdk(5), JDK_Version::jdk(7) },
   181   { "DelayTickAdjustment",           JDK_Version::jdk(5), JDK_Version::jdk(7) },
   182   { "ProcessingToTenuringRatio",     JDK_Version::jdk(5), JDK_Version::jdk(7) },
   183   { "MinTrainLength",                JDK_Version::jdk(5), JDK_Version::jdk(7) },
   184   { "AppendRatio",         JDK_Version::jdk_update(6,10), JDK_Version::jdk(7) },
   185   { NULL, JDK_Version(0), JDK_Version(0) }
   186 };
   188 // Returns true if the flag is obsolete and fits into the range specified
   189 // for being ignored.  In the case that the flag is ignored, the 'version'
   190 // value is filled in with the version number when the flag became
   191 // obsolete so that that value can be displayed to the user.
   192 bool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {
   193   int i = 0;
   194   assert(version != NULL, "Must provide a version buffer");
   195   while (obsolete_jvm_flags[i].name != NULL) {
   196     const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];
   197     // <flag>=xxx form
   198     // [-|+]<flag> form
   199     if ((strncmp(flag_status.name, s, strlen(flag_status.name)) == 0) ||
   200         ((s[0] == '+' || s[0] == '-') &&
   201         (strncmp(flag_status.name, &s[1], strlen(flag_status.name)) == 0))) {
   202       if (JDK_Version::current().compare(flag_status.accept_until) == -1) {
   203           *version = flag_status.obsoleted_in;
   204           return true;
   205       }
   206     }
   207     i++;
   208   }
   209   return false;
   210 }
   212 // Constructs the system class path (aka boot class path) from the following
   213 // components, in order:
   214 //
   215 //     prefix           // from -Xbootclasspath/p:...
   216 //     endorsed         // the expansion of -Djava.endorsed.dirs=...
   217 //     base             // from os::get_system_properties() or -Xbootclasspath=
   218 //     suffix           // from -Xbootclasspath/a:...
   219 //
   220 // java.endorsed.dirs is a list of directories; any jar or zip files in the
   221 // directories are added to the sysclasspath just before the base.
   222 //
   223 // This could be AllStatic, but it isn't needed after argument processing is
   224 // complete.
   225 class SysClassPath: public StackObj {
   226 public:
   227   SysClassPath(const char* base);
   228   ~SysClassPath();
   230   inline void set_base(const char* base);
   231   inline void add_prefix(const char* prefix);
   232   inline void add_suffix(const char* suffix);
   233   inline void reset_path(const char* base);
   235   // Expand the jar/zip files in each directory listed by the java.endorsed.dirs
   236   // property.  Must be called after all command-line arguments have been
   237   // processed (in particular, -Djava.endorsed.dirs=...) and before calling
   238   // combined_path().
   239   void expand_endorsed();
   241   inline const char* get_base()     const { return _items[_scp_base]; }
   242   inline const char* get_prefix()   const { return _items[_scp_prefix]; }
   243   inline const char* get_suffix()   const { return _items[_scp_suffix]; }
   244   inline const char* get_endorsed() const { return _items[_scp_endorsed]; }
   246   // Combine all the components into a single c-heap-allocated string; caller
   247   // must free the string if/when no longer needed.
   248   char* combined_path();
   250 private:
   251   // Utility routines.
   252   static char* add_to_path(const char* path, const char* str, bool prepend);
   253   static char* add_jars_to_path(char* path, const char* directory);
   255   inline void reset_item_at(int index);
   257   // Array indices for the items that make up the sysclasspath.  All except the
   258   // base are allocated in the C heap and freed by this class.
   259   enum {
   260     _scp_prefix,        // from -Xbootclasspath/p:...
   261     _scp_endorsed,      // the expansion of -Djava.endorsed.dirs=...
   262     _scp_base,          // the default sysclasspath
   263     _scp_suffix,        // from -Xbootclasspath/a:...
   264     _scp_nitems         // the number of items, must be last.
   265   };
   267   const char* _items[_scp_nitems];
   268   DEBUG_ONLY(bool _expansion_done;)
   269 };
   271 SysClassPath::SysClassPath(const char* base) {
   272   memset(_items, 0, sizeof(_items));
   273   _items[_scp_base] = base;
   274   DEBUG_ONLY(_expansion_done = false;)
   275 }
   277 SysClassPath::~SysClassPath() {
   278   // Free everything except the base.
   279   for (int i = 0; i < _scp_nitems; ++i) {
   280     if (i != _scp_base) reset_item_at(i);
   281   }
   282   DEBUG_ONLY(_expansion_done = false;)
   283 }
   285 inline void SysClassPath::set_base(const char* base) {
   286   _items[_scp_base] = base;
   287 }
   289 inline void SysClassPath::add_prefix(const char* prefix) {
   290   _items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);
   291 }
   293 inline void SysClassPath::add_suffix(const char* suffix) {
   294   _items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);
   295 }
   297 inline void SysClassPath::reset_item_at(int index) {
   298   assert(index < _scp_nitems && index != _scp_base, "just checking");
   299   if (_items[index] != NULL) {
   300     FREE_C_HEAP_ARRAY(char, _items[index]);
   301     _items[index] = NULL;
   302   }
   303 }
   305 inline void SysClassPath::reset_path(const char* base) {
   306   // Clear the prefix and suffix.
   307   reset_item_at(_scp_prefix);
   308   reset_item_at(_scp_suffix);
   309   set_base(base);
   310 }
   312 //------------------------------------------------------------------------------
   314 void SysClassPath::expand_endorsed() {
   315   assert(_items[_scp_endorsed] == NULL, "can only be called once.");
   317   const char* path = Arguments::get_property("java.endorsed.dirs");
   318   if (path == NULL) {
   319     path = Arguments::get_endorsed_dir();
   320     assert(path != NULL, "no default for java.endorsed.dirs");
   321   }
   323   char* expanded_path = NULL;
   324   const char separator = *os::path_separator();
   325   const char* const end = path + strlen(path);
   326   while (path < end) {
   327     const char* tmp_end = strchr(path, separator);
   328     if (tmp_end == NULL) {
   329       expanded_path = add_jars_to_path(expanded_path, path);
   330       path = end;
   331     } else {
   332       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1);
   333       memcpy(dirpath, path, tmp_end - path);
   334       dirpath[tmp_end - path] = '\0';
   335       expanded_path = add_jars_to_path(expanded_path, dirpath);
   336       FREE_C_HEAP_ARRAY(char, dirpath);
   337       path = tmp_end + 1;
   338     }
   339   }
   340   _items[_scp_endorsed] = expanded_path;
   341   DEBUG_ONLY(_expansion_done = true;)
   342 }
   344 // Combine the bootclasspath elements, some of which may be null, into a single
   345 // c-heap-allocated string.
   346 char* SysClassPath::combined_path() {
   347   assert(_items[_scp_base] != NULL, "empty default sysclasspath");
   348   assert(_expansion_done, "must call expand_endorsed() first.");
   350   size_t lengths[_scp_nitems];
   351   size_t total_len = 0;
   353   const char separator = *os::path_separator();
   355   // Get the lengths.
   356   int i;
   357   for (i = 0; i < _scp_nitems; ++i) {
   358     if (_items[i] != NULL) {
   359       lengths[i] = strlen(_items[i]);
   360       // Include space for the separator char (or a NULL for the last item).
   361       total_len += lengths[i] + 1;
   362     }
   363   }
   364   assert(total_len > 0, "empty sysclasspath not allowed");
   366   // Copy the _items to a single string.
   367   char* cp = NEW_C_HEAP_ARRAY(char, total_len);
   368   char* cp_tmp = cp;
   369   for (i = 0; i < _scp_nitems; ++i) {
   370     if (_items[i] != NULL) {
   371       memcpy(cp_tmp, _items[i], lengths[i]);
   372       cp_tmp += lengths[i];
   373       *cp_tmp++ = separator;
   374     }
   375   }
   376   *--cp_tmp = '\0';     // Replace the extra separator.
   377   return cp;
   378 }
   380 // Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
   381 char*
   382 SysClassPath::add_to_path(const char* path, const char* str, bool prepend) {
   383   char *cp;
   385   assert(str != NULL, "just checking");
   386   if (path == NULL) {
   387     size_t len = strlen(str) + 1;
   388     cp = NEW_C_HEAP_ARRAY(char, len);
   389     memcpy(cp, str, len);                       // copy the trailing null
   390   } else {
   391     const char separator = *os::path_separator();
   392     size_t old_len = strlen(path);
   393     size_t str_len = strlen(str);
   394     size_t len = old_len + str_len + 2;
   396     if (prepend) {
   397       cp = NEW_C_HEAP_ARRAY(char, len);
   398       char* cp_tmp = cp;
   399       memcpy(cp_tmp, str, str_len);
   400       cp_tmp += str_len;
   401       *cp_tmp = separator;
   402       memcpy(++cp_tmp, path, old_len + 1);      // copy the trailing null
   403       FREE_C_HEAP_ARRAY(char, path);
   404     } else {
   405       cp = REALLOC_C_HEAP_ARRAY(char, path, len);
   406       char* cp_tmp = cp + old_len;
   407       *cp_tmp = separator;
   408       memcpy(++cp_tmp, str, str_len + 1);       // copy the trailing null
   409     }
   410   }
   411   return cp;
   412 }
   414 // Scan the directory and append any jar or zip files found to path.
   415 // Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
   416 char* SysClassPath::add_jars_to_path(char* path, const char* directory) {
   417   DIR* dir = os::opendir(directory);
   418   if (dir == NULL) return path;
   420   char dir_sep[2] = { '\0', '\0' };
   421   size_t directory_len = strlen(directory);
   422   const char fileSep = *os::file_separator();
   423   if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;
   425   /* Scan the directory for jars/zips, appending them to path. */
   426   struct dirent *entry;
   427   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory));
   428   while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
   429     const char* name = entry->d_name;
   430     const char* ext = name + strlen(name) - 4;
   431     bool isJarOrZip = ext > name &&
   432       (os::file_name_strcmp(ext, ".jar") == 0 ||
   433        os::file_name_strcmp(ext, ".zip") == 0);
   434     if (isJarOrZip) {
   435       char* jarpath = NEW_C_HEAP_ARRAY(char, directory_len + 2 + strlen(name));
   436       sprintf(jarpath, "%s%s%s", directory, dir_sep, name);
   437       path = add_to_path(path, jarpath, false);
   438       FREE_C_HEAP_ARRAY(char, jarpath);
   439     }
   440   }
   441   FREE_C_HEAP_ARRAY(char, dbuf);
   442   os::closedir(dir);
   443   return path;
   444 }
   446 // Parses a memory size specification string.
   447 static bool atomull(const char *s, julong* result) {
   448   julong n = 0;
   449   int args_read = sscanf(s, os::julong_format_specifier(), &n);
   450   if (args_read != 1) {
   451     return false;
   452   }
   453   while (*s != '\0' && isdigit(*s)) {
   454     s++;
   455   }
   456   // 4705540: illegal if more characters are found after the first non-digit
   457   if (strlen(s) > 1) {
   458     return false;
   459   }
   460   switch (*s) {
   461     case 'T': case 't':
   462       *result = n * G * K;
   463       // Check for overflow.
   464       if (*result/((julong)G * K) != n) return false;
   465       return true;
   466     case 'G': case 'g':
   467       *result = n * G;
   468       if (*result/G != n) return false;
   469       return true;
   470     case 'M': case 'm':
   471       *result = n * M;
   472       if (*result/M != n) return false;
   473       return true;
   474     case 'K': case 'k':
   475       *result = n * K;
   476       if (*result/K != n) return false;
   477       return true;
   478     case '\0':
   479       *result = n;
   480       return true;
   481     default:
   482       return false;
   483   }
   484 }
   486 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
   487   if (size < min_size) return arg_too_small;
   488   // Check that size will fit in a size_t (only relevant on 32-bit)
   489   if (size > max_uintx) return arg_too_big;
   490   return arg_in_range;
   491 }
   493 // Describe an argument out of range error
   494 void Arguments::describe_range_error(ArgsRange errcode) {
   495   switch(errcode) {
   496   case arg_too_big:
   497     jio_fprintf(defaultStream::error_stream(),
   498                 "The specified size exceeds the maximum "
   499                 "representable size.\n");
   500     break;
   501   case arg_too_small:
   502   case arg_unreadable:
   503   case arg_in_range:
   504     // do nothing for now
   505     break;
   506   default:
   507     ShouldNotReachHere();
   508   }
   509 }
   511 static bool set_bool_flag(char* name, bool value, FlagValueOrigin origin) {
   512   return CommandLineFlags::boolAtPut(name, &value, origin);
   513 }
   516 static bool set_fp_numeric_flag(char* name, char* value, FlagValueOrigin origin) {
   517   double v;
   518   if (sscanf(value, "%lf", &v) != 1) {
   519     return false;
   520   }
   522   if (CommandLineFlags::doubleAtPut(name, &v, origin)) {
   523     return true;
   524   }
   525   return false;
   526 }
   529 static bool set_numeric_flag(char* name, char* value, FlagValueOrigin origin) {
   530   julong v;
   531   intx intx_v;
   532   bool is_neg = false;
   533   // Check the sign first since atomull() parses only unsigned values.
   534   if (*value == '-') {
   535     if (!CommandLineFlags::intxAt(name, &intx_v)) {
   536       return false;
   537     }
   538     value++;
   539     is_neg = true;
   540   }
   541   if (!atomull(value, &v)) {
   542     return false;
   543   }
   544   intx_v = (intx) v;
   545   if (is_neg) {
   546     intx_v = -intx_v;
   547   }
   548   if (CommandLineFlags::intxAtPut(name, &intx_v, origin)) {
   549     return true;
   550   }
   551   uintx uintx_v = (uintx) v;
   552   if (!is_neg && CommandLineFlags::uintxAtPut(name, &uintx_v, origin)) {
   553     return true;
   554   }
   555   return false;
   556 }
   559 static bool set_string_flag(char* name, const char* value, FlagValueOrigin origin) {
   560   if (!CommandLineFlags::ccstrAtPut(name, &value, origin))  return false;
   561   // Contract:  CommandLineFlags always returns a pointer that needs freeing.
   562   FREE_C_HEAP_ARRAY(char, value);
   563   return true;
   564 }
   566 static bool append_to_string_flag(char* name, const char* new_value, FlagValueOrigin origin) {
   567   const char* old_value = "";
   568   if (!CommandLineFlags::ccstrAt(name, &old_value))  return false;
   569   size_t old_len = old_value != NULL ? strlen(old_value) : 0;
   570   size_t new_len = strlen(new_value);
   571   const char* value;
   572   char* free_this_too = NULL;
   573   if (old_len == 0) {
   574     value = new_value;
   575   } else if (new_len == 0) {
   576     value = old_value;
   577   } else {
   578     char* buf = NEW_C_HEAP_ARRAY(char, old_len + 1 + new_len + 1);
   579     // each new setting adds another LINE to the switch:
   580     sprintf(buf, "%s\n%s", old_value, new_value);
   581     value = buf;
   582     free_this_too = buf;
   583   }
   584   (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
   585   // CommandLineFlags always returns a pointer that needs freeing.
   586   FREE_C_HEAP_ARRAY(char, value);
   587   if (free_this_too != NULL) {
   588     // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
   589     FREE_C_HEAP_ARRAY(char, free_this_too);
   590   }
   591   return true;
   592 }
   595 bool Arguments::parse_argument(const char* arg, FlagValueOrigin origin) {
   597   // range of acceptable characters spelled out for portability reasons
   598 #define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
   599 #define BUFLEN 255
   600   char name[BUFLEN+1];
   601   char dummy;
   603   if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
   604     return set_bool_flag(name, false, origin);
   605   }
   606   if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
   607     return set_bool_flag(name, true, origin);
   608   }
   610   char punct;
   611   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
   612     const char* value = strchr(arg, '=') + 1;
   613     Flag* flag = Flag::find_flag(name, strlen(name));
   614     if (flag != NULL && flag->is_ccstr()) {
   615       if (flag->ccstr_accumulates()) {
   616         return append_to_string_flag(name, value, origin);
   617       } else {
   618         if (value[0] == '\0') {
   619           value = NULL;
   620         }
   621         return set_string_flag(name, value, origin);
   622       }
   623     }
   624   }
   626   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
   627     const char* value = strchr(arg, '=') + 1;
   628     // -XX:Foo:=xxx will reset the string flag to the given value.
   629     if (value[0] == '\0') {
   630       value = NULL;
   631     }
   632     return set_string_flag(name, value, origin);
   633   }
   635 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"
   636 #define SIGNED_NUMBER_RANGE    "[-0123456789]"
   637 #define        NUMBER_RANGE    "[0123456789]"
   638   char value[BUFLEN + 1];
   639   char value2[BUFLEN + 1];
   640   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
   641     // Looks like a floating-point number -- try again with more lenient format string
   642     if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
   643       return set_fp_numeric_flag(name, value, origin);
   644     }
   645   }
   647 #define VALUE_RANGE "[-kmgtKMGT0123456789]"
   648   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
   649     return set_numeric_flag(name, value, origin);
   650   }
   652   return false;
   653 }
   656 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
   657   assert(bldarray != NULL, "illegal argument");
   659   if (arg == NULL) {
   660     return;
   661   }
   663   int index = *count;
   665   // expand the array and add arg to the last element
   666   (*count)++;
   667   if (*bldarray == NULL) {
   668     *bldarray = NEW_C_HEAP_ARRAY(char*, *count);
   669   } else {
   670     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, *count);
   671   }
   672   (*bldarray)[index] = strdup(arg);
   673 }
   675 void Arguments::build_jvm_args(const char* arg) {
   676   add_string(&_jvm_args_array, &_num_jvm_args, arg);
   677 }
   679 void Arguments::build_jvm_flags(const char* arg) {
   680   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
   681 }
   683 // utility function to return a string that concatenates all
   684 // strings in a given char** array
   685 const char* Arguments::build_resource_string(char** args, int count) {
   686   if (args == NULL || count == 0) {
   687     return NULL;
   688   }
   689   size_t length = strlen(args[0]) + 1; // add 1 for the null terminator
   690   for (int i = 1; i < count; i++) {
   691     length += strlen(args[i]) + 1; // add 1 for a space
   692   }
   693   char* s = NEW_RESOURCE_ARRAY(char, length);
   694   strcpy(s, args[0]);
   695   for (int j = 1; j < count; j++) {
   696     strcat(s, " ");
   697     strcat(s, args[j]);
   698   }
   699   return (const char*) s;
   700 }
   702 void Arguments::print_on(outputStream* st) {
   703   st->print_cr("VM Arguments:");
   704   if (num_jvm_flags() > 0) {
   705     st->print("jvm_flags: "); print_jvm_flags_on(st);
   706   }
   707   if (num_jvm_args() > 0) {
   708     st->print("jvm_args: "); print_jvm_args_on(st);
   709   }
   710   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
   711   st->print_cr("Launcher Type: %s", _sun_java_launcher);
   712 }
   714 void Arguments::print_jvm_flags_on(outputStream* st) {
   715   if (_num_jvm_flags > 0) {
   716     for (int i=0; i < _num_jvm_flags; i++) {
   717       st->print("%s ", _jvm_flags_array[i]);
   718     }
   719     st->print_cr("");
   720   }
   721 }
   723 void Arguments::print_jvm_args_on(outputStream* st) {
   724   if (_num_jvm_args > 0) {
   725     for (int i=0; i < _num_jvm_args; i++) {
   726       st->print("%s ", _jvm_args_array[i]);
   727     }
   728     st->print_cr("");
   729   }
   730 }
   732 bool Arguments::process_argument(const char* arg,
   733     jboolean ignore_unrecognized, FlagValueOrigin origin) {
   735   JDK_Version since = JDK_Version();
   737   if (parse_argument(arg, origin)) {
   738     // do nothing
   739   } else if (is_newly_obsolete(arg, &since)) {
   740     enum { bufsize = 256 };
   741     char buffer[bufsize];
   742     since.to_string(buffer, bufsize);
   743     jio_fprintf(defaultStream::error_stream(),
   744       "Warning: The flag %s has been EOL'd as of %s and will"
   745       " be ignored\n", arg, buffer);
   746   } else {
   747     if (!ignore_unrecognized) {
   748       jio_fprintf(defaultStream::error_stream(),
   749                   "Unrecognized VM option '%s'\n", arg);
   750       // allow for commandline "commenting out" options like -XX:#+Verbose
   751       if (strlen(arg) == 0 || arg[0] != '#') {
   752         return false;
   753       }
   754     }
   755   }
   756   return true;
   757 }
   760 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
   761   FILE* stream = fopen(file_name, "rb");
   762   if (stream == NULL) {
   763     if (should_exist) {
   764       jio_fprintf(defaultStream::error_stream(),
   765                   "Could not open settings file %s\n", file_name);
   766       return false;
   767     } else {
   768       return true;
   769     }
   770   }
   772   char token[1024];
   773   int  pos = 0;
   775   bool in_white_space = true;
   776   bool in_comment     = false;
   777   bool in_quote       = false;
   778   char quote_c        = 0;
   779   bool result         = true;
   781   int c = getc(stream);
   782   while(c != EOF) {
   783     if (in_white_space) {
   784       if (in_comment) {
   785         if (c == '\n') in_comment = false;
   786       } else {
   787         if (c == '#') in_comment = true;
   788         else if (!isspace(c)) {
   789           in_white_space = false;
   790           token[pos++] = c;
   791         }
   792       }
   793     } else {
   794       if (c == '\n' || (!in_quote && isspace(c))) {
   795         // token ends at newline, or at unquoted whitespace
   796         // this allows a way to include spaces in string-valued options
   797         token[pos] = '\0';
   798         logOption(token);
   799         result &= process_argument(token, ignore_unrecognized, CONFIG_FILE);
   800         build_jvm_flags(token);
   801         pos = 0;
   802         in_white_space = true;
   803         in_quote = false;
   804       } else if (!in_quote && (c == '\'' || c == '"')) {
   805         in_quote = true;
   806         quote_c = c;
   807       } else if (in_quote && (c == quote_c)) {
   808         in_quote = false;
   809       } else {
   810         token[pos++] = c;
   811       }
   812     }
   813     c = getc(stream);
   814   }
   815   if (pos > 0) {
   816     token[pos] = '\0';
   817     result &= process_argument(token, ignore_unrecognized, CONFIG_FILE);
   818     build_jvm_flags(token);
   819   }
   820   fclose(stream);
   821   return result;
   822 }
   824 //=============================================================================================================
   825 // Parsing of properties (-D)
   827 const char* Arguments::get_property(const char* key) {
   828   return PropertyList_get_value(system_properties(), key);
   829 }
   831 bool Arguments::add_property(const char* prop) {
   832   const char* eq = strchr(prop, '=');
   833   char* key;
   834   // ns must be static--its address may be stored in a SystemProperty object.
   835   const static char ns[1] = {0};
   836   char* value = (char *)ns;
   838   size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);
   839   key = AllocateHeap(key_len + 1, "add_property");
   840   strncpy(key, prop, key_len);
   841   key[key_len] = '\0';
   843   if (eq != NULL) {
   844     size_t value_len = strlen(prop) - key_len - 1;
   845     value = AllocateHeap(value_len + 1, "add_property");
   846     strncpy(value, &prop[key_len + 1], value_len + 1);
   847   }
   849   if (strcmp(key, "java.compiler") == 0) {
   850     process_java_compiler_argument(value);
   851     FreeHeap(key);
   852     if (eq != NULL) {
   853       FreeHeap(value);
   854     }
   855     return true;
   856   }
   857   else if (strcmp(key, "sun.java.command") == 0) {
   859     _java_command = value;
   861     // don't add this property to the properties exposed to the java application
   862     FreeHeap(key);
   863     return true;
   864   }
   865   else if (strcmp(key, "sun.java.launcher.pid") == 0) {
   866     // launcher.pid property is private and is processed
   867     // in process_sun_java_launcher_properties();
   868     // the sun.java.launcher property is passed on to the java application
   869     FreeHeap(key);
   870     if (eq != NULL) {
   871       FreeHeap(value);
   872     }
   873     return true;
   874   }
   875   else if (strcmp(key, "java.vendor.url.bug") == 0) {
   876     // save it in _java_vendor_url_bug, so JVM fatal error handler can access
   877     // its value without going through the property list or making a Java call.
   878     _java_vendor_url_bug = value;
   879   }
   881   // Create new property and add at the end of the list
   882   PropertyList_unique_add(&_system_properties, key, value);
   883   return true;
   884 }
   886 //===========================================================================================================
   887 // Setting int/mixed/comp mode flags
   889 void Arguments::set_mode_flags(Mode mode) {
   890   // Set up default values for all flags.
   891   // If you add a flag to any of the branches below,
   892   // add a default value for it here.
   893   set_java_compiler(false);
   894   _mode                      = mode;
   896   // Ensure Agent_OnLoad has the correct initial values.
   897   // This may not be the final mode; mode may change later in onload phase.
   898   PropertyList_unique_add(&_system_properties, "java.vm.info",
   899      (char*)Abstract_VM_Version::vm_info_string());
   901   UseInterpreter             = true;
   902   UseCompiler                = true;
   903   UseLoopCounter             = true;
   905   // Default values may be platform/compiler dependent -
   906   // use the saved values
   907   ClipInlining               = Arguments::_ClipInlining;
   908   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
   909   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
   910   BackgroundCompilation      = Arguments::_BackgroundCompilation;
   911   Tier2CompileThreshold      = Arguments::_Tier2CompileThreshold;
   913   // Change from defaults based on mode
   914   switch (mode) {
   915   default:
   916     ShouldNotReachHere();
   917     break;
   918   case _int:
   919     UseCompiler              = false;
   920     UseLoopCounter           = false;
   921     AlwaysCompileLoopMethods = false;
   922     UseOnStackReplacement    = false;
   923     break;
   924   case _mixed:
   925     // same as default
   926     break;
   927   case _comp:
   928     UseInterpreter           = false;
   929     BackgroundCompilation    = false;
   930     ClipInlining             = false;
   931     break;
   932   }
   933 }
   936 // Conflict: required to use shared spaces (-Xshare:on), but
   937 // incompatible command line options were chosen.
   939 static void no_shared_spaces() {
   940   if (RequireSharedSpaces) {
   941     jio_fprintf(defaultStream::error_stream(),
   942       "Class data sharing is inconsistent with other specified options.\n");
   943     vm_exit_during_initialization("Unable to use shared archive.", NULL);
   944   } else {
   945     FLAG_SET_DEFAULT(UseSharedSpaces, false);
   946   }
   947 }
   950 // If the user has chosen ParallelGCThreads > 0, we set UseParNewGC
   951 // if it's not explictly set or unset. If the user has chosen
   952 // UseParNewGC and not explicitly set ParallelGCThreads we
   953 // set it, unless this is a single cpu machine.
   954 void Arguments::set_parnew_gc_flags() {
   955   assert(!UseSerialGC && !UseParallelGC && !UseG1GC,
   956          "control point invariant");
   957   assert(UseParNewGC, "Error");
   959   // Turn off AdaptiveSizePolicy by default for parnew until it is
   960   // complete.
   961   if (FLAG_IS_DEFAULT(UseAdaptiveSizePolicy)) {
   962     FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
   963   }
   965   if (ParallelGCThreads == 0) {
   966     FLAG_SET_DEFAULT(ParallelGCThreads,
   967                      Abstract_VM_Version::parallel_worker_threads());
   968     if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
   969       FLAG_SET_DEFAULT(UseParNewGC, false);
   970     }
   971   }
   972   if (!UseParNewGC) {
   973     FLAG_SET_DEFAULT(ParallelGCThreads, 0);
   974   } else {
   975     no_shared_spaces();
   977     // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 correspondinly,
   978     // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
   979     // we set them to 1024 and 1024.
   980     // See CR 6362902.
   981     if (FLAG_IS_DEFAULT(YoungPLABSize)) {
   982       FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
   983     }
   984     if (FLAG_IS_DEFAULT(OldPLABSize)) {
   985       FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
   986     }
   988     // AlwaysTenure flag should make ParNew to promote all at first collection.
   989     // See CR 6362902.
   990     if (AlwaysTenure) {
   991       FLAG_SET_CMDLINE(intx, MaxTenuringThreshold, 0);
   992     }
   993   }
   994 }
   996 // Adjust some sizes to suit CMS and/or ParNew needs; these work well on
   997 // sparc/solaris for certain applications, but would gain from
   998 // further optimization and tuning efforts, and would almost
   999 // certainly gain from analysis of platform and environment.
  1000 void Arguments::set_cms_and_parnew_gc_flags() {
  1001   assert(!UseSerialGC && !UseParallelGC, "Error");
  1002   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
  1004   // If we are using CMS, we prefer to UseParNewGC,
  1005   // unless explicitly forbidden.
  1006   if (FLAG_IS_DEFAULT(UseParNewGC)) {
  1007     FLAG_SET_ERGO(bool, UseParNewGC, true);
  1010   // Turn off AdaptiveSizePolicy by default for cms until it is
  1011   // complete.
  1012   if (FLAG_IS_DEFAULT(UseAdaptiveSizePolicy)) {
  1013     FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
  1016   // In either case, adjust ParallelGCThreads and/or UseParNewGC
  1017   // as needed.
  1018   if (UseParNewGC) {
  1019     set_parnew_gc_flags();
  1022   // Now make adjustments for CMS
  1023   size_t young_gen_per_worker;
  1024   intx new_ratio;
  1025   size_t min_new_default;
  1026   intx tenuring_default;
  1027   if (CMSUseOldDefaults) {  // old defaults: "old" as of 6.0
  1028     if FLAG_IS_DEFAULT(CMSYoungGenPerWorker) {
  1029       FLAG_SET_ERGO(intx, CMSYoungGenPerWorker, 4*M);
  1031     young_gen_per_worker = 4*M;
  1032     new_ratio = (intx)15;
  1033     min_new_default = 4*M;
  1034     tenuring_default = (intx)0;
  1035   } else { // new defaults: "new" as of 6.0
  1036     young_gen_per_worker = CMSYoungGenPerWorker;
  1037     new_ratio = (intx)7;
  1038     min_new_default = 16*M;
  1039     tenuring_default = (intx)4;
  1042   // Preferred young gen size for "short" pauses
  1043   const uintx parallel_gc_threads =
  1044     (ParallelGCThreads == 0 ? 1 : ParallelGCThreads);
  1045   const size_t preferred_max_new_size_unaligned =
  1046     ScaleForWordSize(young_gen_per_worker * parallel_gc_threads);
  1047   const size_t preferred_max_new_size =
  1048     align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
  1050   // Unless explicitly requested otherwise, size young gen
  1051   // for "short" pauses ~ 4M*ParallelGCThreads
  1052   if (FLAG_IS_DEFAULT(MaxNewSize)) {  // MaxNewSize not set at command-line
  1053     if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
  1054       FLAG_SET_ERGO(uintx, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
  1055     } else {
  1056       FLAG_SET_ERGO(uintx, MaxNewSize, preferred_max_new_size);
  1058     if(PrintGCDetails && Verbose) {
  1059       // Too early to use gclog_or_tty
  1060       tty->print_cr("Ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
  1063   // Unless explicitly requested otherwise, prefer a large
  1064   // Old to Young gen size so as to shift the collection load
  1065   // to the old generation concurrent collector
  1066   if (FLAG_IS_DEFAULT(NewRatio)) {
  1067     FLAG_SET_ERGO(intx, NewRatio, MAX2(NewRatio, new_ratio));
  1069     size_t min_new  = align_size_up(ScaleForWordSize(min_new_default), os::vm_page_size());
  1070     size_t prev_initial_size = initial_heap_size();
  1071     if (prev_initial_size != 0 && prev_initial_size < min_new+OldSize) {
  1072       set_initial_heap_size(min_new+OldSize);
  1073       // Currently minimum size and the initial heap sizes are the same.
  1074       set_min_heap_size(initial_heap_size());
  1075       if (PrintGCDetails && Verbose) {
  1076         warning("Initial heap size increased to " SIZE_FORMAT " M from "
  1077                 SIZE_FORMAT " M; use -XX:NewSize=... for finer control.",
  1078                 initial_heap_size()/M, prev_initial_size/M);
  1081     // MaxHeapSize is aligned down in collectorPolicy
  1082     size_t max_heap = align_size_down(MaxHeapSize,
  1083                                       CardTableRS::ct_max_alignment_constraint());
  1085     if(PrintGCDetails && Verbose) {
  1086       // Too early to use gclog_or_tty
  1087       tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
  1088            " initial_heap_size:  " SIZE_FORMAT
  1089            " max_heap: " SIZE_FORMAT,
  1090            min_heap_size(), initial_heap_size(), max_heap);
  1092     if (max_heap > min_new) {
  1093       // Unless explicitly requested otherwise, make young gen
  1094       // at least min_new, and at most preferred_max_new_size.
  1095       if (FLAG_IS_DEFAULT(NewSize)) {
  1096         FLAG_SET_ERGO(uintx, NewSize, MAX2(NewSize, min_new));
  1097         FLAG_SET_ERGO(uintx, NewSize, MIN2(preferred_max_new_size, NewSize));
  1098         if(PrintGCDetails && Verbose) {
  1099           // Too early to use gclog_or_tty
  1100           tty->print_cr("Ergo set NewSize: " SIZE_FORMAT, NewSize);
  1103       // Unless explicitly requested otherwise, size old gen
  1104       // so that it's at least 3X of NewSize to begin with;
  1105       // later NewRatio will decide how it grows; see above.
  1106       if (FLAG_IS_DEFAULT(OldSize)) {
  1107         if (max_heap > NewSize) {
  1108           FLAG_SET_ERGO(uintx, OldSize, MIN2(3*NewSize,  max_heap - NewSize));
  1109           if(PrintGCDetails && Verbose) {
  1110             // Too early to use gclog_or_tty
  1111             tty->print_cr("Ergo set OldSize: " SIZE_FORMAT, OldSize);
  1117   // Unless explicitly requested otherwise, definitely
  1118   // promote all objects surviving "tenuring_default" scavenges.
  1119   if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
  1120       FLAG_IS_DEFAULT(SurvivorRatio)) {
  1121     FLAG_SET_ERGO(intx, MaxTenuringThreshold, tenuring_default);
  1123   // If we decided above (or user explicitly requested)
  1124   // `promote all' (via MaxTenuringThreshold := 0),
  1125   // prefer minuscule survivor spaces so as not to waste
  1126   // space for (non-existent) survivors
  1127   if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
  1128     FLAG_SET_ERGO(intx, SurvivorRatio, MAX2((intx)1024, SurvivorRatio));
  1130   // If OldPLABSize is set and CMSParPromoteBlocksToClaim is not,
  1131   // set CMSParPromoteBlocksToClaim equal to OldPLABSize.
  1132   // This is done in order to make ParNew+CMS configuration to work
  1133   // with YoungPLABSize and OldPLABSize options.
  1134   // See CR 6362902.
  1135   if (!FLAG_IS_DEFAULT(OldPLABSize)) {
  1136     if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {
  1137       // OldPLABSize is not the default value but CMSParPromoteBlocksToClaim
  1138       // is.  In this situtation let CMSParPromoteBlocksToClaim follow
  1139       // the value (either from the command line or ergonomics) of
  1140       // OldPLABSize.  Following OldPLABSize is an ergonomics decision.
  1141       FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, OldPLABSize);
  1143     else {
  1144       // OldPLABSize and CMSParPromoteBlocksToClaim are both set.
  1145       // CMSParPromoteBlocksToClaim is a collector-specific flag, so
  1146       // we'll let it to take precedence.
  1147       jio_fprintf(defaultStream::error_stream(),
  1148                   "Both OldPLABSize and CMSParPromoteBlocksToClaim options are specified "
  1149                   "for the CMS collector. CMSParPromoteBlocksToClaim will take precedence.\n");
  1154 inline uintx max_heap_for_compressed_oops() {
  1155   LP64_ONLY(return oopDesc::OopEncodingHeapMax - MaxPermSize - os::vm_page_size());
  1156   NOT_LP64(return DefaultMaxRAM);
  1159 bool Arguments::should_auto_select_low_pause_collector() {
  1160   if (UseAutoGCSelectPolicy &&
  1161       !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
  1162       (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
  1163     if (PrintGCDetails) {
  1164       // Cannot use gclog_or_tty yet.
  1165       tty->print_cr("Automatic selection of the low pause collector"
  1166        " based on pause goal of %d (ms)", MaxGCPauseMillis);
  1168     return true;
  1170   return false;
  1173 void Arguments::set_ergonomics_flags() {
  1174   // Parallel GC is not compatible with sharing. If one specifies
  1175   // that they want sharing explicitly, do not set ergonmics flags.
  1176   if (DumpSharedSpaces || ForceSharedSpaces) {
  1177     return;
  1180   if (os::is_server_class_machine() && !force_client_mode ) {
  1181     // If no other collector is requested explicitly,
  1182     // let the VM select the collector based on
  1183     // machine class and automatic selection policy.
  1184     if (!UseSerialGC &&
  1185         !UseConcMarkSweepGC &&
  1186         !UseG1GC &&
  1187         !UseParNewGC &&
  1188         !DumpSharedSpaces &&
  1189         FLAG_IS_DEFAULT(UseParallelGC)) {
  1190       if (should_auto_select_low_pause_collector()) {
  1191         FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
  1192       } else {
  1193         FLAG_SET_ERGO(bool, UseParallelGC, true);
  1195       no_shared_spaces();
  1199 #ifdef _LP64
  1200   // Compressed Headers do not work with CMS, which uses a bit in the klass
  1201   // field offset to determine free list chunk markers.
  1202   // Check that UseCompressedOops can be set with the max heap size allocated
  1203   // by ergonomics.
  1204   if (MaxHeapSize <= max_heap_for_compressed_oops()) {
  1205     if (FLAG_IS_DEFAULT(UseCompressedOops) && !UseG1GC) {
  1206       // Turn off until bug is fixed.
  1207       // the following line to return it to default status.
  1208       // FLAG_SET_ERGO(bool, UseCompressedOops, true);
  1209     } else if (UseCompressedOops && UseG1GC) {
  1210       warning(" UseCompressedOops does not currently work with UseG1GC; switching off UseCompressedOops. ");
  1211       FLAG_SET_DEFAULT(UseCompressedOops, false);
  1213 #ifdef _WIN64
  1214     if (UseLargePages && UseCompressedOops) {
  1215       // Cannot allocate guard pages for implicit checks in indexed addressing
  1216       // mode, when large pages are specified on windows.
  1217       FLAG_SET_DEFAULT(UseImplicitNullCheckForNarrowOop, false);
  1219 #endif //  _WIN64
  1220   } else {
  1221     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
  1222       warning("Max heap size too large for Compressed Oops");
  1223       FLAG_SET_DEFAULT(UseCompressedOops, false);
  1226   // Also checks that certain machines are slower with compressed oops
  1227   // in vm_version initialization code.
  1228 #endif // _LP64
  1231 void Arguments::set_parallel_gc_flags() {
  1232   assert(UseParallelGC || UseParallelOldGC, "Error");
  1233   // If parallel old was requested, automatically enable parallel scavenge.
  1234   if (UseParallelOldGC && !UseParallelGC && FLAG_IS_DEFAULT(UseParallelGC)) {
  1235     FLAG_SET_DEFAULT(UseParallelGC, true);
  1238   // If no heap maximum was requested explicitly, use some reasonable fraction
  1239   // of the physical memory, up to a maximum of 1GB.
  1240   if (UseParallelGC) {
  1241     FLAG_SET_ERGO(uintx, ParallelGCThreads,
  1242                   Abstract_VM_Version::parallel_worker_threads());
  1244     // PS is a server collector, setup the heap sizes accordingly.
  1245     set_server_heap_size();
  1246     // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
  1247     // SurvivorRatio has been set, reset their default values to SurvivorRatio +
  1248     // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
  1249     // See CR 6362902 for details.
  1250     if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
  1251       if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
  1252          FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
  1254       if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
  1255         FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
  1259     if (UseParallelOldGC) {
  1260       // Par compact uses lower default values since they are treated as
  1261       // minimums.  These are different defaults because of the different
  1262       // interpretation and are not ergonomically set.
  1263       if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
  1264         FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
  1266       if (FLAG_IS_DEFAULT(PermMarkSweepDeadRatio)) {
  1267         FLAG_SET_DEFAULT(PermMarkSweepDeadRatio, 5);
  1273 void Arguments::set_g1_gc_flags() {
  1274   assert(UseG1GC, "Error");
  1275   // G1 is a server collector, setup the heap sizes accordingly.
  1276   set_server_heap_size();
  1277 #ifdef COMPILER1
  1278   FastTLABRefill = false;
  1279 #endif
  1280   FLAG_SET_DEFAULT(ParallelGCThreads,
  1281                      Abstract_VM_Version::parallel_worker_threads());
  1282   if (ParallelGCThreads == 0) {
  1283     FLAG_SET_DEFAULT(ParallelGCThreads,
  1284                      Abstract_VM_Version::parallel_worker_threads
  1285 ());
  1287   no_shared_spaces();
  1290 void Arguments::set_server_heap_size() {
  1291   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
  1292     const uint64_t reasonable_fraction =
  1293       os::physical_memory() / DefaultMaxRAMFraction;
  1294     const uint64_t maximum_size = (uint64_t)
  1295                  (FLAG_IS_DEFAULT(DefaultMaxRAM) && UseCompressedOops ?
  1296                      MIN2(max_heap_for_compressed_oops(), DefaultMaxRAM) :
  1297                      DefaultMaxRAM);
  1298     size_t reasonable_max =
  1299       (size_t) os::allocatable_physical_memory(reasonable_fraction);
  1300     if (reasonable_max > maximum_size) {
  1301       reasonable_max = maximum_size;
  1303     if (PrintGCDetails && Verbose) {
  1304       // Cannot use gclog_or_tty yet.
  1305       tty->print_cr("  Max heap size for server class platform "
  1306                     SIZE_FORMAT, reasonable_max);
  1308     // If the initial_heap_size has not been set with -Xms,
  1309     // then set it as fraction of size of physical memory
  1310     // respecting the maximum and minimum sizes of the heap.
  1311     if (initial_heap_size() == 0) {
  1312       const uint64_t reasonable_initial_fraction =
  1313         os::physical_memory() / DefaultInitialRAMFraction;
  1314       const size_t reasonable_initial =
  1315         (size_t) os::allocatable_physical_memory(reasonable_initial_fraction);
  1316       const size_t minimum_size = NewSize + OldSize;
  1317       set_initial_heap_size(MAX2(MIN2(reasonable_initial, reasonable_max),
  1318                                 minimum_size));
  1319       // Currently the minimum size and the initial heap sizes are the same.
  1320       set_min_heap_size(initial_heap_size());
  1321       if (PrintGCDetails && Verbose) {
  1322         // Cannot use gclog_or_tty yet.
  1323         tty->print_cr("  Initial heap size for server class platform "
  1324                       SIZE_FORMAT, initial_heap_size());
  1326     } else {
  1327       // A minimum size was specified on the command line.  Be sure
  1328       // that the maximum size is consistent.
  1329       if (initial_heap_size() > reasonable_max) {
  1330         reasonable_max = initial_heap_size();
  1333     FLAG_SET_ERGO(uintx, MaxHeapSize, (uintx) reasonable_max);
  1337 // This must be called after ergonomics because we want bytecode rewriting
  1338 // if the server compiler is used, or if UseSharedSpaces is disabled.
  1339 void Arguments::set_bytecode_flags() {
  1340   // Better not attempt to store into a read-only space.
  1341   if (UseSharedSpaces) {
  1342     FLAG_SET_DEFAULT(RewriteBytecodes, false);
  1343     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
  1346   if (!RewriteBytecodes) {
  1347     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
  1351 // Aggressive optimization flags  -XX:+AggressiveOpts
  1352 void Arguments::set_aggressive_opts_flags() {
  1353 #ifdef COMPILER2
  1354   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
  1355     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
  1356       FLAG_SET_DEFAULT(EliminateAutoBox, true);
  1358     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
  1359       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
  1362     // Feed the cache size setting into the JDK
  1363     char buffer[1024];
  1364     sprintf(buffer, "java.lang.Integer.IntegerCache.high=%d", AutoBoxCacheMax);
  1365     add_property(buffer);
  1367   if (AggressiveOpts && FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
  1368     FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
  1370   if (AggressiveOpts && FLAG_IS_DEFAULT(SpecialArraysEquals)) {
  1371     FLAG_SET_DEFAULT(SpecialArraysEquals, true);
  1373   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
  1374     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
  1376 #endif
  1378   if (AggressiveOpts) {
  1379 // Sample flag setting code
  1380 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
  1381 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
  1382 //    }
  1386 //===========================================================================================================
  1387 // Parsing of java.compiler property
  1389 void Arguments::process_java_compiler_argument(char* arg) {
  1390   // For backwards compatibility, Djava.compiler=NONE or ""
  1391   // causes us to switch to -Xint mode UNLESS -Xdebug
  1392   // is also specified.
  1393   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
  1394     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
  1398 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
  1399   _sun_java_launcher = strdup(launcher);
  1402 bool Arguments::created_by_java_launcher() {
  1403   assert(_sun_java_launcher != NULL, "property must have value");
  1404   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
  1407 //===========================================================================================================
  1408 // Parsing of main arguments
  1410 bool Arguments::verify_percentage(uintx value, const char* name) {
  1411   if (value <= 100) {
  1412     return true;
  1414   jio_fprintf(defaultStream::error_stream(),
  1415               "%s of " UINTX_FORMAT " is invalid; must be between 0 and 100\n",
  1416               name, value);
  1417   return false;
  1420 static void set_serial_gc_flags() {
  1421   FLAG_SET_DEFAULT(UseSerialGC, true);
  1422   FLAG_SET_DEFAULT(UseParNewGC, false);
  1423   FLAG_SET_DEFAULT(UseConcMarkSweepGC, false);
  1424   FLAG_SET_DEFAULT(UseParallelGC, false);
  1425   FLAG_SET_DEFAULT(UseParallelOldGC, false);
  1426   FLAG_SET_DEFAULT(UseG1GC, false);
  1429 static bool verify_serial_gc_flags() {
  1430   return (UseSerialGC &&
  1431         !(UseParNewGC || UseConcMarkSweepGC || UseG1GC ||
  1432           UseParallelGC || UseParallelOldGC));
  1435 // Check consistency of GC selection
  1436 bool Arguments::check_gc_consistency() {
  1437   bool status = true;
  1438   // Ensure that the user has not selected conflicting sets
  1439   // of collectors. [Note: this check is merely a user convenience;
  1440   // collectors over-ride each other so that only a non-conflicting
  1441   // set is selected; however what the user gets is not what they
  1442   // may have expected from the combination they asked for. It's
  1443   // better to reduce user confusion by not allowing them to
  1444   // select conflicting combinations.
  1445   uint i = 0;
  1446   if (UseSerialGC)                       i++;
  1447   if (UseConcMarkSweepGC || UseParNewGC) i++;
  1448   if (UseParallelGC || UseParallelOldGC) i++;
  1449   if (i > 1) {
  1450     jio_fprintf(defaultStream::error_stream(),
  1451                 "Conflicting collector combinations in option list; "
  1452                 "please refer to the release notes for the combinations "
  1453                 "allowed\n");
  1454     status = false;
  1457   return status;
  1460 // Check the consistency of vm_init_args
  1461 bool Arguments::check_vm_args_consistency() {
  1462   // Method for adding checks for flag consistency.
  1463   // The intent is to warn the user of all possible conflicts,
  1464   // before returning an error.
  1465   // Note: Needs platform-dependent factoring.
  1466   bool status = true;
  1468 #if ( (defined(COMPILER2) && defined(SPARC)))
  1469   // NOTE: The call to VM_Version_init depends on the fact that VM_Version_init
  1470   // on sparc doesn't require generation of a stub as is the case on, e.g.,
  1471   // x86.  Normally, VM_Version_init must be called from init_globals in
  1472   // init.cpp, which is called by the initial java thread *after* arguments
  1473   // have been parsed.  VM_Version_init gets called twice on sparc.
  1474   extern void VM_Version_init();
  1475   VM_Version_init();
  1476   if (!VM_Version::has_v9()) {
  1477     jio_fprintf(defaultStream::error_stream(),
  1478                 "V8 Machine detected, Server requires V9\n");
  1479     status = false;
  1481 #endif /* COMPILER2 && SPARC */
  1483   // Allow both -XX:-UseStackBanging and -XX:-UseBoundThreads in non-product
  1484   // builds so the cost of stack banging can be measured.
  1485 #if (defined(PRODUCT) && defined(SOLARIS))
  1486   if (!UseBoundThreads && !UseStackBanging) {
  1487     jio_fprintf(defaultStream::error_stream(),
  1488                 "-UseStackBanging conflicts with -UseBoundThreads\n");
  1490      status = false;
  1492 #endif
  1494   if (TLABRefillWasteFraction == 0) {
  1495     jio_fprintf(defaultStream::error_stream(),
  1496                 "TLABRefillWasteFraction should be a denominator, "
  1497                 "not " SIZE_FORMAT "\n",
  1498                 TLABRefillWasteFraction);
  1499     status = false;
  1502   status = status && verify_percentage(MaxLiveObjectEvacuationRatio,
  1503                               "MaxLiveObjectEvacuationRatio");
  1504   status = status && verify_percentage(AdaptiveSizePolicyWeight,
  1505                               "AdaptiveSizePolicyWeight");
  1506   status = status && verify_percentage(AdaptivePermSizeWeight, "AdaptivePermSizeWeight");
  1507   status = status && verify_percentage(ThresholdTolerance, "ThresholdTolerance");
  1508   status = status && verify_percentage(MinHeapFreeRatio, "MinHeapFreeRatio");
  1509   status = status && verify_percentage(MaxHeapFreeRatio, "MaxHeapFreeRatio");
  1511   if (MinHeapFreeRatio > MaxHeapFreeRatio) {
  1512     jio_fprintf(defaultStream::error_stream(),
  1513                 "MinHeapFreeRatio (" UINTX_FORMAT ") must be less than or "
  1514                 "equal to MaxHeapFreeRatio (" UINTX_FORMAT ")\n",
  1515                 MinHeapFreeRatio, MaxHeapFreeRatio);
  1516     status = false;
  1518   // Keeping the heap 100% free is hard ;-) so limit it to 99%.
  1519   MinHeapFreeRatio = MIN2(MinHeapFreeRatio, (uintx) 99);
  1521   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
  1522     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
  1525   if (UseParallelOldGC && ParallelOldGCSplitALot) {
  1526     // Settings to encourage splitting.
  1527     if (!FLAG_IS_CMDLINE(NewRatio)) {
  1528       FLAG_SET_CMDLINE(intx, NewRatio, 2);
  1530     if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
  1531       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
  1535   status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit");
  1536   status = status && verify_percentage(GCTimeLimit, "GCTimeLimit");
  1537   if (GCTimeLimit == 100) {
  1538     // Turn off gc-overhead-limit-exceeded checks
  1539     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
  1542   status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit");
  1544   // Check user specified sharing option conflict with Parallel GC
  1545   bool cannot_share = (UseConcMarkSweepGC || UseG1GC || UseParNewGC ||
  1546                        UseParallelGC || UseParallelOldGC ||
  1547                        SOLARIS_ONLY(UseISM) NOT_SOLARIS(UseLargePages));
  1549   if (cannot_share) {
  1550     // Either force sharing on by forcing the other options off, or
  1551     // force sharing off.
  1552     if (DumpSharedSpaces || ForceSharedSpaces) {
  1553       set_serial_gc_flags();
  1554       FLAG_SET_DEFAULT(SOLARIS_ONLY(UseISM) NOT_SOLARIS(UseLargePages), false);
  1555     } else {
  1556       no_shared_spaces();
  1560   status = status && check_gc_consistency();
  1562   if (_has_alloc_profile) {
  1563     if (UseParallelGC || UseParallelOldGC) {
  1564       jio_fprintf(defaultStream::error_stream(),
  1565                   "error:  invalid argument combination.\n"
  1566                   "Allocation profiling (-Xaprof) cannot be used together with "
  1567                   "Parallel GC (-XX:+UseParallelGC or -XX:+UseParallelOldGC).\n");
  1568       status = false;
  1570     if (UseConcMarkSweepGC) {
  1571       jio_fprintf(defaultStream::error_stream(),
  1572                   "error:  invalid argument combination.\n"
  1573                   "Allocation profiling (-Xaprof) cannot be used together with "
  1574                   "the CMS collector (-XX:+UseConcMarkSweepGC).\n");
  1575       status = false;
  1579   if (CMSIncrementalMode) {
  1580     if (!UseConcMarkSweepGC) {
  1581       jio_fprintf(defaultStream::error_stream(),
  1582                   "error:  invalid argument combination.\n"
  1583                   "The CMS collector (-XX:+UseConcMarkSweepGC) must be "
  1584                   "selected in order\nto use CMSIncrementalMode.\n");
  1585       status = false;
  1586     } else {
  1587       status = status && verify_percentage(CMSIncrementalDutyCycle,
  1588                                   "CMSIncrementalDutyCycle");
  1589       status = status && verify_percentage(CMSIncrementalDutyCycleMin,
  1590                                   "CMSIncrementalDutyCycleMin");
  1591       status = status && verify_percentage(CMSIncrementalSafetyFactor,
  1592                                   "CMSIncrementalSafetyFactor");
  1593       status = status && verify_percentage(CMSIncrementalOffset,
  1594                                   "CMSIncrementalOffset");
  1595       status = status && verify_percentage(CMSExpAvgFactor,
  1596                                   "CMSExpAvgFactor");
  1597       // If it was not set on the command line, set
  1598       // CMSInitiatingOccupancyFraction to 1 so icms can initiate cycles early.
  1599       if (CMSInitiatingOccupancyFraction < 0) {
  1600         FLAG_SET_DEFAULT(CMSInitiatingOccupancyFraction, 1);
  1605   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
  1606   // insists that we hold the requisite locks so that the iteration is
  1607   // MT-safe. For the verification at start-up and shut-down, we don't
  1608   // yet have a good way of acquiring and releasing these locks,
  1609   // which are not visible at the CollectedHeap level. We want to
  1610   // be able to acquire these locks and then do the iteration rather
  1611   // than just disable the lock verification. This will be fixed under
  1612   // bug 4788986.
  1613   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
  1614     if (VerifyGCStartAt == 0) {
  1615       warning("Heap verification at start-up disabled "
  1616               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
  1617       VerifyGCStartAt = 1;      // Disable verification at start-up
  1619     if (VerifyBeforeExit) {
  1620       warning("Heap verification at shutdown disabled "
  1621               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
  1622       VerifyBeforeExit = false; // Disable verification at shutdown
  1626   // Note: only executed in non-PRODUCT mode
  1627   if (!UseAsyncConcMarkSweepGC &&
  1628       (ExplicitGCInvokesConcurrent ||
  1629        ExplicitGCInvokesConcurrentAndUnloadsClasses)) {
  1630     jio_fprintf(defaultStream::error_stream(),
  1631                 "error: +ExplictGCInvokesConcurrent[AndUnloadsClasses] conflicts"
  1632                 " with -UseAsyncConcMarkSweepGC");
  1633     status = false;
  1636   return status;
  1639 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
  1640   const char* option_type) {
  1641   if (ignore) return false;
  1643   const char* spacer = " ";
  1644   if (option_type == NULL) {
  1645     option_type = ++spacer; // Set both to the empty string.
  1648   if (os::obsolete_option(option)) {
  1649     jio_fprintf(defaultStream::error_stream(),
  1650                 "Obsolete %s%soption: %s\n", option_type, spacer,
  1651       option->optionString);
  1652     return false;
  1653   } else {
  1654     jio_fprintf(defaultStream::error_stream(),
  1655                 "Unrecognized %s%soption: %s\n", option_type, spacer,
  1656       option->optionString);
  1657     return true;
  1661 static const char* user_assertion_options[] = {
  1662   "-da", "-ea", "-disableassertions", "-enableassertions", 0
  1663 };
  1665 static const char* system_assertion_options[] = {
  1666   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
  1667 };
  1669 // Return true if any of the strings in null-terminated array 'names' matches.
  1670 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
  1671 // the option must match exactly.
  1672 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
  1673   bool tail_allowed) {
  1674   for (/* empty */; *names != NULL; ++names) {
  1675     if (match_option(option, *names, tail)) {
  1676       if (**tail == '\0' || tail_allowed && **tail == ':') {
  1677         return true;
  1681   return false;
  1684 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
  1685                                                   julong* long_arg,
  1686                                                   julong min_size) {
  1687   if (!atomull(s, long_arg)) return arg_unreadable;
  1688   return check_memory_size(*long_arg, min_size);
  1691 // Parse JavaVMInitArgs structure
  1693 jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {
  1694   // For components of the system classpath.
  1695   SysClassPath scp(Arguments::get_sysclasspath());
  1696   bool scp_assembly_required = false;
  1698   // Save default settings for some mode flags
  1699   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
  1700   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
  1701   Arguments::_ClipInlining             = ClipInlining;
  1702   Arguments::_BackgroundCompilation    = BackgroundCompilation;
  1703   Arguments::_Tier2CompileThreshold    = Tier2CompileThreshold;
  1705   // Parse JAVA_TOOL_OPTIONS environment variable (if present)
  1706   jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);
  1707   if (result != JNI_OK) {
  1708     return result;
  1711   // Parse JavaVMInitArgs structure passed in
  1712   result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, COMMAND_LINE);
  1713   if (result != JNI_OK) {
  1714     return result;
  1717   // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
  1718   result = parse_java_options_environment_variable(&scp, &scp_assembly_required);
  1719   if (result != JNI_OK) {
  1720     return result;
  1723   // Do final processing now that all arguments have been parsed
  1724   result = finalize_vm_init_args(&scp, scp_assembly_required);
  1725   if (result != JNI_OK) {
  1726     return result;
  1729   return JNI_OK;
  1733 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
  1734                                        SysClassPath* scp_p,
  1735                                        bool* scp_assembly_required_p,
  1736                                        FlagValueOrigin origin) {
  1737   // Remaining part of option string
  1738   const char* tail;
  1740   // iterate over arguments
  1741   for (int index = 0; index < args->nOptions; index++) {
  1742     bool is_absolute_path = false;  // for -agentpath vs -agentlib
  1744     const JavaVMOption* option = args->options + index;
  1746     if (!match_option(option, "-Djava.class.path", &tail) &&
  1747         !match_option(option, "-Dsun.java.command", &tail) &&
  1748         !match_option(option, "-Dsun.java.launcher", &tail)) {
  1750         // add all jvm options to the jvm_args string. This string
  1751         // is used later to set the java.vm.args PerfData string constant.
  1752         // the -Djava.class.path and the -Dsun.java.command options are
  1753         // omitted from jvm_args string as each have their own PerfData
  1754         // string constant object.
  1755         build_jvm_args(option->optionString);
  1758     // -verbose:[class/gc/jni]
  1759     if (match_option(option, "-verbose", &tail)) {
  1760       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
  1761         FLAG_SET_CMDLINE(bool, TraceClassLoading, true);
  1762         FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);
  1763       } else if (!strcmp(tail, ":gc")) {
  1764         FLAG_SET_CMDLINE(bool, PrintGC, true);
  1765         FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);
  1766       } else if (!strcmp(tail, ":jni")) {
  1767         FLAG_SET_CMDLINE(bool, PrintJNIResolving, true);
  1769     // -da / -ea / -disableassertions / -enableassertions
  1770     // These accept an optional class/package name separated by a colon, e.g.,
  1771     // -da:java.lang.Thread.
  1772     } else if (match_option(option, user_assertion_options, &tail, true)) {
  1773       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
  1774       if (*tail == '\0') {
  1775         JavaAssertions::setUserClassDefault(enable);
  1776       } else {
  1777         assert(*tail == ':', "bogus match by match_option()");
  1778         JavaAssertions::addOption(tail + 1, enable);
  1780     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
  1781     } else if (match_option(option, system_assertion_options, &tail, false)) {
  1782       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
  1783       JavaAssertions::setSystemClassDefault(enable);
  1784     // -bootclasspath:
  1785     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
  1786       scp_p->reset_path(tail);
  1787       *scp_assembly_required_p = true;
  1788     // -bootclasspath/a:
  1789     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
  1790       scp_p->add_suffix(tail);
  1791       *scp_assembly_required_p = true;
  1792     // -bootclasspath/p:
  1793     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
  1794       scp_p->add_prefix(tail);
  1795       *scp_assembly_required_p = true;
  1796     // -Xrun
  1797     } else if (match_option(option, "-Xrun", &tail)) {
  1798       if(tail != NULL) {
  1799         const char* pos = strchr(tail, ':');
  1800         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
  1801         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1), tail, len);
  1802         name[len] = '\0';
  1804         char *options = NULL;
  1805         if(pos != NULL) {
  1806           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
  1807           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2), pos+1, len2);
  1809 #ifdef JVMTI_KERNEL
  1810         if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
  1811           warning("profiling and debugging agents are not supported with Kernel VM");
  1812         } else
  1813 #endif // JVMTI_KERNEL
  1814         add_init_library(name, options);
  1816     // -agentlib and -agentpath
  1817     } else if (match_option(option, "-agentlib:", &tail) ||
  1818           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
  1819       if(tail != NULL) {
  1820         const char* pos = strchr(tail, '=');
  1821         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
  1822         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1), tail, len);
  1823         name[len] = '\0';
  1825         char *options = NULL;
  1826         if(pos != NULL) {
  1827           options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(pos + 1) + 1), pos + 1);
  1829 #ifdef JVMTI_KERNEL
  1830         if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
  1831           warning("profiling and debugging agents are not supported with Kernel VM");
  1832         } else
  1833 #endif // JVMTI_KERNEL
  1834         add_init_agent(name, options, is_absolute_path);
  1837     // -javaagent
  1838     } else if (match_option(option, "-javaagent:", &tail)) {
  1839       if(tail != NULL) {
  1840         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1), tail);
  1841         add_init_agent("instrument", options, false);
  1843     // -Xnoclassgc
  1844     } else if (match_option(option, "-Xnoclassgc", &tail)) {
  1845       FLAG_SET_CMDLINE(bool, ClassUnloading, false);
  1846     // -Xincgc: i-CMS
  1847     } else if (match_option(option, "-Xincgc", &tail)) {
  1848       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
  1849       FLAG_SET_CMDLINE(bool, CMSIncrementalMode, true);
  1850     // -Xnoincgc: no i-CMS
  1851     } else if (match_option(option, "-Xnoincgc", &tail)) {
  1852       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
  1853       FLAG_SET_CMDLINE(bool, CMSIncrementalMode, false);
  1854     // -Xconcgc
  1855     } else if (match_option(option, "-Xconcgc", &tail)) {
  1856       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
  1857     // -Xnoconcgc
  1858     } else if (match_option(option, "-Xnoconcgc", &tail)) {
  1859       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
  1860     // -Xbatch
  1861     } else if (match_option(option, "-Xbatch", &tail)) {
  1862       FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
  1863     // -Xmn for compatibility with other JVM vendors
  1864     } else if (match_option(option, "-Xmn", &tail)) {
  1865       julong long_initial_eden_size = 0;
  1866       ArgsRange errcode = parse_memory_size(tail, &long_initial_eden_size, 1);
  1867       if (errcode != arg_in_range) {
  1868         jio_fprintf(defaultStream::error_stream(),
  1869                     "Invalid initial eden size: %s\n", option->optionString);
  1870         describe_range_error(errcode);
  1871         return JNI_EINVAL;
  1873       FLAG_SET_CMDLINE(uintx, MaxNewSize, (size_t) long_initial_eden_size);
  1874       FLAG_SET_CMDLINE(uintx, NewSize, (size_t) long_initial_eden_size);
  1875     // -Xms
  1876     } else if (match_option(option, "-Xms", &tail)) {
  1877       julong long_initial_heap_size = 0;
  1878       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 1);
  1879       if (errcode != arg_in_range) {
  1880         jio_fprintf(defaultStream::error_stream(),
  1881                     "Invalid initial heap size: %s\n", option->optionString);
  1882         describe_range_error(errcode);
  1883         return JNI_EINVAL;
  1885       set_initial_heap_size((size_t) long_initial_heap_size);
  1886       // Currently the minimum size and the initial heap sizes are the same.
  1887       set_min_heap_size(initial_heap_size());
  1888     // -Xmx
  1889     } else if (match_option(option, "-Xmx", &tail)) {
  1890       julong long_max_heap_size = 0;
  1891       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
  1892       if (errcode != arg_in_range) {
  1893         jio_fprintf(defaultStream::error_stream(),
  1894                     "Invalid maximum heap size: %s\n", option->optionString);
  1895         describe_range_error(errcode);
  1896         return JNI_EINVAL;
  1898       FLAG_SET_CMDLINE(uintx, MaxHeapSize, (size_t) long_max_heap_size);
  1899     // Xmaxf
  1900     } else if (match_option(option, "-Xmaxf", &tail)) {
  1901       int maxf = (int)(atof(tail) * 100);
  1902       if (maxf < 0 || maxf > 100) {
  1903         jio_fprintf(defaultStream::error_stream(),
  1904                     "Bad max heap free percentage size: %s\n",
  1905                     option->optionString);
  1906         return JNI_EINVAL;
  1907       } else {
  1908         FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf);
  1910     // Xminf
  1911     } else if (match_option(option, "-Xminf", &tail)) {
  1912       int minf = (int)(atof(tail) * 100);
  1913       if (minf < 0 || minf > 100) {
  1914         jio_fprintf(defaultStream::error_stream(),
  1915                     "Bad min heap free percentage size: %s\n",
  1916                     option->optionString);
  1917         return JNI_EINVAL;
  1918       } else {
  1919         FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf);
  1921     // -Xss
  1922     } else if (match_option(option, "-Xss", &tail)) {
  1923       julong long_ThreadStackSize = 0;
  1924       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
  1925       if (errcode != arg_in_range) {
  1926         jio_fprintf(defaultStream::error_stream(),
  1927                     "Invalid thread stack size: %s\n", option->optionString);
  1928         describe_range_error(errcode);
  1929         return JNI_EINVAL;
  1931       // Internally track ThreadStackSize in units of 1024 bytes.
  1932       FLAG_SET_CMDLINE(intx, ThreadStackSize,
  1933                               round_to((int)long_ThreadStackSize, K) / K);
  1934     // -Xoss
  1935     } else if (match_option(option, "-Xoss", &tail)) {
  1936           // HotSpot does not have separate native and Java stacks, ignore silently for compatibility
  1937     // -Xmaxjitcodesize
  1938     } else if (match_option(option, "-Xmaxjitcodesize", &tail)) {
  1939       julong long_ReservedCodeCacheSize = 0;
  1940       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize,
  1941                                             (size_t)InitialCodeCacheSize);
  1942       if (errcode != arg_in_range) {
  1943         jio_fprintf(defaultStream::error_stream(),
  1944                     "Invalid maximum code cache size: %s\n",
  1945                     option->optionString);
  1946         describe_range_error(errcode);
  1947         return JNI_EINVAL;
  1949       FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize);
  1950     // -green
  1951     } else if (match_option(option, "-green", &tail)) {
  1952       jio_fprintf(defaultStream::error_stream(),
  1953                   "Green threads support not available\n");
  1954           return JNI_EINVAL;
  1955     // -native
  1956     } else if (match_option(option, "-native", &tail)) {
  1957           // HotSpot always uses native threads, ignore silently for compatibility
  1958     // -Xsqnopause
  1959     } else if (match_option(option, "-Xsqnopause", &tail)) {
  1960           // EVM option, ignore silently for compatibility
  1961     // -Xrs
  1962     } else if (match_option(option, "-Xrs", &tail)) {
  1963           // Classic/EVM option, new functionality
  1964       FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true);
  1965     } else if (match_option(option, "-Xusealtsigs", &tail)) {
  1966           // change default internal VM signals used - lower case for back compat
  1967       FLAG_SET_CMDLINE(bool, UseAltSigs, true);
  1968     // -Xoptimize
  1969     } else if (match_option(option, "-Xoptimize", &tail)) {
  1970           // EVM option, ignore silently for compatibility
  1971     // -Xprof
  1972     } else if (match_option(option, "-Xprof", &tail)) {
  1973 #ifndef FPROF_KERNEL
  1974       _has_profile = true;
  1975 #else // FPROF_KERNEL
  1976       // do we have to exit?
  1977       warning("Kernel VM does not support flat profiling.");
  1978 #endif // FPROF_KERNEL
  1979     // -Xaprof
  1980     } else if (match_option(option, "-Xaprof", &tail)) {
  1981       _has_alloc_profile = true;
  1982     // -Xconcurrentio
  1983     } else if (match_option(option, "-Xconcurrentio", &tail)) {
  1984       FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true);
  1985       FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
  1986       FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1);
  1987       FLAG_SET_CMDLINE(bool, UseTLAB, false);
  1988       FLAG_SET_CMDLINE(uintx, NewSizeThreadIncrease, 16 * K);  // 20Kb per thread added to new generation
  1990       // -Xinternalversion
  1991     } else if (match_option(option, "-Xinternalversion", &tail)) {
  1992       jio_fprintf(defaultStream::output_stream(), "%s\n",
  1993                   VM_Version::internal_vm_info_string());
  1994       vm_exit(0);
  1995 #ifndef PRODUCT
  1996     // -Xprintflags
  1997     } else if (match_option(option, "-Xprintflags", &tail)) {
  1998       CommandLineFlags::printFlags();
  1999       vm_exit(0);
  2000 #endif
  2001     // -D
  2002     } else if (match_option(option, "-D", &tail)) {
  2003       if (!add_property(tail)) {
  2004         return JNI_ENOMEM;
  2006       // Out of the box management support
  2007       if (match_option(option, "-Dcom.sun.management", &tail)) {
  2008         FLAG_SET_CMDLINE(bool, ManagementServer, true);
  2010     // -Xint
  2011     } else if (match_option(option, "-Xint", &tail)) {
  2012           set_mode_flags(_int);
  2013     // -Xmixed
  2014     } else if (match_option(option, "-Xmixed", &tail)) {
  2015           set_mode_flags(_mixed);
  2016     // -Xcomp
  2017     } else if (match_option(option, "-Xcomp", &tail)) {
  2018       // for testing the compiler; turn off all flags that inhibit compilation
  2019           set_mode_flags(_comp);
  2021     // -Xshare:dump
  2022     } else if (match_option(option, "-Xshare:dump", &tail)) {
  2023 #ifdef TIERED
  2024       FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);
  2025       set_mode_flags(_int);     // Prevent compilation, which creates objects
  2026 #elif defined(COMPILER2)
  2027       vm_exit_during_initialization(
  2028           "Dumping a shared archive is not supported on the Server JVM.", NULL);
  2029 #elif defined(KERNEL)
  2030       vm_exit_during_initialization(
  2031           "Dumping a shared archive is not supported on the Kernel JVM.", NULL);
  2032 #else
  2033       FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);
  2034       set_mode_flags(_int);     // Prevent compilation, which creates objects
  2035 #endif
  2036     // -Xshare:on
  2037     } else if (match_option(option, "-Xshare:on", &tail)) {
  2038       FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
  2039       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
  2040 #ifdef TIERED
  2041       FLAG_SET_CMDLINE(bool, ForceSharedSpaces, true);
  2042 #endif // TIERED
  2043     // -Xshare:auto
  2044     } else if (match_option(option, "-Xshare:auto", &tail)) {
  2045       FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
  2046       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
  2047     // -Xshare:off
  2048     } else if (match_option(option, "-Xshare:off", &tail)) {
  2049       FLAG_SET_CMDLINE(bool, UseSharedSpaces, false);
  2050       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
  2052     // -Xverify
  2053     } else if (match_option(option, "-Xverify", &tail)) {
  2054       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
  2055         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true);
  2056         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
  2057       } else if (strcmp(tail, ":remote") == 0) {
  2058         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
  2059         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
  2060       } else if (strcmp(tail, ":none") == 0) {
  2061         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
  2062         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false);
  2063       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
  2064         return JNI_EINVAL;
  2066     // -Xdebug
  2067     } else if (match_option(option, "-Xdebug", &tail)) {
  2068       // note this flag has been used, then ignore
  2069       set_xdebug_mode(true);
  2070     // -Xnoagent
  2071     } else if (match_option(option, "-Xnoagent", &tail)) {
  2072       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
  2073     } else if (match_option(option, "-Xboundthreads", &tail)) {
  2074       // Bind user level threads to kernel threads (Solaris only)
  2075       FLAG_SET_CMDLINE(bool, UseBoundThreads, true);
  2076     } else if (match_option(option, "-Xloggc:", &tail)) {
  2077       // Redirect GC output to the file. -Xloggc:<filename>
  2078       // ostream_init_log(), when called will use this filename
  2079       // to initialize a fileStream.
  2080       _gc_log_filename = strdup(tail);
  2081       FLAG_SET_CMDLINE(bool, PrintGC, true);
  2082       FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true);
  2083       FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);
  2085     // JNI hooks
  2086     } else if (match_option(option, "-Xcheck", &tail)) {
  2087       if (!strcmp(tail, ":jni")) {
  2088         CheckJNICalls = true;
  2089       } else if (is_bad_option(option, args->ignoreUnrecognized,
  2090                                      "check")) {
  2091         return JNI_EINVAL;
  2093     } else if (match_option(option, "vfprintf", &tail)) {
  2094       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
  2095     } else if (match_option(option, "exit", &tail)) {
  2096       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
  2097     } else if (match_option(option, "abort", &tail)) {
  2098       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
  2099     // -XX:+AggressiveHeap
  2100     } else if (match_option(option, "-XX:+AggressiveHeap", &tail)) {
  2102       // This option inspects the machine and attempts to set various
  2103       // parameters to be optimal for long-running, memory allocation
  2104       // intensive jobs.  It is intended for machines with large
  2105       // amounts of cpu and memory.
  2107       // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
  2108       // VM, but we may not be able to represent the total physical memory
  2109       // available (like having 8gb of memory on a box but using a 32bit VM).
  2110       // Thus, we need to make sure we're using a julong for intermediate
  2111       // calculations.
  2112       julong initHeapSize;
  2113       julong total_memory = os::physical_memory();
  2115       if (total_memory < (julong)256*M) {
  2116         jio_fprintf(defaultStream::error_stream(),
  2117                     "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
  2118         vm_exit(1);
  2121       // The heap size is half of available memory, or (at most)
  2122       // all of possible memory less 160mb (leaving room for the OS
  2123       // when using ISM).  This is the maximum; because adaptive sizing
  2124       // is turned on below, the actual space used may be smaller.
  2126       initHeapSize = MIN2(total_memory / (julong)2,
  2127                           total_memory - (julong)160*M);
  2129       // Make sure that if we have a lot of memory we cap the 32 bit
  2130       // process space.  The 64bit VM version of this function is a nop.
  2131       initHeapSize = os::allocatable_physical_memory(initHeapSize);
  2133       // The perm gen is separate but contiguous with the
  2134       // object heap (and is reserved with it) so subtract it
  2135       // from the heap size.
  2136       if (initHeapSize > MaxPermSize) {
  2137         initHeapSize = initHeapSize - MaxPermSize;
  2138       } else {
  2139         warning("AggressiveHeap and MaxPermSize values may conflict");
  2142       if (FLAG_IS_DEFAULT(MaxHeapSize)) {
  2143          FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);
  2144          set_initial_heap_size(MaxHeapSize);
  2145          // Currently the minimum size and the initial heap sizes are the same.
  2146          set_min_heap_size(initial_heap_size());
  2148       if (FLAG_IS_DEFAULT(NewSize)) {
  2149          // Make the young generation 3/8ths of the total heap.
  2150          FLAG_SET_CMDLINE(uintx, NewSize,
  2151                                 ((julong)MaxHeapSize / (julong)8) * (julong)3);
  2152          FLAG_SET_CMDLINE(uintx, MaxNewSize, NewSize);
  2155       FLAG_SET_DEFAULT(UseLargePages, true);
  2157       // Increase some data structure sizes for efficiency
  2158       FLAG_SET_CMDLINE(uintx, BaseFootPrintEstimate, MaxHeapSize);
  2159       FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
  2160       FLAG_SET_CMDLINE(uintx, TLABSize, 256*K);
  2162       // See the OldPLABSize comment below, but replace 'after promotion'
  2163       // with 'after copying'.  YoungPLABSize is the size of the survivor
  2164       // space per-gc-thread buffers.  The default is 4kw.
  2165       FLAG_SET_CMDLINE(uintx, YoungPLABSize, 256*K);      // Note: this is in words
  2167       // OldPLABSize is the size of the buffers in the old gen that
  2168       // UseParallelGC uses to promote live data that doesn't fit in the
  2169       // survivor spaces.  At any given time, there's one for each gc thread.
  2170       // The default size is 1kw. These buffers are rarely used, since the
  2171       // survivor spaces are usually big enough.  For specjbb, however, there
  2172       // are occasions when there's lots of live data in the young gen
  2173       // and we end up promoting some of it.  We don't have a definite
  2174       // explanation for why bumping OldPLABSize helps, but the theory
  2175       // is that a bigger PLAB results in retaining something like the
  2176       // original allocation order after promotion, which improves mutator
  2177       // locality.  A minor effect may be that larger PLABs reduce the
  2178       // number of PLAB allocation events during gc.  The value of 8kw
  2179       // was arrived at by experimenting with specjbb.
  2180       FLAG_SET_CMDLINE(uintx, OldPLABSize, 8*K);  // Note: this is in words
  2182       // CompilationPolicyChoice=0 causes the server compiler to adopt
  2183       // a more conservative which-method-do-I-compile policy when one
  2184       // of the counters maintained by the interpreter trips.  The
  2185       // result is reduced startup time and improved specjbb and
  2186       // alacrity performance.  Zero is the default, but we set it
  2187       // explicitly here in case the default changes.
  2188       // See runtime/compilationPolicy.*.
  2189       FLAG_SET_CMDLINE(intx, CompilationPolicyChoice, 0);
  2191       // Enable parallel GC and adaptive generation sizing
  2192       FLAG_SET_CMDLINE(bool, UseParallelGC, true);
  2193       FLAG_SET_DEFAULT(ParallelGCThreads,
  2194                        Abstract_VM_Version::parallel_worker_threads());
  2196       // Encourage steady state memory management
  2197       FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);
  2199       // This appears to improve mutator locality
  2200       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
  2202       // Get around early Solaris scheduling bug
  2203       // (affinity vs other jobs on system)
  2204       // but disallow DR and offlining (5008695).
  2205       FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);
  2207     } else if (match_option(option, "-XX:+NeverTenure", &tail)) {
  2208       // The last option must always win.
  2209       FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
  2210       FLAG_SET_CMDLINE(bool, NeverTenure, true);
  2211     } else if (match_option(option, "-XX:+AlwaysTenure", &tail)) {
  2212       // The last option must always win.
  2213       FLAG_SET_CMDLINE(bool, NeverTenure, false);
  2214       FLAG_SET_CMDLINE(bool, AlwaysTenure, true);
  2215     } else if (match_option(option, "-XX:+CMSPermGenSweepingEnabled", &tail) ||
  2216                match_option(option, "-XX:-CMSPermGenSweepingEnabled", &tail)) {
  2217       jio_fprintf(defaultStream::error_stream(),
  2218         "Please use CMSClassUnloadingEnabled in place of "
  2219         "CMSPermGenSweepingEnabled in the future\n");
  2220     } else if (match_option(option, "-XX:+UseGCTimeLimit", &tail)) {
  2221       FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, true);
  2222       jio_fprintf(defaultStream::error_stream(),
  2223         "Please use -XX:+UseGCOverheadLimit in place of "
  2224         "-XX:+UseGCTimeLimit in the future\n");
  2225     } else if (match_option(option, "-XX:-UseGCTimeLimit", &tail)) {
  2226       FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, false);
  2227       jio_fprintf(defaultStream::error_stream(),
  2228         "Please use -XX:-UseGCOverheadLimit in place of "
  2229         "-XX:-UseGCTimeLimit in the future\n");
  2230     // The TLE options are for compatibility with 1.3 and will be
  2231     // removed without notice in a future release.  These options
  2232     // are not to be documented.
  2233     } else if (match_option(option, "-XX:MaxTLERatio=", &tail)) {
  2234       // No longer used.
  2235     } else if (match_option(option, "-XX:+ResizeTLE", &tail)) {
  2236       FLAG_SET_CMDLINE(bool, ResizeTLAB, true);
  2237     } else if (match_option(option, "-XX:-ResizeTLE", &tail)) {
  2238       FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
  2239     } else if (match_option(option, "-XX:+PrintTLE", &tail)) {
  2240       FLAG_SET_CMDLINE(bool, PrintTLAB, true);
  2241     } else if (match_option(option, "-XX:-PrintTLE", &tail)) {
  2242       FLAG_SET_CMDLINE(bool, PrintTLAB, false);
  2243     } else if (match_option(option, "-XX:TLEFragmentationRatio=", &tail)) {
  2244       // No longer used.
  2245     } else if (match_option(option, "-XX:TLESize=", &tail)) {
  2246       julong long_tlab_size = 0;
  2247       ArgsRange errcode = parse_memory_size(tail, &long_tlab_size, 1);
  2248       if (errcode != arg_in_range) {
  2249         jio_fprintf(defaultStream::error_stream(),
  2250                     "Invalid TLAB size: %s\n", option->optionString);
  2251         describe_range_error(errcode);
  2252         return JNI_EINVAL;
  2254       FLAG_SET_CMDLINE(uintx, TLABSize, long_tlab_size);
  2255     } else if (match_option(option, "-XX:TLEThreadRatio=", &tail)) {
  2256       // No longer used.
  2257     } else if (match_option(option, "-XX:+UseTLE", &tail)) {
  2258       FLAG_SET_CMDLINE(bool, UseTLAB, true);
  2259     } else if (match_option(option, "-XX:-UseTLE", &tail)) {
  2260       FLAG_SET_CMDLINE(bool, UseTLAB, false);
  2261 SOLARIS_ONLY(
  2262     } else if (match_option(option, "-XX:+UsePermISM", &tail)) {
  2263       warning("-XX:+UsePermISM is obsolete.");
  2264       FLAG_SET_CMDLINE(bool, UseISM, true);
  2265     } else if (match_option(option, "-XX:-UsePermISM", &tail)) {
  2266       FLAG_SET_CMDLINE(bool, UseISM, false);
  2268     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr", &tail)) {
  2269       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false);
  2270       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true);
  2271     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout", &tail)) {
  2272       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false);
  2273       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true);
  2274     } else if (match_option(option, "-XX:+ExtendedDTraceProbes", &tail)) {
  2275 #ifdef SOLARIS
  2276       FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true);
  2277       FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true);
  2278       FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true);
  2279       FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true);
  2280 #else // ndef SOLARIS
  2281       jio_fprintf(defaultStream::error_stream(),
  2282                   "ExtendedDTraceProbes flag is only applicable on Solaris\n");
  2283       return JNI_EINVAL;
  2284 #endif // ndef SOLARIS
  2285     } else
  2286 #ifdef ASSERT
  2287     if (match_option(option, "-XX:+FullGCALot", &tail)) {
  2288       FLAG_SET_CMDLINE(bool, FullGCALot, true);
  2289       // disable scavenge before parallel mark-compact
  2290       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
  2291     } else
  2292 #endif
  2293     if (match_option(option, "-XX:ParCMSPromoteBlocksToClaim=", &tail)) {
  2294       julong cms_blocks_to_claim = (julong)atol(tail);
  2295       FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);
  2296       jio_fprintf(defaultStream::error_stream(),
  2297         "Please use -XX:CMSParPromoteBlocksToClaim in place of "
  2298         "-XX:ParCMSPromoteBlocksToClaim in the future\n");
  2299     } else
  2300     if (match_option(option, "-XX:ParallelGCOldGenAllocBufferSize=", &tail)) {
  2301       julong old_plab_size = 0;
  2302       ArgsRange errcode = parse_memory_size(tail, &old_plab_size, 1);
  2303       if (errcode != arg_in_range) {
  2304         jio_fprintf(defaultStream::error_stream(),
  2305                     "Invalid old PLAB size: %s\n", option->optionString);
  2306         describe_range_error(errcode);
  2307         return JNI_EINVAL;
  2309       FLAG_SET_CMDLINE(uintx, OldPLABSize, old_plab_size);
  2310       jio_fprintf(defaultStream::error_stream(),
  2311                   "Please use -XX:OldPLABSize in place of "
  2312                   "-XX:ParallelGCOldGenAllocBufferSize in the future\n");
  2313     } else
  2314     if (match_option(option, "-XX:ParallelGCToSpaceAllocBufferSize=", &tail)) {
  2315       julong young_plab_size = 0;
  2316       ArgsRange errcode = parse_memory_size(tail, &young_plab_size, 1);
  2317       if (errcode != arg_in_range) {
  2318         jio_fprintf(defaultStream::error_stream(),
  2319                     "Invalid young PLAB size: %s\n", option->optionString);
  2320         describe_range_error(errcode);
  2321         return JNI_EINVAL;
  2323       FLAG_SET_CMDLINE(uintx, YoungPLABSize, young_plab_size);
  2324       jio_fprintf(defaultStream::error_stream(),
  2325                   "Please use -XX:YoungPLABSize in place of "
  2326                   "-XX:ParallelGCToSpaceAllocBufferSize in the future\n");
  2327     } else
  2328     if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
  2329       // Skip -XX:Flags= since that case has already been handled
  2330       if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
  2331         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
  2332           return JNI_EINVAL;
  2335     // Unknown option
  2336     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
  2337       return JNI_ERR;
  2340   // Change the default value for flags  which have different default values
  2341   // when working with older JDKs.
  2342   if (JDK_Version::current().compare_major(6) <= 0 &&
  2343       FLAG_IS_DEFAULT(UseVMInterruptibleIO)) {
  2344     FLAG_SET_DEFAULT(UseVMInterruptibleIO, true);
  2346   return JNI_OK;
  2349 jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
  2350   // This must be done after all -D arguments have been processed.
  2351   scp_p->expand_endorsed();
  2353   if (scp_assembly_required || scp_p->get_endorsed() != NULL) {
  2354     // Assemble the bootclasspath elements into the final path.
  2355     Arguments::set_sysclasspath(scp_p->combined_path());
  2358   // This must be done after all arguments have been processed.
  2359   // java_compiler() true means set to "NONE" or empty.
  2360   if (java_compiler() && !xdebug_mode()) {
  2361     // For backwards compatibility, we switch to interpreted mode if
  2362     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
  2363     // not specified.
  2364     set_mode_flags(_int);
  2366   if (CompileThreshold == 0) {
  2367     set_mode_flags(_int);
  2370 #ifdef TIERED
  2371   // If we are using tiered compilation in the tiered vm then c1 will
  2372   // do the profiling and we don't want to waste that time in the
  2373   // interpreter.
  2374   if (TieredCompilation) {
  2375     ProfileInterpreter = false;
  2376   } else {
  2377     // Since we are running vanilla server we must adjust the compile threshold
  2378     // unless the user has already adjusted it because the default threshold assumes
  2379     // we will run tiered.
  2381     if (FLAG_IS_DEFAULT(CompileThreshold)) {
  2382       CompileThreshold = Tier2CompileThreshold;
  2385 #endif // TIERED
  2387 #ifndef COMPILER2
  2388   // Don't degrade server performance for footprint
  2389   if (FLAG_IS_DEFAULT(UseLargePages) &&
  2390       MaxHeapSize < LargePageHeapSizeThreshold) {
  2391     // No need for large granularity pages w/small heaps.
  2392     // Note that large pages are enabled/disabled for both the
  2393     // Java heap and the code cache.
  2394     FLAG_SET_DEFAULT(UseLargePages, false);
  2395     SOLARIS_ONLY(FLAG_SET_DEFAULT(UseMPSS, false));
  2396     SOLARIS_ONLY(FLAG_SET_DEFAULT(UseISM, false));
  2399 #else
  2400   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
  2401     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
  2403   // Temporary disable bulk zeroing reduction with G1. See CR 6627983.
  2404   if (UseG1GC) {
  2405     FLAG_SET_DEFAULT(ReduceBulkZeroing, false);
  2407 #endif
  2409   if (!check_vm_args_consistency()) {
  2410     return JNI_ERR;
  2413   return JNI_OK;
  2416 jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
  2417   return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,
  2418                                             scp_assembly_required_p);
  2421 jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
  2422   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,
  2423                                             scp_assembly_required_p);
  2426 jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {
  2427   const int N_MAX_OPTIONS = 64;
  2428   const int OPTION_BUFFER_SIZE = 1024;
  2429   char buffer[OPTION_BUFFER_SIZE];
  2431   // The variable will be ignored if it exceeds the length of the buffer.
  2432   // Don't check this variable if user has special privileges
  2433   // (e.g. unix su command).
  2434   if (os::getenv(name, buffer, sizeof(buffer)) &&
  2435       !os::have_special_privileges()) {
  2436     JavaVMOption options[N_MAX_OPTIONS];      // Construct option array
  2437     jio_fprintf(defaultStream::error_stream(),
  2438                 "Picked up %s: %s\n", name, buffer);
  2439     char* rd = buffer;                        // pointer to the input string (rd)
  2440     int i;
  2441     for (i = 0; i < N_MAX_OPTIONS;) {         // repeat for all options in the input string
  2442       while (isspace(*rd)) rd++;              // skip whitespace
  2443       if (*rd == 0) break;                    // we re done when the input string is read completely
  2445       // The output, option string, overwrites the input string.
  2446       // Because of quoting, the pointer to the option string (wrt) may lag the pointer to
  2447       // input string (rd).
  2448       char* wrt = rd;
  2450       options[i++].optionString = wrt;        // Fill in option
  2451       while (*rd != 0 && !isspace(*rd)) {     // unquoted strings terminate with a space or NULL
  2452         if (*rd == '\'' || *rd == '"') {      // handle a quoted string
  2453           int quote = *rd;                    // matching quote to look for
  2454           rd++;                               // don't copy open quote
  2455           while (*rd != quote) {              // include everything (even spaces) up until quote
  2456             if (*rd == 0) {                   // string termination means unmatched string
  2457               jio_fprintf(defaultStream::error_stream(),
  2458                           "Unmatched quote in %s\n", name);
  2459               return JNI_ERR;
  2461             *wrt++ = *rd++;                   // copy to option string
  2463           rd++;                               // don't copy close quote
  2464         } else {
  2465           *wrt++ = *rd++;                     // copy to option string
  2468       // Need to check if we're done before writing a NULL,
  2469       // because the write could be to the byte that rd is pointing to.
  2470       if (*rd++ == 0) {
  2471         *wrt = 0;
  2472         break;
  2474       *wrt = 0;                               // Zero terminate option
  2476     // Construct JavaVMInitArgs structure and parse as if it was part of the command line
  2477     JavaVMInitArgs vm_args;
  2478     vm_args.version = JNI_VERSION_1_2;
  2479     vm_args.options = options;
  2480     vm_args.nOptions = i;
  2481     vm_args.ignoreUnrecognized = false;
  2483     if (PrintVMOptions) {
  2484       const char* tail;
  2485       for (int i = 0; i < vm_args.nOptions; i++) {
  2486         const JavaVMOption *option = vm_args.options + i;
  2487         if (match_option(option, "-XX:", &tail)) {
  2488           logOption(tail);
  2493     return(parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p, ENVIRON_VAR));
  2495   return JNI_OK;
  2498 // Parse entry point called from JNI_CreateJavaVM
  2500 jint Arguments::parse(const JavaVMInitArgs* args) {
  2502   // Sharing support
  2503   // Construct the path to the archive
  2504   char jvm_path[JVM_MAXPATHLEN];
  2505   os::jvm_path(jvm_path, sizeof(jvm_path));
  2506 #ifdef TIERED
  2507   if (strstr(jvm_path, "client") != NULL) {
  2508     force_client_mode = true;
  2510 #endif // TIERED
  2511   char *end = strrchr(jvm_path, *os::file_separator());
  2512   if (end != NULL) *end = '\0';
  2513   char *shared_archive_path = NEW_C_HEAP_ARRAY(char, strlen(jvm_path) +
  2514                                         strlen(os::file_separator()) + 20);
  2515   if (shared_archive_path == NULL) return JNI_ENOMEM;
  2516   strcpy(shared_archive_path, jvm_path);
  2517   strcat(shared_archive_path, os::file_separator());
  2518   strcat(shared_archive_path, "classes");
  2519   DEBUG_ONLY(strcat(shared_archive_path, "_g");)
  2520   strcat(shared_archive_path, ".jsa");
  2521   SharedArchivePath = shared_archive_path;
  2523   // Remaining part of option string
  2524   const char* tail;
  2526   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
  2527   bool settings_file_specified = false;
  2528   int index;
  2529   for (index = 0; index < args->nOptions; index++) {
  2530     const JavaVMOption *option = args->options + index;
  2531     if (match_option(option, "-XX:Flags=", &tail)) {
  2532       if (!process_settings_file(tail, true, args->ignoreUnrecognized)) {
  2533         return JNI_EINVAL;
  2535       settings_file_specified = true;
  2537     if (match_option(option, "-XX:+PrintVMOptions", &tail)) {
  2538       PrintVMOptions = true;
  2540     if (match_option(option, "-XX:-PrintVMOptions", &tail)) {
  2541       PrintVMOptions = false;
  2545   // Parse default .hotspotrc settings file
  2546   if (!settings_file_specified) {
  2547     if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
  2548       return JNI_EINVAL;
  2552   if (PrintVMOptions) {
  2553     for (index = 0; index < args->nOptions; index++) {
  2554       const JavaVMOption *option = args->options + index;
  2555       if (match_option(option, "-XX:", &tail)) {
  2556         logOption(tail);
  2562   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
  2563   jint result = parse_vm_init_args(args);
  2564   if (result != JNI_OK) {
  2565     return result;
  2568   // These are hacks until G1 is fully supported and tested
  2569   // but lets you force -XX:+UseG1GC in PRT and get it where it (mostly) works
  2570   if (UseG1GC) {
  2571     if (UseConcMarkSweepGC || UseParNewGC || UseParallelGC || UseParallelOldGC || UseSerialGC) {
  2572 #ifndef PRODUCT
  2573       tty->print_cr("-XX:+UseG1GC is incompatible with other collectors, using UseG1GC");
  2574 #endif // PRODUCT
  2575       UseConcMarkSweepGC = false;
  2576       UseParNewGC        = false;
  2577       UseParallelGC      = false;
  2578       UseParallelOldGC   = false;
  2579       UseSerialGC        = false;
  2581     no_shared_spaces();
  2584 #ifndef PRODUCT
  2585   if (TraceBytecodesAt != 0) {
  2586     TraceBytecodes = true;
  2588   if (CountCompiledCalls) {
  2589     if (UseCounterDecay) {
  2590       warning("UseCounterDecay disabled because CountCalls is set");
  2591       UseCounterDecay = false;
  2594 #endif // PRODUCT
  2596   if (PrintGCDetails) {
  2597     // Turn on -verbose:gc options as well
  2598     PrintGC = true;
  2599     if (FLAG_IS_DEFAULT(TraceClassUnloading)) {
  2600       TraceClassUnloading = true;
  2604 #ifdef SERIALGC
  2605   set_serial_gc_flags();
  2606 #endif // SERIALGC
  2607 #ifdef KERNEL
  2608   no_shared_spaces();
  2609 #endif // KERNEL
  2611   // Set flags based on ergonomics.
  2612   set_ergonomics_flags();
  2614   // Check the GC selections again.
  2615   if (!check_gc_consistency()) {
  2616     return JNI_EINVAL;
  2619   if (UseParallelGC || UseParallelOldGC) {
  2620     // Set some flags for ParallelGC if needed.
  2621     set_parallel_gc_flags();
  2622   } else if (UseConcMarkSweepGC) {
  2623     // Set some flags for CMS
  2624     set_cms_and_parnew_gc_flags();
  2625   } else if (UseParNewGC) {
  2626     // Set some flags for ParNew
  2627     set_parnew_gc_flags();
  2629   // Temporary; make the "if" an "else-if" before
  2630   // we integrate G1. XXX
  2631   if (UseG1GC) {
  2632     // Set some flags for garbage-first, if needed.
  2633     set_g1_gc_flags();
  2636 #ifdef SERIALGC
  2637   assert(verify_serial_gc_flags(), "SerialGC unset");
  2638 #endif // SERIALGC
  2640   // Set bytecode rewriting flags
  2641   set_bytecode_flags();
  2643   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled.
  2644   set_aggressive_opts_flags();
  2646 #ifdef CC_INTERP
  2647   // Biased locking is not implemented with c++ interpreter
  2648   FLAG_SET_DEFAULT(UseBiasedLocking, false);
  2649 #endif /* CC_INTERP */
  2651 #ifdef COMPILER2
  2652   if (!UseBiasedLocking || EmitSync != 0) {
  2653     UseOptoBiasInlining = false;
  2655 #endif
  2657   if (PrintCommandLineFlags) {
  2658     CommandLineFlags::printSetFlags();
  2661 #ifdef ASSERT
  2662   if (PrintFlagsFinal) {
  2663     CommandLineFlags::printFlags();
  2665 #endif
  2667   return JNI_OK;
  2670 int Arguments::PropertyList_count(SystemProperty* pl) {
  2671   int count = 0;
  2672   while(pl != NULL) {
  2673     count++;
  2674     pl = pl->next();
  2676   return count;
  2679 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
  2680   assert(key != NULL, "just checking");
  2681   SystemProperty* prop;
  2682   for (prop = pl; prop != NULL; prop = prop->next()) {
  2683     if (strcmp(key, prop->key()) == 0) return prop->value();
  2685   return NULL;
  2688 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
  2689   int count = 0;
  2690   const char* ret_val = NULL;
  2692   while(pl != NULL) {
  2693     if(count >= index) {
  2694       ret_val = pl->key();
  2695       break;
  2697     count++;
  2698     pl = pl->next();
  2701   return ret_val;
  2704 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
  2705   int count = 0;
  2706   char* ret_val = NULL;
  2708   while(pl != NULL) {
  2709     if(count >= index) {
  2710       ret_val = pl->value();
  2711       break;
  2713     count++;
  2714     pl = pl->next();
  2717   return ret_val;
  2720 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
  2721   SystemProperty* p = *plist;
  2722   if (p == NULL) {
  2723     *plist = new_p;
  2724   } else {
  2725     while (p->next() != NULL) {
  2726       p = p->next();
  2728     p->set_next(new_p);
  2732 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {
  2733   if (plist == NULL)
  2734     return;
  2736   SystemProperty* new_p = new SystemProperty(k, v, true);
  2737   PropertyList_add(plist, new_p);
  2740 // This add maintains unique property key in the list.
  2741 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v) {
  2742   if (plist == NULL)
  2743     return;
  2745   // If property key exist then update with new value.
  2746   SystemProperty* prop;
  2747   for (prop = *plist; prop != NULL; prop = prop->next()) {
  2748     if (strcmp(k, prop->key()) == 0) {
  2749       prop->set_value(v);
  2750       return;
  2754   PropertyList_add(plist, k, v);
  2757 #ifdef KERNEL
  2758 char *Arguments::get_kernel_properties() {
  2759   // Find properties starting with kernel and append them to string
  2760   // We need to find out how long they are first because the URL's that they
  2761   // might point to could get long.
  2762   int length = 0;
  2763   SystemProperty* prop;
  2764   for (prop = _system_properties; prop != NULL; prop = prop->next()) {
  2765     if (strncmp(prop->key(), "kernel.", 7 ) == 0) {
  2766       length += (strlen(prop->key()) + strlen(prop->value()) + 5);  // "-D ="
  2769   // Add one for null terminator.
  2770   char *props = AllocateHeap(length + 1, "get_kernel_properties");
  2771   if (length != 0) {
  2772     int pos = 0;
  2773     for (prop = _system_properties; prop != NULL; prop = prop->next()) {
  2774       if (strncmp(prop->key(), "kernel.", 7 ) == 0) {
  2775         jio_snprintf(&props[pos], length-pos,
  2776                      "-D%s=%s ", prop->key(), prop->value());
  2777         pos = strlen(props);
  2781   // null terminate props in case of null
  2782   props[length] = '\0';
  2783   return props;
  2785 #endif // KERNEL
  2787 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
  2788 // Returns true if all of the source pointed by src has been copied over to
  2789 // the destination buffer pointed by buf. Otherwise, returns false.
  2790 // Notes:
  2791 // 1. If the length (buflen) of the destination buffer excluding the
  2792 // NULL terminator character is not long enough for holding the expanded
  2793 // pid characters, it also returns false instead of returning the partially
  2794 // expanded one.
  2795 // 2. The passed in "buflen" should be large enough to hold the null terminator.
  2796 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
  2797                                 char* buf, size_t buflen) {
  2798   const char* p = src;
  2799   char* b = buf;
  2800   const char* src_end = &src[srclen];
  2801   char* buf_end = &buf[buflen - 1];
  2803   while (p < src_end && b < buf_end) {
  2804     if (*p == '%') {
  2805       switch (*(++p)) {
  2806       case '%':         // "%%" ==> "%"
  2807         *b++ = *p++;
  2808         break;
  2809       case 'p':  {       //  "%p" ==> current process id
  2810         // buf_end points to the character before the last character so
  2811         // that we could write '\0' to the end of the buffer.
  2812         size_t buf_sz = buf_end - b + 1;
  2813         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
  2815         // if jio_snprintf fails or the buffer is not long enough to hold
  2816         // the expanded pid, returns false.
  2817         if (ret < 0 || ret >= (int)buf_sz) {
  2818           return false;
  2819         } else {
  2820           b += ret;
  2821           assert(*b == '\0', "fail in copy_expand_pid");
  2822           if (p == src_end && b == buf_end + 1) {
  2823             // reach the end of the buffer.
  2824             return true;
  2827         p++;
  2828         break;
  2830       default :
  2831         *b++ = '%';
  2833     } else {
  2834       *b++ = *p++;
  2837   *b = '\0';
  2838   return (p == src_end); // return false if not all of the source was copied

mercurial