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