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