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