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