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