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