arguments.cpp revision 8569:5bbf25472731
1132718Skan/*
2132718Skan * Copyright (c) 1997, 2015, 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/classLoader.hpp"
27#include "classfile/javaAssertions.hpp"
28#include "classfile/stringTable.hpp"
29#include "classfile/symbolTable.hpp"
30#include "compiler/compilerOracle.hpp"
31#include "gc/shared/cardTableRS.hpp"
32#include "gc/shared/genCollectedHeap.hpp"
33#include "gc/shared/referenceProcessor.hpp"
34#include "gc/shared/taskqueue.hpp"
35#include "memory/allocation.inline.hpp"
36#include "memory/universe.inline.hpp"
37#include "oops/oop.inline.hpp"
38#include "prims/jvmtiExport.hpp"
39#include "runtime/arguments.hpp"
40#include "runtime/arguments_ext.hpp"
41#include "runtime/commandLineFlagConstraintList.hpp"
42#include "runtime/commandLineFlagRangeList.hpp"
43#include "runtime/globals.hpp"
44#include "runtime/globals_extension.hpp"
45#include "runtime/java.hpp"
46#include "runtime/os.hpp"
47#include "runtime/vm_version.hpp"
48#include "services/management.hpp"
49#include "services/memTracker.hpp"
50#include "utilities/defaultStream.hpp"
51#include "utilities/macros.hpp"
52#include "utilities/stringUtils.hpp"
53#if INCLUDE_ALL_GCS
54#include "gc/cms/compactibleFreeListSpace.hpp"
55#include "gc/g1/g1CollectedHeap.inline.hpp"
56#include "gc/parallel/parallelScavengeHeap.hpp"
57#endif // INCLUDE_ALL_GCS
58
59// Note: This is a special bug reporting site for the JVM
60#define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
61#define DEFAULT_JAVA_LAUNCHER  "generic"
62
63#define UNSUPPORTED_GC_OPTION(gc)                                     \
64do {                                                                  \
65  if (gc) {                                                           \
66    if (FLAG_IS_CMDLINE(gc)) {                                        \
67      warning(#gc " is not supported in this VM.  Using Serial GC."); \
68    }                                                                 \
69    FLAG_SET_DEFAULT(gc, false);                                      \
70  }                                                                   \
71} while(0)
72
73char** Arguments::_jvm_flags_array              = NULL;
74int    Arguments::_num_jvm_flags                = 0;
75char** Arguments::_jvm_args_array               = NULL;
76int    Arguments::_num_jvm_args                 = 0;
77char*  Arguments::_java_command                 = NULL;
78SystemProperty* Arguments::_system_properties   = NULL;
79const char*  Arguments::_gc_log_filename        = NULL;
80bool   Arguments::_has_profile                  = false;
81size_t Arguments::_conservative_max_heap_alignment = 0;
82size_t Arguments::_min_heap_size                = 0;
83uintx  Arguments::_min_heap_free_ratio          = 0;
84uintx  Arguments::_max_heap_free_ratio          = 0;
85Arguments::Mode Arguments::_mode                = _mixed;
86bool   Arguments::_java_compiler                = false;
87bool   Arguments::_xdebug_mode                  = false;
88const char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
89const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
90int    Arguments::_sun_java_launcher_pid        = -1;
91bool   Arguments::_sun_java_launcher_is_altjvm  = false;
92
93// These parameters are reset in method parse_vm_init_args(JavaVMInitArgs*)
94bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
95bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
96bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
97bool   Arguments::_ClipInlining                 = ClipInlining;
98intx   Arguments::_Tier3InvokeNotifyFreqLog     = Tier3InvokeNotifyFreqLog;
99intx   Arguments::_Tier4InvocationThreshold     = Tier4InvocationThreshold;
100
101char*  Arguments::SharedArchivePath             = NULL;
102
103AgentLibraryList Arguments::_libraryList;
104AgentLibraryList Arguments::_agentList;
105
106abort_hook_t     Arguments::_abort_hook         = NULL;
107exit_hook_t      Arguments::_exit_hook          = NULL;
108vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
109
110
111SystemProperty *Arguments::_sun_boot_library_path = NULL;
112SystemProperty *Arguments::_java_library_path = NULL;
113SystemProperty *Arguments::_java_home = NULL;
114SystemProperty *Arguments::_java_class_path = NULL;
115SystemProperty *Arguments::_sun_boot_class_path = NULL;
116
117char* Arguments::_ext_dirs = NULL;
118
119// Check if head of 'option' matches 'name', and sets 'tail' to the remaining
120// part of the option string.
121static bool match_option(const JavaVMOption *option, const char* name,
122                         const char** tail) {
123  int len = (int)strlen(name);
124  if (strncmp(option->optionString, name, len) == 0) {
125    *tail = option->optionString + len;
126    return true;
127  } else {
128    return false;
129  }
130}
131
132// Check if 'option' matches 'name'. No "tail" is allowed.
133static bool match_option(const JavaVMOption *option, const char* name) {
134  const char* tail = NULL;
135  bool result = match_option(option, name, &tail);
136  if (tail != NULL && *tail == '\0') {
137    return result;
138  } else {
139    return false;
140  }
141}
142
143// Return true if any of the strings in null-terminated array 'names' matches.
144// If tail_allowed is true, then the tail must begin with a colon; otherwise,
145// the option must match exactly.
146static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
147  bool tail_allowed) {
148  for (/* empty */; *names != NULL; ++names) {
149    if (match_option(option, *names, tail)) {
150      if (**tail == '\0' || tail_allowed && **tail == ':') {
151        return true;
152      }
153    }
154  }
155  return false;
156}
157
158static void logOption(const char* opt) {
159  if (PrintVMOptions) {
160    jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
161  }
162}
163
164// Process java launcher properties.
165void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
166  // See if sun.java.launcher, sun.java.launcher.is_altjvm or
167  // sun.java.launcher.pid is defined.
168  // Must do this before setting up other system properties,
169  // as some of them may depend on launcher type.
170  for (int index = 0; index < args->nOptions; index++) {
171    const JavaVMOption* option = args->options + index;
172    const char* tail;
173
174    if (match_option(option, "-Dsun.java.launcher=", &tail)) {
175      process_java_launcher_argument(tail, option->extraInfo);
176      continue;
177    }
178    if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
179      if (strcmp(tail, "true") == 0) {
180        _sun_java_launcher_is_altjvm = true;
181      }
182      continue;
183    }
184    if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
185      _sun_java_launcher_pid = atoi(tail);
186      continue;
187    }
188  }
189}
190
191// Initialize system properties key and value.
192void Arguments::init_system_properties() {
193  PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
194                                                                 "Java Virtual Machine Specification",  false));
195  PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
196  PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
197  PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
198
199  // Following are JVMTI agent writable properties.
200  // Properties values are set to NULL and they are
201  // os specific they are initialized in os::init_system_properties_values().
202  _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
203  _java_library_path = new SystemProperty("java.library.path", NULL,  true);
204  _java_home =  new SystemProperty("java.home", NULL,  true);
205  _sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL,  true);
206
207  _java_class_path = new SystemProperty("java.class.path", "",  true);
208
209  // Add to System Property list.
210  PropertyList_add(&_system_properties, _sun_boot_library_path);
211  PropertyList_add(&_system_properties, _java_library_path);
212  PropertyList_add(&_system_properties, _java_home);
213  PropertyList_add(&_system_properties, _java_class_path);
214  PropertyList_add(&_system_properties, _sun_boot_class_path);
215
216  // Set OS specific system properties values
217  os::init_system_properties_values();
218}
219
220// Update/Initialize System properties after JDK version number is known
221void Arguments::init_version_specific_system_properties() {
222  enum { bufsz = 16 };
223  char buffer[bufsz];
224  const char* spec_vendor = "Sun Microsystems Inc.";
225  uint32_t spec_version = 0;
226
227  spec_vendor = "Oracle Corporation";
228  spec_version = JDK_Version::current().major_version();
229  jio_snprintf(buffer, bufsz, "1." UINT32_FORMAT, spec_version);
230
231  PropertyList_add(&_system_properties,
232      new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
233  PropertyList_add(&_system_properties,
234      new SystemProperty("java.vm.specification.version", buffer, false));
235  PropertyList_add(&_system_properties,
236      new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
237}
238
239/**
240 * Provide a slightly more user-friendly way of eliminating -XX flags.
241 * When a flag is eliminated, it can be added to this list in order to
242 * continue accepting this flag on the command-line, while issuing a warning
243 * and ignoring the value.  Once the JDK version reaches the 'accept_until'
244 * limit, we flatly refuse to admit the existence of the flag.  This allows
245 * a flag to die correctly over JDK releases using HSX.
246 * But now that HSX is no longer supported only options with a future
247 * accept_until value need to be listed, and the list can be pruned
248 * on each major release.
249 */
250typedef struct {
251  const char* name;
252  JDK_Version obsoleted_in; // when the flag went away
253  JDK_Version accept_until; // which version to start denying the existence
254} ObsoleteFlag;
255
256static ObsoleteFlag obsolete_jvm_flags[] = {
257  { "UseOldInlining",                JDK_Version::jdk(9), JDK_Version::jdk(10) },
258  { "SafepointPollOffset",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
259  { "UseBoundThreads",               JDK_Version::jdk(9), JDK_Version::jdk(10) },
260  { "DefaultThreadPriority",         JDK_Version::jdk(9), JDK_Version::jdk(10) },
261  { "NoYieldsInMicrolock",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
262  { "BackEdgeThreshold",             JDK_Version::jdk(9), JDK_Version::jdk(10) },
263  { "UseNewReflection",              JDK_Version::jdk(9), JDK_Version::jdk(10) },
264  { "ReflectionWrapResolutionErrors",JDK_Version::jdk(9), JDK_Version::jdk(10) },
265  { "VerifyReflectionBytecodes",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
266  { "AutoShutdownNMT",               JDK_Version::jdk(9), JDK_Version::jdk(10) },
267  { "NmethodSweepFraction",          JDK_Version::jdk(9), JDK_Version::jdk(10) },
268  { "NmethodSweepCheckInterval",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
269  { "CodeCacheMinimumFreeSpace",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
270#ifndef ZERO
271  { "UseFastAccessorMethods",        JDK_Version::jdk(9), JDK_Version::jdk(10) },
272  { "UseFastEmptyMethods",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
273#endif // ZERO
274  { "UseCompilerSafepoints",         JDK_Version::jdk(9), JDK_Version::jdk(10) },
275  { "AdaptiveSizePausePolicy",       JDK_Version::jdk(9), JDK_Version::jdk(10) },
276  { "ParallelGCRetainPLAB",          JDK_Version::jdk(9), JDK_Version::jdk(10) },
277  { NULL, JDK_Version(0), JDK_Version(0) }
278};
279
280// Returns true if the flag is obsolete and fits into the range specified
281// for being ignored.  In the case that the flag is ignored, the 'version'
282// value is filled in with the version number when the flag became
283// obsolete so that that value can be displayed to the user.
284bool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {
285  int i = 0;
286  assert(version != NULL, "Must provide a version buffer");
287  while (obsolete_jvm_flags[i].name != NULL) {
288    const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];
289    // <flag>=xxx form
290    // [-|+]<flag> form
291    size_t len = strlen(flag_status.name);
292    if ((strncmp(flag_status.name, s, len) == 0) &&
293        (strlen(s) == len)){
294      if (JDK_Version::current().compare(flag_status.accept_until) == -1) {
295          *version = flag_status.obsoleted_in;
296          return true;
297      }
298    }
299    i++;
300  }
301  return false;
302}
303
304// Constructs the system class path (aka boot class path) from the following
305// components, in order:
306//
307//     prefix           // from -Xbootclasspath/p:...
308//     base             // from os::get_system_properties() or -Xbootclasspath=
309//     suffix           // from -Xbootclasspath/a:...
310//
311// This could be AllStatic, but it isn't needed after argument processing is
312// complete.
313class SysClassPath: public StackObj {
314public:
315  SysClassPath(const char* base);
316  ~SysClassPath();
317
318  inline void set_base(const char* base);
319  inline void add_prefix(const char* prefix);
320  inline void add_suffix_to_prefix(const char* suffix);
321  inline void add_suffix(const char* suffix);
322  inline void reset_path(const char* base);
323
324  inline const char* get_base()     const { return _items[_scp_base]; }
325  inline const char* get_prefix()   const { return _items[_scp_prefix]; }
326  inline const char* get_suffix()   const { return _items[_scp_suffix]; }
327
328  // Combine all the components into a single c-heap-allocated string; caller
329  // must free the string if/when no longer needed.
330  char* combined_path();
331
332private:
333  // Utility routines.
334  static char* add_to_path(const char* path, const char* str, bool prepend);
335  static char* add_jars_to_path(char* path, const char* directory);
336
337  inline void reset_item_at(int index);
338
339  // Array indices for the items that make up the sysclasspath.  All except the
340  // base are allocated in the C heap and freed by this class.
341  enum {
342    _scp_prefix,        // from -Xbootclasspath/p:...
343    _scp_base,          // the default sysclasspath
344    _scp_suffix,        // from -Xbootclasspath/a:...
345    _scp_nitems         // the number of items, must be last.
346  };
347
348  const char* _items[_scp_nitems];
349};
350
351SysClassPath::SysClassPath(const char* base) {
352  memset(_items, 0, sizeof(_items));
353  _items[_scp_base] = base;
354}
355
356SysClassPath::~SysClassPath() {
357  // Free everything except the base.
358  for (int i = 0; i < _scp_nitems; ++i) {
359    if (i != _scp_base) reset_item_at(i);
360  }
361}
362
363inline void SysClassPath::set_base(const char* base) {
364  _items[_scp_base] = base;
365}
366
367inline void SysClassPath::add_prefix(const char* prefix) {
368  _items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);
369}
370
371inline void SysClassPath::add_suffix_to_prefix(const char* suffix) {
372  _items[_scp_prefix] = add_to_path(_items[_scp_prefix], suffix, false);
373}
374
375inline void SysClassPath::add_suffix(const char* suffix) {
376  _items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);
377}
378
379inline void SysClassPath::reset_item_at(int index) {
380  assert(index < _scp_nitems && index != _scp_base, "just checking");
381  if (_items[index] != NULL) {
382    FREE_C_HEAP_ARRAY(char, _items[index]);
383    _items[index] = NULL;
384  }
385}
386
387inline void SysClassPath::reset_path(const char* base) {
388  // Clear the prefix and suffix.
389  reset_item_at(_scp_prefix);
390  reset_item_at(_scp_suffix);
391  set_base(base);
392}
393
394//------------------------------------------------------------------------------
395
396
397// Combine the bootclasspath elements, some of which may be null, into a single
398// c-heap-allocated string.
399char* SysClassPath::combined_path() {
400  assert(_items[_scp_base] != NULL, "empty default sysclasspath");
401
402  size_t lengths[_scp_nitems];
403  size_t total_len = 0;
404
405  const char separator = *os::path_separator();
406
407  // Get the lengths.
408  int i;
409  for (i = 0; i < _scp_nitems; ++i) {
410    if (_items[i] != NULL) {
411      lengths[i] = strlen(_items[i]);
412      // Include space for the separator char (or a NULL for the last item).
413      total_len += lengths[i] + 1;
414    }
415  }
416  assert(total_len > 0, "empty sysclasspath not allowed");
417
418  // Copy the _items to a single string.
419  char* cp = NEW_C_HEAP_ARRAY(char, total_len, mtInternal);
420  char* cp_tmp = cp;
421  for (i = 0; i < _scp_nitems; ++i) {
422    if (_items[i] != NULL) {
423      memcpy(cp_tmp, _items[i], lengths[i]);
424      cp_tmp += lengths[i];
425      *cp_tmp++ = separator;
426    }
427  }
428  *--cp_tmp = '\0';     // Replace the extra separator.
429  return cp;
430}
431
432// Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
433char*
434SysClassPath::add_to_path(const char* path, const char* str, bool prepend) {
435  char *cp;
436
437  assert(str != NULL, "just checking");
438  if (path == NULL) {
439    size_t len = strlen(str) + 1;
440    cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
441    memcpy(cp, str, len);                       // copy the trailing null
442  } else {
443    const char separator = *os::path_separator();
444    size_t old_len = strlen(path);
445    size_t str_len = strlen(str);
446    size_t len = old_len + str_len + 2;
447
448    if (prepend) {
449      cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
450      char* cp_tmp = cp;
451      memcpy(cp_tmp, str, str_len);
452      cp_tmp += str_len;
453      *cp_tmp = separator;
454      memcpy(++cp_tmp, path, old_len + 1);      // copy the trailing null
455      FREE_C_HEAP_ARRAY(char, path);
456    } else {
457      cp = REALLOC_C_HEAP_ARRAY(char, path, len, mtInternal);
458      char* cp_tmp = cp + old_len;
459      *cp_tmp = separator;
460      memcpy(++cp_tmp, str, str_len + 1);       // copy the trailing null
461    }
462  }
463  return cp;
464}
465
466// Scan the directory and append any jar or zip files found to path.
467// Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
468char* SysClassPath::add_jars_to_path(char* path, const char* directory) {
469  DIR* dir = os::opendir(directory);
470  if (dir == NULL) return path;
471
472  char dir_sep[2] = { '\0', '\0' };
473  size_t directory_len = strlen(directory);
474  const char fileSep = *os::file_separator();
475  if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;
476
477  /* Scan the directory for jars/zips, appending them to path. */
478  struct dirent *entry;
479  char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
480  while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
481    const char* name = entry->d_name;
482    const char* ext = name + strlen(name) - 4;
483    bool isJarOrZip = ext > name &&
484      (os::file_name_strcmp(ext, ".jar") == 0 ||
485       os::file_name_strcmp(ext, ".zip") == 0);
486    if (isJarOrZip) {
487      char* jarpath = NEW_C_HEAP_ARRAY(char, directory_len + 2 + strlen(name), mtInternal);
488      sprintf(jarpath, "%s%s%s", directory, dir_sep, name);
489      path = add_to_path(path, jarpath, false);
490      FREE_C_HEAP_ARRAY(char, jarpath);
491    }
492  }
493  FREE_C_HEAP_ARRAY(char, dbuf);
494  os::closedir(dir);
495  return path;
496}
497
498// Parses a memory size specification string.
499static bool atomull(const char *s, julong* result) {
500  julong n = 0;
501  int args_read = 0;
502  bool is_hex = false;
503  // Skip leading 0[xX] for hexadecimal
504  if (*s =='0' && (*(s+1) == 'x' || *(s+1) == 'X')) {
505    s += 2;
506    is_hex = true;
507    args_read = sscanf(s, JULONG_FORMAT_X, &n);
508  } else {
509    args_read = sscanf(s, JULONG_FORMAT, &n);
510  }
511  if (args_read != 1) {
512    return false;
513  }
514  while (*s != '\0' && (isdigit(*s) || (is_hex && isxdigit(*s)))) {
515    s++;
516  }
517  // 4705540: illegal if more characters are found after the first non-digit
518  if (strlen(s) > 1) {
519    return false;
520  }
521  switch (*s) {
522    case 'T': case 't':
523      *result = n * G * K;
524      // Check for overflow.
525      if (*result/((julong)G * K) != n) return false;
526      return true;
527    case 'G': case 'g':
528      *result = n * G;
529      if (*result/G != n) return false;
530      return true;
531    case 'M': case 'm':
532      *result = n * M;
533      if (*result/M != n) return false;
534      return true;
535    case 'K': case 'k':
536      *result = n * K;
537      if (*result/K != n) return false;
538      return true;
539    case '\0':
540      *result = n;
541      return true;
542    default:
543      return false;
544  }
545}
546
547Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
548  if (size < min_size) return arg_too_small;
549  // Check that size will fit in a size_t (only relevant on 32-bit)
550  if (size > max_uintx) return arg_too_big;
551  return arg_in_range;
552}
553
554// Describe an argument out of range error
555void Arguments::describe_range_error(ArgsRange errcode) {
556  switch(errcode) {
557  case arg_too_big:
558    jio_fprintf(defaultStream::error_stream(),
559                "The specified size exceeds the maximum "
560                "representable size.\n");
561    break;
562  case arg_too_small:
563  case arg_unreadable:
564  case arg_in_range:
565    // do nothing for now
566    break;
567  default:
568    ShouldNotReachHere();
569  }
570}
571
572static bool set_bool_flag(char* name, bool value, Flag::Flags origin) {
573  if (CommandLineFlags::boolAtPut(name, &value, origin) == Flag::SUCCESS) {
574    return true;
575  } else {
576    return false;
577  }
578}
579
580static bool set_fp_numeric_flag(char* name, char* value, Flag::Flags origin) {
581  double v;
582  if (sscanf(value, "%lf", &v) != 1) {
583    return false;
584  }
585
586  if (CommandLineFlags::doubleAtPut(name, &v, origin) == Flag::SUCCESS) {
587    return true;
588  }
589  return false;
590}
591
592static bool set_numeric_flag(char* name, char* value, Flag::Flags origin) {
593  julong v;
594  int int_v;
595  intx intx_v;
596  bool is_neg = false;
597  // Check the sign first since atomull() parses only unsigned values.
598  if (*value == '-') {
599    if ((CommandLineFlags::intxAt(name, &intx_v) != Flag::SUCCESS) && (CommandLineFlags::intAt(name, &int_v) != Flag::SUCCESS)) {
600      return false;
601    }
602    value++;
603    is_neg = true;
604  }
605  if (!atomull(value, &v)) {
606    return false;
607  }
608  int_v = (int) v;
609  if (is_neg) {
610    int_v = -int_v;
611  }
612  if (CommandLineFlags::intAtPut(name, &int_v, origin) == Flag::SUCCESS) {
613    return true;
614  }
615  uint uint_v = (uint) v;
616  if (!is_neg && CommandLineFlags::uintAtPut(name, &uint_v, origin) == Flag::SUCCESS) {
617    return true;
618  }
619  intx_v = (intx) v;
620  if (is_neg) {
621    intx_v = -intx_v;
622  }
623  if (CommandLineFlags::intxAtPut(name, &intx_v, origin) == Flag::SUCCESS) {
624    return true;
625  }
626  uintx uintx_v = (uintx) v;
627  if (!is_neg && (CommandLineFlags::uintxAtPut(name, &uintx_v, origin) == Flag::SUCCESS)) {
628    return true;
629  }
630  uint64_t uint64_t_v = (uint64_t) v;
631  if (!is_neg && (CommandLineFlags::uint64_tAtPut(name, &uint64_t_v, origin) == Flag::SUCCESS)) {
632    return true;
633  }
634  size_t size_t_v = (size_t) v;
635  if (!is_neg && (CommandLineFlags::size_tAtPut(name, &size_t_v, origin) == Flag::SUCCESS)) {
636    return true;
637  }
638  return false;
639}
640
641static bool set_string_flag(char* name, const char* value, Flag::Flags origin) {
642  if (CommandLineFlags::ccstrAtPut(name, &value, origin) != Flag::SUCCESS) return false;
643  // Contract:  CommandLineFlags always returns a pointer that needs freeing.
644  FREE_C_HEAP_ARRAY(char, value);
645  return true;
646}
647
648static bool append_to_string_flag(char* name, const char* new_value, Flag::Flags origin) {
649  const char* old_value = "";
650  if (CommandLineFlags::ccstrAt(name, &old_value) != Flag::SUCCESS) return false;
651  size_t old_len = old_value != NULL ? strlen(old_value) : 0;
652  size_t new_len = strlen(new_value);
653  const char* value;
654  char* free_this_too = NULL;
655  if (old_len == 0) {
656    value = new_value;
657  } else if (new_len == 0) {
658    value = old_value;
659  } else {
660    char* buf = NEW_C_HEAP_ARRAY(char, old_len + 1 + new_len + 1, mtInternal);
661    // each new setting adds another LINE to the switch:
662    sprintf(buf, "%s\n%s", old_value, new_value);
663    value = buf;
664    free_this_too = buf;
665  }
666  (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
667  // CommandLineFlags always returns a pointer that needs freeing.
668  FREE_C_HEAP_ARRAY(char, value);
669  if (free_this_too != NULL) {
670    // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
671    FREE_C_HEAP_ARRAY(char, free_this_too);
672  }
673  return true;
674}
675
676bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
677
678  // range of acceptable characters spelled out for portability reasons
679#define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
680#define BUFLEN 255
681  char name[BUFLEN+1];
682  char dummy;
683
684  if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
685    return set_bool_flag(name, false, origin);
686  }
687  if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
688    return set_bool_flag(name, true, origin);
689  }
690
691  char punct;
692  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
693    const char* value = strchr(arg, '=') + 1;
694    Flag* flag = Flag::find_flag(name, strlen(name));
695    if (flag != NULL && flag->is_ccstr()) {
696      if (flag->ccstr_accumulates()) {
697        return append_to_string_flag(name, value, origin);
698      } else {
699        if (value[0] == '\0') {
700          value = NULL;
701        }
702        return set_string_flag(name, value, origin);
703      }
704    }
705  }
706
707  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
708    const char* value = strchr(arg, '=') + 1;
709    // -XX:Foo:=xxx will reset the string flag to the given value.
710    if (value[0] == '\0') {
711      value = NULL;
712    }
713    return set_string_flag(name, value, origin);
714  }
715
716#define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"
717#define SIGNED_NUMBER_RANGE    "[-0123456789]"
718#define        NUMBER_RANGE    "[0123456789]"
719  char value[BUFLEN + 1];
720  char value2[BUFLEN + 1];
721  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
722    // Looks like a floating-point number -- try again with more lenient format string
723    if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
724      return set_fp_numeric_flag(name, value, origin);
725    }
726  }
727
728#define VALUE_RANGE "[-kmgtxKMGTX0123456789abcdefABCDEF]"
729  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
730    return set_numeric_flag(name, value, origin);
731  }
732
733  return false;
734}
735
736void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
737  assert(bldarray != NULL, "illegal argument");
738
739  if (arg == NULL) {
740    return;
741  }
742
743  int new_count = *count + 1;
744
745  // expand the array and add arg to the last element
746  if (*bldarray == NULL) {
747    *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtInternal);
748  } else {
749    *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtInternal);
750  }
751  (*bldarray)[*count] = os::strdup_check_oom(arg);
752  *count = new_count;
753}
754
755void Arguments::build_jvm_args(const char* arg) {
756  add_string(&_jvm_args_array, &_num_jvm_args, arg);
757}
758
759void Arguments::build_jvm_flags(const char* arg) {
760  add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
761}
762
763// utility function to return a string that concatenates all
764// strings in a given char** array
765const char* Arguments::build_resource_string(char** args, int count) {
766  if (args == NULL || count == 0) {
767    return NULL;
768  }
769  size_t length = strlen(args[0]) + 1; // add 1 for the null terminator
770  for (int i = 1; i < count; i++) {
771    length += strlen(args[i]) + 1; // add 1 for a space
772  }
773  char* s = NEW_RESOURCE_ARRAY(char, length);
774  strcpy(s, args[0]);
775  for (int j = 1; j < count; j++) {
776    strcat(s, " ");
777    strcat(s, args[j]);
778  }
779  return (const char*) s;
780}
781
782void Arguments::print_on(outputStream* st) {
783  st->print_cr("VM Arguments:");
784  if (num_jvm_flags() > 0) {
785    st->print("jvm_flags: "); print_jvm_flags_on(st);
786  }
787  if (num_jvm_args() > 0) {
788    st->print("jvm_args: "); print_jvm_args_on(st);
789  }
790  st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
791  if (_java_class_path != NULL) {
792    char* path = _java_class_path->value();
793    st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
794  }
795  st->print_cr("Launcher Type: %s", _sun_java_launcher);
796}
797
798void Arguments::print_jvm_flags_on(outputStream* st) {
799  if (_num_jvm_flags > 0) {
800    for (int i=0; i < _num_jvm_flags; i++) {
801      st->print("%s ", _jvm_flags_array[i]);
802    }
803    st->cr();
804  }
805}
806
807void Arguments::print_jvm_args_on(outputStream* st) {
808  if (_num_jvm_args > 0) {
809    for (int i=0; i < _num_jvm_args; i++) {
810      st->print("%s ", _jvm_args_array[i]);
811    }
812    st->cr();
813  }
814}
815
816bool Arguments::process_argument(const char* arg,
817    jboolean ignore_unrecognized, Flag::Flags origin) {
818
819  JDK_Version since = JDK_Version();
820
821  if (parse_argument(arg, origin) || ignore_unrecognized) {
822    return true;
823  }
824
825  // Determine if the flag has '+', '-', or '=' characters.
826  bool has_plus_minus = (*arg == '+' || *arg == '-');
827  const char* const argname = has_plus_minus ? arg + 1 : arg;
828
829  size_t arg_len;
830  const char* equal_sign = strchr(argname, '=');
831  if (equal_sign == NULL) {
832    arg_len = strlen(argname);
833  } else {
834    arg_len = equal_sign - argname;
835  }
836
837  // Construct a string which consists only of the argument name without '+', '-', or '='.
838  char stripped_argname[256];
839  strncpy(stripped_argname, argname, arg_len);
840  stripped_argname[arg_len] = '\0'; //strncpy doesn't null terminate.
841
842  if (is_newly_obsolete(stripped_argname, &since)) {
843    char version[256];
844    since.to_string(version, sizeof(version));
845    warning("ignoring option %s; support was removed in %s", stripped_argname, version);
846    return true;
847  }
848
849  // For locked flags, report a custom error message if available.
850  // Otherwise, report the standard unrecognized VM option.
851  Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
852  if (found_flag != NULL) {
853    char locked_message_buf[BUFLEN];
854    found_flag->get_locked_message(locked_message_buf, BUFLEN);
855    if (strlen(locked_message_buf) == 0) {
856      if (found_flag->is_bool() && !has_plus_minus) {
857        jio_fprintf(defaultStream::error_stream(),
858          "Missing +/- setting for VM option '%s'\n", argname);
859      } else if (!found_flag->is_bool() && has_plus_minus) {
860        jio_fprintf(defaultStream::error_stream(),
861          "Unexpected +/- setting in VM option '%s'\n", argname);
862      } else {
863        jio_fprintf(defaultStream::error_stream(),
864          "Improperly specified VM option '%s'\n", argname);
865      }
866    } else {
867      jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
868    }
869  } else {
870    jio_fprintf(defaultStream::error_stream(),
871                "Unrecognized VM option '%s'\n", argname);
872    Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
873    if (fuzzy_matched != NULL) {
874      jio_fprintf(defaultStream::error_stream(),
875                  "Did you mean '%s%s%s'? ",
876                  (fuzzy_matched->is_bool()) ? "(+/-)" : "",
877                  fuzzy_matched->_name,
878                  (fuzzy_matched->is_bool()) ? "" : "=<value>");
879    }
880  }
881
882  // allow for commandline "commenting out" options like -XX:#+Verbose
883  return arg[0] == '#';
884}
885
886bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
887  FILE* stream = fopen(file_name, "rb");
888  if (stream == NULL) {
889    if (should_exist) {
890      jio_fprintf(defaultStream::error_stream(),
891                  "Could not open settings file %s\n", file_name);
892      return false;
893    } else {
894      return true;
895    }
896  }
897
898  char token[1024];
899  int  pos = 0;
900
901  bool in_white_space = true;
902  bool in_comment     = false;
903  bool in_quote       = false;
904  char quote_c        = 0;
905  bool result         = true;
906
907  int c = getc(stream);
908  while(c != EOF && pos < (int)(sizeof(token)-1)) {
909    if (in_white_space) {
910      if (in_comment) {
911        if (c == '\n') in_comment = false;
912      } else {
913        if (c == '#') in_comment = true;
914        else if (!isspace(c)) {
915          in_white_space = false;
916          token[pos++] = c;
917        }
918      }
919    } else {
920      if (c == '\n' || (!in_quote && isspace(c))) {
921        // token ends at newline, or at unquoted whitespace
922        // this allows a way to include spaces in string-valued options
923        token[pos] = '\0';
924        logOption(token);
925        result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
926        build_jvm_flags(token);
927        pos = 0;
928        in_white_space = true;
929        in_quote = false;
930      } else if (!in_quote && (c == '\'' || c == '"')) {
931        in_quote = true;
932        quote_c = c;
933      } else if (in_quote && (c == quote_c)) {
934        in_quote = false;
935      } else {
936        token[pos++] = c;
937      }
938    }
939    c = getc(stream);
940  }
941  if (pos > 0) {
942    token[pos] = '\0';
943    result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
944    build_jvm_flags(token);
945  }
946  fclose(stream);
947  return result;
948}
949
950//=============================================================================================================
951// Parsing of properties (-D)
952
953const char* Arguments::get_property(const char* key) {
954  return PropertyList_get_value(system_properties(), key);
955}
956
957bool Arguments::add_property(const char* prop) {
958  const char* eq = strchr(prop, '=');
959  char* key;
960  // ns must be static--its address may be stored in a SystemProperty object.
961  const static char ns[1] = {0};
962  char* value = (char *)ns;
963
964  size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);
965  key = AllocateHeap(key_len + 1, mtInternal);
966  strncpy(key, prop, key_len);
967  key[key_len] = '\0';
968
969  if (eq != NULL) {
970    size_t value_len = strlen(prop) - key_len - 1;
971    value = AllocateHeap(value_len + 1, mtInternal);
972    strncpy(value, &prop[key_len + 1], value_len + 1);
973  }
974
975  if (strcmp(key, "java.compiler") == 0) {
976    process_java_compiler_argument(value);
977    FreeHeap(key);
978    if (eq != NULL) {
979      FreeHeap(value);
980    }
981    return true;
982  } else if (strcmp(key, "sun.java.command") == 0) {
983    _java_command = value;
984
985    // Record value in Arguments, but let it get passed to Java.
986  } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0 ||
987             strcmp(key, "sun.java.launcher.pid") == 0) {
988    // sun.java.launcher.is_altjvm and sun.java.launcher.pid property are
989    // private and are processed in process_sun_java_launcher_properties();
990    // the sun.java.launcher property is passed on to the java application
991    FreeHeap(key);
992    if (eq != NULL) {
993      FreeHeap(value);
994    }
995    return true;
996  } else if (strcmp(key, "java.vendor.url.bug") == 0) {
997    // save it in _java_vendor_url_bug, so JVM fatal error handler can access
998    // its value without going through the property list or making a Java call.
999    _java_vendor_url_bug = value;
1000  } else if (strcmp(key, "sun.boot.library.path") == 0) {
1001    PropertyList_unique_add(&_system_properties, key, value, true);
1002    return true;
1003  }
1004  // Create new property and add at the end of the list
1005  PropertyList_unique_add(&_system_properties, key, value);
1006  return true;
1007}
1008
1009//===========================================================================================================
1010// Setting int/mixed/comp mode flags
1011
1012void Arguments::set_mode_flags(Mode mode) {
1013  // Set up default values for all flags.
1014  // If you add a flag to any of the branches below,
1015  // add a default value for it here.
1016  set_java_compiler(false);
1017  _mode                      = mode;
1018
1019  // Ensure Agent_OnLoad has the correct initial values.
1020  // This may not be the final mode; mode may change later in onload phase.
1021  PropertyList_unique_add(&_system_properties, "java.vm.info",
1022                          (char*)VM_Version::vm_info_string(), false);
1023
1024  UseInterpreter             = true;
1025  UseCompiler                = true;
1026  UseLoopCounter             = true;
1027
1028  // Default values may be platform/compiler dependent -
1029  // use the saved values
1030  ClipInlining               = Arguments::_ClipInlining;
1031  AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1032  UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1033  BackgroundCompilation      = Arguments::_BackgroundCompilation;
1034  if (TieredCompilation) {
1035    if (FLAG_IS_DEFAULT(Tier3InvokeNotifyFreqLog)) {
1036      Tier3InvokeNotifyFreqLog = Arguments::_Tier3InvokeNotifyFreqLog;
1037    }
1038    if (FLAG_IS_DEFAULT(Tier4InvocationThreshold)) {
1039      Tier4InvocationThreshold = Arguments::_Tier4InvocationThreshold;
1040    }
1041  }
1042
1043  // Change from defaults based on mode
1044  switch (mode) {
1045  default:
1046    ShouldNotReachHere();
1047    break;
1048  case _int:
1049    UseCompiler              = false;
1050    UseLoopCounter           = false;
1051    AlwaysCompileLoopMethods = false;
1052    UseOnStackReplacement    = false;
1053    break;
1054  case _mixed:
1055    // same as default
1056    break;
1057  case _comp:
1058    UseInterpreter           = false;
1059    BackgroundCompilation    = false;
1060    ClipInlining             = false;
1061    // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1062    // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1063    // compile a level 4 (C2) and then continue executing it.
1064    if (TieredCompilation) {
1065      Tier3InvokeNotifyFreqLog = 0;
1066      Tier4InvocationThreshold = 0;
1067    }
1068    break;
1069  }
1070}
1071
1072#if defined(COMPILER2) || defined(_LP64) || !INCLUDE_CDS
1073// Conflict: required to use shared spaces (-Xshare:on), but
1074// incompatible command line options were chosen.
1075
1076static void no_shared_spaces(const char* message) {
1077  if (RequireSharedSpaces) {
1078    jio_fprintf(defaultStream::error_stream(),
1079      "Class data sharing is inconsistent with other specified options.\n");
1080    vm_exit_during_initialization("Unable to use shared archive.", message);
1081  } else {
1082    FLAG_SET_DEFAULT(UseSharedSpaces, false);
1083  }
1084}
1085#endif
1086
1087// Returns threshold scaled with the value of scale.
1088// If scale < 0.0, threshold is returned without scaling.
1089intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
1090  if (scale == 1.0 || scale < 0.0) {
1091    return threshold;
1092  } else {
1093    return (intx)(threshold * scale);
1094  }
1095}
1096
1097// Returns freq_log scaled with the value of scale.
1098// Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
1099// If scale < 0.0, freq_log is returned without scaling.
1100intx Arguments::scaled_freq_log(intx freq_log, double scale) {
1101  // Check if scaling is necessary or if negative value was specified.
1102  if (scale == 1.0 || scale < 0.0) {
1103    return freq_log;
1104  }
1105  // Check values to avoid calculating log2 of 0.
1106  if (scale == 0.0 || freq_log == 0) {
1107    return 0;
1108  }
1109  // Determine the maximum notification frequency value currently supported.
1110  // The largest mask value that the interpreter/C1 can handle is
1111  // of length InvocationCounter::number_of_count_bits. Mask values are always
1112  // one bit shorter then the value of the notification frequency. Set
1113  // max_freq_bits accordingly.
1114  intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
1115  intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
1116  if (scaled_freq == 0) {
1117    // Return 0 right away to avoid calculating log2 of 0.
1118    return 0;
1119  } else if (scaled_freq > nth_bit(max_freq_bits)) {
1120    return max_freq_bits;
1121  } else {
1122    return log2_intptr(scaled_freq);
1123  }
1124}
1125
1126void Arguments::set_tiered_flags() {
1127  // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1128  if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1129    FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1130  }
1131  if (CompilationPolicyChoice < 2) {
1132    vm_exit_during_initialization(
1133      "Incompatible compilation policy selected", NULL);
1134  }
1135  // Increase the code cache size - tiered compiles a lot more.
1136  if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1137    FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
1138                  MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1139  }
1140  // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
1141  if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
1142    FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
1143
1144    if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1145      // Multiply sizes by 5 but fix NonNMethodCodeHeapSize (distribute among non-profiled and profiled code heap)
1146      if (FLAG_IS_DEFAULT(ProfiledCodeHeapSize)) {
1147        FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, ProfiledCodeHeapSize * 5 + NonNMethodCodeHeapSize * 2);
1148      }
1149      if (FLAG_IS_DEFAULT(NonProfiledCodeHeapSize)) {
1150        FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, NonProfiledCodeHeapSize * 5 + NonNMethodCodeHeapSize * 2);
1151      }
1152      // Check consistency of code heap sizes
1153      if ((NonNMethodCodeHeapSize + NonProfiledCodeHeapSize + ProfiledCodeHeapSize) != ReservedCodeCacheSize) {
1154        jio_fprintf(defaultStream::error_stream(),
1155                    "Invalid code heap sizes: NonNMethodCodeHeapSize(%dK) + ProfiledCodeHeapSize(%dK) + NonProfiledCodeHeapSize(%dK) = %dK. Must be equal to ReservedCodeCacheSize = %uK.\n",
1156                    NonNMethodCodeHeapSize/K, ProfiledCodeHeapSize/K, NonProfiledCodeHeapSize/K,
1157                    (NonNMethodCodeHeapSize + ProfiledCodeHeapSize + NonProfiledCodeHeapSize)/K, ReservedCodeCacheSize/K);
1158        vm_exit(1);
1159      }
1160    }
1161  }
1162  if (!UseInterpreter) { // -Xcomp
1163    Tier3InvokeNotifyFreqLog = 0;
1164    Tier4InvocationThreshold = 0;
1165  }
1166
1167  if (CompileThresholdScaling < 0) {
1168    vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
1169  }
1170
1171  // Scale tiered compilation thresholds.
1172  // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
1173  if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
1174    FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
1175    FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
1176
1177    FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
1178    FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
1179    FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
1180    FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
1181
1182    // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
1183    // once these thresholds become supported.
1184
1185    FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
1186    FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
1187
1188    FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
1189    FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
1190
1191    FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
1192
1193    FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
1194    FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
1195    FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
1196    FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
1197  }
1198}
1199
1200/**
1201 * Returns the minimum number of compiler threads needed to run the JVM. The following
1202 * configurations are possible.
1203 *
1204 * 1) The JVM is build using an interpreter only. As a result, the minimum number of
1205 *    compiler threads is 0.
1206 * 2) The JVM is build using the compiler(s) and tiered compilation is disabled. As
1207 *    a result, either C1 or C2 is used, so the minimum number of compiler threads is 1.
1208 * 3) The JVM is build using the compiler(s) and tiered compilation is enabled. However,
1209 *    the option "TieredStopAtLevel < CompLevel_full_optimization". As a result, only
1210 *    C1 can be used, so the minimum number of compiler threads is 1.
1211 * 4) The JVM is build using the compilers and tiered compilation is enabled. The option
1212 *    'TieredStopAtLevel = CompLevel_full_optimization' (the default value). As a result,
1213 *    the minimum number of compiler threads is 2.
1214 */
1215int Arguments::get_min_number_of_compiler_threads() {
1216#if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)
1217  return 0;   // case 1
1218#else
1219  if (!TieredCompilation || (TieredStopAtLevel < CompLevel_full_optimization)) {
1220    return 1; // case 2 or case 3
1221  }
1222  return 2;   // case 4 (tiered)
1223#endif
1224}
1225
1226#if INCLUDE_ALL_GCS
1227static void disable_adaptive_size_policy(const char* collector_name) {
1228  if (UseAdaptiveSizePolicy) {
1229    if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
1230      warning("disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
1231              collector_name);
1232    }
1233    FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
1234  }
1235}
1236
1237void Arguments::set_parnew_gc_flags() {
1238  assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
1239         "control point invariant");
1240  assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1241  assert(UseParNewGC, "ParNew should always be used with CMS");
1242
1243  if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
1244    FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1245    assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
1246  } else if (ParallelGCThreads == 0) {
1247    jio_fprintf(defaultStream::error_stream(),
1248        "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
1249    vm_exit(1);
1250  }
1251
1252  // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
1253  // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
1254  // we set them to 1024 and 1024.
1255  // See CR 6362902.
1256  if (FLAG_IS_DEFAULT(YoungPLABSize)) {
1257    FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
1258  }
1259  if (FLAG_IS_DEFAULT(OldPLABSize)) {
1260    FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
1261  }
1262
1263  // When using compressed oops, we use local overflow stacks,
1264  // rather than using a global overflow list chained through
1265  // the klass word of the object's pre-image.
1266  if (UseCompressedOops && !ParGCUseLocalOverflow) {
1267    if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
1268      warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
1269    }
1270    FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
1271  }
1272  assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
1273}
1274
1275// Adjust some sizes to suit CMS and/or ParNew needs; these work well on
1276// sparc/solaris for certain applications, but would gain from
1277// further optimization and tuning efforts, and would almost
1278// certainly gain from analysis of platform and environment.
1279void Arguments::set_cms_and_parnew_gc_flags() {
1280  assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
1281  assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1282  assert(UseParNewGC, "ParNew should always be used with CMS");
1283
1284  // Turn off AdaptiveSizePolicy by default for cms until it is complete.
1285  disable_adaptive_size_policy("UseConcMarkSweepGC");
1286
1287  set_parnew_gc_flags();
1288
1289  size_t max_heap = align_size_down(MaxHeapSize,
1290                                    CardTableRS::ct_max_alignment_constraint());
1291
1292  // Now make adjustments for CMS
1293  intx   tenuring_default = (intx)6;
1294  size_t young_gen_per_worker = CMSYoungGenPerWorker;
1295
1296  // Preferred young gen size for "short" pauses:
1297  // upper bound depends on # of threads and NewRatio.
1298  const size_t preferred_max_new_size_unaligned =
1299    MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * ParallelGCThreads));
1300  size_t preferred_max_new_size =
1301    align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
1302
1303  // Unless explicitly requested otherwise, size young gen
1304  // for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
1305
1306  // If either MaxNewSize or NewRatio is set on the command line,
1307  // assume the user is trying to set the size of the young gen.
1308  if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
1309
1310    // Set MaxNewSize to our calculated preferred_max_new_size unless
1311    // NewSize was set on the command line and it is larger than
1312    // preferred_max_new_size.
1313    if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
1314      FLAG_SET_ERGO(size_t, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
1315    } else {
1316      FLAG_SET_ERGO(size_t, MaxNewSize, preferred_max_new_size);
1317    }
1318    if (PrintGCDetails && Verbose) {
1319      // Too early to use gclog_or_tty
1320      tty->print_cr("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
1321    }
1322
1323    // Code along this path potentially sets NewSize and OldSize
1324    if (PrintGCDetails && Verbose) {
1325      // Too early to use gclog_or_tty
1326      tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
1327           " initial_heap_size:  " SIZE_FORMAT
1328           " max_heap: " SIZE_FORMAT,
1329           min_heap_size(), InitialHeapSize, max_heap);
1330    }
1331    size_t min_new = preferred_max_new_size;
1332    if (FLAG_IS_CMDLINE(NewSize)) {
1333      min_new = NewSize;
1334    }
1335    if (max_heap > min_new && min_heap_size() > min_new) {
1336      // Unless explicitly requested otherwise, make young gen
1337      // at least min_new, and at most preferred_max_new_size.
1338      if (FLAG_IS_DEFAULT(NewSize)) {
1339        FLAG_SET_ERGO(size_t, NewSize, MAX2(NewSize, min_new));
1340        FLAG_SET_ERGO(size_t, NewSize, MIN2(preferred_max_new_size, NewSize));
1341        if (PrintGCDetails && Verbose) {
1342          // Too early to use gclog_or_tty
1343          tty->print_cr("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
1344        }
1345      }
1346      // Unless explicitly requested otherwise, size old gen
1347      // so it's NewRatio x of NewSize.
1348      if (FLAG_IS_DEFAULT(OldSize)) {
1349        if (max_heap > NewSize) {
1350          FLAG_SET_ERGO(size_t, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
1351          if (PrintGCDetails && Verbose) {
1352            // Too early to use gclog_or_tty
1353            tty->print_cr("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
1354          }
1355        }
1356      }
1357    }
1358  }
1359  // Unless explicitly requested otherwise, definitely
1360  // promote all objects surviving "tenuring_default" scavenges.
1361  if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
1362      FLAG_IS_DEFAULT(SurvivorRatio)) {
1363    FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
1364  }
1365  // If we decided above (or user explicitly requested)
1366  // `promote all' (via MaxTenuringThreshold := 0),
1367  // prefer minuscule survivor spaces so as not to waste
1368  // space for (non-existent) survivors
1369  if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
1370    FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
1371  }
1372
1373  // OldPLABSize is interpreted in CMS as not the size of the PLAB in words,
1374  // but rather the number of free blocks of a given size that are used when
1375  // replenishing the local per-worker free list caches.
1376  if (FLAG_IS_DEFAULT(OldPLABSize)) {
1377    if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
1378      // OldPLAB sizing manually turned off: Use a larger default setting,
1379      // unless it was manually specified. This is because a too-low value
1380      // will slow down scavenges.
1381      FLAG_SET_ERGO(size_t, OldPLABSize, CFLS_LAB::_default_static_old_plab_size); // default value before 6631166
1382    } else {
1383      FLAG_SET_DEFAULT(OldPLABSize, CFLS_LAB::_default_dynamic_old_plab_size); // old CMSParPromoteBlocksToClaim default
1384    }
1385  }
1386
1387  // If either of the static initialization defaults have changed, note this
1388  // modification.
1389  if (!FLAG_IS_DEFAULT(OldPLABSize) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
1390    CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
1391  }
1392  if (PrintGCDetails && Verbose) {
1393    tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1394      (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1395    tty->print_cr("ConcGCThreads: %u", ConcGCThreads);
1396  }
1397}
1398#endif // INCLUDE_ALL_GCS
1399
1400void set_object_alignment() {
1401  // Object alignment.
1402  assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1403  MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1404  assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1405  MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1406  assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1407  MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1408
1409  LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1410  LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1411
1412  // Oop encoding heap max
1413  OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1414
1415  if (SurvivorAlignmentInBytes == 0) {
1416    SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1417  }
1418
1419#if INCLUDE_ALL_GCS
1420  // Set CMS global values
1421  CompactibleFreeListSpace::set_cms_values();
1422#endif // INCLUDE_ALL_GCS
1423}
1424
1425size_t Arguments::max_heap_for_compressed_oops() {
1426  // Avoid sign flip.
1427  assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1428  // We need to fit both the NULL page and the heap into the memory budget, while
1429  // keeping alignment constraints of the heap. To guarantee the latter, as the
1430  // NULL page is located before the heap, we pad the NULL page to the conservative
1431  // maximum alignment that the GC may ever impose upon the heap.
1432  size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
1433                                                        _conservative_max_heap_alignment);
1434
1435  LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1436  NOT_LP64(ShouldNotReachHere(); return 0);
1437}
1438
1439bool Arguments::should_auto_select_low_pause_collector() {
1440  if (UseAutoGCSelectPolicy &&
1441      !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
1442      (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
1443    if (PrintGCDetails) {
1444      // Cannot use gclog_or_tty yet.
1445      tty->print_cr("Automatic selection of the low pause collector"
1446       " based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
1447    }
1448    return true;
1449  }
1450  return false;
1451}
1452
1453void Arguments::set_use_compressed_oops() {
1454#ifndef ZERO
1455#ifdef _LP64
1456  // MaxHeapSize is not set up properly at this point, but
1457  // the only value that can override MaxHeapSize if we are
1458  // to use UseCompressedOops is InitialHeapSize.
1459  size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1460
1461  if (max_heap_size <= max_heap_for_compressed_oops()) {
1462#if !defined(COMPILER1) || defined(TIERED)
1463    if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1464      FLAG_SET_ERGO(bool, UseCompressedOops, true);
1465    }
1466#endif
1467  } else {
1468    if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1469      warning("Max heap size too large for Compressed Oops");
1470      FLAG_SET_DEFAULT(UseCompressedOops, false);
1471      FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1472    }
1473  }
1474#endif // _LP64
1475#endif // ZERO
1476}
1477
1478
1479// NOTE: set_use_compressed_klass_ptrs() must be called after calling
1480// set_use_compressed_oops().
1481void Arguments::set_use_compressed_klass_ptrs() {
1482#ifndef ZERO
1483#ifdef _LP64
1484  // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1485  if (!UseCompressedOops) {
1486    if (UseCompressedClassPointers) {
1487      warning("UseCompressedClassPointers requires UseCompressedOops");
1488    }
1489    FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1490  } else {
1491    // Turn on UseCompressedClassPointers too
1492    if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1493      FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1494    }
1495    // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1496    if (UseCompressedClassPointers) {
1497      if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1498        warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1499        FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1500      }
1501    }
1502  }
1503#endif // _LP64
1504#endif // !ZERO
1505}
1506
1507void Arguments::set_conservative_max_heap_alignment() {
1508  // The conservative maximum required alignment for the heap is the maximum of
1509  // the alignments imposed by several sources: any requirements from the heap
1510  // itself, the collector policy and the maximum page size we may run the VM
1511  // with.
1512  size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
1513#if INCLUDE_ALL_GCS
1514  if (UseParallelGC) {
1515    heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
1516  } else if (UseG1GC) {
1517    heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
1518  }
1519#endif // INCLUDE_ALL_GCS
1520  _conservative_max_heap_alignment = MAX4(heap_alignment,
1521                                          (size_t)os::vm_allocation_granularity(),
1522                                          os::max_page_size(),
1523                                          CollectorPolicy::compute_heap_alignment());
1524}
1525
1526void Arguments::select_gc_ergonomically() {
1527  if (os::is_server_class_machine()) {
1528    if (should_auto_select_low_pause_collector()) {
1529      FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
1530    } else {
1531      FLAG_SET_ERGO(bool, UseParallelGC, true);
1532    }
1533  } else {
1534    FLAG_SET_ERGO(bool, UseSerialGC, true);
1535  }
1536}
1537
1538void Arguments::select_gc() {
1539  if (!gc_selected()) {
1540    select_gc_ergonomically();
1541    guarantee(gc_selected(), "No GC selected");
1542  }
1543}
1544
1545void Arguments::set_ergonomics_flags() {
1546  select_gc();
1547
1548#ifdef COMPILER2
1549  // Shared spaces work fine with other GCs but causes bytecode rewriting
1550  // to be disabled, which hurts interpreter performance and decreases
1551  // server performance.  When -server is specified, keep the default off
1552  // unless it is asked for.  Future work: either add bytecode rewriting
1553  // at link time, or rewrite bytecodes in non-shared methods.
1554  if (!DumpSharedSpaces && !RequireSharedSpaces &&
1555      (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1556    no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1557  }
1558#endif
1559
1560  set_conservative_max_heap_alignment();
1561
1562#ifndef ZERO
1563#ifdef _LP64
1564  set_use_compressed_oops();
1565
1566  // set_use_compressed_klass_ptrs() must be called after calling
1567  // set_use_compressed_oops().
1568  set_use_compressed_klass_ptrs();
1569
1570  // Also checks that certain machines are slower with compressed oops
1571  // in vm_version initialization code.
1572#endif // _LP64
1573#endif // !ZERO
1574}
1575
1576void Arguments::set_parallel_gc_flags() {
1577  assert(UseParallelGC || UseParallelOldGC, "Error");
1578  // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1579  if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1580    FLAG_SET_DEFAULT(UseParallelOldGC, true);
1581  }
1582  FLAG_SET_DEFAULT(UseParallelGC, true);
1583
1584  // If no heap maximum was requested explicitly, use some reasonable fraction
1585  // of the physical memory, up to a maximum of 1GB.
1586  FLAG_SET_DEFAULT(ParallelGCThreads,
1587                   Abstract_VM_Version::parallel_worker_threads());
1588  if (ParallelGCThreads == 0) {
1589    jio_fprintf(defaultStream::error_stream(),
1590        "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1591    vm_exit(1);
1592  }
1593
1594  if (UseAdaptiveSizePolicy) {
1595    // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1596    // unless the user actually sets these flags.
1597    if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1598      FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1599      _min_heap_free_ratio = MinHeapFreeRatio;
1600    }
1601    if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1602      FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1603      _max_heap_free_ratio = MaxHeapFreeRatio;
1604    }
1605  }
1606
1607  // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1608  // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1609  // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1610  // See CR 6362902 for details.
1611  if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1612    if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1613       FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1614    }
1615    if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1616      FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1617    }
1618  }
1619
1620  if (UseParallelOldGC) {
1621    // Par compact uses lower default values since they are treated as
1622    // minimums.  These are different defaults because of the different
1623    // interpretation and are not ergonomically set.
1624    if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1625      FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1626    }
1627  }
1628}
1629
1630void Arguments::set_g1_gc_flags() {
1631  assert(UseG1GC, "Error");
1632#ifdef COMPILER1
1633  FastTLABRefill = false;
1634#endif
1635  FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1636  if (ParallelGCThreads == 0) {
1637    assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
1638    vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1639  }
1640
1641#if INCLUDE_ALL_GCS
1642  if (G1ConcRefinementThreads == 0) {
1643    FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);
1644  }
1645#endif
1646
1647  // MarkStackSize will be set (if it hasn't been set by the user)
1648  // when concurrent marking is initialized.
1649  // Its value will be based upon the number of parallel marking threads.
1650  // But we do set the maximum mark stack size here.
1651  if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1652    FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1653  }
1654
1655  if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1656    // In G1, we want the default GC overhead goal to be higher than
1657    // say in PS. So we set it here to 10%. Otherwise the heap might
1658    // be expanded more aggressively than we would like it to. In
1659    // fact, even 10% seems to not be high enough in some cases
1660    // (especially small GC stress tests that the main thing they do
1661    // is allocation). We might consider increase it further.
1662    FLAG_SET_DEFAULT(GCTimeRatio, 9);
1663  }
1664
1665  if (PrintGCDetails && Verbose) {
1666    tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1667      (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1668    tty->print_cr("ConcGCThreads: %u", ConcGCThreads);
1669  }
1670}
1671
1672#if !INCLUDE_ALL_GCS
1673#ifdef ASSERT
1674static bool verify_serial_gc_flags() {
1675  return (UseSerialGC &&
1676        !(UseParNewGC || (UseConcMarkSweepGC) || UseG1GC ||
1677          UseParallelGC || UseParallelOldGC));
1678}
1679#endif // ASSERT
1680#endif // INCLUDE_ALL_GCS
1681
1682void Arguments::set_gc_specific_flags() {
1683#if INCLUDE_ALL_GCS
1684  // Set per-collector flags
1685  if (UseParallelGC || UseParallelOldGC) {
1686    set_parallel_gc_flags();
1687  } else if (UseConcMarkSweepGC) {
1688    set_cms_and_parnew_gc_flags();
1689  } else if (UseG1GC) {
1690    set_g1_gc_flags();
1691  }
1692  check_deprecated_gc_flags();
1693  if (AssumeMP && !UseSerialGC) {
1694    if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
1695      warning("If the number of processors is expected to increase from one, then"
1696              " you should configure the number of parallel GC threads appropriately"
1697              " using -XX:ParallelGCThreads=N");
1698    }
1699  }
1700  if (MinHeapFreeRatio == 100) {
1701    // Keeping the heap 100% free is hard ;-) so limit it to 99%.
1702    FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
1703  }
1704#else // INCLUDE_ALL_GCS
1705  assert(verify_serial_gc_flags(), "SerialGC unset");
1706#endif // INCLUDE_ALL_GCS
1707}
1708
1709julong Arguments::limit_by_allocatable_memory(julong limit) {
1710  julong max_allocatable;
1711  julong result = limit;
1712  if (os::has_allocatable_memory_limit(&max_allocatable)) {
1713    result = MIN2(result, max_allocatable / MaxVirtMemFraction);
1714  }
1715  return result;
1716}
1717
1718// Use static initialization to get the default before parsing
1719static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1720
1721void Arguments::set_heap_size() {
1722  if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
1723    // Deprecated flag
1724    FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
1725  }
1726
1727  const julong phys_mem =
1728    FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1729                            : (julong)MaxRAM;
1730
1731  // If the maximum heap size has not been set with -Xmx,
1732  // then set it as fraction of the size of physical memory,
1733  // respecting the maximum and minimum sizes of the heap.
1734  if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1735    julong reasonable_max = phys_mem / MaxRAMFraction;
1736
1737    if (phys_mem <= MaxHeapSize * MinRAMFraction) {
1738      // Small physical memory, so use a minimum fraction of it for the heap
1739      reasonable_max = phys_mem / MinRAMFraction;
1740    } else {
1741      // Not-small physical memory, so require a heap at least
1742      // as large as MaxHeapSize
1743      reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1744    }
1745    if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1746      // Limit the heap size to ErgoHeapSizeLimit
1747      reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1748    }
1749    if (UseCompressedOops) {
1750      // Limit the heap size to the maximum possible when using compressed oops
1751      julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1752
1753      // HeapBaseMinAddress can be greater than default but not less than.
1754      if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1755        if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1756          // matches compressed oops printing flags
1757          if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
1758            jio_fprintf(defaultStream::error_stream(),
1759                        "HeapBaseMinAddress must be at least " SIZE_FORMAT
1760                        " (" SIZE_FORMAT "G) which is greater than value given "
1761                        SIZE_FORMAT "\n",
1762                        DefaultHeapBaseMinAddress,
1763                        DefaultHeapBaseMinAddress/G,
1764                        HeapBaseMinAddress);
1765          }
1766          FLAG_SET_ERGO(size_t, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1767        }
1768      }
1769
1770      if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1771        // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1772        // but it should be not less than default MaxHeapSize.
1773        max_coop_heap -= HeapBaseMinAddress;
1774      }
1775      reasonable_max = MIN2(reasonable_max, max_coop_heap);
1776    }
1777    reasonable_max = limit_by_allocatable_memory(reasonable_max);
1778
1779    if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1780      // An initial heap size was specified on the command line,
1781      // so be sure that the maximum size is consistent.  Done
1782      // after call to limit_by_allocatable_memory because that
1783      // method might reduce the allocation size.
1784      reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1785    }
1786
1787    if (PrintGCDetails && Verbose) {
1788      // Cannot use gclog_or_tty yet.
1789      tty->print_cr("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1790    }
1791    FLAG_SET_ERGO(size_t, MaxHeapSize, (size_t)reasonable_max);
1792  }
1793
1794  // If the minimum or initial heap_size have not been set or requested to be set
1795  // ergonomically, set them accordingly.
1796  if (InitialHeapSize == 0 || min_heap_size() == 0) {
1797    julong reasonable_minimum = (julong)(OldSize + NewSize);
1798
1799    reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1800
1801    reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1802
1803    if (InitialHeapSize == 0) {
1804      julong reasonable_initial = phys_mem / InitialRAMFraction;
1805
1806      reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
1807      reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1808
1809      reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
1810
1811      if (PrintGCDetails && Verbose) {
1812        // Cannot use gclog_or_tty yet.
1813        tty->print_cr("  Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
1814      }
1815      FLAG_SET_ERGO(size_t, InitialHeapSize, (size_t)reasonable_initial);
1816    }
1817    // If the minimum heap size has not been set (via -Xms),
1818    // synchronize with InitialHeapSize to avoid errors with the default value.
1819    if (min_heap_size() == 0) {
1820      set_min_heap_size(MIN2((size_t)reasonable_minimum, InitialHeapSize));
1821      if (PrintGCDetails && Verbose) {
1822        // Cannot use gclog_or_tty yet.
1823        tty->print_cr("  Minimum heap size " SIZE_FORMAT, min_heap_size());
1824      }
1825    }
1826  }
1827}
1828
1829// This must be called after ergonomics.
1830void Arguments::set_bytecode_flags() {
1831  if (!RewriteBytecodes) {
1832    FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1833  }
1834}
1835
1836// Aggressive optimization flags  -XX:+AggressiveOpts
1837void Arguments::set_aggressive_opts_flags() {
1838#ifdef COMPILER2
1839  if (AggressiveUnboxing) {
1840    if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1841      FLAG_SET_DEFAULT(EliminateAutoBox, true);
1842    } else if (!EliminateAutoBox) {
1843      // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
1844      AggressiveUnboxing = false;
1845    }
1846    if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1847      FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1848    } else if (!DoEscapeAnalysis) {
1849      // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
1850      AggressiveUnboxing = false;
1851    }
1852  }
1853  if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1854    if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1855      FLAG_SET_DEFAULT(EliminateAutoBox, true);
1856    }
1857    if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1858      FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
1859    }
1860
1861    // Feed the cache size setting into the JDK
1862    char buffer[1024];
1863    sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
1864    add_property(buffer);
1865  }
1866  if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
1867    FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
1868  }
1869#endif
1870
1871  if (AggressiveOpts) {
1872// Sample flag setting code
1873//    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
1874//      FLAG_SET_DEFAULT(EliminateZeroing, true);
1875//    }
1876  }
1877}
1878
1879//===========================================================================================================
1880// Parsing of java.compiler property
1881
1882void Arguments::process_java_compiler_argument(char* arg) {
1883  // For backwards compatibility, Djava.compiler=NONE or ""
1884  // causes us to switch to -Xint mode UNLESS -Xdebug
1885  // is also specified.
1886  if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
1887    set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
1888  }
1889}
1890
1891void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1892  _sun_java_launcher = os::strdup_check_oom(launcher);
1893}
1894
1895bool Arguments::created_by_java_launcher() {
1896  assert(_sun_java_launcher != NULL, "property must have value");
1897  return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1898}
1899
1900bool Arguments::sun_java_launcher_is_altjvm() {
1901  return _sun_java_launcher_is_altjvm;
1902}
1903
1904//===========================================================================================================
1905// Parsing of main arguments
1906
1907// check if do gclog rotation
1908// +UseGCLogFileRotation is a must,
1909// no gc log rotation when log file not supplied or
1910// NumberOfGCLogFiles is 0
1911void check_gclog_consistency() {
1912  if (UseGCLogFileRotation) {
1913    if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {
1914      jio_fprintf(defaultStream::output_stream(),
1915                  "To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"
1916                  "where num_of_file > 0\n"
1917                  "GC log rotation is turned off\n");
1918      UseGCLogFileRotation = false;
1919    }
1920  }
1921
1922  if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {
1923    if (FLAG_SET_CMDLINE(size_t, GCLogFileSize, 8*K) == Flag::SUCCESS) {
1924      jio_fprintf(defaultStream::output_stream(),
1925                "GCLogFileSize changed to minimum 8K\n");
1926    }
1927  }
1928}
1929
1930// This function is called for -Xloggc:<filename>, it can be used
1931// to check if a given file name(or string) conforms to the following
1932// specification:
1933// A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"
1934// %p and %t only allowed once. We only limit usage of filename not path
1935bool is_filename_valid(const char *file_name) {
1936  const char* p = file_name;
1937  char file_sep = os::file_separator()[0];
1938  const char* cp;
1939  // skip prefix path
1940  for (cp = file_name; *cp != '\0'; cp++) {
1941    if (*cp == '/' || *cp == file_sep) {
1942      p = cp + 1;
1943    }
1944  }
1945
1946  int count_p = 0;
1947  int count_t = 0;
1948  while (*p != '\0') {
1949    if ((*p >= '0' && *p <= '9') ||
1950        (*p >= 'A' && *p <= 'Z') ||
1951        (*p >= 'a' && *p <= 'z') ||
1952         *p == '-'               ||
1953         *p == '_'               ||
1954         *p == '.') {
1955       p++;
1956       continue;
1957    }
1958    if (*p == '%') {
1959      if(*(p + 1) == 'p') {
1960        p += 2;
1961        count_p ++;
1962        continue;
1963      }
1964      if (*(p + 1) == 't') {
1965        p += 2;
1966        count_t ++;
1967        continue;
1968      }
1969    }
1970    return false;
1971  }
1972  return count_p < 2 && count_t < 2;
1973}
1974
1975// Check consistency of GC selection
1976bool Arguments::check_gc_consistency() {
1977  check_gclog_consistency();
1978  // Ensure that the user has not selected conflicting sets
1979  // of collectors.
1980  uint i = 0;
1981  if (UseSerialGC)                       i++;
1982  if (UseConcMarkSweepGC)                i++;
1983  if (UseParallelGC || UseParallelOldGC) i++;
1984  if (UseG1GC)                           i++;
1985  if (i > 1) {
1986    jio_fprintf(defaultStream::error_stream(),
1987                "Conflicting collector combinations in option list; "
1988                "please refer to the release notes for the combinations "
1989                "allowed\n");
1990    return false;
1991  }
1992
1993  if (UseConcMarkSweepGC && !UseParNewGC) {
1994    jio_fprintf(defaultStream::error_stream(),
1995        "It is not possible to combine the DefNew young collector with the CMS collector.\n");
1996    return false;
1997  }
1998
1999  if (UseParNewGC && !UseConcMarkSweepGC) {
2000    jio_fprintf(defaultStream::error_stream(),
2001        "It is not possible to combine the ParNew young collector with any collector other than CMS.\n");
2002    return false;
2003  }
2004
2005  return true;
2006}
2007
2008void Arguments::check_deprecated_gc_flags() {
2009  if (FLAG_IS_CMDLINE(UseParNewGC)) {
2010    warning("The UseParNewGC flag is deprecated and will likely be removed in a future release");
2011  }
2012  if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {
2013    warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
2014            "and will likely be removed in future release");
2015  }
2016  if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {
2017    warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "
2018        "Use MaxRAMFraction instead.");
2019  }
2020}
2021
2022// Check the consistency of vm_init_args
2023bool Arguments::check_vm_args_consistency() {
2024  // Method for adding checks for flag consistency.
2025  // The intent is to warn the user of all possible conflicts,
2026  // before returning an error.
2027  // Note: Needs platform-dependent factoring.
2028  bool status = true;
2029
2030  if (TLABRefillWasteFraction == 0) {
2031    jio_fprintf(defaultStream::error_stream(),
2032                "TLABRefillWasteFraction should be a denominator, "
2033                "not " SIZE_FORMAT "\n",
2034                TLABRefillWasteFraction);
2035    status = false;
2036  }
2037
2038  if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2039    MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
2040  }
2041
2042  if (UseParallelOldGC && ParallelOldGCSplitALot) {
2043    // Settings to encourage splitting.
2044    if (!FLAG_IS_CMDLINE(NewRatio)) {
2045      if (FLAG_SET_CMDLINE(uintx, NewRatio, 2) != Flag::SUCCESS) {
2046        status = false;
2047      }
2048    }
2049    if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
2050      if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2051        status = false;
2052      }
2053    }
2054  }
2055
2056  if (!(UseParallelGC || UseParallelOldGC) && FLAG_IS_DEFAULT(ScavengeBeforeFullGC)) {
2057    FLAG_SET_DEFAULT(ScavengeBeforeFullGC, false);
2058  }
2059
2060  if (GCTimeLimit == 100) {
2061    // Turn off gc-overhead-limit-exceeded checks
2062    FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2063  }
2064
2065  status = status && check_gc_consistency();
2066
2067  // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2068  // insists that we hold the requisite locks so that the iteration is
2069  // MT-safe. For the verification at start-up and shut-down, we don't
2070  // yet have a good way of acquiring and releasing these locks,
2071  // which are not visible at the CollectedHeap level. We want to
2072  // be able to acquire these locks and then do the iteration rather
2073  // than just disable the lock verification. This will be fixed under
2074  // bug 4788986.
2075  if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2076    if (VerifyDuringStartup) {
2077      warning("Heap verification at start-up disabled "
2078              "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2079      VerifyDuringStartup = false; // Disable verification at start-up
2080    }
2081
2082    if (VerifyBeforeExit) {
2083      warning("Heap verification at shutdown disabled "
2084              "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2085      VerifyBeforeExit = false; // Disable verification at shutdown
2086    }
2087  }
2088
2089  // Note: only executed in non-PRODUCT mode
2090  if (!UseAsyncConcMarkSweepGC &&
2091      (ExplicitGCInvokesConcurrent ||
2092       ExplicitGCInvokesConcurrentAndUnloadsClasses)) {
2093    jio_fprintf(defaultStream::error_stream(),
2094                "error: +ExplicitGCInvokesConcurrent[AndUnloadsClasses] conflicts"
2095                " with -UseAsyncConcMarkSweepGC");
2096    status = false;
2097  }
2098
2099  if (PrintNMTStatistics) {
2100#if INCLUDE_NMT
2101    if (MemTracker::tracking_level() == NMT_off) {
2102#endif // INCLUDE_NMT
2103      warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2104      PrintNMTStatistics = false;
2105#if INCLUDE_NMT
2106    }
2107#endif
2108  }
2109
2110  // Check lower bounds of the code cache
2111  // Template Interpreter code is approximately 3X larger in debug builds.
2112  uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2113  if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2114    jio_fprintf(defaultStream::error_stream(),
2115                "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
2116                os::vm_page_size()/K);
2117    status = false;
2118  } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2119    jio_fprintf(defaultStream::error_stream(),
2120                "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2121                ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2122    status = false;
2123  } else if (ReservedCodeCacheSize < min_code_cache_size) {
2124    jio_fprintf(defaultStream::error_stream(),
2125                "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2126                min_code_cache_size/K);
2127    status = false;
2128  } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2129    // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2130    jio_fprintf(defaultStream::error_stream(),
2131                "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2132                CODE_CACHE_SIZE_LIMIT/M);
2133    status = false;
2134  } else if (NonNMethodCodeHeapSize < min_code_cache_size){
2135    jio_fprintf(defaultStream::error_stream(),
2136                "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2137                min_code_cache_size/K);
2138    status = false;
2139  } else if ((!FLAG_IS_DEFAULT(NonNMethodCodeHeapSize) || !FLAG_IS_DEFAULT(ProfiledCodeHeapSize) || !FLAG_IS_DEFAULT(NonProfiledCodeHeapSize))
2140             && (NonNMethodCodeHeapSize + NonProfiledCodeHeapSize + ProfiledCodeHeapSize) != ReservedCodeCacheSize) {
2141    jio_fprintf(defaultStream::error_stream(),
2142                "Invalid code heap sizes: NonNMethodCodeHeapSize(%dK) + ProfiledCodeHeapSize(%dK) + NonProfiledCodeHeapSize(%dK) = %dK. Must be equal to ReservedCodeCacheSize = %uK.\n",
2143                NonNMethodCodeHeapSize/K, ProfiledCodeHeapSize/K, NonProfiledCodeHeapSize/K,
2144                (NonNMethodCodeHeapSize + ProfiledCodeHeapSize + NonProfiledCodeHeapSize)/K, ReservedCodeCacheSize/K);
2145    status = false;
2146  }
2147
2148  int min_number_of_compiler_threads = get_min_number_of_compiler_threads();
2149  // The default CICompilerCount's value is CI_COMPILER_COUNT.
2150  assert(min_number_of_compiler_threads <= CI_COMPILER_COUNT, "minimum should be less or equal default number");
2151
2152  if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2153    warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2154  }
2155
2156  return status;
2157}
2158
2159bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2160  const char* option_type) {
2161  if (ignore) return false;
2162
2163  const char* spacer = " ";
2164  if (option_type == NULL) {
2165    option_type = ++spacer; // Set both to the empty string.
2166  }
2167
2168  if (os::obsolete_option(option)) {
2169    jio_fprintf(defaultStream::error_stream(),
2170                "Obsolete %s%soption: %s\n", option_type, spacer,
2171      option->optionString);
2172    return false;
2173  } else {
2174    jio_fprintf(defaultStream::error_stream(),
2175                "Unrecognized %s%soption: %s\n", option_type, spacer,
2176      option->optionString);
2177    return true;
2178  }
2179}
2180
2181static const char* user_assertion_options[] = {
2182  "-da", "-ea", "-disableassertions", "-enableassertions", 0
2183};
2184
2185static const char* system_assertion_options[] = {
2186  "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2187};
2188
2189bool Arguments::parse_uintx(const char* value,
2190                            uintx* uintx_arg,
2191                            uintx min_size) {
2192
2193  // Check the sign first since atomull() parses only unsigned values.
2194  bool value_is_positive = !(*value == '-');
2195
2196  if (value_is_positive) {
2197    julong n;
2198    bool good_return = atomull(value, &n);
2199    if (good_return) {
2200      bool above_minimum = n >= min_size;
2201      bool value_is_too_large = n > max_uintx;
2202
2203      if (above_minimum && !value_is_too_large) {
2204        *uintx_arg = n;
2205        return true;
2206      }
2207    }
2208  }
2209  return false;
2210}
2211
2212Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2213                                                  julong* long_arg,
2214                                                  julong min_size) {
2215  if (!atomull(s, long_arg)) return arg_unreadable;
2216  return check_memory_size(*long_arg, min_size);
2217}
2218
2219// Parse JavaVMInitArgs structure
2220
2221jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {
2222  // For components of the system classpath.
2223  SysClassPath scp(Arguments::get_sysclasspath());
2224  bool scp_assembly_required = false;
2225
2226  // Save default settings for some mode flags
2227  Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2228  Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2229  Arguments::_ClipInlining             = ClipInlining;
2230  Arguments::_BackgroundCompilation    = BackgroundCompilation;
2231  if (TieredCompilation) {
2232    Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2233    Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2234  }
2235
2236  // Setup flags for mixed which is the default
2237  set_mode_flags(_mixed);
2238
2239  // Parse JAVA_TOOL_OPTIONS environment variable (if present)
2240  jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);
2241  if (result != JNI_OK) {
2242    return result;
2243  }
2244
2245  // Parse JavaVMInitArgs structure passed in
2246  result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, Flag::COMMAND_LINE);
2247  if (result != JNI_OK) {
2248    return result;
2249  }
2250
2251  // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
2252  result = parse_java_options_environment_variable(&scp, &scp_assembly_required);
2253  if (result != JNI_OK) {
2254    return result;
2255  }
2256
2257  // Do final processing now that all arguments have been parsed
2258  result = finalize_vm_init_args(&scp, scp_assembly_required);
2259  if (result != JNI_OK) {
2260    return result;
2261  }
2262
2263  return JNI_OK;
2264}
2265
2266// Checks if name in command-line argument -agent{lib,path}:name[=options]
2267// represents a valid HPROF of JDWP agent.  is_path==true denotes that we
2268// are dealing with -agentpath (case where name is a path), otherwise with
2269// -agentlib
2270bool valid_hprof_or_jdwp_agent(char *name, bool is_path) {
2271  char *_name;
2272  const char *_hprof = "hprof", *_jdwp = "jdwp";
2273  size_t _len_hprof, _len_jdwp, _len_prefix;
2274
2275  if (is_path) {
2276    if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2277      return false;
2278    }
2279
2280    _name++;  // skip past last path separator
2281    _len_prefix = strlen(JNI_LIB_PREFIX);
2282
2283    if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2284      return false;
2285    }
2286
2287    _name += _len_prefix;
2288    _len_hprof = strlen(_hprof);
2289    _len_jdwp = strlen(_jdwp);
2290
2291    if (strncmp(_name, _hprof, _len_hprof) == 0) {
2292      _name += _len_hprof;
2293    }
2294    else if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2295      _name += _len_jdwp;
2296    }
2297    else {
2298      return false;
2299    }
2300
2301    if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2302      return false;
2303    }
2304
2305    return true;
2306  }
2307
2308  if (strcmp(name, _hprof) == 0 || strcmp(name, _jdwp) == 0) {
2309    return true;
2310  }
2311
2312  return false;
2313}
2314
2315jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2316                                       SysClassPath* scp_p,
2317                                       bool* scp_assembly_required_p,
2318                                       Flag::Flags origin) {
2319  // Remaining part of option string
2320  const char* tail;
2321
2322  // iterate over arguments
2323  for (int index = 0; index < args->nOptions; index++) {
2324    bool is_absolute_path = false;  // for -agentpath vs -agentlib
2325
2326    const JavaVMOption* option = args->options + index;
2327
2328    if (!match_option(option, "-Djava.class.path", &tail) &&
2329        !match_option(option, "-Dsun.java.command", &tail) &&
2330        !match_option(option, "-Dsun.java.launcher", &tail)) {
2331
2332        // add all jvm options to the jvm_args string. This string
2333        // is used later to set the java.vm.args PerfData string constant.
2334        // the -Djava.class.path and the -Dsun.java.command options are
2335        // omitted from jvm_args string as each have their own PerfData
2336        // string constant object.
2337        build_jvm_args(option->optionString);
2338    }
2339
2340    // -verbose:[class/gc/jni]
2341    if (match_option(option, "-verbose", &tail)) {
2342      if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2343        if (FLAG_SET_CMDLINE(bool, TraceClassLoading, true) != Flag::SUCCESS) {
2344          return JNI_EINVAL;
2345        }
2346        if (FLAG_SET_CMDLINE(bool, TraceClassUnloading, true) != Flag::SUCCESS) {
2347          return JNI_EINVAL;
2348        }
2349      } else if (!strcmp(tail, ":gc")) {
2350        if (FLAG_SET_CMDLINE(bool, PrintGC, true) != Flag::SUCCESS) {
2351          return JNI_EINVAL;
2352        }
2353      } else if (!strcmp(tail, ":jni")) {
2354        if (FLAG_SET_CMDLINE(bool, PrintJNIResolving, true) != Flag::SUCCESS) {
2355          return JNI_EINVAL;
2356        }
2357      }
2358    // -da / -ea / -disableassertions / -enableassertions
2359    // These accept an optional class/package name separated by a colon, e.g.,
2360    // -da:java.lang.Thread.
2361    } else if (match_option(option, user_assertion_options, &tail, true)) {
2362      bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2363      if (*tail == '\0') {
2364        JavaAssertions::setUserClassDefault(enable);
2365      } else {
2366        assert(*tail == ':', "bogus match by match_option()");
2367        JavaAssertions::addOption(tail + 1, enable);
2368      }
2369    // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2370    } else if (match_option(option, system_assertion_options, &tail, false)) {
2371      bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2372      JavaAssertions::setSystemClassDefault(enable);
2373    // -bootclasspath:
2374    } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2375      scp_p->reset_path(tail);
2376      *scp_assembly_required_p = true;
2377    // -bootclasspath/a:
2378    } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2379      scp_p->add_suffix(tail);
2380      *scp_assembly_required_p = true;
2381    // -bootclasspath/p:
2382    } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2383      scp_p->add_prefix(tail);
2384      *scp_assembly_required_p = true;
2385    // -Xrun
2386    } else if (match_option(option, "-Xrun", &tail)) {
2387      if (tail != NULL) {
2388        const char* pos = strchr(tail, ':');
2389        size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2390        char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2391        name[len] = '\0';
2392
2393        char *options = NULL;
2394        if(pos != NULL) {
2395          size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2396          options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
2397        }
2398#if !INCLUDE_JVMTI
2399        if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
2400          jio_fprintf(defaultStream::error_stream(),
2401            "Profiling and debugging agents are not supported in this VM\n");
2402          return JNI_ERR;
2403        }
2404#endif // !INCLUDE_JVMTI
2405        add_init_library(name, options);
2406      }
2407    // -agentlib and -agentpath
2408    } else if (match_option(option, "-agentlib:", &tail) ||
2409          (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2410      if(tail != NULL) {
2411        const char* pos = strchr(tail, '=');
2412        size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2413        char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2414        name[len] = '\0';
2415
2416        char *options = NULL;
2417        if(pos != NULL) {
2418          options = os::strdup_check_oom(pos + 1, mtInternal);
2419        }
2420#if !INCLUDE_JVMTI
2421        if (valid_hprof_or_jdwp_agent(name, is_absolute_path)) {
2422          jio_fprintf(defaultStream::error_stream(),
2423            "Profiling and debugging agents are not supported in this VM\n");
2424          return JNI_ERR;
2425        }
2426#endif // !INCLUDE_JVMTI
2427        add_init_agent(name, options, is_absolute_path);
2428      }
2429    // -javaagent
2430    } else if (match_option(option, "-javaagent:", &tail)) {
2431#if !INCLUDE_JVMTI
2432      jio_fprintf(defaultStream::error_stream(),
2433        "Instrumentation agents are not supported in this VM\n");
2434      return JNI_ERR;
2435#else
2436      if(tail != NULL) {
2437        char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtInternal), tail);
2438        add_init_agent("instrument", options, false);
2439      }
2440#endif // !INCLUDE_JVMTI
2441    // -Xnoclassgc
2442    } else if (match_option(option, "-Xnoclassgc")) {
2443      if (FLAG_SET_CMDLINE(bool, ClassUnloading, false) != Flag::SUCCESS) {
2444        return JNI_EINVAL;
2445      }
2446    // -Xconcgc
2447    } else if (match_option(option, "-Xconcgc")) {
2448      if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true) != Flag::SUCCESS) {
2449        return JNI_EINVAL;
2450      }
2451    // -Xnoconcgc
2452    } else if (match_option(option, "-Xnoconcgc")) {
2453      if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false) != Flag::SUCCESS) {
2454        return JNI_EINVAL;
2455      }
2456    // -Xbatch
2457    } else if (match_option(option, "-Xbatch")) {
2458      if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2459        return JNI_EINVAL;
2460      }
2461    // -Xmn for compatibility with other JVM vendors
2462    } else if (match_option(option, "-Xmn", &tail)) {
2463      julong long_initial_young_size = 0;
2464      ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2465      if (errcode != arg_in_range) {
2466        jio_fprintf(defaultStream::error_stream(),
2467                    "Invalid initial young generation size: %s\n", option->optionString);
2468        describe_range_error(errcode);
2469        return JNI_EINVAL;
2470      }
2471      if (FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2472        return JNI_EINVAL;
2473      }
2474      if (FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2475        return JNI_EINVAL;
2476      }
2477    // -Xms
2478    } else if (match_option(option, "-Xms", &tail)) {
2479      julong long_initial_heap_size = 0;
2480      // an initial heap size of 0 means automatically determine
2481      ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2482      if (errcode != arg_in_range) {
2483        jio_fprintf(defaultStream::error_stream(),
2484                    "Invalid initial heap size: %s\n", option->optionString);
2485        describe_range_error(errcode);
2486        return JNI_EINVAL;
2487      }
2488      set_min_heap_size((size_t)long_initial_heap_size);
2489      // Currently the minimum size and the initial heap sizes are the same.
2490      // Can be overridden with -XX:InitialHeapSize.
2491      if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size) != Flag::SUCCESS) {
2492        return JNI_EINVAL;
2493      }
2494    // -Xmx
2495    } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2496      julong long_max_heap_size = 0;
2497      ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2498      if (errcode != arg_in_range) {
2499        jio_fprintf(defaultStream::error_stream(),
2500                    "Invalid maximum heap size: %s\n", option->optionString);
2501        describe_range_error(errcode);
2502        return JNI_EINVAL;
2503      }
2504      if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size) != Flag::SUCCESS) {
2505        return JNI_EINVAL;
2506      }
2507    // Xmaxf
2508    } else if (match_option(option, "-Xmaxf", &tail)) {
2509      char* err;
2510      int maxf = (int)(strtod(tail, &err) * 100);
2511      if (*err != '\0' || *tail == '\0') {
2512        jio_fprintf(defaultStream::error_stream(),
2513                    "Bad max heap free percentage size: %s\n",
2514                    option->optionString);
2515        return JNI_EINVAL;
2516      } else {
2517        if (FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf) != Flag::SUCCESS) {
2518            return JNI_EINVAL;
2519        }
2520      }
2521    // Xminf
2522    } else if (match_option(option, "-Xminf", &tail)) {
2523      char* err;
2524      int minf = (int)(strtod(tail, &err) * 100);
2525      if (*err != '\0' || *tail == '\0') {
2526        jio_fprintf(defaultStream::error_stream(),
2527                    "Bad min heap free percentage size: %s\n",
2528                    option->optionString);
2529        return JNI_EINVAL;
2530      } else {
2531        if (FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf) != Flag::SUCCESS) {
2532          return JNI_EINVAL;
2533        }
2534      }
2535    // -Xss
2536    } else if (match_option(option, "-Xss", &tail)) {
2537      julong long_ThreadStackSize = 0;
2538      ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2539      if (errcode != arg_in_range) {
2540        jio_fprintf(defaultStream::error_stream(),
2541                    "Invalid thread stack size: %s\n", option->optionString);
2542        describe_range_error(errcode);
2543        return JNI_EINVAL;
2544      }
2545      // Internally track ThreadStackSize in units of 1024 bytes.
2546      if (FLAG_SET_CMDLINE(intx, ThreadStackSize,
2547                       round_to((int)long_ThreadStackSize, K) / K) != Flag::SUCCESS) {
2548        return JNI_EINVAL;
2549      }
2550    // -Xoss
2551    } else if (match_option(option, "-Xoss", &tail)) {
2552          // HotSpot does not have separate native and Java stacks, ignore silently for compatibility
2553    } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
2554      julong long_CodeCacheExpansionSize = 0;
2555      ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
2556      if (errcode != arg_in_range) {
2557        jio_fprintf(defaultStream::error_stream(),
2558                   "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
2559                   os::vm_page_size()/K);
2560        return JNI_EINVAL;
2561      }
2562      if (FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize) != Flag::SUCCESS) {
2563        return JNI_EINVAL;
2564      }
2565    } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2566               match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2567      julong long_ReservedCodeCacheSize = 0;
2568
2569      ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2570      if (errcode != arg_in_range) {
2571        jio_fprintf(defaultStream::error_stream(),
2572                    "Invalid maximum code cache size: %s.\n", option->optionString);
2573        return JNI_EINVAL;
2574      }
2575      if (FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != Flag::SUCCESS) {
2576        return JNI_EINVAL;
2577      }
2578      // -XX:NonNMethodCodeHeapSize=
2579    } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
2580      julong long_NonNMethodCodeHeapSize = 0;
2581
2582      ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
2583      if (errcode != arg_in_range) {
2584        jio_fprintf(defaultStream::error_stream(),
2585                    "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
2586        return JNI_EINVAL;
2587      }
2588      if (FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize) != Flag::SUCCESS) {
2589        return JNI_EINVAL;
2590      }
2591      // -XX:ProfiledCodeHeapSize=
2592    } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
2593      julong long_ProfiledCodeHeapSize = 0;
2594
2595      ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
2596      if (errcode != arg_in_range) {
2597        jio_fprintf(defaultStream::error_stream(),
2598                    "Invalid maximum profiled code heap size: %s.\n", option->optionString);
2599        return JNI_EINVAL;
2600      }
2601      if (FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize) != Flag::SUCCESS) {
2602        return JNI_EINVAL;
2603      }
2604      // -XX:NonProfiledCodeHeapSizee=
2605    } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
2606      julong long_NonProfiledCodeHeapSize = 0;
2607
2608      ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
2609      if (errcode != arg_in_range) {
2610        jio_fprintf(defaultStream::error_stream(),
2611                    "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
2612        return JNI_EINVAL;
2613      }
2614      if (FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize) != Flag::SUCCESS) {
2615        return JNI_EINVAL;
2616      }
2617    // -green
2618    } else if (match_option(option, "-green")) {
2619      jio_fprintf(defaultStream::error_stream(),
2620                  "Green threads support not available\n");
2621          return JNI_EINVAL;
2622    // -native
2623    } else if (match_option(option, "-native")) {
2624          // HotSpot always uses native threads, ignore silently for compatibility
2625    // -Xsqnopause
2626    } else if (match_option(option, "-Xsqnopause")) {
2627          // EVM option, ignore silently for compatibility
2628    // -Xrs
2629    } else if (match_option(option, "-Xrs")) {
2630          // Classic/EVM option, new functionality
2631      if (FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true) != Flag::SUCCESS) {
2632        return JNI_EINVAL;
2633      }
2634    } else if (match_option(option, "-Xusealtsigs")) {
2635          // change default internal VM signals used - lower case for back compat
2636      if (FLAG_SET_CMDLINE(bool, UseAltSigs, true) != Flag::SUCCESS) {
2637        return JNI_EINVAL;
2638      }
2639    // -Xoptimize
2640    } else if (match_option(option, "-Xoptimize")) {
2641          // EVM option, ignore silently for compatibility
2642    // -Xprof
2643    } else if (match_option(option, "-Xprof")) {
2644#if INCLUDE_FPROF
2645      _has_profile = true;
2646#else // INCLUDE_FPROF
2647      jio_fprintf(defaultStream::error_stream(),
2648        "Flat profiling is not supported in this VM.\n");
2649      return JNI_ERR;
2650#endif // INCLUDE_FPROF
2651    // -Xconcurrentio
2652    } else if (match_option(option, "-Xconcurrentio")) {
2653      if (FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true) != Flag::SUCCESS) {
2654        return JNI_EINVAL;
2655      }
2656      if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2657        return JNI_EINVAL;
2658      }
2659      if (FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1) != Flag::SUCCESS) {
2660        return JNI_EINVAL;
2661      }
2662      if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
2663        return JNI_EINVAL;
2664      }
2665      if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
2666        return JNI_EINVAL;
2667      }
2668
2669      // -Xinternalversion
2670    } else if (match_option(option, "-Xinternalversion")) {
2671      jio_fprintf(defaultStream::output_stream(), "%s\n",
2672                  VM_Version::internal_vm_info_string());
2673      vm_exit(0);
2674#ifndef PRODUCT
2675    // -Xprintflags
2676    } else if (match_option(option, "-Xprintflags")) {
2677      CommandLineFlags::printFlags(tty, false);
2678      vm_exit(0);
2679#endif
2680    // -D
2681    } else if (match_option(option, "-D", &tail)) {
2682      const char* value;
2683      if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2684            *value!= '\0' && strcmp(value, "\"\"") != 0) {
2685        // abort if -Djava.endorsed.dirs is set
2686        jio_fprintf(defaultStream::output_stream(),
2687          "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2688          "in modular form will be supported via the concept of upgradeable modules.\n", value);
2689        return JNI_EINVAL;
2690      }
2691      if (match_option(option, "-Djava.ext.dirs=", &value) &&
2692            *value != '\0' && strcmp(value, "\"\"") != 0) {
2693        // abort if -Djava.ext.dirs is set
2694        jio_fprintf(defaultStream::output_stream(),
2695          "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2696        return JNI_EINVAL;
2697      }
2698
2699      if (!add_property(tail)) {
2700        return JNI_ENOMEM;
2701      }
2702      // Out of the box management support
2703      if (match_option(option, "-Dcom.sun.management", &tail)) {
2704#if INCLUDE_MANAGEMENT
2705        if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
2706          return JNI_EINVAL;
2707        }
2708#else
2709        jio_fprintf(defaultStream::output_stream(),
2710          "-Dcom.sun.management is not supported in this VM.\n");
2711        return JNI_ERR;
2712#endif
2713      }
2714    // -Xint
2715    } else if (match_option(option, "-Xint")) {
2716          set_mode_flags(_int);
2717    // -Xmixed
2718    } else if (match_option(option, "-Xmixed")) {
2719          set_mode_flags(_mixed);
2720    // -Xcomp
2721    } else if (match_option(option, "-Xcomp")) {
2722      // for testing the compiler; turn off all flags that inhibit compilation
2723          set_mode_flags(_comp);
2724    // -Xshare:dump
2725    } else if (match_option(option, "-Xshare:dump")) {
2726      if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
2727        return JNI_EINVAL;
2728      }
2729      set_mode_flags(_int);     // Prevent compilation, which creates objects
2730    // -Xshare:on
2731    } else if (match_option(option, "-Xshare:on")) {
2732      if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
2733        return JNI_EINVAL;
2734      }
2735      if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
2736        return JNI_EINVAL;
2737      }
2738    // -Xshare:auto
2739    } else if (match_option(option, "-Xshare:auto")) {
2740      if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
2741        return JNI_EINVAL;
2742      }
2743      if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
2744        return JNI_EINVAL;
2745      }
2746    // -Xshare:off
2747    } else if (match_option(option, "-Xshare:off")) {
2748      if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
2749        return JNI_EINVAL;
2750      }
2751      if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
2752        return JNI_EINVAL;
2753      }
2754    // -Xverify
2755    } else if (match_option(option, "-Xverify", &tail)) {
2756      if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
2757        if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
2758          return JNI_EINVAL;
2759        }
2760        if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
2761          return JNI_EINVAL;
2762        }
2763      } else if (strcmp(tail, ":remote") == 0) {
2764        if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
2765          return JNI_EINVAL;
2766        }
2767        if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
2768          return JNI_EINVAL;
2769        }
2770      } else if (strcmp(tail, ":none") == 0) {
2771        if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
2772          return JNI_EINVAL;
2773        }
2774        if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
2775          return JNI_EINVAL;
2776        }
2777      } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
2778        return JNI_EINVAL;
2779      }
2780    // -Xdebug
2781    } else if (match_option(option, "-Xdebug")) {
2782      // note this flag has been used, then ignore
2783      set_xdebug_mode(true);
2784    // -Xnoagent
2785    } else if (match_option(option, "-Xnoagent")) {
2786      // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
2787    } else if (match_option(option, "-Xboundthreads")) {
2788      // Ignore silently for compatibility
2789    } else if (match_option(option, "-Xloggc:", &tail)) {
2790      // Redirect GC output to the file. -Xloggc:<filename>
2791      // ostream_init_log(), when called will use this filename
2792      // to initialize a fileStream.
2793      _gc_log_filename = os::strdup_check_oom(tail);
2794     if (!is_filename_valid(_gc_log_filename)) {
2795       jio_fprintf(defaultStream::output_stream(),
2796                  "Invalid file name for use with -Xloggc: Filename can only contain the "
2797                  "characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"
2798                  "Note %%p or %%t can only be used once\n", _gc_log_filename);
2799        return JNI_EINVAL;
2800      }
2801      if (FLAG_SET_CMDLINE(bool, PrintGC, true) != Flag::SUCCESS) {
2802        return JNI_EINVAL;
2803      }
2804      if (FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true) != Flag::SUCCESS) {
2805        return JNI_EINVAL;
2806      }
2807    // JNI hooks
2808    } else if (match_option(option, "-Xcheck", &tail)) {
2809      if (!strcmp(tail, ":jni")) {
2810#if !INCLUDE_JNI_CHECK
2811        warning("JNI CHECKING is not supported in this VM");
2812#else
2813        CheckJNICalls = true;
2814#endif // INCLUDE_JNI_CHECK
2815      } else if (is_bad_option(option, args->ignoreUnrecognized,
2816                                     "check")) {
2817        return JNI_EINVAL;
2818      }
2819    } else if (match_option(option, "vfprintf")) {
2820      _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
2821    } else if (match_option(option, "exit")) {
2822      _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
2823    } else if (match_option(option, "abort")) {
2824      _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
2825    // -XX:+AggressiveHeap
2826    } else if (match_option(option, "-XX:+AggressiveHeap")) {
2827
2828      // This option inspects the machine and attempts to set various
2829      // parameters to be optimal for long-running, memory allocation
2830      // intensive jobs.  It is intended for machines with large
2831      // amounts of cpu and memory.
2832
2833      // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
2834      // VM, but we may not be able to represent the total physical memory
2835      // available (like having 8gb of memory on a box but using a 32bit VM).
2836      // Thus, we need to make sure we're using a julong for intermediate
2837      // calculations.
2838      julong initHeapSize;
2839      julong total_memory = os::physical_memory();
2840
2841      if (total_memory < (julong)256*M) {
2842        jio_fprintf(defaultStream::error_stream(),
2843                    "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
2844        vm_exit(1);
2845      }
2846
2847      // The heap size is half of available memory, or (at most)
2848      // all of possible memory less 160mb (leaving room for the OS
2849      // when using ISM).  This is the maximum; because adaptive sizing
2850      // is turned on below, the actual space used may be smaller.
2851
2852      initHeapSize = MIN2(total_memory / (julong)2,
2853                          total_memory - (julong)160*M);
2854
2855      initHeapSize = limit_by_allocatable_memory(initHeapSize);
2856
2857      if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2858         if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, initHeapSize) != Flag::SUCCESS) {
2859           return JNI_EINVAL;
2860         }
2861         if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, initHeapSize) != Flag::SUCCESS) {
2862           return JNI_EINVAL;
2863         }
2864         // Currently the minimum size and the initial heap sizes are the same.
2865         set_min_heap_size(initHeapSize);
2866      }
2867      if (FLAG_IS_DEFAULT(NewSize)) {
2868         // Make the young generation 3/8ths of the total heap.
2869         if (FLAG_SET_CMDLINE(size_t, NewSize,
2870                                ((julong)MaxHeapSize / (julong)8) * (julong)3) != Flag::SUCCESS) {
2871           return JNI_EINVAL;
2872         }
2873         if (FLAG_SET_CMDLINE(size_t, MaxNewSize, NewSize) != Flag::SUCCESS) {
2874           return JNI_EINVAL;
2875         }
2876      }
2877
2878#if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
2879      FLAG_SET_DEFAULT(UseLargePages, true);
2880#endif
2881
2882      // Increase some data structure sizes for efficiency
2883      if (FLAG_SET_CMDLINE(size_t, BaseFootPrintEstimate, MaxHeapSize) != Flag::SUCCESS) {
2884        return JNI_EINVAL;
2885      }
2886      if (FLAG_SET_CMDLINE(bool, ResizeTLAB, false) != Flag::SUCCESS) {
2887        return JNI_EINVAL;
2888      }
2889      if (FLAG_SET_CMDLINE(size_t, TLABSize, 256*K) != Flag::SUCCESS) {
2890        return JNI_EINVAL;
2891      }
2892
2893      // See the OldPLABSize comment below, but replace 'after promotion'
2894      // with 'after copying'.  YoungPLABSize is the size of the survivor
2895      // space per-gc-thread buffers.  The default is 4kw.
2896      if (FLAG_SET_CMDLINE(size_t, YoungPLABSize, 256*K) != Flag::SUCCESS) {      // Note: this is in words
2897        return JNI_EINVAL;
2898      }
2899
2900      // OldPLABSize is the size of the buffers in the old gen that
2901      // UseParallelGC uses to promote live data that doesn't fit in the
2902      // survivor spaces.  At any given time, there's one for each gc thread.
2903      // The default size is 1kw. These buffers are rarely used, since the
2904      // survivor spaces are usually big enough.  For specjbb, however, there
2905      // are occasions when there's lots of live data in the young gen
2906      // and we end up promoting some of it.  We don't have a definite
2907      // explanation for why bumping OldPLABSize helps, but the theory
2908      // is that a bigger PLAB results in retaining something like the
2909      // original allocation order after promotion, which improves mutator
2910      // locality.  A minor effect may be that larger PLABs reduce the
2911      // number of PLAB allocation events during gc.  The value of 8kw
2912      // was arrived at by experimenting with specjbb.
2913      if (FLAG_SET_CMDLINE(size_t, OldPLABSize, 8*K) != Flag::SUCCESS) {  // Note: this is in words
2914        return JNI_EINVAL;
2915      }
2916
2917      // Enable parallel GC and adaptive generation sizing
2918      if (FLAG_SET_CMDLINE(bool, UseParallelGC, true) != Flag::SUCCESS) {
2919        return JNI_EINVAL;
2920      }
2921      FLAG_SET_DEFAULT(ParallelGCThreads,
2922                       Abstract_VM_Version::parallel_worker_threads());
2923
2924      // Encourage steady state memory management
2925      if (FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100) != Flag::SUCCESS) {
2926        return JNI_EINVAL;
2927      }
2928
2929      // This appears to improve mutator locality
2930      if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2931        return JNI_EINVAL;
2932      }
2933
2934      // Get around early Solaris scheduling bug
2935      // (affinity vs other jobs on system)
2936      // but disallow DR and offlining (5008695).
2937      if (FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true) != Flag::SUCCESS) {
2938        return JNI_EINVAL;
2939      }
2940
2941    // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
2942    // and the last option wins.
2943    } else if (match_option(option, "-XX:+NeverTenure")) {
2944      if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
2945        return JNI_EINVAL;
2946      }
2947      if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
2948        return JNI_EINVAL;
2949      }
2950      if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
2951        return JNI_EINVAL;
2952      }
2953    } else if (match_option(option, "-XX:+AlwaysTenure")) {
2954      if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
2955        return JNI_EINVAL;
2956      }
2957      if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
2958        return JNI_EINVAL;
2959      }
2960      if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
2961        return JNI_EINVAL;
2962      }
2963    } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
2964      uintx max_tenuring_thresh = 0;
2965      if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
2966        jio_fprintf(defaultStream::error_stream(),
2967                    "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
2968        return JNI_EINVAL;
2969      }
2970
2971      if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
2972        return JNI_EINVAL;
2973      }
2974
2975      if (MaxTenuringThreshold == 0) {
2976        if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
2977          return JNI_EINVAL;
2978        }
2979        if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
2980          return JNI_EINVAL;
2981        }
2982      } else {
2983        if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
2984          return JNI_EINVAL;
2985        }
2986        if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
2987          return JNI_EINVAL;
2988        }
2989      }
2990    } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
2991      if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
2992        return JNI_EINVAL;
2993      }
2994      if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
2995        return JNI_EINVAL;
2996      }
2997    } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
2998      if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
2999        return JNI_EINVAL;
3000      }
3001      if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3002        return JNI_EINVAL;
3003      }
3004    } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3005#if defined(DTRACE_ENABLED)
3006      if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3007        return JNI_EINVAL;
3008      }
3009      if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3010        return JNI_EINVAL;
3011      }
3012      if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3013        return JNI_EINVAL;
3014      }
3015      if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3016        return JNI_EINVAL;
3017      }
3018#else // defined(DTRACE_ENABLED)
3019      jio_fprintf(defaultStream::error_stream(),
3020                  "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3021      return JNI_EINVAL;
3022#endif // defined(DTRACE_ENABLED)
3023#ifdef ASSERT
3024    } else if (match_option(option, "-XX:+FullGCALot")) {
3025      if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3026        return JNI_EINVAL;
3027      }
3028      // disable scavenge before parallel mark-compact
3029      if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3030        return JNI_EINVAL;
3031      }
3032#endif
3033    } else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||
3034               match_option(option, "-XX:G1MarkStackSize=", &tail)) {
3035      julong stack_size = 0;
3036      ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);
3037      if (errcode != arg_in_range) {
3038        jio_fprintf(defaultStream::error_stream(),
3039                    "Invalid mark stack size: %s\n", option->optionString);
3040        describe_range_error(errcode);
3041        return JNI_EINVAL;
3042      }
3043      jio_fprintf(defaultStream::error_stream(),
3044        "Please use -XX:MarkStackSize in place of "
3045        "-XX:CMSMarkStackSize or -XX:G1MarkStackSize in the future\n");
3046      if (FLAG_SET_CMDLINE(size_t, MarkStackSize, stack_size) != Flag::SUCCESS) {
3047        return JNI_EINVAL;
3048      }
3049    } else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {
3050      julong max_stack_size = 0;
3051      ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);
3052      if (errcode != arg_in_range) {
3053        jio_fprintf(defaultStream::error_stream(),
3054                    "Invalid maximum mark stack size: %s\n",
3055                    option->optionString);
3056        describe_range_error(errcode);
3057        return JNI_EINVAL;
3058      }
3059      jio_fprintf(defaultStream::error_stream(),
3060         "Please use -XX:MarkStackSizeMax in place of "
3061         "-XX:CMSMarkStackSizeMax in the future\n");
3062      if (FLAG_SET_CMDLINE(size_t, MarkStackSizeMax, max_stack_size) != Flag::SUCCESS) {
3063        return JNI_EINVAL;
3064      }
3065    } else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||
3066               match_option(option, "-XX:ParallelCMSThreads=", &tail)) {
3067      uintx conc_threads = 0;
3068      if (!parse_uintx(tail, &conc_threads, 1)) {
3069        jio_fprintf(defaultStream::error_stream(),
3070                    "Invalid concurrent threads: %s\n", option->optionString);
3071        return JNI_EINVAL;
3072      }
3073      jio_fprintf(defaultStream::error_stream(),
3074        "Please use -XX:ConcGCThreads in place of "
3075        "-XX:ParallelMarkingThreads or -XX:ParallelCMSThreads in the future\n");
3076      if (FLAG_SET_CMDLINE(uint, ConcGCThreads, conc_threads) != Flag::SUCCESS) {
3077        return JNI_EINVAL;
3078      }
3079    } else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {
3080      julong max_direct_memory_size = 0;
3081      ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);
3082      if (errcode != arg_in_range) {
3083        jio_fprintf(defaultStream::error_stream(),
3084                    "Invalid maximum direct memory size: %s\n",
3085                    option->optionString);
3086        describe_range_error(errcode);
3087        return JNI_EINVAL;
3088      }
3089      if (FLAG_SET_CMDLINE(size_t, MaxDirectMemorySize, max_direct_memory_size) != Flag::SUCCESS) {
3090        return JNI_EINVAL;
3091      }
3092#if !INCLUDE_MANAGEMENT
3093    } else if (match_option(option, "-XX:+ManagementServer")) {
3094        jio_fprintf(defaultStream::error_stream(),
3095          "ManagementServer is not supported in this VM.\n");
3096        return JNI_ERR;
3097#endif // INCLUDE_MANAGEMENT
3098    // CreateMinidumpOnCrash is removed, and replaced by CreateCoredumpOnCrash
3099    } else if (match_option(option, "-XX:+CreateMinidumpOnCrash")) {
3100      if (FLAG_SET_CMDLINE(bool, CreateCoredumpOnCrash, true) != Flag::SUCCESS) {
3101        return JNI_EINVAL;
3102      }
3103      jio_fprintf(defaultStream::output_stream(),
3104          "CreateMinidumpOnCrash is replaced by CreateCoredumpOnCrash: CreateCoredumpOnCrash is on\n");
3105    } else if (match_option(option, "-XX:-CreateMinidumpOnCrash")) {
3106      if (FLAG_SET_CMDLINE(bool, CreateCoredumpOnCrash, false) != Flag::SUCCESS) {
3107        return JNI_EINVAL;
3108      }
3109      jio_fprintf(defaultStream::output_stream(),
3110          "CreateMinidumpOnCrash is replaced by CreateCoredumpOnCrash: CreateCoredumpOnCrash is off\n");
3111    } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3112      // Skip -XX:Flags= since that case has already been handled
3113      if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
3114        if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3115          return JNI_EINVAL;
3116        }
3117      }
3118    // Unknown option
3119    } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3120      return JNI_ERR;
3121    }
3122  }
3123
3124  // PrintSharedArchiveAndExit will turn on
3125  //   -Xshare:on
3126  //   -XX:+TraceClassPaths
3127  if (PrintSharedArchiveAndExit) {
3128    if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3129      return JNI_EINVAL;
3130    }
3131    if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3132      return JNI_EINVAL;
3133    }
3134    if (FLAG_SET_CMDLINE(bool, TraceClassPaths, true) != Flag::SUCCESS) {
3135      return JNI_EINVAL;
3136    }
3137  }
3138
3139  // Change the default value for flags  which have different default values
3140  // when working with older JDKs.
3141#ifdef LINUX
3142 if (JDK_Version::current().compare_major(6) <= 0 &&
3143      FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3144    FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3145  }
3146#endif // LINUX
3147  fix_appclasspath();
3148  return JNI_OK;
3149}
3150
3151// Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3152//
3153// This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3154// in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3155// Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3156// path is treated as the current directory.
3157//
3158// This causes problems with CDS, which requires that all directories specified in the classpath
3159// must be empty. In most cases, applications do NOT want to load classes from the current
3160// directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3161// scripts compatible with CDS.
3162void Arguments::fix_appclasspath() {
3163  if (IgnoreEmptyClassPaths) {
3164    const char separator = *os::path_separator();
3165    const char* src = _java_class_path->value();
3166
3167    // skip over all the leading empty paths
3168    while (*src == separator) {
3169      src ++;
3170    }
3171
3172    char* copy = os::strdup_check_oom(src, mtInternal);
3173
3174    // trim all trailing empty paths
3175    for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3176      *tail = '\0';
3177    }
3178
3179    char from[3] = {separator, separator, '\0'};
3180    char to  [2] = {separator, '\0'};
3181    while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3182      // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3183      // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3184    }
3185
3186    _java_class_path->set_value(copy);
3187    FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3188  }
3189
3190  if (!PrintSharedArchiveAndExit) {
3191    ClassLoader::trace_class_path("[classpath: ", _java_class_path->value());
3192  }
3193}
3194
3195static bool has_jar_files(const char* directory) {
3196  DIR* dir = os::opendir(directory);
3197  if (dir == NULL) return false;
3198
3199  struct dirent *entry;
3200  char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
3201  bool hasJarFile = false;
3202  while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3203    const char* name = entry->d_name;
3204    const char* ext = name + strlen(name) - 4;
3205    hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3206  }
3207  FREE_C_HEAP_ARRAY(char, dbuf);
3208  os::closedir(dir);
3209  return hasJarFile ;
3210}
3211
3212static int check_non_empty_dirs(const char* path) {
3213  const char separator = *os::path_separator();
3214  const char* const end = path + strlen(path);
3215  int nonEmptyDirs = 0;
3216  while (path < end) {
3217    const char* tmp_end = strchr(path, separator);
3218    if (tmp_end == NULL) {
3219      if (has_jar_files(path)) {
3220        nonEmptyDirs++;
3221        jio_fprintf(defaultStream::output_stream(),
3222          "Non-empty directory: %s\n", path);
3223      }
3224      path = end;
3225    } else {
3226      char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
3227      memcpy(dirpath, path, tmp_end - path);
3228      dirpath[tmp_end - path] = '\0';
3229      if (has_jar_files(dirpath)) {
3230        nonEmptyDirs++;
3231        jio_fprintf(defaultStream::output_stream(),
3232          "Non-empty directory: %s\n", dirpath);
3233      }
3234      FREE_C_HEAP_ARRAY(char, dirpath);
3235      path = tmp_end + 1;
3236    }
3237  }
3238  return nonEmptyDirs;
3239}
3240
3241jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
3242  // check if the default lib/endorsed directory exists; if so, error
3243  char path[JVM_MAXPATHLEN];
3244  const char* fileSep = os::file_separator();
3245  sprintf(path, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3246
3247  if (CheckEndorsedAndExtDirs) {
3248    int nonEmptyDirs = 0;
3249    // check endorsed directory
3250    nonEmptyDirs += check_non_empty_dirs(path);
3251    // check the extension directories
3252    nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3253    if (nonEmptyDirs > 0) {
3254      return JNI_ERR;
3255    }
3256  }
3257
3258  DIR* dir = os::opendir(path);
3259  if (dir != NULL) {
3260    jio_fprintf(defaultStream::output_stream(),
3261      "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3262      "in modular form will be supported via the concept of upgradeable modules.\n");
3263    os::closedir(dir);
3264    return JNI_ERR;
3265  }
3266
3267  sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3268  dir = os::opendir(path);
3269  if (dir != NULL) {
3270    jio_fprintf(defaultStream::output_stream(),
3271      "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3272      "Use -classpath instead.\n.");
3273    os::closedir(dir);
3274    return JNI_ERR;
3275  }
3276
3277  if (scp_assembly_required) {
3278    // Assemble the bootclasspath elements into the final path.
3279    Arguments::set_sysclasspath(scp_p->combined_path());
3280  }
3281
3282  // This must be done after all arguments have been processed.
3283  // java_compiler() true means set to "NONE" or empty.
3284  if (java_compiler() && !xdebug_mode()) {
3285    // For backwards compatibility, we switch to interpreted mode if
3286    // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3287    // not specified.
3288    set_mode_flags(_int);
3289  }
3290
3291  // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3292  // but like -Xint, leave compilation thresholds unaffected.
3293  // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3294  if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3295    set_mode_flags(_int);
3296  }
3297
3298  // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3299  if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3300    FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3301  }
3302
3303#ifndef COMPILER2
3304  // Don't degrade server performance for footprint
3305  if (FLAG_IS_DEFAULT(UseLargePages) &&
3306      MaxHeapSize < LargePageHeapSizeThreshold) {
3307    // No need for large granularity pages w/small heaps.
3308    // Note that large pages are enabled/disabled for both the
3309    // Java heap and the code cache.
3310    FLAG_SET_DEFAULT(UseLargePages, false);
3311  }
3312
3313#else
3314  if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3315    FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3316  }
3317#endif
3318
3319#ifndef TIERED
3320  // Tiered compilation is undefined.
3321  UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
3322#endif
3323
3324  // If we are running in a headless jre, force java.awt.headless property
3325  // to be true unless the property has already been set.
3326  // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3327  if (os::is_headless_jre()) {
3328    const char* headless = Arguments::get_property("java.awt.headless");
3329    if (headless == NULL) {
3330      const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3331      if (headless_env == NULL) {
3332        if (!add_property("java.awt.headless=true")) {
3333          return JNI_ENOMEM;
3334        }
3335      } else {
3336        char buffer[256];
3337        jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3338        if (!add_property(buffer)) {
3339          return JNI_ENOMEM;
3340        }
3341      }
3342    }
3343  }
3344
3345  if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3346    // CMS can only be used with ParNew
3347    FLAG_SET_ERGO(bool, UseParNewGC, true);
3348  }
3349
3350  if (!check_vm_args_consistency()) {
3351    return JNI_ERR;
3352  }
3353
3354  return JNI_OK;
3355}
3356
3357jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3358  return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,
3359                                            scp_assembly_required_p);
3360}
3361
3362jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3363  return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,
3364                                            scp_assembly_required_p);
3365}
3366
3367jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {
3368  char *buffer = ::getenv(name);
3369
3370  // Don't check this variable if user has special privileges
3371  // (e.g. unix su command).
3372  if (buffer == NULL || os::have_special_privileges()) {
3373    return JNI_OK;
3374  }
3375
3376  if ((buffer = os::strdup(buffer)) == NULL) {
3377    return JNI_ENOMEM;
3378  }
3379
3380  GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3381  jio_fprintf(defaultStream::error_stream(),
3382              "Picked up %s: %s\n", name, buffer);
3383  char* rd = buffer;                        // pointer to the input string (rd)
3384  while (true) {                            // repeat for all options in the input string
3385    while (isspace(*rd)) rd++;              // skip whitespace
3386    if (*rd == 0) break;                    // we re done when the input string is read completely
3387
3388    // The output, option string, overwrites the input string.
3389    // Because of quoting, the pointer to the option string (wrt) may lag the pointer to
3390    // input string (rd).
3391    char* wrt = rd;
3392
3393    JavaVMOption option;
3394    option.optionString = wrt;
3395    options->append(option);                // Fill in option
3396    while (*rd != 0 && !isspace(*rd)) {     // unquoted strings terminate with a space or NULL
3397      if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3398        int quote = *rd;                    // matching quote to look for
3399        rd++;                               // don't copy open quote
3400        while (*rd != quote) {              // include everything (even spaces) up until quote
3401          if (*rd == 0) {                   // string termination means unmatched string
3402            jio_fprintf(defaultStream::error_stream(),
3403                        "Unmatched quote in %s\n", name);
3404            delete options;
3405            os::free(buffer);
3406            return JNI_ERR;
3407          }
3408          *wrt++ = *rd++;                   // copy to option string
3409        }
3410        rd++;                               // don't copy close quote
3411      } else {
3412        *wrt++ = *rd++;                     // copy to option string
3413      }
3414    }
3415    // Need to check if we're done before writing a NULL,
3416    // because the write could be to the byte that rd is pointing to.
3417    if (*rd++ == 0) {
3418      *wrt = 0;
3419      break;
3420    }
3421    *wrt = 0;                               // Zero terminate option
3422  }
3423  JavaVMOption* options_arr =
3424      NEW_C_HEAP_ARRAY_RETURN_NULL(JavaVMOption, options->length(), mtInternal);
3425  if (options_arr == NULL) {
3426    delete options;
3427    os::free(buffer);
3428    return JNI_ENOMEM;
3429  }
3430  for (int i = 0; i < options->length(); i++) {
3431    options_arr[i] = options->at(i);
3432  }
3433
3434  // Construct JavaVMInitArgs structure and parse as if it was part of the command line
3435  JavaVMInitArgs vm_args;
3436  vm_args.version = JNI_VERSION_1_2;
3437  vm_args.options = options_arr;
3438  vm_args.nOptions = options->length();
3439  vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3440
3441  if (PrintVMOptions) {
3442    const char* tail;
3443    for (int i = 0; i < vm_args.nOptions; i++) {
3444      const JavaVMOption *option = vm_args.options + i;
3445      if (match_option(option, "-XX:", &tail)) {
3446        logOption(tail);
3447      }
3448    }
3449  }
3450
3451  jint result = parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p,
3452                                       Flag::ENVIRON_VAR);
3453  FREE_C_HEAP_ARRAY(JavaVMOption, options_arr);
3454  delete options;
3455  os::free(buffer);
3456  return result;
3457}
3458
3459void Arguments::set_shared_spaces_flags() {
3460  if (DumpSharedSpaces) {
3461    if (RequireSharedSpaces) {
3462      warning("cannot dump shared archive while using shared archive");
3463    }
3464    UseSharedSpaces = false;
3465#ifdef _LP64
3466    if (!UseCompressedOops || !UseCompressedClassPointers) {
3467      vm_exit_during_initialization(
3468        "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3469    }
3470  } else {
3471    if (!UseCompressedOops || !UseCompressedClassPointers) {
3472      no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3473    }
3474#endif
3475  }
3476}
3477
3478#if !INCLUDE_ALL_GCS
3479static void force_serial_gc() {
3480  FLAG_SET_DEFAULT(UseSerialGC, true);
3481  UNSUPPORTED_GC_OPTION(UseG1GC);
3482  UNSUPPORTED_GC_OPTION(UseParallelGC);
3483  UNSUPPORTED_GC_OPTION(UseParallelOldGC);
3484  UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
3485  UNSUPPORTED_GC_OPTION(UseParNewGC);
3486}
3487#endif // INCLUDE_ALL_GCS
3488
3489// Sharing support
3490// Construct the path to the archive
3491static char* get_shared_archive_path() {
3492  char *shared_archive_path;
3493  if (SharedArchiveFile == NULL) {
3494    char jvm_path[JVM_MAXPATHLEN];
3495    os::jvm_path(jvm_path, sizeof(jvm_path));
3496    char *end = strrchr(jvm_path, *os::file_separator());
3497    if (end != NULL) *end = '\0';
3498    size_t jvm_path_len = strlen(jvm_path);
3499    size_t file_sep_len = strlen(os::file_separator());
3500    const size_t len = jvm_path_len + file_sep_len + 20;
3501    shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtInternal);
3502    if (shared_archive_path != NULL) {
3503      jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3504        jvm_path, os::file_separator());
3505    }
3506  } else {
3507    shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtInternal);
3508  }
3509  return shared_archive_path;
3510}
3511
3512#ifndef PRODUCT
3513// Determine whether LogVMOutput should be implicitly turned on.
3514static bool use_vm_log() {
3515  if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3516      PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3517      PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3518      PrintAssembly || TraceDeoptimization || TraceDependencies ||
3519      (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3520    return true;
3521  }
3522
3523#ifdef COMPILER1
3524  if (PrintC1Statistics) {
3525    return true;
3526  }
3527#endif // COMPILER1
3528
3529#ifdef COMPILER2
3530  if (PrintOptoAssembly || PrintOptoStatistics) {
3531    return true;
3532  }
3533#endif // COMPILER2
3534
3535  return false;
3536}
3537#endif // PRODUCT
3538
3539// Parse entry point called from JNI_CreateJavaVM
3540
3541jint Arguments::parse(const JavaVMInitArgs* args) {
3542
3543  // Initialize ranges and constraints
3544  CommandLineFlagRangeList::init();
3545  CommandLineFlagConstraintList::init();
3546
3547  // Remaining part of option string
3548  const char* tail;
3549
3550  // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3551  const char* hotspotrc = ".hotspotrc";
3552  bool settings_file_specified = false;
3553  bool needs_hotspotrc_warning = false;
3554
3555  const char* flags_file;
3556  int index;
3557  for (index = 0; index < args->nOptions; index++) {
3558    const JavaVMOption *option = args->options + index;
3559    if (ArgumentsExt::process_options(option)) {
3560      continue;
3561    }
3562    if (match_option(option, "-XX:Flags=", &tail)) {
3563      flags_file = tail;
3564      settings_file_specified = true;
3565      continue;
3566    }
3567    if (match_option(option, "-XX:+PrintVMOptions")) {
3568      PrintVMOptions = true;
3569      continue;
3570    }
3571    if (match_option(option, "-XX:-PrintVMOptions")) {
3572      PrintVMOptions = false;
3573      continue;
3574    }
3575    if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3576      IgnoreUnrecognizedVMOptions = true;
3577      continue;
3578    }
3579    if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3580      IgnoreUnrecognizedVMOptions = false;
3581      continue;
3582    }
3583    if (match_option(option, "-XX:+PrintFlagsInitial")) {
3584      CommandLineFlags::printFlags(tty, false);
3585      vm_exit(0);
3586    }
3587    if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3588#if INCLUDE_NMT
3589      // The launcher did not setup nmt environment variable properly.
3590      if (!MemTracker::check_launcher_nmt_support(tail)) {
3591        warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3592      }
3593
3594      // Verify if nmt option is valid.
3595      if (MemTracker::verify_nmt_option()) {
3596        // Late initialization, still in single-threaded mode.
3597        if (MemTracker::tracking_level() >= NMT_summary) {
3598          MemTracker::init();
3599        }
3600      } else {
3601        vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3602      }
3603      continue;
3604#else
3605      jio_fprintf(defaultStream::error_stream(),
3606        "Native Memory Tracking is not supported in this VM\n");
3607      return JNI_ERR;
3608#endif
3609    }
3610
3611#ifndef PRODUCT
3612    if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3613      CommandLineFlags::printFlags(tty, true);
3614      vm_exit(0);
3615    }
3616#endif
3617  }
3618
3619  if (IgnoreUnrecognizedVMOptions) {
3620    // uncast const to modify the flag args->ignoreUnrecognized
3621    *(jboolean*)(&args->ignoreUnrecognized) = true;
3622  }
3623
3624  // Parse specified settings file
3625  if (settings_file_specified) {
3626    if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
3627      return JNI_EINVAL;
3628    }
3629  } else {
3630#ifdef ASSERT
3631    // Parse default .hotspotrc settings file
3632    if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
3633      return JNI_EINVAL;
3634    }
3635#else
3636    struct stat buf;
3637    if (os::stat(hotspotrc, &buf) == 0) {
3638      needs_hotspotrc_warning = true;
3639    }
3640#endif
3641  }
3642
3643  if (PrintVMOptions) {
3644    for (index = 0; index < args->nOptions; index++) {
3645      const JavaVMOption *option = args->options + index;
3646      if (match_option(option, "-XX:", &tail)) {
3647        logOption(tail);
3648      }
3649    }
3650  }
3651
3652  // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
3653  jint result = parse_vm_init_args(args);
3654  if (result != JNI_OK) {
3655    return result;
3656  }
3657
3658  // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
3659  SharedArchivePath = get_shared_archive_path();
3660  if (SharedArchivePath == NULL) {
3661    return JNI_ENOMEM;
3662  }
3663
3664  // Set up VerifySharedSpaces
3665  if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
3666    VerifySharedSpaces = true;
3667  }
3668
3669  // Delay warning until here so that we've had a chance to process
3670  // the -XX:-PrintWarnings flag
3671  if (needs_hotspotrc_warning) {
3672    warning("%s file is present but has been ignored.  "
3673            "Run with -XX:Flags=%s to load the file.",
3674            hotspotrc, hotspotrc);
3675  }
3676
3677#if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
3678  UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
3679#endif
3680
3681  ArgumentsExt::report_unsupported_options();
3682
3683#ifndef PRODUCT
3684  if (TraceBytecodesAt != 0) {
3685    TraceBytecodes = true;
3686  }
3687  if (CountCompiledCalls) {
3688    if (UseCounterDecay) {
3689      warning("UseCounterDecay disabled because CountCalls is set");
3690      UseCounterDecay = false;
3691    }
3692  }
3693#endif // PRODUCT
3694
3695  if (ScavengeRootsInCode == 0) {
3696    if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3697      warning("forcing ScavengeRootsInCode non-zero");
3698    }
3699    ScavengeRootsInCode = 1;
3700  }
3701
3702  if (PrintGCDetails) {
3703    // Turn on -verbose:gc options as well
3704    PrintGC = true;
3705  }
3706
3707  // Set object alignment values.
3708  set_object_alignment();
3709
3710#if !INCLUDE_ALL_GCS
3711  force_serial_gc();
3712#endif // INCLUDE_ALL_GCS
3713#if !INCLUDE_CDS
3714  if (DumpSharedSpaces || RequireSharedSpaces) {
3715    jio_fprintf(defaultStream::error_stream(),
3716      "Shared spaces are not supported in this VM\n");
3717    return JNI_ERR;
3718  }
3719  if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
3720    warning("Shared spaces are not supported in this VM");
3721    FLAG_SET_DEFAULT(UseSharedSpaces, false);
3722    FLAG_SET_DEFAULT(PrintSharedSpaces, false);
3723  }
3724  no_shared_spaces("CDS Disabled");
3725#endif // INCLUDE_CDS
3726
3727  return JNI_OK;
3728}
3729
3730jint Arguments::apply_ergo() {
3731
3732  // Set flags based on ergonomics.
3733  set_ergonomics_flags();
3734
3735  set_shared_spaces_flags();
3736
3737  // Check the GC selections again.
3738  if (!check_gc_consistency()) {
3739    return JNI_EINVAL;
3740  }
3741
3742  if (TieredCompilation) {
3743    set_tiered_flags();
3744  } else {
3745    // Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup.
3746    if (CompilationPolicyChoice >= 2) {
3747      vm_exit_during_initialization(
3748        "Incompatible compilation policy selected", NULL);
3749    }
3750    // Scale CompileThreshold
3751    // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
3752    if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
3753      FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
3754    }
3755  }
3756
3757#ifdef COMPILER2
3758#ifndef PRODUCT
3759  if (PrintIdealGraphLevel > 0) {
3760    FLAG_SET_ERGO(bool, PrintIdealGraph, true);
3761  }
3762#endif
3763#endif
3764
3765  // Set heap size based on available physical memory
3766  set_heap_size();
3767
3768  ArgumentsExt::set_gc_specific_flags();
3769
3770  // Initialize Metaspace flags and alignments
3771  Metaspace::ergo_initialize();
3772
3773  // Set bytecode rewriting flags
3774  set_bytecode_flags();
3775
3776  // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
3777  set_aggressive_opts_flags();
3778
3779  // Turn off biased locking for locking debug mode flags,
3780  // which are subtly different from each other but neither works with
3781  // biased locking
3782  if (UseHeavyMonitors
3783#ifdef COMPILER1
3784      || !UseFastLocking
3785#endif // COMPILER1
3786    ) {
3787    if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
3788      // flag set to true on command line; warn the user that they
3789      // can't enable biased locking here
3790      warning("Biased Locking is not supported with locking debug flags"
3791              "; ignoring UseBiasedLocking flag." );
3792    }
3793    UseBiasedLocking = false;
3794  }
3795
3796#ifdef ZERO
3797  // Clear flags not supported on zero.
3798  FLAG_SET_DEFAULT(ProfileInterpreter, false);
3799  FLAG_SET_DEFAULT(UseBiasedLocking, false);
3800  LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
3801  LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
3802#endif // CC_INTERP
3803
3804#ifdef COMPILER2
3805  if (!EliminateLocks) {
3806    EliminateNestedLocks = false;
3807  }
3808  if (!Inline) {
3809    IncrementalInline = false;
3810  }
3811#ifndef PRODUCT
3812  if (!IncrementalInline) {
3813    AlwaysIncrementalInline = false;
3814  }
3815#endif
3816  if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
3817    // nothing to use the profiling, turn if off
3818    FLAG_SET_DEFAULT(TypeProfileLevel, 0);
3819  }
3820#endif
3821
3822  if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
3823    warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
3824    DebugNonSafepoints = true;
3825  }
3826
3827  if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
3828    warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
3829  }
3830
3831#ifndef PRODUCT
3832  if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
3833    if (use_vm_log()) {
3834      LogVMOutput = true;
3835    }
3836  }
3837#endif // PRODUCT
3838
3839  if (PrintCommandLineFlags) {
3840    CommandLineFlags::printSetFlags(tty);
3841  }
3842
3843  // Apply CPU specific policy for the BiasedLocking
3844  if (UseBiasedLocking) {
3845    if (!VM_Version::use_biased_locking() &&
3846        !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
3847      UseBiasedLocking = false;
3848    }
3849  }
3850#ifdef COMPILER2
3851  if (!UseBiasedLocking || EmitSync != 0) {
3852    UseOptoBiasInlining = false;
3853  }
3854#endif
3855
3856  return JNI_OK;
3857}
3858
3859jint Arguments::adjust_after_os() {
3860  if (UseNUMA) {
3861    if (UseParallelGC || UseParallelOldGC) {
3862      if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
3863         FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
3864      }
3865    }
3866    // UseNUMAInterleaving is set to ON for all collectors and
3867    // platforms when UseNUMA is set to ON. NUMA-aware collectors
3868    // such as the parallel collector for Linux and Solaris will
3869    // interleave old gen and survivor spaces on top of NUMA
3870    // allocation policy for the eden space.
3871    // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
3872    // all platforms and ParallelGC on Windows will interleave all
3873    // of the heap spaces across NUMA nodes.
3874    if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
3875      FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
3876    }
3877  }
3878  return JNI_OK;
3879}
3880
3881// Any custom code post the final range and constraint check
3882// can be done here. We pass a flag that specifies whether
3883// the check passed successfully
3884void Arguments::post_final_range_and_constraint_check(bool check_passed) {
3885  // This does not set the flag itself, but stores the value in a safe place for later usage.
3886  _min_heap_free_ratio = MinHeapFreeRatio;
3887  _max_heap_free_ratio = MaxHeapFreeRatio;
3888}
3889
3890int Arguments::PropertyList_count(SystemProperty* pl) {
3891  int count = 0;
3892  while(pl != NULL) {
3893    count++;
3894    pl = pl->next();
3895  }
3896  return count;
3897}
3898
3899const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
3900  assert(key != NULL, "just checking");
3901  SystemProperty* prop;
3902  for (prop = pl; prop != NULL; prop = prop->next()) {
3903    if (strcmp(key, prop->key()) == 0) return prop->value();
3904  }
3905  return NULL;
3906}
3907
3908const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
3909  int count = 0;
3910  const char* ret_val = NULL;
3911
3912  while(pl != NULL) {
3913    if(count >= index) {
3914      ret_val = pl->key();
3915      break;
3916    }
3917    count++;
3918    pl = pl->next();
3919  }
3920
3921  return ret_val;
3922}
3923
3924char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
3925  int count = 0;
3926  char* ret_val = NULL;
3927
3928  while(pl != NULL) {
3929    if(count >= index) {
3930      ret_val = pl->value();
3931      break;
3932    }
3933    count++;
3934    pl = pl->next();
3935  }
3936
3937  return ret_val;
3938}
3939
3940void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
3941  SystemProperty* p = *plist;
3942  if (p == NULL) {
3943    *plist = new_p;
3944  } else {
3945    while (p->next() != NULL) {
3946      p = p->next();
3947    }
3948    p->set_next(new_p);
3949  }
3950}
3951
3952void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {
3953  if (plist == NULL)
3954    return;
3955
3956  SystemProperty* new_p = new SystemProperty(k, v, true);
3957  PropertyList_add(plist, new_p);
3958}
3959
3960void Arguments::PropertyList_add(SystemProperty *element) {
3961  PropertyList_add(&_system_properties, element);
3962}
3963
3964// This add maintains unique property key in the list.
3965void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {
3966  if (plist == NULL)
3967    return;
3968
3969  // If property key exist then update with new value.
3970  SystemProperty* prop;
3971  for (prop = *plist; prop != NULL; prop = prop->next()) {
3972    if (strcmp(k, prop->key()) == 0) {
3973      if (append) {
3974        prop->append_value(v);
3975      } else {
3976        prop->set_value(v);
3977      }
3978      return;
3979    }
3980  }
3981
3982  PropertyList_add(plist, k, v);
3983}
3984
3985// Copies src into buf, replacing "%%" with "%" and "%p" with pid
3986// Returns true if all of the source pointed by src has been copied over to
3987// the destination buffer pointed by buf. Otherwise, returns false.
3988// Notes:
3989// 1. If the length (buflen) of the destination buffer excluding the
3990// NULL terminator character is not long enough for holding the expanded
3991// pid characters, it also returns false instead of returning the partially
3992// expanded one.
3993// 2. The passed in "buflen" should be large enough to hold the null terminator.
3994bool Arguments::copy_expand_pid(const char* src, size_t srclen,
3995                                char* buf, size_t buflen) {
3996  const char* p = src;
3997  char* b = buf;
3998  const char* src_end = &src[srclen];
3999  char* buf_end = &buf[buflen - 1];
4000
4001  while (p < src_end && b < buf_end) {
4002    if (*p == '%') {
4003      switch (*(++p)) {
4004      case '%':         // "%%" ==> "%"
4005        *b++ = *p++;
4006        break;
4007      case 'p':  {       //  "%p" ==> current process id
4008        // buf_end points to the character before the last character so
4009        // that we could write '\0' to the end of the buffer.
4010        size_t buf_sz = buf_end - b + 1;
4011        int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4012
4013        // if jio_snprintf fails or the buffer is not long enough to hold
4014        // the expanded pid, returns false.
4015        if (ret < 0 || ret >= (int)buf_sz) {
4016          return false;
4017        } else {
4018          b += ret;
4019          assert(*b == '\0', "fail in copy_expand_pid");
4020          if (p == src_end && b == buf_end + 1) {
4021            // reach the end of the buffer.
4022            return true;
4023          }
4024        }
4025        p++;
4026        break;
4027      }
4028      default :
4029        *b++ = '%';
4030      }
4031    } else {
4032      *b++ = *p++;
4033    }
4034  }
4035  *b = '\0';
4036  return (p == src_end); // return false if not all of the source was copied
4037}
4038