|
Java example source code file (arguments.cpp)
The arguments.cpp Java example source code
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/javaAssertions.hpp"
#include "classfile/symbolTable.hpp"
#include "compiler/compilerOracle.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/cardTableRS.hpp"
#include "memory/genCollectedHeap.hpp"
#include "memory/referenceProcessor.hpp"
#include "memory/universe.inline.hpp"
#include "oops/oop.inline.hpp"
#include "prims/jvmtiExport.hpp"
#include "runtime/arguments.hpp"
#include "runtime/globals_extension.hpp"
#include "runtime/java.hpp"
#include "services/management.hpp"
#include "services/memTracker.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/macros.hpp"
#include "utilities/taskqueue.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "os_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "os_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "os_windows.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_bsd
# include "os_bsd.inline.hpp"
#endif
#if INCLUDE_ALL_GCS
#include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
#include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
#endif // INCLUDE_ALL_GCS
// Note: This is a special bug reporting site for the JVM
#define DEFAULT_VENDOR_URL_BUG "http://bugreport.sun.com/bugreport/crash.jsp"
#define DEFAULT_JAVA_LAUNCHER "generic"
// Disable options not supported in this release, with a warning if they
// were explicitly requested on the command-line
#define UNSUPPORTED_OPTION(opt, description) \
do { \
if (opt) { \
if (FLAG_IS_CMDLINE(opt)) { \
warning(description " is disabled in this release."); \
} \
FLAG_SET_DEFAULT(opt, false); \
} \
} while(0)
#define UNSUPPORTED_GC_OPTION(gc) \
do { \
if (gc) { \
if (FLAG_IS_CMDLINE(gc)) { \
warning(#gc " is not supported in this VM. Using Serial GC."); \
} \
FLAG_SET_DEFAULT(gc, false); \
} \
} while(0)
char** Arguments::_jvm_flags_array = NULL;
int Arguments::_num_jvm_flags = 0;
char** Arguments::_jvm_args_array = NULL;
int Arguments::_num_jvm_args = 0;
char* Arguments::_java_command = NULL;
SystemProperty* Arguments::_system_properties = NULL;
const char* Arguments::_gc_log_filename = NULL;
bool Arguments::_has_profile = false;
size_t Arguments::_conservative_max_heap_alignment = 0;
uintx Arguments::_min_heap_size = 0;
Arguments::Mode Arguments::_mode = _mixed;
bool Arguments::_java_compiler = false;
bool Arguments::_xdebug_mode = false;
const char* Arguments::_java_vendor_url_bug = DEFAULT_VENDOR_URL_BUG;
const char* Arguments::_sun_java_launcher = DEFAULT_JAVA_LAUNCHER;
int Arguments::_sun_java_launcher_pid = -1;
bool Arguments::_created_by_gamma_launcher = false;
// These parameters are reset in method parse_vm_init_args(JavaVMInitArgs*)
bool Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
bool Arguments::_UseOnStackReplacement = UseOnStackReplacement;
bool Arguments::_BackgroundCompilation = BackgroundCompilation;
bool Arguments::_ClipInlining = ClipInlining;
char* Arguments::SharedArchivePath = NULL;
AgentLibraryList Arguments::_libraryList;
AgentLibraryList Arguments::_agentList;
abort_hook_t Arguments::_abort_hook = NULL;
exit_hook_t Arguments::_exit_hook = NULL;
vfprintf_hook_t Arguments::_vfprintf_hook = NULL;
SystemProperty *Arguments::_java_ext_dirs = NULL;
SystemProperty *Arguments::_java_endorsed_dirs = NULL;
SystemProperty *Arguments::_sun_boot_library_path = NULL;
SystemProperty *Arguments::_java_library_path = NULL;
SystemProperty *Arguments::_java_home = NULL;
SystemProperty *Arguments::_java_class_path = NULL;
SystemProperty *Arguments::_sun_boot_class_path = NULL;
char* Arguments::_meta_index_path = NULL;
char* Arguments::_meta_index_dir = NULL;
// Check if head of 'option' matches 'name', and sets 'tail' remaining part of option string
static bool match_option(const JavaVMOption *option, const char* name,
const char** tail) {
int len = (int)strlen(name);
if (strncmp(option->optionString, name, len) == 0) {
*tail = option->optionString + len;
return true;
} else {
return false;
}
}
static void logOption(const char* opt) {
if (PrintVMOptions) {
jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
}
}
// Process java launcher properties.
void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
// See if sun.java.launcher or sun.java.launcher.pid is defined.
// Must do this before setting up other system properties,
// as some of them may depend on launcher type.
for (int index = 0; index < args->nOptions; index++) {
const JavaVMOption* option = args->options + index;
const char* tail;
if (match_option(option, "-Dsun.java.launcher=", &tail)) {
process_java_launcher_argument(tail, option->extraInfo);
continue;
}
if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
_sun_java_launcher_pid = atoi(tail);
continue;
}
}
}
// Initialize system properties key and value.
void Arguments::init_system_properties() {
PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
"Java Virtual Machine Specification", false));
PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(), false));
PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(), false));
PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(), true));
// following are JVMTI agent writeable properties.
// Properties values are set to NULL and they are
// os specific they are initialized in os::init_system_properties_values().
_java_ext_dirs = new SystemProperty("java.ext.dirs", NULL, true);
_java_endorsed_dirs = new SystemProperty("java.endorsed.dirs", NULL, true);
_sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL, true);
_java_library_path = new SystemProperty("java.library.path", NULL, true);
_java_home = new SystemProperty("java.home", NULL, true);
_sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL, true);
_java_class_path = new SystemProperty("java.class.path", "", true);
// Add to System Property list.
PropertyList_add(&_system_properties, _java_ext_dirs);
PropertyList_add(&_system_properties, _java_endorsed_dirs);
PropertyList_add(&_system_properties, _sun_boot_library_path);
PropertyList_add(&_system_properties, _java_library_path);
PropertyList_add(&_system_properties, _java_home);
PropertyList_add(&_system_properties, _java_class_path);
PropertyList_add(&_system_properties, _sun_boot_class_path);
// Set OS specific system properties values
os::init_system_properties_values();
}
// Update/Initialize System properties after JDK version number is known
void Arguments::init_version_specific_system_properties() {
enum { bufsz = 16 };
char buffer[bufsz];
const char* spec_vendor = "Sun Microsystems Inc.";
uint32_t spec_version = 0;
if (JDK_Version::is_gte_jdk17x_version()) {
spec_vendor = "Oracle Corporation";
spec_version = JDK_Version::current().major_version();
}
jio_snprintf(buffer, bufsz, "1." UINT32_FORMAT, spec_version);
PropertyList_add(&_system_properties,
new SystemProperty("java.vm.specification.vendor", spec_vendor, false));
PropertyList_add(&_system_properties,
new SystemProperty("java.vm.specification.version", buffer, false));
PropertyList_add(&_system_properties,
new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(), false));
}
/**
* Provide a slightly more user-friendly way of eliminating -XX flags.
* When a flag is eliminated, it can be added to this list in order to
* continue accepting this flag on the command-line, while issuing a warning
* and ignoring the value. Once the JDK version reaches the 'accept_until'
* limit, we flatly refuse to admit the existence of the flag. This allows
* a flag to die correctly over JDK releases using HSX.
*/
typedef struct {
const char* name;
JDK_Version obsoleted_in; // when the flag went away
JDK_Version accept_until; // which version to start denying the existence
} ObsoleteFlag;
static ObsoleteFlag obsolete_jvm_flags[] = {
{ "UseTrainGC", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "UseSpecialLargeObjectHandling", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "UseOversizedCarHandling", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "TraceCarAllocation", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "PrintTrainGCProcessingStats", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "LogOfCarSpaceSize", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "OversizedCarThreshold", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "MinTickInterval", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "DefaultTickInterval", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "MaxTickInterval", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "DelayTickAdjustment", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "ProcessingToTenuringRatio", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "MinTrainLength", JDK_Version::jdk(5), JDK_Version::jdk(7) },
{ "AppendRatio", JDK_Version::jdk_update(6,10), JDK_Version::jdk(7) },
{ "DefaultMaxRAM", JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },
{ "DefaultInitialRAMFraction",
JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },
{ "UseDepthFirstScavengeOrder",
JDK_Version::jdk_update(6,22), JDK_Version::jdk(7) },
{ "HandlePromotionFailure",
JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },
{ "MaxLiveObjectEvacuationRatio",
JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },
{ "ForceSharedSpaces", JDK_Version::jdk_update(6,25), JDK_Version::jdk(8) },
{ "UseParallelOldGCCompacting",
JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
{ "UseParallelDensePrefixUpdate",
JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
{ "UseParallelOldGCDensePrefix",
JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
{ "AllowTransitionalJSR292", JDK_Version::jdk(7), JDK_Version::jdk(8) },
{ "UseCompressedStrings", JDK_Version::jdk(7), JDK_Version::jdk(8) },
{ "CMSPermGenPrecleaningEnabled", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "CMSTriggerPermRatio", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "CMSInitiatingPermOccupancyFraction", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "AdaptivePermSizeWeight", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "PermGenPadding", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "PermMarkSweepDeadRatio", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "PermSize", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "MaxPermSize", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "MinPermHeapExpansion", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "MaxPermHeapExpansion", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "CMSRevisitStackSize", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "PrintRevisitStats", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "UseVectoredExceptions", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "UseSplitVerifier", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "UseISM", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "UsePermISM", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "UseMPSS", JDK_Version::jdk(8), JDK_Version::jdk(9) },
{ "UseStringCache", JDK_Version::jdk(8), JDK_Version::jdk(9) },
#ifdef PRODUCT
{ "DesiredMethodLimit",
JDK_Version::jdk_update(7, 2), JDK_Version::jdk(8) },
#endif // PRODUCT
{ NULL, JDK_Version(0), JDK_Version(0) }
};
// Returns true if the flag is obsolete and fits into the range specified
// for being ignored. In the case that the flag is ignored, the 'version'
// value is filled in with the version number when the flag became
// obsolete so that that value can be displayed to the user.
bool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {
int i = 0;
assert(version != NULL, "Must provide a version buffer");
while (obsolete_jvm_flags[i].name != NULL) {
const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];
// <flag>=xxx form
// [-|+]<flag> form
if ((strncmp(flag_status.name, s, strlen(flag_status.name)) == 0) ||
((s[0] == '+' || s[0] == '-') &&
(strncmp(flag_status.name, &s[1], strlen(flag_status.name)) == 0))) {
if (JDK_Version::current().compare(flag_status.accept_until) == -1) {
*version = flag_status.obsoleted_in;
return true;
}
}
i++;
}
return false;
}
// Constructs the system class path (aka boot class path) from the following
// components, in order:
//
// prefix // from -Xbootclasspath/p:...
// endorsed // the expansion of -Djava.endorsed.dirs=...
// base // from os::get_system_properties() or -Xbootclasspath=
// suffix // from -Xbootclasspath/a:...
//
// java.endorsed.dirs is a list of directories; any jar or zip files in the
// directories are added to the sysclasspath just before the base.
//
// This could be AllStatic, but it isn't needed after argument processing is
// complete.
class SysClassPath: public StackObj {
public:
SysClassPath(const char* base);
~SysClassPath();
inline void set_base(const char* base);
inline void add_prefix(const char* prefix);
inline void add_suffix_to_prefix(const char* suffix);
inline void add_suffix(const char* suffix);
inline void reset_path(const char* base);
// Expand the jar/zip files in each directory listed by the java.endorsed.dirs
// property. Must be called after all command-line arguments have been
// processed (in particular, -Djava.endorsed.dirs=...) and before calling
// combined_path().
void expand_endorsed();
inline const char* get_base() const { return _items[_scp_base]; }
inline const char* get_prefix() const { return _items[_scp_prefix]; }
inline const char* get_suffix() const { return _items[_scp_suffix]; }
inline const char* get_endorsed() const { return _items[_scp_endorsed]; }
// Combine all the components into a single c-heap-allocated string; caller
// must free the string if/when no longer needed.
char* combined_path();
private:
// Utility routines.
static char* add_to_path(const char* path, const char* str, bool prepend);
static char* add_jars_to_path(char* path, const char* directory);
inline void reset_item_at(int index);
// Array indices for the items that make up the sysclasspath. All except the
// base are allocated in the C heap and freed by this class.
enum {
_scp_prefix, // from -Xbootclasspath/p:...
_scp_endorsed, // the expansion of -Djava.endorsed.dirs=...
_scp_base, // the default sysclasspath
_scp_suffix, // from -Xbootclasspath/a:...
_scp_nitems // the number of items, must be last.
};
const char* _items[_scp_nitems];
DEBUG_ONLY(bool _expansion_done;)
};
SysClassPath::SysClassPath(const char* base) {
memset(_items, 0, sizeof(_items));
_items[_scp_base] = base;
DEBUG_ONLY(_expansion_done = false;)
}
SysClassPath::~SysClassPath() {
// Free everything except the base.
for (int i = 0; i < _scp_nitems; ++i) {
if (i != _scp_base) reset_item_at(i);
}
DEBUG_ONLY(_expansion_done = false;)
}
inline void SysClassPath::set_base(const char* base) {
_items[_scp_base] = base;
}
inline void SysClassPath::add_prefix(const char* prefix) {
_items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);
}
inline void SysClassPath::add_suffix_to_prefix(const char* suffix) {
_items[_scp_prefix] = add_to_path(_items[_scp_prefix], suffix, false);
}
inline void SysClassPath::add_suffix(const char* suffix) {
_items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);
}
inline void SysClassPath::reset_item_at(int index) {
assert(index < _scp_nitems && index != _scp_base, "just checking");
if (_items[index] != NULL) {
FREE_C_HEAP_ARRAY(char, _items[index], mtInternal);
_items[index] = NULL;
}
}
inline void SysClassPath::reset_path(const char* base) {
// Clear the prefix and suffix.
reset_item_at(_scp_prefix);
reset_item_at(_scp_suffix);
set_base(base);
}
//------------------------------------------------------------------------------
void SysClassPath::expand_endorsed() {
assert(_items[_scp_endorsed] == NULL, "can only be called once.");
const char* path = Arguments::get_property("java.endorsed.dirs");
if (path == NULL) {
path = Arguments::get_endorsed_dir();
assert(path != NULL, "no default for java.endorsed.dirs");
}
char* expanded_path = NULL;
const char separator = *os::path_separator();
const char* const end = path + strlen(path);
while (path < end) {
const char* tmp_end = strchr(path, separator);
if (tmp_end == NULL) {
expanded_path = add_jars_to_path(expanded_path, path);
path = end;
} else {
char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
memcpy(dirpath, path, tmp_end - path);
dirpath[tmp_end - path] = '\0';
expanded_path = add_jars_to_path(expanded_path, dirpath);
FREE_C_HEAP_ARRAY(char, dirpath, mtInternal);
path = tmp_end + 1;
}
}
_items[_scp_endorsed] = expanded_path;
DEBUG_ONLY(_expansion_done = true;)
}
// Combine the bootclasspath elements, some of which may be null, into a single
// c-heap-allocated string.
char* SysClassPath::combined_path() {
assert(_items[_scp_base] != NULL, "empty default sysclasspath");
assert(_expansion_done, "must call expand_endorsed() first.");
size_t lengths[_scp_nitems];
size_t total_len = 0;
const char separator = *os::path_separator();
// Get the lengths.
int i;
for (i = 0; i < _scp_nitems; ++i) {
if (_items[i] != NULL) {
lengths[i] = strlen(_items[i]);
// Include space for the separator char (or a NULL for the last item).
total_len += lengths[i] + 1;
}
}
assert(total_len > 0, "empty sysclasspath not allowed");
// Copy the _items to a single string.
char* cp = NEW_C_HEAP_ARRAY(char, total_len, mtInternal);
char* cp_tmp = cp;
for (i = 0; i < _scp_nitems; ++i) {
if (_items[i] != NULL) {
memcpy(cp_tmp, _items[i], lengths[i]);
cp_tmp += lengths[i];
*cp_tmp++ = separator;
}
}
*--cp_tmp = '\0'; // Replace the extra separator.
return cp;
}
// Note: path must be c-heap-allocated (or NULL); it is freed if non-null.
char*
SysClassPath::add_to_path(const char* path, const char* str, bool prepend) {
char *cp;
assert(str != NULL, "just checking");
if (path == NULL) {
size_t len = strlen(str) + 1;
cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
memcpy(cp, str, len); // copy the trailing null
} else {
const char separator = *os::path_separator();
size_t old_len = strlen(path);
size_t str_len = strlen(str);
size_t len = old_len + str_len + 2;
if (prepend) {
cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
char* cp_tmp = cp;
memcpy(cp_tmp, str, str_len);
cp_tmp += str_len;
*cp_tmp = separator;
memcpy(++cp_tmp, path, old_len + 1); // copy the trailing null
FREE_C_HEAP_ARRAY(char, path, mtInternal);
} else {
cp = REALLOC_C_HEAP_ARRAY(char, path, len, mtInternal);
char* cp_tmp = cp + old_len;
*cp_tmp = separator;
memcpy(++cp_tmp, str, str_len + 1); // copy the trailing null
}
}
return cp;
}
// Scan the directory and append any jar or zip files found to path.
// Note: path must be c-heap-allocated (or NULL); it is freed if non-null.
char* SysClassPath::add_jars_to_path(char* path, const char* directory) {
DIR* dir = os::opendir(directory);
if (dir == NULL) return path;
char dir_sep[2] = { '\0', '\0' };
size_t directory_len = strlen(directory);
const char fileSep = *os::file_separator();
if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;
/* Scan the directory for jars/zips, appending them to path. */
struct dirent *entry;
char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
const char* name = entry->d_name;
const char* ext = name + strlen(name) - 4;
bool isJarOrZip = ext > name &&
(os::file_name_strcmp(ext, ".jar") == 0 ||
os::file_name_strcmp(ext, ".zip") == 0);
if (isJarOrZip) {
char* jarpath = NEW_C_HEAP_ARRAY(char, directory_len + 2 + strlen(name), mtInternal);
sprintf(jarpath, "%s%s%s", directory, dir_sep, name);
path = add_to_path(path, jarpath, false);
FREE_C_HEAP_ARRAY(char, jarpath, mtInternal);
}
}
FREE_C_HEAP_ARRAY(char, dbuf, mtInternal);
os::closedir(dir);
return path;
}
// Parses a memory size specification string.
static bool atomull(const char *s, julong* result) {
julong n = 0;
int args_read = sscanf(s, JULONG_FORMAT, &n);
if (args_read != 1) {
return false;
}
while (*s != '\0' && isdigit(*s)) {
s++;
}
// 4705540: illegal if more characters are found after the first non-digit
if (strlen(s) > 1) {
return false;
}
switch (*s) {
case 'T': case 't':
*result = n * G * K;
// Check for overflow.
if (*result/((julong)G * K) != n) return false;
return true;
case 'G': case 'g':
*result = n * G;
if (*result/G != n) return false;
return true;
case 'M': case 'm':
*result = n * M;
if (*result/M != n) return false;
return true;
case 'K': case 'k':
*result = n * K;
if (*result/K != n) return false;
return true;
case '\0':
*result = n;
return true;
default:
return false;
}
}
Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
if (size < min_size) return arg_too_small;
// Check that size will fit in a size_t (only relevant on 32-bit)
if (size > max_uintx) return arg_too_big;
return arg_in_range;
}
// Describe an argument out of range error
void Arguments::describe_range_error(ArgsRange errcode) {
switch(errcode) {
case arg_too_big:
jio_fprintf(defaultStream::error_stream(),
"The specified size exceeds the maximum "
"representable size.\n");
break;
case arg_too_small:
case arg_unreadable:
case arg_in_range:
// do nothing for now
break;
default:
ShouldNotReachHere();
}
}
static bool set_bool_flag(char* name, bool value, Flag::Flags origin) {
return CommandLineFlags::boolAtPut(name, &value, origin);
}
static bool set_fp_numeric_flag(char* name, char* value, Flag::Flags origin) {
double v;
if (sscanf(value, "%lf", &v) != 1) {
return false;
}
if (CommandLineFlags::doubleAtPut(name, &v, origin)) {
return true;
}
return false;
}
static bool set_numeric_flag(char* name, char* value, Flag::Flags origin) {
julong v;
intx intx_v;
bool is_neg = false;
// Check the sign first since atomull() parses only unsigned values.
if (*value == '-') {
if (!CommandLineFlags::intxAt(name, &intx_v)) {
return false;
}
value++;
is_neg = true;
}
if (!atomull(value, &v)) {
return false;
}
intx_v = (intx) v;
if (is_neg) {
intx_v = -intx_v;
}
if (CommandLineFlags::intxAtPut(name, &intx_v, origin)) {
return true;
}
uintx uintx_v = (uintx) v;
if (!is_neg && CommandLineFlags::uintxAtPut(name, &uintx_v, origin)) {
return true;
}
uint64_t uint64_t_v = (uint64_t) v;
if (!is_neg && CommandLineFlags::uint64_tAtPut(name, &uint64_t_v, origin)) {
return true;
}
return false;
}
static bool set_string_flag(char* name, const char* value, Flag::Flags origin) {
if (!CommandLineFlags::ccstrAtPut(name, &value, origin)) return false;
// Contract: CommandLineFlags always returns a pointer that needs freeing.
FREE_C_HEAP_ARRAY(char, value, mtInternal);
return true;
}
static bool append_to_string_flag(char* name, const char* new_value, Flag::Flags origin) {
const char* old_value = "";
if (!CommandLineFlags::ccstrAt(name, &old_value)) return false;
size_t old_len = old_value != NULL ? strlen(old_value) : 0;
size_t new_len = strlen(new_value);
const char* value;
char* free_this_too = NULL;
if (old_len == 0) {
value = new_value;
} else if (new_len == 0) {
value = old_value;
} else {
char* buf = NEW_C_HEAP_ARRAY(char, old_len + 1 + new_len + 1, mtInternal);
// each new setting adds another LINE to the switch:
sprintf(buf, "%s\n%s", old_value, new_value);
value = buf;
free_this_too = buf;
}
(void) CommandLineFlags::ccstrAtPut(name, &value, origin);
// CommandLineFlags always returns a pointer that needs freeing.
FREE_C_HEAP_ARRAY(char, value, mtInternal);
if (free_this_too != NULL) {
// CommandLineFlags made its own copy, so I must delete my own temp. buffer.
FREE_C_HEAP_ARRAY(char, free_this_too, mtInternal);
}
return true;
}
bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
// range of acceptable characters spelled out for portability reasons
#define NAME_RANGE "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
#define BUFLEN 255
char name[BUFLEN+1];
char dummy;
if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
return set_bool_flag(name, false, origin);
}
if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
return set_bool_flag(name, true, origin);
}
char punct;
if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
const char* value = strchr(arg, '=') + 1;
Flag* flag = Flag::find_flag(name, strlen(name));
if (flag != NULL && flag->is_ccstr()) {
if (flag->ccstr_accumulates()) {
return append_to_string_flag(name, value, origin);
} else {
if (value[0] == '\0') {
value = NULL;
}
return set_string_flag(name, value, origin);
}
}
}
if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
const char* value = strchr(arg, '=') + 1;
// -XX:Foo:=xxx will reset the string flag to the given value.
if (value[0] == '\0') {
value = NULL;
}
return set_string_flag(name, value, origin);
}
#define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"
#define SIGNED_NUMBER_RANGE "[-0123456789]"
#define NUMBER_RANGE "[0123456789]"
char value[BUFLEN + 1];
char value2[BUFLEN + 1];
if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
// Looks like a floating-point number -- try again with more lenient format string
if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
return set_fp_numeric_flag(name, value, origin);
}
}
#define VALUE_RANGE "[-kmgtKMGT0123456789]"
if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
return set_numeric_flag(name, value, origin);
}
return false;
}
void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
assert(bldarray != NULL, "illegal argument");
if (arg == NULL) {
return;
}
int new_count = *count + 1;
// expand the array and add arg to the last element
if (*bldarray == NULL) {
*bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtInternal);
} else {
*bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtInternal);
}
(*bldarray)[*count] = strdup(arg);
*count = new_count;
}
void Arguments::build_jvm_args(const char* arg) {
add_string(&_jvm_args_array, &_num_jvm_args, arg);
}
void Arguments::build_jvm_flags(const char* arg) {
add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
}
// utility function to return a string that concatenates all
// strings in a given char** array
const char* Arguments::build_resource_string(char** args, int count) {
if (args == NULL || count == 0) {
return NULL;
}
size_t length = strlen(args[0]) + 1; // add 1 for the null terminator
for (int i = 1; i < count; i++) {
length += strlen(args[i]) + 1; // add 1 for a space
}
char* s = NEW_RESOURCE_ARRAY(char, length);
strcpy(s, args[0]);
for (int j = 1; j < count; j++) {
strcat(s, " ");
strcat(s, args[j]);
}
return (const char*) s;
}
void Arguments::print_on(outputStream* st) {
st->print_cr("VM Arguments:");
if (num_jvm_flags() > 0) {
st->print("jvm_flags: "); print_jvm_flags_on(st);
}
if (num_jvm_args() > 0) {
st->print("jvm_args: "); print_jvm_args_on(st);
}
st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
if (_java_class_path != NULL) {
char* path = _java_class_path->value();
st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
}
st->print_cr("Launcher Type: %s", _sun_java_launcher);
}
void Arguments::print_jvm_flags_on(outputStream* st) {
if (_num_jvm_flags > 0) {
for (int i=0; i < _num_jvm_flags; i++) {
st->print("%s ", _jvm_flags_array[i]);
}
st->print_cr("");
}
}
void Arguments::print_jvm_args_on(outputStream* st) {
if (_num_jvm_args > 0) {
for (int i=0; i < _num_jvm_args; i++) {
st->print("%s ", _jvm_args_array[i]);
}
st->print_cr("");
}
}
bool Arguments::process_argument(const char* arg,
jboolean ignore_unrecognized, Flag::Flags origin) {
JDK_Version since = JDK_Version();
if (parse_argument(arg, origin) || ignore_unrecognized) {
return true;
}
bool has_plus_minus = (*arg == '+' || *arg == '-');
const char* const argname = has_plus_minus ? arg + 1 : arg;
if (is_newly_obsolete(arg, &since)) {
char version[256];
since.to_string(version, sizeof(version));
warning("ignoring option %s; support was removed in %s", argname, version);
return true;
}
// For locked flags, report a custom error message if available.
// Otherwise, report the standard unrecognized VM option.
size_t arg_len;
const char* equal_sign = strchr(argname, '=');
if (equal_sign == NULL) {
arg_len = strlen(argname);
} else {
arg_len = equal_sign - argname;
}
Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true);
if (found_flag != NULL) {
char locked_message_buf[BUFLEN];
found_flag->get_locked_message(locked_message_buf, BUFLEN);
if (strlen(locked_message_buf) == 0) {
if (found_flag->is_bool() && !has_plus_minus) {
jio_fprintf(defaultStream::error_stream(),
"Missing +/- setting for VM option '%s'\n", argname);
} else if (!found_flag->is_bool() && has_plus_minus) {
jio_fprintf(defaultStream::error_stream(),
"Unexpected +/- setting in VM option '%s'\n", argname);
} else {
jio_fprintf(defaultStream::error_stream(),
"Improperly specified VM option '%s'\n", argname);
}
} else {
jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
}
} else {
jio_fprintf(defaultStream::error_stream(),
"Unrecognized VM option '%s'\n", argname);
Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
if (fuzzy_matched != NULL) {
jio_fprintf(defaultStream::error_stream(),
"Did you mean '%s%s%s'?\n",
(fuzzy_matched->is_bool()) ? "(+/-)" : "",
fuzzy_matched->_name,
(fuzzy_matched->is_bool()) ? "" : "=<value>");
}
}
// allow for commandline "commenting out" options like -XX:#+Verbose
return arg[0] == '#';
}
bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
FILE* stream = fopen(file_name, "rb");
if (stream == NULL) {
if (should_exist) {
jio_fprintf(defaultStream::error_stream(),
"Could not open settings file %s\n", file_name);
return false;
} else {
return true;
}
}
char token[1024];
int pos = 0;
bool in_white_space = true;
bool in_comment = false;
bool in_quote = false;
char quote_c = 0;
bool result = true;
int c = getc(stream);
while(c != EOF && pos < (int)(sizeof(token)-1)) {
if (in_white_space) {
if (in_comment) {
if (c == '\n') in_comment = false;
} else {
if (c == '#') in_comment = true;
else if (!isspace(c)) {
in_white_space = false;
token[pos++] = c;
}
}
} else {
if (c == '\n' || (!in_quote && isspace(c))) {
// token ends at newline, or at unquoted whitespace
// this allows a way to include spaces in string-valued options
token[pos] = '\0';
logOption(token);
result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
build_jvm_flags(token);
pos = 0;
in_white_space = true;
in_quote = false;
} else if (!in_quote && (c == '\'' || c == '"')) {
in_quote = true;
quote_c = c;
} else if (in_quote && (c == quote_c)) {
in_quote = false;
} else {
token[pos++] = c;
}
}
c = getc(stream);
}
if (pos > 0) {
token[pos] = '\0';
result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
build_jvm_flags(token);
}
fclose(stream);
return result;
}
//=============================================================================================================
// Parsing of properties (-D)
const char* Arguments::get_property(const char* key) {
return PropertyList_get_value(system_properties(), key);
}
bool Arguments::add_property(const char* prop) {
const char* eq = strchr(prop, '=');
char* key;
// ns must be static--its address may be stored in a SystemProperty object.
const static char ns[1] = {0};
char* value = (char *)ns;
size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);
key = AllocateHeap(key_len + 1, mtInternal);
strncpy(key, prop, key_len);
key[key_len] = '\0';
if (eq != NULL) {
size_t value_len = strlen(prop) - key_len - 1;
value = AllocateHeap(value_len + 1, mtInternal);
strncpy(value, &prop[key_len + 1], value_len + 1);
}
if (strcmp(key, "java.compiler") == 0) {
process_java_compiler_argument(value);
FreeHeap(key);
if (eq != NULL) {
FreeHeap(value);
}
return true;
} else if (strcmp(key, "sun.java.command") == 0) {
_java_command = value;
// Record value in Arguments, but let it get passed to Java.
} else if (strcmp(key, "sun.java.launcher.pid") == 0) {
// launcher.pid property is private and is processed
// in process_sun_java_launcher_properties();
// the sun.java.launcher property is passed on to the java application
FreeHeap(key);
if (eq != NULL) {
FreeHeap(value);
}
return true;
} else if (strcmp(key, "java.vendor.url.bug") == 0) {
// save it in _java_vendor_url_bug, so JVM fatal error handler can access
// its value without going through the property list or making a Java call.
_java_vendor_url_bug = value;
} else if (strcmp(key, "sun.boot.library.path") == 0) {
PropertyList_unique_add(&_system_properties, key, value, true);
return true;
}
// Create new property and add at the end of the list
PropertyList_unique_add(&_system_properties, key, value);
return true;
}
//===========================================================================================================
// Setting int/mixed/comp mode flags
void Arguments::set_mode_flags(Mode mode) {
// Set up default values for all flags.
// If you add a flag to any of the branches below,
// add a default value for it here.
set_java_compiler(false);
_mode = mode;
// Ensure Agent_OnLoad has the correct initial values.
// This may not be the final mode; mode may change later in onload phase.
PropertyList_unique_add(&_system_properties, "java.vm.info",
(char*)VM_Version::vm_info_string(), false);
UseInterpreter = true;
UseCompiler = true;
UseLoopCounter = true;
#ifndef ZERO
// Turn these off for mixed and comp. Leave them on for Zero.
if (FLAG_IS_DEFAULT(UseFastAccessorMethods)) {
UseFastAccessorMethods = (mode == _int);
}
if (FLAG_IS_DEFAULT(UseFastEmptyMethods)) {
UseFastEmptyMethods = (mode == _int);
}
#endif
// Default values may be platform/compiler dependent -
// use the saved values
ClipInlining = Arguments::_ClipInlining;
AlwaysCompileLoopMethods = Arguments::_AlwaysCompileLoopMethods;
UseOnStackReplacement = Arguments::_UseOnStackReplacement;
BackgroundCompilation = Arguments::_BackgroundCompilation;
// Change from defaults based on mode
switch (mode) {
default:
ShouldNotReachHere();
break;
case _int:
UseCompiler = false;
UseLoopCounter = false;
AlwaysCompileLoopMethods = false;
UseOnStackReplacement = false;
break;
case _mixed:
// same as default
break;
case _comp:
UseInterpreter = false;
BackgroundCompilation = false;
ClipInlining = false;
// Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
// We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
// compile a level 4 (C2) and then continue executing it.
if (TieredCompilation) {
Tier3InvokeNotifyFreqLog = 0;
Tier4InvocationThreshold = 0;
}
break;
}
}
#if defined(COMPILER2) || defined(_LP64) || !INCLUDE_CDS
// Conflict: required to use shared spaces (-Xshare:on), but
// incompatible command line options were chosen.
static void no_shared_spaces() {
if (RequireSharedSpaces) {
jio_fprintf(defaultStream::error_stream(),
"Class data sharing is inconsistent with other specified options.\n");
vm_exit_during_initialization("Unable to use shared archive.", NULL);
} else {
FLAG_SET_DEFAULT(UseSharedSpaces, false);
}
}
#endif
void Arguments::set_tiered_flags() {
// With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
}
if (CompilationPolicyChoice < 2) {
vm_exit_during_initialization(
"Incompatible compilation policy selected", NULL);
}
// Increase the code cache size - tiered compiles a lot more.
if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
FLAG_SET_DEFAULT(ReservedCodeCacheSize, ReservedCodeCacheSize * 5);
}
if (!UseInterpreter) { // -Xcomp
Tier3InvokeNotifyFreqLog = 0;
Tier4InvocationThreshold = 0;
}
}
#if INCLUDE_ALL_GCS
static void disable_adaptive_size_policy(const char* collector_name) {
if (UseAdaptiveSizePolicy) {
if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
warning("disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
collector_name);
}
FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
}
}
void Arguments::set_parnew_gc_flags() {
assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
"control point invariant");
assert(UseParNewGC, "Error");
// Turn off AdaptiveSizePolicy for parnew until it is complete.
disable_adaptive_size_policy("UseParNewGC");
if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
} else if (ParallelGCThreads == 0) {
jio_fprintf(defaultStream::error_stream(),
"The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
vm_exit(1);
}
// By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
// these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
// we set them to 1024 and 1024.
// See CR 6362902.
if (FLAG_IS_DEFAULT(YoungPLABSize)) {
FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
}
if (FLAG_IS_DEFAULT(OldPLABSize)) {
FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
}
// AlwaysTenure flag should make ParNew promote all at first collection.
// See CR 6362902.
if (AlwaysTenure) {
FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0);
}
// When using compressed oops, we use local overflow stacks,
// rather than using a global overflow list chained through
// the klass word of the object's pre-image.
if (UseCompressedOops && !ParGCUseLocalOverflow) {
if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
}
FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
}
assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
}
// Adjust some sizes to suit CMS and/or ParNew needs; these work well on
// sparc/solaris for certain applications, but would gain from
// further optimization and tuning efforts, and would almost
// certainly gain from analysis of platform and environment.
void Arguments::set_cms_and_parnew_gc_flags() {
assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
assert(UseConcMarkSweepGC, "CMS is expected to be on here");
// If we are using CMS, we prefer to UseParNewGC,
// unless explicitly forbidden.
if (FLAG_IS_DEFAULT(UseParNewGC)) {
FLAG_SET_ERGO(bool, UseParNewGC, true);
}
// Turn off AdaptiveSizePolicy by default for cms until it is complete.
disable_adaptive_size_policy("UseConcMarkSweepGC");
// In either case, adjust ParallelGCThreads and/or UseParNewGC
// as needed.
if (UseParNewGC) {
set_parnew_gc_flags();
}
size_t max_heap = align_size_down(MaxHeapSize,
CardTableRS::ct_max_alignment_constraint());
// Now make adjustments for CMS
intx tenuring_default = (intx)6;
size_t young_gen_per_worker = CMSYoungGenPerWorker;
// Preferred young gen size for "short" pauses:
// upper bound depends on # of threads and NewRatio.
const uintx parallel_gc_threads =
(ParallelGCThreads == 0 ? 1 : ParallelGCThreads);
const size_t preferred_max_new_size_unaligned =
MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * parallel_gc_threads));
size_t preferred_max_new_size =
align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
// Unless explicitly requested otherwise, size young gen
// for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
// If either MaxNewSize or NewRatio is set on the command line,
// assume the user is trying to set the size of the young gen.
if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
// Set MaxNewSize to our calculated preferred_max_new_size unless
// NewSize was set on the command line and it is larger than
// preferred_max_new_size.
if (!FLAG_IS_DEFAULT(NewSize)) { // NewSize explicitly set at command-line
FLAG_SET_ERGO(uintx, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
} else {
FLAG_SET_ERGO(uintx, MaxNewSize, preferred_max_new_size);
}
if (PrintGCDetails && Verbose) {
// Too early to use gclog_or_tty
tty->print_cr("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
}
// Code along this path potentially sets NewSize and OldSize
if (PrintGCDetails && Verbose) {
// Too early to use gclog_or_tty
tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
" initial_heap_size: " SIZE_FORMAT
" max_heap: " SIZE_FORMAT,
min_heap_size(), InitialHeapSize, max_heap);
}
size_t min_new = preferred_max_new_size;
if (FLAG_IS_CMDLINE(NewSize)) {
min_new = NewSize;
}
if (max_heap > min_new && min_heap_size() > min_new) {
// Unless explicitly requested otherwise, make young gen
// at least min_new, and at most preferred_max_new_size.
if (FLAG_IS_DEFAULT(NewSize)) {
FLAG_SET_ERGO(uintx, NewSize, MAX2(NewSize, min_new));
FLAG_SET_ERGO(uintx, NewSize, MIN2(preferred_max_new_size, NewSize));
if (PrintGCDetails && Verbose) {
// Too early to use gclog_or_tty
tty->print_cr("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
}
}
// Unless explicitly requested otherwise, size old gen
// so it's NewRatio x of NewSize.
if (FLAG_IS_DEFAULT(OldSize)) {
if (max_heap > NewSize) {
FLAG_SET_ERGO(uintx, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
if (PrintGCDetails && Verbose) {
// Too early to use gclog_or_tty
tty->print_cr("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
}
}
}
}
}
// Unless explicitly requested otherwise, definitely
// promote all objects surviving "tenuring_default" scavenges.
if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
FLAG_IS_DEFAULT(SurvivorRatio)) {
FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
}
// If we decided above (or user explicitly requested)
// `promote all' (via MaxTenuringThreshold := 0),
// prefer minuscule survivor spaces so as not to waste
// space for (non-existent) survivors
if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
}
// If OldPLABSize is set and CMSParPromoteBlocksToClaim is not,
// set CMSParPromoteBlocksToClaim equal to OldPLABSize.
// This is done in order to make ParNew+CMS configuration to work
// with YoungPLABSize and OldPLABSize options.
// See CR 6362902.
if (!FLAG_IS_DEFAULT(OldPLABSize)) {
if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {
// OldPLABSize is not the default value but CMSParPromoteBlocksToClaim
// is. In this situtation let CMSParPromoteBlocksToClaim follow
// the value (either from the command line or ergonomics) of
// OldPLABSize. Following OldPLABSize is an ergonomics decision.
FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, OldPLABSize);
} else {
// OldPLABSize and CMSParPromoteBlocksToClaim are both set.
// CMSParPromoteBlocksToClaim is a collector-specific flag, so
// we'll let it to take precedence.
jio_fprintf(defaultStream::error_stream(),
"Both OldPLABSize and CMSParPromoteBlocksToClaim"
" options are specified for the CMS collector."
" CMSParPromoteBlocksToClaim will take precedence.\n");
}
}
if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
// OldPLAB sizing manually turned off: Use a larger default setting,
// unless it was manually specified. This is because a too-low value
// will slow down scavenges.
if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {
FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, 50); // default value before 6631166
}
}
// Overwrite OldPLABSize which is the variable we will internally use everywhere.
FLAG_SET_ERGO(uintx, OldPLABSize, CMSParPromoteBlocksToClaim);
// If either of the static initialization defaults have changed, note this
// modification.
if (!FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
}
if (PrintGCDetails && Verbose) {
tty->print_cr("MarkStackSize: %uk MarkStackSizeMax: %uk",
MarkStackSize / K, MarkStackSizeMax / K);
tty->print_cr("ConcGCThreads: %u", ConcGCThreads);
}
}
#endif // INCLUDE_ALL_GCS
void set_object_alignment() {
// Object alignment.
assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
MinObjAlignmentInBytes = ObjectAlignmentInBytes;
assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
MinObjAlignment = MinObjAlignmentInBytes / HeapWordSize;
assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
LogMinObjAlignmentInBytes = exact_log2(ObjectAlignmentInBytes);
LogMinObjAlignment = LogMinObjAlignmentInBytes - LogHeapWordSize;
// Oop encoding heap max
OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
#if INCLUDE_ALL_GCS
// Set CMS global values
CompactibleFreeListSpace::set_cms_values();
#endif // INCLUDE_ALL_GCS
}
bool verify_object_alignment() {
// Object alignment.
if (!is_power_of_2(ObjectAlignmentInBytes)) {
jio_fprintf(defaultStream::error_stream(),
"error: ObjectAlignmentInBytes=%d must be power of 2\n",
(int)ObjectAlignmentInBytes);
return false;
}
if ((int)ObjectAlignmentInBytes < BytesPerLong) {
jio_fprintf(defaultStream::error_stream(),
"error: ObjectAlignmentInBytes=%d must be greater or equal %d\n",
(int)ObjectAlignmentInBytes, BytesPerLong);
return false;
}
// It does not make sense to have big object alignment
// since a space lost due to alignment will be greater
// then a saved space from compressed oops.
if ((int)ObjectAlignmentInBytes > 256) {
jio_fprintf(defaultStream::error_stream(),
"error: ObjectAlignmentInBytes=%d must not be greater than 256\n",
(int)ObjectAlignmentInBytes);
return false;
}
// In case page size is very small.
if ((int)ObjectAlignmentInBytes >= os::vm_page_size()) {
jio_fprintf(defaultStream::error_stream(),
"error: ObjectAlignmentInBytes=%d must be less than page size %d\n",
(int)ObjectAlignmentInBytes, os::vm_page_size());
return false;
}
return true;
}
uintx Arguments::max_heap_for_compressed_oops() {
// Avoid sign flip.
assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
// We need to fit both the NULL page and the heap into the memory budget, while
// keeping alignment constraints of the heap. To guarantee the latter, as the
// NULL page is located before the heap, we pad the NULL page to the conservative
// maximum alignment that the GC may ever impose upon the heap.
size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
_conservative_max_heap_alignment);
LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
NOT_LP64(ShouldNotReachHere(); return 0);
}
bool Arguments::should_auto_select_low_pause_collector() {
if (UseAutoGCSelectPolicy &&
!FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
(MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
if (PrintGCDetails) {
// Cannot use gclog_or_tty yet.
tty->print_cr("Automatic selection of the low pause collector"
" based on pause goal of %d (ms)", MaxGCPauseMillis);
}
return true;
}
return false;
}
void Arguments::set_use_compressed_oops() {
#ifndef ZERO
#ifdef _LP64
// MaxHeapSize is not set up properly at this point, but
// the only value that can override MaxHeapSize if we are
// to use UseCompressedOops is InitialHeapSize.
size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
if (max_heap_size <= max_heap_for_compressed_oops()) {
#if !defined(COMPILER1) || defined(TIERED)
if (FLAG_IS_DEFAULT(UseCompressedOops)) {
FLAG_SET_ERGO(bool, UseCompressedOops, true);
}
#endif
#ifdef _WIN64
if (UseLargePages && UseCompressedOops) {
// Cannot allocate guard pages for implicit checks in indexed addressing
// mode, when large pages are specified on windows.
// This flag could be switched ON if narrow oop base address is set to 0,
// see code in Universe::initialize_heap().
Universe::set_narrow_oop_use_implicit_null_checks(false);
}
#endif // _WIN64
} else {
if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
warning("Max heap size too large for Compressed Oops");
FLAG_SET_DEFAULT(UseCompressedOops, false);
FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
}
}
#endif // _LP64
#endif // ZERO
}
// NOTE: set_use_compressed_klass_ptrs() must be called after calling
// set_use_compressed_oops().
void Arguments::set_use_compressed_klass_ptrs() {
#ifndef ZERO
#ifdef _LP64
// UseCompressedOops must be on for UseCompressedClassPointers to be on.
if (!UseCompressedOops) {
if (UseCompressedClassPointers) {
warning("UseCompressedClassPointers requires UseCompressedOops");
}
FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
} else {
// Turn on UseCompressedClassPointers too
if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
}
// Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
if (UseCompressedClassPointers) {
if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
}
}
}
#endif // _LP64
#endif // !ZERO
}
void Arguments::set_conservative_max_heap_alignment() {
// The conservative maximum required alignment for the heap is the maximum of
// the alignments imposed by several sources: any requirements from the heap
// itself, the collector policy and the maximum page size we may run the VM
// with.
size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
#if INCLUDE_ALL_GCS
if (UseParallelGC) {
heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
} else if (UseG1GC) {
heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
}
#endif // INCLUDE_ALL_GCS
_conservative_max_heap_alignment = MAX3(heap_alignment, os::max_page_size(),
CollectorPolicy::compute_heap_alignment());
}
void Arguments::set_ergonomics_flags() {
if (os::is_server_class_machine()) {
// If no other collector is requested explicitly,
// let the VM select the collector based on
// machine class and automatic selection policy.
if (!UseSerialGC &&
!UseConcMarkSweepGC &&
!UseG1GC &&
!UseParNewGC &&
FLAG_IS_DEFAULT(UseParallelGC)) {
if (should_auto_select_low_pause_collector()) {
FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
} else {
FLAG_SET_ERGO(bool, UseParallelGC, true);
}
}
}
#ifdef COMPILER2
// Shared spaces work fine with other GCs but causes bytecode rewriting
// to be disabled, which hurts interpreter performance and decreases
// server performance. When -server is specified, keep the default off
// unless it is asked for. Future work: either add bytecode rewriting
// at link time, or rewrite bytecodes in non-shared methods.
if (!DumpSharedSpaces && !RequireSharedSpaces &&
(FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
no_shared_spaces();
}
#endif
set_conservative_max_heap_alignment();
#ifndef ZERO
#ifdef _LP64
set_use_compressed_oops();
// set_use_compressed_klass_ptrs() must be called after calling
// set_use_compressed_oops().
set_use_compressed_klass_ptrs();
// Also checks that certain machines are slower with compressed oops
// in vm_version initialization code.
#endif // _LP64
#endif // !ZERO
}
void Arguments::set_parallel_gc_flags() {
assert(UseParallelGC || UseParallelOldGC, "Error");
// Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
FLAG_SET_DEFAULT(UseParallelOldGC, true);
}
FLAG_SET_DEFAULT(UseParallelGC, true);
// If no heap maximum was requested explicitly, use some reasonable fraction
// of the physical memory, up to a maximum of 1GB.
FLAG_SET_DEFAULT(ParallelGCThreads,
Abstract_VM_Version::parallel_worker_threads());
if (ParallelGCThreads == 0) {
jio_fprintf(defaultStream::error_stream(),
"The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
vm_exit(1);
}
// If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
// SurvivorRatio has been set, reset their default values to SurvivorRatio +
// 2. By doing this we make SurvivorRatio also work for Parallel Scavenger.
// See CR 6362902 for details.
if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
}
if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
}
}
if (UseParallelOldGC) {
// Par compact uses lower default values since they are treated as
// minimums. These are different defaults because of the different
// interpretation and are not ergonomically set.
if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
}
}
}
void Arguments::set_g1_gc_flags() {
assert(UseG1GC, "Error");
#ifdef COMPILER1
FastTLABRefill = false;
#endif
FLAG_SET_DEFAULT(ParallelGCThreads,
Abstract_VM_Version::parallel_worker_threads());
if (ParallelGCThreads == 0) {
FLAG_SET_DEFAULT(ParallelGCThreads,
Abstract_VM_Version::parallel_worker_threads());
}
// MarkStackSize will be set (if it hasn't been set by the user)
// when concurrent marking is initialized.
// Its value will be based upon the number of parallel marking threads.
// But we do set the maximum mark stack size here.
if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
}
if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
// In G1, we want the default GC overhead goal to be higher than
// say in PS. So we set it here to 10%. Otherwise the heap might
// be expanded more aggressively than we would like it to. In
// fact, even 10% seems to not be high enough in some cases
// (especially small GC stress tests that the main thing they do
// is allocation). We might consider increase it further.
FLAG_SET_DEFAULT(GCTimeRatio, 9);
}
if (PrintGCDetails && Verbose) {
tty->print_cr("MarkStackSize: %uk MarkStackSizeMax: %uk",
MarkStackSize / K, MarkStackSizeMax / K);
tty->print_cr("ConcGCThreads: %u", ConcGCThreads);
}
}
julong Arguments::limit_by_allocatable_memory(julong limit) {
julong max_allocatable;
julong result = limit;
if (os::has_allocatable_memory_limit(&max_allocatable)) {
result = MIN2(result, max_allocatable / MaxVirtMemFraction);
}
return result;
}
void Arguments::set_heap_size() {
if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
// Deprecated flag
FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
}
const julong phys_mem =
FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
: (julong)MaxRAM;
// If the maximum heap size has not been set with -Xmx,
// then set it as fraction of the size of physical memory,
// respecting the maximum and minimum sizes of the heap.
if (FLAG_IS_DEFAULT(MaxHeapSize)) {
julong reasonable_max = phys_mem / MaxRAMFraction;
if (phys_mem <= MaxHeapSize * MinRAMFraction) {
// Small physical memory, so use a minimum fraction of it for the heap
reasonable_max = phys_mem / MinRAMFraction;
} else {
// Not-small physical memory, so require a heap at least
// as large as MaxHeapSize
reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
}
if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
// Limit the heap size to ErgoHeapSizeLimit
reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
}
if (UseCompressedOops) {
// Limit the heap size to the maximum possible when using compressed oops
julong max_coop_heap = (julong)max_heap_for_compressed_oops();
if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
// Heap should be above HeapBaseMinAddress to get zero based compressed oops
// but it should be not less than default MaxHeapSize.
max_coop_heap -= HeapBaseMinAddress;
}
reasonable_max = MIN2(reasonable_max, max_coop_heap);
}
reasonable_max = limit_by_allocatable_memory(reasonable_max);
if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
// An initial heap size was specified on the command line,
// so be sure that the maximum size is consistent. Done
// after call to limit_by_allocatable_memory because that
// method might reduce the allocation size.
reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
}
if (PrintGCDetails && Verbose) {
// Cannot use gclog_or_tty yet.
tty->print_cr(" Maximum heap size " SIZE_FORMAT, reasonable_max);
}
FLAG_SET_ERGO(uintx, MaxHeapSize, (uintx)reasonable_max);
}
// If the minimum or initial heap_size have not been set or requested to be set
// ergonomically, set them accordingly.
if (InitialHeapSize == 0 || min_heap_size() == 0) {
julong reasonable_minimum = (julong)(OldSize + NewSize);
reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
if (InitialHeapSize == 0) {
julong reasonable_initial = phys_mem / InitialRAMFraction;
reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
if (PrintGCDetails && Verbose) {
// Cannot use gclog_or_tty yet.
tty->print_cr(" Initial heap size " SIZE_FORMAT, (uintx)reasonable_initial);
}
FLAG_SET_ERGO(uintx, InitialHeapSize, (uintx)reasonable_initial);
}
// If the minimum heap size has not been set (via -Xms),
// synchronize with InitialHeapSize to avoid errors with the default value.
if (min_heap_size() == 0) {
set_min_heap_size(MIN2((uintx)reasonable_minimum, InitialHeapSize));
if (PrintGCDetails && Verbose) {
// Cannot use gclog_or_tty yet.
tty->print_cr(" Minimum heap size " SIZE_FORMAT, min_heap_size());
}
}
}
}
// This must be called after ergonomics because we want bytecode rewriting
// if the server compiler is used, or if UseSharedSpaces is disabled.
void Arguments::set_bytecode_flags() {
// Better not attempt to store into a read-only space.
if (UseSharedSpaces) {
FLAG_SET_DEFAULT(RewriteBytecodes, false);
FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
}
if (!RewriteBytecodes) {
FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
}
}
// Aggressive optimization flags -XX:+AggressiveOpts
void Arguments::set_aggressive_opts_flags() {
#ifdef COMPILER2
if (AggressiveUnboxing) {
if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
FLAG_SET_DEFAULT(EliminateAutoBox, true);
} else if (!EliminateAutoBox) {
// warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
AggressiveUnboxing = false;
}
if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
} else if (!DoEscapeAnalysis) {
// warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
AggressiveUnboxing = false;
}
}
if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
FLAG_SET_DEFAULT(EliminateAutoBox, true);
}
if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
}
// Feed the cache size setting into the JDK
char buffer[1024];
sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
add_property(buffer);
}
if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
}
#endif
if (AggressiveOpts) {
// Sample flag setting code
// if (FLAG_IS_DEFAULT(EliminateZeroing)) {
// FLAG_SET_DEFAULT(EliminateZeroing, true);
// }
}
}
//===========================================================================================================
// Parsing of java.compiler property
void Arguments::process_java_compiler_argument(char* arg) {
// For backwards compatibility, Djava.compiler=NONE or ""
// causes us to switch to -Xint mode UNLESS -Xdebug
// is also specified.
if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
set_java_compiler(true); // "-Djava.compiler[=...]" most recently seen.
}
}
void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
_sun_java_launcher = strdup(launcher);
if (strcmp("gamma", _sun_java_launcher) == 0) {
_created_by_gamma_launcher = true;
}
}
bool Arguments::created_by_java_launcher() {
assert(_sun_java_launcher != NULL, "property must have value");
return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
}
bool Arguments::created_by_gamma_launcher() {
return _created_by_gamma_launcher;
}
//===========================================================================================================
// Parsing of main arguments
bool Arguments::verify_interval(uintx val, uintx min,
uintx max, const char* name) {
// Returns true iff value is in the inclusive interval [min..max]
// false, otherwise.
if (val >= min && val <= max) {
return true;
}
jio_fprintf(defaultStream::error_stream(),
"%s of " UINTX_FORMAT " is invalid; must be between " UINTX_FORMAT
" and " UINTX_FORMAT "\n",
name, val, min, max);
return false;
}
bool Arguments::verify_min_value(intx val, intx min, const char* name) {
// Returns true if given value is at least specified min threshold
// false, otherwise.
if (val >= min ) {
return true;
}
jio_fprintf(defaultStream::error_stream(),
"%s of " INTX_FORMAT " is invalid; must be at least " INTX_FORMAT "\n",
name, val, min);
return false;
}
bool Arguments::verify_percentage(uintx value, const char* name) {
if (value <= 100) {
return true;
}
jio_fprintf(defaultStream::error_stream(),
"%s of " UINTX_FORMAT " is invalid; must be between 0 and 100\n",
name, value);
return false;
}
#if !INCLUDE_ALL_GCS
#ifdef ASSERT
static bool verify_serial_gc_flags() {
return (UseSerialGC &&
!(UseParNewGC || (UseConcMarkSweepGC || CMSIncrementalMode) || UseG1GC ||
UseParallelGC || UseParallelOldGC));
}
#endif // ASSERT
#endif // INCLUDE_ALL_GCS
// check if do gclog rotation
// +UseGCLogFileRotation is a must,
// no gc log rotation when log file not supplied or
// NumberOfGCLogFiles is 0, or GCLogFileSize is 0
void check_gclog_consistency() {
if (UseGCLogFileRotation) {
if ((Arguments::gc_log_filename() == NULL) ||
(NumberOfGCLogFiles == 0) ||
(GCLogFileSize == 0)) {
jio_fprintf(defaultStream::output_stream(),
"To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=
Other Java examples (source code examples)Here is a short list of links related to this Java arguments.cpp source code file: |
| ... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.