Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/runtime/arguments.cpp
32285 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#include "gc_implementation/shenandoah/shenandoahHeap.hpp"69#include "gc_implementation/shenandoah/shenandoahLogging.hpp"70#include "gc_implementation/shenandoah/shenandoahHeapRegion.hpp"71#endif // INCLUDE_ALL_GCS7273// Note: This is a special bug reporting site for the JVM74#ifdef VENDOR_URL_VM_BUG75# define DEFAULT_VENDOR_URL_BUG VENDOR_URL_VM_BUG76#else77# define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"78#endif79#define DEFAULT_JAVA_LAUNCHER "generic"8081// Disable options not supported in this release, with a warning if they82// were explicitly requested on the command-line83#define UNSUPPORTED_OPTION(opt, description) \84do { \85if (opt) { \86if (FLAG_IS_CMDLINE(opt)) { \87warning(description " is disabled in this release."); \88} \89FLAG_SET_DEFAULT(opt, false); \90} \91} while(0)9293#define UNSUPPORTED_GC_OPTION(gc) \94do { \95if (gc) { \96if (FLAG_IS_CMDLINE(gc)) { \97warning(#gc " is not supported in this VM. Using Serial GC."); \98} \99FLAG_SET_DEFAULT(gc, false); \100} \101} while(0)102103char** Arguments::_jvm_flags_array = NULL;104int Arguments::_num_jvm_flags = 0;105char** Arguments::_jvm_args_array = NULL;106int Arguments::_num_jvm_args = 0;107char* Arguments::_java_command = NULL;108SystemProperty* Arguments::_system_properties = NULL;109const char* Arguments::_gc_log_filename = NULL;110bool Arguments::_has_profile = false;111size_t Arguments::_conservative_max_heap_alignment = 0;112uintx Arguments::_min_heap_size = 0;113uintx Arguments::_min_heap_free_ratio = 0;114uintx Arguments::_max_heap_free_ratio = 0;115Arguments::Mode Arguments::_mode = _mixed;116bool Arguments::_java_compiler = false;117bool Arguments::_xdebug_mode = false;118const char* Arguments::_java_vendor_url_bug = DEFAULT_VENDOR_URL_BUG;119const char* Arguments::_sun_java_launcher = DEFAULT_JAVA_LAUNCHER;120int Arguments::_sun_java_launcher_pid = -1;121bool Arguments::_created_by_gamma_launcher = false;122123// These parameters are reset in method parse_vm_init_args(JavaVMInitArgs*)124bool Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;125bool Arguments::_UseOnStackReplacement = UseOnStackReplacement;126bool Arguments::_BackgroundCompilation = BackgroundCompilation;127bool Arguments::_ClipInlining = ClipInlining;128129char* Arguments::SharedArchivePath = NULL;130131AgentLibraryList Arguments::_libraryList;132AgentLibraryList Arguments::_agentList;133134abort_hook_t Arguments::_abort_hook = NULL;135exit_hook_t Arguments::_exit_hook = NULL;136vfprintf_hook_t Arguments::_vfprintf_hook = NULL;137138139SystemProperty *Arguments::_java_ext_dirs = NULL;140SystemProperty *Arguments::_java_endorsed_dirs = NULL;141SystemProperty *Arguments::_sun_boot_library_path = NULL;142SystemProperty *Arguments::_java_library_path = NULL;143SystemProperty *Arguments::_java_home = NULL;144SystemProperty *Arguments::_java_class_path = NULL;145SystemProperty *Arguments::_sun_boot_class_path = NULL;146147char* Arguments::_meta_index_path = NULL;148char* Arguments::_meta_index_dir = NULL;149150// Check if head of 'option' matches 'name', and sets 'tail' remaining part of option string151152static bool match_option(const JavaVMOption *option, const char* name,153const char** tail) {154int len = (int)strlen(name);155if (strncmp(option->optionString, name, len) == 0) {156*tail = option->optionString + len;157return true;158} else {159return false;160}161}162163#if INCLUDE_JFR164// return true on failure165static bool match_jfr_option(const JavaVMOption** option) {166assert((*option)->optionString != NULL, "invariant");167char* tail = NULL;168if (match_option(*option, "-XX:StartFlightRecording", (const char**)&tail)) {169return Jfr::on_start_flight_recording_option(option, tail);170} else if (match_option(*option, "-XX:FlightRecorderOptions", (const char**)&tail)) {171return Jfr::on_flight_recorder_option(option, tail);172}173return false;174}175#endif176177static void logOption(const char* opt) {178if (PrintVMOptions) {179jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);180}181}182183// Process java launcher properties.184void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {185// See if sun.java.launcher or sun.java.launcher.pid is defined.186// Must do this before setting up other system properties,187// as some of them may depend on launcher type.188for (int index = 0; index < args->nOptions; index++) {189const JavaVMOption* option = args->options + index;190const char* tail;191192if (match_option(option, "-Dsun.java.launcher=", &tail)) {193process_java_launcher_argument(tail, option->extraInfo);194continue;195}196if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {197_sun_java_launcher_pid = atoi(tail);198continue;199}200}201}202203// Initialize system properties key and value.204void Arguments::init_system_properties() {205206PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",207"Java Virtual Machine Specification", false));208PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(), false));209PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(), false));210PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(), true));211212// following are JVMTI agent writeable properties.213// Properties values are set to NULL and they are214// os specific they are initialized in os::init_system_properties_values().215_java_ext_dirs = new SystemProperty("java.ext.dirs", NULL, true);216_java_endorsed_dirs = new SystemProperty("java.endorsed.dirs", NULL, true);217_sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL, true);218_java_library_path = new SystemProperty("java.library.path", NULL, true);219_java_home = new SystemProperty("java.home", NULL, true);220_sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL, true);221222_java_class_path = new SystemProperty("java.class.path", "", true);223224// Add to System Property list.225PropertyList_add(&_system_properties, _java_ext_dirs);226PropertyList_add(&_system_properties, _java_endorsed_dirs);227PropertyList_add(&_system_properties, _sun_boot_library_path);228PropertyList_add(&_system_properties, _java_library_path);229PropertyList_add(&_system_properties, _java_home);230PropertyList_add(&_system_properties, _java_class_path);231PropertyList_add(&_system_properties, _sun_boot_class_path);232233// Set OS specific system properties values234os::init_system_properties_values();235}236237238// Update/Initialize System properties after JDK version number is known239void Arguments::init_version_specific_system_properties() {240enum { bufsz = 16 };241char buffer[bufsz];242const char* spec_vendor = "Sun Microsystems Inc.";243uint32_t spec_version = 0;244245if (JDK_Version::is_gte_jdk17x_version()) {246spec_vendor = "Oracle Corporation";247spec_version = JDK_Version::current().major_version();248}249jio_snprintf(buffer, bufsz, "1." UINT32_FORMAT, spec_version);250251PropertyList_add(&_system_properties,252new SystemProperty("java.vm.specification.vendor", spec_vendor, false));253PropertyList_add(&_system_properties,254new SystemProperty("java.vm.specification.version", buffer, false));255PropertyList_add(&_system_properties,256new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(), false));257}258259/**260* Provide a slightly more user-friendly way of eliminating -XX flags.261* When a flag is eliminated, it can be added to this list in order to262* continue accepting this flag on the command-line, while issuing a warning263* and ignoring the value. Once the JDK version reaches the 'accept_until'264* limit, we flatly refuse to admit the existence of the flag. This allows265* a flag to die correctly over JDK releases using HSX.266*/267typedef struct {268const char* name;269JDK_Version obsoleted_in; // when the flag went away270JDK_Version accept_until; // which version to start denying the existence271} ObsoleteFlag;272273static ObsoleteFlag obsolete_jvm_flags[] = {274{ "UseTrainGC", JDK_Version::jdk(5), JDK_Version::jdk(7) },275{ "UseSpecialLargeObjectHandling", JDK_Version::jdk(5), JDK_Version::jdk(7) },276{ "UseOversizedCarHandling", JDK_Version::jdk(5), JDK_Version::jdk(7) },277{ "TraceCarAllocation", JDK_Version::jdk(5), JDK_Version::jdk(7) },278{ "PrintTrainGCProcessingStats", JDK_Version::jdk(5), JDK_Version::jdk(7) },279{ "LogOfCarSpaceSize", JDK_Version::jdk(5), JDK_Version::jdk(7) },280{ "OversizedCarThreshold", JDK_Version::jdk(5), JDK_Version::jdk(7) },281{ "MinTickInterval", JDK_Version::jdk(5), JDK_Version::jdk(7) },282{ "DefaultTickInterval", JDK_Version::jdk(5), JDK_Version::jdk(7) },283{ "MaxTickInterval", JDK_Version::jdk(5), JDK_Version::jdk(7) },284{ "DelayTickAdjustment", JDK_Version::jdk(5), JDK_Version::jdk(7) },285{ "ProcessingToTenuringRatio", JDK_Version::jdk(5), JDK_Version::jdk(7) },286{ "MinTrainLength", JDK_Version::jdk(5), JDK_Version::jdk(7) },287{ "AppendRatio", JDK_Version::jdk_update(6,10), JDK_Version::jdk(7) },288{ "DefaultMaxRAM", JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },289{ "DefaultInitialRAMFraction",290JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },291{ "UseDepthFirstScavengeOrder",292JDK_Version::jdk_update(6,22), JDK_Version::jdk(7) },293{ "HandlePromotionFailure",294JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },295{ "MaxLiveObjectEvacuationRatio",296JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },297{ "ForceSharedSpaces", JDK_Version::jdk_update(6,25), JDK_Version::jdk(8) },298{ "UseParallelOldGCCompacting",299JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },300{ "UseParallelDensePrefixUpdate",301JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },302{ "UseParallelOldGCDensePrefix",303JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },304{ "AllowTransitionalJSR292", JDK_Version::jdk(7), JDK_Version::jdk(8) },305{ "UseCompressedStrings", JDK_Version::jdk(7), JDK_Version::jdk(8) },306{ "CMSPermGenPrecleaningEnabled", JDK_Version::jdk(8), JDK_Version::jdk(9) },307{ "CMSTriggerPermRatio", JDK_Version::jdk(8), JDK_Version::jdk(9) },308{ "CMSInitiatingPermOccupancyFraction", JDK_Version::jdk(8), JDK_Version::jdk(9) },309{ "AdaptivePermSizeWeight", JDK_Version::jdk(8), JDK_Version::jdk(9) },310{ "PermGenPadding", JDK_Version::jdk(8), JDK_Version::jdk(9) },311{ "PermMarkSweepDeadRatio", JDK_Version::jdk(8), JDK_Version::jdk(9) },312{ "PermSize", JDK_Version::jdk(8), JDK_Version::jdk(9) },313{ "MaxPermSize", JDK_Version::jdk(8), JDK_Version::jdk(9) },314{ "MinPermHeapExpansion", JDK_Version::jdk(8), JDK_Version::jdk(9) },315{ "MaxPermHeapExpansion", JDK_Version::jdk(8), JDK_Version::jdk(9) },316{ "CMSRevisitStackSize", JDK_Version::jdk(8), JDK_Version::jdk(9) },317{ "PrintRevisitStats", JDK_Version::jdk(8), JDK_Version::jdk(9) },318{ "UseVectoredExceptions", JDK_Version::jdk(8), JDK_Version::jdk(9) },319{ "UseSplitVerifier", JDK_Version::jdk(8), JDK_Version::jdk(9) },320{ "UseISM", JDK_Version::jdk(8), JDK_Version::jdk(9) },321{ "UsePermISM", JDK_Version::jdk(8), JDK_Version::jdk(9) },322{ "UseMPSS", JDK_Version::jdk(8), JDK_Version::jdk(9) },323{ "UseStringCache", JDK_Version::jdk(8), JDK_Version::jdk(9) },324{ "UseOldInlining", JDK_Version::jdk_update(8, 20), JDK_Version::jdk(10) },325{ "AutoShutdownNMT", JDK_Version::jdk_update(8, 40), JDK_Version::jdk(10) },326{ "CompilationRepeat", JDK_Version::jdk(8), JDK_Version::jdk(9) },327{ "SegmentedHeapDumpThreshold", JDK_Version::jdk_update(8, 252), JDK_Version::jdk(10) },328#ifdef PRODUCT329{ "DesiredMethodLimit",330JDK_Version::jdk_update(7, 2), JDK_Version::jdk(8) },331#endif // PRODUCT332{ NULL, JDK_Version(0), JDK_Version(0) }333};334335// Returns true if the flag is obsolete and fits into the range specified336// for being ignored. In the case that the flag is ignored, the 'version'337// value is filled in with the version number when the flag became338// obsolete so that that value can be displayed to the user.339bool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {340int i = 0;341assert(version != NULL, "Must provide a version buffer");342while (obsolete_jvm_flags[i].name != NULL) {343const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];344// <flag>=xxx form345// [-|+]<flag> form346if ((strncmp(flag_status.name, s, strlen(flag_status.name)) == 0) ||347((s[0] == '+' || s[0] == '-') &&348(strncmp(flag_status.name, &s[1], strlen(flag_status.name)) == 0))) {349if (JDK_Version::current().compare(flag_status.accept_until) == -1) {350*version = flag_status.obsoleted_in;351return true;352}353}354i++;355}356return false;357}358359// Constructs the system class path (aka boot class path) from the following360// components, in order:361//362// prefix // from -Xbootclasspath/p:...363// endorsed // the expansion of -Djava.endorsed.dirs=...364// base // from os::get_system_properties() or -Xbootclasspath=365// suffix // from -Xbootclasspath/a:...366//367// java.endorsed.dirs is a list of directories; any jar or zip files in the368// directories are added to the sysclasspath just before the base.369//370// This could be AllStatic, but it isn't needed after argument processing is371// complete.372class SysClassPath: public StackObj {373public:374SysClassPath(const char* base);375~SysClassPath();376377inline void set_base(const char* base);378inline void add_prefix(const char* prefix);379inline void add_suffix_to_prefix(const char* suffix);380inline void add_suffix(const char* suffix);381inline void reset_path(const char* base);382383// Expand the jar/zip files in each directory listed by the java.endorsed.dirs384// property. Must be called after all command-line arguments have been385// processed (in particular, -Djava.endorsed.dirs=...) and before calling386// combined_path().387void expand_endorsed();388389inline const char* get_base() const { return _items[_scp_base]; }390inline const char* get_prefix() const { return _items[_scp_prefix]; }391inline const char* get_suffix() const { return _items[_scp_suffix]; }392inline const char* get_endorsed() const { return _items[_scp_endorsed]; }393394// Combine all the components into a single c-heap-allocated string; caller395// must free the string if/when no longer needed.396char* combined_path();397398private:399// Utility routines.400static char* add_to_path(const char* path, const char* str, bool prepend);401static char* add_jars_to_path(char* path, const char* directory);402403inline void reset_item_at(int index);404405// Array indices for the items that make up the sysclasspath. All except the406// base are allocated in the C heap and freed by this class.407enum {408_scp_prefix, // from -Xbootclasspath/p:...409_scp_endorsed, // the expansion of -Djava.endorsed.dirs=...410_scp_base, // the default sysclasspath411_scp_suffix, // from -Xbootclasspath/a:...412_scp_nitems // the number of items, must be last.413};414415const char* _items[_scp_nitems];416DEBUG_ONLY(bool _expansion_done;)417};418419SysClassPath::SysClassPath(const char* base) {420memset(_items, 0, sizeof(_items));421_items[_scp_base] = base;422DEBUG_ONLY(_expansion_done = false;)423}424425SysClassPath::~SysClassPath() {426// Free everything except the base.427for (int i = 0; i < _scp_nitems; ++i) {428if (i != _scp_base) reset_item_at(i);429}430DEBUG_ONLY(_expansion_done = false;)431}432433inline void SysClassPath::set_base(const char* base) {434_items[_scp_base] = base;435}436437inline void SysClassPath::add_prefix(const char* prefix) {438_items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);439}440441inline void SysClassPath::add_suffix_to_prefix(const char* suffix) {442_items[_scp_prefix] = add_to_path(_items[_scp_prefix], suffix, false);443}444445inline void SysClassPath::add_suffix(const char* suffix) {446_items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);447}448449inline void SysClassPath::reset_item_at(int index) {450assert(index < _scp_nitems && index != _scp_base, "just checking");451if (_items[index] != NULL) {452FREE_C_HEAP_ARRAY(char, _items[index], mtInternal);453_items[index] = NULL;454}455}456457inline void SysClassPath::reset_path(const char* base) {458// Clear the prefix and suffix.459reset_item_at(_scp_prefix);460reset_item_at(_scp_suffix);461set_base(base);462}463464//------------------------------------------------------------------------------465466void SysClassPath::expand_endorsed() {467assert(_items[_scp_endorsed] == NULL, "can only be called once.");468469const char* path = Arguments::get_property("java.endorsed.dirs");470if (path == NULL) {471path = Arguments::get_endorsed_dir();472assert(path != NULL, "no default for java.endorsed.dirs");473}474475char* expanded_path = NULL;476const char separator = *os::path_separator();477const char* const end = path + strlen(path);478while (path < end) {479const char* tmp_end = strchr(path, separator);480if (tmp_end == NULL) {481expanded_path = add_jars_to_path(expanded_path, path);482path = end;483} else {484char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);485memcpy(dirpath, path, tmp_end - path);486dirpath[tmp_end - path] = '\0';487expanded_path = add_jars_to_path(expanded_path, dirpath);488FREE_C_HEAP_ARRAY(char, dirpath, mtInternal);489path = tmp_end + 1;490}491}492_items[_scp_endorsed] = expanded_path;493DEBUG_ONLY(_expansion_done = true;)494}495496// Combine the bootclasspath elements, some of which may be null, into a single497// c-heap-allocated string.498char* SysClassPath::combined_path() {499assert(_items[_scp_base] != NULL, "empty default sysclasspath");500assert(_expansion_done, "must call expand_endorsed() first.");501502size_t lengths[_scp_nitems];503size_t total_len = 0;504505const char separator = *os::path_separator();506507// Get the lengths.508int i;509for (i = 0; i < _scp_nitems; ++i) {510if (_items[i] != NULL) {511lengths[i] = strlen(_items[i]);512// Include space for the separator char (or a NULL for the last item).513total_len += lengths[i] + 1;514}515}516assert(total_len > 0, "empty sysclasspath not allowed");517518// Copy the _items to a single string.519char* cp = NEW_C_HEAP_ARRAY(char, total_len, mtInternal);520char* cp_tmp = cp;521for (i = 0; i < _scp_nitems; ++i) {522if (_items[i] != NULL) {523memcpy(cp_tmp, _items[i], lengths[i]);524cp_tmp += lengths[i];525*cp_tmp++ = separator;526}527}528*--cp_tmp = '\0'; // Replace the extra separator.529return cp;530}531532// Note: path must be c-heap-allocated (or NULL); it is freed if non-null.533char*534SysClassPath::add_to_path(const char* path, const char* str, bool prepend) {535char *cp;536537assert(str != NULL, "just checking");538if (path == NULL) {539size_t len = strlen(str) + 1;540cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);541memcpy(cp, str, len); // copy the trailing null542} else {543const char separator = *os::path_separator();544size_t old_len = strlen(path);545size_t str_len = strlen(str);546size_t len = old_len + str_len + 2;547548if (prepend) {549cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);550char* cp_tmp = cp;551memcpy(cp_tmp, str, str_len);552cp_tmp += str_len;553*cp_tmp = separator;554memcpy(++cp_tmp, path, old_len + 1); // copy the trailing null555FREE_C_HEAP_ARRAY(char, path, mtInternal);556} else {557cp = REALLOC_C_HEAP_ARRAY(char, path, len, mtInternal);558char* cp_tmp = cp + old_len;559*cp_tmp = separator;560memcpy(++cp_tmp, str, str_len + 1); // copy the trailing null561}562}563return cp;564}565566// Scan the directory and append any jar or zip files found to path.567// Note: path must be c-heap-allocated (or NULL); it is freed if non-null.568char* SysClassPath::add_jars_to_path(char* path, const char* directory) {569DIR* dir = os::opendir(directory);570if (dir == NULL) return path;571572char dir_sep[2] = { '\0', '\0' };573size_t directory_len = strlen(directory);574const char fileSep = *os::file_separator();575if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;576577/* Scan the directory for jars/zips, appending them to path. */578struct dirent *entry;579while ((entry = os::readdir(dir)) != NULL) {580const char* name = entry->d_name;581const char* ext = name + strlen(name) - 4;582bool isJarOrZip = ext > name &&583(os::file_name_strcmp(ext, ".jar") == 0 ||584os::file_name_strcmp(ext, ".zip") == 0);585if (isJarOrZip) {586size_t length = directory_len + 2 + strlen(name);587char* jarpath = NEW_C_HEAP_ARRAY(char, length, mtInternal);588jio_snprintf(jarpath, length, "%s%s%s", directory, dir_sep, name);589path = add_to_path(path, jarpath, false);590FREE_C_HEAP_ARRAY(char, jarpath, mtInternal);591}592}593os::closedir(dir);594return path;595}596597// Parses a memory size specification string.598static bool atomull(const char *s, julong* result) {599julong n = 0;600int args_read = sscanf(s, JULONG_FORMAT, &n);601if (args_read != 1) {602return false;603}604while (*s != '\0' && isdigit(*s)) {605s++;606}607// 4705540: illegal if more characters are found after the first non-digit608if (strlen(s) > 1) {609return false;610}611switch (*s) {612case 'T': case 't':613*result = n * G * K;614// Check for overflow.615if (*result/((julong)G * K) != n) return false;616return true;617case 'G': case 'g':618*result = n * G;619if (*result/G != n) return false;620return true;621case 'M': case 'm':622*result = n * M;623if (*result/M != n) return false;624return true;625case 'K': case 'k':626*result = n * K;627if (*result/K != n) return false;628return true;629case '\0':630*result = n;631return true;632default:633return false;634}635}636637Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {638if (size < min_size) return arg_too_small;639// Check that size will fit in a size_t (only relevant on 32-bit)640if (size > max_uintx) return arg_too_big;641return arg_in_range;642}643644// Describe an argument out of range error645void Arguments::describe_range_error(ArgsRange errcode) {646switch(errcode) {647case arg_too_big:648jio_fprintf(defaultStream::error_stream(),649"The specified size exceeds the maximum "650"representable size.\n");651break;652case arg_too_small:653case arg_unreadable:654case arg_in_range:655// do nothing for now656break;657default:658ShouldNotReachHere();659}660}661662static bool set_bool_flag(char* name, bool value, Flag::Flags origin) {663return CommandLineFlags::boolAtPut(name, &value, origin);664}665666static bool set_fp_numeric_flag(char* name, char* value, Flag::Flags origin) {667double v;668if (sscanf(value, "%lf", &v) != 1) {669return false;670}671672if (CommandLineFlags::doubleAtPut(name, &v, origin)) {673return true;674}675return false;676}677678static bool set_numeric_flag(char* name, char* value, Flag::Flags origin) {679julong v;680intx intx_v;681bool is_neg = false;682// Check the sign first since atomull() parses only unsigned values.683if (*value == '-') {684if (!CommandLineFlags::intxAt(name, &intx_v)) {685return false;686}687value++;688is_neg = true;689}690if (!atomull(value, &v)) {691return false;692}693intx_v = (intx) v;694if (is_neg) {695intx_v = -intx_v;696}697if (CommandLineFlags::intxAtPut(name, &intx_v, origin)) {698return true;699}700uintx uintx_v = (uintx) v;701if (!is_neg && CommandLineFlags::uintxAtPut(name, &uintx_v, origin)) {702return true;703}704uint64_t uint64_t_v = (uint64_t) v;705if (!is_neg && CommandLineFlags::uint64_tAtPut(name, &uint64_t_v, origin)) {706return true;707}708return false;709}710711static bool set_string_flag(char* name, const char* value, Flag::Flags origin) {712if (!CommandLineFlags::ccstrAtPut(name, &value, origin)) return false;713// Contract: CommandLineFlags always returns a pointer that needs freeing.714FREE_C_HEAP_ARRAY(char, value, mtInternal);715return true;716}717718static bool append_to_string_flag(char* name, const char* new_value, Flag::Flags origin) {719const char* old_value = "";720if (!CommandLineFlags::ccstrAt(name, &old_value)) return false;721size_t old_len = old_value != NULL ? strlen(old_value) : 0;722size_t new_len = strlen(new_value);723const char* value;724char* free_this_too = NULL;725if (old_len == 0) {726value = new_value;727} else if (new_len == 0) {728value = old_value;729} else {730size_t length = old_len + 1 + new_len + 1;731char* buf = NEW_C_HEAP_ARRAY(char, length, mtInternal);732// each new setting adds another LINE to the switch:733jio_snprintf(buf, length, "%s\n%s", old_value, new_value);734value = buf;735free_this_too = buf;736}737(void) CommandLineFlags::ccstrAtPut(name, &value, origin);738// CommandLineFlags always returns a pointer that needs freeing.739FREE_C_HEAP_ARRAY(char, value, mtInternal);740if (free_this_too != NULL) {741// CommandLineFlags made its own copy, so I must delete my own temp. buffer.742FREE_C_HEAP_ARRAY(char, free_this_too, mtInternal);743}744return true;745}746747bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {748749// range of acceptable characters spelled out for portability reasons750#define NAME_RANGE "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"751#define BUFLEN 255752char name[BUFLEN+1];753char dummy;754755if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {756return set_bool_flag(name, false, origin);757}758if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {759return set_bool_flag(name, true, origin);760}761762char punct;763if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {764const char* value = strchr(arg, '=') + 1;765Flag* flag = Flag::find_flag(name, strlen(name));766if (flag != NULL && flag->is_ccstr()) {767if (flag->ccstr_accumulates()) {768return append_to_string_flag(name, value, origin);769} else {770if (value[0] == '\0') {771value = NULL;772}773return set_string_flag(name, value, origin);774}775}776}777778if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {779const char* value = strchr(arg, '=') + 1;780// -XX:Foo:=xxx will reset the string flag to the given value.781if (value[0] == '\0') {782value = NULL;783}784return set_string_flag(name, value, origin);785}786787#define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"788#define SIGNED_NUMBER_RANGE "[-0123456789]"789#define NUMBER_RANGE "[0123456789]"790char value[BUFLEN + 1];791char value2[BUFLEN + 1];792if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {793// Looks like a floating-point number -- try again with more lenient format string794if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {795return set_fp_numeric_flag(name, value, origin);796}797}798799#define VALUE_RANGE "[-kmgtKMGT0123456789]"800if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {801return set_numeric_flag(name, value, origin);802}803804return false;805}806807void Arguments::add_string(char*** bldarray, int* count, const char* arg) {808assert(bldarray != NULL, "illegal argument");809810if (arg == NULL) {811return;812}813814int new_count = *count + 1;815816// expand the array and add arg to the last element817if (*bldarray == NULL) {818*bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtInternal);819} else {820*bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtInternal);821}822(*bldarray)[*count] = strdup(arg);823*count = new_count;824}825826void Arguments::build_jvm_args(const char* arg) {827add_string(&_jvm_args_array, &_num_jvm_args, arg);828}829830void Arguments::build_jvm_flags(const char* arg) {831add_string(&_jvm_flags_array, &_num_jvm_flags, arg);832}833834// utility function to return a string that concatenates all835// strings in a given char** array836const char* Arguments::build_resource_string(char** args, int count) {837if (args == NULL || count == 0) {838return NULL;839}840size_t length = 0;841for (int i = 0; i < count; i++) {842length += strlen(args[i]) + 1; // add 1 for a space or NULL terminating character843}844char* s = NEW_RESOURCE_ARRAY(char, length);845char* dst = s;846for (int j = 0; j < count; j++) {847size_t offset = strlen(args[j]) + 1; // add 1 for a space or NULL terminating character848jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with NULL character849dst += offset;850length -= offset;851}852return (const char*) s;853}854855void Arguments::print_on(outputStream* st) {856st->print_cr("VM Arguments:");857if (num_jvm_flags() > 0) {858st->print("jvm_flags: "); print_jvm_flags_on(st);859}860if (num_jvm_args() > 0) {861st->print("jvm_args: "); print_jvm_args_on(st);862}863st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");864if (_java_class_path != NULL) {865char* path = _java_class_path->value();866st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );867}868st->print_cr("Launcher Type: %s", _sun_java_launcher);869}870871void Arguments::print_jvm_flags_on(outputStream* st) {872if (_num_jvm_flags > 0) {873for (int i=0; i < _num_jvm_flags; i++) {874st->print("%s ", _jvm_flags_array[i]);875}876st->cr();877}878}879880void Arguments::print_jvm_args_on(outputStream* st) {881if (_num_jvm_args > 0) {882for (int i=0; i < _num_jvm_args; i++) {883st->print("%s ", _jvm_args_array[i]);884}885st->cr();886}887}888889bool Arguments::process_argument(const char* arg,890jboolean ignore_unrecognized, Flag::Flags origin) {891892JDK_Version since = JDK_Version();893894if (parse_argument(arg, origin) || ignore_unrecognized) {895return true;896}897898bool has_plus_minus = (*arg == '+' || *arg == '-');899const char* const argname = has_plus_minus ? arg + 1 : arg;900if (is_newly_obsolete(arg, &since)) {901char version[256];902since.to_string(version, sizeof(version));903warning("ignoring option %s; support was removed in %s", argname, version);904return true;905}906907// For locked flags, report a custom error message if available.908// Otherwise, report the standard unrecognized VM option.909910size_t arg_len;911const char* equal_sign = strchr(argname, '=');912if (equal_sign == NULL) {913arg_len = strlen(argname);914} else {915arg_len = equal_sign - argname;916}917918Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);919if (found_flag != NULL) {920char locked_message_buf[BUFLEN];921found_flag->get_locked_message(locked_message_buf, BUFLEN);922if (strlen(locked_message_buf) == 0) {923if (found_flag->is_bool() && !has_plus_minus) {924jio_fprintf(defaultStream::error_stream(),925"Missing +/- setting for VM option '%s'\n", argname);926} else if (!found_flag->is_bool() && has_plus_minus) {927jio_fprintf(defaultStream::error_stream(),928"Unexpected +/- setting in VM option '%s'\n", argname);929} else {930jio_fprintf(defaultStream::error_stream(),931"Improperly specified VM option '%s'\n", argname);932}933} else {934jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);935}936} else {937jio_fprintf(defaultStream::error_stream(),938"Unrecognized VM option '%s'\n", argname);939Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);940if (fuzzy_matched != NULL) {941jio_fprintf(defaultStream::error_stream(),942"Did you mean '%s%s%s'?\n",943(fuzzy_matched->is_bool()) ? "(+/-)" : "",944fuzzy_matched->_name,945(fuzzy_matched->is_bool()) ? "" : "=<value>");946}947}948949// allow for commandline "commenting out" options like -XX:#+Verbose950return arg[0] == '#';951}952953bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {954FILE* stream = fopen(file_name, "rb");955if (stream == NULL) {956if (should_exist) {957jio_fprintf(defaultStream::error_stream(),958"Could not open settings file %s\n", file_name);959return false;960} else {961return true;962}963}964965char token[1024];966int pos = 0;967968bool in_white_space = true;969bool in_comment = false;970bool in_quote = false;971char quote_c = 0;972bool result = true;973974int c = getc(stream);975while(c != EOF && pos < (int)(sizeof(token)-1)) {976if (in_white_space) {977if (in_comment) {978if (c == '\n') in_comment = false;979} else {980if (c == '#') in_comment = true;981else if (!isspace(c)) {982in_white_space = false;983token[pos++] = c;984}985}986} else {987if (c == '\n' || (!in_quote && isspace(c))) {988// token ends at newline, or at unquoted whitespace989// this allows a way to include spaces in string-valued options990token[pos] = '\0';991logOption(token);992result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);993build_jvm_flags(token);994pos = 0;995in_white_space = true;996in_quote = false;997} else if (!in_quote && (c == '\'' || c == '"')) {998in_quote = true;999quote_c = c;1000} else if (in_quote && (c == quote_c)) {1001in_quote = false;1002} else {1003token[pos++] = c;1004}1005}1006c = getc(stream);1007}1008if (pos > 0) {1009token[pos] = '\0';1010result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);1011build_jvm_flags(token);1012}1013fclose(stream);1014return result;1015}10161017//=============================================================================================================1018// Parsing of properties (-D)10191020const char* Arguments::get_property(const char* key) {1021return PropertyList_get_value(system_properties(), key);1022}10231024bool Arguments::add_property(const char* prop) {1025const char* eq = strchr(prop, '=');1026char* key;1027// ns must be static--its address may be stored in a SystemProperty object.1028const static char ns[1] = {0};1029char* value = (char *)ns;10301031size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);1032key = AllocateHeap(key_len + 1, mtInternal);1033strncpy(key, prop, key_len);1034key[key_len] = '\0';10351036if (eq != NULL) {1037size_t value_len = strlen(prop) - key_len - 1;1038value = AllocateHeap(value_len + 1, mtInternal);1039strncpy(value, &prop[key_len + 1], value_len + 1);1040}10411042if (strcmp(key, "java.compiler") == 0) {1043process_java_compiler_argument(value);1044FreeHeap(key);1045if (eq != NULL) {1046FreeHeap(value);1047}1048return true;1049} else if (strcmp(key, "sun.java.command") == 0) {1050_java_command = value;10511052// Record value in Arguments, but let it get passed to Java.1053} else if (strcmp(key, "sun.java.launcher.pid") == 0) {1054// launcher.pid property is private and is processed1055// in process_sun_java_launcher_properties();1056// the sun.java.launcher property is passed on to the java application1057FreeHeap(key);1058if (eq != NULL) {1059FreeHeap(value);1060}1061return true;1062} else if (strcmp(key, "java.vendor.url.bug") == 0) {1063// save it in _java_vendor_url_bug, so JVM fatal error handler can access1064// its value without going through the property list or making a Java call.1065_java_vendor_url_bug = value;1066} else if (strcmp(key, "sun.boot.library.path") == 0) {1067PropertyList_unique_add(&_system_properties, key, value, true);1068return true;1069}1070// Create new property and add at the end of the list1071PropertyList_unique_add(&_system_properties, key, value);1072return true;1073}10741075//===========================================================================================================1076// Setting int/mixed/comp mode flags10771078void Arguments::set_mode_flags(Mode mode) {1079// Set up default values for all flags.1080// If you add a flag to any of the branches below,1081// add a default value for it here.1082set_java_compiler(false);1083_mode = mode;10841085// Ensure Agent_OnLoad has the correct initial values.1086// This may not be the final mode; mode may change later in onload phase.1087PropertyList_unique_add(&_system_properties, "java.vm.info",1088(char*)VM_Version::vm_info_string(), false);10891090UseInterpreter = true;1091UseCompiler = true;1092UseLoopCounter = true;10931094#ifndef ZERO1095// Turn these off for mixed and comp. Leave them on for Zero.1096if (FLAG_IS_DEFAULT(UseFastAccessorMethods)) {1097UseFastAccessorMethods = (mode == _int);1098}1099if (FLAG_IS_DEFAULT(UseFastEmptyMethods)) {1100UseFastEmptyMethods = (mode == _int);1101}1102#endif11031104// Default values may be platform/compiler dependent -1105// use the saved values1106ClipInlining = Arguments::_ClipInlining;1107AlwaysCompileLoopMethods = Arguments::_AlwaysCompileLoopMethods;1108UseOnStackReplacement = Arguments::_UseOnStackReplacement;1109BackgroundCompilation = Arguments::_BackgroundCompilation;11101111// Change from defaults based on mode1112switch (mode) {1113default:1114ShouldNotReachHere();1115break;1116case _int:1117UseCompiler = false;1118UseLoopCounter = false;1119AlwaysCompileLoopMethods = false;1120UseOnStackReplacement = false;1121break;1122case _mixed:1123// same as default1124break;1125case _comp:1126UseInterpreter = false;1127BackgroundCompilation = false;1128ClipInlining = false;1129// Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.1130// We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and1131// compile a level 4 (C2) and then continue executing it.1132if (TieredCompilation) {1133Tier3InvokeNotifyFreqLog = 0;1134Tier4InvocationThreshold = 0;1135}1136break;1137}1138}11391140#if defined(COMPILER2) || defined(_LP64) || !INCLUDE_CDS1141// Conflict: required to use shared spaces (-Xshare:on), but1142// incompatible command line options were chosen.11431144static void no_shared_spaces(const char* message) {1145if (RequireSharedSpaces) {1146jio_fprintf(defaultStream::error_stream(),1147"Class data sharing is inconsistent with other specified options.\n");1148vm_exit_during_initialization("Unable to use shared archive.", message);1149} else {1150FLAG_SET_DEFAULT(UseSharedSpaces, false);1151}1152}1153#endif11541155void Arguments::set_tiered_flags() {1156// With tiered, set default policy to AdvancedThresholdPolicy, which is 3.1157if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {1158FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);1159}1160if (CompilationPolicyChoice < 2) {1161vm_exit_during_initialization(1162"Incompatible compilation policy selected", NULL);1163}1164// Increase the code cache size - tiered compiles a lot more.1165if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {1166#ifndef AARCH641167FLAG_SET_DEFAULT(ReservedCodeCacheSize, ReservedCodeCacheSize * 5);1168#else1169FLAG_SET_DEFAULT(ReservedCodeCacheSize,1170MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));1171#endif1172}1173if (!UseInterpreter) { // -Xcomp1174Tier3InvokeNotifyFreqLog = 0;1175Tier4InvocationThreshold = 0;1176}1177}11781179/**1180* Returns the minimum number of compiler threads needed to run the JVM. The following1181* configurations are possible.1182*1183* 1) The JVM is build using an interpreter only. As a result, the minimum number of1184* compiler threads is 0.1185* 2) The JVM is build using the compiler(s) and tiered compilation is disabled. As1186* a result, either C1 or C2 is used, so the minimum number of compiler threads is 1.1187* 3) The JVM is build using the compiler(s) and tiered compilation is enabled. However,1188* the option "TieredStopAtLevel < CompLevel_full_optimization". As a result, only1189* C1 can be used, so the minimum number of compiler threads is 1.1190* 4) The JVM is build using the compilers and tiered compilation is enabled. The option1191* 'TieredStopAtLevel = CompLevel_full_optimization' (the default value). As a result,1192* the minimum number of compiler threads is 2.1193*/1194int Arguments::get_min_number_of_compiler_threads() {1195#if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)1196return 0; // case 11197#else1198if (!TieredCompilation || (TieredStopAtLevel < CompLevel_full_optimization)) {1199return 1; // case 2 or case 31200}1201return 2; // case 4 (tiered)1202#endif1203}12041205#if INCLUDE_ALL_GCS1206static void disable_adaptive_size_policy(const char* collector_name) {1207if (UseAdaptiveSizePolicy) {1208if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {1209warning("disabling UseAdaptiveSizePolicy; it is incompatible with %s.",1210collector_name);1211}1212FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);1213}1214}12151216void Arguments::set_parnew_gc_flags() {1217assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,1218"control point invariant");1219assert(UseParNewGC, "Error");12201221// Turn off AdaptiveSizePolicy for parnew until it is complete.1222disable_adaptive_size_policy("UseParNewGC");12231224if (FLAG_IS_DEFAULT(ParallelGCThreads)) {1225FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());1226assert(ParallelGCThreads > 0, "We should always have at least one thread by default");1227} else if (ParallelGCThreads == 0) {1228jio_fprintf(defaultStream::error_stream(),1229"The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");1230vm_exit(1);1231}12321233// By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,1234// these settings are default for Parallel Scavenger. For ParNew+Tenured configuration1235// we set them to 1024 and 1024.1236// See CR 6362902.1237if (FLAG_IS_DEFAULT(YoungPLABSize)) {1238FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);1239}1240if (FLAG_IS_DEFAULT(OldPLABSize)) {1241FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);1242}12431244// AlwaysTenure flag should make ParNew promote all at first collection.1245// See CR 6362902.1246if (AlwaysTenure) {1247FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0);1248}1249// When using compressed oops, we use local overflow stacks,1250// rather than using a global overflow list chained through1251// the klass word of the object's pre-image.1252if (UseCompressedOops && !ParGCUseLocalOverflow) {1253if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {1254warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");1255}1256FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);1257}1258assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");1259}12601261// Adjust some sizes to suit CMS and/or ParNew needs; these work well on1262// sparc/solaris for certain applications, but would gain from1263// further optimization and tuning efforts, and would almost1264// certainly gain from analysis of platform and environment.1265void Arguments::set_cms_and_parnew_gc_flags() {1266assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");1267assert(UseConcMarkSweepGC, "CMS is expected to be on here");12681269// If we are using CMS, we prefer to UseParNewGC,1270// unless explicitly forbidden.1271if (FLAG_IS_DEFAULT(UseParNewGC)) {1272FLAG_SET_ERGO(bool, UseParNewGC, true);1273}12741275// Turn off AdaptiveSizePolicy by default for cms until it is complete.1276disable_adaptive_size_policy("UseConcMarkSweepGC");12771278// In either case, adjust ParallelGCThreads and/or UseParNewGC1279// as needed.1280if (UseParNewGC) {1281set_parnew_gc_flags();1282}12831284size_t max_heap = align_size_down(MaxHeapSize,1285CardTableRS::ct_max_alignment_constraint());12861287// Now make adjustments for CMS1288intx tenuring_default = (intx)6;1289size_t young_gen_per_worker = CMSYoungGenPerWorker;12901291// Preferred young gen size for "short" pauses:1292// upper bound depends on # of threads and NewRatio.1293const uintx parallel_gc_threads =1294(ParallelGCThreads == 0 ? 1 : ParallelGCThreads);1295const size_t preferred_max_new_size_unaligned =1296MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * parallel_gc_threads));1297size_t preferred_max_new_size =1298align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());12991300// Unless explicitly requested otherwise, size young gen1301// for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads13021303// If either MaxNewSize or NewRatio is set on the command line,1304// assume the user is trying to set the size of the young gen.1305if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {13061307// Set MaxNewSize to our calculated preferred_max_new_size unless1308// NewSize was set on the command line and it is larger than1309// preferred_max_new_size.1310if (!FLAG_IS_DEFAULT(NewSize)) { // NewSize explicitly set at command-line1311FLAG_SET_ERGO(uintx, MaxNewSize, MAX2(NewSize, preferred_max_new_size));1312} else {1313FLAG_SET_ERGO(uintx, MaxNewSize, preferred_max_new_size);1314}1315if (PrintGCDetails && Verbose) {1316// Too early to use gclog_or_tty1317tty->print_cr("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);1318}13191320// Code along this path potentially sets NewSize and OldSize1321if (PrintGCDetails && Verbose) {1322// Too early to use gclog_or_tty1323tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT1324" initial_heap_size: " SIZE_FORMAT1325" max_heap: " SIZE_FORMAT,1326min_heap_size(), InitialHeapSize, max_heap);1327}1328size_t min_new = preferred_max_new_size;1329if (FLAG_IS_CMDLINE(NewSize)) {1330min_new = NewSize;1331}1332if (max_heap > min_new && min_heap_size() > min_new) {1333// Unless explicitly requested otherwise, make young gen1334// at least min_new, and at most preferred_max_new_size.1335if (FLAG_IS_DEFAULT(NewSize)) {1336FLAG_SET_ERGO(uintx, NewSize, MAX2(NewSize, min_new));1337FLAG_SET_ERGO(uintx, NewSize, MIN2(preferred_max_new_size, NewSize));1338if (PrintGCDetails && Verbose) {1339// Too early to use gclog_or_tty1340tty->print_cr("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);1341}1342}1343// Unless explicitly requested otherwise, size old gen1344// so it's NewRatio x of NewSize.1345if (FLAG_IS_DEFAULT(OldSize)) {1346if (max_heap > NewSize) {1347FLAG_SET_ERGO(uintx, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));1348if (PrintGCDetails && Verbose) {1349// Too early to use gclog_or_tty1350tty->print_cr("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);1351}1352}1353}1354}1355}1356// Unless explicitly requested otherwise, definitely1357// promote all objects surviving "tenuring_default" scavenges.1358if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&1359FLAG_IS_DEFAULT(SurvivorRatio)) {1360FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);1361}1362// If we decided above (or user explicitly requested)1363// `promote all' (via MaxTenuringThreshold := 0),1364// prefer minuscule survivor spaces so as not to waste1365// space for (non-existent) survivors1366if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {1367FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));1368}1369// If OldPLABSize is set and CMSParPromoteBlocksToClaim is not,1370// set CMSParPromoteBlocksToClaim equal to OldPLABSize.1371// This is done in order to make ParNew+CMS configuration to work1372// with YoungPLABSize and OldPLABSize options.1373// See CR 6362902.1374if (!FLAG_IS_DEFAULT(OldPLABSize)) {1375if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {1376// OldPLABSize is not the default value but CMSParPromoteBlocksToClaim1377// is. In this situtation let CMSParPromoteBlocksToClaim follow1378// the value (either from the command line or ergonomics) of1379// OldPLABSize. Following OldPLABSize is an ergonomics decision.1380FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, OldPLABSize);1381} else {1382// OldPLABSize and CMSParPromoteBlocksToClaim are both set.1383// CMSParPromoteBlocksToClaim is a collector-specific flag, so1384// we'll let it to take precedence.1385jio_fprintf(defaultStream::error_stream(),1386"Both OldPLABSize and CMSParPromoteBlocksToClaim"1387" options are specified for the CMS collector."1388" CMSParPromoteBlocksToClaim will take precedence.\n");1389}1390}1391if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {1392// OldPLAB sizing manually turned off: Use a larger default setting,1393// unless it was manually specified. This is because a too-low value1394// will slow down scavenges.1395if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {1396FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, 50); // default value before 66311661397}1398}1399// Overwrite OldPLABSize which is the variable we will internally use everywhere.1400FLAG_SET_ERGO(uintx, OldPLABSize, CMSParPromoteBlocksToClaim);1401// If either of the static initialization defaults have changed, note this1402// modification.1403if (!FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim) || !FLAG_IS_DEFAULT(OldPLABWeight)) {1404CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);1405}14061407if (PrintGCDetails && Verbose) {1408tty->print_cr("MarkStackSize: %uk MarkStackSizeMax: %uk",1409(unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));1410tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);1411}1412}1413#endif // INCLUDE_ALL_GCS14141415void set_object_alignment() {1416// Object alignment.1417assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");1418MinObjAlignmentInBytes = ObjectAlignmentInBytes;1419assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");1420MinObjAlignment = MinObjAlignmentInBytes / HeapWordSize;1421assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");1422MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;14231424LogMinObjAlignmentInBytes = exact_log2(ObjectAlignmentInBytes);1425LogMinObjAlignment = LogMinObjAlignmentInBytes - LogHeapWordSize;14261427// Oop encoding heap max1428OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;14291430#if INCLUDE_ALL_GCS1431// Set CMS global values1432CompactibleFreeListSpace::set_cms_values();1433#endif // INCLUDE_ALL_GCS1434}14351436bool verify_object_alignment() {1437// Object alignment.1438if (!is_power_of_2(ObjectAlignmentInBytes)) {1439jio_fprintf(defaultStream::error_stream(),1440"error: ObjectAlignmentInBytes=%d must be power of 2\n",1441(int)ObjectAlignmentInBytes);1442return false;1443}1444if ((int)ObjectAlignmentInBytes < BytesPerLong) {1445jio_fprintf(defaultStream::error_stream(),1446"error: ObjectAlignmentInBytes=%d must be greater or equal %d\n",1447(int)ObjectAlignmentInBytes, BytesPerLong);1448return false;1449}1450// It does not make sense to have big object alignment1451// since a space lost due to alignment will be greater1452// then a saved space from compressed oops.1453if ((int)ObjectAlignmentInBytes > 256) {1454jio_fprintf(defaultStream::error_stream(),1455"error: ObjectAlignmentInBytes=%d must not be greater than 256\n",1456(int)ObjectAlignmentInBytes);1457return false;1458}1459// In case page size is very small.1460if ((int)ObjectAlignmentInBytes >= os::vm_page_size()) {1461jio_fprintf(defaultStream::error_stream(),1462"error: ObjectAlignmentInBytes=%d must be less than page size %d\n",1463(int)ObjectAlignmentInBytes, os::vm_page_size());1464return false;1465}1466if(SurvivorAlignmentInBytes == 0) {1467SurvivorAlignmentInBytes = ObjectAlignmentInBytes;1468} else {1469if (!is_power_of_2(SurvivorAlignmentInBytes)) {1470jio_fprintf(defaultStream::error_stream(),1471"error: SurvivorAlignmentInBytes=%d must be power of 2\n",1472(int)SurvivorAlignmentInBytes);1473return false;1474}1475if (SurvivorAlignmentInBytes < ObjectAlignmentInBytes) {1476jio_fprintf(defaultStream::error_stream(),1477"error: SurvivorAlignmentInBytes=%d must be greater than ObjectAlignmentInBytes=%d \n",1478(int)SurvivorAlignmentInBytes, (int)ObjectAlignmentInBytes);1479return false;1480}1481}1482return true;1483}14841485size_t Arguments::max_heap_for_compressed_oops() {1486// Avoid sign flip.1487assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");1488// We need to fit both the NULL page and the heap into the memory budget, while1489// keeping alignment constraints of the heap. To guarantee the latter, as the1490// NULL page is located before the heap, we pad the NULL page to the conservative1491// maximum alignment that the GC may ever impose upon the heap.1492size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),1493_conservative_max_heap_alignment);14941495LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);1496NOT_LP64(ShouldNotReachHere(); return 0);1497}14981499bool Arguments::should_auto_select_low_pause_collector() {1500if (UseAutoGCSelectPolicy &&1501!FLAG_IS_DEFAULT(MaxGCPauseMillis) &&1502(MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {1503if (PrintGCDetails) {1504// Cannot use gclog_or_tty yet.1505tty->print_cr("Automatic selection of the low pause collector"1506" based on pause goal of %d (ms)", (int) MaxGCPauseMillis);1507}1508return true;1509}1510return false;1511}15121513void Arguments::set_use_compressed_oops() {1514#ifndef ZERO1515#ifdef _LP641516// MaxHeapSize is not set up properly at this point, but1517// the only value that can override MaxHeapSize if we are1518// to use UseCompressedOops is InitialHeapSize.1519size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);15201521if (max_heap_size <= max_heap_for_compressed_oops()) {1522#if !defined(COMPILER1) || defined(TIERED)1523if (FLAG_IS_DEFAULT(UseCompressedOops)) {1524FLAG_SET_ERGO(bool, UseCompressedOops, true);1525}1526#endif1527#ifdef _WIN641528if (UseLargePages && UseCompressedOops) {1529// Cannot allocate guard pages for implicit checks in indexed addressing1530// mode, when large pages are specified on windows.1531// This flag could be switched ON if narrow oop base address is set to 0,1532// see code in Universe::initialize_heap().1533Universe::set_narrow_oop_use_implicit_null_checks(false);1534}1535#endif // _WIN641536} else {1537if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {1538warning("Max heap size too large for Compressed Oops");1539FLAG_SET_DEFAULT(UseCompressedOops, false);1540FLAG_SET_DEFAULT(UseCompressedClassPointers, false);1541}1542}1543#endif // _LP641544#endif // ZERO1545}15461547// NOTE: set_use_compressed_klass_ptrs() must be called after calling1548// set_use_compressed_oops().1549void Arguments::set_use_compressed_klass_ptrs() {1550#ifndef ZERO1551#ifdef _LP641552// UseCompressedOops must be on for UseCompressedClassPointers to be on.1553if (!UseCompressedOops) {1554if (UseCompressedClassPointers) {1555warning("UseCompressedClassPointers requires UseCompressedOops");1556}1557FLAG_SET_DEFAULT(UseCompressedClassPointers, false);1558} else {1559// Turn on UseCompressedClassPointers too1560if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {1561FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);1562}1563// Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.1564if (UseCompressedClassPointers) {1565if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {1566warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");1567FLAG_SET_DEFAULT(UseCompressedClassPointers, false);1568}1569}1570}1571#endif // _LP641572#endif // !ZERO1573}15741575void Arguments::set_conservative_max_heap_alignment() {1576// The conservative maximum required alignment for the heap is the maximum of1577// the alignments imposed by several sources: any requirements from the heap1578// itself, the collector policy and the maximum page size we may run the VM1579// with.1580size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();1581#if INCLUDE_ALL_GCS1582if (UseParallelGC) {1583heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();1584} else if (UseG1GC) {1585heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();1586} else if (UseShenandoahGC) {1587heap_alignment = ShenandoahHeap::conservative_max_heap_alignment();1588}1589#endif // INCLUDE_ALL_GCS1590_conservative_max_heap_alignment = MAX4(heap_alignment,1591(size_t)os::vm_allocation_granularity(),1592os::max_page_size(),1593CollectorPolicy::compute_heap_alignment());1594}15951596void Arguments::select_gc_ergonomically() {1597if (os::is_server_class_machine()) {1598if (should_auto_select_low_pause_collector()) {1599FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);1600} else {1601FLAG_SET_ERGO(bool, UseParallelGC, true);1602}1603}1604}16051606void Arguments::select_gc() {1607if (!gc_selected()) {1608select_gc_ergonomically();1609}1610}16111612void Arguments::set_ergonomics_flags() {1613select_gc();16141615#ifdef COMPILER21616// Shared spaces work fine with other GCs but causes bytecode rewriting1617// to be disabled, which hurts interpreter performance and decreases1618// server performance. When -server is specified, keep the default off1619// unless it is asked for. Future work: either add bytecode rewriting1620// at link time, or rewrite bytecodes in non-shared methods.1621if (!DumpSharedSpaces && !RequireSharedSpaces &&1622(FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {1623no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");1624}1625#endif16261627set_conservative_max_heap_alignment();16281629#ifndef ZERO1630#ifdef _LP641631set_use_compressed_oops();16321633// set_use_compressed_klass_ptrs() must be called after calling1634// set_use_compressed_oops().1635set_use_compressed_klass_ptrs();16361637// Also checks that certain machines are slower with compressed oops1638// in vm_version initialization code.1639#endif // _LP641640#endif // !ZERO1641}16421643void Arguments::set_parallel_gc_flags() {1644assert(UseParallelGC || UseParallelOldGC, "Error");1645// Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).1646if (FLAG_IS_DEFAULT(UseParallelOldGC)) {1647FLAG_SET_DEFAULT(UseParallelOldGC, true);1648}1649FLAG_SET_DEFAULT(UseParallelGC, true);16501651// If no heap maximum was requested explicitly, use some reasonable fraction1652// of the physical memory, up to a maximum of 1GB.1653FLAG_SET_DEFAULT(ParallelGCThreads,1654Abstract_VM_Version::parallel_worker_threads());1655if (ParallelGCThreads == 0) {1656jio_fprintf(defaultStream::error_stream(),1657"The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");1658vm_exit(1);1659}16601661if (UseAdaptiveSizePolicy) {1662// We don't want to limit adaptive heap sizing's freedom to adjust the heap1663// unless the user actually sets these flags.1664if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {1665FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);1666_min_heap_free_ratio = MinHeapFreeRatio;1667}1668if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {1669FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);1670_max_heap_free_ratio = MaxHeapFreeRatio;1671}1672}16731674// If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the1675// SurvivorRatio has been set, reset their default values to SurvivorRatio +1676// 2. By doing this we make SurvivorRatio also work for Parallel Scavenger.1677// See CR 6362902 for details.1678if (!FLAG_IS_DEFAULT(SurvivorRatio)) {1679if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {1680FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);1681}1682if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {1683FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);1684}1685}16861687if (UseParallelOldGC) {1688// Par compact uses lower default values since they are treated as1689// minimums. These are different defaults because of the different1690// interpretation and are not ergonomically set.1691if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {1692FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);1693}1694}1695}16961697void Arguments::set_g1_gc_flags() {1698assert(UseG1GC, "Error");1699#ifdef COMPILER11700FastTLABRefill = false;1701#endif1702FLAG_SET_DEFAULT(ParallelGCThreads,1703Abstract_VM_Version::parallel_worker_threads());1704if (ParallelGCThreads == 0) {1705vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);1706}17071708#if INCLUDE_ALL_GCS1709if (G1ConcRefinementThreads == 0) {1710FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);1711}1712#endif17131714// MarkStackSize will be set (if it hasn't been set by the user)1715// when concurrent marking is initialized.1716// Its value will be based upon the number of parallel marking threads.1717// But we do set the maximum mark stack size here.1718if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {1719FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);1720}17211722if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {1723// In G1, we want the default GC overhead goal to be higher than1724// say in PS. So we set it here to 10%. Otherwise the heap might1725// be expanded more aggressively than we would like it to. In1726// fact, even 10% seems to not be high enough in some cases1727// (especially small GC stress tests that the main thing they do1728// is allocation). We might consider increase it further.1729FLAG_SET_DEFAULT(GCTimeRatio, 9);1730}17311732if (PrintGCDetails && Verbose) {1733tty->print_cr("MarkStackSize: %uk MarkStackSizeMax: %uk",1734(unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));1735tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);1736}1737}17381739void Arguments::set_shenandoah_gc_flags() {17401741#if !(defined AARCH64 || defined AMD64 || defined IA32)1742UNSUPPORTED_GC_OPTION(UseShenandoahGC);1743#endif17441745#if 0 // leave this block as stepping stone for future platforms1746warning("Shenandoah GC is not fully supported on this platform:");1747warning(" concurrent modes are not supported, only STW cycles are enabled;");1748warning(" arch-specific barrier code is not implemented, disabling barriers;");17491750#if INCLUDE_ALL_GCS1751FLAG_SET_DEFAULT(ShenandoahGCHeuristics, "passive");17521753FLAG_SET_DEFAULT(ShenandoahSATBBarrier, false);1754FLAG_SET_DEFAULT(ShenandoahLoadRefBarrier, false);1755FLAG_SET_DEFAULT(ShenandoahStoreValEnqueueBarrier, false);1756FLAG_SET_DEFAULT(ShenandoahCASBarrier, false);1757FLAG_SET_DEFAULT(ShenandoahCloneBarrier, false);17581759FLAG_SET_DEFAULT(ShenandoahVerifyOptoBarriers, false);1760#endif1761#endif17621763#if INCLUDE_ALL_GCS1764if (!FLAG_IS_DEFAULT(ShenandoahGarbageThreshold)) {1765if (0 > ShenandoahGarbageThreshold || ShenandoahGarbageThreshold > 100) {1766vm_exit_during_initialization("The flag -XX:ShenandoahGarbageThreshold is out of range", NULL);1767}1768}17691770if (!FLAG_IS_DEFAULT(ShenandoahAllocationThreshold)) {1771if (0 > ShenandoahAllocationThreshold || ShenandoahAllocationThreshold > 100) {1772vm_exit_during_initialization("The flag -XX:ShenandoahAllocationThreshold is out of range", NULL);1773}1774}17751776if (!FLAG_IS_DEFAULT(ShenandoahMinFreeThreshold)) {1777if (0 > ShenandoahMinFreeThreshold || ShenandoahMinFreeThreshold > 100) {1778vm_exit_during_initialization("The flag -XX:ShenandoahMinFreeThreshold is out of range", NULL);1779}1780}1781#endif17821783#if INCLUDE_ALL_GCS1784if (UseLargePages && (MaxHeapSize / os::large_page_size()) < ShenandoahHeapRegion::MIN_NUM_REGIONS) {1785warning("Large pages size (" SIZE_FORMAT "K) is too large to afford page-sized regions, disabling uncommit",1786os::large_page_size() / K);1787FLAG_SET_DEFAULT(ShenandoahUncommit, false);1788}1789#endif17901791// Enable NUMA by default. While Shenandoah is not NUMA-aware, enabling NUMA makes1792// storage allocation code NUMA-aware.1793if (FLAG_IS_DEFAULT(UseNUMA)) {1794FLAG_SET_DEFAULT(UseNUMA, true);1795}17961797// Set up default number of concurrent threads. We want to have cycles complete fast1798// enough, but we also do not want to steal too much CPU from the concurrently running1799// application. Using 1/4 of available threads for concurrent GC seems a good1800// compromise here.1801bool ergo_conc = FLAG_IS_DEFAULT(ConcGCThreads);1802if (ergo_conc) {1803FLAG_SET_DEFAULT(ConcGCThreads, MAX2(1, os::initial_active_processor_count() / 4));1804}18051806if (ConcGCThreads == 0) {1807vm_exit_during_initialization("Shenandoah expects ConcGCThreads > 0, check -XX:ConcGCThreads=#");1808}18091810// Set up default number of parallel threads. We want to have decent pauses performance1811// which would use parallel threads, but we also do not want to do too many threads1812// that will overwhelm the OS scheduler. Using 1/2 of available threads seems to be a fair1813// compromise here. Due to implementation constraints, it should not be lower than1814// the number of concurrent threads.1815bool ergo_parallel = FLAG_IS_DEFAULT(ParallelGCThreads);1816if (ergo_parallel) {1817FLAG_SET_DEFAULT(ParallelGCThreads, MAX2(1, os::initial_active_processor_count() / 2));1818}18191820if (ParallelGCThreads == 0) {1821vm_exit_during_initialization("Shenandoah expects ParallelGCThreads > 0, check -XX:ParallelGCThreads=#");1822}18231824// Make sure ergonomic decisions do not break the thread count invariants.1825// This may happen when user overrides one of the flags, but not the other.1826// When that happens, we want to adjust the setting that was set ergonomically.1827if (ParallelGCThreads < ConcGCThreads) {1828if (ergo_conc && !ergo_parallel) {1829FLAG_SET_DEFAULT(ConcGCThreads, ParallelGCThreads);1830} else if (!ergo_conc && ergo_parallel) {1831FLAG_SET_DEFAULT(ParallelGCThreads, ConcGCThreads);1832} else if (ergo_conc && ergo_parallel) {1833// Should not happen, check the ergonomic computation above. Fail with relevant error.1834vm_exit_during_initialization("Shenandoah thread count ergonomic error");1835} else {1836// User settings error, report and ask user to rectify.1837vm_exit_during_initialization("Shenandoah expects ConcGCThreads <= ParallelGCThreads, check -XX:ParallelGCThreads, -XX:ConcGCThreads");1838}1839}18401841if (FLAG_IS_DEFAULT(ParallelRefProcEnabled)) {1842FLAG_SET_DEFAULT(ParallelRefProcEnabled, true);1843}18441845#if INCLUDE_ALL_GCS1846if (ShenandoahRegionSampling && FLAG_IS_DEFAULT(PerfDataMemorySize)) {1847// When sampling is enabled, max out the PerfData memory to get more1848// Shenandoah data in, including Matrix.1849FLAG_SET_DEFAULT(PerfDataMemorySize, 2048*K);1850}1851#endif18521853#ifdef COMPILER21854// Shenandoah cares more about pause times, rather than raw throughput.1855// Enabling safepoints in counted loops makes it more responsive with1856// long loops. However, it is risky in 8u, due to bugs it brings, for1857// example JDK-8176506. Warn user about this, and proceed.1858if (UseCountedLoopSafepoints) {1859warning("Enabling -XX:UseCountedLoopSafepoints is known to cause JVM bugs. Use at your own risk.");1860}18611862#ifdef ASSERT1863// C2 barrier verification is only reliable when all default barriers are enabled1864if (ShenandoahVerifyOptoBarriers &&1865(!FLAG_IS_DEFAULT(ShenandoahSATBBarrier) ||1866!FLAG_IS_DEFAULT(ShenandoahLoadRefBarrier) ||1867!FLAG_IS_DEFAULT(ShenandoahStoreValEnqueueBarrier) ||1868!FLAG_IS_DEFAULT(ShenandoahCASBarrier) ||1869!FLAG_IS_DEFAULT(ShenandoahCloneBarrier)1870)) {1871warning("Unusual barrier configuration, disabling C2 barrier verification");1872FLAG_SET_DEFAULT(ShenandoahVerifyOptoBarriers, false);1873}1874#else1875guarantee(!ShenandoahVerifyOptoBarriers, "Should be disabled");1876#endif // ASSERT1877#endif // COMPILER218781879#if INCLUDE_ALL_GCS1880if ((InitialHeapSize == MaxHeapSize) && ShenandoahUncommit) {1881if (PrintGC) {1882tty->print_cr("Min heap equals to max heap, disabling ShenandoahUncommit");1883}1884FLAG_SET_DEFAULT(ShenandoahUncommit, false);1885}18861887// If class unloading is disabled, no unloading for concurrent cycles as well.1888if (!ClassUnloading) {1889FLAG_SET_DEFAULT(ClassUnloadingWithConcurrentMark, false);1890}18911892// TLAB sizing policy makes resizing decisions before each GC cycle. It averages1893// historical data, assigning more recent data the weight according to TLABAllocationWeight.1894// Current default is good for generational collectors that run frequent young GCs.1895// With Shenandoah, GC cycles are much less frequent, so we need we need sizing policy1896// to converge faster over smaller number of resizing decisions.1897if (FLAG_IS_DEFAULT(TLABAllocationWeight)) {1898FLAG_SET_DEFAULT(TLABAllocationWeight, 90);1899}19001901if (FLAG_IS_DEFAULT(ShenandoahSoftMaxHeapSize)) {1902FLAG_SET_DEFAULT(ShenandoahSoftMaxHeapSize, MaxHeapSize);1903} else {1904if (ShenandoahSoftMaxHeapSize > MaxHeapSize) {1905vm_exit_during_initialization("ShenandoahSoftMaxHeapSize must be less than or equal to the maximum heap size\n");1906}1907}1908#endif1909}19101911#if !INCLUDE_ALL_GCS1912#ifdef ASSERT1913static bool verify_serial_gc_flags() {1914return (UseSerialGC &&1915!(UseParNewGC || (UseConcMarkSweepGC || CMSIncrementalMode) || UseG1GC ||1916UseParallelGC || UseParallelOldGC));1917}1918#endif // ASSERT1919#endif // INCLUDE_ALL_GCS19201921void Arguments::set_gc_specific_flags() {1922#if INCLUDE_ALL_GCS1923// Set per-collector flags1924if (UseParallelGC || UseParallelOldGC) {1925set_parallel_gc_flags();1926} else if (UseConcMarkSweepGC) { // Should be done before ParNew check below1927set_cms_and_parnew_gc_flags();1928} else if (UseParNewGC) { // Skipped if CMS is set above1929set_parnew_gc_flags();1930} else if (UseG1GC) {1931set_g1_gc_flags();1932} else if (UseShenandoahGC) {1933set_shenandoah_gc_flags();1934}1935check_deprecated_gcs();1936check_deprecated_gc_flags();1937if (AssumeMP && !UseSerialGC) {1938if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {1939warning("If the number of processors is expected to increase from one, then"1940" you should configure the number of parallel GC threads appropriately"1941" using -XX:ParallelGCThreads=N");1942}1943}1944if (MinHeapFreeRatio == 100) {1945// Keeping the heap 100% free is hard ;-) so limit it to 99%.1946FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);1947}19481949// If class unloading is disabled, also disable concurrent class unloading.1950if (!ClassUnloading) {1951FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);1952FLAG_SET_CMDLINE(bool, ClassUnloadingWithConcurrentMark, false);1953FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);1954FLAG_SET_CMDLINE(uintx, ShenandoahUnloadClassesFrequency, 0);1955}1956#else // INCLUDE_ALL_GCS1957assert(verify_serial_gc_flags(), "SerialGC unset");1958#endif // INCLUDE_ALL_GCS1959}19601961julong Arguments::limit_by_allocatable_memory(julong limit) {1962julong max_allocatable;1963julong result = limit;1964if (os::has_allocatable_memory_limit(&max_allocatable)) {1965result = MIN2(result, max_allocatable / MaxVirtMemFraction);1966}1967return result;1968}19691970void Arguments::set_heap_size() {1971if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {1972// Deprecated flag1973FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);1974}19751976julong phys_mem =1977FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)1978: (julong)MaxRAM;19791980// Experimental support for CGroup memory limits1981if (UseCGroupMemoryLimitForHeap) {1982// This is a rough indicator that a CGroup limit may be in force1983// for this process1984const char* lim_file = "/sys/fs/cgroup/memory/memory.limit_in_bytes";1985FILE *fp = fopen(lim_file, "r");1986if (fp != NULL) {1987julong cgroup_max = 0;1988int ret = fscanf(fp, JULONG_FORMAT, &cgroup_max);1989if (ret == 1 && cgroup_max > 0) {1990// If unlimited, cgroup_max will be a very large, but unspecified1991// value, so use initial phys_mem as a limit1992if (PrintGCDetails && Verbose) {1993// Cannot use gclog_or_tty yet.1994tty->print_cr("Setting phys_mem to the min of cgroup limit ("1995JULONG_FORMAT "MB) and initial phys_mem ("1996JULONG_FORMAT "MB)", cgroup_max/M, phys_mem/M);1997}1998phys_mem = MIN2(cgroup_max, phys_mem);1999} else {2000warning("Unable to read/parse cgroup memory limit from %s: %s",2001lim_file, errno != 0 ? strerror(errno) : "unknown error");2002}2003fclose(fp);2004} else {2005warning("Unable to open cgroup memory limit file %s (%s)", lim_file, strerror(errno));2006}2007}20082009// Convert Fraction to Precentage values2010if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&2011!FLAG_IS_DEFAULT(MaxRAMFraction))2012MaxRAMPercentage = 100.0 / MaxRAMFraction;20132014if (FLAG_IS_DEFAULT(MinRAMPercentage) &&2015!FLAG_IS_DEFAULT(MinRAMFraction))2016MinRAMPercentage = 100.0 / MinRAMFraction;20172018if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&2019!FLAG_IS_DEFAULT(InitialRAMFraction))2020InitialRAMPercentage = 100.0 / InitialRAMFraction;20212022// If the maximum heap size has not been set with -Xmx,2023// then set it as fraction of the size of physical memory,2024// respecting the maximum and minimum sizes of the heap.2025if (FLAG_IS_DEFAULT(MaxHeapSize)) {2026julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);2027const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);2028if (reasonable_min < MaxHeapSize) {2029// Small physical memory, so use a minimum fraction of it for the heap2030reasonable_max = reasonable_min;2031} else {2032// Not-small physical memory, so require a heap at least2033// as large as MaxHeapSize2034reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);2035}20362037if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {2038// Limit the heap size to ErgoHeapSizeLimit2039reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);2040}2041if (UseCompressedOops) {2042// Limit the heap size to the maximum possible when using compressed oops2043julong max_coop_heap = (julong)max_heap_for_compressed_oops();2044if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {2045// Heap should be above HeapBaseMinAddress to get zero based compressed oops2046// but it should be not less than default MaxHeapSize.2047max_coop_heap -= HeapBaseMinAddress;2048}2049reasonable_max = MIN2(reasonable_max, max_coop_heap);2050}2051reasonable_max = limit_by_allocatable_memory(reasonable_max);20522053if (!FLAG_IS_DEFAULT(InitialHeapSize)) {2054// An initial heap size was specified on the command line,2055// so be sure that the maximum size is consistent. Done2056// after call to limit_by_allocatable_memory because that2057// method might reduce the allocation size.2058reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);2059}20602061if (PrintGCDetails && Verbose) {2062// Cannot use gclog_or_tty yet.2063tty->print_cr(" Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);2064}2065FLAG_SET_ERGO(uintx, MaxHeapSize, (uintx)reasonable_max);2066}20672068// If the minimum or initial heap_size have not been set or requested to be set2069// ergonomically, set them accordingly.2070if (InitialHeapSize == 0 || min_heap_size() == 0) {2071julong reasonable_minimum = (julong)(OldSize + NewSize);20722073reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);20742075reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);20762077if (InitialHeapSize == 0) {2078julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);20792080reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());2081reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);20822083reasonable_initial = limit_by_allocatable_memory(reasonable_initial);20842085if (PrintGCDetails && Verbose) {2086// Cannot use gclog_or_tty yet.2087tty->print_cr(" Initial heap size " SIZE_FORMAT, (uintx)reasonable_initial);2088}2089FLAG_SET_ERGO(uintx, InitialHeapSize, (uintx)reasonable_initial);2090}2091// If the minimum heap size has not been set (via -Xms),2092// synchronize with InitialHeapSize to avoid errors with the default value.2093if (min_heap_size() == 0) {2094set_min_heap_size(MIN2((uintx)reasonable_minimum, InitialHeapSize));2095if (PrintGCDetails && Verbose) {2096// Cannot use gclog_or_tty yet.2097tty->print_cr(" Minimum heap size " SIZE_FORMAT, min_heap_size());2098}2099}2100}2101}21022103// This option inspects the machine and attempts to set various2104// parameters to be optimal for long-running, memory allocation2105// intensive jobs. It is intended for machines with large2106// amounts of cpu and memory.2107jint Arguments::set_aggressive_heap_flags() {2108// initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit2109// VM, but we may not be able to represent the total physical memory2110// available (like having 8gb of memory on a box but using a 32bit VM).2111// Thus, we need to make sure we're using a julong for intermediate2112// calculations.2113julong initHeapSize;2114julong total_memory = os::physical_memory();21152116if (total_memory < (julong) 256 * M) {2117jio_fprintf(defaultStream::error_stream(),2118"You need at least 256mb of memory to use -XX:+AggressiveHeap\n");2119vm_exit(1);2120}21212122// The heap size is half of available memory, or (at most)2123// all of possible memory less 160mb (leaving room for the OS2124// when using ISM). This is the maximum; because adaptive sizing2125// is turned on below, the actual space used may be smaller.21262127initHeapSize = MIN2(total_memory / (julong) 2,2128total_memory - (julong) 160 * M);21292130initHeapSize = limit_by_allocatable_memory(initHeapSize);21312132if (FLAG_IS_DEFAULT(MaxHeapSize)) {2133FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);2134FLAG_SET_CMDLINE(uintx, InitialHeapSize, initHeapSize);2135// Currently the minimum size and the initial heap sizes are the same.2136set_min_heap_size(initHeapSize);2137}2138if (FLAG_IS_DEFAULT(NewSize)) {2139// Make the young generation 3/8ths of the total heap.2140FLAG_SET_CMDLINE(uintx, NewSize,2141((julong) MaxHeapSize / (julong) 8) * (julong) 3);2142FLAG_SET_CMDLINE(uintx, MaxNewSize, NewSize);2143}21442145#ifndef _ALLBSD_SOURCE // UseLargePages is not yet supported on BSD.2146FLAG_SET_DEFAULT(UseLargePages, true);2147#endif21482149// Increase some data structure sizes for efficiency2150FLAG_SET_CMDLINE(uintx, BaseFootPrintEstimate, MaxHeapSize);2151FLAG_SET_CMDLINE(bool, ResizeTLAB, false);2152FLAG_SET_CMDLINE(uintx, TLABSize, 256 * K);21532154// See the OldPLABSize comment below, but replace 'after promotion'2155// with 'after copying'. YoungPLABSize is the size of the survivor2156// space per-gc-thread buffers. The default is 4kw.2157FLAG_SET_CMDLINE(uintx, YoungPLABSize, 256 * K); // Note: this is in words21582159// OldPLABSize is the size of the buffers in the old gen that2160// UseParallelGC uses to promote live data that doesn't fit in the2161// survivor spaces. At any given time, there's one for each gc thread.2162// The default size is 1kw. These buffers are rarely used, since the2163// survivor spaces are usually big enough. For specjbb, however, there2164// are occasions when there's lots of live data in the young gen2165// and we end up promoting some of it. We don't have a definite2166// explanation for why bumping OldPLABSize helps, but the theory2167// is that a bigger PLAB results in retaining something like the2168// original allocation order after promotion, which improves mutator2169// locality. A minor effect may be that larger PLABs reduce the2170// number of PLAB allocation events during gc. The value of 8kw2171// was arrived at by experimenting with specjbb.2172FLAG_SET_CMDLINE(uintx, OldPLABSize, 8 * K); // Note: this is in words21732174// Enable parallel GC and adaptive generation sizing2175FLAG_SET_CMDLINE(bool, UseParallelGC, true);21762177// Encourage steady state memory management2178FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);21792180// This appears to improve mutator locality2181FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);21822183// Get around early Solaris scheduling bug2184// (affinity vs other jobs on system)2185// but disallow DR and offlining (5008695).2186FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);21872188return JNI_OK;2189}21902191// This must be called after ergonomics because we want bytecode rewriting2192// if the server compiler is used, or if UseSharedSpaces is disabled.2193void Arguments::set_bytecode_flags() {2194// Better not attempt to store into a read-only space.2195if (UseSharedSpaces) {2196FLAG_SET_DEFAULT(RewriteBytecodes, false);2197FLAG_SET_DEFAULT(RewriteFrequentPairs, false);2198}21992200if (!RewriteBytecodes) {2201FLAG_SET_DEFAULT(RewriteFrequentPairs, false);2202}2203}22042205// Aggressive optimization flags -XX:+AggressiveOpts2206void Arguments::set_aggressive_opts_flags() {2207#ifdef COMPILER22208if (AggressiveUnboxing) {2209if (FLAG_IS_DEFAULT(EliminateAutoBox)) {2210FLAG_SET_DEFAULT(EliminateAutoBox, true);2211} else if (!EliminateAutoBox) {2212// warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");2213AggressiveUnboxing = false;2214}2215if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {2216FLAG_SET_DEFAULT(DoEscapeAnalysis, true);2217} else if (!DoEscapeAnalysis) {2218// warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");2219AggressiveUnboxing = false;2220}2221}2222if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {2223if (FLAG_IS_DEFAULT(EliminateAutoBox)) {2224FLAG_SET_DEFAULT(EliminateAutoBox, true);2225}2226if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {2227FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);2228}22292230// Feed the cache size setting into the JDK2231char buffer[1024];2232jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);2233add_property(buffer);2234}2235if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {2236FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);2237}2238#endif22392240if (AggressiveOpts) {2241// Sample flag setting code2242// if (FLAG_IS_DEFAULT(EliminateZeroing)) {2243// FLAG_SET_DEFAULT(EliminateZeroing, true);2244// }2245}2246}22472248//===========================================================================================================2249// Parsing of java.compiler property22502251void Arguments::process_java_compiler_argument(char* arg) {2252// For backwards compatibility, Djava.compiler=NONE or ""2253// causes us to switch to -Xint mode UNLESS -Xdebug2254// is also specified.2255if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {2256set_java_compiler(true); // "-Djava.compiler[=...]" most recently seen.2257}2258}22592260void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {2261_sun_java_launcher = strdup(launcher);2262if (strcmp("gamma", _sun_java_launcher) == 0) {2263_created_by_gamma_launcher = true;2264}2265}22662267bool Arguments::created_by_java_launcher() {2268assert(_sun_java_launcher != NULL, "property must have value");2269return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;2270}22712272bool Arguments::created_by_gamma_launcher() {2273return _created_by_gamma_launcher;2274}22752276//===========================================================================================================2277// Parsing of main arguments22782279bool Arguments::verify_interval(uintx val, uintx min,2280uintx max, const char* name) {2281// Returns true iff value is in the inclusive interval [min..max]2282// false, otherwise.2283if (val >= min && val <= max) {2284return true;2285}2286jio_fprintf(defaultStream::error_stream(),2287"%s of " UINTX_FORMAT " is invalid; must be between " UINTX_FORMAT2288" and " UINTX_FORMAT "\n",2289name, val, min, max);2290return false;2291}22922293bool Arguments::verify_min_value(intx val, intx min, const char* name) {2294// Returns true if given value is at least specified min threshold2295// false, otherwise.2296if (val >= min ) {2297return true;2298}2299jio_fprintf(defaultStream::error_stream(),2300"%s of " INTX_FORMAT " is invalid; must be at least " INTX_FORMAT "\n",2301name, val, min);2302return false;2303}23042305bool Arguments::verify_percentage(uintx value, const char* name) {2306if (is_percentage(value)) {2307return true;2308}2309jio_fprintf(defaultStream::error_stream(),2310"%s of " UINTX_FORMAT " is invalid; must be between 0 and 100\n",2311name, value);2312return false;2313}23142315// check if do gclog rotation2316// +UseGCLogFileRotation is a must,2317// no gc log rotation when log file not supplied or2318// NumberOfGCLogFiles is 02319void check_gclog_consistency() {2320if (UseGCLogFileRotation) {2321if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {2322jio_fprintf(defaultStream::output_stream(),2323"To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"2324"where num_of_file > 0\n"2325"GC log rotation is turned off\n");2326UseGCLogFileRotation = false;2327}2328}23292330if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {2331FLAG_SET_CMDLINE(uintx, GCLogFileSize, 8*K);2332jio_fprintf(defaultStream::output_stream(),2333"GCLogFileSize changed to minimum 8K\n");2334}23352336// Record more information about previous cycles for improved debugging pleasure2337if (FLAG_IS_DEFAULT(LogEventsBufferEntries)) {2338FLAG_SET_DEFAULT(LogEventsBufferEntries, 250);2339}2340}23412342// This function is called for -Xloggc:<filename>, it can be used2343// to check if a given file name(or string) conforms to the following2344// specification:2345// A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"2346// %p and %t only allowed once. We only limit usage of filename not path2347bool is_filename_valid(const char *file_name) {2348const char* p = file_name;2349char file_sep = os::file_separator()[0];2350const char* cp;2351// skip prefix path2352for (cp = file_name; *cp != '\0'; cp++) {2353if (*cp == '/' || *cp == file_sep) {2354p = cp + 1;2355}2356}23572358int count_p = 0;2359int count_t = 0;2360while (*p != '\0') {2361if ((*p >= '0' && *p <= '9') ||2362(*p >= 'A' && *p <= 'Z') ||2363(*p >= 'a' && *p <= 'z') ||2364*p == '-' ||2365*p == '_' ||2366*p == '.') {2367p++;2368continue;2369}2370if (*p == '%') {2371if(*(p + 1) == 'p') {2372p += 2;2373count_p ++;2374continue;2375}2376if (*(p + 1) == 't') {2377p += 2;2378count_t ++;2379continue;2380}2381}2382return false;2383}2384return count_p < 2 && count_t < 2;2385}23862387bool Arguments::verify_MinHeapFreeRatio(FormatBuffer<80>& err_msg, uintx min_heap_free_ratio) {2388if (!is_percentage(min_heap_free_ratio)) {2389err_msg.print("MinHeapFreeRatio must have a value between 0 and 100");2390return false;2391}2392if (min_heap_free_ratio > MaxHeapFreeRatio) {2393err_msg.print("MinHeapFreeRatio (" UINTX_FORMAT ") must be less than or "2394"equal to MaxHeapFreeRatio (" UINTX_FORMAT ")", min_heap_free_ratio,2395MaxHeapFreeRatio);2396return false;2397}2398// This does not set the flag itself, but stores the value in a safe place for later usage.2399_min_heap_free_ratio = min_heap_free_ratio;2400return true;2401}24022403bool Arguments::verify_MaxHeapFreeRatio(FormatBuffer<80>& err_msg, uintx max_heap_free_ratio) {2404if (!is_percentage(max_heap_free_ratio)) {2405err_msg.print("MaxHeapFreeRatio must have a value between 0 and 100");2406return false;2407}2408if (max_heap_free_ratio < MinHeapFreeRatio) {2409err_msg.print("MaxHeapFreeRatio (" UINTX_FORMAT ") must be greater than or "2410"equal to MinHeapFreeRatio (" UINTX_FORMAT ")", max_heap_free_ratio,2411MinHeapFreeRatio);2412return false;2413}2414// This does not set the flag itself, but stores the value in a safe place for later usage.2415_max_heap_free_ratio = max_heap_free_ratio;2416return true;2417}24182419// Check consistency of GC selection2420bool Arguments::check_gc_consistency() {2421check_gclog_consistency();2422bool status = true;2423// Ensure that the user has not selected conflicting sets2424// of collectors. [Note: this check is merely a user convenience;2425// collectors over-ride each other so that only a non-conflicting2426// set is selected; however what the user gets is not what they2427// may have expected from the combination they asked for. It's2428// better to reduce user confusion by not allowing them to2429// select conflicting combinations.2430uint i = 0;2431if (UseSerialGC) i++;2432if (UseConcMarkSweepGC || UseParNewGC) i++;2433if (UseParallelGC || UseParallelOldGC) i++;2434if (UseG1GC) i++;2435if (UseShenandoahGC) i++;2436if (i > 1) {2437jio_fprintf(defaultStream::error_stream(),2438"Conflicting collector combinations in option list; "2439"please refer to the release notes for the combinations "2440"allowed\n");2441status = false;2442}2443return status;2444}24452446void Arguments::check_deprecated_gcs() {2447if (UseConcMarkSweepGC && !UseParNewGC) {2448warning("Using the DefNew young collector with the CMS collector is deprecated "2449"and will likely be removed in a future release");2450}24512452if (UseParNewGC && !UseConcMarkSweepGC) {2453// !UseConcMarkSweepGC means that we are using serial old gc. Unfortunately we don't2454// set up UseSerialGC properly, so that can't be used in the check here.2455warning("Using the ParNew young collector with the Serial old collector is deprecated "2456"and will likely be removed in a future release");2457}24582459if (CMSIncrementalMode) {2460warning("Using incremental CMS is deprecated and will likely be removed in a future release");2461}2462}24632464void Arguments::check_deprecated_gc_flags() {2465if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {2466warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"2467"and will likely be removed in future release");2468}2469if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {2470warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "2471"Use MaxRAMFraction instead.");2472}2473if (FLAG_IS_CMDLINE(UseCMSCompactAtFullCollection)) {2474warning("UseCMSCompactAtFullCollection is deprecated and will likely be removed in a future release.");2475}2476if (FLAG_IS_CMDLINE(CMSFullGCsBeforeCompaction)) {2477warning("CMSFullGCsBeforeCompaction is deprecated and will likely be removed in a future release.");2478}2479if (FLAG_IS_CMDLINE(UseCMSCollectionPassing)) {2480warning("UseCMSCollectionPassing is deprecated and will likely be removed in a future release.");2481}2482}24832484// Check stack pages settings2485bool Arguments::check_stack_pages()2486{2487bool status = true;2488status = status && verify_min_value(StackYellowPages, 1, "StackYellowPages");2489status = status && verify_min_value(StackRedPages, 1, "StackRedPages");2490// greater stack shadow pages can't generate instruction to bang stack2491status = status && verify_interval(StackShadowPages, 1, 50, "StackShadowPages");2492return status;2493}24942495// Check the consistency of vm_init_args2496bool Arguments::check_vm_args_consistency() {2497// Method for adding checks for flag consistency.2498// The intent is to warn the user of all possible conflicts,2499// before returning an error.2500// Note: Needs platform-dependent factoring.2501bool status = true;25022503// Allow both -XX:-UseStackBanging and -XX:-UseBoundThreads in non-product2504// builds so the cost of stack banging can be measured.2505#if (defined(PRODUCT) && defined(SOLARIS))2506if (!UseBoundThreads && !UseStackBanging) {2507jio_fprintf(defaultStream::error_stream(),2508"-UseStackBanging conflicts with -UseBoundThreads\n");25092510status = false;2511}2512#endif25132514if (TLABRefillWasteFraction == 0) {2515jio_fprintf(defaultStream::error_stream(),2516"TLABRefillWasteFraction should be a denominator, "2517"not " SIZE_FORMAT "\n",2518TLABRefillWasteFraction);2519status = false;2520}25212522status = status && verify_interval(AdaptiveSizePolicyWeight, 0, 100,2523"AdaptiveSizePolicyWeight");2524status = status && verify_percentage(ThresholdTolerance, "ThresholdTolerance");25252526// Divide by bucket size to prevent a large size from causing rollover when2527// calculating amount of memory needed to be allocated for the String table.2528status = status && verify_interval(StringTableSize, minimumStringTableSize,2529(max_uintx / StringTable::bucket_size()), "StringTable size");25302531status = status && verify_interval(SymbolTableSize, minimumSymbolTableSize,2532(max_uintx / SymbolTable::bucket_size()), "SymbolTable size");25332534{2535// Using "else if" below to avoid printing two error messages if min > max.2536// This will also prevent us from reporting both min>100 and max>100 at the2537// same time, but that is less annoying than printing two identical errors IMHO.2538FormatBuffer<80> err_msg("%s","");2539if (!verify_MinHeapFreeRatio(err_msg, MinHeapFreeRatio)) {2540jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());2541status = false;2542} else if (!verify_MaxHeapFreeRatio(err_msg, MaxHeapFreeRatio)) {2543jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());2544status = false;2545}2546}25472548// Min/MaxMetaspaceFreeRatio2549status = status && verify_percentage(MinMetaspaceFreeRatio, "MinMetaspaceFreeRatio");2550status = status && verify_percentage(MaxMetaspaceFreeRatio, "MaxMetaspaceFreeRatio");25512552if (MinMetaspaceFreeRatio > MaxMetaspaceFreeRatio) {2553jio_fprintf(defaultStream::error_stream(),2554"MinMetaspaceFreeRatio (%s" UINTX_FORMAT ") must be less than or "2555"equal to MaxMetaspaceFreeRatio (%s" UINTX_FORMAT ")\n",2556FLAG_IS_DEFAULT(MinMetaspaceFreeRatio) ? "Default: " : "",2557MinMetaspaceFreeRatio,2558FLAG_IS_DEFAULT(MaxMetaspaceFreeRatio) ? "Default: " : "",2559MaxMetaspaceFreeRatio);2560status = false;2561}25622563// Trying to keep 100% free is not practical2564MinMetaspaceFreeRatio = MIN2(MinMetaspaceFreeRatio, (uintx) 99);25652566if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {2567MarkSweepAlwaysCompactCount = 1; // Move objects every gc.2568}25692570if (UseParallelOldGC && ParallelOldGCSplitALot) {2571// Settings to encourage splitting.2572if (!FLAG_IS_CMDLINE(NewRatio)) {2573FLAG_SET_CMDLINE(uintx, NewRatio, 2);2574}2575if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {2576FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);2577}2578}25792580status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit");2581status = status && verify_percentage(GCTimeLimit, "GCTimeLimit");2582if (GCTimeLimit == 100) {2583// Turn off gc-overhead-limit-exceeded checks2584FLAG_SET_DEFAULT(UseGCOverheadLimit, false);2585}25862587status = status && check_gc_consistency();2588status = status && check_stack_pages();25892590if (CMSIncrementalMode) {2591if (!UseConcMarkSweepGC) {2592jio_fprintf(defaultStream::error_stream(),2593"error: invalid argument combination.\n"2594"The CMS collector (-XX:+UseConcMarkSweepGC) must be "2595"selected in order\nto use CMSIncrementalMode.\n");2596status = false;2597} else {2598status = status && verify_percentage(CMSIncrementalDutyCycle,2599"CMSIncrementalDutyCycle");2600status = status && verify_percentage(CMSIncrementalDutyCycleMin,2601"CMSIncrementalDutyCycleMin");2602status = status && verify_percentage(CMSIncrementalSafetyFactor,2603"CMSIncrementalSafetyFactor");2604status = status && verify_percentage(CMSIncrementalOffset,2605"CMSIncrementalOffset");2606status = status && verify_percentage(CMSExpAvgFactor,2607"CMSExpAvgFactor");2608// If it was not set on the command line, set2609// CMSInitiatingOccupancyFraction to 1 so icms can initiate cycles early.2610if (CMSInitiatingOccupancyFraction < 0) {2611FLAG_SET_DEFAULT(CMSInitiatingOccupancyFraction, 1);2612}2613}2614}26152616// CMS space iteration, which FLSVerifyAllHeapreferences entails,2617// insists that we hold the requisite locks so that the iteration is2618// MT-safe. For the verification at start-up and shut-down, we don't2619// yet have a good way of acquiring and releasing these locks,2620// which are not visible at the CollectedHeap level. We want to2621// be able to acquire these locks and then do the iteration rather2622// than just disable the lock verification. This will be fixed under2623// bug 4788986.2624if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {2625if (VerifyDuringStartup) {2626warning("Heap verification at start-up disabled "2627"(due to current incompatibility with FLSVerifyAllHeapReferences)");2628VerifyDuringStartup = false; // Disable verification at start-up2629}26302631if (VerifyBeforeExit) {2632warning("Heap verification at shutdown disabled "2633"(due to current incompatibility with FLSVerifyAllHeapReferences)");2634VerifyBeforeExit = false; // Disable verification at shutdown2635}2636}26372638// Note: only executed in non-PRODUCT mode2639if (!UseAsyncConcMarkSweepGC &&2640(ExplicitGCInvokesConcurrent ||2641ExplicitGCInvokesConcurrentAndUnloadsClasses)) {2642jio_fprintf(defaultStream::error_stream(),2643"error: +ExplicitGCInvokesConcurrent[AndUnloadsClasses] conflicts"2644" with -UseAsyncConcMarkSweepGC");2645status = false;2646}26472648status = status && verify_min_value(ParGCArrayScanChunk, 1, "ParGCArrayScanChunk");26492650#if INCLUDE_ALL_GCS2651if (UseG1GC) {2652status = status && verify_percentage(G1NewSizePercent, "G1NewSizePercent");2653status = status && verify_percentage(G1MaxNewSizePercent, "G1MaxNewSizePercent");2654status = status && verify_interval(G1NewSizePercent, 0, G1MaxNewSizePercent, "G1NewSizePercent");26552656status = status && verify_percentage(InitiatingHeapOccupancyPercent,2657"InitiatingHeapOccupancyPercent");2658status = status && verify_min_value(G1RefProcDrainInterval, 1,2659"G1RefProcDrainInterval");2660status = status && verify_min_value((intx)G1ConcMarkStepDurationMillis, 1,2661"G1ConcMarkStepDurationMillis");2662status = status && verify_interval(G1ConcRSHotCardLimit, 0, max_jubyte,2663"G1ConcRSHotCardLimit");2664status = status && verify_interval(G1ConcRSLogCacheSize, 0, 27,2665"G1ConcRSLogCacheSize");2666status = status && verify_interval(StringDeduplicationAgeThreshold, 1, markOopDesc::max_age,2667"StringDeduplicationAgeThreshold");2668}2669if (UseConcMarkSweepGC) {2670status = status && verify_min_value(CMSOldPLABNumRefills, 1, "CMSOldPLABNumRefills");2671status = status && verify_min_value(CMSOldPLABToleranceFactor, 1, "CMSOldPLABToleranceFactor");2672status = status && verify_min_value(CMSOldPLABMax, 1, "CMSOldPLABMax");2673status = status && verify_interval(CMSOldPLABMin, 1, CMSOldPLABMax, "CMSOldPLABMin");26742675status = status && verify_min_value(CMSYoungGenPerWorker, 1, "CMSYoungGenPerWorker");26762677status = status && verify_min_value(CMSSamplingGrain, 1, "CMSSamplingGrain");2678status = status && verify_interval(CMS_SweepWeight, 0, 100, "CMS_SweepWeight");2679status = status && verify_interval(CMS_FLSWeight, 0, 100, "CMS_FLSWeight");26802681status = status && verify_interval(FLSCoalescePolicy, 0, 4, "FLSCoalescePolicy");26822683status = status && verify_min_value(CMSRescanMultiple, 1, "CMSRescanMultiple");2684status = status && verify_min_value(CMSConcMarkMultiple, 1, "CMSConcMarkMultiple");26852686status = status && verify_interval(CMSPrecleanIter, 0, 9, "CMSPrecleanIter");2687status = status && verify_min_value(CMSPrecleanDenominator, 1, "CMSPrecleanDenominator");2688status = status && verify_interval(CMSPrecleanNumerator, 0, CMSPrecleanDenominator - 1, "CMSPrecleanNumerator");26892690status = status && verify_percentage(CMSBootstrapOccupancy, "CMSBootstrapOccupancy");26912692status = status && verify_min_value(CMSPrecleanThreshold, 100, "CMSPrecleanThreshold");26932694status = status && verify_percentage(CMSScheduleRemarkEdenPenetration, "CMSScheduleRemarkEdenPenetration");2695status = status && verify_min_value(CMSScheduleRemarkSamplingRatio, 1, "CMSScheduleRemarkSamplingRatio");2696status = status && verify_min_value(CMSBitMapYieldQuantum, 1, "CMSBitMapYieldQuantum");2697status = status && verify_percentage(CMSTriggerRatio, "CMSTriggerRatio");2698status = status && verify_percentage(CMSIsTooFullPercentage, "CMSIsTooFullPercentage");2699}27002701if (UseParallelGC || UseParallelOldGC) {2702status = status && verify_interval(ParallelOldDeadWoodLimiterMean, 0, 100, "ParallelOldDeadWoodLimiterMean");2703status = status && verify_interval(ParallelOldDeadWoodLimiterStdDev, 0, 100, "ParallelOldDeadWoodLimiterStdDev");27042705status = status && verify_percentage(YoungGenerationSizeIncrement, "YoungGenerationSizeIncrement");2706status = status && verify_percentage(TenuredGenerationSizeIncrement, "TenuredGenerationSizeIncrement");27072708status = status && verify_min_value(YoungGenerationSizeSupplementDecay, 1, "YoungGenerationSizeSupplementDecay");2709status = status && verify_min_value(TenuredGenerationSizeSupplementDecay, 1, "TenuredGenerationSizeSupplementDecay");27102711status = status && verify_min_value(ParGCCardsPerStrideChunk, 1, "ParGCCardsPerStrideChunk");27122713status = status && verify_min_value(ParallelOldGCSplitInterval, 0, "ParallelOldGCSplitInterval");2714}2715#endif // INCLUDE_ALL_GCS27162717status = status && verify_interval(RefDiscoveryPolicy,2718ReferenceProcessor::DiscoveryPolicyMin,2719ReferenceProcessor::DiscoveryPolicyMax,2720"RefDiscoveryPolicy");27212722// Limit the lower bound of this flag to 1 as it is used in a division2723// expression.2724status = status && verify_interval(TLABWasteTargetPercent,27251, 100, "TLABWasteTargetPercent");27262727status = status && verify_object_alignment();27282729status = status && verify_interval(CompressedClassSpaceSize, 1*M, 3*G,2730"CompressedClassSpaceSize");27312732status = status && verify_interval(MarkStackSizeMax,27331, (max_jint - 1), "MarkStackSizeMax");2734status = status && verify_interval(NUMAChunkResizeWeight, 0, 100, "NUMAChunkResizeWeight");27352736status = status && verify_min_value(LogEventsBufferEntries, 1, "LogEventsBufferEntries");27372738status = status && verify_min_value(HeapSizePerGCThread, (uintx) os::vm_page_size(), "HeapSizePerGCThread");27392740status = status && verify_min_value(GCTaskTimeStampEntries, 1, "GCTaskTimeStampEntries");27412742status = status && verify_percentage(ParallelGCBufferWastePct, "ParallelGCBufferWastePct");2743status = status && verify_interval(TargetPLABWastePct, 1, 100, "TargetPLABWastePct");27442745status = status && verify_min_value(ParGCStridesPerThread, 1, "ParGCStridesPerThread");27462747status = status && verify_min_value(MinRAMFraction, 1, "MinRAMFraction");2748status = status && verify_min_value(InitialRAMFraction, 1, "InitialRAMFraction");2749status = status && verify_min_value(MaxRAMFraction, 1, "MaxRAMFraction");2750status = status && verify_min_value(DefaultMaxRAMFraction, 1, "DefaultMaxRAMFraction");27512752status = status && verify_interval(AdaptiveTimeWeight, 0, 100, "AdaptiveTimeWeight");2753status = status && verify_min_value(AdaptiveSizeDecrementScaleFactor, 1, "AdaptiveSizeDecrementScaleFactor");27542755status = status && verify_interval(TLABAllocationWeight, 0, 100, "TLABAllocationWeight");2756status = status && verify_min_value(MinTLABSize, 1, "MinTLABSize");2757status = status && verify_min_value(TLABRefillWasteFraction, 1, "TLABRefillWasteFraction");27582759status = status && verify_percentage(YoungGenerationSizeSupplement, "YoungGenerationSizeSupplement");2760status = status && verify_percentage(TenuredGenerationSizeSupplement, "TenuredGenerationSizeSupplement");27612762// the "age" field in the oop header is 4 bits; do not want to pull in markOop.hpp2763// just for that, so hardcode here.2764status = status && verify_interval(MaxTenuringThreshold, 0, 15, "MaxTenuringThreshold");2765status = status && verify_interval(InitialTenuringThreshold, 0, MaxTenuringThreshold, "MaxTenuringThreshold");2766status = status && verify_percentage(TargetSurvivorRatio, "TargetSurvivorRatio");2767status = status && verify_percentage(MarkSweepDeadRatio, "MarkSweepDeadRatio");27682769status = status && verify_min_value(MarkSweepAlwaysCompactCount, 1, "MarkSweepAlwaysCompactCount");2770#ifdef COMPILER12771status = status && verify_min_value(ValueMapInitialSize, 1, "ValueMapInitialSize");2772#endif27732774if (PrintNMTStatistics) {2775#if INCLUDE_NMT2776if (MemTracker::tracking_level() == NMT_off) {2777#endif // INCLUDE_NMT2778warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");2779PrintNMTStatistics = false;2780#if INCLUDE_NMT2781}2782#endif2783}27842785// Need to limit the extent of the padding to reasonable size.2786// 8K is well beyond the reasonable HW cache line size, even with the2787// aggressive prefetching, while still leaving the room for segregating2788// among the distinct pages.2789if (ContendedPaddingWidth < 0 || ContendedPaddingWidth > 8192) {2790jio_fprintf(defaultStream::error_stream(),2791"ContendedPaddingWidth=" INTX_FORMAT " must be in between %d and %d\n",2792ContendedPaddingWidth, 0, 8192);2793status = false;2794}27952796// Need to enforce the padding not to break the existing field alignments.2797// It is sufficient to check against the largest type size.2798if ((ContendedPaddingWidth % BytesPerLong) != 0) {2799jio_fprintf(defaultStream::error_stream(),2800"ContendedPaddingWidth=" INTX_FORMAT " must be a multiple of %d\n",2801ContendedPaddingWidth, BytesPerLong);2802status = false;2803}28042805// Check lower bounds of the code cache2806// Template Interpreter code is approximately 3X larger in debug builds.2807uint min_code_cache_size = (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3)) + CodeCacheMinimumFreeSpace;2808if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {2809jio_fprintf(defaultStream::error_stream(),2810"Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,2811os::vm_page_size()/K);2812status = false;2813} else if (ReservedCodeCacheSize < InitialCodeCacheSize) {2814jio_fprintf(defaultStream::error_stream(),2815"Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",2816ReservedCodeCacheSize/K, InitialCodeCacheSize/K);2817status = false;2818} else if (ReservedCodeCacheSize < min_code_cache_size) {2819jio_fprintf(defaultStream::error_stream(),2820"Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,2821min_code_cache_size/K);2822status = false;2823} else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {2824// Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.2825jio_fprintf(defaultStream::error_stream(),2826"Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,2827CODE_CACHE_SIZE_LIMIT/M);2828status = false;2829}28302831status &= verify_interval(NmethodSweepFraction, 1, ReservedCodeCacheSize/K, "NmethodSweepFraction");2832status &= verify_interval(NmethodSweepActivity, 0, 2000, "NmethodSweepActivity");28332834if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {2835warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");2836}28372838#ifdef COMPILER12839status &= verify_interval(SafepointPollOffset, 0, os::vm_page_size() - BytesPerWord, "SafepointPollOffset");2840#endif28412842int min_number_of_compiler_threads = get_min_number_of_compiler_threads();2843// The default CICompilerCount's value is CI_COMPILER_COUNT.2844assert(min_number_of_compiler_threads <= CI_COMPILER_COUNT, "minimum should be less or equal default number");2845// Check the minimum number of compiler threads2846status &=verify_min_value(CICompilerCount, min_number_of_compiler_threads, "CICompilerCount");28472848return status;2849}28502851bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,2852const char* option_type) {2853if (ignore) return false;28542855const char* spacer = " ";2856if (option_type == NULL) {2857option_type = ++spacer; // Set both to the empty string.2858}28592860if (os::obsolete_option(option)) {2861jio_fprintf(defaultStream::error_stream(),2862"Obsolete %s%soption: %s\n", option_type, spacer,2863option->optionString);2864return false;2865} else {2866jio_fprintf(defaultStream::error_stream(),2867"Unrecognized %s%soption: %s\n", option_type, spacer,2868option->optionString);2869return true;2870}2871}28722873static const char* user_assertion_options[] = {2874"-da", "-ea", "-disableassertions", "-enableassertions", 02875};28762877static const char* system_assertion_options[] = {2878"-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 02879};28802881// Return true if any of the strings in null-terminated array 'names' matches.2882// If tail_allowed is true, then the tail must begin with a colon; otherwise,2883// the option must match exactly.2884static bool match_option(const JavaVMOption* option, const char** names, const char** tail,2885bool tail_allowed) {2886for (/* empty */; *names != NULL; ++names) {2887if (match_option(option, *names, tail)) {2888if (**tail == '\0' || tail_allowed && **tail == ':') {2889return true;2890}2891}2892}2893return false;2894}28952896bool Arguments::parse_uintx(const char* value,2897uintx* uintx_arg,2898uintx min_size) {28992900// Check the sign first since atomull() parses only unsigned values.2901bool value_is_positive = !(*value == '-');29022903if (value_is_positive) {2904julong n;2905bool good_return = atomull(value, &n);2906if (good_return) {2907bool above_minimum = n >= min_size;2908bool value_is_too_large = n > max_uintx;29092910if (above_minimum && !value_is_too_large) {2911*uintx_arg = n;2912return true;2913}2914}2915}2916return false;2917}29182919Arguments::ArgsRange Arguments::parse_memory_size(const char* s,2920julong* long_arg,2921julong min_size) {2922if (!atomull(s, long_arg)) return arg_unreadable;2923return check_memory_size(*long_arg, min_size);2924}29252926// Parse JavaVMInitArgs structure29272928jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {2929// For components of the system classpath.2930SysClassPath scp(Arguments::get_sysclasspath());2931bool scp_assembly_required = false;29322933// Save default settings for some mode flags2934Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;2935Arguments::_UseOnStackReplacement = UseOnStackReplacement;2936Arguments::_ClipInlining = ClipInlining;2937Arguments::_BackgroundCompilation = BackgroundCompilation;29382939// Setup flags for mixed which is the default2940set_mode_flags(_mixed);29412942// Parse JAVA_TOOL_OPTIONS environment variable (if present)2943jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);2944if (result != JNI_OK) {2945return result;2946}29472948// Parse JavaVMInitArgs structure passed in2949result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, Flag::COMMAND_LINE);2950if (result != JNI_OK) {2951return result;2952}29532954// Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)2955result = parse_java_options_environment_variable(&scp, &scp_assembly_required);2956if (result != JNI_OK) {2957return result;2958}29592960// We need to ensure processor and memory resources have been properly2961// configured - which may rely on arguments we just processed - before2962// doing the final argument processing. Any argument processing that2963// needs to know about processor and memory resources must occur after2964// this point.29652966os::init_container_support();29672968// Do final processing now that all arguments have been parsed2969result = finalize_vm_init_args(&scp, scp_assembly_required);2970if (result != JNI_OK) {2971return result;2972}29732974return JNI_OK;2975}29762977// Checks if name in command-line argument -agent{lib,path}:name[=options]2978// represents a valid HPROF of JDWP agent. is_path==true denotes that we2979// are dealing with -agentpath (case where name is a path), otherwise with2980// -agentlib2981bool valid_hprof_or_jdwp_agent(char *name, bool is_path) {2982char *_name;2983const char *_hprof = "hprof", *_jdwp = "jdwp";2984size_t _len_hprof, _len_jdwp, _len_prefix;29852986if (is_path) {2987if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {2988return false;2989}29902991_name++; // skip past last path separator2992_len_prefix = strlen(JNI_LIB_PREFIX);29932994if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {2995return false;2996}29972998_name += _len_prefix;2999_len_hprof = strlen(_hprof);3000_len_jdwp = strlen(_jdwp);30013002if (strncmp(_name, _hprof, _len_hprof) == 0) {3003_name += _len_hprof;3004}3005else if (strncmp(_name, _jdwp, _len_jdwp) == 0) {3006_name += _len_jdwp;3007}3008else {3009return false;3010}30113012if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {3013return false;3014}30153016return true;3017}30183019if (strcmp(name, _hprof) == 0 || strcmp(name, _jdwp) == 0) {3020return true;3021}30223023return false;3024}30253026jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,3027SysClassPath* scp_p,3028bool* scp_assembly_required_p,3029Flag::Flags origin) {3030// Remaining part of option string3031const char* tail;30323033// iterate over arguments3034for (int index = 0; index < args->nOptions; index++) {3035bool is_absolute_path = false; // for -agentpath vs -agentlib30363037const JavaVMOption* option = args->options + index;30383039if (!match_option(option, "-Djava.class.path", &tail) &&3040!match_option(option, "-Dsun.java.command", &tail) &&3041!match_option(option, "-Dsun.java.launcher", &tail)) {30423043// add all jvm options to the jvm_args string. This string3044// is used later to set the java.vm.args PerfData string constant.3045// the -Djava.class.path and the -Dsun.java.command options are3046// omitted from jvm_args string as each have their own PerfData3047// string constant object.3048build_jvm_args(option->optionString);3049}30503051// -verbose:[class/gc/jni]3052if (match_option(option, "-verbose", &tail)) {3053if (!strcmp(tail, ":class") || !strcmp(tail, "")) {3054FLAG_SET_CMDLINE(bool, TraceClassLoading, true);3055FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);3056} else if (!strcmp(tail, ":gc")) {3057FLAG_SET_CMDLINE(bool, PrintGC, true);3058} else if (!strcmp(tail, ":jni")) {3059FLAG_SET_CMDLINE(bool, PrintJNIResolving, true);3060}3061// -da / -ea / -disableassertions / -enableassertions3062// These accept an optional class/package name separated by a colon, e.g.,3063// -da:java.lang.Thread.3064} else if (match_option(option, user_assertion_options, &tail, true)) {3065bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'3066if (*tail == '\0') {3067JavaAssertions::setUserClassDefault(enable);3068} else {3069assert(*tail == ':', "bogus match by match_option()");3070JavaAssertions::addOption(tail + 1, enable);3071}3072// -dsa / -esa / -disablesystemassertions / -enablesystemassertions3073} else if (match_option(option, system_assertion_options, &tail, false)) {3074bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'3075JavaAssertions::setSystemClassDefault(enable);3076// -bootclasspath:3077} else if (match_option(option, "-Xbootclasspath:", &tail)) {3078scp_p->reset_path(tail);3079*scp_assembly_required_p = true;3080// -bootclasspath/a:3081} else if (match_option(option, "-Xbootclasspath/a:", &tail)) {3082scp_p->add_suffix(tail);3083*scp_assembly_required_p = true;3084// -bootclasspath/p:3085} else if (match_option(option, "-Xbootclasspath/p:", &tail)) {3086scp_p->add_prefix(tail);3087*scp_assembly_required_p = true;3088// -Xrun3089} else if (match_option(option, "-Xrun", &tail)) {3090if (tail != NULL) {3091const char* pos = strchr(tail, ':');3092size_t len = (pos == NULL) ? strlen(tail) : pos - tail;3093char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);3094name[len] = '\0';30953096char *options = NULL;3097if(pos != NULL) {3098size_t len2 = strlen(pos+1) + 1; // options start after ':'. Final zero must be copied.3099options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);3100}3101#if !INCLUDE_JVMTI3102if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {3103jio_fprintf(defaultStream::error_stream(),3104"Profiling and debugging agents are not supported in this VM\n");3105return JNI_ERR;3106}3107#endif // !INCLUDE_JVMTI3108add_init_library(name, options);3109}3110// -agentlib and -agentpath3111} else if (match_option(option, "-agentlib:", &tail) ||3112(is_absolute_path = match_option(option, "-agentpath:", &tail))) {3113if(tail != NULL) {3114const char* pos = strchr(tail, '=');3115size_t len = (pos == NULL) ? strlen(tail) : pos - tail;3116char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);3117name[len] = '\0';31183119char *options = NULL;3120if(pos != NULL) {3121size_t length = strlen(pos + 1) + 1;3122options = NEW_C_HEAP_ARRAY(char, length, mtInternal);3123jio_snprintf(options, length, "%s", pos + 1);3124}3125#if !INCLUDE_JVMTI3126if (valid_hprof_or_jdwp_agent(name, is_absolute_path)) {3127jio_fprintf(defaultStream::error_stream(),3128"Profiling and debugging agents are not supported in this VM\n");3129return JNI_ERR;3130}3131#endif // !INCLUDE_JVMTI3132add_init_agent(name, options, is_absolute_path);3133}3134// -javaagent3135} else if (match_option(option, "-javaagent:", &tail)) {3136#if !INCLUDE_JVMTI3137jio_fprintf(defaultStream::error_stream(),3138"Instrumentation agents are not supported in this VM\n");3139return JNI_ERR;3140#else3141if(tail != NULL) {3142size_t length = strlen(tail) + 1;3143char *options = NEW_C_HEAP_ARRAY(char, length, mtInternal);3144jio_snprintf(options, length, "%s", tail);3145add_init_agent("instrument", options, false);3146}3147#endif // !INCLUDE_JVMTI3148// -Xnoclassgc3149} else if (match_option(option, "-Xnoclassgc", &tail)) {3150FLAG_SET_CMDLINE(bool, ClassUnloading, false);3151// -Xincgc: i-CMS3152} else if (match_option(option, "-Xincgc", &tail)) {3153FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);3154FLAG_SET_CMDLINE(bool, CMSIncrementalMode, true);3155// -Xnoincgc: no i-CMS3156} else if (match_option(option, "-Xnoincgc", &tail)) {3157FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);3158FLAG_SET_CMDLINE(bool, CMSIncrementalMode, false);3159// -Xconcgc3160} else if (match_option(option, "-Xconcgc", &tail)) {3161FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);3162// -Xnoconcgc3163} else if (match_option(option, "-Xnoconcgc", &tail)) {3164FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);3165// -Xbatch3166} else if (match_option(option, "-Xbatch", &tail)) {3167FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);3168// -Xmn for compatibility with other JVM vendors3169} else if (match_option(option, "-Xmn", &tail)) {3170julong long_initial_young_size = 0;3171ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);3172if (errcode != arg_in_range) {3173jio_fprintf(defaultStream::error_stream(),3174"Invalid initial young generation size: %s\n", option->optionString);3175describe_range_error(errcode);3176return JNI_EINVAL;3177}3178FLAG_SET_CMDLINE(uintx, MaxNewSize, (uintx)long_initial_young_size);3179FLAG_SET_CMDLINE(uintx, NewSize, (uintx)long_initial_young_size);3180// -Xms3181} else if (match_option(option, "-Xms", &tail)) {3182julong long_initial_heap_size = 0;3183// an initial heap size of 0 means automatically determine3184ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);3185if (errcode != arg_in_range) {3186jio_fprintf(defaultStream::error_stream(),3187"Invalid initial heap size: %s\n", option->optionString);3188describe_range_error(errcode);3189return JNI_EINVAL;3190}3191set_min_heap_size((uintx)long_initial_heap_size);3192// Currently the minimum size and the initial heap sizes are the same.3193// Can be overridden with -XX:InitialHeapSize.3194FLAG_SET_CMDLINE(uintx, InitialHeapSize, (uintx)long_initial_heap_size);3195// -Xmx3196} else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {3197julong long_max_heap_size = 0;3198ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);3199if (errcode != arg_in_range) {3200jio_fprintf(defaultStream::error_stream(),3201"Invalid maximum heap size: %s\n", option->optionString);3202describe_range_error(errcode);3203return JNI_EINVAL;3204}3205FLAG_SET_CMDLINE(uintx, MaxHeapSize, (uintx)long_max_heap_size);3206// Xmaxf3207} else if (match_option(option, "-Xmaxf", &tail)) {3208char* err;3209int maxf = (int)(strtod(tail, &err) * 100);3210if (*err != '\0' || *tail == '\0' || maxf < 0 || maxf > 100) {3211jio_fprintf(defaultStream::error_stream(),3212"Bad max heap free percentage size: %s\n",3213option->optionString);3214return JNI_EINVAL;3215} else {3216FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf);3217}3218// Xminf3219} else if (match_option(option, "-Xminf", &tail)) {3220char* err;3221int minf = (int)(strtod(tail, &err) * 100);3222if (*err != '\0' || *tail == '\0' || minf < 0 || minf > 100) {3223jio_fprintf(defaultStream::error_stream(),3224"Bad min heap free percentage size: %s\n",3225option->optionString);3226return JNI_EINVAL;3227} else {3228FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf);3229}3230// -Xss3231} else if (match_option(option, "-Xss", &tail)) {3232julong long_ThreadStackSize = 0;3233ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);3234if (errcode != arg_in_range) {3235jio_fprintf(defaultStream::error_stream(),3236"Invalid thread stack size: %s\n", option->optionString);3237describe_range_error(errcode);3238return JNI_EINVAL;3239}3240// Internally track ThreadStackSize in units of 1024 bytes.3241FLAG_SET_CMDLINE(intx, ThreadStackSize,3242round_to((int)long_ThreadStackSize, K) / K);3243// -Xoss3244} else if (match_option(option, "-Xoss", &tail)) {3245// HotSpot does not have separate native and Java stacks, ignore silently for compatibility3246} else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {3247julong long_CodeCacheExpansionSize = 0;3248ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());3249if (errcode != arg_in_range) {3250jio_fprintf(defaultStream::error_stream(),3251"Invalid argument: %s. Must be at least %luK.\n", option->optionString,3252os::vm_page_size()/K);3253return JNI_EINVAL;3254}3255FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize);3256} else if (match_option(option, "-Xmaxjitcodesize", &tail) ||3257match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {3258julong long_ReservedCodeCacheSize = 0;32593260ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);3261if (errcode != arg_in_range) {3262jio_fprintf(defaultStream::error_stream(),3263"Invalid maximum code cache size: %s.\n", option->optionString);3264return JNI_EINVAL;3265}3266FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize);3267//-XX:IncreaseFirstTierCompileThresholdAt=3268} else if (match_option(option, "-XX:IncreaseFirstTierCompileThresholdAt=", &tail)) {3269uintx uint_IncreaseFirstTierCompileThresholdAt = 0;3270if (!parse_uintx(tail, &uint_IncreaseFirstTierCompileThresholdAt, 0) || uint_IncreaseFirstTierCompileThresholdAt > 99) {3271jio_fprintf(defaultStream::error_stream(),3272"Invalid value for IncreaseFirstTierCompileThresholdAt: %s. Should be between 0 and 99.\n",3273option->optionString);3274return JNI_EINVAL;3275}3276FLAG_SET_CMDLINE(uintx, IncreaseFirstTierCompileThresholdAt, (uintx)uint_IncreaseFirstTierCompileThresholdAt);3277// -green3278} else if (match_option(option, "-green", &tail)) {3279jio_fprintf(defaultStream::error_stream(),3280"Green threads support not available\n");3281return JNI_EINVAL;3282// -native3283} else if (match_option(option, "-native", &tail)) {3284// HotSpot always uses native threads, ignore silently for compatibility3285// -Xsqnopause3286} else if (match_option(option, "-Xsqnopause", &tail)) {3287// EVM option, ignore silently for compatibility3288// -Xrs3289} else if (match_option(option, "-Xrs", &tail)) {3290// Classic/EVM option, new functionality3291FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true);3292} else if (match_option(option, "-Xusealtsigs", &tail)) {3293// change default internal VM signals used - lower case for back compat3294FLAG_SET_CMDLINE(bool, UseAltSigs, true);3295// -Xoptimize3296} else if (match_option(option, "-Xoptimize", &tail)) {3297// EVM option, ignore silently for compatibility3298// -Xprof3299} else if (match_option(option, "-Xprof", &tail)) {3300#if INCLUDE_FPROF3301_has_profile = true;3302#else // INCLUDE_FPROF3303jio_fprintf(defaultStream::error_stream(),3304"Flat profiling is not supported in this VM.\n");3305return JNI_ERR;3306#endif // INCLUDE_FPROF3307// -Xconcurrentio3308} else if (match_option(option, "-Xconcurrentio", &tail)) {3309FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true);3310FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);3311FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1);3312FLAG_SET_CMDLINE(bool, UseTLAB, false);3313FLAG_SET_CMDLINE(uintx, NewSizeThreadIncrease, 16 * K); // 20Kb per thread added to new generation33143315// -Xinternalversion3316} else if (match_option(option, "-Xinternalversion", &tail)) {3317jio_fprintf(defaultStream::output_stream(), "%s\n",3318VM_Version::internal_vm_info_string());3319vm_exit(0);3320#ifndef PRODUCT3321// -Xprintflags3322} else if (match_option(option, "-Xprintflags", &tail)) {3323CommandLineFlags::printFlags(tty, false);3324vm_exit(0);3325#endif3326// -D3327} else if (match_option(option, "-D", &tail)) {3328if (CheckEndorsedAndExtDirs) {3329if (match_option(option, "-Djava.endorsed.dirs=", &tail)) {3330// abort if -Djava.endorsed.dirs is set3331jio_fprintf(defaultStream::output_stream(),3332"-Djava.endorsed.dirs will not be supported in a future release.\n"3333"Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");3334return JNI_EINVAL;3335}3336if (match_option(option, "-Djava.ext.dirs=", &tail)) {3337// abort if -Djava.ext.dirs is set3338jio_fprintf(defaultStream::output_stream(),3339"-Djava.ext.dirs will not be supported in a future release.\n"3340"Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");3341return JNI_EINVAL;3342}3343}33443345if (!add_property(tail)) {3346return JNI_ENOMEM;3347}3348// Out of the box management support3349if (match_option(option, "-Dcom.sun.management", &tail)) {3350#if INCLUDE_MANAGEMENT3351FLAG_SET_CMDLINE(bool, ManagementServer, true);3352#else3353jio_fprintf(defaultStream::output_stream(),3354"-Dcom.sun.management is not supported in this VM.\n");3355return JNI_ERR;3356#endif3357}3358// -Xint3359} else if (match_option(option, "-Xint", &tail)) {3360set_mode_flags(_int);3361// -Xmixed3362} else if (match_option(option, "-Xmixed", &tail)) {3363set_mode_flags(_mixed);3364// -Xcomp3365} else if (match_option(option, "-Xcomp", &tail)) {3366// for testing the compiler; turn off all flags that inhibit compilation3367set_mode_flags(_comp);3368// -Xshare:dump3369} else if (match_option(option, "-Xshare:dump", &tail)) {3370FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);3371set_mode_flags(_int); // Prevent compilation, which creates objects3372// -Xshare:on3373} else if (match_option(option, "-Xshare:on", &tail)) {3374FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);3375FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);3376// -Xshare:auto3377} else if (match_option(option, "-Xshare:auto", &tail)) {3378FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);3379FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);3380// -Xshare:off3381} else if (match_option(option, "-Xshare:off", &tail)) {3382FLAG_SET_CMDLINE(bool, UseSharedSpaces, false);3383FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);3384// -Xverify3385} else if (match_option(option, "-Xverify", &tail)) {3386if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {3387FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true);3388FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);3389} else if (strcmp(tail, ":remote") == 0) {3390FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);3391FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);3392} else if (strcmp(tail, ":none") == 0) {3393FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);3394FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false);3395} else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {3396return JNI_EINVAL;3397}3398// -Xdebug3399} else if (match_option(option, "-Xdebug", &tail)) {3400// note this flag has been used, then ignore3401set_xdebug_mode(true);3402// -Xnoagent3403} else if (match_option(option, "-Xnoagent", &tail)) {3404// For compatibility with classic. HotSpot refuses to load the old style agent.dll.3405} else if (match_option(option, "-Xboundthreads", &tail)) {3406// Bind user level threads to kernel threads (Solaris only)3407FLAG_SET_CMDLINE(bool, UseBoundThreads, true);3408} else if (match_option(option, "-Xloggc:", &tail)) {3409// Redirect GC output to the file. -Xloggc:<filename>3410// ostream_init_log(), when called will use this filename3411// to initialize a fileStream.3412_gc_log_filename = strdup(tail);3413if (!is_filename_valid(_gc_log_filename)) {3414jio_fprintf(defaultStream::output_stream(),3415"Invalid file name for use with -Xloggc: Filename can only contain the "3416"characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"3417"Note %%p or %%t can only be used once\n", _gc_log_filename);3418return JNI_EINVAL;3419}3420FLAG_SET_CMDLINE(bool, PrintGC, true);3421FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true);34223423// JNI hooks3424} else if (match_option(option, "-Xcheck", &tail)) {3425if (!strcmp(tail, ":jni")) {3426#if !INCLUDE_JNI_CHECK3427warning("JNI CHECKING is not supported in this VM");3428#else3429CheckJNICalls = true;3430#endif // INCLUDE_JNI_CHECK3431} else if (is_bad_option(option, args->ignoreUnrecognized,3432"check")) {3433return JNI_EINVAL;3434}3435} else if (match_option(option, "vfprintf", &tail)) {3436_vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);3437} else if (match_option(option, "exit", &tail)) {3438_exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);3439} else if (match_option(option, "abort", &tail)) {3440_abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);3441} else if (match_option(option, "-XX:+NeverTenure", &tail)) {3442// The last option must always win.3443FLAG_SET_CMDLINE(bool, AlwaysTenure, false);3444FLAG_SET_CMDLINE(bool, NeverTenure, true);3445} else if (match_option(option, "-XX:+AlwaysTenure", &tail)) {3446// The last option must always win.3447FLAG_SET_CMDLINE(bool, NeverTenure, false);3448FLAG_SET_CMDLINE(bool, AlwaysTenure, true);3449} else if (match_option(option, "-XX:+CMSPermGenSweepingEnabled", &tail) ||3450match_option(option, "-XX:-CMSPermGenSweepingEnabled", &tail)) {3451jio_fprintf(defaultStream::error_stream(),3452"Please use CMSClassUnloadingEnabled in place of "3453"CMSPermGenSweepingEnabled in the future\n");3454} else if (match_option(option, "-XX:+UseGCTimeLimit", &tail)) {3455FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, true);3456jio_fprintf(defaultStream::error_stream(),3457"Please use -XX:+UseGCOverheadLimit in place of "3458"-XX:+UseGCTimeLimit in the future\n");3459} else if (match_option(option, "-XX:-UseGCTimeLimit", &tail)) {3460FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, false);3461jio_fprintf(defaultStream::error_stream(),3462"Please use -XX:-UseGCOverheadLimit in place of "3463"-XX:-UseGCTimeLimit in the future\n");3464// The TLE options are for compatibility with 1.3 and will be3465// removed without notice in a future release. These options3466// are not to be documented.3467} else if (match_option(option, "-XX:MaxTLERatio=", &tail)) {3468// No longer used.3469} else if (match_option(option, "-XX:+ResizeTLE", &tail)) {3470FLAG_SET_CMDLINE(bool, ResizeTLAB, true);3471} else if (match_option(option, "-XX:-ResizeTLE", &tail)) {3472FLAG_SET_CMDLINE(bool, ResizeTLAB, false);3473} else if (match_option(option, "-XX:+PrintTLE", &tail)) {3474FLAG_SET_CMDLINE(bool, PrintTLAB, true);3475} else if (match_option(option, "-XX:-PrintTLE", &tail)) {3476FLAG_SET_CMDLINE(bool, PrintTLAB, false);3477} else if (match_option(option, "-XX:TLEFragmentationRatio=", &tail)) {3478// No longer used.3479} else if (match_option(option, "-XX:TLESize=", &tail)) {3480julong long_tlab_size = 0;3481ArgsRange errcode = parse_memory_size(tail, &long_tlab_size, 1);3482if (errcode != arg_in_range) {3483jio_fprintf(defaultStream::error_stream(),3484"Invalid TLAB size: %s\n", option->optionString);3485describe_range_error(errcode);3486return JNI_EINVAL;3487}3488FLAG_SET_CMDLINE(uintx, TLABSize, long_tlab_size);3489} else if (match_option(option, "-XX:TLEThreadRatio=", &tail)) {3490// No longer used.3491} else if (match_option(option, "-XX:+UseTLE", &tail)) {3492FLAG_SET_CMDLINE(bool, UseTLAB, true);3493} else if (match_option(option, "-XX:-UseTLE", &tail)) {3494FLAG_SET_CMDLINE(bool, UseTLAB, false);3495} else if (match_option(option, "-XX:+DisplayVMOutputToStderr", &tail)) {3496FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false);3497FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true);3498} else if (match_option(option, "-XX:+DisplayVMOutputToStdout", &tail)) {3499FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false);3500FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true);3501} else if (match_option(option, "-XX:+ExtendedDTraceProbes", &tail)) {3502#if defined(DTRACE_ENABLED)3503FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true);3504FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true);3505FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true);3506FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true);3507#else // defined(DTRACE_ENABLED)3508jio_fprintf(defaultStream::error_stream(),3509"ExtendedDTraceProbes flag is not applicable for this configuration\n");3510return JNI_EINVAL;3511#endif // defined(DTRACE_ENABLED)3512#ifdef ASSERT3513} else if (match_option(option, "-XX:+FullGCALot", &tail)) {3514FLAG_SET_CMDLINE(bool, FullGCALot, true);3515// disable scavenge before parallel mark-compact3516FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);3517#endif3518} else if (match_option(option, "-XX:CMSParPromoteBlocksToClaim=", &tail)) {3519julong cms_blocks_to_claim = (julong)atol(tail);3520FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);3521jio_fprintf(defaultStream::error_stream(),3522"Please use -XX:OldPLABSize in place of "3523"-XX:CMSParPromoteBlocksToClaim in the future\n");3524} else if (match_option(option, "-XX:ParCMSPromoteBlocksToClaim=", &tail)) {3525julong cms_blocks_to_claim = (julong)atol(tail);3526FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);3527jio_fprintf(defaultStream::error_stream(),3528"Please use -XX:OldPLABSize in place of "3529"-XX:ParCMSPromoteBlocksToClaim in the future\n");3530} else if (match_option(option, "-XX:ParallelGCOldGenAllocBufferSize=", &tail)) {3531julong old_plab_size = 0;3532ArgsRange errcode = parse_memory_size(tail, &old_plab_size, 1);3533if (errcode != arg_in_range) {3534jio_fprintf(defaultStream::error_stream(),3535"Invalid old PLAB size: %s\n", option->optionString);3536describe_range_error(errcode);3537return JNI_EINVAL;3538}3539FLAG_SET_CMDLINE(uintx, OldPLABSize, old_plab_size);3540jio_fprintf(defaultStream::error_stream(),3541"Please use -XX:OldPLABSize in place of "3542"-XX:ParallelGCOldGenAllocBufferSize in the future\n");3543} else if (match_option(option, "-XX:ParallelGCToSpaceAllocBufferSize=", &tail)) {3544julong young_plab_size = 0;3545ArgsRange errcode = parse_memory_size(tail, &young_plab_size, 1);3546if (errcode != arg_in_range) {3547jio_fprintf(defaultStream::error_stream(),3548"Invalid young PLAB size: %s\n", option->optionString);3549describe_range_error(errcode);3550return JNI_EINVAL;3551}3552FLAG_SET_CMDLINE(uintx, YoungPLABSize, young_plab_size);3553jio_fprintf(defaultStream::error_stream(),3554"Please use -XX:YoungPLABSize in place of "3555"-XX:ParallelGCToSpaceAllocBufferSize in the future\n");3556} else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||3557match_option(option, "-XX:G1MarkStackSize=", &tail)) {3558julong stack_size = 0;3559ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);3560if (errcode != arg_in_range) {3561jio_fprintf(defaultStream::error_stream(),3562"Invalid mark stack size: %s\n", option->optionString);3563describe_range_error(errcode);3564return JNI_EINVAL;3565}3566FLAG_SET_CMDLINE(uintx, MarkStackSize, stack_size);3567} else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {3568julong max_stack_size = 0;3569ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);3570if (errcode != arg_in_range) {3571jio_fprintf(defaultStream::error_stream(),3572"Invalid maximum mark stack size: %s\n",3573option->optionString);3574describe_range_error(errcode);3575return JNI_EINVAL;3576}3577FLAG_SET_CMDLINE(uintx, MarkStackSizeMax, max_stack_size);3578} else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||3579match_option(option, "-XX:ParallelCMSThreads=", &tail)) {3580uintx conc_threads = 0;3581if (!parse_uintx(tail, &conc_threads, 1)) {3582jio_fprintf(defaultStream::error_stream(),3583"Invalid concurrent threads: %s\n", option->optionString);3584return JNI_EINVAL;3585}3586FLAG_SET_CMDLINE(uintx, ConcGCThreads, conc_threads);3587} else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {3588julong max_direct_memory_size = 0;3589ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);3590if (errcode != arg_in_range) {3591jio_fprintf(defaultStream::error_stream(),3592"Invalid maximum direct memory size: %s\n",3593option->optionString);3594describe_range_error(errcode);3595return JNI_EINVAL;3596}3597FLAG_SET_CMDLINE(uintx, MaxDirectMemorySize, max_direct_memory_size);3598} else if (match_option(option, "-XX:+UseVMInterruptibleIO", &tail)) {3599// NOTE! In JDK 9, the UseVMInterruptibleIO flag will completely go3600// away and will cause VM initialization failures!3601warning("-XX:+UseVMInterruptibleIO is obsolete and will be removed in a future release.");3602FLAG_SET_CMDLINE(bool, UseVMInterruptibleIO, true);3603#if !INCLUDE_MANAGEMENT3604} else if (match_option(option, "-XX:+ManagementServer", &tail)) {3605jio_fprintf(defaultStream::error_stream(),3606"ManagementServer is not supported in this VM.\n");3607return JNI_ERR;3608#endif // INCLUDE_MANAGEMENT3609#if INCLUDE_JFR3610} else if (match_jfr_option(&option)) {3611return JNI_EINVAL;3612#endif3613} else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx3614// Skip -XX:Flags= since that case has already been handled3615if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {3616if (!process_argument(tail, args->ignoreUnrecognized, origin)) {3617return JNI_EINVAL;3618}3619}3620// Unknown option3621} else if (is_bad_option(option, args->ignoreUnrecognized)) {3622return JNI_ERR;3623}3624}36253626// PrintSharedArchiveAndExit will turn on3627// -Xshare:on3628// -XX:+TraceClassPaths3629if (PrintSharedArchiveAndExit) {3630FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);3631FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);3632FLAG_SET_CMDLINE(bool, TraceClassPaths, true);3633}36343635// Change the default value for flags which have different default values3636// when working with older JDKs.3637#ifdef LINUX3638if (JDK_Version::current().compare_major(6) <= 0 &&3639FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {3640FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);3641}3642#endif // LINUX3643fix_appclasspath();3644return JNI_OK;3645}36463647// Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)3648//3649// This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar3650// in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".3651// Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty3652// path is treated as the current directory.3653//3654// This causes problems with CDS, which requires that all directories specified in the classpath3655// must be empty. In most cases, applications do NOT want to load classes from the current3656// directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up3657// scripts compatible with CDS.3658void Arguments::fix_appclasspath() {3659if (IgnoreEmptyClassPaths) {3660const char separator = *os::path_separator();3661const char* src = _java_class_path->value();36623663// skip over all the leading empty paths3664while (*src == separator) {3665src ++;3666}36673668char* copy = os::strdup(src, mtInternal);36693670// trim all trailing empty paths3671for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {3672*tail = '\0';3673}36743675char from[3] = {separator, separator, '\0'};3676char to [2] = {separator, '\0'};3677while (StringUtils::replace_no_expand(copy, from, to) > 0) {3678// Keep replacing "::" -> ":" until we have no more "::" (non-windows)3679// Keep replacing ";;" -> ";" until we have no more ";;" (windows)3680}36813682_java_class_path->set_value(copy);3683FreeHeap(copy); // a copy was made by set_value, so don't need this anymore3684}36853686if (!PrintSharedArchiveAndExit) {3687ClassLoader::trace_class_path(tty, "[classpath: ", _java_class_path->value());3688}3689}36903691static bool has_jar_files(const char* directory) {3692DIR* dir = os::opendir(directory);3693if (dir == NULL) return false;36943695struct dirent *entry;3696bool hasJarFile = false;3697while (!hasJarFile && (entry = os::readdir(dir)) != NULL) {3698const char* name = entry->d_name;3699const char* ext = name + strlen(name) - 4;3700hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);3701}3702os::closedir(dir);3703return hasJarFile ;3704}37053706// returns the number of directories in the given path containing JAR files3707// If the skip argument is not NULL, it will skip that directory3708static int check_non_empty_dirs(const char* path, const char* type, const char* skip) {3709const char separator = *os::path_separator();3710const char* const end = path + strlen(path);3711int nonEmptyDirs = 0;3712while (path < end) {3713const char* tmp_end = strchr(path, separator);3714if (tmp_end == NULL) {3715if ((skip == NULL || strcmp(path, skip) != 0) && has_jar_files(path)) {3716nonEmptyDirs++;3717jio_fprintf(defaultStream::output_stream(),3718"Non-empty %s directory: %s\n", type, path);3719}3720path = end;3721} else {3722char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);3723memcpy(dirpath, path, tmp_end - path);3724dirpath[tmp_end - path] = '\0';3725if ((skip == NULL || strcmp(dirpath, skip) != 0) && has_jar_files(dirpath)) {3726nonEmptyDirs++;3727jio_fprintf(defaultStream::output_stream(),3728"Non-empty %s directory: %s\n", type, dirpath);3729}3730FREE_C_HEAP_ARRAY(char, dirpath, mtInternal);3731path = tmp_end + 1;3732}3733}3734return nonEmptyDirs;3735}37363737// Returns true if endorsed standards override mechanism and extension mechanism3738// are not used.3739static bool check_endorsed_and_ext_dirs() {3740if (!CheckEndorsedAndExtDirs)3741return true;37423743char endorsedDir[JVM_MAXPATHLEN];3744char extDir[JVM_MAXPATHLEN];3745const char* fileSep = os::file_separator();3746jio_snprintf(endorsedDir, sizeof(endorsedDir), "%s%slib%sendorsed",3747Arguments::get_java_home(), fileSep, fileSep);3748jio_snprintf(extDir, sizeof(extDir), "%s%slib%sext",3749Arguments::get_java_home(), fileSep, fileSep);37503751// check endorsed directory3752int nonEmptyDirs = check_non_empty_dirs(Arguments::get_endorsed_dir(), "endorsed", NULL);37533754// check the extension directories but skip the default lib/ext directory3755nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs(), "extension", extDir);37563757// List of JAR files installed in the default lib/ext directory.3758// -XX:+CheckEndorsedAndExtDirs checks if any non-JDK file installed3759static const char* jdk_ext_jars[] = {3760"access-bridge-32.jar",3761"access-bridge-64.jar",3762"access-bridge.jar",3763"cldrdata.jar",3764"dnsns.jar",3765"jaccess.jar",3766"jfxrt.jar",3767"localedata.jar",3768"nashorn.jar",3769"sunec.jar",3770"sunjce_provider.jar",3771"sunmscapi.jar",3772"sunpkcs11.jar",3773"ucrypto.jar",3774"zipfs.jar",3775NULL3776};37773778// check if the default lib/ext directory has any non-JDK jar files; if so, error3779DIR* dir = os::opendir(extDir);3780if (dir != NULL) {3781int num_ext_jars = 0;3782struct dirent *entry;3783while ((entry = os::readdir(dir)) != NULL) {3784const char* name = entry->d_name;3785const char* ext = name + strlen(name) - 4;3786if (ext > name && (os::file_name_strcmp(ext, ".jar") == 0)) {3787bool is_jdk_jar = false;3788const char* jarfile = NULL;3789for (int i=0; (jarfile = jdk_ext_jars[i]) != NULL; i++) {3790if (os::file_name_strcmp(name, jarfile) == 0) {3791is_jdk_jar = true;3792break;3793}3794}3795if (!is_jdk_jar) {3796jio_fprintf(defaultStream::output_stream(),3797"%s installed in <JAVA_HOME>/lib/ext\n", name);3798num_ext_jars++;3799}3800}3801}3802os::closedir(dir);3803if (num_ext_jars > 0) {3804nonEmptyDirs += 1;3805}3806}38073808// check if the default lib/endorsed directory exists; if so, error3809dir = os::opendir(endorsedDir);3810if (dir != NULL) {3811jio_fprintf(defaultStream::output_stream(), "<JAVA_HOME>/lib/endorsed exists\n");3812os::closedir(dir);3813nonEmptyDirs += 1;3814}38153816if (nonEmptyDirs > 0) {3817jio_fprintf(defaultStream::output_stream(),3818"Endorsed standards override mechanism and extension mechanism "3819"will not be supported in a future release.\n"3820"Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");3821return false;3822}38233824return true;3825}38263827jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {3828// This must be done after all -D arguments have been processed.3829scp_p->expand_endorsed();38303831if (scp_assembly_required || scp_p->get_endorsed() != NULL) {3832// Assemble the bootclasspath elements into the final path.3833Arguments::set_sysclasspath(scp_p->combined_path());3834}38353836if (!check_endorsed_and_ext_dirs()) {3837return JNI_ERR;3838}38393840// This must be done after all arguments have been processed3841// and the container support has been initialized since AggressiveHeap3842// relies on the amount of total memory available.3843if (AggressiveHeap) {3844jint result = set_aggressive_heap_flags();3845if (result != JNI_OK) {3846return result;3847}3848}3849// This must be done after all arguments have been processed.3850// java_compiler() true means set to "NONE" or empty.3851if (java_compiler() && !xdebug_mode()) {3852// For backwards compatibility, we switch to interpreted mode if3853// -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was3854// not specified.3855set_mode_flags(_int);3856}3857if (CompileThreshold == 0) {3858set_mode_flags(_int);3859}38603861// eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set3862if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {3863FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);3864}38653866#ifndef COMPILER23867// Don't degrade server performance for footprint3868if (FLAG_IS_DEFAULT(UseLargePages) &&3869MaxHeapSize < LargePageHeapSizeThreshold) {3870// No need for large granularity pages w/small heaps.3871// Note that large pages are enabled/disabled for both the3872// Java heap and the code cache.3873FLAG_SET_DEFAULT(UseLargePages, false);3874}38753876#else3877if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {3878FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);3879}3880#endif38813882#ifndef TIERED3883// Tiered compilation is undefined.3884UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");3885#endif38863887// If we are running in a headless jre, force java.awt.headless property3888// to be true unless the property has already been set.3889// Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.3890if (os::is_headless_jre()) {3891const char* headless = Arguments::get_property("java.awt.headless");3892if (headless == NULL) {3893char envbuffer[128];3894if (!os::getenv("JAVA_AWT_HEADLESS", envbuffer, sizeof(envbuffer))) {3895if (!add_property("java.awt.headless=true")) {3896return JNI_ENOMEM;3897}3898} else {3899char buffer[256];3900jio_snprintf(buffer, 256, "java.awt.headless=%s", envbuffer);3901if (!add_property(buffer)) {3902return JNI_ENOMEM;3903}3904}3905}3906}39073908if (!check_vm_args_consistency()) {3909return JNI_ERR;3910}39113912return JNI_OK;3913}39143915jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {3916return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,3917scp_assembly_required_p);3918}39193920jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {3921return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,3922scp_assembly_required_p);3923}39243925jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {3926const int N_MAX_OPTIONS = 64;3927const int OPTION_BUFFER_SIZE = 1024;3928char buffer[OPTION_BUFFER_SIZE];39293930// The variable will be ignored if it exceeds the length of the buffer.3931// Don't check this variable if user has special privileges3932// (e.g. unix su command).3933if (os::getenv(name, buffer, sizeof(buffer)) &&3934!os::have_special_privileges()) {3935JavaVMOption options[N_MAX_OPTIONS]; // Construct option array3936jio_fprintf(defaultStream::error_stream(),3937"Picked up %s: %s\n", name, buffer);3938char* rd = buffer; // pointer to the input string (rd)3939int i;3940for (i = 0; i < N_MAX_OPTIONS;) { // repeat for all options in the input string3941while (isspace(*rd)) rd++; // skip whitespace3942if (*rd == 0) break; // we re done when the input string is read completely39433944// The output, option string, overwrites the input string.3945// Because of quoting, the pointer to the option string (wrt) may lag the pointer to3946// input string (rd).3947char* wrt = rd;39483949options[i++].optionString = wrt; // Fill in option3950while (*rd != 0 && !isspace(*rd)) { // unquoted strings terminate with a space or NULL3951if (*rd == '\'' || *rd == '"') { // handle a quoted string3952int quote = *rd; // matching quote to look for3953rd++; // don't copy open quote3954while (*rd != quote) { // include everything (even spaces) up until quote3955if (*rd == 0) { // string termination means unmatched string3956jio_fprintf(defaultStream::error_stream(),3957"Unmatched quote in %s\n", name);3958return JNI_ERR;3959}3960*wrt++ = *rd++; // copy to option string3961}3962rd++; // don't copy close quote3963} else {3964*wrt++ = *rd++; // copy to option string3965}3966}3967// Need to check if we're done before writing a NULL,3968// because the write could be to the byte that rd is pointing to.3969if (*rd++ == 0) {3970*wrt = 0;3971break;3972}3973*wrt = 0; // Zero terminate option3974}3975// Construct JavaVMInitArgs structure and parse as if it was part of the command line3976JavaVMInitArgs vm_args;3977vm_args.version = JNI_VERSION_1_2;3978vm_args.options = options;3979vm_args.nOptions = i;3980vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;39813982if (PrintVMOptions) {3983const char* tail;3984for (int i = 0; i < vm_args.nOptions; i++) {3985const JavaVMOption *option = vm_args.options + i;3986if (match_option(option, "-XX:", &tail)) {3987logOption(tail);3988}3989}3990}39913992return(parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p, Flag::ENVIRON_VAR));3993}3994return JNI_OK;3995}39963997void Arguments::set_shared_spaces_flags() {3998if (DumpSharedSpaces) {3999if (FailOverToOldVerifier) {4000// Don't fall back to the old verifier on verification failure. If a4001// class fails verification with the split verifier, it might fail the4002// CDS runtime verifier constraint check. In that case, we don't want4003// to share the class. We only archive classes that pass the split verifier.4004FLAG_SET_DEFAULT(FailOverToOldVerifier, false);4005}40064007if (RequireSharedSpaces) {4008warning("cannot dump shared archive while using shared archive");4009}4010UseSharedSpaces = false;4011#ifdef _LP644012if (!UseCompressedOops || !UseCompressedClassPointers) {4013vm_exit_during_initialization(4014"Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);4015}4016} else {4017if (!UseCompressedOops || !UseCompressedClassPointers) {4018no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");4019}4020#endif4021}4022}40234024#if !INCLUDE_ALL_GCS4025static void force_serial_gc() {4026FLAG_SET_DEFAULT(UseSerialGC, true);4027FLAG_SET_DEFAULT(CMSIncrementalMode, false); // special CMS suboption4028UNSUPPORTED_GC_OPTION(UseG1GC);4029UNSUPPORTED_GC_OPTION(UseParallelGC);4030UNSUPPORTED_GC_OPTION(UseParallelOldGC);4031UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);4032UNSUPPORTED_GC_OPTION(UseParNewGC);4033}4034#endif // INCLUDE_ALL_GCS40354036// Sharing support4037// Construct the path to the archive4038static char* get_shared_archive_path() {4039char *shared_archive_path;4040if (SharedArchiveFile == NULL) {4041char jvm_path[JVM_MAXPATHLEN];4042os::jvm_path(jvm_path, sizeof(jvm_path));4043char *end = strrchr(jvm_path, *os::file_separator());4044if (end != NULL) *end = '\0';4045size_t jvm_path_len = strlen(jvm_path);4046size_t file_sep_len = strlen(os::file_separator());4047const size_t len = jvm_path_len + file_sep_len + 20;4048shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtInternal);4049if (shared_archive_path != NULL) {4050jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",4051jvm_path, os::file_separator());4052}4053} else {4054shared_archive_path = os::strdup(SharedArchiveFile, mtInternal);4055}4056return shared_archive_path;4057}40584059#ifndef PRODUCT4060// Determine whether LogVMOutput should be implicitly turned on.4061static bool use_vm_log() {4062if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||4063PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||4064PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||4065PrintAssembly || TraceDeoptimization || TraceDependencies ||4066(VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {4067return true;4068}40694070#ifdef COMPILER14071if (PrintC1Statistics) {4072return true;4073}4074#endif // COMPILER140754076#ifdef COMPILER24077if (PrintOptoAssembly || PrintOptoStatistics) {4078return true;4079}4080#endif // COMPILER240814082return false;4083}4084#endif // PRODUCT40854086// Parse entry point called from JNI_CreateJavaVM40874088jint Arguments::parse(const JavaVMInitArgs* args) {40894090// Remaining part of option string4091const char* tail;40924093// If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.4094const char* hotspotrc = ".hotspotrc";4095bool settings_file_specified = false;4096bool needs_hotspotrc_warning = false;40974098ArgumentsExt::process_options(args);40994100const char* flags_file;4101int index;4102for (index = 0; index < args->nOptions; index++) {4103const JavaVMOption *option = args->options + index;4104if (match_option(option, "-XX:Flags=", &tail)) {4105flags_file = tail;4106settings_file_specified = true;4107}4108if (match_option(option, "-XX:+PrintVMOptions", &tail)) {4109PrintVMOptions = true;4110}4111if (match_option(option, "-XX:-PrintVMOptions", &tail)) {4112PrintVMOptions = false;4113}4114if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions", &tail)) {4115IgnoreUnrecognizedVMOptions = true;4116}4117if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions", &tail)) {4118IgnoreUnrecognizedVMOptions = false;4119}4120if (match_option(option, "-XX:+PrintFlagsInitial", &tail)) {4121CommandLineFlags::printFlags(tty, false);4122vm_exit(0);4123}4124if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {4125#if INCLUDE_NMT4126// The launcher did not setup nmt environment variable properly.4127if (!MemTracker::check_launcher_nmt_support(tail)) {4128warning("Native Memory Tracking did not setup properly, using wrong launcher?");4129}41304131// Verify if nmt option is valid.4132if (MemTracker::verify_nmt_option()) {4133// Late initialization, still in single-threaded mode.4134if (MemTracker::tracking_level() >= NMT_summary) {4135MemTracker::init();4136}4137} else {4138vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);4139}4140#else4141jio_fprintf(defaultStream::error_stream(),4142"Native Memory Tracking is not supported in this VM\n");4143return JNI_ERR;4144#endif4145}414641474148#ifndef PRODUCT4149if (match_option(option, "-XX:+PrintFlagsWithComments", &tail)) {4150CommandLineFlags::printFlags(tty, true);4151vm_exit(0);4152}4153#endif4154}41554156if (IgnoreUnrecognizedVMOptions) {4157// uncast const to modify the flag args->ignoreUnrecognized4158*(jboolean*)(&args->ignoreUnrecognized) = true;4159}41604161// Parse specified settings file4162if (settings_file_specified) {4163if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {4164return JNI_EINVAL;4165}4166} else {4167#ifdef ASSERT4168// Parse default .hotspotrc settings file4169if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {4170return JNI_EINVAL;4171}4172#else4173struct stat buf;4174if (os::stat(hotspotrc, &buf) == 0) {4175needs_hotspotrc_warning = true;4176}4177#endif4178}41794180if (PrintVMOptions) {4181for (index = 0; index < args->nOptions; index++) {4182const JavaVMOption *option = args->options + index;4183if (match_option(option, "-XX:", &tail)) {4184logOption(tail);4185}4186}4187}41884189// Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS4190jint result = parse_vm_init_args(args);4191if (result != JNI_OK) {4192return result;4193}41944195// Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.4196SharedArchivePath = get_shared_archive_path();4197if (SharedArchivePath == NULL) {4198return JNI_ENOMEM;4199}42004201// Set up VerifySharedSpaces4202if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {4203VerifySharedSpaces = true;4204}42054206// Delay warning until here so that we've had a chance to process4207// the -XX:-PrintWarnings flag4208if (needs_hotspotrc_warning) {4209warning("%s file is present but has been ignored. "4210"Run with -XX:Flags=%s to load the file.",4211hotspotrc, hotspotrc);4212}42134214#ifdef _ALLBSD_SOURCE // UseLargePages is not yet supported on BSD.4215UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");4216#endif42174218#if INCLUDE_ALL_GCS4219#if (defined JAVASE_EMBEDDED || defined ARM)4220UNSUPPORTED_OPTION(UseG1GC, "G1 GC");4221#endif4222#endif42234224#ifndef PRODUCT4225if (TraceBytecodesAt != 0) {4226TraceBytecodes = true;4227}4228if (CountCompiledCalls) {4229if (UseCounterDecay) {4230warning("UseCounterDecay disabled because CountCalls is set");4231UseCounterDecay = false;4232}4233}4234#endif // PRODUCT42354236// JSR 292 is not supported before 1.74237if (!JDK_Version::is_gte_jdk17x_version()) {4238if (EnableInvokeDynamic) {4239if (!FLAG_IS_DEFAULT(EnableInvokeDynamic)) {4240warning("JSR 292 is not supported before 1.7. Disabling support.");4241}4242EnableInvokeDynamic = false;4243}4244}42454246if (EnableInvokeDynamic && ScavengeRootsInCode == 0) {4247if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {4248warning("forcing ScavengeRootsInCode non-zero because EnableInvokeDynamic is true");4249}4250ScavengeRootsInCode = 1;4251}42524253if (PrintGCDetails) {4254// Turn on -verbose:gc options as well4255PrintGC = true;4256}42574258if (!JDK_Version::is_gte_jdk18x_version()) {4259// To avoid changing the log format for 7 updates this flag is only4260// true by default in JDK8 and above.4261if (FLAG_IS_DEFAULT(PrintGCCause)) {4262FLAG_SET_DEFAULT(PrintGCCause, false);4263}4264}42654266// Set object alignment values.4267set_object_alignment();42684269#if !INCLUDE_ALL_GCS4270force_serial_gc();4271#endif // INCLUDE_ALL_GCS4272#if !INCLUDE_CDS4273if (DumpSharedSpaces || RequireSharedSpaces) {4274jio_fprintf(defaultStream::error_stream(),4275"Shared spaces are not supported in this VM\n");4276return JNI_ERR;4277}4278if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {4279warning("Shared spaces are not supported in this VM");4280FLAG_SET_DEFAULT(UseSharedSpaces, false);4281FLAG_SET_DEFAULT(PrintSharedSpaces, false);4282}4283no_shared_spaces("CDS Disabled");4284#endif // INCLUDE_CDS42854286return JNI_OK;4287}42884289jint Arguments::apply_ergo() {42904291// Set flags based on ergonomics.4292set_ergonomics_flags();42934294set_shared_spaces_flags();42954296#if defined(SPARC)4297// BIS instructions require 'membar' instruction regardless of the number4298// of CPUs because in virtualized/container environments which might use only 14299// CPU, BIS instructions may produce incorrect results.43004301if (FLAG_IS_DEFAULT(AssumeMP)) {4302FLAG_SET_DEFAULT(AssumeMP, true);4303}4304#endif43054306// Check the GC selections again.4307if (!check_gc_consistency()) {4308return JNI_EINVAL;4309}43104311if (TieredCompilation) {4312set_tiered_flags();4313} else {4314// Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup.4315if (CompilationPolicyChoice >= 2) {4316vm_exit_during_initialization(4317"Incompatible compilation policy selected", NULL);4318}4319}4320// Set NmethodSweepFraction after the size of the code cache is adapted (in case of tiered)4321if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {4322FLAG_SET_DEFAULT(NmethodSweepFraction, 1 + ReservedCodeCacheSize / (16 * M));4323}432443254326// Set heap size based on available physical memory4327set_heap_size();43284329ArgumentsExt::set_gc_specific_flags();43304331// Initialize Metaspace flags and alignments.4332Metaspace::ergo_initialize();43334334// Set bytecode rewriting flags4335set_bytecode_flags();43364337// Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled.4338set_aggressive_opts_flags();43394340// Turn off biased locking for locking debug mode flags,4341// which are subtlely different from each other but neither works with4342// biased locking.4343if (UseHeavyMonitors4344#ifdef COMPILER14345|| !UseFastLocking4346#endif // COMPILER14347) {4348if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {4349// flag set to true on command line; warn the user that they4350// can't enable biased locking here4351warning("Biased Locking is not supported with locking debug flags"4352"; ignoring UseBiasedLocking flag." );4353}4354UseBiasedLocking = false;4355}43564357#ifdef ZERO4358// Clear flags not supported on zero.4359FLAG_SET_DEFAULT(ProfileInterpreter, false);4360FLAG_SET_DEFAULT(UseBiasedLocking, false);4361LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));4362LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));4363#endif // CC_INTERP43644365#ifdef COMPILER24366if (!EliminateLocks) {4367EliminateNestedLocks = false;4368}4369if (!Inline) {4370IncrementalInline = false;4371}4372#ifndef PRODUCT4373if (!IncrementalInline) {4374AlwaysIncrementalInline = false;4375}4376#endif4377if (IncrementalInline && FLAG_IS_DEFAULT(MaxNodeLimit)) {4378// incremental inlining: bump MaxNodeLimit4379FLAG_SET_DEFAULT(MaxNodeLimit, (intx)75000);4380}4381if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {4382// nothing to use the profiling, turn if off4383FLAG_SET_DEFAULT(TypeProfileLevel, 0);4384}4385#endif43864387if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {4388warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");4389DebugNonSafepoints = true;4390}43914392if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {4393warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");4394}43954396if (UseOnStackReplacement && !UseLoopCounter) {4397warning("On-stack-replacement requires loop counters; enabling loop counters");4398FLAG_SET_DEFAULT(UseLoopCounter, true);4399}44004401#ifndef PRODUCT4402if (CompileTheWorld) {4403// Force NmethodSweeper to sweep whole CodeCache each time.4404if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {4405NmethodSweepFraction = 1;4406}4407}44084409if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {4410if (use_vm_log()) {4411LogVMOutput = true;4412}4413}4414#endif // PRODUCT44154416if (PrintCommandLineFlags) {4417CommandLineFlags::printSetFlags(tty);4418}44194420// Apply CPU specific policy for the BiasedLocking4421if (UseBiasedLocking) {4422if (!VM_Version::use_biased_locking() &&4423!(FLAG_IS_CMDLINE(UseBiasedLocking))) {4424UseBiasedLocking = false;4425}4426}4427#ifdef COMPILER24428if (!UseBiasedLocking || EmitSync != 0) {4429UseOptoBiasInlining = false;4430}4431#endif44324433// set PauseAtExit if the gamma launcher was used and a debugger is attached4434// but only if not already set on the commandline4435if (Arguments::created_by_gamma_launcher() && os::is_debugger_attached()) {4436bool set = false;4437CommandLineFlags::wasSetOnCmdline("PauseAtExit", &set);4438if (!set) {4439FLAG_SET_DEFAULT(PauseAtExit, true);4440}4441}44424443return JNI_OK;4444}44454446jint Arguments::adjust_after_os() {4447if (UseNUMA) {4448if (UseParallelGC || UseParallelOldGC) {4449if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {4450FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);4451}4452}4453// UseNUMAInterleaving is set to ON for all collectors and4454// platforms when UseNUMA is set to ON. NUMA-aware collectors4455// such as the parallel collector for Linux and Solaris will4456// interleave old gen and survivor spaces on top of NUMA4457// allocation policy for the eden space.4458// Non NUMA-aware collectors such as CMS, G1 and Serial-GC on4459// all platforms and ParallelGC on Windows will interleave all4460// of the heap spaces across NUMA nodes.4461if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {4462FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);4463}4464}4465return JNI_OK;4466}44674468int Arguments::PropertyList_count(SystemProperty* pl) {4469int count = 0;4470while(pl != NULL) {4471count++;4472pl = pl->next();4473}4474return count;4475}44764477const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {4478assert(key != NULL, "just checking");4479SystemProperty* prop;4480for (prop = pl; prop != NULL; prop = prop->next()) {4481if (strcmp(key, prop->key()) == 0) return prop->value();4482}4483return NULL;4484}44854486const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {4487int count = 0;4488const char* ret_val = NULL;44894490while(pl != NULL) {4491if(count >= index) {4492ret_val = pl->key();4493break;4494}4495count++;4496pl = pl->next();4497}44984499return ret_val;4500}45014502char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {4503int count = 0;4504char* ret_val = NULL;45054506while(pl != NULL) {4507if(count >= index) {4508ret_val = pl->value();4509break;4510}4511count++;4512pl = pl->next();4513}45144515return ret_val;4516}45174518void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {4519SystemProperty* p = *plist;4520if (p == NULL) {4521*plist = new_p;4522} else {4523while (p->next() != NULL) {4524p = p->next();4525}4526p->set_next(new_p);4527}4528}45294530void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {4531if (plist == NULL)4532return;45334534SystemProperty* new_p = new SystemProperty(k, v, true);4535PropertyList_add(plist, new_p);4536}45374538// This add maintains unique property key in the list.4539void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {4540if (plist == NULL)4541return;45424543// If property key exist then update with new value.4544SystemProperty* prop;4545for (prop = *plist; prop != NULL; prop = prop->next()) {4546if (strcmp(k, prop->key()) == 0) {4547if (append) {4548prop->append_value(v);4549} else {4550prop->set_value(v);4551}4552return;4553}4554}45554556PropertyList_add(plist, k, v);4557}45584559// Copies src into buf, replacing "%%" with "%" and "%p" with pid4560// Returns true if all of the source pointed by src has been copied over to4561// the destination buffer pointed by buf. Otherwise, returns false.4562// Notes:4563// 1. If the length (buflen) of the destination buffer excluding the4564// NULL terminator character is not long enough for holding the expanded4565// pid characters, it also returns false instead of returning the partially4566// expanded one.4567// 2. The passed in "buflen" should be large enough to hold the null terminator.4568bool Arguments::copy_expand_pid(const char* src, size_t srclen,4569char* buf, size_t buflen) {4570const char* p = src;4571char* b = buf;4572const char* src_end = &src[srclen];4573char* buf_end = &buf[buflen - 1];45744575while (p < src_end && b < buf_end) {4576if (*p == '%') {4577switch (*(++p)) {4578case '%': // "%%" ==> "%"4579*b++ = *p++;4580break;4581case 'p': { // "%p" ==> current process id4582// buf_end points to the character before the last character so4583// that we could write '\0' to the end of the buffer.4584size_t buf_sz = buf_end - b + 1;4585int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());45864587// if jio_snprintf fails or the buffer is not long enough to hold4588// the expanded pid, returns false.4589if (ret < 0 || ret >= (int)buf_sz) {4590return false;4591} else {4592b += ret;4593assert(*b == '\0', "fail in copy_expand_pid");4594if (p == src_end && b == buf_end + 1) {4595// reach the end of the buffer.4596return true;4597}4598}4599p++;4600break;4601}4602default :4603*b++ = '%';4604}4605} else {4606*b++ = *p++;4607}4608}4609*b = '\0';4610return (p == src_end); // return false if not all of the source was copied4611}461246134614