Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/runtime/arguments.cpp
48785 views
/*1* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/classLoader.hpp"26#include "classfile/javaAssertions.hpp"27#include "classfile/symbolTable.hpp"28#include "compiler/compilerOracle.hpp"29#include "memory/allocation.inline.hpp"30#include "memory/cardTableRS.hpp"31#include "memory/genCollectedHeap.hpp"32#include "memory/referenceProcessor.hpp"33#include "memory/universe.inline.hpp"34#include "oops/oop.inline.hpp"35#include "prims/jvmtiExport.hpp"36#include "runtime/arguments.hpp"37#include "runtime/arguments_ext.hpp"38#include "runtime/globals_extension.hpp"39#include "runtime/java.hpp"40#include "services/management.hpp"41#include "services/memTracker.hpp"42#include "utilities/defaultStream.hpp"43#include "utilities/macros.hpp"44#include "utilities/stringUtils.hpp"45#include "utilities/taskqueue.hpp"46#if INCLUDE_JFR47#include "jfr/jfr.hpp"48#endif49#ifdef TARGET_OS_FAMILY_linux50# include "os_linux.inline.hpp"51#endif52#ifdef TARGET_OS_FAMILY_solaris53# include "os_solaris.inline.hpp"54#endif55#ifdef TARGET_OS_FAMILY_windows56# include "os_windows.inline.hpp"57#endif58#ifdef TARGET_OS_FAMILY_aix59# include "os_aix.inline.hpp"60#endif61#ifdef TARGET_OS_FAMILY_bsd62# include "os_bsd.inline.hpp"63#endif64#if INCLUDE_ALL_GCS65#include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"66#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"67#include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"68#endif // INCLUDE_ALL_GCS6970// Note: This is a special bug reporting site for the JVM71#ifdef VENDOR_URL_VM_BUG72# define DEFAULT_VENDOR_URL_BUG VENDOR_URL_VM_BUG73#else74# define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"75#endif76#define DEFAULT_JAVA_LAUNCHER "generic"7778// Disable options not supported in this release, with a warning if they79// were explicitly requested on the command-line80#define UNSUPPORTED_OPTION(opt, description) \81do { \82if (opt) { \83if (FLAG_IS_CMDLINE(opt)) { \84warning(description " is disabled in this release."); \85} \86FLAG_SET_DEFAULT(opt, false); \87} \88} while(0)8990#define UNSUPPORTED_GC_OPTION(gc) \91do { \92if (gc) { \93if (FLAG_IS_CMDLINE(gc)) { \94warning(#gc " is not supported in this VM. Using Serial GC."); \95} \96FLAG_SET_DEFAULT(gc, false); \97} \98} while(0)99100char** Arguments::_jvm_flags_array = NULL;101int Arguments::_num_jvm_flags = 0;102char** Arguments::_jvm_args_array = NULL;103int Arguments::_num_jvm_args = 0;104char* Arguments::_java_command = NULL;105SystemProperty* Arguments::_system_properties = NULL;106const char* Arguments::_gc_log_filename = NULL;107bool Arguments::_has_profile = false;108size_t Arguments::_conservative_max_heap_alignment = 0;109uintx Arguments::_min_heap_size = 0;110uintx Arguments::_min_heap_free_ratio = 0;111uintx Arguments::_max_heap_free_ratio = 0;112Arguments::Mode Arguments::_mode = _mixed;113bool Arguments::_java_compiler = false;114bool Arguments::_xdebug_mode = false;115const char* Arguments::_java_vendor_url_bug = DEFAULT_VENDOR_URL_BUG;116const char* Arguments::_sun_java_launcher = DEFAULT_JAVA_LAUNCHER;117int Arguments::_sun_java_launcher_pid = -1;118bool Arguments::_created_by_gamma_launcher = false;119120// These parameters are reset in method parse_vm_init_args(JavaVMInitArgs*)121bool Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;122bool Arguments::_UseOnStackReplacement = UseOnStackReplacement;123bool Arguments::_BackgroundCompilation = BackgroundCompilation;124bool Arguments::_ClipInlining = ClipInlining;125126char* Arguments::SharedArchivePath = NULL;127128AgentLibraryList Arguments::_libraryList;129AgentLibraryList Arguments::_agentList;130131abort_hook_t Arguments::_abort_hook = NULL;132exit_hook_t Arguments::_exit_hook = NULL;133vfprintf_hook_t Arguments::_vfprintf_hook = NULL;134135136SystemProperty *Arguments::_java_ext_dirs = NULL;137SystemProperty *Arguments::_java_endorsed_dirs = NULL;138SystemProperty *Arguments::_sun_boot_library_path = NULL;139SystemProperty *Arguments::_java_library_path = NULL;140SystemProperty *Arguments::_java_home = NULL;141SystemProperty *Arguments::_java_class_path = NULL;142SystemProperty *Arguments::_sun_boot_class_path = NULL;143144char* Arguments::_meta_index_path = NULL;145char* Arguments::_meta_index_dir = NULL;146147// Check if head of 'option' matches 'name', and sets 'tail' remaining part of option string148149static bool match_option(const JavaVMOption *option, const char* name,150const char** tail) {151int len = (int)strlen(name);152if (strncmp(option->optionString, name, len) == 0) {153*tail = option->optionString + len;154return true;155} else {156return false;157}158}159160#if INCLUDE_JFR161// return true on failure162static bool match_jfr_option(const JavaVMOption** option) {163assert((*option)->optionString != NULL, "invariant");164char* tail = NULL;165if (match_option(*option, "-XX:StartFlightRecording", (const char**)&tail)) {166return Jfr::on_start_flight_recording_option(option, tail);167} else if (match_option(*option, "-XX:FlightRecorderOptions", (const char**)&tail)) {168return Jfr::on_flight_recorder_option(option, tail);169}170return false;171}172#endif173174static void logOption(const char* opt) {175if (PrintVMOptions) {176jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);177}178}179180// Process java launcher properties.181void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {182// See if sun.java.launcher or sun.java.launcher.pid is defined.183// Must do this before setting up other system properties,184// as some of them may depend on launcher type.185for (int index = 0; index < args->nOptions; index++) {186const JavaVMOption* option = args->options + index;187const char* tail;188189if (match_option(option, "-Dsun.java.launcher=", &tail)) {190process_java_launcher_argument(tail, option->extraInfo);191continue;192}193if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {194_sun_java_launcher_pid = atoi(tail);195continue;196}197}198}199200// Initialize system properties key and value.201void Arguments::init_system_properties() {202203PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",204"Java Virtual Machine Specification", false));205PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(), false));206PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(), false));207PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(), true));208209// following are JVMTI agent writeable properties.210// Properties values are set to NULL and they are211// os specific they are initialized in os::init_system_properties_values().212_java_ext_dirs = new SystemProperty("java.ext.dirs", NULL, true);213_java_endorsed_dirs = new SystemProperty("java.endorsed.dirs", NULL, true);214_sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL, true);215_java_library_path = new SystemProperty("java.library.path", NULL, true);216_java_home = new SystemProperty("java.home", NULL, true);217_sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL, true);218219_java_class_path = new SystemProperty("java.class.path", "", true);220221// Add to System Property list.222PropertyList_add(&_system_properties, _java_ext_dirs);223PropertyList_add(&_system_properties, _java_endorsed_dirs);224PropertyList_add(&_system_properties, _sun_boot_library_path);225PropertyList_add(&_system_properties, _java_library_path);226PropertyList_add(&_system_properties, _java_home);227PropertyList_add(&_system_properties, _java_class_path);228PropertyList_add(&_system_properties, _sun_boot_class_path);229230// Set OS specific system properties values231os::init_system_properties_values();232}233234235// Update/Initialize System properties after JDK version number is known236void Arguments::init_version_specific_system_properties() {237enum { bufsz = 16 };238char buffer[bufsz];239const char* spec_vendor = "Sun Microsystems Inc.";240uint32_t spec_version = 0;241242if (JDK_Version::is_gte_jdk17x_version()) {243spec_vendor = "Oracle Corporation";244spec_version = JDK_Version::current().major_version();245}246jio_snprintf(buffer, bufsz, "1." UINT32_FORMAT, spec_version);247248PropertyList_add(&_system_properties,249new SystemProperty("java.vm.specification.vendor", spec_vendor, false));250PropertyList_add(&_system_properties,251new SystemProperty("java.vm.specification.version", buffer, false));252PropertyList_add(&_system_properties,253new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(), false));254}255256/**257* Provide a slightly more user-friendly way of eliminating -XX flags.258* When a flag is eliminated, it can be added to this list in order to259* continue accepting this flag on the command-line, while issuing a warning260* and ignoring the value. Once the JDK version reaches the 'accept_until'261* limit, we flatly refuse to admit the existence of the flag. This allows262* a flag to die correctly over JDK releases using HSX.263*/264typedef struct {265const char* name;266JDK_Version obsoleted_in; // when the flag went away267JDK_Version accept_until; // which version to start denying the existence268} ObsoleteFlag;269270static ObsoleteFlag obsolete_jvm_flags[] = {271{ "UseTrainGC", JDK_Version::jdk(5), JDK_Version::jdk(7) },272{ "UseSpecialLargeObjectHandling", JDK_Version::jdk(5), JDK_Version::jdk(7) },273{ "UseOversizedCarHandling", JDK_Version::jdk(5), JDK_Version::jdk(7) },274{ "TraceCarAllocation", JDK_Version::jdk(5), JDK_Version::jdk(7) },275{ "PrintTrainGCProcessingStats", JDK_Version::jdk(5), JDK_Version::jdk(7) },276{ "LogOfCarSpaceSize", JDK_Version::jdk(5), JDK_Version::jdk(7) },277{ "OversizedCarThreshold", JDK_Version::jdk(5), JDK_Version::jdk(7) },278{ "MinTickInterval", JDK_Version::jdk(5), JDK_Version::jdk(7) },279{ "DefaultTickInterval", JDK_Version::jdk(5), JDK_Version::jdk(7) },280{ "MaxTickInterval", JDK_Version::jdk(5), JDK_Version::jdk(7) },281{ "DelayTickAdjustment", JDK_Version::jdk(5), JDK_Version::jdk(7) },282{ "ProcessingToTenuringRatio", JDK_Version::jdk(5), JDK_Version::jdk(7) },283{ "MinTrainLength", JDK_Version::jdk(5), JDK_Version::jdk(7) },284{ "AppendRatio", JDK_Version::jdk_update(6,10), JDK_Version::jdk(7) },285{ "DefaultMaxRAM", JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },286{ "DefaultInitialRAMFraction",287JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },288{ "UseDepthFirstScavengeOrder",289JDK_Version::jdk_update(6,22), JDK_Version::jdk(7) },290{ "HandlePromotionFailure",291JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },292{ "MaxLiveObjectEvacuationRatio",293JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },294{ "ForceSharedSpaces", JDK_Version::jdk_update(6,25), JDK_Version::jdk(8) },295{ "UseParallelOldGCCompacting",296JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },297{ "UseParallelDensePrefixUpdate",298JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },299{ "UseParallelOldGCDensePrefix",300JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },301{ "AllowTransitionalJSR292", JDK_Version::jdk(7), JDK_Version::jdk(8) },302{ "UseCompressedStrings", JDK_Version::jdk(7), JDK_Version::jdk(8) },303{ "CMSPermGenPrecleaningEnabled", JDK_Version::jdk(8), JDK_Version::jdk(9) },304{ "CMSTriggerPermRatio", JDK_Version::jdk(8), JDK_Version::jdk(9) },305{ "CMSInitiatingPermOccupancyFraction", JDK_Version::jdk(8), JDK_Version::jdk(9) },306{ "AdaptivePermSizeWeight", JDK_Version::jdk(8), JDK_Version::jdk(9) },307{ "PermGenPadding", JDK_Version::jdk(8), JDK_Version::jdk(9) },308{ "PermMarkSweepDeadRatio", JDK_Version::jdk(8), JDK_Version::jdk(9) },309{ "PermSize", JDK_Version::jdk(8), JDK_Version::jdk(9) },310{ "MaxPermSize", JDK_Version::jdk(8), JDK_Version::jdk(9) },311{ "MinPermHeapExpansion", JDK_Version::jdk(8), JDK_Version::jdk(9) },312{ "MaxPermHeapExpansion", JDK_Version::jdk(8), JDK_Version::jdk(9) },313{ "CMSRevisitStackSize", JDK_Version::jdk(8), JDK_Version::jdk(9) },314{ "PrintRevisitStats", JDK_Version::jdk(8), JDK_Version::jdk(9) },315{ "UseVectoredExceptions", JDK_Version::jdk(8), JDK_Version::jdk(9) },316{ "UseSplitVerifier", JDK_Version::jdk(8), JDK_Version::jdk(9) },317{ "UseISM", JDK_Version::jdk(8), JDK_Version::jdk(9) },318{ "UsePermISM", JDK_Version::jdk(8), JDK_Version::jdk(9) },319{ "UseMPSS", JDK_Version::jdk(8), JDK_Version::jdk(9) },320{ "UseStringCache", JDK_Version::jdk(8), JDK_Version::jdk(9) },321{ "UseOldInlining", JDK_Version::jdk_update(8, 20), JDK_Version::jdk(10) },322{ "AutoShutdownNMT", JDK_Version::jdk_update(8, 40), JDK_Version::jdk(10) },323{ "CompilationRepeat", JDK_Version::jdk(8), JDK_Version::jdk(9) },324{ "SegmentedHeapDumpThreshold", JDK_Version::jdk_update(8, 252), JDK_Version::jdk(10) },325#ifdef PRODUCT326{ "DesiredMethodLimit",327JDK_Version::jdk_update(7, 2), JDK_Version::jdk(8) },328#endif // PRODUCT329{ NULL, JDK_Version(0), JDK_Version(0) }330};331332// Returns true if the flag is obsolete and fits into the range specified333// for being ignored. In the case that the flag is ignored, the 'version'334// value is filled in with the version number when the flag became335// obsolete so that that value can be displayed to the user.336bool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {337int i = 0;338assert(version != NULL, "Must provide a version buffer");339while (obsolete_jvm_flags[i].name != NULL) {340const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];341// <flag>=xxx form342// [-|+]<flag> form343if ((strncmp(flag_status.name, s, strlen(flag_status.name)) == 0) ||344((s[0] == '+' || s[0] == '-') &&345(strncmp(flag_status.name, &s[1], strlen(flag_status.name)) == 0))) {346if (JDK_Version::current().compare(flag_status.accept_until) == -1) {347*version = flag_status.obsoleted_in;348return true;349}350}351i++;352}353return false;354}355356// Constructs the system class path (aka boot class path) from the following357// components, in order:358//359// prefix // from -Xbootclasspath/p:...360// endorsed // the expansion of -Djava.endorsed.dirs=...361// base // from os::get_system_properties() or -Xbootclasspath=362// suffix // from -Xbootclasspath/a:...363//364// java.endorsed.dirs is a list of directories; any jar or zip files in the365// directories are added to the sysclasspath just before the base.366//367// This could be AllStatic, but it isn't needed after argument processing is368// complete.369class SysClassPath: public StackObj {370public:371SysClassPath(const char* base);372~SysClassPath();373374inline void set_base(const char* base);375inline void add_prefix(const char* prefix);376inline void add_suffix_to_prefix(const char* suffix);377inline void add_suffix(const char* suffix);378inline void reset_path(const char* base);379380// Expand the jar/zip files in each directory listed by the java.endorsed.dirs381// property. Must be called after all command-line arguments have been382// processed (in particular, -Djava.endorsed.dirs=...) and before calling383// combined_path().384void expand_endorsed();385386inline const char* get_base() const { return _items[_scp_base]; }387inline const char* get_prefix() const { return _items[_scp_prefix]; }388inline const char* get_suffix() const { return _items[_scp_suffix]; }389inline const char* get_endorsed() const { return _items[_scp_endorsed]; }390391// Combine all the components into a single c-heap-allocated string; caller392// must free the string if/when no longer needed.393char* combined_path();394395private:396// Utility routines.397static char* add_to_path(const char* path, const char* str, bool prepend);398static char* add_jars_to_path(char* path, const char* directory);399400inline void reset_item_at(int index);401402// Array indices for the items that make up the sysclasspath. All except the403// base are allocated in the C heap and freed by this class.404enum {405_scp_prefix, // from -Xbootclasspath/p:...406_scp_endorsed, // the expansion of -Djava.endorsed.dirs=...407_scp_base, // the default sysclasspath408_scp_suffix, // from -Xbootclasspath/a:...409_scp_nitems // the number of items, must be last.410};411412const char* _items[_scp_nitems];413DEBUG_ONLY(bool _expansion_done;)414};415416SysClassPath::SysClassPath(const char* base) {417memset(_items, 0, sizeof(_items));418_items[_scp_base] = base;419DEBUG_ONLY(_expansion_done = false;)420}421422SysClassPath::~SysClassPath() {423// Free everything except the base.424for (int i = 0; i < _scp_nitems; ++i) {425if (i != _scp_base) reset_item_at(i);426}427DEBUG_ONLY(_expansion_done = false;)428}429430inline void SysClassPath::set_base(const char* base) {431_items[_scp_base] = base;432}433434inline void SysClassPath::add_prefix(const char* prefix) {435_items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);436}437438inline void SysClassPath::add_suffix_to_prefix(const char* suffix) {439_items[_scp_prefix] = add_to_path(_items[_scp_prefix], suffix, false);440}441442inline void SysClassPath::add_suffix(const char* suffix) {443_items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);444}445446inline void SysClassPath::reset_item_at(int index) {447assert(index < _scp_nitems && index != _scp_base, "just checking");448if (_items[index] != NULL) {449FREE_C_HEAP_ARRAY(char, _items[index], mtInternal);450_items[index] = NULL;451}452}453454inline void SysClassPath::reset_path(const char* base) {455// Clear the prefix and suffix.456reset_item_at(_scp_prefix);457reset_item_at(_scp_suffix);458set_base(base);459}460461//------------------------------------------------------------------------------462463void SysClassPath::expand_endorsed() {464assert(_items[_scp_endorsed] == NULL, "can only be called once.");465466const char* path = Arguments::get_property("java.endorsed.dirs");467if (path == NULL) {468path = Arguments::get_endorsed_dir();469assert(path != NULL, "no default for java.endorsed.dirs");470}471472char* expanded_path = NULL;473const char separator = *os::path_separator();474const char* const end = path + strlen(path);475while (path < end) {476const char* tmp_end = strchr(path, separator);477if (tmp_end == NULL) {478expanded_path = add_jars_to_path(expanded_path, path);479path = end;480} else {481char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);482memcpy(dirpath, path, tmp_end - path);483dirpath[tmp_end - path] = '\0';484expanded_path = add_jars_to_path(expanded_path, dirpath);485FREE_C_HEAP_ARRAY(char, dirpath, mtInternal);486path = tmp_end + 1;487}488}489_items[_scp_endorsed] = expanded_path;490DEBUG_ONLY(_expansion_done = true;)491}492493// Combine the bootclasspath elements, some of which may be null, into a single494// c-heap-allocated string.495char* SysClassPath::combined_path() {496assert(_items[_scp_base] != NULL, "empty default sysclasspath");497assert(_expansion_done, "must call expand_endorsed() first.");498499size_t lengths[_scp_nitems];500size_t total_len = 0;501502const char separator = *os::path_separator();503504// Get the lengths.505int i;506for (i = 0; i < _scp_nitems; ++i) {507if (_items[i] != NULL) {508lengths[i] = strlen(_items[i]);509// Include space for the separator char (or a NULL for the last item).510total_len += lengths[i] + 1;511}512}513assert(total_len > 0, "empty sysclasspath not allowed");514515// Copy the _items to a single string.516char* cp = NEW_C_HEAP_ARRAY(char, total_len, mtInternal);517char* cp_tmp = cp;518for (i = 0; i < _scp_nitems; ++i) {519if (_items[i] != NULL) {520memcpy(cp_tmp, _items[i], lengths[i]);521cp_tmp += lengths[i];522*cp_tmp++ = separator;523}524}525*--cp_tmp = '\0'; // Replace the extra separator.526return cp;527}528529// Note: path must be c-heap-allocated (or NULL); it is freed if non-null.530char*531SysClassPath::add_to_path(const char* path, const char* str, bool prepend) {532char *cp;533534assert(str != NULL, "just checking");535if (path == NULL) {536size_t len = strlen(str) + 1;537cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);538memcpy(cp, str, len); // copy the trailing null539} else {540const char separator = *os::path_separator();541size_t old_len = strlen(path);542size_t str_len = strlen(str);543size_t len = old_len + str_len + 2;544545if (prepend) {546cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);547char* cp_tmp = cp;548memcpy(cp_tmp, str, str_len);549cp_tmp += str_len;550*cp_tmp = separator;551memcpy(++cp_tmp, path, old_len + 1); // copy the trailing null552FREE_C_HEAP_ARRAY(char, path, mtInternal);553} else {554cp = REALLOC_C_HEAP_ARRAY(char, path, len, mtInternal);555char* cp_tmp = cp + old_len;556*cp_tmp = separator;557memcpy(++cp_tmp, str, str_len + 1); // copy the trailing null558}559}560return cp;561}562563// Scan the directory and append any jar or zip files found to path.564// Note: path must be c-heap-allocated (or NULL); it is freed if non-null.565char* SysClassPath::add_jars_to_path(char* path, const char* directory) {566DIR* dir = os::opendir(directory);567if (dir == NULL) return path;568569char dir_sep[2] = { '\0', '\0' };570size_t directory_len = strlen(directory);571const char fileSep = *os::file_separator();572if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;573574/* Scan the directory for jars/zips, appending them to path. */575struct dirent *entry;576while ((entry = os::readdir(dir)) != NULL) {577const char* name = entry->d_name;578const char* ext = name + strlen(name) - 4;579bool isJarOrZip = ext > name &&580(os::file_name_strcmp(ext, ".jar") == 0 ||581os::file_name_strcmp(ext, ".zip") == 0);582if (isJarOrZip) {583size_t length = directory_len + 2 + strlen(name);584char* jarpath = NEW_C_HEAP_ARRAY(char, length, mtInternal);585jio_snprintf(jarpath, length, "%s%s%s", directory, dir_sep, name);586path = add_to_path(path, jarpath, false);587FREE_C_HEAP_ARRAY(char, jarpath, mtInternal);588}589}590os::closedir(dir);591return path;592}593594// Parses a memory size specification string.595static bool atomull(const char *s, julong* result) {596julong n = 0;597int args_read = sscanf(s, JULONG_FORMAT, &n);598if (args_read != 1) {599return false;600}601while (*s != '\0' && isdigit(*s)) {602s++;603}604// 4705540: illegal if more characters are found after the first non-digit605if (strlen(s) > 1) {606return false;607}608switch (*s) {609case 'T': case 't':610*result = n * G * K;611// Check for overflow.612if (*result/((julong)G * K) != n) return false;613return true;614case 'G': case 'g':615*result = n * G;616if (*result/G != n) return false;617return true;618case 'M': case 'm':619*result = n * M;620if (*result/M != n) return false;621return true;622case 'K': case 'k':623*result = n * K;624if (*result/K != n) return false;625return true;626case '\0':627*result = n;628return true;629default:630return false;631}632}633634Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {635if (size < min_size) return arg_too_small;636// Check that size will fit in a size_t (only relevant on 32-bit)637if (size > max_uintx) return arg_too_big;638return arg_in_range;639}640641// Describe an argument out of range error642void Arguments::describe_range_error(ArgsRange errcode) {643switch(errcode) {644case arg_too_big:645jio_fprintf(defaultStream::error_stream(),646"The specified size exceeds the maximum "647"representable size.\n");648break;649case arg_too_small:650case arg_unreadable:651case arg_in_range:652// do nothing for now653break;654default:655ShouldNotReachHere();656}657}658659static bool set_bool_flag(char* name, bool value, Flag::Flags origin) {660return CommandLineFlags::boolAtPut(name, &value, origin);661}662663static bool set_fp_numeric_flag(char* name, char* value, Flag::Flags origin) {664double v;665if (sscanf(value, "%lf", &v) != 1) {666return false;667}668669if (CommandLineFlags::doubleAtPut(name, &v, origin)) {670return true;671}672return false;673}674675static bool set_numeric_flag(char* name, char* value, Flag::Flags origin) {676julong v;677intx intx_v;678bool is_neg = false;679// Check the sign first since atomull() parses only unsigned values.680if (*value == '-') {681if (!CommandLineFlags::intxAt(name, &intx_v)) {682return false;683}684value++;685is_neg = true;686}687if (!atomull(value, &v)) {688return false;689}690intx_v = (intx) v;691if (is_neg) {692intx_v = -intx_v;693}694if (CommandLineFlags::intxAtPut(name, &intx_v, origin)) {695return true;696}697uintx uintx_v = (uintx) v;698if (!is_neg && CommandLineFlags::uintxAtPut(name, &uintx_v, origin)) {699return true;700}701uint64_t uint64_t_v = (uint64_t) v;702if (!is_neg && CommandLineFlags::uint64_tAtPut(name, &uint64_t_v, origin)) {703return true;704}705return false;706}707708static bool set_string_flag(char* name, const char* value, Flag::Flags origin) {709if (!CommandLineFlags::ccstrAtPut(name, &value, origin)) return false;710// Contract: CommandLineFlags always returns a pointer that needs freeing.711FREE_C_HEAP_ARRAY(char, value, mtInternal);712return true;713}714715static bool append_to_string_flag(char* name, const char* new_value, Flag::Flags origin) {716const char* old_value = "";717if (!CommandLineFlags::ccstrAt(name, &old_value)) return false;718size_t old_len = old_value != NULL ? strlen(old_value) : 0;719size_t new_len = strlen(new_value);720const char* value;721char* free_this_too = NULL;722if (old_len == 0) {723value = new_value;724} else if (new_len == 0) {725value = old_value;726} else {727size_t length = old_len + 1 + new_len + 1;728char* buf = NEW_C_HEAP_ARRAY(char, length, mtInternal);729// each new setting adds another LINE to the switch:730jio_snprintf(buf, length, "%s\n%s", old_value, new_value);731value = buf;732free_this_too = buf;733}734(void) CommandLineFlags::ccstrAtPut(name, &value, origin);735// CommandLineFlags always returns a pointer that needs freeing.736FREE_C_HEAP_ARRAY(char, value, mtInternal);737if (free_this_too != NULL) {738// CommandLineFlags made its own copy, so I must delete my own temp. buffer.739FREE_C_HEAP_ARRAY(char, free_this_too, mtInternal);740}741return true;742}743744bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {745746// range of acceptable characters spelled out for portability reasons747#define NAME_RANGE "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"748#define BUFLEN 255749char name[BUFLEN+1];750char dummy;751752if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {753return set_bool_flag(name, false, origin);754}755if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {756return set_bool_flag(name, true, origin);757}758759char punct;760if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {761const char* value = strchr(arg, '=') + 1;762Flag* flag = Flag::find_flag(name, strlen(name));763if (flag != NULL && flag->is_ccstr()) {764if (flag->ccstr_accumulates()) {765return append_to_string_flag(name, value, origin);766} else {767if (value[0] == '\0') {768value = NULL;769}770return set_string_flag(name, value, origin);771}772}773}774775if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {776const char* value = strchr(arg, '=') + 1;777// -XX:Foo:=xxx will reset the string flag to the given value.778if (value[0] == '\0') {779value = NULL;780}781return set_string_flag(name, value, origin);782}783784#define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"785#define SIGNED_NUMBER_RANGE "[-0123456789]"786#define NUMBER_RANGE "[0123456789]"787char value[BUFLEN + 1];788char value2[BUFLEN + 1];789if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {790// Looks like a floating-point number -- try again with more lenient format string791if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {792return set_fp_numeric_flag(name, value, origin);793}794}795796#define VALUE_RANGE "[-kmgtKMGT0123456789]"797if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {798return set_numeric_flag(name, value, origin);799}800801return false;802}803804void Arguments::add_string(char*** bldarray, int* count, const char* arg) {805assert(bldarray != NULL, "illegal argument");806807if (arg == NULL) {808return;809}810811int new_count = *count + 1;812813// expand the array and add arg to the last element814if (*bldarray == NULL) {815*bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtInternal);816} else {817*bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtInternal);818}819(*bldarray)[*count] = strdup(arg);820*count = new_count;821}822823void Arguments::build_jvm_args(const char* arg) {824add_string(&_jvm_args_array, &_num_jvm_args, arg);825}826827void Arguments::build_jvm_flags(const char* arg) {828add_string(&_jvm_flags_array, &_num_jvm_flags, arg);829}830831// utility function to return a string that concatenates all832// strings in a given char** array833const char* Arguments::build_resource_string(char** args, int count) {834if (args == NULL || count == 0) {835return NULL;836}837size_t length = 0;838for (int i = 0; i < count; i++) {839length += strlen(args[i]) + 1; // add 1 for a space or NULL terminating character840}841char* s = NEW_RESOURCE_ARRAY(char, length);842char* dst = s;843for (int j = 0; j < count; j++) {844size_t offset = strlen(args[j]) + 1; // add 1 for a space or NULL terminating character845jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with NULL character846dst += offset;847length -= offset;848}849return (const char*) s;850}851852void Arguments::print_on(outputStream* st) {853st->print_cr("VM Arguments:");854if (num_jvm_flags() > 0) {855st->print("jvm_flags: "); print_jvm_flags_on(st);856}857if (num_jvm_args() > 0) {858st->print("jvm_args: "); print_jvm_args_on(st);859}860st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");861if (_java_class_path != NULL) {862char* path = _java_class_path->value();863st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );864}865st->print_cr("Launcher Type: %s", _sun_java_launcher);866}867868void Arguments::print_jvm_flags_on(outputStream* st) {869if (_num_jvm_flags > 0) {870for (int i=0; i < _num_jvm_flags; i++) {871st->print("%s ", _jvm_flags_array[i]);872}873st->cr();874}875}876877void Arguments::print_jvm_args_on(outputStream* st) {878if (_num_jvm_args > 0) {879for (int i=0; i < _num_jvm_args; i++) {880st->print("%s ", _jvm_args_array[i]);881}882st->cr();883}884}885886bool Arguments::process_argument(const char* arg,887jboolean ignore_unrecognized, Flag::Flags origin) {888889JDK_Version since = JDK_Version();890891if (parse_argument(arg, origin) || ignore_unrecognized) {892return true;893}894895bool has_plus_minus = (*arg == '+' || *arg == '-');896const char* const argname = has_plus_minus ? arg + 1 : arg;897if (is_newly_obsolete(arg, &since)) {898char version[256];899since.to_string(version, sizeof(version));900warning("ignoring option %s; support was removed in %s", argname, version);901return true;902}903904// For locked flags, report a custom error message if available.905// Otherwise, report the standard unrecognized VM option.906907size_t arg_len;908const char* equal_sign = strchr(argname, '=');909if (equal_sign == NULL) {910arg_len = strlen(argname);911} else {912arg_len = equal_sign - argname;913}914915Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);916if (found_flag != NULL) {917char locked_message_buf[BUFLEN];918found_flag->get_locked_message(locked_message_buf, BUFLEN);919if (strlen(locked_message_buf) == 0) {920if (found_flag->is_bool() && !has_plus_minus) {921jio_fprintf(defaultStream::error_stream(),922"Missing +/- setting for VM option '%s'\n", argname);923} else if (!found_flag->is_bool() && has_plus_minus) {924jio_fprintf(defaultStream::error_stream(),925"Unexpected +/- setting in VM option '%s'\n", argname);926} else {927jio_fprintf(defaultStream::error_stream(),928"Improperly specified VM option '%s'\n", argname);929}930} else {931jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);932}933} else {934jio_fprintf(defaultStream::error_stream(),935"Unrecognized VM option '%s'\n", argname);936Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);937if (fuzzy_matched != NULL) {938jio_fprintf(defaultStream::error_stream(),939"Did you mean '%s%s%s'?\n",940(fuzzy_matched->is_bool()) ? "(+/-)" : "",941fuzzy_matched->_name,942(fuzzy_matched->is_bool()) ? "" : "=<value>");943}944}945946// allow for commandline "commenting out" options like -XX:#+Verbose947return arg[0] == '#';948}949950bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {951FILE* stream = fopen(file_name, "rb");952if (stream == NULL) {953if (should_exist) {954jio_fprintf(defaultStream::error_stream(),955"Could not open settings file %s\n", file_name);956return false;957} else {958return true;959}960}961962char token[1024];963int pos = 0;964965bool in_white_space = true;966bool in_comment = false;967bool in_quote = false;968char quote_c = 0;969bool result = true;970971int c = getc(stream);972while(c != EOF && pos < (int)(sizeof(token)-1)) {973if (in_white_space) {974if (in_comment) {975if (c == '\n') in_comment = false;976} else {977if (c == '#') in_comment = true;978else if (!isspace(c)) {979in_white_space = false;980token[pos++] = c;981}982}983} else {984if (c == '\n' || (!in_quote && isspace(c))) {985// token ends at newline, or at unquoted whitespace986// this allows a way to include spaces in string-valued options987token[pos] = '\0';988logOption(token);989result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);990build_jvm_flags(token);991pos = 0;992in_white_space = true;993in_quote = false;994} else if (!in_quote && (c == '\'' || c == '"')) {995in_quote = true;996quote_c = c;997} else if (in_quote && (c == quote_c)) {998in_quote = false;999} else {1000token[pos++] = c;1001}1002}1003c = getc(stream);1004}1005if (pos > 0) {1006token[pos] = '\0';1007result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);1008build_jvm_flags(token);1009}1010fclose(stream);1011return result;1012}10131014//=============================================================================================================1015// Parsing of properties (-D)10161017const char* Arguments::get_property(const char* key) {1018return PropertyList_get_value(system_properties(), key);1019}10201021bool Arguments::add_property(const char* prop) {1022const char* eq = strchr(prop, '=');1023char* key;1024// ns must be static--its address may be stored in a SystemProperty object.1025const static char ns[1] = {0};1026char* value = (char *)ns;10271028size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);1029key = AllocateHeap(key_len + 1, mtInternal);1030strncpy(key, prop, key_len);1031key[key_len] = '\0';10321033if (eq != NULL) {1034size_t value_len = strlen(prop) - key_len - 1;1035value = AllocateHeap(value_len + 1, mtInternal);1036strncpy(value, &prop[key_len + 1], value_len + 1);1037}10381039if (strcmp(key, "java.compiler") == 0) {1040process_java_compiler_argument(value);1041FreeHeap(key);1042if (eq != NULL) {1043FreeHeap(value);1044}1045return true;1046} else if (strcmp(key, "sun.java.command") == 0) {1047_java_command = value;10481049// Record value in Arguments, but let it get passed to Java.1050} else if (strcmp(key, "sun.java.launcher.pid") == 0) {1051// launcher.pid property is private and is processed1052// in process_sun_java_launcher_properties();1053// the sun.java.launcher property is passed on to the java application1054FreeHeap(key);1055if (eq != NULL) {1056FreeHeap(value);1057}1058return true;1059} else if (strcmp(key, "java.vendor.url.bug") == 0) {1060// save it in _java_vendor_url_bug, so JVM fatal error handler can access1061// its value without going through the property list or making a Java call.1062_java_vendor_url_bug = value;1063} else if (strcmp(key, "sun.boot.library.path") == 0) {1064PropertyList_unique_add(&_system_properties, key, value, true);1065return true;1066}1067// Create new property and add at the end of the list1068PropertyList_unique_add(&_system_properties, key, value);1069return true;1070}10711072//===========================================================================================================1073// Setting int/mixed/comp mode flags10741075void Arguments::set_mode_flags(Mode mode) {1076// Set up default values for all flags.1077// If you add a flag to any of the branches below,1078// add a default value for it here.1079set_java_compiler(false);1080_mode = mode;10811082// Ensure Agent_OnLoad has the correct initial values.1083// This may not be the final mode; mode may change later in onload phase.1084PropertyList_unique_add(&_system_properties, "java.vm.info",1085(char*)VM_Version::vm_info_string(), false);10861087UseInterpreter = true;1088UseCompiler = true;1089UseLoopCounter = true;10901091#ifndef ZERO1092// Turn these off for mixed and comp. Leave them on for Zero.1093if (FLAG_IS_DEFAULT(UseFastAccessorMethods)) {1094UseFastAccessorMethods = (mode == _int);1095}1096if (FLAG_IS_DEFAULT(UseFastEmptyMethods)) {1097UseFastEmptyMethods = (mode == _int);1098}1099#endif11001101// Default values may be platform/compiler dependent -1102// use the saved values1103ClipInlining = Arguments::_ClipInlining;1104AlwaysCompileLoopMethods = Arguments::_AlwaysCompileLoopMethods;1105UseOnStackReplacement = Arguments::_UseOnStackReplacement;1106BackgroundCompilation = Arguments::_BackgroundCompilation;11071108// Change from defaults based on mode1109switch (mode) {1110default:1111ShouldNotReachHere();1112break;1113case _int:1114UseCompiler = false;1115UseLoopCounter = false;1116AlwaysCompileLoopMethods = false;1117UseOnStackReplacement = false;1118break;1119case _mixed:1120// same as default1121break;1122case _comp:1123UseInterpreter = false;1124BackgroundCompilation = false;1125ClipInlining = false;1126// Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.1127// We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and1128// compile a level 4 (C2) and then continue executing it.1129if (TieredCompilation) {1130Tier3InvokeNotifyFreqLog = 0;1131Tier4InvocationThreshold = 0;1132}1133break;1134}1135}11361137#if defined(COMPILER2) || defined(_LP64) || !INCLUDE_CDS1138// Conflict: required to use shared spaces (-Xshare:on), but1139// incompatible command line options were chosen.11401141static void no_shared_spaces(const char* message) {1142if (RequireSharedSpaces) {1143jio_fprintf(defaultStream::error_stream(),1144"Class data sharing is inconsistent with other specified options.\n");1145vm_exit_during_initialization("Unable to use shared archive.", message);1146} else {1147FLAG_SET_DEFAULT(UseSharedSpaces, false);1148}1149}1150#endif11511152void Arguments::set_tiered_flags() {1153// With tiered, set default policy to AdvancedThresholdPolicy, which is 3.1154if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {1155FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);1156}1157if (CompilationPolicyChoice < 2) {1158vm_exit_during_initialization(1159"Incompatible compilation policy selected", NULL);1160}1161// Increase the code cache size - tiered compiles a lot more.1162if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {1163#ifndef AARCH641164FLAG_SET_DEFAULT(ReservedCodeCacheSize, ReservedCodeCacheSize * 5);1165#else1166FLAG_SET_DEFAULT(ReservedCodeCacheSize,1167MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));1168#endif1169}1170if (!UseInterpreter) { // -Xcomp1171Tier3InvokeNotifyFreqLog = 0;1172Tier4InvocationThreshold = 0;1173}1174}11751176/**1177* Returns the minimum number of compiler threads needed to run the JVM. The following1178* configurations are possible.1179*1180* 1) The JVM is build using an interpreter only. As a result, the minimum number of1181* compiler threads is 0.1182* 2) The JVM is build using the compiler(s) and tiered compilation is disabled. As1183* a result, either C1 or C2 is used, so the minimum number of compiler threads is 1.1184* 3) The JVM is build using the compiler(s) and tiered compilation is enabled. However,1185* the option "TieredStopAtLevel < CompLevel_full_optimization". As a result, only1186* C1 can be used, so the minimum number of compiler threads is 1.1187* 4) The JVM is build using the compilers and tiered compilation is enabled. The option1188* 'TieredStopAtLevel = CompLevel_full_optimization' (the default value). As a result,1189* the minimum number of compiler threads is 2.1190*/1191int Arguments::get_min_number_of_compiler_threads() {1192#if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)1193return 0; // case 11194#else1195if (!TieredCompilation || (TieredStopAtLevel < CompLevel_full_optimization)) {1196return 1; // case 2 or case 31197}1198return 2; // case 4 (tiered)1199#endif1200}12011202#if INCLUDE_ALL_GCS1203static void disable_adaptive_size_policy(const char* collector_name) {1204if (UseAdaptiveSizePolicy) {1205if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {1206warning("disabling UseAdaptiveSizePolicy; it is incompatible with %s.",1207collector_name);1208}1209FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);1210}1211}12121213void Arguments::set_parnew_gc_flags() {1214assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,1215"control point invariant");1216assert(UseParNewGC, "Error");12171218// Turn off AdaptiveSizePolicy for parnew until it is complete.1219disable_adaptive_size_policy("UseParNewGC");12201221if (FLAG_IS_DEFAULT(ParallelGCThreads)) {1222FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());1223assert(ParallelGCThreads > 0, "We should always have at least one thread by default");1224} else if (ParallelGCThreads == 0) {1225jio_fprintf(defaultStream::error_stream(),1226"The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");1227vm_exit(1);1228}12291230// By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,1231// these settings are default for Parallel Scavenger. For ParNew+Tenured configuration1232// we set them to 1024 and 1024.1233// See CR 6362902.1234if (FLAG_IS_DEFAULT(YoungPLABSize)) {1235FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);1236}1237if (FLAG_IS_DEFAULT(OldPLABSize)) {1238FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);1239}12401241// AlwaysTenure flag should make ParNew promote all at first collection.1242// See CR 6362902.1243if (AlwaysTenure) {1244FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0);1245}1246// When using compressed oops, we use local overflow stacks,1247// rather than using a global overflow list chained through1248// the klass word of the object's pre-image.1249if (UseCompressedOops && !ParGCUseLocalOverflow) {1250if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {1251warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");1252}1253FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);1254}1255assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");1256}12571258// Adjust some sizes to suit CMS and/or ParNew needs; these work well on1259// sparc/solaris for certain applications, but would gain from1260// further optimization and tuning efforts, and would almost1261// certainly gain from analysis of platform and environment.1262void Arguments::set_cms_and_parnew_gc_flags() {1263assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");1264assert(UseConcMarkSweepGC, "CMS is expected to be on here");12651266// If we are using CMS, we prefer to UseParNewGC,1267// unless explicitly forbidden.1268if (FLAG_IS_DEFAULT(UseParNewGC)) {1269FLAG_SET_ERGO(bool, UseParNewGC, true);1270}12711272// Turn off AdaptiveSizePolicy by default for cms until it is complete.1273disable_adaptive_size_policy("UseConcMarkSweepGC");12741275// In either case, adjust ParallelGCThreads and/or UseParNewGC1276// as needed.1277if (UseParNewGC) {1278set_parnew_gc_flags();1279}12801281size_t max_heap = align_size_down(MaxHeapSize,1282CardTableRS::ct_max_alignment_constraint());12831284// Now make adjustments for CMS1285intx tenuring_default = (intx)6;1286size_t young_gen_per_worker = CMSYoungGenPerWorker;12871288// Preferred young gen size for "short" pauses:1289// upper bound depends on # of threads and NewRatio.1290const uintx parallel_gc_threads =1291(ParallelGCThreads == 0 ? 1 : ParallelGCThreads);1292const size_t preferred_max_new_size_unaligned =1293MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * parallel_gc_threads));1294size_t preferred_max_new_size =1295align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());12961297// Unless explicitly requested otherwise, size young gen1298// for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads12991300// If either MaxNewSize or NewRatio is set on the command line,1301// assume the user is trying to set the size of the young gen.1302if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {13031304// Set MaxNewSize to our calculated preferred_max_new_size unless1305// NewSize was set on the command line and it is larger than1306// preferred_max_new_size.1307if (!FLAG_IS_DEFAULT(NewSize)) { // NewSize explicitly set at command-line1308FLAG_SET_ERGO(uintx, MaxNewSize, MAX2(NewSize, preferred_max_new_size));1309} else {1310FLAG_SET_ERGO(uintx, MaxNewSize, preferred_max_new_size);1311}1312if (PrintGCDetails && Verbose) {1313// Too early to use gclog_or_tty1314tty->print_cr("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);1315}13161317// Code along this path potentially sets NewSize and OldSize1318if (PrintGCDetails && Verbose) {1319// Too early to use gclog_or_tty1320tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT1321" initial_heap_size: " SIZE_FORMAT1322" max_heap: " SIZE_FORMAT,1323min_heap_size(), InitialHeapSize, max_heap);1324}1325size_t min_new = preferred_max_new_size;1326if (FLAG_IS_CMDLINE(NewSize)) {1327min_new = NewSize;1328}1329if (max_heap > min_new && min_heap_size() > min_new) {1330// Unless explicitly requested otherwise, make young gen1331// at least min_new, and at most preferred_max_new_size.1332if (FLAG_IS_DEFAULT(NewSize)) {1333FLAG_SET_ERGO(uintx, NewSize, MAX2(NewSize, min_new));1334FLAG_SET_ERGO(uintx, NewSize, MIN2(preferred_max_new_size, NewSize));1335if (PrintGCDetails && Verbose) {1336// Too early to use gclog_or_tty1337tty->print_cr("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);1338}1339}1340// Unless explicitly requested otherwise, size old gen1341// so it's NewRatio x of NewSize.1342if (FLAG_IS_DEFAULT(OldSize)) {1343if (max_heap > NewSize) {1344FLAG_SET_ERGO(uintx, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));1345if (PrintGCDetails && Verbose) {1346// Too early to use gclog_or_tty1347tty->print_cr("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);1348}1349}1350}1351}1352}1353// Unless explicitly requested otherwise, definitely1354// promote all objects surviving "tenuring_default" scavenges.1355if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&1356FLAG_IS_DEFAULT(SurvivorRatio)) {1357FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);1358}1359// If we decided above (or user explicitly requested)1360// `promote all' (via MaxTenuringThreshold := 0),1361// prefer minuscule survivor spaces so as not to waste1362// space for (non-existent) survivors1363if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {1364FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));1365}1366// If OldPLABSize is set and CMSParPromoteBlocksToClaim is not,1367// set CMSParPromoteBlocksToClaim equal to OldPLABSize.1368// This is done in order to make ParNew+CMS configuration to work1369// with YoungPLABSize and OldPLABSize options.1370// See CR 6362902.1371if (!FLAG_IS_DEFAULT(OldPLABSize)) {1372if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {1373// OldPLABSize is not the default value but CMSParPromoteBlocksToClaim1374// is. In this situtation let CMSParPromoteBlocksToClaim follow1375// the value (either from the command line or ergonomics) of1376// OldPLABSize. Following OldPLABSize is an ergonomics decision.1377FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, OldPLABSize);1378} else {1379// OldPLABSize and CMSParPromoteBlocksToClaim are both set.1380// CMSParPromoteBlocksToClaim is a collector-specific flag, so1381// we'll let it to take precedence.1382jio_fprintf(defaultStream::error_stream(),1383"Both OldPLABSize and CMSParPromoteBlocksToClaim"1384" options are specified for the CMS collector."1385" CMSParPromoteBlocksToClaim will take precedence.\n");1386}1387}1388if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {1389// OldPLAB sizing manually turned off: Use a larger default setting,1390// unless it was manually specified. This is because a too-low value1391// will slow down scavenges.1392if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {1393FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, 50); // default value before 66311661394}1395}1396// Overwrite OldPLABSize which is the variable we will internally use everywhere.1397FLAG_SET_ERGO(uintx, OldPLABSize, CMSParPromoteBlocksToClaim);1398// If either of the static initialization defaults have changed, note this1399// modification.1400if (!FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim) || !FLAG_IS_DEFAULT(OldPLABWeight)) {1401CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);1402}14031404if (PrintGCDetails && Verbose) {1405tty->print_cr("MarkStackSize: %uk MarkStackSizeMax: %uk",1406(unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));1407tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);1408}1409}1410#endif // INCLUDE_ALL_GCS14111412void set_object_alignment() {1413// Object alignment.1414assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");1415MinObjAlignmentInBytes = ObjectAlignmentInBytes;1416assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");1417MinObjAlignment = MinObjAlignmentInBytes / HeapWordSize;1418assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");1419MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;14201421LogMinObjAlignmentInBytes = exact_log2(ObjectAlignmentInBytes);1422LogMinObjAlignment = LogMinObjAlignmentInBytes - LogHeapWordSize;14231424// Oop encoding heap max1425OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;14261427#if INCLUDE_ALL_GCS1428// Set CMS global values1429CompactibleFreeListSpace::set_cms_values();1430#endif // INCLUDE_ALL_GCS1431}14321433bool verify_object_alignment() {1434// Object alignment.1435if (!is_power_of_2(ObjectAlignmentInBytes)) {1436jio_fprintf(defaultStream::error_stream(),1437"error: ObjectAlignmentInBytes=%d must be power of 2\n",1438(int)ObjectAlignmentInBytes);1439return false;1440}1441if ((int)ObjectAlignmentInBytes < BytesPerLong) {1442jio_fprintf(defaultStream::error_stream(),1443"error: ObjectAlignmentInBytes=%d must be greater or equal %d\n",1444(int)ObjectAlignmentInBytes, BytesPerLong);1445return false;1446}1447// It does not make sense to have big object alignment1448// since a space lost due to alignment will be greater1449// then a saved space from compressed oops.1450if ((int)ObjectAlignmentInBytes > 256) {1451jio_fprintf(defaultStream::error_stream(),1452"error: ObjectAlignmentInBytes=%d must not be greater than 256\n",1453(int)ObjectAlignmentInBytes);1454return false;1455}1456// In case page size is very small.1457if ((int)ObjectAlignmentInBytes >= os::vm_page_size()) {1458jio_fprintf(defaultStream::error_stream(),1459"error: ObjectAlignmentInBytes=%d must be less than page size %d\n",1460(int)ObjectAlignmentInBytes, os::vm_page_size());1461return false;1462}1463if(SurvivorAlignmentInBytes == 0) {1464SurvivorAlignmentInBytes = ObjectAlignmentInBytes;1465} else {1466if (!is_power_of_2(SurvivorAlignmentInBytes)) {1467jio_fprintf(defaultStream::error_stream(),1468"error: SurvivorAlignmentInBytes=%d must be power of 2\n",1469(int)SurvivorAlignmentInBytes);1470return false;1471}1472if (SurvivorAlignmentInBytes < ObjectAlignmentInBytes) {1473jio_fprintf(defaultStream::error_stream(),1474"error: SurvivorAlignmentInBytes=%d must be greater than ObjectAlignmentInBytes=%d \n",1475(int)SurvivorAlignmentInBytes, (int)ObjectAlignmentInBytes);1476return false;1477}1478}1479return true;1480}14811482size_t Arguments::max_heap_for_compressed_oops() {1483// Avoid sign flip.1484assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");1485// We need to fit both the NULL page and the heap into the memory budget, while1486// keeping alignment constraints of the heap. To guarantee the latter, as the1487// NULL page is located before the heap, we pad the NULL page to the conservative1488// maximum alignment that the GC may ever impose upon the heap.1489size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),1490_conservative_max_heap_alignment);14911492LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);1493NOT_LP64(ShouldNotReachHere(); return 0);1494}14951496bool Arguments::should_auto_select_low_pause_collector() {1497if (UseAutoGCSelectPolicy &&1498!FLAG_IS_DEFAULT(MaxGCPauseMillis) &&1499(MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {1500if (PrintGCDetails) {1501// Cannot use gclog_or_tty yet.1502tty->print_cr("Automatic selection of the low pause collector"1503" based on pause goal of %d (ms)", (int) MaxGCPauseMillis);1504}1505return true;1506}1507return false;1508}15091510void Arguments::set_use_compressed_oops() {1511#ifndef ZERO1512#ifdef _LP641513// MaxHeapSize is not set up properly at this point, but1514// the only value that can override MaxHeapSize if we are1515// to use UseCompressedOops is InitialHeapSize.1516size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);15171518if (max_heap_size <= max_heap_for_compressed_oops()) {1519#if !defined(COMPILER1) || defined(TIERED)1520if (FLAG_IS_DEFAULT(UseCompressedOops)) {1521FLAG_SET_ERGO(bool, UseCompressedOops, true);1522}1523#endif1524#ifdef _WIN641525if (UseLargePages && UseCompressedOops) {1526// Cannot allocate guard pages for implicit checks in indexed addressing1527// mode, when large pages are specified on windows.1528// This flag could be switched ON if narrow oop base address is set to 0,1529// see code in Universe::initialize_heap().1530Universe::set_narrow_oop_use_implicit_null_checks(false);1531}1532#endif // _WIN641533} else {1534if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {1535warning("Max heap size too large for Compressed Oops");1536FLAG_SET_DEFAULT(UseCompressedOops, false);1537FLAG_SET_DEFAULT(UseCompressedClassPointers, false);1538}1539}1540#endif // _LP641541#endif // ZERO1542}154315441545// NOTE: set_use_compressed_klass_ptrs() must be called after calling1546// set_use_compressed_oops().1547void Arguments::set_use_compressed_klass_ptrs() {1548#ifndef ZERO1549#ifdef _LP641550// UseCompressedOops must be on for UseCompressedClassPointers to be on.1551if (!UseCompressedOops) {1552if (UseCompressedClassPointers) {1553warning("UseCompressedClassPointers requires UseCompressedOops");1554}1555FLAG_SET_DEFAULT(UseCompressedClassPointers, false);1556} else {1557// Turn on UseCompressedClassPointers too1558if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {1559FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);1560}1561// Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.1562if (UseCompressedClassPointers) {1563if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {1564warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");1565FLAG_SET_DEFAULT(UseCompressedClassPointers, false);1566}1567}1568}1569#endif // _LP641570#endif // !ZERO1571}15721573void Arguments::set_conservative_max_heap_alignment() {1574// The conservative maximum required alignment for the heap is the maximum of1575// the alignments imposed by several sources: any requirements from the heap1576// itself, the collector policy and the maximum page size we may run the VM1577// with.1578size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();1579#if INCLUDE_ALL_GCS1580if (UseParallelGC) {1581heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();1582} else if (UseG1GC) {1583heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();1584}1585#endif // INCLUDE_ALL_GCS1586_conservative_max_heap_alignment = MAX4(heap_alignment,1587(size_t)os::vm_allocation_granularity(),1588os::max_page_size(),1589CollectorPolicy::compute_heap_alignment());1590}15911592void Arguments::select_gc_ergonomically() {1593if (os::is_server_class_machine()) {1594if (should_auto_select_low_pause_collector()) {1595FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);1596} else {1597FLAG_SET_ERGO(bool, UseParallelGC, true);1598}1599}1600}16011602void Arguments::select_gc() {1603if (!gc_selected()) {1604select_gc_ergonomically();1605}1606}16071608void Arguments::set_ergonomics_flags() {1609select_gc();16101611#ifdef COMPILER21612// Shared spaces work fine with other GCs but causes bytecode rewriting1613// to be disabled, which hurts interpreter performance and decreases1614// server performance. When -server is specified, keep the default off1615// unless it is asked for. Future work: either add bytecode rewriting1616// at link time, or rewrite bytecodes in non-shared methods.1617if (!DumpSharedSpaces && !RequireSharedSpaces &&1618(FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {1619no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");1620}1621#endif16221623set_conservative_max_heap_alignment();16241625#ifndef ZERO1626#ifdef _LP641627set_use_compressed_oops();16281629// set_use_compressed_klass_ptrs() must be called after calling1630// set_use_compressed_oops().1631set_use_compressed_klass_ptrs();16321633// Also checks that certain machines are slower with compressed oops1634// in vm_version initialization code.1635#endif // _LP641636#endif // !ZERO1637}16381639void Arguments::set_parallel_gc_flags() {1640assert(UseParallelGC || UseParallelOldGC, "Error");1641// Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).1642if (FLAG_IS_DEFAULT(UseParallelOldGC)) {1643FLAG_SET_DEFAULT(UseParallelOldGC, true);1644}1645FLAG_SET_DEFAULT(UseParallelGC, true);16461647// If no heap maximum was requested explicitly, use some reasonable fraction1648// of the physical memory, up to a maximum of 1GB.1649FLAG_SET_DEFAULT(ParallelGCThreads,1650Abstract_VM_Version::parallel_worker_threads());1651if (ParallelGCThreads == 0) {1652jio_fprintf(defaultStream::error_stream(),1653"The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");1654vm_exit(1);1655}16561657if (UseAdaptiveSizePolicy) {1658// We don't want to limit adaptive heap sizing's freedom to adjust the heap1659// unless the user actually sets these flags.1660if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {1661FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);1662_min_heap_free_ratio = MinHeapFreeRatio;1663}1664if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {1665FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);1666_max_heap_free_ratio = MaxHeapFreeRatio;1667}1668}16691670// If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the1671// SurvivorRatio has been set, reset their default values to SurvivorRatio +1672// 2. By doing this we make SurvivorRatio also work for Parallel Scavenger.1673// See CR 6362902 for details.1674if (!FLAG_IS_DEFAULT(SurvivorRatio)) {1675if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {1676FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);1677}1678if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {1679FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);1680}1681}16821683if (UseParallelOldGC) {1684// Par compact uses lower default values since they are treated as1685// minimums. These are different defaults because of the different1686// interpretation and are not ergonomically set.1687if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {1688FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);1689}1690}1691}16921693void Arguments::set_g1_gc_flags() {1694assert(UseG1GC, "Error");1695#ifdef COMPILER11696FastTLABRefill = false;1697#endif1698FLAG_SET_DEFAULT(ParallelGCThreads,1699Abstract_VM_Version::parallel_worker_threads());1700if (ParallelGCThreads == 0) {1701vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);1702}17031704#if INCLUDE_ALL_GCS1705if (G1ConcRefinementThreads == 0) {1706FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);1707}1708#endif17091710// MarkStackSize will be set (if it hasn't been set by the user)1711// when concurrent marking is initialized.1712// Its value will be based upon the number of parallel marking threads.1713// But we do set the maximum mark stack size here.1714if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {1715FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);1716}17171718if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {1719// In G1, we want the default GC overhead goal to be higher than1720// say in PS. So we set it here to 10%. Otherwise the heap might1721// be expanded more aggressively than we would like it to. In1722// fact, even 10% seems to not be high enough in some cases1723// (especially small GC stress tests that the main thing they do1724// is allocation). We might consider increase it further.1725FLAG_SET_DEFAULT(GCTimeRatio, 9);1726}17271728if (PrintGCDetails && Verbose) {1729tty->print_cr("MarkStackSize: %uk MarkStackSizeMax: %uk",1730(unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));1731tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);1732}1733}17341735#if !INCLUDE_ALL_GCS1736#ifdef ASSERT1737static bool verify_serial_gc_flags() {1738return (UseSerialGC &&1739!(UseParNewGC || (UseConcMarkSweepGC || CMSIncrementalMode) || UseG1GC ||1740UseParallelGC || UseParallelOldGC));1741}1742#endif // ASSERT1743#endif // INCLUDE_ALL_GCS17441745void Arguments::set_gc_specific_flags() {1746#if INCLUDE_ALL_GCS1747// Set per-collector flags1748if (UseParallelGC || UseParallelOldGC) {1749set_parallel_gc_flags();1750} else if (UseConcMarkSweepGC) { // Should be done before ParNew check below1751set_cms_and_parnew_gc_flags();1752} else if (UseParNewGC) { // Skipped if CMS is set above1753set_parnew_gc_flags();1754} else if (UseG1GC) {1755set_g1_gc_flags();1756}1757check_deprecated_gcs();1758check_deprecated_gc_flags();1759if (AssumeMP && !UseSerialGC) {1760if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {1761warning("If the number of processors is expected to increase from one, then"1762" you should configure the number of parallel GC threads appropriately"1763" using -XX:ParallelGCThreads=N");1764}1765}1766if (MinHeapFreeRatio == 100) {1767// Keeping the heap 100% free is hard ;-) so limit it to 99%.1768FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);1769}17701771// If class unloading is disabled, also disable concurrent class unloading.1772if (!ClassUnloading) {1773FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);1774FLAG_SET_CMDLINE(bool, ClassUnloadingWithConcurrentMark, false);1775FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);1776}1777#else // INCLUDE_ALL_GCS1778assert(verify_serial_gc_flags(), "SerialGC unset");1779#endif // INCLUDE_ALL_GCS1780}17811782julong Arguments::limit_by_allocatable_memory(julong limit) {1783julong max_allocatable;1784julong result = limit;1785if (os::has_allocatable_memory_limit(&max_allocatable)) {1786result = MIN2(result, max_allocatable / MaxVirtMemFraction);1787}1788return result;1789}17901791void Arguments::set_heap_size() {1792if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {1793// Deprecated flag1794FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);1795}17961797julong phys_mem =1798FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)1799: (julong)MaxRAM;18001801// Experimental support for CGroup memory limits1802if (UseCGroupMemoryLimitForHeap) {1803// This is a rough indicator that a CGroup limit may be in force1804// for this process1805const char* lim_file = "/sys/fs/cgroup/memory/memory.limit_in_bytes";1806FILE *fp = fopen(lim_file, "r");1807if (fp != NULL) {1808julong cgroup_max = 0;1809int ret = fscanf(fp, JULONG_FORMAT, &cgroup_max);1810if (ret == 1 && cgroup_max > 0) {1811// If unlimited, cgroup_max will be a very large, but unspecified1812// value, so use initial phys_mem as a limit1813if (PrintGCDetails && Verbose) {1814// Cannot use gclog_or_tty yet.1815tty->print_cr("Setting phys_mem to the min of cgroup limit ("1816JULONG_FORMAT "MB) and initial phys_mem ("1817JULONG_FORMAT "MB)", cgroup_max/M, phys_mem/M);1818}1819phys_mem = MIN2(cgroup_max, phys_mem);1820} else {1821warning("Unable to read/parse cgroup memory limit from %s: %s",1822lim_file, errno != 0 ? strerror(errno) : "unknown error");1823}1824fclose(fp);1825} else {1826warning("Unable to open cgroup memory limit file %s (%s)", lim_file, strerror(errno));1827}1828}18291830// Convert Fraction to Precentage values1831if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&1832!FLAG_IS_DEFAULT(MaxRAMFraction))1833MaxRAMPercentage = 100.0 / MaxRAMFraction;18341835if (FLAG_IS_DEFAULT(MinRAMPercentage) &&1836!FLAG_IS_DEFAULT(MinRAMFraction))1837MinRAMPercentage = 100.0 / MinRAMFraction;18381839if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&1840!FLAG_IS_DEFAULT(InitialRAMFraction))1841InitialRAMPercentage = 100.0 / InitialRAMFraction;18421843// If the maximum heap size has not been set with -Xmx,1844// then set it as fraction of the size of physical memory,1845// respecting the maximum and minimum sizes of the heap.1846if (FLAG_IS_DEFAULT(MaxHeapSize)) {1847julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);1848const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);1849if (reasonable_min < MaxHeapSize) {1850// Small physical memory, so use a minimum fraction of it for the heap1851reasonable_max = reasonable_min;1852} else {1853// Not-small physical memory, so require a heap at least1854// as large as MaxHeapSize1855reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);1856}18571858if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {1859// Limit the heap size to ErgoHeapSizeLimit1860reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);1861}1862if (UseCompressedOops) {1863// Limit the heap size to the maximum possible when using compressed oops1864julong max_coop_heap = (julong)max_heap_for_compressed_oops();1865if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {1866// Heap should be above HeapBaseMinAddress to get zero based compressed oops1867// but it should be not less than default MaxHeapSize.1868max_coop_heap -= HeapBaseMinAddress;1869}1870reasonable_max = MIN2(reasonable_max, max_coop_heap);1871}1872reasonable_max = limit_by_allocatable_memory(reasonable_max);18731874if (!FLAG_IS_DEFAULT(InitialHeapSize)) {1875// An initial heap size was specified on the command line,1876// so be sure that the maximum size is consistent. Done1877// after call to limit_by_allocatable_memory because that1878// method might reduce the allocation size.1879reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);1880}18811882if (PrintGCDetails && Verbose) {1883// Cannot use gclog_or_tty yet.1884tty->print_cr(" Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);1885}1886FLAG_SET_ERGO(uintx, MaxHeapSize, (uintx)reasonable_max);1887}18881889// If the minimum or initial heap_size have not been set or requested to be set1890// ergonomically, set them accordingly.1891if (InitialHeapSize == 0 || min_heap_size() == 0) {1892julong reasonable_minimum = (julong)(OldSize + NewSize);18931894reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);18951896reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);18971898if (InitialHeapSize == 0) {1899julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);19001901reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());1902reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);19031904reasonable_initial = limit_by_allocatable_memory(reasonable_initial);19051906if (PrintGCDetails && Verbose) {1907// Cannot use gclog_or_tty yet.1908tty->print_cr(" Initial heap size " SIZE_FORMAT, (uintx)reasonable_initial);1909}1910FLAG_SET_ERGO(uintx, InitialHeapSize, (uintx)reasonable_initial);1911}1912// If the minimum heap size has not been set (via -Xms),1913// synchronize with InitialHeapSize to avoid errors with the default value.1914if (min_heap_size() == 0) {1915set_min_heap_size(MIN2((uintx)reasonable_minimum, InitialHeapSize));1916if (PrintGCDetails && Verbose) {1917// Cannot use gclog_or_tty yet.1918tty->print_cr(" Minimum heap size " SIZE_FORMAT, min_heap_size());1919}1920}1921}1922}19231924// This option inspects the machine and attempts to set various1925// parameters to be optimal for long-running, memory allocation1926// intensive jobs. It is intended for machines with large1927// amounts of cpu and memory.1928jint Arguments::set_aggressive_heap_flags() {1929// initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit1930// VM, but we may not be able to represent the total physical memory1931// available (like having 8gb of memory on a box but using a 32bit VM).1932// Thus, we need to make sure we're using a julong for intermediate1933// calculations.1934julong initHeapSize;1935julong total_memory = os::physical_memory();19361937if (total_memory < (julong) 256 * M) {1938jio_fprintf(defaultStream::error_stream(),1939"You need at least 256mb of memory to use -XX:+AggressiveHeap\n");1940vm_exit(1);1941}19421943// The heap size is half of available memory, or (at most)1944// all of possible memory less 160mb (leaving room for the OS1945// when using ISM). This is the maximum; because adaptive sizing1946// is turned on below, the actual space used may be smaller.19471948initHeapSize = MIN2(total_memory / (julong) 2,1949total_memory - (julong) 160 * M);19501951initHeapSize = limit_by_allocatable_memory(initHeapSize);19521953if (FLAG_IS_DEFAULT(MaxHeapSize)) {1954FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);1955FLAG_SET_CMDLINE(uintx, InitialHeapSize, initHeapSize);1956// Currently the minimum size and the initial heap sizes are the same.1957set_min_heap_size(initHeapSize);1958}1959if (FLAG_IS_DEFAULT(NewSize)) {1960// Make the young generation 3/8ths of the total heap.1961FLAG_SET_CMDLINE(uintx, NewSize,1962((julong) MaxHeapSize / (julong) 8) * (julong) 3);1963FLAG_SET_CMDLINE(uintx, MaxNewSize, NewSize);1964}19651966#ifndef _ALLBSD_SOURCE // UseLargePages is not yet supported on BSD.1967FLAG_SET_DEFAULT(UseLargePages, true);1968#endif19691970// Increase some data structure sizes for efficiency1971FLAG_SET_CMDLINE(uintx, BaseFootPrintEstimate, MaxHeapSize);1972FLAG_SET_CMDLINE(bool, ResizeTLAB, false);1973FLAG_SET_CMDLINE(uintx, TLABSize, 256 * K);19741975// See the OldPLABSize comment below, but replace 'after promotion'1976// with 'after copying'. YoungPLABSize is the size of the survivor1977// space per-gc-thread buffers. The default is 4kw.1978FLAG_SET_CMDLINE(uintx, YoungPLABSize, 256 * K); // Note: this is in words19791980// OldPLABSize is the size of the buffers in the old gen that1981// UseParallelGC uses to promote live data that doesn't fit in the1982// survivor spaces. At any given time, there's one for each gc thread.1983// The default size is 1kw. These buffers are rarely used, since the1984// survivor spaces are usually big enough. For specjbb, however, there1985// are occasions when there's lots of live data in the young gen1986// and we end up promoting some of it. We don't have a definite1987// explanation for why bumping OldPLABSize helps, but the theory1988// is that a bigger PLAB results in retaining something like the1989// original allocation order after promotion, which improves mutator1990// locality. A minor effect may be that larger PLABs reduce the1991// number of PLAB allocation events during gc. The value of 8kw1992// was arrived at by experimenting with specjbb.1993FLAG_SET_CMDLINE(uintx, OldPLABSize, 8 * K); // Note: this is in words19941995// Enable parallel GC and adaptive generation sizing1996FLAG_SET_CMDLINE(bool, UseParallelGC, true);19971998// Encourage steady state memory management1999FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);20002001// This appears to improve mutator locality2002FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);20032004// Get around early Solaris scheduling bug2005// (affinity vs other jobs on system)2006// but disallow DR and offlining (5008695).2007FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);20082009return JNI_OK;2010}20112012// This must be called after ergonomics because we want bytecode rewriting2013// if the server compiler is used, or if UseSharedSpaces is disabled.2014void Arguments::set_bytecode_flags() {2015// Better not attempt to store into a read-only space.2016if (UseSharedSpaces) {2017FLAG_SET_DEFAULT(RewriteBytecodes, false);2018FLAG_SET_DEFAULT(RewriteFrequentPairs, false);2019}20202021if (!RewriteBytecodes) {2022FLAG_SET_DEFAULT(RewriteFrequentPairs, false);2023}2024}20252026// Aggressive optimization flags -XX:+AggressiveOpts2027void Arguments::set_aggressive_opts_flags() {2028#ifdef COMPILER22029if (AggressiveUnboxing) {2030if (FLAG_IS_DEFAULT(EliminateAutoBox)) {2031FLAG_SET_DEFAULT(EliminateAutoBox, true);2032} else if (!EliminateAutoBox) {2033// warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");2034AggressiveUnboxing = false;2035}2036if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {2037FLAG_SET_DEFAULT(DoEscapeAnalysis, true);2038} else if (!DoEscapeAnalysis) {2039// warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");2040AggressiveUnboxing = false;2041}2042}2043if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {2044if (FLAG_IS_DEFAULT(EliminateAutoBox)) {2045FLAG_SET_DEFAULT(EliminateAutoBox, true);2046}2047if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {2048FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);2049}20502051// Feed the cache size setting into the JDK2052char buffer[1024];2053jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);2054add_property(buffer);2055}2056if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {2057FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);2058}2059#endif20602061if (AggressiveOpts) {2062// Sample flag setting code2063// if (FLAG_IS_DEFAULT(EliminateZeroing)) {2064// FLAG_SET_DEFAULT(EliminateZeroing, true);2065// }2066}2067}20682069//===========================================================================================================2070// Parsing of java.compiler property20712072void Arguments::process_java_compiler_argument(char* arg) {2073// For backwards compatibility, Djava.compiler=NONE or ""2074// causes us to switch to -Xint mode UNLESS -Xdebug2075// is also specified.2076if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {2077set_java_compiler(true); // "-Djava.compiler[=...]" most recently seen.2078}2079}20802081void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {2082_sun_java_launcher = strdup(launcher);2083if (strcmp("gamma", _sun_java_launcher) == 0) {2084_created_by_gamma_launcher = true;2085}2086}20872088bool Arguments::created_by_java_launcher() {2089assert(_sun_java_launcher != NULL, "property must have value");2090return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;2091}20922093bool Arguments::created_by_gamma_launcher() {2094return _created_by_gamma_launcher;2095}20962097//===========================================================================================================2098// Parsing of main arguments20992100bool Arguments::verify_interval(uintx val, uintx min,2101uintx max, const char* name) {2102// Returns true iff value is in the inclusive interval [min..max]2103// false, otherwise.2104if (val >= min && val <= max) {2105return true;2106}2107jio_fprintf(defaultStream::error_stream(),2108"%s of " UINTX_FORMAT " is invalid; must be between " UINTX_FORMAT2109" and " UINTX_FORMAT "\n",2110name, val, min, max);2111return false;2112}21132114bool Arguments::verify_min_value(intx val, intx min, const char* name) {2115// Returns true if given value is at least specified min threshold2116// false, otherwise.2117if (val >= min ) {2118return true;2119}2120jio_fprintf(defaultStream::error_stream(),2121"%s of " INTX_FORMAT " is invalid; must be at least " INTX_FORMAT "\n",2122name, val, min);2123return false;2124}21252126bool Arguments::verify_percentage(uintx value, const char* name) {2127if (is_percentage(value)) {2128return true;2129}2130jio_fprintf(defaultStream::error_stream(),2131"%s of " UINTX_FORMAT " is invalid; must be between 0 and 100\n",2132name, value);2133return false;2134}21352136// check if do gclog rotation2137// +UseGCLogFileRotation is a must,2138// no gc log rotation when log file not supplied or2139// NumberOfGCLogFiles is 02140void check_gclog_consistency() {2141if (UseGCLogFileRotation) {2142if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {2143jio_fprintf(defaultStream::output_stream(),2144"To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"2145"where num_of_file > 0\n"2146"GC log rotation is turned off\n");2147UseGCLogFileRotation = false;2148}2149}21502151if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {2152FLAG_SET_CMDLINE(uintx, GCLogFileSize, 8*K);2153jio_fprintf(defaultStream::output_stream(),2154"GCLogFileSize changed to minimum 8K\n");2155}2156}21572158// This function is called for -Xloggc:<filename>, it can be used2159// to check if a given file name(or string) conforms to the following2160// specification:2161// A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"2162// %p and %t only allowed once. We only limit usage of filename not path2163bool is_filename_valid(const char *file_name) {2164const char* p = file_name;2165char file_sep = os::file_separator()[0];2166const char* cp;2167// skip prefix path2168for (cp = file_name; *cp != '\0'; cp++) {2169if (*cp == '/' || *cp == file_sep) {2170p = cp + 1;2171}2172}21732174int count_p = 0;2175int count_t = 0;2176while (*p != '\0') {2177if ((*p >= '0' && *p <= '9') ||2178(*p >= 'A' && *p <= 'Z') ||2179(*p >= 'a' && *p <= 'z') ||2180*p == '-' ||2181*p == '_' ||2182*p == '.') {2183p++;2184continue;2185}2186if (*p == '%') {2187if(*(p + 1) == 'p') {2188p += 2;2189count_p ++;2190continue;2191}2192if (*(p + 1) == 't') {2193p += 2;2194count_t ++;2195continue;2196}2197}2198return false;2199}2200return count_p < 2 && count_t < 2;2201}22022203bool Arguments::verify_MinHeapFreeRatio(FormatBuffer<80>& err_msg, uintx min_heap_free_ratio) {2204if (!is_percentage(min_heap_free_ratio)) {2205err_msg.print("MinHeapFreeRatio must have a value between 0 and 100");2206return false;2207}2208if (min_heap_free_ratio > MaxHeapFreeRatio) {2209err_msg.print("MinHeapFreeRatio (" UINTX_FORMAT ") must be less than or "2210"equal to MaxHeapFreeRatio (" UINTX_FORMAT ")", min_heap_free_ratio,2211MaxHeapFreeRatio);2212return false;2213}2214// This does not set the flag itself, but stores the value in a safe place for later usage.2215_min_heap_free_ratio = min_heap_free_ratio;2216return true;2217}22182219bool Arguments::verify_MaxHeapFreeRatio(FormatBuffer<80>& err_msg, uintx max_heap_free_ratio) {2220if (!is_percentage(max_heap_free_ratio)) {2221err_msg.print("MaxHeapFreeRatio must have a value between 0 and 100");2222return false;2223}2224if (max_heap_free_ratio < MinHeapFreeRatio) {2225err_msg.print("MaxHeapFreeRatio (" UINTX_FORMAT ") must be greater than or "2226"equal to MinHeapFreeRatio (" UINTX_FORMAT ")", max_heap_free_ratio,2227MinHeapFreeRatio);2228return false;2229}2230// This does not set the flag itself, but stores the value in a safe place for later usage.2231_max_heap_free_ratio = max_heap_free_ratio;2232return true;2233}22342235// Check consistency of GC selection2236bool Arguments::check_gc_consistency() {2237check_gclog_consistency();2238bool status = true;2239// Ensure that the user has not selected conflicting sets2240// of collectors. [Note: this check is merely a user convenience;2241// collectors over-ride each other so that only a non-conflicting2242// set is selected; however what the user gets is not what they2243// may have expected from the combination they asked for. It's2244// better to reduce user confusion by not allowing them to2245// select conflicting combinations.2246uint i = 0;2247if (UseSerialGC) i++;2248if (UseConcMarkSweepGC || UseParNewGC) i++;2249if (UseParallelGC || UseParallelOldGC) i++;2250if (UseG1GC) i++;2251if (i > 1) {2252jio_fprintf(defaultStream::error_stream(),2253"Conflicting collector combinations in option list; "2254"please refer to the release notes for the combinations "2255"allowed\n");2256status = false;2257}2258return status;2259}22602261void Arguments::check_deprecated_gcs() {2262if (UseConcMarkSweepGC && !UseParNewGC) {2263warning("Using the DefNew young collector with the CMS collector is deprecated "2264"and will likely be removed in a future release");2265}22662267if (UseParNewGC && !UseConcMarkSweepGC) {2268// !UseConcMarkSweepGC means that we are using serial old gc. Unfortunately we don't2269// set up UseSerialGC properly, so that can't be used in the check here.2270warning("Using the ParNew young collector with the Serial old collector is deprecated "2271"and will likely be removed in a future release");2272}22732274if (CMSIncrementalMode) {2275warning("Using incremental CMS is deprecated and will likely be removed in a future release");2276}2277}22782279void Arguments::check_deprecated_gc_flags() {2280if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {2281warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"2282"and will likely be removed in future release");2283}2284if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {2285warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "2286"Use MaxRAMFraction instead.");2287}2288if (FLAG_IS_CMDLINE(UseCMSCompactAtFullCollection)) {2289warning("UseCMSCompactAtFullCollection is deprecated and will likely be removed in a future release.");2290}2291if (FLAG_IS_CMDLINE(CMSFullGCsBeforeCompaction)) {2292warning("CMSFullGCsBeforeCompaction is deprecated and will likely be removed in a future release.");2293}2294if (FLAG_IS_CMDLINE(UseCMSCollectionPassing)) {2295warning("UseCMSCollectionPassing is deprecated and will likely be removed in a future release.");2296}2297}22982299// Check stack pages settings2300bool Arguments::check_stack_pages()2301{2302bool status = true;2303status = status && verify_min_value(StackYellowPages, 1, "StackYellowPages");2304status = status && verify_min_value(StackRedPages, 1, "StackRedPages");2305// greater stack shadow pages can't generate instruction to bang stack2306status = status && verify_interval(StackShadowPages, 1, 50, "StackShadowPages");2307return status;2308}23092310// Check the consistency of vm_init_args2311bool Arguments::check_vm_args_consistency() {2312// Method for adding checks for flag consistency.2313// The intent is to warn the user of all possible conflicts,2314// before returning an error.2315// Note: Needs platform-dependent factoring.2316bool status = true;23172318// Allow both -XX:-UseStackBanging and -XX:-UseBoundThreads in non-product2319// builds so the cost of stack banging can be measured.2320#if (defined(PRODUCT) && defined(SOLARIS))2321if (!UseBoundThreads && !UseStackBanging) {2322jio_fprintf(defaultStream::error_stream(),2323"-UseStackBanging conflicts with -UseBoundThreads\n");23242325status = false;2326}2327#endif23282329if (TLABRefillWasteFraction == 0) {2330jio_fprintf(defaultStream::error_stream(),2331"TLABRefillWasteFraction should be a denominator, "2332"not " SIZE_FORMAT "\n",2333TLABRefillWasteFraction);2334status = false;2335}23362337status = status && verify_interval(AdaptiveSizePolicyWeight, 0, 100,2338"AdaptiveSizePolicyWeight");2339status = status && verify_percentage(ThresholdTolerance, "ThresholdTolerance");23402341// Divide by bucket size to prevent a large size from causing rollover when2342// calculating amount of memory needed to be allocated for the String table.2343status = status && verify_interval(StringTableSize, minimumStringTableSize,2344(max_uintx / StringTable::bucket_size()), "StringTable size");23452346status = status && verify_interval(SymbolTableSize, minimumSymbolTableSize,2347(max_uintx / SymbolTable::bucket_size()), "SymbolTable size");23482349{2350// Using "else if" below to avoid printing two error messages if min > max.2351// This will also prevent us from reporting both min>100 and max>100 at the2352// same time, but that is less annoying than printing two identical errors IMHO.2353FormatBuffer<80> err_msg("%s","");2354if (!verify_MinHeapFreeRatio(err_msg, MinHeapFreeRatio)) {2355jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());2356status = false;2357} else if (!verify_MaxHeapFreeRatio(err_msg, MaxHeapFreeRatio)) {2358jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());2359status = false;2360}2361}23622363// Min/MaxMetaspaceFreeRatio2364status = status && verify_percentage(MinMetaspaceFreeRatio, "MinMetaspaceFreeRatio");2365status = status && verify_percentage(MaxMetaspaceFreeRatio, "MaxMetaspaceFreeRatio");23662367if (MinMetaspaceFreeRatio > MaxMetaspaceFreeRatio) {2368jio_fprintf(defaultStream::error_stream(),2369"MinMetaspaceFreeRatio (%s" UINTX_FORMAT ") must be less than or "2370"equal to MaxMetaspaceFreeRatio (%s" UINTX_FORMAT ")\n",2371FLAG_IS_DEFAULT(MinMetaspaceFreeRatio) ? "Default: " : "",2372MinMetaspaceFreeRatio,2373FLAG_IS_DEFAULT(MaxMetaspaceFreeRatio) ? "Default: " : "",2374MaxMetaspaceFreeRatio);2375status = false;2376}23772378// Trying to keep 100% free is not practical2379MinMetaspaceFreeRatio = MIN2(MinMetaspaceFreeRatio, (uintx) 99);23802381if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {2382MarkSweepAlwaysCompactCount = 1; // Move objects every gc.2383}23842385if (UseParallelOldGC && ParallelOldGCSplitALot) {2386// Settings to encourage splitting.2387if (!FLAG_IS_CMDLINE(NewRatio)) {2388FLAG_SET_CMDLINE(uintx, NewRatio, 2);2389}2390if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {2391FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);2392}2393}23942395status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit");2396status = status && verify_percentage(GCTimeLimit, "GCTimeLimit");2397if (GCTimeLimit == 100) {2398// Turn off gc-overhead-limit-exceeded checks2399FLAG_SET_DEFAULT(UseGCOverheadLimit, false);2400}24012402status = status && check_gc_consistency();2403status = status && check_stack_pages();24042405if (CMSIncrementalMode) {2406if (!UseConcMarkSweepGC) {2407jio_fprintf(defaultStream::error_stream(),2408"error: invalid argument combination.\n"2409"The CMS collector (-XX:+UseConcMarkSweepGC) must be "2410"selected in order\nto use CMSIncrementalMode.\n");2411status = false;2412} else {2413status = status && verify_percentage(CMSIncrementalDutyCycle,2414"CMSIncrementalDutyCycle");2415status = status && verify_percentage(CMSIncrementalDutyCycleMin,2416"CMSIncrementalDutyCycleMin");2417status = status && verify_percentage(CMSIncrementalSafetyFactor,2418"CMSIncrementalSafetyFactor");2419status = status && verify_percentage(CMSIncrementalOffset,2420"CMSIncrementalOffset");2421status = status && verify_percentage(CMSExpAvgFactor,2422"CMSExpAvgFactor");2423// If it was not set on the command line, set2424// CMSInitiatingOccupancyFraction to 1 so icms can initiate cycles early.2425if (CMSInitiatingOccupancyFraction < 0) {2426FLAG_SET_DEFAULT(CMSInitiatingOccupancyFraction, 1);2427}2428}2429}24302431// CMS space iteration, which FLSVerifyAllHeapreferences entails,2432// insists that we hold the requisite locks so that the iteration is2433// MT-safe. For the verification at start-up and shut-down, we don't2434// yet have a good way of acquiring and releasing these locks,2435// which are not visible at the CollectedHeap level. We want to2436// be able to acquire these locks and then do the iteration rather2437// than just disable the lock verification. This will be fixed under2438// bug 4788986.2439if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {2440if (VerifyDuringStartup) {2441warning("Heap verification at start-up disabled "2442"(due to current incompatibility with FLSVerifyAllHeapReferences)");2443VerifyDuringStartup = false; // Disable verification at start-up2444}24452446if (VerifyBeforeExit) {2447warning("Heap verification at shutdown disabled "2448"(due to current incompatibility with FLSVerifyAllHeapReferences)");2449VerifyBeforeExit = false; // Disable verification at shutdown2450}2451}24522453// Note: only executed in non-PRODUCT mode2454if (!UseAsyncConcMarkSweepGC &&2455(ExplicitGCInvokesConcurrent ||2456ExplicitGCInvokesConcurrentAndUnloadsClasses)) {2457jio_fprintf(defaultStream::error_stream(),2458"error: +ExplicitGCInvokesConcurrent[AndUnloadsClasses] conflicts"2459" with -UseAsyncConcMarkSweepGC");2460status = false;2461}24622463status = status && verify_min_value(ParGCArrayScanChunk, 1, "ParGCArrayScanChunk");24642465#if INCLUDE_ALL_GCS2466if (UseG1GC) {2467status = status && verify_percentage(G1NewSizePercent, "G1NewSizePercent");2468status = status && verify_percentage(G1MaxNewSizePercent, "G1MaxNewSizePercent");2469status = status && verify_interval(G1NewSizePercent, 0, G1MaxNewSizePercent, "G1NewSizePercent");24702471status = status && verify_percentage(InitiatingHeapOccupancyPercent,2472"InitiatingHeapOccupancyPercent");2473status = status && verify_min_value(G1RefProcDrainInterval, 1,2474"G1RefProcDrainInterval");2475status = status && verify_min_value((intx)G1ConcMarkStepDurationMillis, 1,2476"G1ConcMarkStepDurationMillis");2477status = status && verify_interval(G1ConcRSHotCardLimit, 0, max_jubyte,2478"G1ConcRSHotCardLimit");2479status = status && verify_interval(G1ConcRSLogCacheSize, 0, 27,2480"G1ConcRSLogCacheSize");2481status = status && verify_interval(StringDeduplicationAgeThreshold, 1, markOopDesc::max_age,2482"StringDeduplicationAgeThreshold");2483}2484if (UseConcMarkSweepGC) {2485status = status && verify_min_value(CMSOldPLABNumRefills, 1, "CMSOldPLABNumRefills");2486status = status && verify_min_value(CMSOldPLABToleranceFactor, 1, "CMSOldPLABToleranceFactor");2487status = status && verify_min_value(CMSOldPLABMax, 1, "CMSOldPLABMax");2488status = status && verify_interval(CMSOldPLABMin, 1, CMSOldPLABMax, "CMSOldPLABMin");24892490status = status && verify_min_value(CMSYoungGenPerWorker, 1, "CMSYoungGenPerWorker");24912492status = status && verify_min_value(CMSSamplingGrain, 1, "CMSSamplingGrain");2493status = status && verify_interval(CMS_SweepWeight, 0, 100, "CMS_SweepWeight");2494status = status && verify_interval(CMS_FLSWeight, 0, 100, "CMS_FLSWeight");24952496status = status && verify_interval(FLSCoalescePolicy, 0, 4, "FLSCoalescePolicy");24972498status = status && verify_min_value(CMSRescanMultiple, 1, "CMSRescanMultiple");2499status = status && verify_min_value(CMSConcMarkMultiple, 1, "CMSConcMarkMultiple");25002501status = status && verify_interval(CMSPrecleanIter, 0, 9, "CMSPrecleanIter");2502status = status && verify_min_value(CMSPrecleanDenominator, 1, "CMSPrecleanDenominator");2503status = status && verify_interval(CMSPrecleanNumerator, 0, CMSPrecleanDenominator - 1, "CMSPrecleanNumerator");25042505status = status && verify_percentage(CMSBootstrapOccupancy, "CMSBootstrapOccupancy");25062507status = status && verify_min_value(CMSPrecleanThreshold, 100, "CMSPrecleanThreshold");25082509status = status && verify_percentage(CMSScheduleRemarkEdenPenetration, "CMSScheduleRemarkEdenPenetration");2510status = status && verify_min_value(CMSScheduleRemarkSamplingRatio, 1, "CMSScheduleRemarkSamplingRatio");2511status = status && verify_min_value(CMSBitMapYieldQuantum, 1, "CMSBitMapYieldQuantum");2512status = status && verify_percentage(CMSTriggerRatio, "CMSTriggerRatio");2513status = status && verify_percentage(CMSIsTooFullPercentage, "CMSIsTooFullPercentage");2514}25152516if (UseParallelGC || UseParallelOldGC) {2517status = status && verify_interval(ParallelOldDeadWoodLimiterMean, 0, 100, "ParallelOldDeadWoodLimiterMean");2518status = status && verify_interval(ParallelOldDeadWoodLimiterStdDev, 0, 100, "ParallelOldDeadWoodLimiterStdDev");25192520status = status && verify_percentage(YoungGenerationSizeIncrement, "YoungGenerationSizeIncrement");2521status = status && verify_percentage(TenuredGenerationSizeIncrement, "TenuredGenerationSizeIncrement");25222523status = status && verify_min_value(YoungGenerationSizeSupplementDecay, 1, "YoungGenerationSizeSupplementDecay");2524status = status && verify_min_value(TenuredGenerationSizeSupplementDecay, 1, "TenuredGenerationSizeSupplementDecay");25252526status = status && verify_min_value(ParGCCardsPerStrideChunk, 1, "ParGCCardsPerStrideChunk");25272528status = status && verify_min_value(ParallelOldGCSplitInterval, 0, "ParallelOldGCSplitInterval");2529}2530#endif // INCLUDE_ALL_GCS25312532status = status && verify_interval(RefDiscoveryPolicy,2533ReferenceProcessor::DiscoveryPolicyMin,2534ReferenceProcessor::DiscoveryPolicyMax,2535"RefDiscoveryPolicy");25362537// Limit the lower bound of this flag to 1 as it is used in a division2538// expression.2539status = status && verify_interval(TLABWasteTargetPercent,25401, 100, "TLABWasteTargetPercent");25412542status = status && verify_object_alignment();25432544status = status && verify_interval(CompressedClassSpaceSize, 1*M, 3*G,2545"CompressedClassSpaceSize");25462547status = status && verify_interval(MarkStackSizeMax,25481, (max_jint - 1), "MarkStackSizeMax");2549status = status && verify_interval(NUMAChunkResizeWeight, 0, 100, "NUMAChunkResizeWeight");25502551status = status && verify_min_value(LogEventsBufferEntries, 1, "LogEventsBufferEntries");25522553status = status && verify_min_value(HeapSizePerGCThread, (uintx) os::vm_page_size(), "HeapSizePerGCThread");25542555status = status && verify_min_value(GCTaskTimeStampEntries, 1, "GCTaskTimeStampEntries");25562557status = status && verify_percentage(ParallelGCBufferWastePct, "ParallelGCBufferWastePct");2558status = status && verify_interval(TargetPLABWastePct, 1, 100, "TargetPLABWastePct");25592560status = status && verify_min_value(ParGCStridesPerThread, 1, "ParGCStridesPerThread");25612562status = status && verify_min_value(MinRAMFraction, 1, "MinRAMFraction");2563status = status && verify_min_value(InitialRAMFraction, 1, "InitialRAMFraction");2564status = status && verify_min_value(MaxRAMFraction, 1, "MaxRAMFraction");2565status = status && verify_min_value(DefaultMaxRAMFraction, 1, "DefaultMaxRAMFraction");25662567status = status && verify_interval(AdaptiveTimeWeight, 0, 100, "AdaptiveTimeWeight");2568status = status && verify_min_value(AdaptiveSizeDecrementScaleFactor, 1, "AdaptiveSizeDecrementScaleFactor");25692570status = status && verify_interval(TLABAllocationWeight, 0, 100, "TLABAllocationWeight");2571status = status && verify_min_value(MinTLABSize, 1, "MinTLABSize");2572status = status && verify_min_value(TLABRefillWasteFraction, 1, "TLABRefillWasteFraction");25732574status = status && verify_percentage(YoungGenerationSizeSupplement, "YoungGenerationSizeSupplement");2575status = status && verify_percentage(TenuredGenerationSizeSupplement, "TenuredGenerationSizeSupplement");25762577// the "age" field in the oop header is 4 bits; do not want to pull in markOop.hpp2578// just for that, so hardcode here.2579status = status && verify_interval(MaxTenuringThreshold, 0, 15, "MaxTenuringThreshold");2580status = status && verify_interval(InitialTenuringThreshold, 0, MaxTenuringThreshold, "MaxTenuringThreshold");2581status = status && verify_percentage(TargetSurvivorRatio, "TargetSurvivorRatio");2582status = status && verify_percentage(MarkSweepDeadRatio, "MarkSweepDeadRatio");25832584status = status && verify_min_value(MarkSweepAlwaysCompactCount, 1, "MarkSweepAlwaysCompactCount");2585#ifdef COMPILER12586status = status && verify_min_value(ValueMapInitialSize, 1, "ValueMapInitialSize");2587#endif25882589if (PrintNMTStatistics) {2590#if INCLUDE_NMT2591if (MemTracker::tracking_level() == NMT_off) {2592#endif // INCLUDE_NMT2593warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");2594PrintNMTStatistics = false;2595#if INCLUDE_NMT2596}2597#endif2598}25992600// Need to limit the extent of the padding to reasonable size.2601// 8K is well beyond the reasonable HW cache line size, even with the2602// aggressive prefetching, while still leaving the room for segregating2603// among the distinct pages.2604if (ContendedPaddingWidth < 0 || ContendedPaddingWidth > 8192) {2605jio_fprintf(defaultStream::error_stream(),2606"ContendedPaddingWidth=" INTX_FORMAT " must be in between %d and %d\n",2607ContendedPaddingWidth, 0, 8192);2608status = false;2609}26102611// Need to enforce the padding not to break the existing field alignments.2612// It is sufficient to check against the largest type size.2613if ((ContendedPaddingWidth % BytesPerLong) != 0) {2614jio_fprintf(defaultStream::error_stream(),2615"ContendedPaddingWidth=" INTX_FORMAT " must be a multiple of %d\n",2616ContendedPaddingWidth, BytesPerLong);2617status = false;2618}26192620// Check lower bounds of the code cache2621// Template Interpreter code is approximately 3X larger in debug builds.2622uint min_code_cache_size = (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3)) + CodeCacheMinimumFreeSpace;2623if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {2624jio_fprintf(defaultStream::error_stream(),2625"Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,2626os::vm_page_size()/K);2627status = false;2628} else if (ReservedCodeCacheSize < InitialCodeCacheSize) {2629jio_fprintf(defaultStream::error_stream(),2630"Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",2631ReservedCodeCacheSize/K, InitialCodeCacheSize/K);2632status = false;2633} else if (ReservedCodeCacheSize < min_code_cache_size) {2634jio_fprintf(defaultStream::error_stream(),2635"Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,2636min_code_cache_size/K);2637status = false;2638} else if (ReservedCodeCacheSize > 2*G) {2639// Code cache size larger than MAXINT is not supported.2640jio_fprintf(defaultStream::error_stream(),2641"Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,2642(2*G)/M);2643status = false;2644}26452646status &= verify_interval(NmethodSweepFraction, 1, ReservedCodeCacheSize/K, "NmethodSweepFraction");2647status &= verify_interval(NmethodSweepActivity, 0, 2000, "NmethodSweepActivity");26482649if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {2650warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");2651}26522653#ifdef COMPILER12654status &= verify_interval(SafepointPollOffset, 0, os::vm_page_size() - BytesPerWord, "SafepointPollOffset");2655#endif26562657int min_number_of_compiler_threads = get_min_number_of_compiler_threads();2658// The default CICompilerCount's value is CI_COMPILER_COUNT.2659assert(min_number_of_compiler_threads <= CI_COMPILER_COUNT, "minimum should be less or equal default number");2660// Check the minimum number of compiler threads2661status &=verify_min_value(CICompilerCount, min_number_of_compiler_threads, "CICompilerCount");26622663return status;2664}26652666bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,2667const char* option_type) {2668if (ignore) return false;26692670const char* spacer = " ";2671if (option_type == NULL) {2672option_type = ++spacer; // Set both to the empty string.2673}26742675if (os::obsolete_option(option)) {2676jio_fprintf(defaultStream::error_stream(),2677"Obsolete %s%soption: %s\n", option_type, spacer,2678option->optionString);2679return false;2680} else {2681jio_fprintf(defaultStream::error_stream(),2682"Unrecognized %s%soption: %s\n", option_type, spacer,2683option->optionString);2684return true;2685}2686}26872688static const char* user_assertion_options[] = {2689"-da", "-ea", "-disableassertions", "-enableassertions", 02690};26912692static const char* system_assertion_options[] = {2693"-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 02694};26952696// Return true if any of the strings in null-terminated array 'names' matches.2697// If tail_allowed is true, then the tail must begin with a colon; otherwise,2698// the option must match exactly.2699static bool match_option(const JavaVMOption* option, const char** names, const char** tail,2700bool tail_allowed) {2701for (/* empty */; *names != NULL; ++names) {2702if (match_option(option, *names, tail)) {2703if (**tail == '\0' || tail_allowed && **tail == ':') {2704return true;2705}2706}2707}2708return false;2709}27102711bool Arguments::parse_uintx(const char* value,2712uintx* uintx_arg,2713uintx min_size) {27142715// Check the sign first since atomull() parses only unsigned values.2716bool value_is_positive = !(*value == '-');27172718if (value_is_positive) {2719julong n;2720bool good_return = atomull(value, &n);2721if (good_return) {2722bool above_minimum = n >= min_size;2723bool value_is_too_large = n > max_uintx;27242725if (above_minimum && !value_is_too_large) {2726*uintx_arg = n;2727return true;2728}2729}2730}2731return false;2732}27332734Arguments::ArgsRange Arguments::parse_memory_size(const char* s,2735julong* long_arg,2736julong min_size) {2737if (!atomull(s, long_arg)) return arg_unreadable;2738return check_memory_size(*long_arg, min_size);2739}27402741// Parse JavaVMInitArgs structure27422743jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {2744// For components of the system classpath.2745SysClassPath scp(Arguments::get_sysclasspath());2746bool scp_assembly_required = false;27472748// Save default settings for some mode flags2749Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;2750Arguments::_UseOnStackReplacement = UseOnStackReplacement;2751Arguments::_ClipInlining = ClipInlining;2752Arguments::_BackgroundCompilation = BackgroundCompilation;27532754// Setup flags for mixed which is the default2755set_mode_flags(_mixed);27562757// Parse JAVA_TOOL_OPTIONS environment variable (if present)2758jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);2759if (result != JNI_OK) {2760return result;2761}27622763// Parse JavaVMInitArgs structure passed in2764result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, Flag::COMMAND_LINE);2765if (result != JNI_OK) {2766return result;2767}27682769// Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)2770result = parse_java_options_environment_variable(&scp, &scp_assembly_required);2771if (result != JNI_OK) {2772return result;2773}27742775// We need to ensure processor and memory resources have been properly2776// configured - which may rely on arguments we just processed - before2777// doing the final argument processing. Any argument processing that2778// needs to know about processor and memory resources must occur after2779// this point.27802781os::init_container_support();27822783// Do final processing now that all arguments have been parsed2784result = finalize_vm_init_args(&scp, scp_assembly_required);2785if (result != JNI_OK) {2786return result;2787}27882789return JNI_OK;2790}27912792// Checks if name in command-line argument -agent{lib,path}:name[=options]2793// represents a valid HPROF of JDWP agent. is_path==true denotes that we2794// are dealing with -agentpath (case where name is a path), otherwise with2795// -agentlib2796bool valid_hprof_or_jdwp_agent(char *name, bool is_path) {2797char *_name;2798const char *_hprof = "hprof", *_jdwp = "jdwp";2799size_t _len_hprof, _len_jdwp, _len_prefix;28002801if (is_path) {2802if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {2803return false;2804}28052806_name++; // skip past last path separator2807_len_prefix = strlen(JNI_LIB_PREFIX);28082809if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {2810return false;2811}28122813_name += _len_prefix;2814_len_hprof = strlen(_hprof);2815_len_jdwp = strlen(_jdwp);28162817if (strncmp(_name, _hprof, _len_hprof) == 0) {2818_name += _len_hprof;2819}2820else if (strncmp(_name, _jdwp, _len_jdwp) == 0) {2821_name += _len_jdwp;2822}2823else {2824return false;2825}28262827if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {2828return false;2829}28302831return true;2832}28332834if (strcmp(name, _hprof) == 0 || strcmp(name, _jdwp) == 0) {2835return true;2836}28372838return false;2839}28402841jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,2842SysClassPath* scp_p,2843bool* scp_assembly_required_p,2844Flag::Flags origin) {2845// Remaining part of option string2846const char* tail;28472848// iterate over arguments2849for (int index = 0; index < args->nOptions; index++) {2850bool is_absolute_path = false; // for -agentpath vs -agentlib28512852const JavaVMOption* option = args->options + index;28532854if (!match_option(option, "-Djava.class.path", &tail) &&2855!match_option(option, "-Dsun.java.command", &tail) &&2856!match_option(option, "-Dsun.java.launcher", &tail)) {28572858// add all jvm options to the jvm_args string. This string2859// is used later to set the java.vm.args PerfData string constant.2860// the -Djava.class.path and the -Dsun.java.command options are2861// omitted from jvm_args string as each have their own PerfData2862// string constant object.2863build_jvm_args(option->optionString);2864}28652866// -verbose:[class/gc/jni]2867if (match_option(option, "-verbose", &tail)) {2868if (!strcmp(tail, ":class") || !strcmp(tail, "")) {2869FLAG_SET_CMDLINE(bool, TraceClassLoading, true);2870FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);2871} else if (!strcmp(tail, ":gc")) {2872FLAG_SET_CMDLINE(bool, PrintGC, true);2873} else if (!strcmp(tail, ":jni")) {2874FLAG_SET_CMDLINE(bool, PrintJNIResolving, true);2875}2876// -da / -ea / -disableassertions / -enableassertions2877// These accept an optional class/package name separated by a colon, e.g.,2878// -da:java.lang.Thread.2879} else if (match_option(option, user_assertion_options, &tail, true)) {2880bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'2881if (*tail == '\0') {2882JavaAssertions::setUserClassDefault(enable);2883} else {2884assert(*tail == ':', "bogus match by match_option()");2885JavaAssertions::addOption(tail + 1, enable);2886}2887// -dsa / -esa / -disablesystemassertions / -enablesystemassertions2888} else if (match_option(option, system_assertion_options, &tail, false)) {2889bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'2890JavaAssertions::setSystemClassDefault(enable);2891// -bootclasspath:2892} else if (match_option(option, "-Xbootclasspath:", &tail)) {2893scp_p->reset_path(tail);2894*scp_assembly_required_p = true;2895// -bootclasspath/a:2896} else if (match_option(option, "-Xbootclasspath/a:", &tail)) {2897scp_p->add_suffix(tail);2898*scp_assembly_required_p = true;2899// -bootclasspath/p:2900} else if (match_option(option, "-Xbootclasspath/p:", &tail)) {2901scp_p->add_prefix(tail);2902*scp_assembly_required_p = true;2903// -Xrun2904} else if (match_option(option, "-Xrun", &tail)) {2905if (tail != NULL) {2906const char* pos = strchr(tail, ':');2907size_t len = (pos == NULL) ? strlen(tail) : pos - tail;2908char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);2909name[len] = '\0';29102911char *options = NULL;2912if(pos != NULL) {2913size_t len2 = strlen(pos+1) + 1; // options start after ':'. Final zero must be copied.2914options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);2915}2916#if !INCLUDE_JVMTI2917if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {2918jio_fprintf(defaultStream::error_stream(),2919"Profiling and debugging agents are not supported in this VM\n");2920return JNI_ERR;2921}2922#endif // !INCLUDE_JVMTI2923add_init_library(name, options);2924}2925// -agentlib and -agentpath2926} else if (match_option(option, "-agentlib:", &tail) ||2927(is_absolute_path = match_option(option, "-agentpath:", &tail))) {2928if(tail != NULL) {2929const char* pos = strchr(tail, '=');2930size_t len = (pos == NULL) ? strlen(tail) : pos - tail;2931char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);2932name[len] = '\0';29332934char *options = NULL;2935if(pos != NULL) {2936size_t length = strlen(pos + 1) + 1;2937options = NEW_C_HEAP_ARRAY(char, length, mtInternal);2938jio_snprintf(options, length, "%s", pos + 1);2939}2940#if !INCLUDE_JVMTI2941if (valid_hprof_or_jdwp_agent(name, is_absolute_path)) {2942jio_fprintf(defaultStream::error_stream(),2943"Profiling and debugging agents are not supported in this VM\n");2944return JNI_ERR;2945}2946#endif // !INCLUDE_JVMTI2947add_init_agent(name, options, is_absolute_path);2948}2949// -javaagent2950} else if (match_option(option, "-javaagent:", &tail)) {2951#if !INCLUDE_JVMTI2952jio_fprintf(defaultStream::error_stream(),2953"Instrumentation agents are not supported in this VM\n");2954return JNI_ERR;2955#else2956if(tail != NULL) {2957size_t length = strlen(tail) + 1;2958char *options = NEW_C_HEAP_ARRAY(char, length, mtInternal);2959jio_snprintf(options, length, "%s", tail);2960add_init_agent("instrument", options, false);2961}2962#endif // !INCLUDE_JVMTI2963// -Xnoclassgc2964} else if (match_option(option, "-Xnoclassgc", &tail)) {2965FLAG_SET_CMDLINE(bool, ClassUnloading, false);2966// -Xincgc: i-CMS2967} else if (match_option(option, "-Xincgc", &tail)) {2968FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);2969FLAG_SET_CMDLINE(bool, CMSIncrementalMode, true);2970// -Xnoincgc: no i-CMS2971} else if (match_option(option, "-Xnoincgc", &tail)) {2972FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);2973FLAG_SET_CMDLINE(bool, CMSIncrementalMode, false);2974// -Xconcgc2975} else if (match_option(option, "-Xconcgc", &tail)) {2976FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);2977// -Xnoconcgc2978} else if (match_option(option, "-Xnoconcgc", &tail)) {2979FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);2980// -Xbatch2981} else if (match_option(option, "-Xbatch", &tail)) {2982FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);2983// -Xmn for compatibility with other JVM vendors2984} else if (match_option(option, "-Xmn", &tail)) {2985julong long_initial_young_size = 0;2986ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);2987if (errcode != arg_in_range) {2988jio_fprintf(defaultStream::error_stream(),2989"Invalid initial young generation size: %s\n", option->optionString);2990describe_range_error(errcode);2991return JNI_EINVAL;2992}2993FLAG_SET_CMDLINE(uintx, MaxNewSize, (uintx)long_initial_young_size);2994FLAG_SET_CMDLINE(uintx, NewSize, (uintx)long_initial_young_size);2995// -Xms2996} else if (match_option(option, "-Xms", &tail)) {2997julong long_initial_heap_size = 0;2998// an initial heap size of 0 means automatically determine2999ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);3000if (errcode != arg_in_range) {3001jio_fprintf(defaultStream::error_stream(),3002"Invalid initial heap size: %s\n", option->optionString);3003describe_range_error(errcode);3004return JNI_EINVAL;3005}3006set_min_heap_size((uintx)long_initial_heap_size);3007// Currently the minimum size and the initial heap sizes are the same.3008// Can be overridden with -XX:InitialHeapSize.3009FLAG_SET_CMDLINE(uintx, InitialHeapSize, (uintx)long_initial_heap_size);3010// -Xmx3011} else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {3012julong long_max_heap_size = 0;3013ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);3014if (errcode != arg_in_range) {3015jio_fprintf(defaultStream::error_stream(),3016"Invalid maximum heap size: %s\n", option->optionString);3017describe_range_error(errcode);3018return JNI_EINVAL;3019}3020FLAG_SET_CMDLINE(uintx, MaxHeapSize, (uintx)long_max_heap_size);3021// Xmaxf3022} else if (match_option(option, "-Xmaxf", &tail)) {3023char* err;3024int maxf = (int)(strtod(tail, &err) * 100);3025if (*err != '\0' || *tail == '\0' || maxf < 0 || maxf > 100) {3026jio_fprintf(defaultStream::error_stream(),3027"Bad max heap free percentage size: %s\n",3028option->optionString);3029return JNI_EINVAL;3030} else {3031FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf);3032}3033// Xminf3034} else if (match_option(option, "-Xminf", &tail)) {3035char* err;3036int minf = (int)(strtod(tail, &err) * 100);3037if (*err != '\0' || *tail == '\0' || minf < 0 || minf > 100) {3038jio_fprintf(defaultStream::error_stream(),3039"Bad min heap free percentage size: %s\n",3040option->optionString);3041return JNI_EINVAL;3042} else {3043FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf);3044}3045// -Xss3046} else if (match_option(option, "-Xss", &tail)) {3047julong long_ThreadStackSize = 0;3048ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);3049if (errcode != arg_in_range) {3050jio_fprintf(defaultStream::error_stream(),3051"Invalid thread stack size: %s\n", option->optionString);3052describe_range_error(errcode);3053return JNI_EINVAL;3054}3055// Internally track ThreadStackSize in units of 1024 bytes.3056FLAG_SET_CMDLINE(intx, ThreadStackSize,3057round_to((int)long_ThreadStackSize, K) / K);3058// -Xoss3059} else if (match_option(option, "-Xoss", &tail)) {3060// HotSpot does not have separate native and Java stacks, ignore silently for compatibility3061} else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {3062julong long_CodeCacheExpansionSize = 0;3063ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());3064if (errcode != arg_in_range) {3065jio_fprintf(defaultStream::error_stream(),3066"Invalid argument: %s. Must be at least %luK.\n", option->optionString,3067os::vm_page_size()/K);3068return JNI_EINVAL;3069}3070FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize);3071} else if (match_option(option, "-Xmaxjitcodesize", &tail) ||3072match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {3073julong long_ReservedCodeCacheSize = 0;30743075ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);3076if (errcode != arg_in_range) {3077jio_fprintf(defaultStream::error_stream(),3078"Invalid maximum code cache size: %s.\n", option->optionString);3079return JNI_EINVAL;3080}3081FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize);3082//-XX:IncreaseFirstTierCompileThresholdAt=3083} else if (match_option(option, "-XX:IncreaseFirstTierCompileThresholdAt=", &tail)) {3084uintx uint_IncreaseFirstTierCompileThresholdAt = 0;3085if (!parse_uintx(tail, &uint_IncreaseFirstTierCompileThresholdAt, 0) || uint_IncreaseFirstTierCompileThresholdAt > 99) {3086jio_fprintf(defaultStream::error_stream(),3087"Invalid value for IncreaseFirstTierCompileThresholdAt: %s. Should be between 0 and 99.\n",3088option->optionString);3089return JNI_EINVAL;3090}3091FLAG_SET_CMDLINE(uintx, IncreaseFirstTierCompileThresholdAt, (uintx)uint_IncreaseFirstTierCompileThresholdAt);3092// -green3093} else if (match_option(option, "-green", &tail)) {3094jio_fprintf(defaultStream::error_stream(),3095"Green threads support not available\n");3096return JNI_EINVAL;3097// -native3098} else if (match_option(option, "-native", &tail)) {3099// HotSpot always uses native threads, ignore silently for compatibility3100// -Xsqnopause3101} else if (match_option(option, "-Xsqnopause", &tail)) {3102// EVM option, ignore silently for compatibility3103// -Xrs3104} else if (match_option(option, "-Xrs", &tail)) {3105// Classic/EVM option, new functionality3106FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true);3107} else if (match_option(option, "-Xusealtsigs", &tail)) {3108// change default internal VM signals used - lower case for back compat3109FLAG_SET_CMDLINE(bool, UseAltSigs, true);3110// -Xoptimize3111} else if (match_option(option, "-Xoptimize", &tail)) {3112// EVM option, ignore silently for compatibility3113// -Xprof3114} else if (match_option(option, "-Xprof", &tail)) {3115#if INCLUDE_FPROF3116_has_profile = true;3117#else // INCLUDE_FPROF3118jio_fprintf(defaultStream::error_stream(),3119"Flat profiling is not supported in this VM.\n");3120return JNI_ERR;3121#endif // INCLUDE_FPROF3122// -Xconcurrentio3123} else if (match_option(option, "-Xconcurrentio", &tail)) {3124FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true);3125FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);3126FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1);3127FLAG_SET_CMDLINE(bool, UseTLAB, false);3128FLAG_SET_CMDLINE(uintx, NewSizeThreadIncrease, 16 * K); // 20Kb per thread added to new generation31293130// -Xinternalversion3131} else if (match_option(option, "-Xinternalversion", &tail)) {3132jio_fprintf(defaultStream::output_stream(), "%s\n",3133VM_Version::internal_vm_info_string());3134vm_exit(0);3135#ifndef PRODUCT3136// -Xprintflags3137} else if (match_option(option, "-Xprintflags", &tail)) {3138CommandLineFlags::printFlags(tty, false);3139vm_exit(0);3140#endif3141// -D3142} else if (match_option(option, "-D", &tail)) {3143if (CheckEndorsedAndExtDirs) {3144if (match_option(option, "-Djava.endorsed.dirs=", &tail)) {3145// abort if -Djava.endorsed.dirs is set3146jio_fprintf(defaultStream::output_stream(),3147"-Djava.endorsed.dirs will not be supported in a future release.\n"3148"Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");3149return JNI_EINVAL;3150}3151if (match_option(option, "-Djava.ext.dirs=", &tail)) {3152// abort if -Djava.ext.dirs is set3153jio_fprintf(defaultStream::output_stream(),3154"-Djava.ext.dirs will not be supported in a future release.\n"3155"Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");3156return JNI_EINVAL;3157}3158}31593160if (!add_property(tail)) {3161return JNI_ENOMEM;3162}3163// Out of the box management support3164if (match_option(option, "-Dcom.sun.management", &tail)) {3165#if INCLUDE_MANAGEMENT3166FLAG_SET_CMDLINE(bool, ManagementServer, true);3167#else3168jio_fprintf(defaultStream::output_stream(),3169"-Dcom.sun.management is not supported in this VM.\n");3170return JNI_ERR;3171#endif3172}3173// -Xint3174} else if (match_option(option, "-Xint", &tail)) {3175set_mode_flags(_int);3176// -Xmixed3177} else if (match_option(option, "-Xmixed", &tail)) {3178set_mode_flags(_mixed);3179// -Xcomp3180} else if (match_option(option, "-Xcomp", &tail)) {3181// for testing the compiler; turn off all flags that inhibit compilation3182set_mode_flags(_comp);3183// -Xshare:dump3184} else if (match_option(option, "-Xshare:dump", &tail)) {3185FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);3186set_mode_flags(_int); // Prevent compilation, which creates objects3187// -Xshare:on3188} else if (match_option(option, "-Xshare:on", &tail)) {3189FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);3190FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);3191// -Xshare:auto3192} else if (match_option(option, "-Xshare:auto", &tail)) {3193FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);3194FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);3195// -Xshare:off3196} else if (match_option(option, "-Xshare:off", &tail)) {3197FLAG_SET_CMDLINE(bool, UseSharedSpaces, false);3198FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);3199// -Xverify3200} else if (match_option(option, "-Xverify", &tail)) {3201if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {3202FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true);3203FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);3204} else if (strcmp(tail, ":remote") == 0) {3205FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);3206FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);3207} else if (strcmp(tail, ":none") == 0) {3208FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);3209FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false);3210} else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {3211return JNI_EINVAL;3212}3213// -Xdebug3214} else if (match_option(option, "-Xdebug", &tail)) {3215// note this flag has been used, then ignore3216set_xdebug_mode(true);3217// -Xnoagent3218} else if (match_option(option, "-Xnoagent", &tail)) {3219// For compatibility with classic. HotSpot refuses to load the old style agent.dll.3220} else if (match_option(option, "-Xboundthreads", &tail)) {3221// Bind user level threads to kernel threads (Solaris only)3222FLAG_SET_CMDLINE(bool, UseBoundThreads, true);3223} else if (match_option(option, "-Xloggc:", &tail)) {3224// Redirect GC output to the file. -Xloggc:<filename>3225// ostream_init_log(), when called will use this filename3226// to initialize a fileStream.3227_gc_log_filename = strdup(tail);3228if (!is_filename_valid(_gc_log_filename)) {3229jio_fprintf(defaultStream::output_stream(),3230"Invalid file name for use with -Xloggc: Filename can only contain the "3231"characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"3232"Note %%p or %%t can only be used once\n", _gc_log_filename);3233return JNI_EINVAL;3234}3235FLAG_SET_CMDLINE(bool, PrintGC, true);3236FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true);32373238// JNI hooks3239} else if (match_option(option, "-Xcheck", &tail)) {3240if (!strcmp(tail, ":jni")) {3241#if !INCLUDE_JNI_CHECK3242warning("JNI CHECKING is not supported in this VM");3243#else3244CheckJNICalls = true;3245#endif // INCLUDE_JNI_CHECK3246} else if (is_bad_option(option, args->ignoreUnrecognized,3247"check")) {3248return JNI_EINVAL;3249}3250} else if (match_option(option, "vfprintf", &tail)) {3251_vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);3252} else if (match_option(option, "exit", &tail)) {3253_exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);3254} else if (match_option(option, "abort", &tail)) {3255_abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);3256} else if (match_option(option, "-XX:+NeverTenure", &tail)) {3257// The last option must always win.3258FLAG_SET_CMDLINE(bool, AlwaysTenure, false);3259FLAG_SET_CMDLINE(bool, NeverTenure, true);3260} else if (match_option(option, "-XX:+AlwaysTenure", &tail)) {3261// The last option must always win.3262FLAG_SET_CMDLINE(bool, NeverTenure, false);3263FLAG_SET_CMDLINE(bool, AlwaysTenure, true);3264} else if (match_option(option, "-XX:+CMSPermGenSweepingEnabled", &tail) ||3265match_option(option, "-XX:-CMSPermGenSweepingEnabled", &tail)) {3266jio_fprintf(defaultStream::error_stream(),3267"Please use CMSClassUnloadingEnabled in place of "3268"CMSPermGenSweepingEnabled in the future\n");3269} else if (match_option(option, "-XX:+UseGCTimeLimit", &tail)) {3270FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, true);3271jio_fprintf(defaultStream::error_stream(),3272"Please use -XX:+UseGCOverheadLimit in place of "3273"-XX:+UseGCTimeLimit in the future\n");3274} else if (match_option(option, "-XX:-UseGCTimeLimit", &tail)) {3275FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, false);3276jio_fprintf(defaultStream::error_stream(),3277"Please use -XX:-UseGCOverheadLimit in place of "3278"-XX:-UseGCTimeLimit in the future\n");3279// The TLE options are for compatibility with 1.3 and will be3280// removed without notice in a future release. These options3281// are not to be documented.3282} else if (match_option(option, "-XX:MaxTLERatio=", &tail)) {3283// No longer used.3284} else if (match_option(option, "-XX:+ResizeTLE", &tail)) {3285FLAG_SET_CMDLINE(bool, ResizeTLAB, true);3286} else if (match_option(option, "-XX:-ResizeTLE", &tail)) {3287FLAG_SET_CMDLINE(bool, ResizeTLAB, false);3288} else if (match_option(option, "-XX:+PrintTLE", &tail)) {3289FLAG_SET_CMDLINE(bool, PrintTLAB, true);3290} else if (match_option(option, "-XX:-PrintTLE", &tail)) {3291FLAG_SET_CMDLINE(bool, PrintTLAB, false);3292} else if (match_option(option, "-XX:TLEFragmentationRatio=", &tail)) {3293// No longer used.3294} else if (match_option(option, "-XX:TLESize=", &tail)) {3295julong long_tlab_size = 0;3296ArgsRange errcode = parse_memory_size(tail, &long_tlab_size, 1);3297if (errcode != arg_in_range) {3298jio_fprintf(defaultStream::error_stream(),3299"Invalid TLAB size: %s\n", option->optionString);3300describe_range_error(errcode);3301return JNI_EINVAL;3302}3303FLAG_SET_CMDLINE(uintx, TLABSize, long_tlab_size);3304} else if (match_option(option, "-XX:TLEThreadRatio=", &tail)) {3305// No longer used.3306} else if (match_option(option, "-XX:+UseTLE", &tail)) {3307FLAG_SET_CMDLINE(bool, UseTLAB, true);3308} else if (match_option(option, "-XX:-UseTLE", &tail)) {3309FLAG_SET_CMDLINE(bool, UseTLAB, false);3310} else if (match_option(option, "-XX:+DisplayVMOutputToStderr", &tail)) {3311FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false);3312FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true);3313} else if (match_option(option, "-XX:+DisplayVMOutputToStdout", &tail)) {3314FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false);3315FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true);3316} else if (match_option(option, "-XX:+ExtendedDTraceProbes", &tail)) {3317#if defined(DTRACE_ENABLED)3318FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true);3319FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true);3320FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true);3321FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true);3322#else // defined(DTRACE_ENABLED)3323jio_fprintf(defaultStream::error_stream(),3324"ExtendedDTraceProbes flag is not applicable for this configuration\n");3325return JNI_EINVAL;3326#endif // defined(DTRACE_ENABLED)3327#ifdef ASSERT3328} else if (match_option(option, "-XX:+FullGCALot", &tail)) {3329FLAG_SET_CMDLINE(bool, FullGCALot, true);3330// disable scavenge before parallel mark-compact3331FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);3332#endif3333} else if (match_option(option, "-XX:CMSParPromoteBlocksToClaim=", &tail)) {3334julong cms_blocks_to_claim = (julong)atol(tail);3335FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);3336jio_fprintf(defaultStream::error_stream(),3337"Please use -XX:OldPLABSize in place of "3338"-XX:CMSParPromoteBlocksToClaim in the future\n");3339} else if (match_option(option, "-XX:ParCMSPromoteBlocksToClaim=", &tail)) {3340julong cms_blocks_to_claim = (julong)atol(tail);3341FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);3342jio_fprintf(defaultStream::error_stream(),3343"Please use -XX:OldPLABSize in place of "3344"-XX:ParCMSPromoteBlocksToClaim in the future\n");3345} else if (match_option(option, "-XX:ParallelGCOldGenAllocBufferSize=", &tail)) {3346julong old_plab_size = 0;3347ArgsRange errcode = parse_memory_size(tail, &old_plab_size, 1);3348if (errcode != arg_in_range) {3349jio_fprintf(defaultStream::error_stream(),3350"Invalid old PLAB size: %s\n", option->optionString);3351describe_range_error(errcode);3352return JNI_EINVAL;3353}3354FLAG_SET_CMDLINE(uintx, OldPLABSize, old_plab_size);3355jio_fprintf(defaultStream::error_stream(),3356"Please use -XX:OldPLABSize in place of "3357"-XX:ParallelGCOldGenAllocBufferSize in the future\n");3358} else if (match_option(option, "-XX:ParallelGCToSpaceAllocBufferSize=", &tail)) {3359julong young_plab_size = 0;3360ArgsRange errcode = parse_memory_size(tail, &young_plab_size, 1);3361if (errcode != arg_in_range) {3362jio_fprintf(defaultStream::error_stream(),3363"Invalid young PLAB size: %s\n", option->optionString);3364describe_range_error(errcode);3365return JNI_EINVAL;3366}3367FLAG_SET_CMDLINE(uintx, YoungPLABSize, young_plab_size);3368jio_fprintf(defaultStream::error_stream(),3369"Please use -XX:YoungPLABSize in place of "3370"-XX:ParallelGCToSpaceAllocBufferSize in the future\n");3371} else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||3372match_option(option, "-XX:G1MarkStackSize=", &tail)) {3373julong stack_size = 0;3374ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);3375if (errcode != arg_in_range) {3376jio_fprintf(defaultStream::error_stream(),3377"Invalid mark stack size: %s\n", option->optionString);3378describe_range_error(errcode);3379return JNI_EINVAL;3380}3381FLAG_SET_CMDLINE(uintx, MarkStackSize, stack_size);3382} else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {3383julong max_stack_size = 0;3384ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);3385if (errcode != arg_in_range) {3386jio_fprintf(defaultStream::error_stream(),3387"Invalid maximum mark stack size: %s\n",3388option->optionString);3389describe_range_error(errcode);3390return JNI_EINVAL;3391}3392FLAG_SET_CMDLINE(uintx, MarkStackSizeMax, max_stack_size);3393} else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||3394match_option(option, "-XX:ParallelCMSThreads=", &tail)) {3395uintx conc_threads = 0;3396if (!parse_uintx(tail, &conc_threads, 1)) {3397jio_fprintf(defaultStream::error_stream(),3398"Invalid concurrent threads: %s\n", option->optionString);3399return JNI_EINVAL;3400}3401FLAG_SET_CMDLINE(uintx, ConcGCThreads, conc_threads);3402} else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {3403julong max_direct_memory_size = 0;3404ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);3405if (errcode != arg_in_range) {3406jio_fprintf(defaultStream::error_stream(),3407"Invalid maximum direct memory size: %s\n",3408option->optionString);3409describe_range_error(errcode);3410return JNI_EINVAL;3411}3412FLAG_SET_CMDLINE(uintx, MaxDirectMemorySize, max_direct_memory_size);3413} else if (match_option(option, "-XX:+UseVMInterruptibleIO", &tail)) {3414// NOTE! In JDK 9, the UseVMInterruptibleIO flag will completely go3415// away and will cause VM initialization failures!3416warning("-XX:+UseVMInterruptibleIO is obsolete and will be removed in a future release.");3417FLAG_SET_CMDLINE(bool, UseVMInterruptibleIO, true);3418#if !INCLUDE_MANAGEMENT3419} else if (match_option(option, "-XX:+ManagementServer", &tail)) {3420jio_fprintf(defaultStream::error_stream(),3421"ManagementServer is not supported in this VM.\n");3422return JNI_ERR;3423#endif // INCLUDE_MANAGEMENT3424#if INCLUDE_JFR3425} else if (match_jfr_option(&option)) {3426return JNI_EINVAL;3427#endif3428} else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx3429// Skip -XX:Flags= since that case has already been handled3430if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {3431if (!process_argument(tail, args->ignoreUnrecognized, origin)) {3432return JNI_EINVAL;3433}3434}3435// Unknown option3436} else if (is_bad_option(option, args->ignoreUnrecognized)) {3437return JNI_ERR;3438}3439}34403441// PrintSharedArchiveAndExit will turn on3442// -Xshare:on3443// -XX:+TraceClassPaths3444if (PrintSharedArchiveAndExit) {3445FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);3446FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);3447FLAG_SET_CMDLINE(bool, TraceClassPaths, true);3448}34493450// Change the default value for flags which have different default values3451// when working with older JDKs.3452#ifdef LINUX3453if (JDK_Version::current().compare_major(6) <= 0 &&3454FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {3455FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);3456}3457#endif // LINUX3458fix_appclasspath();3459return JNI_OK;3460}34613462// Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)3463//3464// This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar3465// in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".3466// Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty3467// path is treated as the current directory.3468//3469// This causes problems with CDS, which requires that all directories specified in the classpath3470// must be empty. In most cases, applications do NOT want to load classes from the current3471// directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up3472// scripts compatible with CDS.3473void Arguments::fix_appclasspath() {3474if (IgnoreEmptyClassPaths) {3475const char separator = *os::path_separator();3476const char* src = _java_class_path->value();34773478// skip over all the leading empty paths3479while (*src == separator) {3480src ++;3481}34823483char* copy = os::strdup(src, mtInternal);34843485// trim all trailing empty paths3486for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {3487*tail = '\0';3488}34893490char from[3] = {separator, separator, '\0'};3491char to [2] = {separator, '\0'};3492while (StringUtils::replace_no_expand(copy, from, to) > 0) {3493// Keep replacing "::" -> ":" until we have no more "::" (non-windows)3494// Keep replacing ";;" -> ";" until we have no more ";;" (windows)3495}34963497_java_class_path->set_value(copy);3498FreeHeap(copy); // a copy was made by set_value, so don't need this anymore3499}35003501if (!PrintSharedArchiveAndExit) {3502ClassLoader::trace_class_path(tty, "[classpath: ", _java_class_path->value());3503}3504}35053506static bool has_jar_files(const char* directory) {3507DIR* dir = os::opendir(directory);3508if (dir == NULL) return false;35093510struct dirent *entry;3511bool hasJarFile = false;3512while (!hasJarFile && (entry = os::readdir(dir)) != NULL) {3513const char* name = entry->d_name;3514const char* ext = name + strlen(name) - 4;3515hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);3516}3517os::closedir(dir);3518return hasJarFile ;3519}35203521// returns the number of directories in the given path containing JAR files3522// If the skip argument is not NULL, it will skip that directory3523static int check_non_empty_dirs(const char* path, const char* type, const char* skip) {3524const char separator = *os::path_separator();3525const char* const end = path + strlen(path);3526int nonEmptyDirs = 0;3527while (path < end) {3528const char* tmp_end = strchr(path, separator);3529if (tmp_end == NULL) {3530if ((skip == NULL || strcmp(path, skip) != 0) && has_jar_files(path)) {3531nonEmptyDirs++;3532jio_fprintf(defaultStream::output_stream(),3533"Non-empty %s directory: %s\n", type, path);3534}3535path = end;3536} else {3537char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);3538memcpy(dirpath, path, tmp_end - path);3539dirpath[tmp_end - path] = '\0';3540if ((skip == NULL || strcmp(dirpath, skip) != 0) && has_jar_files(dirpath)) {3541nonEmptyDirs++;3542jio_fprintf(defaultStream::output_stream(),3543"Non-empty %s directory: %s\n", type, dirpath);3544}3545FREE_C_HEAP_ARRAY(char, dirpath, mtInternal);3546path = tmp_end + 1;3547}3548}3549return nonEmptyDirs;3550}35513552// Returns true if endorsed standards override mechanism and extension mechanism3553// are not used.3554static bool check_endorsed_and_ext_dirs() {3555if (!CheckEndorsedAndExtDirs)3556return true;35573558char endorsedDir[JVM_MAXPATHLEN];3559char extDir[JVM_MAXPATHLEN];3560const char* fileSep = os::file_separator();3561jio_snprintf(endorsedDir, sizeof(endorsedDir), "%s%slib%sendorsed",3562Arguments::get_java_home(), fileSep, fileSep);3563jio_snprintf(extDir, sizeof(extDir), "%s%slib%sext",3564Arguments::get_java_home(), fileSep, fileSep);35653566// check endorsed directory3567int nonEmptyDirs = check_non_empty_dirs(Arguments::get_endorsed_dir(), "endorsed", NULL);35683569// check the extension directories but skip the default lib/ext directory3570nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs(), "extension", extDir);35713572// List of JAR files installed in the default lib/ext directory.3573// -XX:+CheckEndorsedAndExtDirs checks if any non-JDK file installed3574static const char* jdk_ext_jars[] = {3575"access-bridge-32.jar",3576"access-bridge-64.jar",3577"access-bridge.jar",3578"cldrdata.jar",3579"dnsns.jar",3580"jaccess.jar",3581"jfxrt.jar",3582"localedata.jar",3583"nashorn.jar",3584"sunec.jar",3585"sunjce_provider.jar",3586"sunmscapi.jar",3587"sunpkcs11.jar",3588"ucrypto.jar",3589"zipfs.jar",3590NULL3591};35923593// check if the default lib/ext directory has any non-JDK jar files; if so, error3594DIR* dir = os::opendir(extDir);3595if (dir != NULL) {3596int num_ext_jars = 0;3597struct dirent *entry;3598while ((entry = os::readdir(dir)) != NULL) {3599const char* name = entry->d_name;3600const char* ext = name + strlen(name) - 4;3601if (ext > name && (os::file_name_strcmp(ext, ".jar") == 0)) {3602bool is_jdk_jar = false;3603const char* jarfile = NULL;3604for (int i=0; (jarfile = jdk_ext_jars[i]) != NULL; i++) {3605if (os::file_name_strcmp(name, jarfile) == 0) {3606is_jdk_jar = true;3607break;3608}3609}3610if (!is_jdk_jar) {3611jio_fprintf(defaultStream::output_stream(),3612"%s installed in <JAVA_HOME>/lib/ext\n", name);3613num_ext_jars++;3614}3615}3616}3617os::closedir(dir);3618if (num_ext_jars > 0) {3619nonEmptyDirs += 1;3620}3621}36223623// check if the default lib/endorsed directory exists; if so, error3624dir = os::opendir(endorsedDir);3625if (dir != NULL) {3626jio_fprintf(defaultStream::output_stream(), "<JAVA_HOME>/lib/endorsed exists\n");3627os::closedir(dir);3628nonEmptyDirs += 1;3629}36303631if (nonEmptyDirs > 0) {3632jio_fprintf(defaultStream::output_stream(),3633"Endorsed standards override mechanism and extension mechanism "3634"will not be supported in a future release.\n"3635"Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");3636return false;3637}36383639return true;3640}36413642jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {3643// This must be done after all -D arguments have been processed.3644scp_p->expand_endorsed();36453646if (scp_assembly_required || scp_p->get_endorsed() != NULL) {3647// Assemble the bootclasspath elements into the final path.3648Arguments::set_sysclasspath(scp_p->combined_path());3649}36503651if (!check_endorsed_and_ext_dirs()) {3652return JNI_ERR;3653}36543655// This must be done after all arguments have been processed3656// and the container support has been initialized since AggressiveHeap3657// relies on the amount of total memory available.3658if (AggressiveHeap) {3659jint result = set_aggressive_heap_flags();3660if (result != JNI_OK) {3661return result;3662}3663}3664// This must be done after all arguments have been processed.3665// java_compiler() true means set to "NONE" or empty.3666if (java_compiler() && !xdebug_mode()) {3667// For backwards compatibility, we switch to interpreted mode if3668// -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was3669// not specified.3670set_mode_flags(_int);3671}3672if (CompileThreshold == 0) {3673set_mode_flags(_int);3674}36753676// eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set3677if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {3678FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);3679}36803681#ifndef COMPILER23682// Don't degrade server performance for footprint3683if (FLAG_IS_DEFAULT(UseLargePages) &&3684MaxHeapSize < LargePageHeapSizeThreshold) {3685// No need for large granularity pages w/small heaps.3686// Note that large pages are enabled/disabled for both the3687// Java heap and the code cache.3688FLAG_SET_DEFAULT(UseLargePages, false);3689}36903691#else3692if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {3693FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);3694}3695#endif36963697#ifndef TIERED3698// Tiered compilation is undefined.3699UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");3700#endif37013702// If we are running in a headless jre, force java.awt.headless property3703// to be true unless the property has already been set.3704// Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.3705if (os::is_headless_jre()) {3706const char* headless = Arguments::get_property("java.awt.headless");3707if (headless == NULL) {3708char envbuffer[128];3709if (!os::getenv("JAVA_AWT_HEADLESS", envbuffer, sizeof(envbuffer))) {3710if (!add_property("java.awt.headless=true")) {3711return JNI_ENOMEM;3712}3713} else {3714char buffer[256];3715jio_snprintf(buffer, 256, "java.awt.headless=%s", envbuffer);3716if (!add_property(buffer)) {3717return JNI_ENOMEM;3718}3719}3720}3721}37223723if (!check_vm_args_consistency()) {3724return JNI_ERR;3725}37263727return JNI_OK;3728}37293730jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {3731return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,3732scp_assembly_required_p);3733}37343735jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {3736return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,3737scp_assembly_required_p);3738}37393740jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {3741const int N_MAX_OPTIONS = 64;3742const int OPTION_BUFFER_SIZE = 1024;3743char buffer[OPTION_BUFFER_SIZE];37443745// The variable will be ignored if it exceeds the length of the buffer.3746// Don't check this variable if user has special privileges3747// (e.g. unix su command).3748if (os::getenv(name, buffer, sizeof(buffer)) &&3749!os::have_special_privileges()) {3750JavaVMOption options[N_MAX_OPTIONS]; // Construct option array3751jio_fprintf(defaultStream::error_stream(),3752"Picked up %s: %s\n", name, buffer);3753char* rd = buffer; // pointer to the input string (rd)3754int i;3755for (i = 0; i < N_MAX_OPTIONS;) { // repeat for all options in the input string3756while (isspace(*rd)) rd++; // skip whitespace3757if (*rd == 0) break; // we re done when the input string is read completely37583759// The output, option string, overwrites the input string.3760// Because of quoting, the pointer to the option string (wrt) may lag the pointer to3761// input string (rd).3762char* wrt = rd;37633764options[i++].optionString = wrt; // Fill in option3765while (*rd != 0 && !isspace(*rd)) { // unquoted strings terminate with a space or NULL3766if (*rd == '\'' || *rd == '"') { // handle a quoted string3767int quote = *rd; // matching quote to look for3768rd++; // don't copy open quote3769while (*rd != quote) { // include everything (even spaces) up until quote3770if (*rd == 0) { // string termination means unmatched string3771jio_fprintf(defaultStream::error_stream(),3772"Unmatched quote in %s\n", name);3773return JNI_ERR;3774}3775*wrt++ = *rd++; // copy to option string3776}3777rd++; // don't copy close quote3778} else {3779*wrt++ = *rd++; // copy to option string3780}3781}3782// Need to check if we're done before writing a NULL,3783// because the write could be to the byte that rd is pointing to.3784if (*rd++ == 0) {3785*wrt = 0;3786break;3787}3788*wrt = 0; // Zero terminate option3789}3790// Construct JavaVMInitArgs structure and parse as if it was part of the command line3791JavaVMInitArgs vm_args;3792vm_args.version = JNI_VERSION_1_2;3793vm_args.options = options;3794vm_args.nOptions = i;3795vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;37963797if (PrintVMOptions) {3798const char* tail;3799for (int i = 0; i < vm_args.nOptions; i++) {3800const JavaVMOption *option = vm_args.options + i;3801if (match_option(option, "-XX:", &tail)) {3802logOption(tail);3803}3804}3805}38063807return(parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p, Flag::ENVIRON_VAR));3808}3809return JNI_OK;3810}38113812void Arguments::set_shared_spaces_flags() {3813if (DumpSharedSpaces) {3814if (FailOverToOldVerifier) {3815// Don't fall back to the old verifier on verification failure. If a3816// class fails verification with the split verifier, it might fail the3817// CDS runtime verifier constraint check. In that case, we don't want3818// to share the class. We only archive classes that pass the split verifier.3819FLAG_SET_DEFAULT(FailOverToOldVerifier, false);3820}38213822if (RequireSharedSpaces) {3823warning("cannot dump shared archive while using shared archive");3824}3825UseSharedSpaces = false;3826#ifdef _LP643827if (!UseCompressedOops || !UseCompressedClassPointers) {3828vm_exit_during_initialization(3829"Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);3830}3831} else {3832if (!UseCompressedOops || !UseCompressedClassPointers) {3833no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");3834}3835#endif3836}3837}38383839#if !INCLUDE_ALL_GCS3840static void force_serial_gc() {3841FLAG_SET_DEFAULT(UseSerialGC, true);3842FLAG_SET_DEFAULT(CMSIncrementalMode, false); // special CMS suboption3843UNSUPPORTED_GC_OPTION(UseG1GC);3844UNSUPPORTED_GC_OPTION(UseParallelGC);3845UNSUPPORTED_GC_OPTION(UseParallelOldGC);3846UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);3847UNSUPPORTED_GC_OPTION(UseParNewGC);3848}3849#endif // INCLUDE_ALL_GCS38503851// Sharing support3852// Construct the path to the archive3853static char* get_shared_archive_path() {3854char *shared_archive_path;3855if (SharedArchiveFile == NULL) {3856char jvm_path[JVM_MAXPATHLEN];3857os::jvm_path(jvm_path, sizeof(jvm_path));3858char *end = strrchr(jvm_path, *os::file_separator());3859if (end != NULL) *end = '\0';3860size_t jvm_path_len = strlen(jvm_path);3861size_t file_sep_len = strlen(os::file_separator());3862const size_t len = jvm_path_len + file_sep_len + 20;3863shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtInternal);3864if (shared_archive_path != NULL) {3865jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",3866jvm_path, os::file_separator());3867}3868} else {3869shared_archive_path = os::strdup(SharedArchiveFile, mtInternal);3870}3871return shared_archive_path;3872}38733874#ifndef PRODUCT3875// Determine whether LogVMOutput should be implicitly turned on.3876static bool use_vm_log() {3877if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||3878PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||3879PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||3880PrintAssembly || TraceDeoptimization || TraceDependencies ||3881(VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {3882return true;3883}38843885#ifdef COMPILER13886if (PrintC1Statistics) {3887return true;3888}3889#endif // COMPILER138903891#ifdef COMPILER23892if (PrintOptoAssembly || PrintOptoStatistics) {3893return true;3894}3895#endif // COMPILER238963897return false;3898}3899#endif // PRODUCT39003901// Parse entry point called from JNI_CreateJavaVM39023903jint Arguments::parse(const JavaVMInitArgs* args) {39043905// Remaining part of option string3906const char* tail;39073908// If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.3909const char* hotspotrc = ".hotspotrc";3910bool settings_file_specified = false;3911bool needs_hotspotrc_warning = false;39123913ArgumentsExt::process_options(args);39143915const char* flags_file;3916int index;3917for (index = 0; index < args->nOptions; index++) {3918const JavaVMOption *option = args->options + index;3919if (match_option(option, "-XX:Flags=", &tail)) {3920flags_file = tail;3921settings_file_specified = true;3922}3923if (match_option(option, "-XX:+PrintVMOptions", &tail)) {3924PrintVMOptions = true;3925}3926if (match_option(option, "-XX:-PrintVMOptions", &tail)) {3927PrintVMOptions = false;3928}3929if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions", &tail)) {3930IgnoreUnrecognizedVMOptions = true;3931}3932if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions", &tail)) {3933IgnoreUnrecognizedVMOptions = false;3934}3935if (match_option(option, "-XX:+PrintFlagsInitial", &tail)) {3936CommandLineFlags::printFlags(tty, false);3937vm_exit(0);3938}3939if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {3940#if INCLUDE_NMT3941// The launcher did not setup nmt environment variable properly.3942if (!MemTracker::check_launcher_nmt_support(tail)) {3943warning("Native Memory Tracking did not setup properly, using wrong launcher?");3944}39453946// Verify if nmt option is valid.3947if (MemTracker::verify_nmt_option()) {3948// Late initialization, still in single-threaded mode.3949if (MemTracker::tracking_level() >= NMT_summary) {3950MemTracker::init();3951}3952} else {3953vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);3954}3955#else3956jio_fprintf(defaultStream::error_stream(),3957"Native Memory Tracking is not supported in this VM\n");3958return JNI_ERR;3959#endif3960}396139623963#ifndef PRODUCT3964if (match_option(option, "-XX:+PrintFlagsWithComments", &tail)) {3965CommandLineFlags::printFlags(tty, true);3966vm_exit(0);3967}3968#endif3969}39703971if (IgnoreUnrecognizedVMOptions) {3972// uncast const to modify the flag args->ignoreUnrecognized3973*(jboolean*)(&args->ignoreUnrecognized) = true;3974}39753976// Parse specified settings file3977if (settings_file_specified) {3978if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {3979return JNI_EINVAL;3980}3981} else {3982#ifdef ASSERT3983// Parse default .hotspotrc settings file3984if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {3985return JNI_EINVAL;3986}3987#else3988struct stat buf;3989if (os::stat(hotspotrc, &buf) == 0) {3990needs_hotspotrc_warning = true;3991}3992#endif3993}39943995if (PrintVMOptions) {3996for (index = 0; index < args->nOptions; index++) {3997const JavaVMOption *option = args->options + index;3998if (match_option(option, "-XX:", &tail)) {3999logOption(tail);4000}4001}4002}40034004// Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS4005jint result = parse_vm_init_args(args);4006if (result != JNI_OK) {4007return result;4008}40094010// Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.4011SharedArchivePath = get_shared_archive_path();4012if (SharedArchivePath == NULL) {4013return JNI_ENOMEM;4014}40154016// Set up VerifySharedSpaces4017if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {4018VerifySharedSpaces = true;4019}40204021// Delay warning until here so that we've had a chance to process4022// the -XX:-PrintWarnings flag4023if (needs_hotspotrc_warning) {4024warning("%s file is present but has been ignored. "4025"Run with -XX:Flags=%s to load the file.",4026hotspotrc, hotspotrc);4027}40284029#ifdef _ALLBSD_SOURCE // UseLargePages is not yet supported on BSD.4030UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");4031#endif40324033#if INCLUDE_ALL_GCS4034#if (defined JAVASE_EMBEDDED || defined ARM)4035UNSUPPORTED_OPTION(UseG1GC, "G1 GC");4036#endif4037#endif40384039#ifndef PRODUCT4040if (TraceBytecodesAt != 0) {4041TraceBytecodes = true;4042}4043if (CountCompiledCalls) {4044if (UseCounterDecay) {4045warning("UseCounterDecay disabled because CountCalls is set");4046UseCounterDecay = false;4047}4048}4049#endif // PRODUCT40504051// JSR 292 is not supported before 1.74052if (!JDK_Version::is_gte_jdk17x_version()) {4053if (EnableInvokeDynamic) {4054if (!FLAG_IS_DEFAULT(EnableInvokeDynamic)) {4055warning("JSR 292 is not supported before 1.7. Disabling support.");4056}4057EnableInvokeDynamic = false;4058}4059}40604061if (EnableInvokeDynamic && ScavengeRootsInCode == 0) {4062if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {4063warning("forcing ScavengeRootsInCode non-zero because EnableInvokeDynamic is true");4064}4065ScavengeRootsInCode = 1;4066}40674068if (PrintGCDetails) {4069// Turn on -verbose:gc options as well4070PrintGC = true;4071}40724073if (!JDK_Version::is_gte_jdk18x_version()) {4074// To avoid changing the log format for 7 updates this flag is only4075// true by default in JDK8 and above.4076if (FLAG_IS_DEFAULT(PrintGCCause)) {4077FLAG_SET_DEFAULT(PrintGCCause, false);4078}4079}40804081// Set object alignment values.4082set_object_alignment();40834084#if !INCLUDE_ALL_GCS4085force_serial_gc();4086#endif // INCLUDE_ALL_GCS4087#if !INCLUDE_CDS4088if (DumpSharedSpaces || RequireSharedSpaces) {4089jio_fprintf(defaultStream::error_stream(),4090"Shared spaces are not supported in this VM\n");4091return JNI_ERR;4092}4093if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {4094warning("Shared spaces are not supported in this VM");4095FLAG_SET_DEFAULT(UseSharedSpaces, false);4096FLAG_SET_DEFAULT(PrintSharedSpaces, false);4097}4098no_shared_spaces("CDS Disabled");4099#endif // INCLUDE_CDS41004101return JNI_OK;4102}41034104jint Arguments::apply_ergo() {41054106// Set flags based on ergonomics.4107set_ergonomics_flags();41084109set_shared_spaces_flags();41104111#if defined(SPARC)4112// BIS instructions require 'membar' instruction regardless of the number4113// of CPUs because in virtualized/container environments which might use only 14114// CPU, BIS instructions may produce incorrect results.41154116if (FLAG_IS_DEFAULT(AssumeMP)) {4117FLAG_SET_DEFAULT(AssumeMP, true);4118}4119#endif41204121// Check the GC selections again.4122if (!check_gc_consistency()) {4123return JNI_EINVAL;4124}41254126if (TieredCompilation) {4127set_tiered_flags();4128} else {4129// Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup.4130if (CompilationPolicyChoice >= 2) {4131vm_exit_during_initialization(4132"Incompatible compilation policy selected", NULL);4133}4134}4135// Set NmethodSweepFraction after the size of the code cache is adapted (in case of tiered)4136if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {4137FLAG_SET_DEFAULT(NmethodSweepFraction, 1 + ReservedCodeCacheSize / (16 * M));4138}413941404141// Set heap size based on available physical memory4142set_heap_size();41434144ArgumentsExt::set_gc_specific_flags();41454146// Initialize Metaspace flags and alignments.4147Metaspace::ergo_initialize();41484149// Set bytecode rewriting flags4150set_bytecode_flags();41514152// Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled.4153set_aggressive_opts_flags();41544155// Turn off biased locking for locking debug mode flags,4156// which are subtlely different from each other but neither works with4157// biased locking.4158if (UseHeavyMonitors4159#ifdef COMPILER14160|| !UseFastLocking4161#endif // COMPILER14162) {4163if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {4164// flag set to true on command line; warn the user that they4165// can't enable biased locking here4166warning("Biased Locking is not supported with locking debug flags"4167"; ignoring UseBiasedLocking flag." );4168}4169UseBiasedLocking = false;4170}41714172#ifdef ZERO4173// Clear flags not supported on zero.4174FLAG_SET_DEFAULT(ProfileInterpreter, false);4175FLAG_SET_DEFAULT(UseBiasedLocking, false);4176LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));4177LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));4178#endif // CC_INTERP41794180#ifdef COMPILER24181if (!EliminateLocks) {4182EliminateNestedLocks = false;4183}4184if (!Inline) {4185IncrementalInline = false;4186}4187#ifndef PRODUCT4188if (!IncrementalInline) {4189AlwaysIncrementalInline = false;4190}4191#endif4192if (IncrementalInline && FLAG_IS_DEFAULT(MaxNodeLimit)) {4193// incremental inlining: bump MaxNodeLimit4194FLAG_SET_DEFAULT(MaxNodeLimit, (intx)75000);4195}4196if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {4197// nothing to use the profiling, turn if off4198FLAG_SET_DEFAULT(TypeProfileLevel, 0);4199}4200#endif42014202if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {4203warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");4204DebugNonSafepoints = true;4205}42064207if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {4208warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");4209}42104211if (UseOnStackReplacement && !UseLoopCounter) {4212warning("On-stack-replacement requires loop counters; enabling loop counters");4213FLAG_SET_DEFAULT(UseLoopCounter, true);4214}42154216#ifndef PRODUCT4217if (CompileTheWorld) {4218// Force NmethodSweeper to sweep whole CodeCache each time.4219if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {4220NmethodSweepFraction = 1;4221}4222}42234224if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {4225if (use_vm_log()) {4226LogVMOutput = true;4227}4228}4229#endif // PRODUCT42304231if (PrintCommandLineFlags) {4232CommandLineFlags::printSetFlags(tty);4233}42344235// Apply CPU specific policy for the BiasedLocking4236if (UseBiasedLocking) {4237if (!VM_Version::use_biased_locking() &&4238!(FLAG_IS_CMDLINE(UseBiasedLocking))) {4239UseBiasedLocking = false;4240}4241}4242#ifdef COMPILER24243if (!UseBiasedLocking || EmitSync != 0) {4244UseOptoBiasInlining = false;4245}4246#endif42474248// set PauseAtExit if the gamma launcher was used and a debugger is attached4249// but only if not already set on the commandline4250if (Arguments::created_by_gamma_launcher() && os::is_debugger_attached()) {4251bool set = false;4252CommandLineFlags::wasSetOnCmdline("PauseAtExit", &set);4253if (!set) {4254FLAG_SET_DEFAULT(PauseAtExit, true);4255}4256}42574258return JNI_OK;4259}42604261jint Arguments::adjust_after_os() {4262if (UseNUMA) {4263if (UseParallelGC || UseParallelOldGC) {4264if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {4265FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);4266}4267}4268// UseNUMAInterleaving is set to ON for all collectors and4269// platforms when UseNUMA is set to ON. NUMA-aware collectors4270// such as the parallel collector for Linux and Solaris will4271// interleave old gen and survivor spaces on top of NUMA4272// allocation policy for the eden space.4273// Non NUMA-aware collectors such as CMS, G1 and Serial-GC on4274// all platforms and ParallelGC on Windows will interleave all4275// of the heap spaces across NUMA nodes.4276if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {4277FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);4278}4279}4280return JNI_OK;4281}42824283int Arguments::PropertyList_count(SystemProperty* pl) {4284int count = 0;4285while(pl != NULL) {4286count++;4287pl = pl->next();4288}4289return count;4290}42914292const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {4293assert(key != NULL, "just checking");4294SystemProperty* prop;4295for (prop = pl; prop != NULL; prop = prop->next()) {4296if (strcmp(key, prop->key()) == 0) return prop->value();4297}4298return NULL;4299}43004301const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {4302int count = 0;4303const char* ret_val = NULL;43044305while(pl != NULL) {4306if(count >= index) {4307ret_val = pl->key();4308break;4309}4310count++;4311pl = pl->next();4312}43134314return ret_val;4315}43164317char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {4318int count = 0;4319char* ret_val = NULL;43204321while(pl != NULL) {4322if(count >= index) {4323ret_val = pl->value();4324break;4325}4326count++;4327pl = pl->next();4328}43294330return ret_val;4331}43324333void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {4334SystemProperty* p = *plist;4335if (p == NULL) {4336*plist = new_p;4337} else {4338while (p->next() != NULL) {4339p = p->next();4340}4341p->set_next(new_p);4342}4343}43444345void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {4346if (plist == NULL)4347return;43484349SystemProperty* new_p = new SystemProperty(k, v, true);4350PropertyList_add(plist, new_p);4351}43524353// This add maintains unique property key in the list.4354void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {4355if (plist == NULL)4356return;43574358// If property key exist then update with new value.4359SystemProperty* prop;4360for (prop = *plist; prop != NULL; prop = prop->next()) {4361if (strcmp(k, prop->key()) == 0) {4362if (append) {4363prop->append_value(v);4364} else {4365prop->set_value(v);4366}4367return;4368}4369}43704371PropertyList_add(plist, k, v);4372}43734374// Copies src into buf, replacing "%%" with "%" and "%p" with pid4375// Returns true if all of the source pointed by src has been copied over to4376// the destination buffer pointed by buf. Otherwise, returns false.4377// Notes:4378// 1. If the length (buflen) of the destination buffer excluding the4379// NULL terminator character is not long enough for holding the expanded4380// pid characters, it also returns false instead of returning the partially4381// expanded one.4382// 2. The passed in "buflen" should be large enough to hold the null terminator.4383bool Arguments::copy_expand_pid(const char* src, size_t srclen,4384char* buf, size_t buflen) {4385const char* p = src;4386char* b = buf;4387const char* src_end = &src[srclen];4388char* buf_end = &buf[buflen - 1];43894390while (p < src_end && b < buf_end) {4391if (*p == '%') {4392switch (*(++p)) {4393case '%': // "%%" ==> "%"4394*b++ = *p++;4395break;4396case 'p': { // "%p" ==> current process id4397// buf_end points to the character before the last character so4398// that we could write '\0' to the end of the buffer.4399size_t buf_sz = buf_end - b + 1;4400int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());44014402// if jio_snprintf fails or the buffer is not long enough to hold4403// the expanded pid, returns false.4404if (ret < 0 || ret >= (int)buf_sz) {4405return false;4406} else {4407b += ret;4408assert(*b == '\0', "fail in copy_expand_pid");4409if (p == src_end && b == buf_end + 1) {4410// reach the end of the buffer.4411return true;4412}4413}4414p++;4415break;4416}4417default :4418*b++ = '%';4419}4420} else {4421*b++ = *p++;4422}4423}4424*b = '\0';4425return (p == src_end); // return false if not all of the source was copied4426}442744284429