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