arguments.cpp revision 7890:f83851ae258e
124269Speter/*
224269Speter * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
324269Speter * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
424269Speter *
528345Sdyson * This code is free software; you can redistribute it and/or modify it
628345Sdyson * under the terms of the GNU General Public License version 2 only, as
728345Sdyson * published by the Free Software Foundation.
824269Speter *
924269Speter * This code is distributed in the hope that it will be useful, but WITHOUT
1024269Speter * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1124269Speter * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
1224269Speter * version 2 for more details (a copy is included in the LICENSE file that
1324269Speter * accompanied this code).
1424269Speter *
1524269Speter * You should have received a copy of the GNU General Public License version
1624269Speter * 2 along with this work; if not, write to the Free Software Foundation,
1724269Speter * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1824269Speter *
1924269Speter * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2024269Speter * or visit www.oracle.com if you need additional information or have any
2124269Speter * questions.
2224269Speter *
2324269Speter */
2424269Speter
2524269Speter#include "precompiled.hpp"
2624269Speter#include "classfile/classLoader.hpp"
2724269Speter#include "classfile/javaAssertions.hpp"
2824269Speter#include "classfile/stringTable.hpp"
2924269Speter#include "classfile/symbolTable.hpp"
3024269Speter#include "compiler/compilerOracle.hpp"
3124269Speter#include "memory/allocation.inline.hpp"
3224269Speter#include "memory/cardTableRS.hpp"
3324269Speter#include "memory/genCollectedHeap.hpp"
3424269Speter#include "memory/referenceProcessor.hpp"
3524269Speter#include "memory/universe.inline.hpp"
3624269Speter#include "oops/oop.inline.hpp"
3724269Speter#include "prims/jvmtiExport.hpp"
3824269Speter#include "runtime/arguments.hpp"
3924269Speter#include "runtime/arguments_ext.hpp"
4024269Speter#include "runtime/globals_extension.hpp"
4150477Speter#include "runtime/java.hpp"
4224269Speter#include "runtime/os.hpp"
4324269Speter#include "runtime/vm_version.hpp"
4424269Speter#include "services/management.hpp"
4567046Sjasone#include "services/memTracker.hpp"
4684812Sjhb#include "utilities/defaultStream.hpp"
4724269Speter#include "utilities/macros.hpp"
48102477Sbde#include "utilities/stringUtils.hpp"
4967353Sjhb#include "utilities/taskqueue.hpp"
50102477Sbde#if INCLUDE_ALL_GCS
5124273Speter#include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
5224269Speter#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
5324269Speter#include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
5424269Speter#endif // INCLUDE_ALL_GCS
5524269Speter
5624269Speter// Note: This is a special bug reporting site for the JVM
5724269Speter#define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
5828345Sdyson#define DEFAULT_JAVA_LAUNCHER  "generic"
5928345Sdyson
6024269Speter#define UNSUPPORTED_GC_OPTION(gc)                                     \
6128345Sdysondo {                                                                  \
6228345Sdyson  if (gc) {                                                           \
6328345Sdyson    if (FLAG_IS_CMDLINE(gc)) {                                        \
6435242Sbde      warning(#gc " is not supported in this VM.  Using Serial GC."); \
6528345Sdyson    }                                                                 \
6624269Speter    FLAG_SET_DEFAULT(gc, false);                                      \
6729653Sdyson  }                                                                   \
6829653Sdyson} while(0)
6929653Sdyson
7067046Sjasonechar**  Arguments::_jvm_flags_array             = NULL;
7167046Sjasoneint     Arguments::_num_jvm_flags               = 0;
7267046Sjasonechar**  Arguments::_jvm_args_array              = NULL;
7367046Sjasoneint     Arguments::_num_jvm_args                = 0;
7467046Sjasonechar*  Arguments::_java_command                 = NULL;
7586333SdillonSystemProperty* Arguments::_system_properties   = NULL;
7671320Sjasoneconst char*  Arguments::_gc_log_filename        = NULL;
7767046Sjasonebool   Arguments::_has_profile                  = false;
7828345Sdysonsize_t Arguments::_conservative_max_heap_alignment = 0;
7929653Sdysonuintx  Arguments::_min_heap_size                = 0;
8029653Sdysonuintx  Arguments::_min_heap_free_ratio          = 0;
8124269Speteruintx  Arguments::_max_heap_free_ratio          = 0;
8267046SjasoneArguments::Mode Arguments::_mode                = _mixed;
8367046Sjasonebool   Arguments::_java_compiler                = false;
8467046Sjasonebool   Arguments::_xdebug_mode                  = false;
8567046Sjasoneconst char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
8667046Sjasoneconst char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
8767046Sjasoneint    Arguments::_sun_java_launcher_pid        = -1;
8867046Sjasonebool   Arguments::_sun_java_launcher_is_altjvm  = false;
8967046Sjasone
9067046Sjasone// These parameters are reset in method parse_vm_init_args(JavaVMInitArgs*)
9186333Sdillonbool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
9293818Sjhbbool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
9386333Sdillonbool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
9467046Sjasonebool   Arguments::_ClipInlining                 = ClipInlining;
9567046Sjasone
9667046Sjasonechar*  Arguments::SharedArchivePath             = NULL;
9767046Sjasone
9828345SdysonAgentLibraryList Arguments::_libraryList;
9928345SdysonAgentLibraryList Arguments::_agentList;
10028345Sdyson
10128345Sdysonabort_hook_t     Arguments::_abort_hook         = NULL;
10228345Sdysonexit_hook_t      Arguments::_exit_hook          = NULL;
10324269Spetervfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
10428345Sdyson
10528345Sdyson
10642453SeivindSystemProperty *Arguments::_sun_boot_library_path = NULL;
10742408SeivindSystemProperty *Arguments::_java_library_path = NULL;
10824269SpeterSystemProperty *Arguments::_java_home = NULL;
10934194SdysonSystemProperty *Arguments::_java_class_path = NULL;
11028345SdysonSystemProperty *Arguments::_sun_boot_class_path = NULL;
11134194Sdyson
11234194Sdysonchar* Arguments::_ext_dirs = NULL;
11334194Sdyson
11434194Sdyson// Check if head of 'option' matches 'name', and sets 'tail' to the remaining
11534194Sdyson// part of the option string.
11634194Sdysonstatic bool match_option(const JavaVMOption *option, const char* name,
11734194Sdyson                         const char** tail) {
11828345Sdyson  int len = (int)strlen(name);
11928345Sdyson  if (strncmp(option->optionString, name, len) == 0) {
12029653Sdyson    *tail = option->optionString + len;
12171576Sjasone    return true;
12229653Sdyson  } else {
12328345Sdyson    return false;
12453090Salc  }
12553090Salc}
12653090Salc
12753090Salc// Check if 'option' matches 'name'. No "tail" is allowed.
12853090Salcstatic bool match_option(const JavaVMOption *option, const char* name) {
12953090Salc  const char* tail = NULL;
13053090Salc  bool result = match_option(option, name, &tail);
13153090Salc  if (tail != NULL && *tail == '\0') {
13253090Salc    return result;
13353090Salc  } else {
13472200Sbmilekic    return false;
13553090Salc  }
13653090Salc}
13753090Salc
13872200Sbmilekic// Return true if any of the strings in null-terminated array 'names' matches.
13928345Sdyson// If tail_allowed is true, then the tail must begin with a colon; otherwise,
14028345Sdyson// the option must match exactly.
14124269Speterstatic bool match_option(const JavaVMOption* option, const char** names, const char** tail,
14253090Salc  bool tail_allowed) {
14328345Sdyson  for (/* empty */; *names != NULL; ++names) {
14428345Sdyson    if (match_option(option, *names, tail)) {
14524269Speter      if (**tail == '\0' || tail_allowed && **tail == ':') {
14628345Sdyson        return true;
14728345Sdyson      }
14834194Sdyson    }
14928345Sdyson  }
15066615Sjasone  return false;
15166615Sjasone}
15266615Sjasone
15366615Sjasonestatic void logOption(const char* opt) {
15428345Sdyson  if (PrintVMOptions) {
15528345Sdyson    jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
15628345Sdyson  }
15728345Sdyson}
15829653Sdyson
15929653Sdyson// Process java launcher properties.
16029653Sdysonvoid Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
16129653Sdyson  // See if sun.java.launcher, sun.java.launcher.is_altjvm or
16229653Sdyson  // sun.java.launcher.pid is defined.
16328345Sdyson  // Must do this before setting up other system properties,
16434194Sdyson  // as some of them may depend on launcher type.
16528345Sdyson  for (int index = 0; index < args->nOptions; index++) {
16628345Sdyson    const JavaVMOption* option = args->options + index;
16728345Sdyson    const char* tail;
16869432Sjake
16988318Sdillon    if (match_option(option, "-Dsun.java.launcher=", &tail)) {
17088318Sdillon      process_java_launcher_argument(tail, option->extraInfo);
17134194Sdyson      continue;
17228345Sdyson    }
17334194Sdyson    if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
17434194Sdyson      if (strcmp(tail, "true") == 0) {
17534194Sdyson        _sun_java_launcher_is_altjvm = true;
17634194Sdyson      }
17734194Sdyson      continue;
17834194Sdyson    }
17928345Sdyson    if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
18034194Sdyson      _sun_java_launcher_pid = atoi(tail);
18128345Sdyson      continue;
18234194Sdyson    }
18328345Sdyson  }
18428345Sdyson}
18528345Sdyson
18634194Sdyson// Initialize system properties key and value.
18728345Sdysonvoid Arguments::init_system_properties() {
18828345Sdyson
18928345Sdyson  PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
19024269Speter                                                                 "Java Virtual Machine Specification",  false));
19124269Speter  PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
19224269Speter  PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
19324269Speter  PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
19424269Speter
19524269Speter  // Following are JVMTI agent writable properties.
19624269Speter  // Properties values are set to NULL and they are
19724269Speter  // os specific they are initialized in os::init_system_properties_values().
19842900Seivind  _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
19983366Sjulian  _java_library_path = new SystemProperty("java.library.path", NULL,  true);
20042900Seivind  _java_home =  new SystemProperty("java.home", NULL,  true);
20183366Sjulian  _sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL,  true);
20242900Seivind
20327894Sfsmp  _java_class_path = new SystemProperty("java.class.path", "",  true);
20424269Speter
20566615Sjasone  // Add to System Property list.
20683366Sjulian  PropertyList_add(&_system_properties, _sun_boot_library_path);
20742900Seivind  PropertyList_add(&_system_properties, _java_library_path);
20842900Seivind  PropertyList_add(&_system_properties, _java_home);
20942900Seivind  PropertyList_add(&_system_properties, _java_class_path);
21042900Seivind  PropertyList_add(&_system_properties, _sun_boot_class_path);
21142900Seivind
21224269Speter  // Set OS specific system properties values
21324269Speter  os::init_system_properties_values();
21424269Speter}
21572227Sjhb
21624269Speter
21766615Sjasone  // Update/Initialize System properties after JDK version number is known
21866615Sjasonevoid Arguments::init_version_specific_system_properties() {
21983366Sjulian  enum { bufsz = 16 };
22066615Sjasone  char buffer[bufsz];
22124269Speter  const char* spec_vendor = "Sun Microsystems Inc.";
22283366Sjulian  uint32_t spec_version = 0;
22328393Sdyson
22428393Sdyson  spec_vendor = "Oracle Corporation";
22583366Sjulian  spec_version = JDK_Version::current().major_version();
22628345Sdyson  jio_snprintf(buffer, bufsz, "1." UINT32_FORMAT, spec_version);
22772200Sbmilekic
22875740Salfred  PropertyList_add(&_system_properties,
22976100Salfred      new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
23072200Sbmilekic  PropertyList_add(&_system_properties,
23175740Salfred      new SystemProperty("java.vm.specification.version", buffer, false));
23228345Sdyson  PropertyList_add(&_system_properties,
23381506Sjhb      new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
23481506Sjhb}
23581506Sjhb
23681506Sjhb/**
23781506Sjhb * Provide a slightly more user-friendly way of eliminating -XX flags.
23824269Speter * When a flag is eliminated, it can be added to this list in order to
23924269Speter * continue accepting this flag on the command-line, while issuing a warning
24024269Speter * and ignoring the value.  Once the JDK version reaches the 'accept_until'
24124269Speter * limit, we flatly refuse to admit the existence of the flag.  This allows
24224269Speter * a flag to die correctly over JDK releases using HSX.
24344681Sjulian */
24444681Sjuliantypedef struct {
24544681Sjulian  const char* name;
24644681Sjulian  JDK_Version obsoleted_in; // when the flag went away
24744681Sjulian  JDK_Version accept_until; // which version to start denying the existence
24883366Sjulian} ObsoleteFlag;
24944681Sjulian
25044681Sjulianstatic ObsoleteFlag obsolete_jvm_flags[] = {
25144681Sjulian  { "UseTrainGC",                    JDK_Version::jdk(5), JDK_Version::jdk(7) },
25224269Speter  { "UseSpecialLargeObjectHandling", JDK_Version::jdk(5), JDK_Version::jdk(7) },
25372227Sjhb  { "UseOversizedCarHandling",       JDK_Version::jdk(5), JDK_Version::jdk(7) },
25483420Sjhb  { "TraceCarAllocation",            JDK_Version::jdk(5), JDK_Version::jdk(7) },
25583420Sjhb  { "PrintTrainGCProcessingStats",   JDK_Version::jdk(5), JDK_Version::jdk(7) },
25683420Sjhb  { "LogOfCarSpaceSize",             JDK_Version::jdk(5), JDK_Version::jdk(7) },
25783420Sjhb  { "OversizedCarThreshold",         JDK_Version::jdk(5), JDK_Version::jdk(7) },
25872227Sjhb  { "MinTickInterval",               JDK_Version::jdk(5), JDK_Version::jdk(7) },
25924269Speter  { "DefaultTickInterval",           JDK_Version::jdk(5), JDK_Version::jdk(7) },
26024269Speter  { "MaxTickInterval",               JDK_Version::jdk(5), JDK_Version::jdk(7) },
26128345Sdyson  { "DelayTickAdjustment",           JDK_Version::jdk(5), JDK_Version::jdk(7) },
26297540Sjeff  { "ProcessingToTenuringRatio",     JDK_Version::jdk(5), JDK_Version::jdk(7) },
26397540Sjeff  { "MinTrainLength",                JDK_Version::jdk(5), JDK_Version::jdk(7) },
26497540Sjeff  { "AppendRatio",         JDK_Version::jdk_update(6,10), JDK_Version::jdk(7) },
26597540Sjeff  { "DefaultMaxRAM",       JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },
26697540Sjeff  { "DefaultInitialRAMFraction",
26797540Sjeff                           JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },
26824269Speter  { "UseDepthFirstScavengeOrder",
26924269Speter                           JDK_Version::jdk_update(6,22), JDK_Version::jdk(7) },
27024269Speter  { "HandlePromotionFailure",
27124269Speter                           JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },
27224269Speter  { "MaxLiveObjectEvacuationRatio",
27324269Speter                           JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },
27428345Sdyson  { "ForceSharedSpaces",   JDK_Version::jdk_update(6,25), JDK_Version::jdk(8) },
275102412Scharnier  { "UseParallelOldGCCompacting",
27624269Speter                           JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
27724269Speter  { "UseParallelDensePrefixUpdate",
27875472Salfred                           JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
27975472Salfred  { "UseParallelOldGCDensePrefix",
28075472Salfred                           JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
28175472Salfred  { "AllowTransitionalJSR292",       JDK_Version::jdk(7), JDK_Version::jdk(8) },
28228345Sdyson  { "UseCompressedStrings",          JDK_Version::jdk(7), JDK_Version::jdk(8) },
28324269Speter  { "CMSPermGenPrecleaningEnabled", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
28424269Speter  { "CMSTriggerPermRatio", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
28524269Speter  { "CMSInitiatingPermOccupancyFraction", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
28624269Speter  { "AdaptivePermSizeWeight", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
28724269Speter  { "PermGenPadding", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
28824269Speter  { "PermMarkSweepDeadRatio", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
28924269Speter  { "PermSize", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
29024269Speter  { "MaxPermSize", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
29124269Speter  { "MinPermHeapExpansion", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
29224269Speter  { "MaxPermHeapExpansion", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
29324269Speter  { "CMSRevisitStackSize",           JDK_Version::jdk(8), JDK_Version::jdk(9) },
29424269Speter  { "PrintRevisitStats",             JDK_Version::jdk(8), JDK_Version::jdk(9) },
29524269Speter  { "UseVectoredExceptions",         JDK_Version::jdk(8), JDK_Version::jdk(9) },
29624269Speter  { "UseSplitVerifier",              JDK_Version::jdk(8), JDK_Version::jdk(9) },
29728345Sdyson  { "UseISM",                        JDK_Version::jdk(8), JDK_Version::jdk(9) },
29824269Speter  { "UsePermISM",                    JDK_Version::jdk(8), JDK_Version::jdk(9) },
29924269Speter  { "UseMPSS",                       JDK_Version::jdk(8), JDK_Version::jdk(9) },
30024269Speter  { "UseStringCache",                JDK_Version::jdk(8), JDK_Version::jdk(9) },
301102412Scharnier  { "UseOldInlining",                JDK_Version::jdk(9), JDK_Version::jdk(10) },
30224269Speter  { "SafepointPollOffset",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
30324269Speter#ifdef PRODUCT
30424269Speter  { "DesiredMethodLimit",
30524269Speter                           JDK_Version::jdk_update(7, 2), JDK_Version::jdk(8) },
30624269Speter#endif // PRODUCT
30724269Speter  { "UseVMInterruptibleIO",          JDK_Version::jdk(8), JDK_Version::jdk(9) },
30824269Speter  { "UseBoundThreads",               JDK_Version::jdk(9), JDK_Version::jdk(10) },
30924269Speter  { "DefaultThreadPriority",         JDK_Version::jdk(9), JDK_Version::jdk(10) },
31024269Speter  { "NoYieldsInMicrolock",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
31124269Speter  { "BackEdgeThreshold",             JDK_Version::jdk(9), JDK_Version::jdk(10) },
31228345Sdyson  { "UseNewReflection",              JDK_Version::jdk(9), JDK_Version::jdk(10) },
31324269Speter  { "ReflectionWrapResolutionErrors",JDK_Version::jdk(9), JDK_Version::jdk(10) },
31428345Sdyson  { "VerifyReflectionBytecodes",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
31524269Speter  { "AutoShutdownNMT",               JDK_Version::jdk(9), JDK_Version::jdk(10) },
31624269Speter  { "NmethodSweepFraction",          JDK_Version::jdk(9), JDK_Version::jdk(10) },
31724269Speter  { "NmethodSweepCheckInterval",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
31824269Speter  { "CodeCacheMinimumFreeSpace",     JDK_Version::jdk(9), JDK_Version::jdk(10) },
31924269Speter#ifndef ZERO
32024269Speter  { "UseFastAccessorMethods",        JDK_Version::jdk(9), JDK_Version::jdk(10) },
32124269Speter  { "UseFastEmptyMethods",           JDK_Version::jdk(9), JDK_Version::jdk(10) },
32224269Speter#endif // ZERO
32324269Speter  { "UseCompilerSafepoints",         JDK_Version::jdk(9), JDK_Version::jdk(10) },
32424269Speter  { NULL, JDK_Version(0), JDK_Version(0) }
32524269Speter};
32624269Speter
32724269Speter// Returns true if the flag is obsolete and fits into the range specified
32824269Speter// for being ignored.  In the case that the flag is ignored, the 'version'
32924269Speter// value is filled in with the version number when the flag became
33024269Speter// obsolete so that that value can be displayed to the user.
33134194Sdysonbool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {
33224269Speter  int i = 0;
33334194Sdyson  assert(version != NULL, "Must provide a version buffer");
33424269Speter  while (obsolete_jvm_flags[i].name != NULL) {
33524269Speter    const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];
33624269Speter    // <flag>=xxx form
33724269Speter    // [-|+]<flag> form
33824269Speter    size_t len = strlen(flag_status.name);
33924269Speter    if (((strncmp(flag_status.name, s, len) == 0) &&
34024269Speter         (strlen(s) == len)) ||
34142900Seivind        ((s[0] == '+' || s[0] == '-') &&
34242900Seivind         (strncmp(flag_status.name, &s[1], len) == 0) &&
34342900Seivind         (strlen(&s[1]) == len))) {
34442900Seivind      if (JDK_Version::current().compare(flag_status.accept_until) == -1) {
34542900Seivind          *version = flag_status.obsoleted_in;
34624269Speter          return true;
34724269Speter      }
34824269Speter    }
34924269Speter    i++;
35024269Speter  }
35124269Speter  return false;
35224269Speter}
35328345Sdyson
35428345Sdyson// Constructs the system class path (aka boot class path) from the following
35524269Speter// components, in order:
356102412Scharnier//
35724269Speter//     prefix           // from -Xbootclasspath/p:...
35824269Speter//     base             // from os::get_system_properties() or -Xbootclasspath=
35924269Speter//     suffix           // from -Xbootclasspath/a:...
36024269Speter//
36124269Speter// This could be AllStatic, but it isn't needed after argument processing is
36224269Speter// complete.
36348301Smckusickclass SysClassPath: public StackObj {
36424269Speterpublic:
36548301Smckusick  SysClassPath(const char* base);
36648301Smckusick  ~SysClassPath();
36748301Smckusick
36848301Smckusick  inline void set_base(const char* base);
36924269Speter  inline void add_prefix(const char* prefix);
37024269Speter  inline void add_suffix_to_prefix(const char* suffix);
37124269Speter  inline void add_suffix(const char* suffix);
37224269Speter  inline void reset_path(const char* base);
37328345Sdyson
37428345Sdyson  inline const char* get_base()     const { return _items[_scp_base]; }
37524269Speter  inline const char* get_prefix()   const { return _items[_scp_prefix]; }
37624269Speter  inline const char* get_suffix()   const { return _items[_scp_suffix]; }
37724269Speter
37824269Speter  // Combine all the components into a single c-heap-allocated string; caller
37924269Speter  // must free the string if/when no longer needed.
38024269Speter  char* combined_path();
38128345Sdyson
38224269Speterprivate:
38324269Speter  // Utility routines.
38424269Speter  static char* add_to_path(const char* path, const char* str, bool prepend);
38524269Speter  static char* add_jars_to_path(char* path, const char* directory);
38624269Speter
38724269Speter  inline void reset_item_at(int index);
38828345Sdyson
38924269Speter  // Array indices for the items that make up the sysclasspath.  All except the
39024269Speter  // base are allocated in the C heap and freed by this class.
39124269Speter  enum {
39224269Speter    _scp_prefix,        // from -Xbootclasspath/p:...
39324269Speter    _scp_base,          // the default sysclasspath
39424269Speter    _scp_suffix,        // from -Xbootclasspath/a:...
39524269Speter    _scp_nitems         // the number of items, must be last.
39624269Speter  };
39742900Seivind
39842900Seivind  const char* _items[_scp_nitems];
39942900Seivind};
40042900Seivind
40142900SeivindSysClassPath::SysClassPath(const char* base) {
40224269Speter  memset(_items, 0, sizeof(_items));
40324269Speter  _items[_scp_base] = base;
40424269Speter}
40524269Speter
40648225SmckusickSysClassPath::~SysClassPath() {
40751702Sdillon  // Free everything except the base.
40824269Speter  for (int i = 0; i < _scp_nitems; ++i) {
40924269Speter    if (i != _scp_base) reset_item_at(i);
41024269Speter  }
41151702Sdillon}
41234194Sdyson
41324269Speterinline void SysClassPath::set_base(const char* base) {
41424269Speter  _items[_scp_base] = base;
41534194Sdyson}
41634194Sdyson
41734194Sdysoninline void SysClassPath::add_prefix(const char* prefix) {
41824269Speter  _items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);
41971576Sjasone}
42028345Sdyson
42128345Sdysoninline void SysClassPath::add_suffix_to_prefix(const char* suffix) {
42224269Speter  _items[_scp_prefix] = add_to_path(_items[_scp_prefix], suffix, false);
42324269Speter}
42424269Speter
42524269Speterinline void SysClassPath::add_suffix(const char* suffix) {
42624269Speter  _items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);
42724269Speter}
42824269Speter
42924269Speterinline void SysClassPath::reset_item_at(int index) {
43024269Speter  assert(index < _scp_nitems && index != _scp_base, "just checking");
43124269Speter  if (_items[index] != NULL) {
43224269Speter    FREE_C_HEAP_ARRAY(char, _items[index]);
43324269Speter    _items[index] = NULL;
43428345Sdyson  }
43528345Sdyson}
43628345Sdyson
43724269Speterinline void SysClassPath::reset_path(const char* base) {
43824269Speter  // Clear the prefix and suffix.
43924269Speter  reset_item_at(_scp_prefix);
44024269Speter  reset_item_at(_scp_suffix);
44142900Seivind  set_base(base);
44242900Seivind}
44342900Seivind
44442900Seivind//------------------------------------------------------------------------------
44542900Seivind
44624269Speter
44724269Speter// Combine the bootclasspath elements, some of which may be null, into a single
44824269Speter// c-heap-allocated string.
44972200Sbmilekicchar* SysClassPath::combined_path() {
45024269Speter  assert(_items[_scp_base] != NULL, "empty default sysclasspath");
45124269Speter
45224269Speter  size_t lengths[_scp_nitems];
45324269Speter  size_t total_len = 0;
45428345Sdyson
45528345Sdyson  const char separator = *os::path_separator();
45628345Sdyson
45724269Speter  // Get the lengths.
45824269Speter  int i;
45924269Speter  for (i = 0; i < _scp_nitems; ++i) {
46072200Sbmilekic    if (_items[i] != NULL) {
46124269Speter      lengths[i] = strlen(_items[i]);
46224269Speter      // Include space for the separator char (or a NULL for the last item).
46324269Speter      total_len += lengths[i] + 1;
46429653Sdyson    }
46529653Sdyson  }
46629653Sdyson  assert(total_len > 0, "empty sysclasspath not allowed");
46729653Sdyson
46829653Sdyson  // Copy the _items to a single string.
46929653Sdyson  char* cp = NEW_C_HEAP_ARRAY(char, total_len, mtInternal);
47029653Sdyson  char* cp_tmp = cp;
47129653Sdyson  for (i = 0; i < _scp_nitems; ++i) {
47229653Sdyson    if (_items[i] != NULL) {
47329653Sdyson      memcpy(cp_tmp, _items[i], lengths[i]);
47429653Sdyson      cp_tmp += lengths[i];
47529653Sdyson      *cp_tmp++ = separator;
47629653Sdyson    }
47729653Sdyson  }
47869432Sjake  *--cp_tmp = '\0';     // Replace the extra separator.
47988318Sdillon  return cp;
48088318Sdillon}
48129653Sdyson
48229653Sdyson// Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
48329653Sdysonchar*
48429653SdysonSysClassPath::add_to_path(const char* path, const char* str, bool prepend) {
48529653Sdyson  char *cp;
48629653Sdyson
48729653Sdyson  assert(str != NULL, "just checking");
48829653Sdyson  if (path == NULL) {
48929653Sdyson    size_t len = strlen(str) + 1;
49024269Speter    cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
49129653Sdyson    memcpy(cp, str, len);                       // copy the trailing null
49229653Sdyson  } else {
49329653Sdyson    const char separator = *os::path_separator();
49429653Sdyson    size_t old_len = strlen(path);
49529653Sdyson    size_t str_len = strlen(str);
49629653Sdyson    size_t len = old_len + str_len + 2;
49791698Seivind
49829653Sdyson    if (prepend) {
49929653Sdyson      cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
50029653Sdyson      char* cp_tmp = cp;
50166615Sjasone      memcpy(cp_tmp, str, str_len);
50266615Sjasone      cp_tmp += str_len;
50329653Sdyson      *cp_tmp = separator;
50486333Sdillon      memcpy(++cp_tmp, path, old_len + 1);      // copy the trailing null
50593818Sjhb      FREE_C_HEAP_ARRAY(char, path);
50686333Sdillon    } else {
50786333Sdillon      cp = REALLOC_C_HEAP_ARRAY(char, path, len, mtInternal);
50886333Sdillon      char* cp_tmp = cp + old_len;
50986333Sdillon      *cp_tmp = separator;
51086333Sdillon      memcpy(++cp_tmp, str, str_len + 1);       // copy the trailing null
51186333Sdillon    }
51286333Sdillon  }
51372200Sbmilekic  return cp;
51486333Sdillon}
51572200Sbmilekic
51667046Sjasone// Scan the directory and append any jar or zip files found to path.
51767046Sjasone// Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
51867046Sjasonechar* SysClassPath::add_jars_to_path(char* path, const char* directory) {
51967046Sjasone  DIR* dir = os::opendir(directory);
52029653Sdyson  if (dir == NULL) return path;
52129653Sdyson
52229653Sdyson  char dir_sep[2] = { '\0', '\0' };
52329653Sdyson  size_t directory_len = strlen(directory);
52429653Sdyson  const char fileSep = *os::file_separator();
52529653Sdyson  if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;
52629653Sdyson
52729653Sdyson  /* Scan the directory for jars/zips, appending them to path. */
52829653Sdyson  struct dirent *entry;
52929653Sdyson  char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
53066615Sjasone  while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
53166615Sjasone    const char* name = entry->d_name;
53266615Sjasone    const char* ext = name + strlen(name) - 4;
53366615Sjasone    bool isJarOrZip = ext > name &&
53466615Sjasone      (os::file_name_strcmp(ext, ".jar") == 0 ||
53566615Sjasone       os::file_name_strcmp(ext, ".zip") == 0);
53666615Sjasone    if (isJarOrZip) {
53766615Sjasone      char* jarpath = NEW_C_HEAP_ARRAY(char, directory_len + 2 + strlen(name), mtInternal);
53866615Sjasone      sprintf(jarpath, "%s%s%s", directory, dir_sep, name);
53966615Sjasone      path = add_to_path(path, jarpath, false);
54066615Sjasone      FREE_C_HEAP_ARRAY(char, jarpath);
54129653Sdyson    }
54229653Sdyson  }
54329653Sdyson  FREE_C_HEAP_ARRAY(char, dbuf);
54483366Sjulian  os::closedir(dir);
54529653Sdyson  return path;
54683366Sjulian}
54729653Sdyson
54829653Sdyson// Parses a memory size specification string.
54929653Sdysonstatic bool atomull(const char *s, julong* result) {
55072200Sbmilekic  julong n = 0;
55154444Seivind  int args_read = 0;
55283366Sjulian  bool is_hex = false;
55354444Seivind  // Skip leading 0[xX] for hexadecimal
55454444Seivind  if (*s =='0' && (*(s+1) == 'x' || *(s+1) == 'X')) {
55554444Seivind    s += 2;
55654444Seivind    is_hex = true;
55729653Sdyson    args_read = sscanf(s, JULONG_FORMAT_X, &n);
55872200Sbmilekic  } else {
55929653Sdyson    args_read = sscanf(s, JULONG_FORMAT, &n);
56029653Sdyson  }
56129653Sdyson  if (args_read != 1) {
56229653Sdyson    return false;
56348225Smckusick  }
56448225Smckusick  while (*s != '\0' && (isdigit(*s) || (is_hex && isxdigit(*s)))) {
56548225Smckusick    s++;
56648225Smckusick  }
56748225Smckusick  // 4705540: illegal if more characters are found after the first non-digit
56848225Smckusick  if (strlen(s) > 1) {
56948225Smckusick    return false;
57048225Smckusick  }
57172200Sbmilekic  switch (*s) {
57248225Smckusick    case 'T': case 't':
57372200Sbmilekic      *result = n * G * K;
57448225Smckusick      // Check for overflow.
57548225Smckusick      if (*result/((julong)G * K) != n) return false;
57648225Smckusick      return true;
57748225Smckusick    case 'G': case 'g':
57824269Speter      *result = n * G;
57928569Sphk      if (*result/G != n) return false;
58024269Speter      return true;
58124271Speter    case 'M': case 'm':
58224269Speter      *result = n * M;
58324269Speter      if (*result/M != n) return false;
58424269Speter      return true;
58524269Speter    case 'K': case 'k':
58624269Speter      *result = n * K;
58724269Speter      if (*result/K != n) return false;
58824269Speter      return true;
58924269Speter    case '\0':
59024269Speter      *result = n;
59124269Speter      return true;
59224269Speter    default:
59324269Speter      return false;
59424269Speter  }
595}
596
597Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
598  if (size < min_size) return arg_too_small;
599  // Check that size will fit in a size_t (only relevant on 32-bit)
600  if (size > max_uintx) return arg_too_big;
601  return arg_in_range;
602}
603
604// Describe an argument out of range error
605void Arguments::describe_range_error(ArgsRange errcode) {
606  switch(errcode) {
607  case arg_too_big:
608    jio_fprintf(defaultStream::error_stream(),
609                "The specified size exceeds the maximum "
610                "representable size.\n");
611    break;
612  case arg_too_small:
613  case arg_unreadable:
614  case arg_in_range:
615    // do nothing for now
616    break;
617  default:
618    ShouldNotReachHere();
619  }
620}
621
622static bool set_bool_flag(char* name, bool value, Flag::Flags origin) {
623  return CommandLineFlags::boolAtPut(name, &value, origin);
624}
625
626static bool set_fp_numeric_flag(char* name, char* value, Flag::Flags origin) {
627  double v;
628  if (sscanf(value, "%lf", &v) != 1) {
629    return false;
630  }
631
632  if (CommandLineFlags::doubleAtPut(name, &v, origin)) {
633    return true;
634  }
635  return false;
636}
637
638static bool set_numeric_flag(char* name, char* value, Flag::Flags origin) {
639  julong v;
640  intx intx_v;
641  bool is_neg = false;
642  // Check the sign first since atomull() parses only unsigned values.
643  if (*value == '-') {
644    if (!CommandLineFlags::intxAt(name, &intx_v)) {
645      return false;
646    }
647    value++;
648    is_neg = true;
649  }
650  if (!atomull(value, &v)) {
651    return false;
652  }
653  intx_v = (intx) v;
654  if (is_neg) {
655    intx_v = -intx_v;
656  }
657  if (CommandLineFlags::intxAtPut(name, &intx_v, origin)) {
658    return true;
659  }
660  uintx uintx_v = (uintx) v;
661  if (!is_neg && CommandLineFlags::uintxAtPut(name, &uintx_v, origin)) {
662    return true;
663  }
664  uint64_t uint64_t_v = (uint64_t) v;
665  if (!is_neg && CommandLineFlags::uint64_tAtPut(name, &uint64_t_v, origin)) {
666    return true;
667  }
668  size_t size_t_v = (size_t) v;
669  if (!is_neg && CommandLineFlags::size_tAtPut(name, &size_t_v, origin)) {
670    return true;
671  }
672  return false;
673}
674
675static bool set_string_flag(char* name, const char* value, Flag::Flags origin) {
676  if (!CommandLineFlags::ccstrAtPut(name, &value, origin))  return false;
677  // Contract:  CommandLineFlags always returns a pointer that needs freeing.
678  FREE_C_HEAP_ARRAY(char, value);
679  return true;
680}
681
682static bool append_to_string_flag(char* name, const char* new_value, Flag::Flags origin) {
683  const char* old_value = "";
684  if (!CommandLineFlags::ccstrAt(name, &old_value))  return false;
685  size_t old_len = old_value != NULL ? strlen(old_value) : 0;
686  size_t new_len = strlen(new_value);
687  const char* value;
688  char* free_this_too = NULL;
689  if (old_len == 0) {
690    value = new_value;
691  } else if (new_len == 0) {
692    value = old_value;
693  } else {
694    char* buf = NEW_C_HEAP_ARRAY(char, old_len + 1 + new_len + 1, mtInternal);
695    // each new setting adds another LINE to the switch:
696    sprintf(buf, "%s\n%s", old_value, new_value);
697    value = buf;
698    free_this_too = buf;
699  }
700  (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
701  // CommandLineFlags always returns a pointer that needs freeing.
702  FREE_C_HEAP_ARRAY(char, value);
703  if (free_this_too != NULL) {
704    // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
705    FREE_C_HEAP_ARRAY(char, free_this_too);
706  }
707  return true;
708}
709
710bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
711
712  // range of acceptable characters spelled out for portability reasons
713#define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
714#define BUFLEN 255
715  char name[BUFLEN+1];
716  char dummy;
717
718  if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
719    return set_bool_flag(name, false, origin);
720  }
721  if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
722    return set_bool_flag(name, true, origin);
723  }
724
725  char punct;
726  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
727    const char* value = strchr(arg, '=') + 1;
728    Flag* flag = Flag::find_flag(name, strlen(name));
729    if (flag != NULL && flag->is_ccstr()) {
730      if (flag->ccstr_accumulates()) {
731        return append_to_string_flag(name, value, origin);
732      } else {
733        if (value[0] == '\0') {
734          value = NULL;
735        }
736        return set_string_flag(name, value, origin);
737      }
738    }
739  }
740
741  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
742    const char* value = strchr(arg, '=') + 1;
743    // -XX:Foo:=xxx will reset the string flag to the given value.
744    if (value[0] == '\0') {
745      value = NULL;
746    }
747    return set_string_flag(name, value, origin);
748  }
749
750#define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"
751#define SIGNED_NUMBER_RANGE    "[-0123456789]"
752#define        NUMBER_RANGE    "[0123456789]"
753  char value[BUFLEN + 1];
754  char value2[BUFLEN + 1];
755  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
756    // Looks like a floating-point number -- try again with more lenient format string
757    if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
758      return set_fp_numeric_flag(name, value, origin);
759    }
760  }
761
762#define VALUE_RANGE "[-kmgtxKMGTX0123456789abcdefABCDEF]"
763  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
764    return set_numeric_flag(name, value, origin);
765  }
766
767  return false;
768}
769
770void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
771  assert(bldarray != NULL, "illegal argument");
772
773  if (arg == NULL) {
774    return;
775  }
776
777  int new_count = *count + 1;
778
779  // expand the array and add arg to the last element
780  if (*bldarray == NULL) {
781    *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtInternal);
782  } else {
783    *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtInternal);
784  }
785  (*bldarray)[*count] = os::strdup_check_oom(arg);
786  *count = new_count;
787}
788
789void Arguments::build_jvm_args(const char* arg) {
790  add_string(&_jvm_args_array, &_num_jvm_args, arg);
791}
792
793void Arguments::build_jvm_flags(const char* arg) {
794  add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
795}
796
797// utility function to return a string that concatenates all
798// strings in a given char** array
799const char* Arguments::build_resource_string(char** args, int count) {
800  if (args == NULL || count == 0) {
801    return NULL;
802  }
803  size_t length = strlen(args[0]) + 1; // add 1 for the null terminator
804  for (int i = 1; i < count; i++) {
805    length += strlen(args[i]) + 1; // add 1 for a space
806  }
807  char* s = NEW_RESOURCE_ARRAY(char, length);
808  strcpy(s, args[0]);
809  for (int j = 1; j < count; j++) {
810    strcat(s, " ");
811    strcat(s, args[j]);
812  }
813  return (const char*) s;
814}
815
816void Arguments::print_on(outputStream* st) {
817  st->print_cr("VM Arguments:");
818  if (num_jvm_flags() > 0) {
819    st->print("jvm_flags: "); print_jvm_flags_on(st);
820  }
821  if (num_jvm_args() > 0) {
822    st->print("jvm_args: "); print_jvm_args_on(st);
823  }
824  st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
825  if (_java_class_path != NULL) {
826    char* path = _java_class_path->value();
827    st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
828  }
829  st->print_cr("Launcher Type: %s", _sun_java_launcher);
830}
831
832void Arguments::print_jvm_flags_on(outputStream* st) {
833  if (_num_jvm_flags > 0) {
834    for (int i=0; i < _num_jvm_flags; i++) {
835      st->print("%s ", _jvm_flags_array[i]);
836    }
837    st->cr();
838  }
839}
840
841void Arguments::print_jvm_args_on(outputStream* st) {
842  if (_num_jvm_args > 0) {
843    for (int i=0; i < _num_jvm_args; i++) {
844      st->print("%s ", _jvm_args_array[i]);
845    }
846    st->cr();
847  }
848}
849
850bool Arguments::process_argument(const char* arg,
851    jboolean ignore_unrecognized, Flag::Flags origin) {
852
853  JDK_Version since = JDK_Version();
854
855  if (parse_argument(arg, origin) || ignore_unrecognized) {
856    return true;
857  }
858
859  bool has_plus_minus = (*arg == '+' || *arg == '-');
860  const char* const argname = has_plus_minus ? arg + 1 : arg;
861  if (is_newly_obsolete(arg, &since)) {
862    char version[256];
863    since.to_string(version, sizeof(version));
864    warning("ignoring option %s; support was removed in %s", argname, version);
865    return true;
866  }
867
868  // For locked flags, report a custom error message if available.
869  // Otherwise, report the standard unrecognized VM option.
870
871  size_t arg_len;
872  const char* equal_sign = strchr(argname, '=');
873  if (equal_sign == NULL) {
874    arg_len = strlen(argname);
875  } else {
876    arg_len = equal_sign - argname;
877  }
878
879  Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
880  if (found_flag != NULL) {
881    char locked_message_buf[BUFLEN];
882    found_flag->get_locked_message(locked_message_buf, BUFLEN);
883    if (strlen(locked_message_buf) == 0) {
884      if (found_flag->is_bool() && !has_plus_minus) {
885        jio_fprintf(defaultStream::error_stream(),
886          "Missing +/- setting for VM option '%s'\n", argname);
887      } else if (!found_flag->is_bool() && has_plus_minus) {
888        jio_fprintf(defaultStream::error_stream(),
889          "Unexpected +/- setting in VM option '%s'\n", argname);
890      } else {
891        jio_fprintf(defaultStream::error_stream(),
892          "Improperly specified VM option '%s'\n", argname);
893      }
894    } else {
895      jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
896    }
897  } else {
898    jio_fprintf(defaultStream::error_stream(),
899                "Unrecognized VM option '%s'\n", argname);
900    Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
901    if (fuzzy_matched != NULL) {
902      jio_fprintf(defaultStream::error_stream(),
903                  "Did you mean '%s%s%s'? ",
904                  (fuzzy_matched->is_bool()) ? "(+/-)" : "",
905                  fuzzy_matched->_name,
906                  (fuzzy_matched->is_bool()) ? "" : "=<value>");
907      if (is_newly_obsolete(fuzzy_matched->_name, &since)) {
908        char version[256];
909        since.to_string(version, sizeof(version));
910        jio_fprintf(defaultStream::error_stream(),
911                    "Warning: support for %s was removed in %s\n",
912                    fuzzy_matched->_name,
913                    version);
914    }
915  }
916  }
917
918  // allow for commandline "commenting out" options like -XX:#+Verbose
919  return arg[0] == '#';
920}
921
922bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
923  FILE* stream = fopen(file_name, "rb");
924  if (stream == NULL) {
925    if (should_exist) {
926      jio_fprintf(defaultStream::error_stream(),
927                  "Could not open settings file %s\n", file_name);
928      return false;
929    } else {
930      return true;
931    }
932  }
933
934  char token[1024];
935  int  pos = 0;
936
937  bool in_white_space = true;
938  bool in_comment     = false;
939  bool in_quote       = false;
940  char quote_c        = 0;
941  bool result         = true;
942
943  int c = getc(stream);
944  while(c != EOF && pos < (int)(sizeof(token)-1)) {
945    if (in_white_space) {
946      if (in_comment) {
947        if (c == '\n') in_comment = false;
948      } else {
949        if (c == '#') in_comment = true;
950        else if (!isspace(c)) {
951          in_white_space = false;
952          token[pos++] = c;
953        }
954      }
955    } else {
956      if (c == '\n' || (!in_quote && isspace(c))) {
957        // token ends at newline, or at unquoted whitespace
958        // this allows a way to include spaces in string-valued options
959        token[pos] = '\0';
960        logOption(token);
961        result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
962        build_jvm_flags(token);
963        pos = 0;
964        in_white_space = true;
965        in_quote = false;
966      } else if (!in_quote && (c == '\'' || c == '"')) {
967        in_quote = true;
968        quote_c = c;
969      } else if (in_quote && (c == quote_c)) {
970        in_quote = false;
971      } else {
972        token[pos++] = c;
973      }
974    }
975    c = getc(stream);
976  }
977  if (pos > 0) {
978    token[pos] = '\0';
979    result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
980    build_jvm_flags(token);
981  }
982  fclose(stream);
983  return result;
984}
985
986//=============================================================================================================
987// Parsing of properties (-D)
988
989const char* Arguments::get_property(const char* key) {
990  return PropertyList_get_value(system_properties(), key);
991}
992
993bool Arguments::add_property(const char* prop) {
994  const char* eq = strchr(prop, '=');
995  char* key;
996  // ns must be static--its address may be stored in a SystemProperty object.
997  const static char ns[1] = {0};
998  char* value = (char *)ns;
999
1000  size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);
1001  key = AllocateHeap(key_len + 1, mtInternal);
1002  strncpy(key, prop, key_len);
1003  key[key_len] = '\0';
1004
1005  if (eq != NULL) {
1006    size_t value_len = strlen(prop) - key_len - 1;
1007    value = AllocateHeap(value_len + 1, mtInternal);
1008    strncpy(value, &prop[key_len + 1], value_len + 1);
1009  }
1010
1011  if (strcmp(key, "java.compiler") == 0) {
1012    process_java_compiler_argument(value);
1013    FreeHeap(key);
1014    if (eq != NULL) {
1015      FreeHeap(value);
1016    }
1017    return true;
1018  } else if (strcmp(key, "sun.java.command") == 0) {
1019    _java_command = value;
1020
1021    // Record value in Arguments, but let it get passed to Java.
1022  } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0 ||
1023             strcmp(key, "sun.java.launcher.pid") == 0) {
1024    // sun.java.launcher.is_altjvm and sun.java.launcher.pid property are
1025    // private and are processed in process_sun_java_launcher_properties();
1026    // the sun.java.launcher property is passed on to the java application
1027    FreeHeap(key);
1028    if (eq != NULL) {
1029      FreeHeap(value);
1030    }
1031    return true;
1032  } else if (strcmp(key, "java.vendor.url.bug") == 0) {
1033    // save it in _java_vendor_url_bug, so JVM fatal error handler can access
1034    // its value without going through the property list or making a Java call.
1035    _java_vendor_url_bug = value;
1036  } else if (strcmp(key, "sun.boot.library.path") == 0) {
1037    PropertyList_unique_add(&_system_properties, key, value, true);
1038    return true;
1039  }
1040  // Create new property and add at the end of the list
1041  PropertyList_unique_add(&_system_properties, key, value);
1042  return true;
1043}
1044
1045//===========================================================================================================
1046// Setting int/mixed/comp mode flags
1047
1048void Arguments::set_mode_flags(Mode mode) {
1049  // Set up default values for all flags.
1050  // If you add a flag to any of the branches below,
1051  // add a default value for it here.
1052  set_java_compiler(false);
1053  _mode                      = mode;
1054
1055  // Ensure Agent_OnLoad has the correct initial values.
1056  // This may not be the final mode; mode may change later in onload phase.
1057  PropertyList_unique_add(&_system_properties, "java.vm.info",
1058                          (char*)VM_Version::vm_info_string(), false);
1059
1060  UseInterpreter             = true;
1061  UseCompiler                = true;
1062  UseLoopCounter             = true;
1063
1064  // Default values may be platform/compiler dependent -
1065  // use the saved values
1066  ClipInlining               = Arguments::_ClipInlining;
1067  AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1068  UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1069  BackgroundCompilation      = Arguments::_BackgroundCompilation;
1070
1071  // Change from defaults based on mode
1072  switch (mode) {
1073  default:
1074    ShouldNotReachHere();
1075    break;
1076  case _int:
1077    UseCompiler              = false;
1078    UseLoopCounter           = false;
1079    AlwaysCompileLoopMethods = false;
1080    UseOnStackReplacement    = false;
1081    break;
1082  case _mixed:
1083    // same as default
1084    break;
1085  case _comp:
1086    UseInterpreter           = false;
1087    BackgroundCompilation    = false;
1088    ClipInlining             = false;
1089    // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1090    // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1091    // compile a level 4 (C2) and then continue executing it.
1092    if (TieredCompilation) {
1093      Tier3InvokeNotifyFreqLog = 0;
1094      Tier4InvocationThreshold = 0;
1095    }
1096    break;
1097  }
1098}
1099
1100#if defined(COMPILER2) || defined(_LP64) || !INCLUDE_CDS
1101// Conflict: required to use shared spaces (-Xshare:on), but
1102// incompatible command line options were chosen.
1103
1104static void no_shared_spaces(const char* message) {
1105  if (RequireSharedSpaces) {
1106    jio_fprintf(defaultStream::error_stream(),
1107      "Class data sharing is inconsistent with other specified options.\n");
1108    vm_exit_during_initialization("Unable to use shared archive.", message);
1109  } else {
1110    FLAG_SET_DEFAULT(UseSharedSpaces, false);
1111  }
1112}
1113#endif
1114
1115// Returns threshold scaled with the value of scale.
1116// If scale < 0.0, threshold is returned without scaling.
1117intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
1118  if (scale == 1.0 || scale < 0.0) {
1119    return threshold;
1120  } else {
1121    return (intx)(threshold * scale);
1122  }
1123}
1124
1125// Returns freq_log scaled with the value of scale.
1126// Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
1127// If scale < 0.0, freq_log is returned without scaling.
1128intx Arguments::scaled_freq_log(intx freq_log, double scale) {
1129  // Check if scaling is necessary or if negative value was specified.
1130  if (scale == 1.0 || scale < 0.0) {
1131    return freq_log;
1132  }
1133  // Check values to avoid calculating log2 of 0.
1134  if (scale == 0.0 || freq_log == 0) {
1135    return 0;
1136  }
1137  // Determine the maximum notification frequency value currently supported.
1138  // The largest mask value that the interpreter/C1 can handle is
1139  // of length InvocationCounter::number_of_count_bits. Mask values are always
1140  // one bit shorter then the value of the notification frequency. Set
1141  // max_freq_bits accordingly.
1142  intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
1143  intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
1144  if (scaled_freq == 0) {
1145    // Return 0 right away to avoid calculating log2 of 0.
1146    return 0;
1147  } else if (scaled_freq > nth_bit(max_freq_bits)) {
1148    return max_freq_bits;
1149  } else {
1150    return log2_intptr(scaled_freq);
1151  }
1152}
1153
1154void Arguments::set_tiered_flags() {
1155  // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1156  if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1157    FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1158  }
1159  if (CompilationPolicyChoice < 2) {
1160    vm_exit_during_initialization(
1161      "Incompatible compilation policy selected", NULL);
1162  }
1163  // Increase the code cache size - tiered compiles a lot more.
1164  if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1165    FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
1166                  MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1167  }
1168  // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
1169  if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
1170    FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
1171
1172    if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1173      // Multiply sizes by 5 but fix NonNMethodCodeHeapSize (distribute among non-profiled and profiled code heap)
1174      if (FLAG_IS_DEFAULT(ProfiledCodeHeapSize)) {
1175        FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, ProfiledCodeHeapSize * 5 + NonNMethodCodeHeapSize * 2);
1176      }
1177      if (FLAG_IS_DEFAULT(NonProfiledCodeHeapSize)) {
1178        FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, NonProfiledCodeHeapSize * 5 + NonNMethodCodeHeapSize * 2);
1179      }
1180      // Check consistency of code heap sizes
1181      if ((NonNMethodCodeHeapSize + NonProfiledCodeHeapSize + ProfiledCodeHeapSize) != ReservedCodeCacheSize) {
1182        jio_fprintf(defaultStream::error_stream(),
1183                    "Invalid code heap sizes: NonNMethodCodeHeapSize(%dK) + ProfiledCodeHeapSize(%dK) + NonProfiledCodeHeapSize(%dK) = %dK. Must be equal to ReservedCodeCacheSize = %uK.\n",
1184                    NonNMethodCodeHeapSize/K, ProfiledCodeHeapSize/K, NonProfiledCodeHeapSize/K,
1185                    (NonNMethodCodeHeapSize + ProfiledCodeHeapSize + NonProfiledCodeHeapSize)/K, ReservedCodeCacheSize/K);
1186        vm_exit(1);
1187      }
1188    }
1189  }
1190  if (!UseInterpreter) { // -Xcomp
1191    Tier3InvokeNotifyFreqLog = 0;
1192    Tier4InvocationThreshold = 0;
1193  }
1194
1195  if (CompileThresholdScaling < 0) {
1196    vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
1197  }
1198
1199  // Scale tiered compilation thresholds.
1200  // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
1201  if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
1202    FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
1203    FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
1204
1205    FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
1206    FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
1207    FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
1208    FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
1209
1210    // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
1211    // once these thresholds become supported.
1212
1213    FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
1214    FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
1215
1216    FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
1217    FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
1218
1219    FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
1220
1221    FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
1222    FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
1223    FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
1224    FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
1225  }
1226}
1227
1228/**
1229 * Returns the minimum number of compiler threads needed to run the JVM. The following
1230 * configurations are possible.
1231 *
1232 * 1) The JVM is build using an interpreter only. As a result, the minimum number of
1233 *    compiler threads is 0.
1234 * 2) The JVM is build using the compiler(s) and tiered compilation is disabled. As
1235 *    a result, either C1 or C2 is used, so the minimum number of compiler threads is 1.
1236 * 3) The JVM is build using the compiler(s) and tiered compilation is enabled. However,
1237 *    the option "TieredStopAtLevel < CompLevel_full_optimization". As a result, only
1238 *    C1 can be used, so the minimum number of compiler threads is 1.
1239 * 4) The JVM is build using the compilers and tiered compilation is enabled. The option
1240 *    'TieredStopAtLevel = CompLevel_full_optimization' (the default value). As a result,
1241 *    the minimum number of compiler threads is 2.
1242 */
1243int Arguments::get_min_number_of_compiler_threads() {
1244#if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)
1245  return 0;   // case 1
1246#else
1247  if (!TieredCompilation || (TieredStopAtLevel < CompLevel_full_optimization)) {
1248    return 1; // case 2 or case 3
1249  }
1250  return 2;   // case 4 (tiered)
1251#endif
1252}
1253
1254#if INCLUDE_ALL_GCS
1255static void disable_adaptive_size_policy(const char* collector_name) {
1256  if (UseAdaptiveSizePolicy) {
1257    if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
1258      warning("disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
1259              collector_name);
1260    }
1261    FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
1262  }
1263}
1264
1265void Arguments::set_parnew_gc_flags() {
1266  assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
1267         "control point invariant");
1268  assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1269  assert(UseParNewGC, "ParNew should always be used with CMS");
1270
1271  if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
1272    FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1273    assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
1274  } else if (ParallelGCThreads == 0) {
1275    jio_fprintf(defaultStream::error_stream(),
1276        "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
1277    vm_exit(1);
1278  }
1279
1280  // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
1281  // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
1282  // we set them to 1024 and 1024.
1283  // See CR 6362902.
1284  if (FLAG_IS_DEFAULT(YoungPLABSize)) {
1285    FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
1286  }
1287  if (FLAG_IS_DEFAULT(OldPLABSize)) {
1288    FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
1289  }
1290
1291  // When using compressed oops, we use local overflow stacks,
1292  // rather than using a global overflow list chained through
1293  // the klass word of the object's pre-image.
1294  if (UseCompressedOops && !ParGCUseLocalOverflow) {
1295    if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
1296      warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
1297    }
1298    FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
1299  }
1300  assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
1301}
1302
1303// Adjust some sizes to suit CMS and/or ParNew needs; these work well on
1304// sparc/solaris for certain applications, but would gain from
1305// further optimization and tuning efforts, and would almost
1306// certainly gain from analysis of platform and environment.
1307void Arguments::set_cms_and_parnew_gc_flags() {
1308  assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
1309  assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1310  assert(UseParNewGC, "ParNew should always be used with CMS");
1311
1312  // Turn off AdaptiveSizePolicy by default for cms until it is complete.
1313  disable_adaptive_size_policy("UseConcMarkSweepGC");
1314
1315  set_parnew_gc_flags();
1316
1317  size_t max_heap = align_size_down(MaxHeapSize,
1318                                    CardTableRS::ct_max_alignment_constraint());
1319
1320  // Now make adjustments for CMS
1321  intx   tenuring_default = (intx)6;
1322  size_t young_gen_per_worker = CMSYoungGenPerWorker;
1323
1324  // Preferred young gen size for "short" pauses:
1325  // upper bound depends on # of threads and NewRatio.
1326  const uintx parallel_gc_threads =
1327    (ParallelGCThreads == 0 ? 1 : ParallelGCThreads);
1328  const size_t preferred_max_new_size_unaligned =
1329    MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * parallel_gc_threads));
1330  size_t preferred_max_new_size =
1331    align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
1332
1333  // Unless explicitly requested otherwise, size young gen
1334  // for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
1335
1336  // If either MaxNewSize or NewRatio is set on the command line,
1337  // assume the user is trying to set the size of the young gen.
1338  if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
1339
1340    // Set MaxNewSize to our calculated preferred_max_new_size unless
1341    // NewSize was set on the command line and it is larger than
1342    // preferred_max_new_size.
1343    if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
1344      FLAG_SET_ERGO(uintx, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
1345    } else {
1346      FLAG_SET_ERGO(uintx, MaxNewSize, preferred_max_new_size);
1347    }
1348    if (PrintGCDetails && Verbose) {
1349      // Too early to use gclog_or_tty
1350      tty->print_cr("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
1351    }
1352
1353    // Code along this path potentially sets NewSize and OldSize
1354    if (PrintGCDetails && Verbose) {
1355      // Too early to use gclog_or_tty
1356      tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
1357           " initial_heap_size:  " SIZE_FORMAT
1358           " max_heap: " SIZE_FORMAT,
1359           min_heap_size(), InitialHeapSize, max_heap);
1360    }
1361    size_t min_new = preferred_max_new_size;
1362    if (FLAG_IS_CMDLINE(NewSize)) {
1363      min_new = NewSize;
1364    }
1365    if (max_heap > min_new && min_heap_size() > min_new) {
1366      // Unless explicitly requested otherwise, make young gen
1367      // at least min_new, and at most preferred_max_new_size.
1368      if (FLAG_IS_DEFAULT(NewSize)) {
1369        FLAG_SET_ERGO(uintx, NewSize, MAX2(NewSize, min_new));
1370        FLAG_SET_ERGO(uintx, NewSize, MIN2(preferred_max_new_size, NewSize));
1371        if (PrintGCDetails && Verbose) {
1372          // Too early to use gclog_or_tty
1373          tty->print_cr("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
1374        }
1375      }
1376      // Unless explicitly requested otherwise, size old gen
1377      // so it's NewRatio x of NewSize.
1378      if (FLAG_IS_DEFAULT(OldSize)) {
1379        if (max_heap > NewSize) {
1380          FLAG_SET_ERGO(uintx, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
1381          if (PrintGCDetails && Verbose) {
1382            // Too early to use gclog_or_tty
1383            tty->print_cr("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
1384          }
1385        }
1386      }
1387    }
1388  }
1389  // Unless explicitly requested otherwise, definitely
1390  // promote all objects surviving "tenuring_default" scavenges.
1391  if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
1392      FLAG_IS_DEFAULT(SurvivorRatio)) {
1393    FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
1394  }
1395  // If we decided above (or user explicitly requested)
1396  // `promote all' (via MaxTenuringThreshold := 0),
1397  // prefer minuscule survivor spaces so as not to waste
1398  // space for (non-existent) survivors
1399  if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
1400    FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
1401  }
1402
1403  // OldPLABSize is interpreted in CMS as not the size of the PLAB in words,
1404  // but rather the number of free blocks of a given size that are used when
1405  // replenishing the local per-worker free list caches.
1406  if (FLAG_IS_DEFAULT(OldPLABSize)) {
1407    if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
1408      // OldPLAB sizing manually turned off: Use a larger default setting,
1409      // unless it was manually specified. This is because a too-low value
1410      // will slow down scavenges.
1411      FLAG_SET_ERGO(uintx, OldPLABSize, CFLS_LAB::_default_static_old_plab_size); // default value before 6631166
1412    } else {
1413      FLAG_SET_DEFAULT(OldPLABSize, CFLS_LAB::_default_dynamic_old_plab_size); // old CMSParPromoteBlocksToClaim default
1414    }
1415  }
1416
1417  // If either of the static initialization defaults have changed, note this
1418  // modification.
1419  if (!FLAG_IS_DEFAULT(OldPLABSize) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
1420    CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
1421  }
1422  if (PrintGCDetails && Verbose) {
1423    tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1424      (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1425    tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
1426  }
1427}
1428#endif // INCLUDE_ALL_GCS
1429
1430void set_object_alignment() {
1431  // Object alignment.
1432  assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1433  MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1434  assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1435  MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1436  assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1437  MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1438
1439  LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1440  LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1441
1442  // Oop encoding heap max
1443  OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1444
1445#if INCLUDE_ALL_GCS
1446  // Set CMS global values
1447  CompactibleFreeListSpace::set_cms_values();
1448#endif // INCLUDE_ALL_GCS
1449}
1450
1451bool verify_object_alignment() {
1452  // Object alignment.
1453  if (!is_power_of_2(ObjectAlignmentInBytes)) {
1454    jio_fprintf(defaultStream::error_stream(),
1455                "error: ObjectAlignmentInBytes=%d must be power of 2\n",
1456                (int)ObjectAlignmentInBytes);
1457    return false;
1458  }
1459  if ((int)ObjectAlignmentInBytes < BytesPerLong) {
1460    jio_fprintf(defaultStream::error_stream(),
1461                "error: ObjectAlignmentInBytes=%d must be greater or equal %d\n",
1462                (int)ObjectAlignmentInBytes, BytesPerLong);
1463    return false;
1464  }
1465  // It does not make sense to have big object alignment
1466  // since a space lost due to alignment will be greater
1467  // then a saved space from compressed oops.
1468  if ((int)ObjectAlignmentInBytes > 256) {
1469    jio_fprintf(defaultStream::error_stream(),
1470                "error: ObjectAlignmentInBytes=%d must not be greater than 256\n",
1471                (int)ObjectAlignmentInBytes);
1472    return false;
1473  }
1474  // In case page size is very small.
1475  if ((int)ObjectAlignmentInBytes >= os::vm_page_size()) {
1476    jio_fprintf(defaultStream::error_stream(),
1477                "error: ObjectAlignmentInBytes=%d must be less than page size %d\n",
1478                (int)ObjectAlignmentInBytes, os::vm_page_size());
1479    return false;
1480  }
1481  if(SurvivorAlignmentInBytes == 0) {
1482    SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1483  } else {
1484    if (!is_power_of_2(SurvivorAlignmentInBytes)) {
1485      jio_fprintf(defaultStream::error_stream(),
1486            "error: SurvivorAlignmentInBytes=%d must be power of 2\n",
1487            (int)SurvivorAlignmentInBytes);
1488      return false;
1489    }
1490    if (SurvivorAlignmentInBytes < ObjectAlignmentInBytes) {
1491      jio_fprintf(defaultStream::error_stream(),
1492          "error: SurvivorAlignmentInBytes=%d must be greater than ObjectAlignmentInBytes=%d \n",
1493          (int)SurvivorAlignmentInBytes, (int)ObjectAlignmentInBytes);
1494      return false;
1495    }
1496  }
1497  return true;
1498}
1499
1500size_t Arguments::max_heap_for_compressed_oops() {
1501  // Avoid sign flip.
1502  assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1503  // We need to fit both the NULL page and the heap into the memory budget, while
1504  // keeping alignment constraints of the heap. To guarantee the latter, as the
1505  // NULL page is located before the heap, we pad the NULL page to the conservative
1506  // maximum alignment that the GC may ever impose upon the heap.
1507  size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
1508                                                        _conservative_max_heap_alignment);
1509
1510  LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1511  NOT_LP64(ShouldNotReachHere(); return 0);
1512}
1513
1514bool Arguments::should_auto_select_low_pause_collector() {
1515  if (UseAutoGCSelectPolicy &&
1516      !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
1517      (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
1518    if (PrintGCDetails) {
1519      // Cannot use gclog_or_tty yet.
1520      tty->print_cr("Automatic selection of the low pause collector"
1521       " based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
1522    }
1523    return true;
1524  }
1525  return false;
1526}
1527
1528void Arguments::set_use_compressed_oops() {
1529#ifndef ZERO
1530#ifdef _LP64
1531  // MaxHeapSize is not set up properly at this point, but
1532  // the only value that can override MaxHeapSize if we are
1533  // to use UseCompressedOops is InitialHeapSize.
1534  size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1535
1536  if (max_heap_size <= max_heap_for_compressed_oops()) {
1537#if !defined(COMPILER1) || defined(TIERED)
1538    if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1539      FLAG_SET_ERGO(bool, UseCompressedOops, true);
1540    }
1541#endif
1542  } else {
1543    if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1544      warning("Max heap size too large for Compressed Oops");
1545      FLAG_SET_DEFAULT(UseCompressedOops, false);
1546      FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1547    }
1548  }
1549#endif // _LP64
1550#endif // ZERO
1551}
1552
1553
1554// NOTE: set_use_compressed_klass_ptrs() must be called after calling
1555// set_use_compressed_oops().
1556void Arguments::set_use_compressed_klass_ptrs() {
1557#ifndef ZERO
1558#ifdef _LP64
1559  // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1560  if (!UseCompressedOops) {
1561    if (UseCompressedClassPointers) {
1562      warning("UseCompressedClassPointers requires UseCompressedOops");
1563    }
1564    FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1565  } else {
1566    // Turn on UseCompressedClassPointers too
1567    if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1568      FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1569    }
1570    // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1571    if (UseCompressedClassPointers) {
1572      if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1573        warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1574        FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1575      }
1576    }
1577  }
1578#endif // _LP64
1579#endif // !ZERO
1580}
1581
1582void Arguments::set_conservative_max_heap_alignment() {
1583  // The conservative maximum required alignment for the heap is the maximum of
1584  // the alignments imposed by several sources: any requirements from the heap
1585  // itself, the collector policy and the maximum page size we may run the VM
1586  // with.
1587  size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
1588#if INCLUDE_ALL_GCS
1589  if (UseParallelGC) {
1590    heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
1591  } else if (UseG1GC) {
1592    heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
1593  }
1594#endif // INCLUDE_ALL_GCS
1595  _conservative_max_heap_alignment = MAX4(heap_alignment,
1596                                          (size_t)os::vm_allocation_granularity(),
1597                                          os::max_page_size(),
1598                                          CollectorPolicy::compute_heap_alignment());
1599}
1600
1601void Arguments::select_gc_ergonomically() {
1602  if (os::is_server_class_machine()) {
1603    if (should_auto_select_low_pause_collector()) {
1604      FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
1605    } else {
1606      FLAG_SET_ERGO(bool, UseParallelGC, true);
1607    }
1608  }
1609}
1610
1611void Arguments::select_gc() {
1612  if (!gc_selected()) {
1613    ArgumentsExt::select_gc_ergonomically();
1614  }
1615}
1616
1617void Arguments::set_ergonomics_flags() {
1618  select_gc();
1619
1620#ifdef COMPILER2
1621  // Shared spaces work fine with other GCs but causes bytecode rewriting
1622  // to be disabled, which hurts interpreter performance and decreases
1623  // server performance.  When -server is specified, keep the default off
1624  // unless it is asked for.  Future work: either add bytecode rewriting
1625  // at link time, or rewrite bytecodes in non-shared methods.
1626  if (!DumpSharedSpaces && !RequireSharedSpaces &&
1627      (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1628    no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1629  }
1630#endif
1631
1632  set_conservative_max_heap_alignment();
1633
1634#ifndef ZERO
1635#ifdef _LP64
1636  set_use_compressed_oops();
1637
1638  // set_use_compressed_klass_ptrs() must be called after calling
1639  // set_use_compressed_oops().
1640  set_use_compressed_klass_ptrs();
1641
1642  // Also checks that certain machines are slower with compressed oops
1643  // in vm_version initialization code.
1644#endif // _LP64
1645#endif // !ZERO
1646}
1647
1648void Arguments::set_parallel_gc_flags() {
1649  assert(UseParallelGC || UseParallelOldGC, "Error");
1650  // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1651  if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1652    FLAG_SET_DEFAULT(UseParallelOldGC, true);
1653  }
1654  FLAG_SET_DEFAULT(UseParallelGC, true);
1655
1656  // If no heap maximum was requested explicitly, use some reasonable fraction
1657  // of the physical memory, up to a maximum of 1GB.
1658  FLAG_SET_DEFAULT(ParallelGCThreads,
1659                   Abstract_VM_Version::parallel_worker_threads());
1660  if (ParallelGCThreads == 0) {
1661    jio_fprintf(defaultStream::error_stream(),
1662        "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1663    vm_exit(1);
1664  }
1665
1666  if (UseAdaptiveSizePolicy) {
1667    // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1668    // unless the user actually sets these flags.
1669    if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1670      FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1671      _min_heap_free_ratio = MinHeapFreeRatio;
1672    }
1673    if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1674      FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1675      _max_heap_free_ratio = MaxHeapFreeRatio;
1676    }
1677  }
1678
1679  // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1680  // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1681  // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1682  // See CR 6362902 for details.
1683  if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1684    if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1685       FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1686    }
1687    if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1688      FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1689    }
1690  }
1691
1692  if (UseParallelOldGC) {
1693    // Par compact uses lower default values since they are treated as
1694    // minimums.  These are different defaults because of the different
1695    // interpretation and are not ergonomically set.
1696    if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1697      FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1698    }
1699  }
1700}
1701
1702void Arguments::set_g1_gc_flags() {
1703  assert(UseG1GC, "Error");
1704#ifdef COMPILER1
1705  FastTLABRefill = false;
1706#endif
1707  FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1708  if (ParallelGCThreads == 0) {
1709    assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
1710    vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1711  }
1712
1713#if INCLUDE_ALL_GCS
1714  if (G1ConcRefinementThreads == 0) {
1715    FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);
1716  }
1717#endif
1718
1719  // MarkStackSize will be set (if it hasn't been set by the user)
1720  // when concurrent marking is initialized.
1721  // Its value will be based upon the number of parallel marking threads.
1722  // But we do set the maximum mark stack size here.
1723  if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1724    FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1725  }
1726
1727  if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1728    // In G1, we want the default GC overhead goal to be higher than
1729    // say in PS. So we set it here to 10%. Otherwise the heap might
1730    // be expanded more aggressively than we would like it to. In
1731    // fact, even 10% seems to not be high enough in some cases
1732    // (especially small GC stress tests that the main thing they do
1733    // is allocation). We might consider increase it further.
1734    FLAG_SET_DEFAULT(GCTimeRatio, 9);
1735  }
1736
1737  if (PrintGCDetails && Verbose) {
1738    tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1739      (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1740    tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
1741  }
1742}
1743
1744#if !INCLUDE_ALL_GCS
1745#ifdef ASSERT
1746static bool verify_serial_gc_flags() {
1747  return (UseSerialGC &&
1748        !(UseParNewGC || (UseConcMarkSweepGC) || UseG1GC ||
1749          UseParallelGC || UseParallelOldGC));
1750}
1751#endif // ASSERT
1752#endif // INCLUDE_ALL_GCS
1753
1754void Arguments::set_gc_specific_flags() {
1755#if INCLUDE_ALL_GCS
1756  // Set per-collector flags
1757  if (UseParallelGC || UseParallelOldGC) {
1758    set_parallel_gc_flags();
1759  } else if (UseConcMarkSweepGC) {
1760    set_cms_and_parnew_gc_flags();
1761  } else if (UseG1GC) {
1762    set_g1_gc_flags();
1763  }
1764  check_deprecated_gc_flags();
1765  if (AssumeMP && !UseSerialGC) {
1766    if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
1767      warning("If the number of processors is expected to increase from one, then"
1768              " you should configure the number of parallel GC threads appropriately"
1769              " using -XX:ParallelGCThreads=N");
1770    }
1771  }
1772  if (MinHeapFreeRatio == 100) {
1773    // Keeping the heap 100% free is hard ;-) so limit it to 99%.
1774    FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
1775  }
1776#else // INCLUDE_ALL_GCS
1777  assert(verify_serial_gc_flags(), "SerialGC unset");
1778#endif // INCLUDE_ALL_GCS
1779}
1780
1781julong Arguments::limit_by_allocatable_memory(julong limit) {
1782  julong max_allocatable;
1783  julong result = limit;
1784  if (os::has_allocatable_memory_limit(&max_allocatable)) {
1785    result = MIN2(result, max_allocatable / MaxVirtMemFraction);
1786  }
1787  return result;
1788}
1789
1790// Use static initialization to get the default before parsing
1791static const uintx DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1792
1793void Arguments::set_heap_size() {
1794  if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
1795    // Deprecated flag
1796    FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
1797  }
1798
1799  const julong phys_mem =
1800    FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1801                            : (julong)MaxRAM;
1802
1803  // If the maximum heap size has not been set with -Xmx,
1804  // then set it as fraction of the size of physical memory,
1805  // respecting the maximum and minimum sizes of the heap.
1806  if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1807    julong reasonable_max = phys_mem / MaxRAMFraction;
1808
1809    if (phys_mem <= MaxHeapSize * MinRAMFraction) {
1810      // Small physical memory, so use a minimum fraction of it for the heap
1811      reasonable_max = phys_mem / MinRAMFraction;
1812    } else {
1813      // Not-small physical memory, so require a heap at least
1814      // as large as MaxHeapSize
1815      reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1816    }
1817    if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1818      // Limit the heap size to ErgoHeapSizeLimit
1819      reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1820    }
1821    if (UseCompressedOops) {
1822      // Limit the heap size to the maximum possible when using compressed oops
1823      julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1824
1825      // HeapBaseMinAddress can be greater than default but not less than.
1826      if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1827        if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1828          // matches compressed oops printing flags
1829          if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
1830            jio_fprintf(defaultStream::error_stream(),
1831                        "HeapBaseMinAddress must be at least " UINTX_FORMAT
1832                        " (" UINTX_FORMAT "G) which is greater than value given "
1833                        UINTX_FORMAT "\n",
1834                        DefaultHeapBaseMinAddress,
1835                        DefaultHeapBaseMinAddress/G,
1836                        HeapBaseMinAddress);
1837          }
1838          FLAG_SET_ERGO(uintx, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1839        }
1840      }
1841
1842      if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1843        // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1844        // but it should be not less than default MaxHeapSize.
1845        max_coop_heap -= HeapBaseMinAddress;
1846      }
1847      reasonable_max = MIN2(reasonable_max, max_coop_heap);
1848    }
1849    reasonable_max = limit_by_allocatable_memory(reasonable_max);
1850
1851    if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1852      // An initial heap size was specified on the command line,
1853      // so be sure that the maximum size is consistent.  Done
1854      // after call to limit_by_allocatable_memory because that
1855      // method might reduce the allocation size.
1856      reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1857    }
1858
1859    if (PrintGCDetails && Verbose) {
1860      // Cannot use gclog_or_tty yet.
1861      tty->print_cr("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1862    }
1863    FLAG_SET_ERGO(uintx, MaxHeapSize, (uintx)reasonable_max);
1864  }
1865
1866  // If the minimum or initial heap_size have not been set or requested to be set
1867  // ergonomically, set them accordingly.
1868  if (InitialHeapSize == 0 || min_heap_size() == 0) {
1869    julong reasonable_minimum = (julong)(OldSize + NewSize);
1870
1871    reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1872
1873    reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1874
1875    if (InitialHeapSize == 0) {
1876      julong reasonable_initial = phys_mem / InitialRAMFraction;
1877
1878      reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
1879      reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1880
1881      reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
1882
1883      if (PrintGCDetails && Verbose) {
1884        // Cannot use gclog_or_tty yet.
1885        tty->print_cr("  Initial heap size " SIZE_FORMAT, (uintx)reasonable_initial);
1886      }
1887      FLAG_SET_ERGO(uintx, InitialHeapSize, (uintx)reasonable_initial);
1888    }
1889    // If the minimum heap size has not been set (via -Xms),
1890    // synchronize with InitialHeapSize to avoid errors with the default value.
1891    if (min_heap_size() == 0) {
1892      set_min_heap_size(MIN2((uintx)reasonable_minimum, InitialHeapSize));
1893      if (PrintGCDetails && Verbose) {
1894        // Cannot use gclog_or_tty yet.
1895        tty->print_cr("  Minimum heap size " SIZE_FORMAT, min_heap_size());
1896      }
1897    }
1898  }
1899}
1900
1901// This must be called after ergonomics because we want bytecode rewriting
1902// if the server compiler is used, or if UseSharedSpaces is disabled.
1903void Arguments::set_bytecode_flags() {
1904  // Better not attempt to store into a read-only space.
1905  if (UseSharedSpaces) {
1906    FLAG_SET_DEFAULT(RewriteBytecodes, false);
1907    FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1908  }
1909
1910  if (!RewriteBytecodes) {
1911    FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1912  }
1913}
1914
1915// Aggressive optimization flags  -XX:+AggressiveOpts
1916void Arguments::set_aggressive_opts_flags() {
1917#ifdef COMPILER2
1918  if (AggressiveUnboxing) {
1919    if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1920      FLAG_SET_DEFAULT(EliminateAutoBox, true);
1921    } else if (!EliminateAutoBox) {
1922      // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
1923      AggressiveUnboxing = false;
1924    }
1925    if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1926      FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1927    } else if (!DoEscapeAnalysis) {
1928      // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
1929      AggressiveUnboxing = false;
1930    }
1931  }
1932  if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1933    if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1934      FLAG_SET_DEFAULT(EliminateAutoBox, true);
1935    }
1936    if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1937      FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
1938    }
1939
1940    // Feed the cache size setting into the JDK
1941    char buffer[1024];
1942    sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
1943    add_property(buffer);
1944  }
1945  if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
1946    FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
1947  }
1948#endif
1949
1950  if (AggressiveOpts) {
1951// Sample flag setting code
1952//    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
1953//      FLAG_SET_DEFAULT(EliminateZeroing, true);
1954//    }
1955  }
1956}
1957
1958//===========================================================================================================
1959// Parsing of java.compiler property
1960
1961void Arguments::process_java_compiler_argument(char* arg) {
1962  // For backwards compatibility, Djava.compiler=NONE or ""
1963  // causes us to switch to -Xint mode UNLESS -Xdebug
1964  // is also specified.
1965  if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
1966    set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
1967  }
1968}
1969
1970void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1971  _sun_java_launcher = os::strdup_check_oom(launcher);
1972}
1973
1974bool Arguments::created_by_java_launcher() {
1975  assert(_sun_java_launcher != NULL, "property must have value");
1976  return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1977}
1978
1979bool Arguments::sun_java_launcher_is_altjvm() {
1980  return _sun_java_launcher_is_altjvm;
1981}
1982
1983//===========================================================================================================
1984// Parsing of main arguments
1985
1986bool Arguments::verify_interval(uintx val, uintx min,
1987                                uintx max, const char* name) {
1988  // Returns true iff value is in the inclusive interval [min..max]
1989  // false, otherwise.
1990  if (val >= min && val <= max) {
1991    return true;
1992  }
1993  jio_fprintf(defaultStream::error_stream(),
1994              "%s of " UINTX_FORMAT " is invalid; must be between " UINTX_FORMAT
1995              " and " UINTX_FORMAT "\n",
1996              name, val, min, max);
1997  return false;
1998}
1999
2000bool Arguments::verify_min_value(intx val, intx min, const char* name) {
2001  // Returns true if given value is at least specified min threshold
2002  // false, otherwise.
2003  if (val >= min ) {
2004      return true;
2005  }
2006  jio_fprintf(defaultStream::error_stream(),
2007              "%s of " INTX_FORMAT " is invalid; must be at least " INTX_FORMAT "\n",
2008              name, val, min);
2009  return false;
2010}
2011
2012bool Arguments::verify_percentage(uintx value, const char* name) {
2013  if (is_percentage(value)) {
2014    return true;
2015  }
2016  jio_fprintf(defaultStream::error_stream(),
2017              "%s of " UINTX_FORMAT " is invalid; must be between 0 and 100\n",
2018              name, value);
2019  return false;
2020}
2021
2022// check if do gclog rotation
2023// +UseGCLogFileRotation is a must,
2024// no gc log rotation when log file not supplied or
2025// NumberOfGCLogFiles is 0
2026void check_gclog_consistency() {
2027  if (UseGCLogFileRotation) {
2028    if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {
2029      jio_fprintf(defaultStream::output_stream(),
2030                  "To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"
2031                  "where num_of_file > 0\n"
2032                  "GC log rotation is turned off\n");
2033      UseGCLogFileRotation = false;
2034    }
2035  }
2036
2037  if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {
2038    FLAG_SET_CMDLINE(uintx, GCLogFileSize, 8*K);
2039    jio_fprintf(defaultStream::output_stream(),
2040                "GCLogFileSize changed to minimum 8K\n");
2041  }
2042}
2043
2044// This function is called for -Xloggc:<filename>, it can be used
2045// to check if a given file name(or string) conforms to the following
2046// specification:
2047// A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"
2048// %p and %t only allowed once. We only limit usage of filename not path
2049bool is_filename_valid(const char *file_name) {
2050  const char* p = file_name;
2051  char file_sep = os::file_separator()[0];
2052  const char* cp;
2053  // skip prefix path
2054  for (cp = file_name; *cp != '\0'; cp++) {
2055    if (*cp == '/' || *cp == file_sep) {
2056      p = cp + 1;
2057    }
2058  }
2059
2060  int count_p = 0;
2061  int count_t = 0;
2062  while (*p != '\0') {
2063    if ((*p >= '0' && *p <= '9') ||
2064        (*p >= 'A' && *p <= 'Z') ||
2065        (*p >= 'a' && *p <= 'z') ||
2066         *p == '-'               ||
2067         *p == '_'               ||
2068         *p == '.') {
2069       p++;
2070       continue;
2071    }
2072    if (*p == '%') {
2073      if(*(p + 1) == 'p') {
2074        p += 2;
2075        count_p ++;
2076        continue;
2077      }
2078      if (*(p + 1) == 't') {
2079        p += 2;
2080        count_t ++;
2081        continue;
2082      }
2083    }
2084    return false;
2085  }
2086  return count_p < 2 && count_t < 2;
2087}
2088
2089bool Arguments::verify_MinHeapFreeRatio(FormatBuffer<80>& err_msg, uintx min_heap_free_ratio) {
2090  if (!is_percentage(min_heap_free_ratio)) {
2091    err_msg.print("MinHeapFreeRatio must have a value between 0 and 100");
2092    return false;
2093  }
2094  if (min_heap_free_ratio > MaxHeapFreeRatio) {
2095    err_msg.print("MinHeapFreeRatio (" UINTX_FORMAT ") must be less than or "
2096                  "equal to MaxHeapFreeRatio (" UINTX_FORMAT ")", min_heap_free_ratio,
2097                  MaxHeapFreeRatio);
2098    return false;
2099  }
2100  // This does not set the flag itself, but stores the value in a safe place for later usage.
2101  _min_heap_free_ratio = min_heap_free_ratio;
2102  return true;
2103}
2104
2105bool Arguments::verify_MaxHeapFreeRatio(FormatBuffer<80>& err_msg, uintx max_heap_free_ratio) {
2106  if (!is_percentage(max_heap_free_ratio)) {
2107    err_msg.print("MaxHeapFreeRatio must have a value between 0 and 100");
2108    return false;
2109  }
2110  if (max_heap_free_ratio < MinHeapFreeRatio) {
2111    err_msg.print("MaxHeapFreeRatio (" UINTX_FORMAT ") must be greater than or "
2112                  "equal to MinHeapFreeRatio (" UINTX_FORMAT ")", max_heap_free_ratio,
2113                  MinHeapFreeRatio);
2114    return false;
2115  }
2116  // This does not set the flag itself, but stores the value in a safe place for later usage.
2117  _max_heap_free_ratio = max_heap_free_ratio;
2118  return true;
2119}
2120
2121// Check consistency of GC selection
2122bool Arguments::check_gc_consistency_user() {
2123  check_gclog_consistency();
2124  // Ensure that the user has not selected conflicting sets
2125  // of collectors.
2126  uint i = 0;
2127  if (UseSerialGC)                       i++;
2128  if (UseConcMarkSweepGC)                i++;
2129  if (UseParallelGC || UseParallelOldGC) i++;
2130  if (UseG1GC)                           i++;
2131  if (i > 1) {
2132    jio_fprintf(defaultStream::error_stream(),
2133                "Conflicting collector combinations in option list; "
2134                "please refer to the release notes for the combinations "
2135                "allowed\n");
2136    return false;
2137  }
2138
2139  if (UseConcMarkSweepGC && !UseParNewGC) {
2140    jio_fprintf(defaultStream::error_stream(),
2141        "It is not possible to combine the DefNew young collector with the CMS collector.\n");
2142    return false;
2143  }
2144
2145  if (UseParNewGC && !UseConcMarkSweepGC) {
2146    // !UseConcMarkSweepGC means that we are using serial old gc. Unfortunately we don't
2147    // set up UseSerialGC properly, so that can't be used in the check here.
2148    jio_fprintf(defaultStream::error_stream(),
2149        "It is not possible to combine the ParNew young collector with the Serial old collector.\n");
2150    return false;
2151  }
2152
2153  return true;
2154}
2155
2156void Arguments::check_deprecated_gc_flags() {
2157  if (FLAG_IS_CMDLINE(UseParNewGC)) {
2158    warning("The UseParNewGC flag is deprecated and will likely be removed in a future release");
2159  }
2160  if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {
2161    warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
2162            "and will likely be removed in future release");
2163  }
2164  if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {
2165    warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "
2166        "Use MaxRAMFraction instead.");
2167  }
2168}
2169
2170// Check stack pages settings
2171bool Arguments::check_stack_pages()
2172{
2173  bool status = true;
2174  status = status && verify_min_value(StackYellowPages, 1, "StackYellowPages");
2175  status = status && verify_min_value(StackRedPages, 1, "StackRedPages");
2176  // greater stack shadow pages can't generate instruction to bang stack
2177  status = status && verify_interval(StackShadowPages, 1, 50, "StackShadowPages");
2178  return status;
2179}
2180
2181// Check the consistency of vm_init_args
2182bool Arguments::check_vm_args_consistency() {
2183  // Method for adding checks for flag consistency.
2184  // The intent is to warn the user of all possible conflicts,
2185  // before returning an error.
2186  // Note: Needs platform-dependent factoring.
2187  bool status = true;
2188
2189  if (TLABRefillWasteFraction == 0) {
2190    jio_fprintf(defaultStream::error_stream(),
2191                "TLABRefillWasteFraction should be a denominator, "
2192                "not " SIZE_FORMAT "\n",
2193                TLABRefillWasteFraction);
2194    status = false;
2195  }
2196
2197  status = status && verify_interval(AdaptiveSizePolicyWeight, 0, 100,
2198                              "AdaptiveSizePolicyWeight");
2199  status = status && verify_percentage(ThresholdTolerance, "ThresholdTolerance");
2200
2201  // Divide by bucket size to prevent a large size from causing rollover when
2202  // calculating amount of memory needed to be allocated for the String table.
2203  status = status && verify_interval(StringTableSize, minimumStringTableSize,
2204    (max_uintx / StringTable::bucket_size()), "StringTable size");
2205
2206  status = status && verify_interval(SymbolTableSize, minimumSymbolTableSize,
2207    (max_uintx / SymbolTable::bucket_size()), "SymbolTable size");
2208
2209  {
2210    // Using "else if" below to avoid printing two error messages if min > max.
2211    // This will also prevent us from reporting both min>100 and max>100 at the
2212    // same time, but that is less annoying than printing two identical errors IMHO.
2213    FormatBuffer<80> err_msg("%s","");
2214    if (!verify_MinHeapFreeRatio(err_msg, MinHeapFreeRatio)) {
2215      jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());
2216      status = false;
2217    } else if (!verify_MaxHeapFreeRatio(err_msg, MaxHeapFreeRatio)) {
2218      jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());
2219      status = false;
2220    }
2221  }
2222
2223  // Min/MaxMetaspaceFreeRatio
2224  status = status && verify_percentage(MinMetaspaceFreeRatio, "MinMetaspaceFreeRatio");
2225  status = status && verify_percentage(MaxMetaspaceFreeRatio, "MaxMetaspaceFreeRatio");
2226
2227  if (MinMetaspaceFreeRatio > MaxMetaspaceFreeRatio) {
2228    jio_fprintf(defaultStream::error_stream(),
2229                "MinMetaspaceFreeRatio (%s" UINTX_FORMAT ") must be less than or "
2230                "equal to MaxMetaspaceFreeRatio (%s" UINTX_FORMAT ")\n",
2231                FLAG_IS_DEFAULT(MinMetaspaceFreeRatio) ? "Default: " : "",
2232                MinMetaspaceFreeRatio,
2233                FLAG_IS_DEFAULT(MaxMetaspaceFreeRatio) ? "Default: " : "",
2234                MaxMetaspaceFreeRatio);
2235    status = false;
2236  }
2237
2238  // Trying to keep 100% free is not practical
2239  MinMetaspaceFreeRatio = MIN2(MinMetaspaceFreeRatio, (uintx) 99);
2240
2241  if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2242    MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
2243  }
2244
2245  if (UseParallelOldGC && ParallelOldGCSplitALot) {
2246    // Settings to encourage splitting.
2247    if (!FLAG_IS_CMDLINE(NewRatio)) {
2248      FLAG_SET_CMDLINE(uintx, NewRatio, 2);
2249    }
2250    if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
2251      FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
2252    }
2253  }
2254
2255  if (!(UseParallelGC || UseParallelOldGC) && FLAG_IS_DEFAULT(ScavengeBeforeFullGC)) {
2256    FLAG_SET_DEFAULT(ScavengeBeforeFullGC, false);
2257  }
2258
2259  status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit");
2260  status = status && verify_percentage(GCTimeLimit, "GCTimeLimit");
2261  if (GCTimeLimit == 100) {
2262    // Turn off gc-overhead-limit-exceeded checks
2263    FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2264  }
2265
2266  status = status && check_gc_consistency_user();
2267  status = status && check_stack_pages();
2268
2269  status = status && verify_percentage(CMSIncrementalSafetyFactor,
2270                                    "CMSIncrementalSafetyFactor");
2271
2272  // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2273  // insists that we hold the requisite locks so that the iteration is
2274  // MT-safe. For the verification at start-up and shut-down, we don't
2275  // yet have a good way of acquiring and releasing these locks,
2276  // which are not visible at the CollectedHeap level. We want to
2277  // be able to acquire these locks and then do the iteration rather
2278  // than just disable the lock verification. This will be fixed under
2279  // bug 4788986.
2280  if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2281    if (VerifyDuringStartup) {
2282      warning("Heap verification at start-up disabled "
2283              "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2284      VerifyDuringStartup = false; // Disable verification at start-up
2285    }
2286
2287    if (VerifyBeforeExit) {
2288      warning("Heap verification at shutdown disabled "
2289              "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2290      VerifyBeforeExit = false; // Disable verification at shutdown
2291    }
2292  }
2293
2294  // Note: only executed in non-PRODUCT mode
2295  if (!UseAsyncConcMarkSweepGC &&
2296      (ExplicitGCInvokesConcurrent ||
2297       ExplicitGCInvokesConcurrentAndUnloadsClasses)) {
2298    jio_fprintf(defaultStream::error_stream(),
2299                "error: +ExplicitGCInvokesConcurrent[AndUnloadsClasses] conflicts"
2300                " with -UseAsyncConcMarkSweepGC");
2301    status = false;
2302  }
2303
2304  status = status && verify_min_value(ParGCArrayScanChunk, 1, "ParGCArrayScanChunk");
2305
2306#if INCLUDE_ALL_GCS
2307  if (UseG1GC) {
2308    status = status && verify_percentage(G1NewSizePercent, "G1NewSizePercent");
2309    status = status && verify_percentage(G1MaxNewSizePercent, "G1MaxNewSizePercent");
2310    status = status && verify_interval(G1NewSizePercent, 0, G1MaxNewSizePercent, "G1NewSizePercent");
2311
2312    status = status && verify_percentage(G1ConfidencePercent, "G1ConfidencePercent");
2313    status = status && verify_percentage(InitiatingHeapOccupancyPercent,
2314                                         "InitiatingHeapOccupancyPercent");
2315    status = status && verify_min_value(G1RefProcDrainInterval, 1,
2316                                        "G1RefProcDrainInterval");
2317    status = status && verify_min_value((intx)G1ConcMarkStepDurationMillis, 1,
2318                                        "G1ConcMarkStepDurationMillis");
2319    status = status && verify_interval(G1ConcRSHotCardLimit, 0, max_jubyte,
2320                                       "G1ConcRSHotCardLimit");
2321    status = status && verify_interval(G1ConcRSLogCacheSize, 0, 31,
2322                                       "G1ConcRSLogCacheSize");
2323    status = status && verify_interval(StringDeduplicationAgeThreshold, 1, markOopDesc::max_age,
2324                                       "StringDeduplicationAgeThreshold");
2325  }
2326  if (UseConcMarkSweepGC) {
2327    status = status && verify_min_value(CMSOldPLABNumRefills, 1, "CMSOldPLABNumRefills");
2328    status = status && verify_min_value(CMSOldPLABToleranceFactor, 1, "CMSOldPLABToleranceFactor");
2329    status = status && verify_min_value(CMSOldPLABMax, 1, "CMSOldPLABMax");
2330    status = status && verify_interval(CMSOldPLABMin, 1, CMSOldPLABMax, "CMSOldPLABMin");
2331
2332    status = status && verify_min_value(CMSYoungGenPerWorker, 1, "CMSYoungGenPerWorker");
2333
2334    status = status && verify_min_value(CMSSamplingGrain, 1, "CMSSamplingGrain");
2335    status = status && verify_interval(CMS_SweepWeight, 0, 100, "CMS_SweepWeight");
2336    status = status && verify_interval(CMS_FLSWeight, 0, 100, "CMS_FLSWeight");
2337
2338    status = status && verify_interval(FLSCoalescePolicy, 0, 4, "FLSCoalescePolicy");
2339
2340    status = status && verify_min_value(CMSRescanMultiple, 1, "CMSRescanMultiple");
2341    status = status && verify_min_value(CMSConcMarkMultiple, 1, "CMSConcMarkMultiple");
2342
2343    status = status && verify_interval(CMSPrecleanIter, 0, 9, "CMSPrecleanIter");
2344    status = status && verify_min_value(CMSPrecleanDenominator, 1, "CMSPrecleanDenominator");
2345    status = status && verify_interval(CMSPrecleanNumerator, 0, CMSPrecleanDenominator - 1, "CMSPrecleanNumerator");
2346
2347    status = status && verify_percentage(CMSBootstrapOccupancy, "CMSBootstrapOccupancy");
2348
2349    status = status && verify_min_value(CMSPrecleanThreshold, 100, "CMSPrecleanThreshold");
2350
2351    status = status && verify_percentage(CMSScheduleRemarkEdenPenetration, "CMSScheduleRemarkEdenPenetration");
2352    status = status && verify_min_value(CMSScheduleRemarkSamplingRatio, 1, "CMSScheduleRemarkSamplingRatio");
2353    status = status && verify_min_value(CMSBitMapYieldQuantum, 1, "CMSBitMapYieldQuantum");
2354    status = status && verify_percentage(CMSTriggerRatio, "CMSTriggerRatio");
2355    status = status && verify_percentage(CMSIsTooFullPercentage, "CMSIsTooFullPercentage");
2356  }
2357
2358  if (UseParallelGC || UseParallelOldGC) {
2359    status = status && verify_interval(ParallelOldDeadWoodLimiterMean, 0, 100, "ParallelOldDeadWoodLimiterMean");
2360    status = status && verify_interval(ParallelOldDeadWoodLimiterStdDev, 0, 100, "ParallelOldDeadWoodLimiterStdDev");
2361
2362    status = status && verify_percentage(YoungGenerationSizeIncrement, "YoungGenerationSizeIncrement");
2363    status = status && verify_percentage(TenuredGenerationSizeIncrement, "TenuredGenerationSizeIncrement");
2364
2365    status = status && verify_min_value(YoungGenerationSizeSupplementDecay, 1, "YoungGenerationSizeSupplementDecay");
2366    status = status && verify_min_value(TenuredGenerationSizeSupplementDecay, 1, "TenuredGenerationSizeSupplementDecay");
2367
2368    status = status && verify_min_value(ParGCCardsPerStrideChunk, 1, "ParGCCardsPerStrideChunk");
2369
2370    status = status && verify_min_value(ParallelOldGCSplitInterval, 0, "ParallelOldGCSplitInterval");
2371  }
2372#endif // INCLUDE_ALL_GCS
2373
2374  status = status && verify_interval(RefDiscoveryPolicy,
2375                                     ReferenceProcessor::DiscoveryPolicyMin,
2376                                     ReferenceProcessor::DiscoveryPolicyMax,
2377                                     "RefDiscoveryPolicy");
2378
2379  // Limit the lower bound of this flag to 1 as it is used in a division
2380  // expression.
2381  status = status && verify_interval(TLABWasteTargetPercent,
2382                                     1, 100, "TLABWasteTargetPercent");
2383
2384  status = status && verify_object_alignment();
2385
2386  status = status && verify_interval(CompressedClassSpaceSize, 1*M, 3*G,
2387                                      "CompressedClassSpaceSize");
2388
2389  status = status && verify_interval(MarkStackSizeMax,
2390                                  1, (max_jint - 1), "MarkStackSizeMax");
2391  status = status && verify_interval(NUMAChunkResizeWeight, 0, 100, "NUMAChunkResizeWeight");
2392
2393  status = status && verify_min_value(LogEventsBufferEntries, 1, "LogEventsBufferEntries");
2394
2395  status = status && verify_min_value(HeapSizePerGCThread, (uintx) os::vm_page_size(), "HeapSizePerGCThread");
2396
2397  status = status && verify_min_value(GCTaskTimeStampEntries, 1, "GCTaskTimeStampEntries");
2398
2399  status = status && verify_percentage(ParallelGCBufferWastePct, "ParallelGCBufferWastePct");
2400  status = status && verify_interval(TargetPLABWastePct, 1, 100, "TargetPLABWastePct");
2401
2402  status = status && verify_min_value(ParGCStridesPerThread, 1, "ParGCStridesPerThread");
2403
2404  status = status && verify_min_value(MinRAMFraction, 1, "MinRAMFraction");
2405  status = status && verify_min_value(InitialRAMFraction, 1, "InitialRAMFraction");
2406  status = status && verify_min_value(MaxRAMFraction, 1, "MaxRAMFraction");
2407  status = status && verify_min_value(DefaultMaxRAMFraction, 1, "DefaultMaxRAMFraction");
2408
2409  status = status && verify_interval(AdaptiveTimeWeight, 0, 100, "AdaptiveTimeWeight");
2410  status = status && verify_min_value(AdaptiveSizeDecrementScaleFactor, 1, "AdaptiveSizeDecrementScaleFactor");
2411
2412  status = status && verify_interval(TLABAllocationWeight, 0, 100, "TLABAllocationWeight");
2413  status = status && verify_min_value(MinTLABSize, 1, "MinTLABSize");
2414  status = status && verify_min_value(TLABRefillWasteFraction, 1, "TLABRefillWasteFraction");
2415
2416  status = status && verify_percentage(YoungGenerationSizeSupplement, "YoungGenerationSizeSupplement");
2417  status = status && verify_percentage(TenuredGenerationSizeSupplement, "TenuredGenerationSizeSupplement");
2418
2419  status = status && verify_interval(MaxTenuringThreshold, 0, markOopDesc::max_age + 1, "MaxTenuringThreshold");
2420  status = status && verify_interval(InitialTenuringThreshold, 0, MaxTenuringThreshold, "InitialTenuringThreshold");
2421  status = status && verify_percentage(TargetSurvivorRatio, "TargetSurvivorRatio");
2422  status = status && verify_percentage(MarkSweepDeadRatio, "MarkSweepDeadRatio");
2423
2424  status = status && verify_min_value(MarkSweepAlwaysCompactCount, 1, "MarkSweepAlwaysCompactCount");
2425#ifdef COMPILER1
2426  status = status && verify_min_value(ValueMapInitialSize, 1, "ValueMapInitialSize");
2427#endif
2428  status = status && verify_min_value(HeapSearchSteps, 1, "HeapSearchSteps");
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  // Need to limit the extent of the padding to reasonable size.
2442  // 8K is well beyond the reasonable HW cache line size, even with the
2443  // aggressive prefetching, while still leaving the room for segregating
2444  // among the distinct pages.
2445  if (ContendedPaddingWidth < 0 || ContendedPaddingWidth > 8192) {
2446    jio_fprintf(defaultStream::error_stream(),
2447                "ContendedPaddingWidth=" INTX_FORMAT " must be in between %d and %d\n",
2448                ContendedPaddingWidth, 0, 8192);
2449    status = false;
2450  }
2451
2452  // Need to enforce the padding not to break the existing field alignments.
2453  // It is sufficient to check against the largest type size.
2454  if ((ContendedPaddingWidth % BytesPerLong) != 0) {
2455    jio_fprintf(defaultStream::error_stream(),
2456                "ContendedPaddingWidth=" INTX_FORMAT " must be a multiple of %d\n",
2457                ContendedPaddingWidth, BytesPerLong);
2458    status = false;
2459  }
2460
2461  // Check lower bounds of the code cache
2462  // Template Interpreter code is approximately 3X larger in debug builds.
2463  uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2464  if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2465    jio_fprintf(defaultStream::error_stream(),
2466                "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
2467                os::vm_page_size()/K);
2468    status = false;
2469  } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2470    jio_fprintf(defaultStream::error_stream(),
2471                "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2472                ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2473    status = false;
2474  } else if (ReservedCodeCacheSize < min_code_cache_size) {
2475    jio_fprintf(defaultStream::error_stream(),
2476                "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2477                min_code_cache_size/K);
2478    status = false;
2479  } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2480    // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2481    jio_fprintf(defaultStream::error_stream(),
2482                "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2483                CODE_CACHE_SIZE_LIMIT/M);
2484    status = false;
2485  } else if (NonNMethodCodeHeapSize < min_code_cache_size){
2486    jio_fprintf(defaultStream::error_stream(),
2487                "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2488                min_code_cache_size/K);
2489    status = false;
2490  } else if ((!FLAG_IS_DEFAULT(NonNMethodCodeHeapSize) || !FLAG_IS_DEFAULT(ProfiledCodeHeapSize) || !FLAG_IS_DEFAULT(NonProfiledCodeHeapSize))
2491             && (NonNMethodCodeHeapSize + NonProfiledCodeHeapSize + ProfiledCodeHeapSize) != ReservedCodeCacheSize) {
2492    jio_fprintf(defaultStream::error_stream(),
2493                "Invalid code heap sizes: NonNMethodCodeHeapSize(%dK) + ProfiledCodeHeapSize(%dK) + NonProfiledCodeHeapSize(%dK) = %dK. Must be equal to ReservedCodeCacheSize = %uK.\n",
2494                NonNMethodCodeHeapSize/K, ProfiledCodeHeapSize/K, NonProfiledCodeHeapSize/K,
2495                (NonNMethodCodeHeapSize + ProfiledCodeHeapSize + NonProfiledCodeHeapSize)/K, ReservedCodeCacheSize/K);
2496    status = false;
2497  }
2498
2499  status &= verify_interval(NmethodSweepActivity, 0, 2000, "NmethodSweepActivity");
2500  status &= verify_interval(CodeCacheMinBlockLength, 1, 100, "CodeCacheMinBlockLength");
2501  status &= verify_interval(CodeCacheSegmentSize, 1, 1024, "CodeCacheSegmentSize");
2502  status &= verify_interval(StartAggressiveSweepingAt, 0, 100, "StartAggressiveSweepingAt");
2503
2504
2505  int min_number_of_compiler_threads = get_min_number_of_compiler_threads();
2506  // The default CICompilerCount's value is CI_COMPILER_COUNT.
2507  assert(min_number_of_compiler_threads <= CI_COMPILER_COUNT, "minimum should be less or equal default number");
2508  // Check the minimum number of compiler threads
2509  status &=verify_min_value(CICompilerCount, min_number_of_compiler_threads, "CICompilerCount");
2510
2511  if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2512    warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2513  }
2514
2515  return status;
2516}
2517
2518bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2519  const char* option_type) {
2520  if (ignore) return false;
2521
2522  const char* spacer = " ";
2523  if (option_type == NULL) {
2524    option_type = ++spacer; // Set both to the empty string.
2525  }
2526
2527  if (os::obsolete_option(option)) {
2528    jio_fprintf(defaultStream::error_stream(),
2529                "Obsolete %s%soption: %s\n", option_type, spacer,
2530      option->optionString);
2531    return false;
2532  } else {
2533    jio_fprintf(defaultStream::error_stream(),
2534                "Unrecognized %s%soption: %s\n", option_type, spacer,
2535      option->optionString);
2536    return true;
2537  }
2538}
2539
2540static const char* user_assertion_options[] = {
2541  "-da", "-ea", "-disableassertions", "-enableassertions", 0
2542};
2543
2544static const char* system_assertion_options[] = {
2545  "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2546};
2547
2548bool Arguments::parse_uintx(const char* value,
2549                            uintx* uintx_arg,
2550                            uintx min_size) {
2551
2552  // Check the sign first since atomull() parses only unsigned values.
2553  bool value_is_positive = !(*value == '-');
2554
2555  if (value_is_positive) {
2556    julong n;
2557    bool good_return = atomull(value, &n);
2558    if (good_return) {
2559      bool above_minimum = n >= min_size;
2560      bool value_is_too_large = n > max_uintx;
2561
2562      if (above_minimum && !value_is_too_large) {
2563        *uintx_arg = n;
2564        return true;
2565      }
2566    }
2567  }
2568  return false;
2569}
2570
2571Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2572                                                  julong* long_arg,
2573                                                  julong min_size) {
2574  if (!atomull(s, long_arg)) return arg_unreadable;
2575  return check_memory_size(*long_arg, min_size);
2576}
2577
2578// Parse JavaVMInitArgs structure
2579
2580jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {
2581  // For components of the system classpath.
2582  SysClassPath scp(Arguments::get_sysclasspath());
2583  bool scp_assembly_required = false;
2584
2585  // Save default settings for some mode flags
2586  Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2587  Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2588  Arguments::_ClipInlining             = ClipInlining;
2589  Arguments::_BackgroundCompilation    = BackgroundCompilation;
2590
2591  // Setup flags for mixed which is the default
2592  set_mode_flags(_mixed);
2593
2594  // Parse JAVA_TOOL_OPTIONS environment variable (if present)
2595  jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);
2596  if (result != JNI_OK) {
2597    return result;
2598  }
2599
2600  // Parse JavaVMInitArgs structure passed in
2601  result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, Flag::COMMAND_LINE);
2602  if (result != JNI_OK) {
2603    return result;
2604  }
2605
2606  // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
2607  result = parse_java_options_environment_variable(&scp, &scp_assembly_required);
2608  if (result != JNI_OK) {
2609    return result;
2610  }
2611
2612  // Do final processing now that all arguments have been parsed
2613  result = finalize_vm_init_args(&scp, scp_assembly_required);
2614  if (result != JNI_OK) {
2615    return result;
2616  }
2617
2618  return JNI_OK;
2619}
2620
2621// Checks if name in command-line argument -agent{lib,path}:name[=options]
2622// represents a valid HPROF of JDWP agent.  is_path==true denotes that we
2623// are dealing with -agentpath (case where name is a path), otherwise with
2624// -agentlib
2625bool valid_hprof_or_jdwp_agent(char *name, bool is_path) {
2626  char *_name;
2627  const char *_hprof = "hprof", *_jdwp = "jdwp";
2628  size_t _len_hprof, _len_jdwp, _len_prefix;
2629
2630  if (is_path) {
2631    if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2632      return false;
2633    }
2634
2635    _name++;  // skip past last path separator
2636    _len_prefix = strlen(JNI_LIB_PREFIX);
2637
2638    if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2639      return false;
2640    }
2641
2642    _name += _len_prefix;
2643    _len_hprof = strlen(_hprof);
2644    _len_jdwp = strlen(_jdwp);
2645
2646    if (strncmp(_name, _hprof, _len_hprof) == 0) {
2647      _name += _len_hprof;
2648    }
2649    else if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2650      _name += _len_jdwp;
2651    }
2652    else {
2653      return false;
2654    }
2655
2656    if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2657      return false;
2658    }
2659
2660    return true;
2661  }
2662
2663  if (strcmp(name, _hprof) == 0 || strcmp(name, _jdwp) == 0) {
2664    return true;
2665  }
2666
2667  return false;
2668}
2669
2670jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2671                                       SysClassPath* scp_p,
2672                                       bool* scp_assembly_required_p,
2673                                       Flag::Flags origin) {
2674  // Remaining part of option string
2675  const char* tail;
2676
2677  // iterate over arguments
2678  for (int index = 0; index < args->nOptions; index++) {
2679    bool is_absolute_path = false;  // for -agentpath vs -agentlib
2680
2681    const JavaVMOption* option = args->options + index;
2682
2683    if (!match_option(option, "-Djava.class.path", &tail) &&
2684        !match_option(option, "-Dsun.java.command", &tail) &&
2685        !match_option(option, "-Dsun.java.launcher", &tail)) {
2686
2687        // add all jvm options to the jvm_args string. This string
2688        // is used later to set the java.vm.args PerfData string constant.
2689        // the -Djava.class.path and the -Dsun.java.command options are
2690        // omitted from jvm_args string as each have their own PerfData
2691        // string constant object.
2692        build_jvm_args(option->optionString);
2693    }
2694
2695    // -verbose:[class/gc/jni]
2696    if (match_option(option, "-verbose", &tail)) {
2697      if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2698        FLAG_SET_CMDLINE(bool, TraceClassLoading, true);
2699        FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);
2700      } else if (!strcmp(tail, ":gc")) {
2701        FLAG_SET_CMDLINE(bool, PrintGC, true);
2702      } else if (!strcmp(tail, ":jni")) {
2703        FLAG_SET_CMDLINE(bool, PrintJNIResolving, true);
2704      }
2705    // -da / -ea / -disableassertions / -enableassertions
2706    // These accept an optional class/package name separated by a colon, e.g.,
2707    // -da:java.lang.Thread.
2708    } else if (match_option(option, user_assertion_options, &tail, true)) {
2709      bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2710      if (*tail == '\0') {
2711        JavaAssertions::setUserClassDefault(enable);
2712      } else {
2713        assert(*tail == ':', "bogus match by match_option()");
2714        JavaAssertions::addOption(tail + 1, enable);
2715      }
2716    // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2717    } else if (match_option(option, system_assertion_options, &tail, false)) {
2718      bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2719      JavaAssertions::setSystemClassDefault(enable);
2720    // -bootclasspath:
2721    } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2722      scp_p->reset_path(tail);
2723      *scp_assembly_required_p = true;
2724    // -bootclasspath/a:
2725    } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2726      scp_p->add_suffix(tail);
2727      *scp_assembly_required_p = true;
2728    // -bootclasspath/p:
2729    } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2730      scp_p->add_prefix(tail);
2731      *scp_assembly_required_p = true;
2732    // -Xrun
2733    } else if (match_option(option, "-Xrun", &tail)) {
2734      if (tail != NULL) {
2735        const char* pos = strchr(tail, ':');
2736        size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2737        char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2738        name[len] = '\0';
2739
2740        char *options = NULL;
2741        if(pos != NULL) {
2742          size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2743          options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
2744        }
2745#if !INCLUDE_JVMTI
2746        if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
2747          jio_fprintf(defaultStream::error_stream(),
2748            "Profiling and debugging agents are not supported in this VM\n");
2749          return JNI_ERR;
2750        }
2751#endif // !INCLUDE_JVMTI
2752        add_init_library(name, options);
2753      }
2754    // -agentlib and -agentpath
2755    } else if (match_option(option, "-agentlib:", &tail) ||
2756          (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2757      if(tail != NULL) {
2758        const char* pos = strchr(tail, '=');
2759        size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2760        char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2761        name[len] = '\0';
2762
2763        char *options = NULL;
2764        if(pos != NULL) {
2765          options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(pos + 1) + 1, mtInternal), pos + 1);
2766        }
2767#if !INCLUDE_JVMTI
2768        if (valid_hprof_or_jdwp_agent(name, is_absolute_path)) {
2769          jio_fprintf(defaultStream::error_stream(),
2770            "Profiling and debugging agents are not supported in this VM\n");
2771          return JNI_ERR;
2772        }
2773#endif // !INCLUDE_JVMTI
2774        add_init_agent(name, options, is_absolute_path);
2775      }
2776    // -javaagent
2777    } else if (match_option(option, "-javaagent:", &tail)) {
2778#if !INCLUDE_JVMTI
2779      jio_fprintf(defaultStream::error_stream(),
2780        "Instrumentation agents are not supported in this VM\n");
2781      return JNI_ERR;
2782#else
2783      if(tail != NULL) {
2784        char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtInternal), tail);
2785        add_init_agent("instrument", options, false);
2786      }
2787#endif // !INCLUDE_JVMTI
2788    // -Xnoclassgc
2789    } else if (match_option(option, "-Xnoclassgc")) {
2790      FLAG_SET_CMDLINE(bool, ClassUnloading, false);
2791    // -Xconcgc
2792    } else if (match_option(option, "-Xconcgc")) {
2793      FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
2794    // -Xnoconcgc
2795    } else if (match_option(option, "-Xnoconcgc")) {
2796      FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
2797    // -Xbatch
2798    } else if (match_option(option, "-Xbatch")) {
2799      FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2800    // -Xmn for compatibility with other JVM vendors
2801    } else if (match_option(option, "-Xmn", &tail)) {
2802      julong long_initial_young_size = 0;
2803      ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2804      if (errcode != arg_in_range) {
2805        jio_fprintf(defaultStream::error_stream(),
2806                    "Invalid initial young generation size: %s\n", option->optionString);
2807        describe_range_error(errcode);
2808        return JNI_EINVAL;
2809      }
2810      FLAG_SET_CMDLINE(uintx, MaxNewSize, (uintx)long_initial_young_size);
2811      FLAG_SET_CMDLINE(uintx, NewSize, (uintx)long_initial_young_size);
2812    // -Xms
2813    } else if (match_option(option, "-Xms", &tail)) {
2814      julong long_initial_heap_size = 0;
2815      // an initial heap size of 0 means automatically determine
2816      ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2817      if (errcode != arg_in_range) {
2818        jio_fprintf(defaultStream::error_stream(),
2819                    "Invalid initial heap size: %s\n", option->optionString);
2820        describe_range_error(errcode);
2821        return JNI_EINVAL;
2822      }
2823      set_min_heap_size((uintx)long_initial_heap_size);
2824      // Currently the minimum size and the initial heap sizes are the same.
2825      // Can be overridden with -XX:InitialHeapSize.
2826      FLAG_SET_CMDLINE(uintx, InitialHeapSize, (uintx)long_initial_heap_size);
2827    // -Xmx
2828    } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2829      julong long_max_heap_size = 0;
2830      ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2831      if (errcode != arg_in_range) {
2832        jio_fprintf(defaultStream::error_stream(),
2833                    "Invalid maximum heap size: %s\n", option->optionString);
2834        describe_range_error(errcode);
2835        return JNI_EINVAL;
2836      }
2837      FLAG_SET_CMDLINE(uintx, MaxHeapSize, (uintx)long_max_heap_size);
2838    // Xmaxf
2839    } else if (match_option(option, "-Xmaxf", &tail)) {
2840      char* err;
2841      int maxf = (int)(strtod(tail, &err) * 100);
2842      if (*err != '\0' || *tail == '\0' || maxf < 0 || maxf > 100) {
2843        jio_fprintf(defaultStream::error_stream(),
2844                    "Bad max heap free percentage size: %s\n",
2845                    option->optionString);
2846        return JNI_EINVAL;
2847      } else {
2848        FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf);
2849      }
2850    // Xminf
2851    } else if (match_option(option, "-Xminf", &tail)) {
2852      char* err;
2853      int minf = (int)(strtod(tail, &err) * 100);
2854      if (*err != '\0' || *tail == '\0' || minf < 0 || minf > 100) {
2855        jio_fprintf(defaultStream::error_stream(),
2856                    "Bad min heap free percentage size: %s\n",
2857                    option->optionString);
2858        return JNI_EINVAL;
2859      } else {
2860        FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf);
2861      }
2862    // -Xss
2863    } else if (match_option(option, "-Xss", &tail)) {
2864      julong long_ThreadStackSize = 0;
2865      ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2866      if (errcode != arg_in_range) {
2867        jio_fprintf(defaultStream::error_stream(),
2868                    "Invalid thread stack size: %s\n", option->optionString);
2869        describe_range_error(errcode);
2870        return JNI_EINVAL;
2871      }
2872      // Internally track ThreadStackSize in units of 1024 bytes.
2873      FLAG_SET_CMDLINE(intx, ThreadStackSize,
2874                              round_to((int)long_ThreadStackSize, K) / K);
2875    // -Xoss
2876    } else if (match_option(option, "-Xoss", &tail)) {
2877          // HotSpot does not have separate native and Java stacks, ignore silently for compatibility
2878    } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
2879      julong long_CodeCacheExpansionSize = 0;
2880      ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
2881      if (errcode != arg_in_range) {
2882        jio_fprintf(defaultStream::error_stream(),
2883                   "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
2884                   os::vm_page_size()/K);
2885        return JNI_EINVAL;
2886      }
2887      FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize);
2888    } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2889               match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2890      julong long_ReservedCodeCacheSize = 0;
2891
2892      ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2893      if (errcode != arg_in_range) {
2894        jio_fprintf(defaultStream::error_stream(),
2895                    "Invalid maximum code cache size: %s.\n", option->optionString);
2896        return JNI_EINVAL;
2897      }
2898      FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize);
2899      // -XX:NonNMethodCodeHeapSize=
2900    } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
2901      julong long_NonNMethodCodeHeapSize = 0;
2902
2903      ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
2904      if (errcode != arg_in_range) {
2905        jio_fprintf(defaultStream::error_stream(),
2906                    "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
2907        return JNI_EINVAL;
2908      }
2909      FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize);
2910      // -XX:ProfiledCodeHeapSize=
2911    } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
2912      julong long_ProfiledCodeHeapSize = 0;
2913
2914      ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
2915      if (errcode != arg_in_range) {
2916        jio_fprintf(defaultStream::error_stream(),
2917                    "Invalid maximum profiled code heap size: %s.\n", option->optionString);
2918        return JNI_EINVAL;
2919      }
2920      FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize);
2921      // -XX:NonProfiledCodeHeapSizee=
2922    } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
2923      julong long_NonProfiledCodeHeapSize = 0;
2924
2925      ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
2926      if (errcode != arg_in_range) {
2927        jio_fprintf(defaultStream::error_stream(),
2928                    "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
2929        return JNI_EINVAL;
2930      }
2931      FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize);
2932      //-XX:IncreaseFirstTierCompileThresholdAt=
2933    } else if (match_option(option, "-XX:IncreaseFirstTierCompileThresholdAt=", &tail)) {
2934        uintx uint_IncreaseFirstTierCompileThresholdAt = 0;
2935        if (!parse_uintx(tail, &uint_IncreaseFirstTierCompileThresholdAt, 0) || uint_IncreaseFirstTierCompileThresholdAt > 99) {
2936          jio_fprintf(defaultStream::error_stream(),
2937                      "Invalid value for IncreaseFirstTierCompileThresholdAt: %s. Should be between 0 and 99.\n",
2938                      option->optionString);
2939          return JNI_EINVAL;
2940        }
2941        FLAG_SET_CMDLINE(uintx, IncreaseFirstTierCompileThresholdAt, (uintx)uint_IncreaseFirstTierCompileThresholdAt);
2942    // -green
2943    } else if (match_option(option, "-green")) {
2944      jio_fprintf(defaultStream::error_stream(),
2945                  "Green threads support not available\n");
2946          return JNI_EINVAL;
2947    // -native
2948    } else if (match_option(option, "-native")) {
2949          // HotSpot always uses native threads, ignore silently for compatibility
2950    // -Xsqnopause
2951    } else if (match_option(option, "-Xsqnopause")) {
2952          // EVM option, ignore silently for compatibility
2953    // -Xrs
2954    } else if (match_option(option, "-Xrs")) {
2955          // Classic/EVM option, new functionality
2956      FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true);
2957    } else if (match_option(option, "-Xusealtsigs")) {
2958          // change default internal VM signals used - lower case for back compat
2959      FLAG_SET_CMDLINE(bool, UseAltSigs, true);
2960    // -Xoptimize
2961    } else if (match_option(option, "-Xoptimize")) {
2962          // EVM option, ignore silently for compatibility
2963    // -Xprof
2964    } else if (match_option(option, "-Xprof")) {
2965#if INCLUDE_FPROF
2966      _has_profile = true;
2967#else // INCLUDE_FPROF
2968      jio_fprintf(defaultStream::error_stream(),
2969        "Flat profiling is not supported in this VM.\n");
2970      return JNI_ERR;
2971#endif // INCLUDE_FPROF
2972    // -Xconcurrentio
2973    } else if (match_option(option, "-Xconcurrentio")) {
2974      FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true);
2975      FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2976      FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1);
2977      FLAG_SET_CMDLINE(bool, UseTLAB, false);
2978      FLAG_SET_CMDLINE(uintx, NewSizeThreadIncrease, 16 * K);  // 20Kb per thread added to new generation
2979
2980      // -Xinternalversion
2981    } else if (match_option(option, "-Xinternalversion")) {
2982      jio_fprintf(defaultStream::output_stream(), "%s\n",
2983                  VM_Version::internal_vm_info_string());
2984      vm_exit(0);
2985#ifndef PRODUCT
2986    // -Xprintflags
2987    } else if (match_option(option, "-Xprintflags")) {
2988      CommandLineFlags::printFlags(tty, false);
2989      vm_exit(0);
2990#endif
2991    // -D
2992    } else if (match_option(option, "-D", &tail)) {
2993      const char* value;
2994      if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2995            *value!= '\0' && strcmp(value, "\"\"") != 0) {
2996        // abort if -Djava.endorsed.dirs is set
2997        jio_fprintf(defaultStream::output_stream(),
2998          "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2999          "in modular form will be supported via the concept of upgradeable modules.\n", value);
3000        return JNI_EINVAL;
3001      }
3002      if (match_option(option, "-Djava.ext.dirs=", &value) &&
3003            *value != '\0' && strcmp(value, "\"\"") != 0) {
3004        // abort if -Djava.ext.dirs is set
3005        jio_fprintf(defaultStream::output_stream(),
3006          "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
3007        return JNI_EINVAL;
3008      }
3009
3010      if (!add_property(tail)) {
3011        return JNI_ENOMEM;
3012      }
3013      // Out of the box management support
3014      if (match_option(option, "-Dcom.sun.management", &tail)) {
3015#if INCLUDE_MANAGEMENT
3016        FLAG_SET_CMDLINE(bool, ManagementServer, true);
3017#else
3018        jio_fprintf(defaultStream::output_stream(),
3019          "-Dcom.sun.management is not supported in this VM.\n");
3020        return JNI_ERR;
3021#endif
3022      }
3023    // -Xint
3024    } else if (match_option(option, "-Xint")) {
3025          set_mode_flags(_int);
3026    // -Xmixed
3027    } else if (match_option(option, "-Xmixed")) {
3028          set_mode_flags(_mixed);
3029    // -Xcomp
3030    } else if (match_option(option, "-Xcomp")) {
3031      // for testing the compiler; turn off all flags that inhibit compilation
3032          set_mode_flags(_comp);
3033    // -Xshare:dump
3034    } else if (match_option(option, "-Xshare:dump")) {
3035      FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);
3036      set_mode_flags(_int);     // Prevent compilation, which creates objects
3037    // -Xshare:on
3038    } else if (match_option(option, "-Xshare:on")) {
3039      FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
3040      FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
3041    // -Xshare:auto
3042    } else if (match_option(option, "-Xshare:auto")) {
3043      FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
3044      FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
3045    // -Xshare:off
3046    } else if (match_option(option, "-Xshare:off")) {
3047      FLAG_SET_CMDLINE(bool, UseSharedSpaces, false);
3048      FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
3049    // -Xverify
3050    } else if (match_option(option, "-Xverify", &tail)) {
3051      if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
3052        FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true);
3053        FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
3054      } else if (strcmp(tail, ":remote") == 0) {
3055        FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
3056        FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
3057      } else if (strcmp(tail, ":none") == 0) {
3058        FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
3059        FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false);
3060      } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3061        return JNI_EINVAL;
3062      }
3063    // -Xdebug
3064    } else if (match_option(option, "-Xdebug")) {
3065      // note this flag has been used, then ignore
3066      set_xdebug_mode(true);
3067    // -Xnoagent
3068    } else if (match_option(option, "-Xnoagent")) {
3069      // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3070    } else if (match_option(option, "-Xboundthreads")) {
3071      // Bind user level threads to kernel threads (Solaris only)
3072      FLAG_SET_CMDLINE(bool, UseBoundThreads, true);
3073    } else if (match_option(option, "-Xloggc:", &tail)) {
3074      // Redirect GC output to the file. -Xloggc:<filename>
3075      // ostream_init_log(), when called will use this filename
3076      // to initialize a fileStream.
3077      _gc_log_filename = os::strdup_check_oom(tail);
3078     if (!is_filename_valid(_gc_log_filename)) {
3079       jio_fprintf(defaultStream::output_stream(),
3080                  "Invalid file name for use with -Xloggc: Filename can only contain the "
3081                  "characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"
3082                  "Note %%p or %%t can only be used once\n", _gc_log_filename);
3083        return JNI_EINVAL;
3084      }
3085      FLAG_SET_CMDLINE(bool, PrintGC, true);
3086      FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true);
3087
3088    // JNI hooks
3089    } else if (match_option(option, "-Xcheck", &tail)) {
3090      if (!strcmp(tail, ":jni")) {
3091#if !INCLUDE_JNI_CHECK
3092        warning("JNI CHECKING is not supported in this VM");
3093#else
3094        CheckJNICalls = true;
3095#endif // INCLUDE_JNI_CHECK
3096      } else if (is_bad_option(option, args->ignoreUnrecognized,
3097                                     "check")) {
3098        return JNI_EINVAL;
3099      }
3100    } else if (match_option(option, "vfprintf")) {
3101      _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3102    } else if (match_option(option, "exit")) {
3103      _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3104    } else if (match_option(option, "abort")) {
3105      _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3106    // -XX:+AggressiveHeap
3107    } else if (match_option(option, "-XX:+AggressiveHeap")) {
3108
3109      // This option inspects the machine and attempts to set various
3110      // parameters to be optimal for long-running, memory allocation
3111      // intensive jobs.  It is intended for machines with large
3112      // amounts of cpu and memory.
3113
3114      // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
3115      // VM, but we may not be able to represent the total physical memory
3116      // available (like having 8gb of memory on a box but using a 32bit VM).
3117      // Thus, we need to make sure we're using a julong for intermediate
3118      // calculations.
3119      julong initHeapSize;
3120      julong total_memory = os::physical_memory();
3121
3122      if (total_memory < (julong)256*M) {
3123        jio_fprintf(defaultStream::error_stream(),
3124                    "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
3125        vm_exit(1);
3126      }
3127
3128      // The heap size is half of available memory, or (at most)
3129      // all of possible memory less 160mb (leaving room for the OS
3130      // when using ISM).  This is the maximum; because adaptive sizing
3131      // is turned on below, the actual space used may be smaller.
3132
3133      initHeapSize = MIN2(total_memory / (julong)2,
3134                          total_memory - (julong)160*M);
3135
3136      initHeapSize = limit_by_allocatable_memory(initHeapSize);
3137
3138      if (FLAG_IS_DEFAULT(MaxHeapSize)) {
3139         FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);
3140         FLAG_SET_CMDLINE(uintx, InitialHeapSize, initHeapSize);
3141         // Currently the minimum size and the initial heap sizes are the same.
3142         set_min_heap_size(initHeapSize);
3143      }
3144      if (FLAG_IS_DEFAULT(NewSize)) {
3145         // Make the young generation 3/8ths of the total heap.
3146         FLAG_SET_CMDLINE(uintx, NewSize,
3147                                ((julong)MaxHeapSize / (julong)8) * (julong)3);
3148         FLAG_SET_CMDLINE(uintx, MaxNewSize, NewSize);
3149      }
3150
3151#ifndef _ALLBSD_SOURCE  // UseLargePages is not yet supported on BSD.
3152      FLAG_SET_DEFAULT(UseLargePages, true);
3153#endif
3154
3155      // Increase some data structure sizes for efficiency
3156      FLAG_SET_CMDLINE(uintx, BaseFootPrintEstimate, MaxHeapSize);
3157      FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
3158      FLAG_SET_CMDLINE(uintx, TLABSize, 256*K);
3159
3160      // See the OldPLABSize comment below, but replace 'after promotion'
3161      // with 'after copying'.  YoungPLABSize is the size of the survivor
3162      // space per-gc-thread buffers.  The default is 4kw.
3163      FLAG_SET_CMDLINE(uintx, YoungPLABSize, 256*K);      // Note: this is in words
3164
3165      // OldPLABSize is the size of the buffers in the old gen that
3166      // UseParallelGC uses to promote live data that doesn't fit in the
3167      // survivor spaces.  At any given time, there's one for each gc thread.
3168      // The default size is 1kw. These buffers are rarely used, since the
3169      // survivor spaces are usually big enough.  For specjbb, however, there
3170      // are occasions when there's lots of live data in the young gen
3171      // and we end up promoting some of it.  We don't have a definite
3172      // explanation for why bumping OldPLABSize helps, but the theory
3173      // is that a bigger PLAB results in retaining something like the
3174      // original allocation order after promotion, which improves mutator
3175      // locality.  A minor effect may be that larger PLABs reduce the
3176      // number of PLAB allocation events during gc.  The value of 8kw
3177      // was arrived at by experimenting with specjbb.
3178      FLAG_SET_CMDLINE(uintx, OldPLABSize, 8*K);  // Note: this is in words
3179
3180      // Enable parallel GC and adaptive generation sizing
3181      FLAG_SET_CMDLINE(bool, UseParallelGC, true);
3182      FLAG_SET_DEFAULT(ParallelGCThreads,
3183                       Abstract_VM_Version::parallel_worker_threads());
3184
3185      // Encourage steady state memory management
3186      FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);
3187
3188      // This appears to improve mutator locality
3189      FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
3190
3191      // Get around early Solaris scheduling bug
3192      // (affinity vs other jobs on system)
3193      // but disallow DR and offlining (5008695).
3194      FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);
3195
3196    // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
3197    // and the last option wins.
3198    } else if (match_option(option, "-XX:+NeverTenure")) {
3199      FLAG_SET_CMDLINE(bool, NeverTenure, true);
3200      FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
3201      FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1);
3202    } else if (match_option(option, "-XX:+AlwaysTenure")) {
3203      FLAG_SET_CMDLINE(bool, NeverTenure, false);
3204      FLAG_SET_CMDLINE(bool, AlwaysTenure, true);
3205      FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0);
3206    } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
3207      uintx max_tenuring_thresh = 0;
3208      if(!parse_uintx(tail, &max_tenuring_thresh, 0)) {
3209        jio_fprintf(defaultStream::error_stream(),
3210                    "Invalid MaxTenuringThreshold: %s\n", option->optionString);
3211      }
3212      FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh);
3213
3214      if (MaxTenuringThreshold == 0) {
3215        FLAG_SET_CMDLINE(bool, NeverTenure, false);
3216        FLAG_SET_CMDLINE(bool, AlwaysTenure, true);
3217      } else {
3218        FLAG_SET_CMDLINE(bool, NeverTenure, false);
3219        FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
3220      }
3221    } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3222      FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false);
3223      FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true);
3224    } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3225      FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false);
3226      FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true);
3227    } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3228#if defined(DTRACE_ENABLED)
3229      FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true);
3230      FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true);
3231      FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true);
3232      FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true);
3233#else // defined(DTRACE_ENABLED)
3234      jio_fprintf(defaultStream::error_stream(),
3235                  "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3236      return JNI_EINVAL;
3237#endif // defined(DTRACE_ENABLED)
3238#ifdef ASSERT
3239    } else if (match_option(option, "-XX:+FullGCALot")) {
3240      FLAG_SET_CMDLINE(bool, FullGCALot, true);
3241      // disable scavenge before parallel mark-compact
3242      FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
3243#endif
3244    } else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||
3245               match_option(option, "-XX:G1MarkStackSize=", &tail)) {
3246      julong stack_size = 0;
3247      ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);
3248      if (errcode != arg_in_range) {
3249        jio_fprintf(defaultStream::error_stream(),
3250                    "Invalid mark stack size: %s\n", option->optionString);
3251        describe_range_error(errcode);
3252        return JNI_EINVAL;
3253      }
3254      jio_fprintf(defaultStream::error_stream(),
3255        "Please use -XX:MarkStackSize in place of "
3256        "-XX:CMSMarkStackSize or -XX:G1MarkStackSize in the future\n");
3257      FLAG_SET_CMDLINE(uintx, MarkStackSize, stack_size);
3258    } else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {
3259      julong max_stack_size = 0;
3260      ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);
3261      if (errcode != arg_in_range) {
3262        jio_fprintf(defaultStream::error_stream(),
3263                    "Invalid maximum mark stack size: %s\n",
3264                    option->optionString);
3265        describe_range_error(errcode);
3266        return JNI_EINVAL;
3267      }
3268      jio_fprintf(defaultStream::error_stream(),
3269         "Please use -XX:MarkStackSizeMax in place of "
3270         "-XX:CMSMarkStackSizeMax in the future\n");
3271      FLAG_SET_CMDLINE(uintx, MarkStackSizeMax, max_stack_size);
3272    } else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||
3273               match_option(option, "-XX:ParallelCMSThreads=", &tail)) {
3274      uintx conc_threads = 0;
3275      if (!parse_uintx(tail, &conc_threads, 1)) {
3276        jio_fprintf(defaultStream::error_stream(),
3277                    "Invalid concurrent threads: %s\n", option->optionString);
3278        return JNI_EINVAL;
3279      }
3280      jio_fprintf(defaultStream::error_stream(),
3281        "Please use -XX:ConcGCThreads in place of "
3282        "-XX:ParallelMarkingThreads or -XX:ParallelCMSThreads in the future\n");
3283      FLAG_SET_CMDLINE(uintx, ConcGCThreads, conc_threads);
3284    } else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {
3285      julong max_direct_memory_size = 0;
3286      ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);
3287      if (errcode != arg_in_range) {
3288        jio_fprintf(defaultStream::error_stream(),
3289                    "Invalid maximum direct memory size: %s\n",
3290                    option->optionString);
3291        describe_range_error(errcode);
3292        return JNI_EINVAL;
3293      }
3294      FLAG_SET_CMDLINE(uintx, MaxDirectMemorySize, max_direct_memory_size);
3295#if !INCLUDE_MANAGEMENT
3296    } else if (match_option(option, "-XX:+ManagementServer")) {
3297        jio_fprintf(defaultStream::error_stream(),
3298          "ManagementServer is not supported in this VM.\n");
3299        return JNI_ERR;
3300#endif // INCLUDE_MANAGEMENT
3301    } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3302      // Skip -XX:Flags= since that case has already been handled
3303      if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
3304        if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3305          return JNI_EINVAL;
3306        }
3307      }
3308    // Unknown option
3309    } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3310      return JNI_ERR;
3311    }
3312  }
3313
3314  // PrintSharedArchiveAndExit will turn on
3315  //   -Xshare:on
3316  //   -XX:+TraceClassPaths
3317  if (PrintSharedArchiveAndExit) {
3318    FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
3319    FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
3320    FLAG_SET_CMDLINE(bool, TraceClassPaths, true);
3321  }
3322
3323  // Change the default value for flags  which have different default values
3324  // when working with older JDKs.
3325#ifdef LINUX
3326 if (JDK_Version::current().compare_major(6) <= 0 &&
3327      FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3328    FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3329  }
3330#endif // LINUX
3331  fix_appclasspath();
3332  return JNI_OK;
3333}
3334
3335// Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3336//
3337// This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3338// in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3339// Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3340// path is treated as the current directory.
3341//
3342// This causes problems with CDS, which requires that all directories specified in the classpath
3343// must be empty. In most cases, applications do NOT want to load classes from the current
3344// directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3345// scripts compatible with CDS.
3346void Arguments::fix_appclasspath() {
3347  if (IgnoreEmptyClassPaths) {
3348    const char separator = *os::path_separator();
3349    const char* src = _java_class_path->value();
3350
3351    // skip over all the leading empty paths
3352    while (*src == separator) {
3353      src ++;
3354    }
3355
3356    char* copy = AllocateHeap(strlen(src) + 1, mtInternal);
3357    strncpy(copy, src, strlen(src) + 1);
3358
3359    // trim all trailing empty paths
3360    for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3361      *tail = '\0';
3362    }
3363
3364    char from[3] = {separator, separator, '\0'};
3365    char to  [2] = {separator, '\0'};
3366    while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3367      // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3368      // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3369    }
3370
3371    _java_class_path->set_value(copy);
3372    FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3373  }
3374
3375  if (!PrintSharedArchiveAndExit) {
3376    ClassLoader::trace_class_path("[classpath: ", _java_class_path->value());
3377  }
3378}
3379
3380static bool has_jar_files(const char* directory) {
3381  DIR* dir = os::opendir(directory);
3382  if (dir == NULL) return false;
3383
3384  struct dirent *entry;
3385  char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
3386  bool hasJarFile = false;
3387  while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3388    const char* name = entry->d_name;
3389    const char* ext = name + strlen(name) - 4;
3390    hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3391  }
3392  FREE_C_HEAP_ARRAY(char, dbuf);
3393  os::closedir(dir);
3394  return hasJarFile ;
3395}
3396
3397static int check_non_empty_dirs(const char* path) {
3398  const char separator = *os::path_separator();
3399  const char* const end = path + strlen(path);
3400  int nonEmptyDirs = 0;
3401  while (path < end) {
3402    const char* tmp_end = strchr(path, separator);
3403    if (tmp_end == NULL) {
3404      if (has_jar_files(path)) {
3405        nonEmptyDirs++;
3406        jio_fprintf(defaultStream::output_stream(),
3407          "Non-empty directory: %s\n", path);
3408      }
3409      path = end;
3410    } else {
3411      char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
3412      memcpy(dirpath, path, tmp_end - path);
3413      dirpath[tmp_end - path] = '\0';
3414      if (has_jar_files(dirpath)) {
3415        nonEmptyDirs++;
3416        jio_fprintf(defaultStream::output_stream(),
3417          "Non-empty directory: %s\n", dirpath);
3418      }
3419      FREE_C_HEAP_ARRAY(char, dirpath);
3420      path = tmp_end + 1;
3421    }
3422  }
3423  return nonEmptyDirs;
3424}
3425
3426jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
3427  // check if the default lib/endorsed directory exists; if so, error
3428  char path[JVM_MAXPATHLEN];
3429  const char* fileSep = os::file_separator();
3430  sprintf(path, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3431
3432  if (CheckEndorsedAndExtDirs) {
3433    int nonEmptyDirs = 0;
3434    // check endorsed directory
3435    nonEmptyDirs += check_non_empty_dirs(path);
3436    // check the extension directories
3437    nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3438    if (nonEmptyDirs > 0) {
3439      return JNI_ERR;
3440    }
3441  }
3442
3443  DIR* dir = os::opendir(path);
3444  if (dir != NULL) {
3445    jio_fprintf(defaultStream::output_stream(),
3446      "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3447      "in modular form will be supported via the concept of upgradeable modules.\n");
3448    os::closedir(dir);
3449    return JNI_ERR;
3450  }
3451
3452  sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3453  dir = os::opendir(path);
3454  if (dir != NULL) {
3455    jio_fprintf(defaultStream::output_stream(),
3456      "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3457      "Use -classpath instead.\n.");
3458    os::closedir(dir);
3459    return JNI_ERR;
3460  }
3461
3462  if (scp_assembly_required) {
3463    // Assemble the bootclasspath elements into the final path.
3464    Arguments::set_sysclasspath(scp_p->combined_path());
3465  }
3466
3467  // This must be done after all arguments have been processed.
3468  // java_compiler() true means set to "NONE" or empty.
3469  if (java_compiler() && !xdebug_mode()) {
3470    // For backwards compatibility, we switch to interpreted mode if
3471    // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3472    // not specified.
3473    set_mode_flags(_int);
3474  }
3475
3476  // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3477  // but like -Xint, leave compilation thresholds unaffected.
3478  // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3479  if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3480    set_mode_flags(_int);
3481  }
3482
3483  // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3484  if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3485    FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3486  }
3487
3488#ifndef COMPILER2
3489  // Don't degrade server performance for footprint
3490  if (FLAG_IS_DEFAULT(UseLargePages) &&
3491      MaxHeapSize < LargePageHeapSizeThreshold) {
3492    // No need for large granularity pages w/small heaps.
3493    // Note that large pages are enabled/disabled for both the
3494    // Java heap and the code cache.
3495    FLAG_SET_DEFAULT(UseLargePages, false);
3496  }
3497
3498#else
3499  if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3500    FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3501  }
3502#endif
3503
3504#ifndef TIERED
3505  // Tiered compilation is undefined.
3506  UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
3507#endif
3508
3509  // If we are running in a headless jre, force java.awt.headless property
3510  // to be true unless the property has already been set.
3511  // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3512  if (os::is_headless_jre()) {
3513    const char* headless = Arguments::get_property("java.awt.headless");
3514    if (headless == NULL) {
3515      char envbuffer[128];
3516      if (!os::getenv("JAVA_AWT_HEADLESS", envbuffer, sizeof(envbuffer))) {
3517        if (!add_property("java.awt.headless=true")) {
3518          return JNI_ENOMEM;
3519        }
3520      } else {
3521        char buffer[256];
3522        strcpy(buffer, "java.awt.headless=");
3523        strcat(buffer, envbuffer);
3524        if (!add_property(buffer)) {
3525          return JNI_ENOMEM;
3526        }
3527      }
3528    }
3529  }
3530
3531  if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3532    // CMS can only be used with ParNew
3533    FLAG_SET_ERGO(bool, UseParNewGC, true);
3534  }
3535
3536  if (!check_vm_args_consistency()) {
3537    return JNI_ERR;
3538  }
3539
3540  return JNI_OK;
3541}
3542
3543jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3544  return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,
3545                                            scp_assembly_required_p);
3546}
3547
3548jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3549  return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,
3550                                            scp_assembly_required_p);
3551}
3552
3553jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {
3554  const int N_MAX_OPTIONS = 64;
3555  const int OPTION_BUFFER_SIZE = 1024;
3556  char buffer[OPTION_BUFFER_SIZE];
3557
3558  // The variable will be ignored if it exceeds the length of the buffer.
3559  // Don't check this variable if user has special privileges
3560  // (e.g. unix su command).
3561  if (os::getenv(name, buffer, sizeof(buffer)) &&
3562      !os::have_special_privileges()) {
3563    JavaVMOption options[N_MAX_OPTIONS];      // Construct option array
3564    jio_fprintf(defaultStream::error_stream(),
3565                "Picked up %s: %s\n", name, buffer);
3566    char* rd = buffer;                        // pointer to the input string (rd)
3567    int i;
3568    for (i = 0; i < N_MAX_OPTIONS;) {         // repeat for all options in the input string
3569      while (isspace(*rd)) rd++;              // skip whitespace
3570      if (*rd == 0) break;                    // we re done when the input string is read completely
3571
3572      // The output, option string, overwrites the input string.
3573      // Because of quoting, the pointer to the option string (wrt) may lag the pointer to
3574      // input string (rd).
3575      char* wrt = rd;
3576
3577      options[i++].optionString = wrt;        // Fill in option
3578      while (*rd != 0 && !isspace(*rd)) {     // unquoted strings terminate with a space or NULL
3579        if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3580          int quote = *rd;                    // matching quote to look for
3581          rd++;                               // don't copy open quote
3582          while (*rd != quote) {              // include everything (even spaces) up until quote
3583            if (*rd == 0) {                   // string termination means unmatched string
3584              jio_fprintf(defaultStream::error_stream(),
3585                          "Unmatched quote in %s\n", name);
3586              return JNI_ERR;
3587            }
3588            *wrt++ = *rd++;                   // copy to option string
3589          }
3590          rd++;                               // don't copy close quote
3591        } else {
3592          *wrt++ = *rd++;                     // copy to option string
3593        }
3594      }
3595      // Need to check if we're done before writing a NULL,
3596      // because the write could be to the byte that rd is pointing to.
3597      if (*rd++ == 0) {
3598        *wrt = 0;
3599        break;
3600      }
3601      *wrt = 0;                               // Zero terminate option
3602    }
3603    // Construct JavaVMInitArgs structure and parse as if it was part of the command line
3604    JavaVMInitArgs vm_args;
3605    vm_args.version = JNI_VERSION_1_2;
3606    vm_args.options = options;
3607    vm_args.nOptions = i;
3608    vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3609
3610    if (PrintVMOptions) {
3611      const char* tail;
3612      for (int i = 0; i < vm_args.nOptions; i++) {
3613        const JavaVMOption *option = vm_args.options + i;
3614        if (match_option(option, "-XX:", &tail)) {
3615          logOption(tail);
3616        }
3617      }
3618    }
3619
3620    return(parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p, Flag::ENVIRON_VAR));
3621  }
3622  return JNI_OK;
3623}
3624
3625void Arguments::set_shared_spaces_flags() {
3626  if (DumpSharedSpaces) {
3627    if (RequireSharedSpaces) {
3628      warning("cannot dump shared archive while using shared archive");
3629    }
3630    UseSharedSpaces = false;
3631#ifdef _LP64
3632    if (!UseCompressedOops || !UseCompressedClassPointers) {
3633      vm_exit_during_initialization(
3634        "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3635    }
3636  } else {
3637    if (!UseCompressedOops || !UseCompressedClassPointers) {
3638      no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3639    }
3640#endif
3641  }
3642}
3643
3644#if !INCLUDE_ALL_GCS
3645static void force_serial_gc() {
3646  FLAG_SET_DEFAULT(UseSerialGC, true);
3647  UNSUPPORTED_GC_OPTION(UseG1GC);
3648  UNSUPPORTED_GC_OPTION(UseParallelGC);
3649  UNSUPPORTED_GC_OPTION(UseParallelOldGC);
3650  UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
3651  UNSUPPORTED_GC_OPTION(UseParNewGC);
3652}
3653#endif // INCLUDE_ALL_GCS
3654
3655// Sharing support
3656// Construct the path to the archive
3657static char* get_shared_archive_path() {
3658  char *shared_archive_path;
3659  if (SharedArchiveFile == NULL) {
3660    char jvm_path[JVM_MAXPATHLEN];
3661    os::jvm_path(jvm_path, sizeof(jvm_path));
3662    char *end = strrchr(jvm_path, *os::file_separator());
3663    if (end != NULL) *end = '\0';
3664    size_t jvm_path_len = strlen(jvm_path);
3665    size_t file_sep_len = strlen(os::file_separator());
3666    shared_archive_path = NEW_C_HEAP_ARRAY(char, jvm_path_len +
3667        file_sep_len + 20, mtInternal);
3668    if (shared_archive_path != NULL) {
3669      strncpy(shared_archive_path, jvm_path, jvm_path_len + 1);
3670      strncat(shared_archive_path, os::file_separator(), file_sep_len);
3671      strncat(shared_archive_path, "classes.jsa", 11);
3672    }
3673  } else {
3674    shared_archive_path = NEW_C_HEAP_ARRAY(char, strlen(SharedArchiveFile) + 1, mtInternal);
3675    if (shared_archive_path != NULL) {
3676      strncpy(shared_archive_path, SharedArchiveFile, strlen(SharedArchiveFile) + 1);
3677    }
3678  }
3679  return shared_archive_path;
3680}
3681
3682#ifndef PRODUCT
3683// Determine whether LogVMOutput should be implicitly turned on.
3684static bool use_vm_log() {
3685  if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3686      PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3687      PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3688      PrintAssembly || TraceDeoptimization || TraceDependencies ||
3689      (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3690    return true;
3691  }
3692
3693#ifdef COMPILER1
3694  if (PrintC1Statistics) {
3695    return true;
3696  }
3697#endif // COMPILER1
3698
3699#ifdef COMPILER2
3700  if (PrintOptoAssembly || PrintOptoStatistics) {
3701    return true;
3702  }
3703#endif // COMPILER2
3704
3705  return false;
3706}
3707#endif // PRODUCT
3708
3709// Parse entry point called from JNI_CreateJavaVM
3710
3711jint Arguments::parse(const JavaVMInitArgs* args) {
3712
3713  // Remaining part of option string
3714  const char* tail;
3715
3716  // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3717  const char* hotspotrc = ".hotspotrc";
3718  bool settings_file_specified = false;
3719  bool needs_hotspotrc_warning = false;
3720
3721  const char* flags_file;
3722  int index;
3723  for (index = 0; index < args->nOptions; index++) {
3724    const JavaVMOption *option = args->options + index;
3725    if (ArgumentsExt::process_options(option)) {
3726      continue;
3727    }
3728    if (match_option(option, "-XX:Flags=", &tail)) {
3729      flags_file = tail;
3730      settings_file_specified = true;
3731      continue;
3732    }
3733    if (match_option(option, "-XX:+PrintVMOptions")) {
3734      PrintVMOptions = true;
3735      continue;
3736    }
3737    if (match_option(option, "-XX:-PrintVMOptions")) {
3738      PrintVMOptions = false;
3739      continue;
3740    }
3741    if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3742      IgnoreUnrecognizedVMOptions = true;
3743      continue;
3744    }
3745    if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3746      IgnoreUnrecognizedVMOptions = false;
3747      continue;
3748    }
3749    if (match_option(option, "-XX:+PrintFlagsInitial")) {
3750      CommandLineFlags::printFlags(tty, false);
3751      vm_exit(0);
3752    }
3753#if INCLUDE_NMT
3754    if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3755      // The launcher did not setup nmt environment variable properly.
3756      if (!MemTracker::check_launcher_nmt_support(tail)) {
3757        warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3758      }
3759
3760      // Verify if nmt option is valid.
3761      if (MemTracker::verify_nmt_option()) {
3762        // Late initialization, still in single-threaded mode.
3763        if (MemTracker::tracking_level() >= NMT_summary) {
3764          MemTracker::init();
3765        }
3766      } else {
3767        vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3768      }
3769      continue;
3770    }
3771#endif
3772
3773
3774#ifndef PRODUCT
3775    if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3776      CommandLineFlags::printFlags(tty, true);
3777      vm_exit(0);
3778    }
3779#endif
3780  }
3781
3782  if (IgnoreUnrecognizedVMOptions) {
3783    // uncast const to modify the flag args->ignoreUnrecognized
3784    *(jboolean*)(&args->ignoreUnrecognized) = true;
3785  }
3786
3787  // Parse specified settings file
3788  if (settings_file_specified) {
3789    if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
3790      return JNI_EINVAL;
3791    }
3792  } else {
3793#ifdef ASSERT
3794    // Parse default .hotspotrc settings file
3795    if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
3796      return JNI_EINVAL;
3797    }
3798#else
3799    struct stat buf;
3800    if (os::stat(hotspotrc, &buf) == 0) {
3801      needs_hotspotrc_warning = true;
3802    }
3803#endif
3804  }
3805
3806  if (PrintVMOptions) {
3807    for (index = 0; index < args->nOptions; index++) {
3808      const JavaVMOption *option = args->options + index;
3809      if (match_option(option, "-XX:", &tail)) {
3810        logOption(tail);
3811      }
3812    }
3813  }
3814
3815  // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
3816  jint result = parse_vm_init_args(args);
3817  if (result != JNI_OK) {
3818    return result;
3819  }
3820
3821  // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
3822  SharedArchivePath = get_shared_archive_path();
3823  if (SharedArchivePath == NULL) {
3824    return JNI_ENOMEM;
3825  }
3826
3827  // Set up VerifySharedSpaces
3828  if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
3829    VerifySharedSpaces = true;
3830  }
3831
3832  // Delay warning until here so that we've had a chance to process
3833  // the -XX:-PrintWarnings flag
3834  if (needs_hotspotrc_warning) {
3835    warning("%s file is present but has been ignored.  "
3836            "Run with -XX:Flags=%s to load the file.",
3837            hotspotrc, hotspotrc);
3838  }
3839
3840#ifdef _ALLBSD_SOURCE  // UseLargePages is not yet supported on BSD.
3841  UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
3842#endif
3843
3844#if INCLUDE_ALL_GCS
3845  #if (defined JAVASE_EMBEDDED || defined ARM)
3846    UNSUPPORTED_OPTION(UseG1GC, "G1 GC");
3847  #endif
3848#endif
3849
3850  ArgumentsExt::report_unsupported_options();
3851
3852#ifndef PRODUCT
3853  if (TraceBytecodesAt != 0) {
3854    TraceBytecodes = true;
3855  }
3856  if (CountCompiledCalls) {
3857    if (UseCounterDecay) {
3858      warning("UseCounterDecay disabled because CountCalls is set");
3859      UseCounterDecay = false;
3860    }
3861  }
3862#endif // PRODUCT
3863
3864  if (ScavengeRootsInCode == 0) {
3865    if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3866      warning("forcing ScavengeRootsInCode non-zero");
3867    }
3868    ScavengeRootsInCode = 1;
3869  }
3870
3871  if (PrintGCDetails) {
3872    // Turn on -verbose:gc options as well
3873    PrintGC = true;
3874  }
3875
3876  // Set object alignment values.
3877  set_object_alignment();
3878
3879#if !INCLUDE_ALL_GCS
3880  force_serial_gc();
3881#endif // INCLUDE_ALL_GCS
3882#if !INCLUDE_CDS
3883  if (DumpSharedSpaces || RequireSharedSpaces) {
3884    jio_fprintf(defaultStream::error_stream(),
3885      "Shared spaces are not supported in this VM\n");
3886    return JNI_ERR;
3887  }
3888  if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
3889    warning("Shared spaces are not supported in this VM");
3890    FLAG_SET_DEFAULT(UseSharedSpaces, false);
3891    FLAG_SET_DEFAULT(PrintSharedSpaces, false);
3892  }
3893  no_shared_spaces("CDS Disabled");
3894#endif // INCLUDE_CDS
3895
3896  return JNI_OK;
3897}
3898
3899jint Arguments::apply_ergo() {
3900
3901  // Set flags based on ergonomics.
3902  set_ergonomics_flags();
3903
3904  set_shared_spaces_flags();
3905
3906  // Check the GC selections again.
3907  if (!ArgumentsExt::check_gc_consistency_ergo()) {
3908    return JNI_EINVAL;
3909  }
3910
3911  if (TieredCompilation) {
3912    set_tiered_flags();
3913  } else {
3914    // Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup.
3915    if (CompilationPolicyChoice >= 2) {
3916      vm_exit_during_initialization(
3917        "Incompatible compilation policy selected", NULL);
3918    }
3919    // Scale CompileThreshold
3920    // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
3921    if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
3922      FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
3923    }
3924  }
3925
3926#ifdef COMPILER2
3927#ifndef PRODUCT
3928  if (PrintIdealGraphLevel > 0) {
3929    FLAG_SET_ERGO(bool, PrintIdealGraph, true);
3930  }
3931#endif
3932#endif
3933
3934  // Set heap size based on available physical memory
3935  set_heap_size();
3936
3937  ArgumentsExt::set_gc_specific_flags();
3938
3939  // Initialize Metaspace flags and alignments
3940  Metaspace::ergo_initialize();
3941
3942  // Set bytecode rewriting flags
3943  set_bytecode_flags();
3944
3945  // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
3946  set_aggressive_opts_flags();
3947
3948  // Turn off biased locking for locking debug mode flags,
3949  // which are subtly different from each other but neither works with
3950  // biased locking
3951  if (UseHeavyMonitors
3952#ifdef COMPILER1
3953      || !UseFastLocking
3954#endif // COMPILER1
3955    ) {
3956    if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
3957      // flag set to true on command line; warn the user that they
3958      // can't enable biased locking here
3959      warning("Biased Locking is not supported with locking debug flags"
3960              "; ignoring UseBiasedLocking flag." );
3961    }
3962    UseBiasedLocking = false;
3963  }
3964
3965#ifdef ZERO
3966  // Clear flags not supported on zero.
3967  FLAG_SET_DEFAULT(ProfileInterpreter, false);
3968  FLAG_SET_DEFAULT(UseBiasedLocking, false);
3969  LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
3970  LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
3971#endif // CC_INTERP
3972
3973#ifdef COMPILER2
3974  if (!EliminateLocks) {
3975    EliminateNestedLocks = false;
3976  }
3977  if (!Inline) {
3978    IncrementalInline = false;
3979  }
3980#ifndef PRODUCT
3981  if (!IncrementalInline) {
3982    AlwaysIncrementalInline = false;
3983  }
3984#endif
3985  if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
3986    // nothing to use the profiling, turn if off
3987    FLAG_SET_DEFAULT(TypeProfileLevel, 0);
3988  }
3989#endif
3990
3991  if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
3992    warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
3993    DebugNonSafepoints = true;
3994  }
3995
3996  if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
3997    warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
3998  }
3999
4000#ifndef PRODUCT
4001  if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4002    if (use_vm_log()) {
4003      LogVMOutput = true;
4004    }
4005  }
4006#endif // PRODUCT
4007
4008  if (PrintCommandLineFlags) {
4009    CommandLineFlags::printSetFlags(tty);
4010  }
4011
4012  // Apply CPU specific policy for the BiasedLocking
4013  if (UseBiasedLocking) {
4014    if (!VM_Version::use_biased_locking() &&
4015        !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4016      UseBiasedLocking = false;
4017    }
4018  }
4019#ifdef COMPILER2
4020  if (!UseBiasedLocking || EmitSync != 0) {
4021    UseOptoBiasInlining = false;
4022  }
4023#endif
4024
4025  return JNI_OK;
4026}
4027
4028jint Arguments::adjust_after_os() {
4029  if (UseNUMA) {
4030    if (UseParallelGC || UseParallelOldGC) {
4031      if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4032         FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4033      }
4034    }
4035    // UseNUMAInterleaving is set to ON for all collectors and
4036    // platforms when UseNUMA is set to ON. NUMA-aware collectors
4037    // such as the parallel collector for Linux and Solaris will
4038    // interleave old gen and survivor spaces on top of NUMA
4039    // allocation policy for the eden space.
4040    // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4041    // all platforms and ParallelGC on Windows will interleave all
4042    // of the heap spaces across NUMA nodes.
4043    if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4044      FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4045    }
4046  }
4047  return JNI_OK;
4048}
4049
4050int Arguments::PropertyList_count(SystemProperty* pl) {
4051  int count = 0;
4052  while(pl != NULL) {
4053    count++;
4054    pl = pl->next();
4055  }
4056  return count;
4057}
4058
4059const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4060  assert(key != NULL, "just checking");
4061  SystemProperty* prop;
4062  for (prop = pl; prop != NULL; prop = prop->next()) {
4063    if (strcmp(key, prop->key()) == 0) return prop->value();
4064  }
4065  return NULL;
4066}
4067
4068const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4069  int count = 0;
4070  const char* ret_val = NULL;
4071
4072  while(pl != NULL) {
4073    if(count >= index) {
4074      ret_val = pl->key();
4075      break;
4076    }
4077    count++;
4078    pl = pl->next();
4079  }
4080
4081  return ret_val;
4082}
4083
4084char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4085  int count = 0;
4086  char* ret_val = NULL;
4087
4088  while(pl != NULL) {
4089    if(count >= index) {
4090      ret_val = pl->value();
4091      break;
4092    }
4093    count++;
4094    pl = pl->next();
4095  }
4096
4097  return ret_val;
4098}
4099
4100void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4101  SystemProperty* p = *plist;
4102  if (p == NULL) {
4103    *plist = new_p;
4104  } else {
4105    while (p->next() != NULL) {
4106      p = p->next();
4107    }
4108    p->set_next(new_p);
4109  }
4110}
4111
4112void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {
4113  if (plist == NULL)
4114    return;
4115
4116  SystemProperty* new_p = new SystemProperty(k, v, true);
4117  PropertyList_add(plist, new_p);
4118}
4119
4120void Arguments::PropertyList_add(SystemProperty *element) {
4121  PropertyList_add(&_system_properties, element);
4122}
4123
4124// This add maintains unique property key in the list.
4125void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {
4126  if (plist == NULL)
4127    return;
4128
4129  // If property key exist then update with new value.
4130  SystemProperty* prop;
4131  for (prop = *plist; prop != NULL; prop = prop->next()) {
4132    if (strcmp(k, prop->key()) == 0) {
4133      if (append) {
4134        prop->append_value(v);
4135      } else {
4136        prop->set_value(v);
4137      }
4138      return;
4139    }
4140  }
4141
4142  PropertyList_add(plist, k, v);
4143}
4144
4145// Copies src into buf, replacing "%%" with "%" and "%p" with pid
4146// Returns true if all of the source pointed by src has been copied over to
4147// the destination buffer pointed by buf. Otherwise, returns false.
4148// Notes:
4149// 1. If the length (buflen) of the destination buffer excluding the
4150// NULL terminator character is not long enough for holding the expanded
4151// pid characters, it also returns false instead of returning the partially
4152// expanded one.
4153// 2. The passed in "buflen" should be large enough to hold the null terminator.
4154bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4155                                char* buf, size_t buflen) {
4156  const char* p = src;
4157  char* b = buf;
4158  const char* src_end = &src[srclen];
4159  char* buf_end = &buf[buflen - 1];
4160
4161  while (p < src_end && b < buf_end) {
4162    if (*p == '%') {
4163      switch (*(++p)) {
4164      case '%':         // "%%" ==> "%"
4165        *b++ = *p++;
4166        break;
4167      case 'p':  {       //  "%p" ==> current process id
4168        // buf_end points to the character before the last character so
4169        // that we could write '\0' to the end of the buffer.
4170        size_t buf_sz = buf_end - b + 1;
4171        int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4172
4173        // if jio_snprintf fails or the buffer is not long enough to hold
4174        // the expanded pid, returns false.
4175        if (ret < 0 || ret >= (int)buf_sz) {
4176          return false;
4177        } else {
4178          b += ret;
4179          assert(*b == '\0', "fail in copy_expand_pid");
4180          if (p == src_end && b == buf_end + 1) {
4181            // reach the end of the buffer.
4182            return true;
4183          }
4184        }
4185        p++;
4186        break;
4187      }
4188      default :
4189        *b++ = '%';
4190      }
4191    } else {
4192      *b++ = *p++;
4193    }
4194  }
4195  *b = '\0';
4196  return (p == src_end); // return false if not all of the source was copied
4197}
4198