Path: blob/master/src/hotspot/share/runtime/arguments.cpp
40951 views
/*1* Copyright (c) 1997, 2021, 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 "jvm.h"26#include "cds/filemap.hpp"27#include "classfile/classLoader.hpp"28#include "classfile/javaAssertions.hpp"29#include "classfile/moduleEntry.hpp"30#include "classfile/stringTable.hpp"31#include "classfile/symbolTable.hpp"32#include "compiler/compilerDefinitions.hpp"33#include "gc/shared/gcArguments.hpp"34#include "gc/shared/gcConfig.hpp"35#include "gc/shared/stringdedup/stringDedup.hpp"36#include "gc/shared/tlab_globals.hpp"37#include "logging/log.hpp"38#include "logging/logConfiguration.hpp"39#include "logging/logStream.hpp"40#include "logging/logTag.hpp"41#include "memory/allocation.inline.hpp"42#include "oops/oop.inline.hpp"43#include "prims/jvmtiExport.hpp"44#include "runtime/arguments.hpp"45#include "runtime/flags/jvmFlag.hpp"46#include "runtime/flags/jvmFlagAccess.hpp"47#include "runtime/flags/jvmFlagLimit.hpp"48#include "runtime/globals_extension.hpp"49#include "runtime/java.hpp"50#include "runtime/os.hpp"51#include "runtime/safepoint.hpp"52#include "runtime/safepointMechanism.hpp"53#include "runtime/vm_version.hpp"54#include "services/management.hpp"55#include "services/memTracker.hpp"56#include "utilities/align.hpp"57#include "utilities/defaultStream.hpp"58#include "utilities/macros.hpp"59#include "utilities/powerOfTwo.hpp"60#include "utilities/stringUtils.hpp"61#if INCLUDE_JFR62#include "jfr/jfr.hpp"63#endif6465#define DEFAULT_JAVA_LAUNCHER "generic"6667char* Arguments::_jvm_flags_file = NULL;68char** Arguments::_jvm_flags_array = NULL;69int Arguments::_num_jvm_flags = 0;70char** Arguments::_jvm_args_array = NULL;71int Arguments::_num_jvm_args = 0;72char* Arguments::_java_command = NULL;73SystemProperty* Arguments::_system_properties = NULL;74const char* Arguments::_gc_log_filename = NULL;75size_t Arguments::_conservative_max_heap_alignment = 0;76Arguments::Mode Arguments::_mode = _mixed;77bool Arguments::_java_compiler = false;78bool Arguments::_xdebug_mode = false;79const char* Arguments::_java_vendor_url_bug = NULL;80const char* Arguments::_sun_java_launcher = DEFAULT_JAVA_LAUNCHER;81bool Arguments::_sun_java_launcher_is_altjvm = false;8283// These parameters are reset in method parse_vm_init_args()84bool Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;85bool Arguments::_UseOnStackReplacement = UseOnStackReplacement;86bool Arguments::_BackgroundCompilation = BackgroundCompilation;87bool Arguments::_ClipInlining = ClipInlining;88size_t Arguments::_default_SharedBaseAddress = SharedBaseAddress;8990bool Arguments::_enable_preview = false;9192char* Arguments::SharedArchivePath = NULL;93char* Arguments::SharedDynamicArchivePath = NULL;9495AgentLibraryList Arguments::_libraryList;96AgentLibraryList Arguments::_agentList;9798// These are not set by the JDK's built-in launchers, but they can be set by99// programs that embed the JVM using JNI_CreateJavaVM. See comments around100// JavaVMOption in jni.h.101abort_hook_t Arguments::_abort_hook = NULL;102exit_hook_t Arguments::_exit_hook = NULL;103vfprintf_hook_t Arguments::_vfprintf_hook = NULL;104105106SystemProperty *Arguments::_sun_boot_library_path = NULL;107SystemProperty *Arguments::_java_library_path = NULL;108SystemProperty *Arguments::_java_home = NULL;109SystemProperty *Arguments::_java_class_path = NULL;110SystemProperty *Arguments::_jdk_boot_class_path_append = NULL;111SystemProperty *Arguments::_vm_info = NULL;112113GrowableArray<ModulePatchPath*> *Arguments::_patch_mod_prefix = NULL;114PathString *Arguments::_system_boot_class_path = NULL;115bool Arguments::_has_jimage = false;116117char* Arguments::_ext_dirs = NULL;118119bool PathString::set_value(const char *value) {120if (_value != NULL) {121FreeHeap(_value);122}123_value = AllocateHeap(strlen(value)+1, mtArguments);124assert(_value != NULL, "Unable to allocate space for new path value");125if (_value != NULL) {126strcpy(_value, value);127} else {128// not able to allocate129return false;130}131return true;132}133134void PathString::append_value(const char *value) {135char *sp;136size_t len = 0;137if (value != NULL) {138len = strlen(value);139if (_value != NULL) {140len += strlen(_value);141}142sp = AllocateHeap(len+2, mtArguments);143assert(sp != NULL, "Unable to allocate space for new append path value");144if (sp != NULL) {145if (_value != NULL) {146strcpy(sp, _value);147strcat(sp, os::path_separator());148strcat(sp, value);149FreeHeap(_value);150} else {151strcpy(sp, value);152}153_value = sp;154}155}156}157158PathString::PathString(const char* value) {159if (value == NULL) {160_value = NULL;161} else {162_value = AllocateHeap(strlen(value)+1, mtArguments);163strcpy(_value, value);164}165}166167PathString::~PathString() {168if (_value != NULL) {169FreeHeap(_value);170_value = NULL;171}172}173174ModulePatchPath::ModulePatchPath(const char* module_name, const char* path) {175assert(module_name != NULL && path != NULL, "Invalid module name or path value");176size_t len = strlen(module_name) + 1;177_module_name = AllocateHeap(len, mtInternal);178strncpy(_module_name, module_name, len); // copy the trailing null179_path = new PathString(path);180}181182ModulePatchPath::~ModulePatchPath() {183if (_module_name != NULL) {184FreeHeap(_module_name);185_module_name = NULL;186}187if (_path != NULL) {188delete _path;189_path = NULL;190}191}192193SystemProperty::SystemProperty(const char* key, const char* value, bool writeable, bool internal) : PathString(value) {194if (key == NULL) {195_key = NULL;196} else {197_key = AllocateHeap(strlen(key)+1, mtArguments);198strcpy(_key, key);199}200_next = NULL;201_internal = internal;202_writeable = writeable;203}204205AgentLibrary::AgentLibrary(const char* name, const char* options,206bool is_absolute_path, void* os_lib,207bool instrument_lib) {208_name = AllocateHeap(strlen(name)+1, mtArguments);209strcpy(_name, name);210if (options == NULL) {211_options = NULL;212} else {213_options = AllocateHeap(strlen(options)+1, mtArguments);214strcpy(_options, options);215}216_is_absolute_path = is_absolute_path;217_os_lib = os_lib;218_next = NULL;219_state = agent_invalid;220_is_static_lib = false;221_is_instrument_lib = instrument_lib;222}223224// Check if head of 'option' matches 'name', and sets 'tail' to the remaining225// part of the option string.226static bool match_option(const JavaVMOption *option, const char* name,227const char** tail) {228size_t len = strlen(name);229if (strncmp(option->optionString, name, len) == 0) {230*tail = option->optionString + len;231return true;232} else {233return false;234}235}236237// Check if 'option' matches 'name'. No "tail" is allowed.238static bool match_option(const JavaVMOption *option, const char* name) {239const char* tail = NULL;240bool result = match_option(option, name, &tail);241if (tail != NULL && *tail == '\0') {242return result;243} else {244return false;245}246}247248// Return true if any of the strings in null-terminated array 'names' matches.249// If tail_allowed is true, then the tail must begin with a colon; otherwise,250// the option must match exactly.251static bool match_option(const JavaVMOption* option, const char** names, const char** tail,252bool tail_allowed) {253for (/* empty */; *names != NULL; ++names) {254if (match_option(option, *names, tail)) {255if (**tail == '\0' || (tail_allowed && **tail == ':')) {256return true;257}258}259}260return false;261}262263#if INCLUDE_JFR264static bool _has_jfr_option = false; // is using JFR265266// return true on failure267static bool match_jfr_option(const JavaVMOption** option) {268assert((*option)->optionString != NULL, "invariant");269char* tail = NULL;270if (match_option(*option, "-XX:StartFlightRecording", (const char**)&tail)) {271_has_jfr_option = true;272return Jfr::on_start_flight_recording_option(option, tail);273} else if (match_option(*option, "-XX:FlightRecorderOptions", (const char**)&tail)) {274_has_jfr_option = true;275return Jfr::on_flight_recorder_option(option, tail);276}277return false;278}279280bool Arguments::has_jfr_option() {281return _has_jfr_option;282}283#endif284285static void logOption(const char* opt) {286if (PrintVMOptions) {287jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);288}289}290291bool needs_module_property_warning = false;292293#define MODULE_PROPERTY_PREFIX "jdk.module."294#define MODULE_PROPERTY_PREFIX_LEN 11295#define ADDEXPORTS "addexports"296#define ADDEXPORTS_LEN 10297#define ADDREADS "addreads"298#define ADDREADS_LEN 8299#define ADDOPENS "addopens"300#define ADDOPENS_LEN 8301#define PATCH "patch"302#define PATCH_LEN 5303#define ADDMODS "addmods"304#define ADDMODS_LEN 7305#define LIMITMODS "limitmods"306#define LIMITMODS_LEN 9307#define PATH "path"308#define PATH_LEN 4309#define UPGRADE_PATH "upgrade.path"310#define UPGRADE_PATH_LEN 12311#define ENABLE_NATIVE_ACCESS "enable.native.access"312#define ENABLE_NATIVE_ACCESS_LEN 20313314void Arguments::add_init_library(const char* name, char* options) {315_libraryList.add(new AgentLibrary(name, options, false, NULL));316}317318void Arguments::add_init_agent(const char* name, char* options, bool absolute_path) {319_agentList.add(new AgentLibrary(name, options, absolute_path, NULL));320}321322void Arguments::add_instrument_agent(const char* name, char* options, bool absolute_path) {323_agentList.add(new AgentLibrary(name, options, absolute_path, NULL, true));324}325326// Late-binding agents not started via arguments327void Arguments::add_loaded_agent(AgentLibrary *agentLib) {328_agentList.add(agentLib);329}330331// Return TRUE if option matches 'property', or 'property=', or 'property.'.332static bool matches_property_suffix(const char* option, const char* property, size_t len) {333return ((strncmp(option, property, len) == 0) &&334(option[len] == '=' || option[len] == '.' || option[len] == '\0'));335}336337// Return true if property starts with "jdk.module." and its ensuing chars match338// any of the reserved module properties.339// property should be passed without the leading "-D".340bool Arguments::is_internal_module_property(const char* property) {341assert((strncmp(property, "-D", 2) != 0), "Unexpected leading -D");342if (strncmp(property, MODULE_PROPERTY_PREFIX, MODULE_PROPERTY_PREFIX_LEN) == 0) {343const char* property_suffix = property + MODULE_PROPERTY_PREFIX_LEN;344if (matches_property_suffix(property_suffix, ADDEXPORTS, ADDEXPORTS_LEN) ||345matches_property_suffix(property_suffix, ADDREADS, ADDREADS_LEN) ||346matches_property_suffix(property_suffix, ADDOPENS, ADDOPENS_LEN) ||347matches_property_suffix(property_suffix, PATCH, PATCH_LEN) ||348matches_property_suffix(property_suffix, ADDMODS, ADDMODS_LEN) ||349matches_property_suffix(property_suffix, LIMITMODS, LIMITMODS_LEN) ||350matches_property_suffix(property_suffix, PATH, PATH_LEN) ||351matches_property_suffix(property_suffix, UPGRADE_PATH, UPGRADE_PATH_LEN) ||352matches_property_suffix(property_suffix, ENABLE_NATIVE_ACCESS, ENABLE_NATIVE_ACCESS_LEN)) {353return true;354}355}356return false;357}358359// Process java launcher properties.360void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {361// See if sun.java.launcher or sun.java.launcher.is_altjvm is defined.362// Must do this before setting up other system properties,363// as some of them may depend on launcher type.364for (int index = 0; index < args->nOptions; index++) {365const JavaVMOption* option = args->options + index;366const char* tail;367368if (match_option(option, "-Dsun.java.launcher=", &tail)) {369process_java_launcher_argument(tail, option->extraInfo);370continue;371}372if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {373if (strcmp(tail, "true") == 0) {374_sun_java_launcher_is_altjvm = true;375}376continue;377}378}379}380381// Initialize system properties key and value.382void Arguments::init_system_properties() {383384// Set up _system_boot_class_path which is not a property but385// relies heavily on argument processing and the jdk.boot.class.path.append386// property. It is used to store the underlying system boot class path.387_system_boot_class_path = new PathString(NULL);388389PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",390"Java Virtual Machine Specification", false));391PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(), false));392PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(), false));393PropertyList_add(&_system_properties, new SystemProperty("jdk.debug", VM_Version::jdk_debug_level(), false));394395// Initialize the vm.info now, but it will need updating after argument parsing.396_vm_info = new SystemProperty("java.vm.info", VM_Version::vm_info_string(), true);397398// Following are JVMTI agent writable properties.399// Properties values are set to NULL and they are400// os specific they are initialized in os::init_system_properties_values().401_sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL, true);402_java_library_path = new SystemProperty("java.library.path", NULL, true);403_java_home = new SystemProperty("java.home", NULL, true);404_java_class_path = new SystemProperty("java.class.path", "", true);405// jdk.boot.class.path.append is a non-writeable, internal property.406// It can only be set by either:407// - -Xbootclasspath/a:408// - AddToBootstrapClassLoaderSearch during JVMTI OnLoad phase409_jdk_boot_class_path_append = new SystemProperty("jdk.boot.class.path.append", "", false, true);410411// Add to System Property list.412PropertyList_add(&_system_properties, _sun_boot_library_path);413PropertyList_add(&_system_properties, _java_library_path);414PropertyList_add(&_system_properties, _java_home);415PropertyList_add(&_system_properties, _java_class_path);416PropertyList_add(&_system_properties, _jdk_boot_class_path_append);417PropertyList_add(&_system_properties, _vm_info);418419// Set OS specific system properties values420os::init_system_properties_values();421}422423// Update/Initialize System properties after JDK version number is known424void Arguments::init_version_specific_system_properties() {425enum { bufsz = 16 };426char buffer[bufsz];427const char* spec_vendor = "Oracle Corporation";428uint32_t spec_version = JDK_Version::current().major_version();429430jio_snprintf(buffer, bufsz, UINT32_FORMAT, spec_version);431432PropertyList_add(&_system_properties,433new SystemProperty("java.vm.specification.vendor", spec_vendor, false));434PropertyList_add(&_system_properties,435new SystemProperty("java.vm.specification.version", buffer, false));436PropertyList_add(&_system_properties,437new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(), false));438}439440/*441* -XX argument processing:442*443* -XX arguments are defined in several places, such as:444* globals.hpp, globals_<cpu>.hpp, globals_<os>.hpp, <compiler>_globals.hpp, or <gc>_globals.hpp.445* -XX arguments are parsed in parse_argument().446* -XX argument bounds checking is done in check_vm_args_consistency().447*448* Over time -XX arguments may change. There are mechanisms to handle common cases:449*450* ALIASED: An option that is simply another name for another option. This is often451* part of the process of deprecating a flag, but not all aliases need452* to be deprecated.453*454* Create an alias for an option by adding the old and new option names to the455* "aliased_jvm_flags" table. Delete the old variable from globals.hpp (etc).456*457* DEPRECATED: An option that is supported, but a warning is printed to let the user know that458* support may be removed in the future. Both regular and aliased options may be459* deprecated.460*461* Add a deprecation warning for an option (or alias) by adding an entry in the462* "special_jvm_flags" table and setting the "deprecated_in" field.463* Often an option "deprecated" in one major release will464* be made "obsolete" in the next. In this case the entry should also have its465* "obsolete_in" field set.466*467* OBSOLETE: An option that has been removed (and deleted from globals.hpp), but is still accepted468* on the command line. A warning is printed to let the user know that option might not469* be accepted in the future.470*471* Add an obsolete warning for an option by adding an entry in the "special_jvm_flags"472* table and setting the "obsolete_in" field.473*474* EXPIRED: A deprecated or obsolete option that has an "accept_until" version less than or equal475* to the current JDK version. The system will flatly refuse to admit the existence of476* the flag. This allows a flag to die automatically over JDK releases.477*478* Note that manual cleanup of expired options should be done at major JDK version upgrades:479* - Newly expired options should be removed from the special_jvm_flags and aliased_jvm_flags tables.480* - Newly obsolete or expired deprecated options should have their global variable481* definitions removed (from globals.hpp, etc) and related implementations removed.482*483* Recommended approach for removing options:484*485* To remove options commonly used by customers (e.g. product -XX options), use486* the 3-step model adding major release numbers to the deprecate, obsolete and expire columns.487*488* To remove internal options (e.g. diagnostic, experimental, develop options), use489* a 2-step model adding major release numbers to the obsolete and expire columns.490*491* To change the name of an option, use the alias table as well as a 2-step492* model adding major release numbers to the deprecate and expire columns.493* Think twice about aliasing commonly used customer options.494*495* There are times when it is appropriate to leave a future release number as undefined.496*497* Tests: Aliases should be tested in VMAliasOptions.java.498* Deprecated options should be tested in VMDeprecatedOptions.java.499*/500501// The special_jvm_flags table declares options that are being deprecated and/or obsoleted. The502// "deprecated_in" or "obsolete_in" fields may be set to "undefined", but not both.503// When the JDK version reaches 'deprecated_in' limit, the JVM will process this flag on504// the command-line as usual, but will issue a warning.505// When the JDK version reaches 'obsolete_in' limit, the JVM will continue accepting this flag on506// the command-line, while issuing a warning and ignoring the flag value.507// Once the JDK version reaches 'expired_in' limit, the JVM will flatly refuse to admit the508// existence of the flag.509//510// MANUAL CLEANUP ON JDK VERSION UPDATES:511// This table ensures that the handling of options will update automatically when the JDK512// version is incremented, but the source code needs to be cleanup up manually:513// - As "deprecated" options age into "obsolete" or "expired" options, the associated "globals"514// variable should be removed, as well as users of the variable.515// - As "deprecated" options age into "obsolete" options, move the entry into the516// "Obsolete Flags" section of the table.517// - All expired options should be removed from the table.518static SpecialFlag const special_jvm_flags[] = {519// -------------- Deprecated Flags --------------520// --- Non-alias flags - sorted by obsolete_in then expired_in:521{ "MaxGCMinorPauseMillis", JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },522{ "MaxRAMFraction", JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },523{ "MinRAMFraction", JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },524{ "InitialRAMFraction", JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },525{ "AllowRedefinitionToAddDeleteMethods", JDK_Version::jdk(13), JDK_Version::undefined(), JDK_Version::undefined() },526{ "FlightRecorder", JDK_Version::jdk(13), JDK_Version::undefined(), JDK_Version::undefined() },527{ "SuspendRetryCount", JDK_Version::undefined(), JDK_Version::jdk(17), JDK_Version::jdk(18) },528{ "SuspendRetryDelay", JDK_Version::undefined(), JDK_Version::jdk(17), JDK_Version::jdk(18) },529{ "CriticalJNINatives", JDK_Version::jdk(16), JDK_Version::jdk(18), JDK_Version::jdk(19) },530{ "AlwaysLockClassLoader", JDK_Version::jdk(17), JDK_Version::jdk(18), JDK_Version::jdk(19) },531{ "UseBiasedLocking", JDK_Version::jdk(15), JDK_Version::jdk(18), JDK_Version::jdk(19) },532{ "BiasedLockingStartupDelay", JDK_Version::jdk(15), JDK_Version::jdk(18), JDK_Version::jdk(19) },533{ "PrintBiasedLockingStatistics", JDK_Version::jdk(15), JDK_Version::jdk(18), JDK_Version::jdk(19) },534{ "BiasedLockingBulkRebiasThreshold", JDK_Version::jdk(15), JDK_Version::jdk(18), JDK_Version::jdk(19) },535{ "BiasedLockingBulkRevokeThreshold", JDK_Version::jdk(15), JDK_Version::jdk(18), JDK_Version::jdk(19) },536{ "BiasedLockingDecayTime", JDK_Version::jdk(15), JDK_Version::jdk(18), JDK_Version::jdk(19) },537{ "UseOptoBiasInlining", JDK_Version::jdk(15), JDK_Version::jdk(18), JDK_Version::jdk(19) },538{ "PrintPreciseBiasedLockingStatistics", JDK_Version::jdk(15), JDK_Version::jdk(18), JDK_Version::jdk(19) },539540// --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in:541{ "DefaultMaxRAMFraction", JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },542{ "CreateMinidumpOnCrash", JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },543{ "TLABStats", JDK_Version::jdk(12), JDK_Version::undefined(), JDK_Version::undefined() },544545// -------------- Obsolete Flags - sorted by expired_in --------------546{ "AssertOnSuspendWaitFailure", JDK_Version::undefined(), JDK_Version::jdk(17), JDK_Version::jdk(18) },547{ "TraceSuspendWaitFailures", JDK_Version::undefined(), JDK_Version::jdk(17), JDK_Version::jdk(18) },548#ifdef ASSERT549{ "DummyObsoleteTestFlag", JDK_Version::undefined(), JDK_Version::jdk(17), JDK_Version::undefined() },550#endif551552#ifdef TEST_VERIFY_SPECIAL_JVM_FLAGS553// These entries will generate build errors. Their purpose is to test the macros.554{ "dep > obs", JDK_Version::jdk(9), JDK_Version::jdk(8), JDK_Version::undefined() },555{ "dep > exp ", JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(8) },556{ "obs > exp ", JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(8) },557{ "obs > exp", JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::jdk(10) },558{ "not deprecated or obsolete", JDK_Version::undefined(), JDK_Version::undefined(), JDK_Version::jdk(9) },559{ "dup option", JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },560{ "dup option", JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },561#endif562563{ NULL, JDK_Version(0), JDK_Version(0) }564};565566// Flags that are aliases for other flags.567typedef struct {568const char* alias_name;569const char* real_name;570} AliasedFlag;571572static AliasedFlag const aliased_jvm_flags[] = {573{ "DefaultMaxRAMFraction", "MaxRAMFraction" },574{ "CreateMinidumpOnCrash", "CreateCoredumpOnCrash" },575{ NULL, NULL}576};577578// Return true if "v" is less than "other", where "other" may be "undefined".579static bool version_less_than(JDK_Version v, JDK_Version other) {580assert(!v.is_undefined(), "must be defined");581if (!other.is_undefined() && v.compare(other) >= 0) {582return false;583} else {584return true;585}586}587588static bool lookup_special_flag(const char *flag_name, SpecialFlag& flag) {589for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {590if ((strcmp(special_jvm_flags[i].name, flag_name) == 0)) {591flag = special_jvm_flags[i];592return true;593}594}595return false;596}597598bool Arguments::is_obsolete_flag(const char *flag_name, JDK_Version* version) {599assert(version != NULL, "Must provide a version buffer");600SpecialFlag flag;601if (lookup_special_flag(flag_name, flag)) {602if (!flag.obsolete_in.is_undefined()) {603if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {604*version = flag.obsolete_in;605// This flag may have been marked for obsoletion in this version, but we may not606// have actually removed it yet. Rather than ignoring it as soon as we reach607// this version we allow some time for the removal to happen. So if the flag608// still actually exists we process it as normal, but issue an adjusted warning.609const JVMFlag *real_flag = JVMFlag::find_declared_flag(flag_name);610if (real_flag != NULL) {611char version_str[256];612version->to_string(version_str, sizeof(version_str));613warning("Temporarily processing option %s; support is scheduled for removal in %s",614flag_name, version_str);615return false;616}617return true;618}619}620}621return false;622}623624int Arguments::is_deprecated_flag(const char *flag_name, JDK_Version* version) {625assert(version != NULL, "Must provide a version buffer");626SpecialFlag flag;627if (lookup_special_flag(flag_name, flag)) {628if (!flag.deprecated_in.is_undefined()) {629if (version_less_than(JDK_Version::current(), flag.obsolete_in) &&630version_less_than(JDK_Version::current(), flag.expired_in)) {631*version = flag.deprecated_in;632return 1;633} else {634return -1;635}636}637}638return 0;639}640641const char* Arguments::real_flag_name(const char *flag_name) {642for (size_t i = 0; aliased_jvm_flags[i].alias_name != NULL; i++) {643const AliasedFlag& flag_status = aliased_jvm_flags[i];644if (strcmp(flag_status.alias_name, flag_name) == 0) {645return flag_status.real_name;646}647}648return flag_name;649}650651#ifdef ASSERT652static bool lookup_special_flag(const char *flag_name, size_t skip_index) {653for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {654if ((i != skip_index) && (strcmp(special_jvm_flags[i].name, flag_name) == 0)) {655return true;656}657}658return false;659}660661// Verifies the correctness of the entries in the special_jvm_flags table.662// If there is a semantic error (i.e. a bug in the table) such as the obsoletion663// version being earlier than the deprecation version, then a warning is issued664// and verification fails - by returning false. If it is detected that the table665// is out of date, with respect to the current version, then ideally a warning is666// issued but verification does not fail. This allows the VM to operate when the667// version is first updated, without needing to update all the impacted flags at668// the same time. In practice we can't issue the warning immediately when the version669// is updated as it occurs for every test and some tests are not prepared to handle670// unexpected output - see 8196739. Instead we only check if the table is up-to-date671// if the check_globals flag is true, and in addition allow a grace period and only672// check for stale flags when we hit build 25 (which is far enough into the 6 month673// release cycle that all flag updates should have been processed, whilst still674// leaving time to make the change before RDP2).675// We use a gtest to call this, passing true, so that we can detect stale flags before676// the end of the release cycle.677678static const int SPECIAL_FLAG_VALIDATION_BUILD = 25;679680bool Arguments::verify_special_jvm_flags(bool check_globals) {681bool success = true;682for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {683const SpecialFlag& flag = special_jvm_flags[i];684if (lookup_special_flag(flag.name, i)) {685warning("Duplicate special flag declaration \"%s\"", flag.name);686success = false;687}688if (flag.deprecated_in.is_undefined() &&689flag.obsolete_in.is_undefined()) {690warning("Special flag entry \"%s\" must declare version deprecated and/or obsoleted in.", flag.name);691success = false;692}693694if (!flag.deprecated_in.is_undefined()) {695if (!version_less_than(flag.deprecated_in, flag.obsolete_in)) {696warning("Special flag entry \"%s\" must be deprecated before obsoleted.", flag.name);697success = false;698}699700if (!version_less_than(flag.deprecated_in, flag.expired_in)) {701warning("Special flag entry \"%s\" must be deprecated before expired.", flag.name);702success = false;703}704}705706if (!flag.obsolete_in.is_undefined()) {707if (!version_less_than(flag.obsolete_in, flag.expired_in)) {708warning("Special flag entry \"%s\" must be obsoleted before expired.", flag.name);709success = false;710}711712// if flag has become obsolete it should not have a "globals" flag defined anymore.713if (check_globals && VM_Version::vm_build_number() >= SPECIAL_FLAG_VALIDATION_BUILD &&714!version_less_than(JDK_Version::current(), flag.obsolete_in)) {715if (JVMFlag::find_declared_flag(flag.name) != NULL) {716warning("Global variable for obsolete special flag entry \"%s\" should be removed", flag.name);717success = false;718}719}720721} else if (!flag.expired_in.is_undefined()) {722warning("Special flag entry \"%s\" must be explicitly obsoleted before expired.", flag.name);723success = false;724}725726if (!flag.expired_in.is_undefined()) {727// if flag has become expired it should not have a "globals" flag defined anymore.728if (check_globals && VM_Version::vm_build_number() >= SPECIAL_FLAG_VALIDATION_BUILD &&729!version_less_than(JDK_Version::current(), flag.expired_in)) {730if (JVMFlag::find_declared_flag(flag.name) != NULL) {731warning("Global variable for expired flag entry \"%s\" should be removed", flag.name);732success = false;733}734}735}736}737return success;738}739#endif740741// Parses a size specification string.742bool Arguments::atojulong(const char *s, julong* result) {743julong n = 0;744745// First char must be a digit. Don't allow negative numbers or leading spaces.746if (!isdigit(*s)) {747return false;748}749750bool is_hex = (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'));751char* remainder;752errno = 0;753n = strtoull(s, &remainder, (is_hex ? 16 : 10));754if (errno != 0) {755return false;756}757758// Fail if no number was read at all or if the remainder contains more than a single non-digit character.759if (remainder == s || strlen(remainder) > 1) {760return false;761}762763switch (*remainder) {764case 'T': case 't':765*result = n * G * K;766// Check for overflow.767if (*result/((julong)G * K) != n) return false;768return true;769case 'G': case 'g':770*result = n * G;771if (*result/G != n) return false;772return true;773case 'M': case 'm':774*result = n * M;775if (*result/M != n) return false;776return true;777case 'K': case 'k':778*result = n * K;779if (*result/K != n) return false;780return true;781case '\0':782*result = n;783return true;784default:785return false;786}787}788789Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size, julong max_size) {790if (size < min_size) return arg_too_small;791if (size > max_size) return arg_too_big;792return arg_in_range;793}794795// Describe an argument out of range error796void Arguments::describe_range_error(ArgsRange errcode) {797switch(errcode) {798case arg_too_big:799jio_fprintf(defaultStream::error_stream(),800"The specified size exceeds the maximum "801"representable size.\n");802break;803case arg_too_small:804case arg_unreadable:805case arg_in_range:806// do nothing for now807break;808default:809ShouldNotReachHere();810}811}812813static bool set_bool_flag(JVMFlag* flag, bool value, JVMFlagOrigin origin) {814if (JVMFlagAccess::set_bool(flag, &value, origin) == JVMFlag::SUCCESS) {815return true;816} else {817return false;818}819}820821static bool set_fp_numeric_flag(JVMFlag* flag, char* value, JVMFlagOrigin origin) {822char* end;823errno = 0;824double v = strtod(value, &end);825if ((errno != 0) || (*end != 0)) {826return false;827}828829if (JVMFlagAccess::set_double(flag, &v, origin) == JVMFlag::SUCCESS) {830return true;831}832return false;833}834835static bool set_numeric_flag(JVMFlag* flag, char* value, JVMFlagOrigin origin) {836julong v;837int int_v;838intx intx_v;839bool is_neg = false;840841if (flag == NULL) {842return false;843}844845// Check the sign first since atojulong() parses only unsigned values.846if (*value == '-') {847if (!flag->is_intx() && !flag->is_int()) {848return false;849}850value++;851is_neg = true;852}853if (!Arguments::atojulong(value, &v)) {854return false;855}856if (flag->is_int()) {857int_v = (int) v;858if (is_neg) {859int_v = -int_v;860}861return JVMFlagAccess::set_int(flag, &int_v, origin) == JVMFlag::SUCCESS;862} else if (flag->is_uint()) {863uint uint_v = (uint) v;864return JVMFlagAccess::set_uint(flag, &uint_v, origin) == JVMFlag::SUCCESS;865} else if (flag->is_intx()) {866intx_v = (intx) v;867if (is_neg) {868intx_v = -intx_v;869}870return JVMFlagAccess::set_intx(flag, &intx_v, origin) == JVMFlag::SUCCESS;871} else if (flag->is_uintx()) {872uintx uintx_v = (uintx) v;873return JVMFlagAccess::set_uintx(flag, &uintx_v, origin) == JVMFlag::SUCCESS;874} else if (flag->is_uint64_t()) {875uint64_t uint64_t_v = (uint64_t) v;876return JVMFlagAccess::set_uint64_t(flag, &uint64_t_v, origin) == JVMFlag::SUCCESS;877} else if (flag->is_size_t()) {878size_t size_t_v = (size_t) v;879return JVMFlagAccess::set_size_t(flag, &size_t_v, origin) == JVMFlag::SUCCESS;880} else if (flag->is_double()) {881double double_v = (double) v;882return JVMFlagAccess::set_double(flag, &double_v, origin) == JVMFlag::SUCCESS;883} else {884return false;885}886}887888static bool set_string_flag(JVMFlag* flag, const char* value, JVMFlagOrigin origin) {889if (JVMFlagAccess::set_ccstr(flag, &value, origin) != JVMFlag::SUCCESS) return false;890// Contract: JVMFlag always returns a pointer that needs freeing.891FREE_C_HEAP_ARRAY(char, value);892return true;893}894895static bool append_to_string_flag(JVMFlag* flag, const char* new_value, JVMFlagOrigin origin) {896const char* old_value = "";897if (JVMFlagAccess::get_ccstr(flag, &old_value) != JVMFlag::SUCCESS) return false;898size_t old_len = old_value != NULL ? strlen(old_value) : 0;899size_t new_len = strlen(new_value);900const char* value;901char* free_this_too = NULL;902if (old_len == 0) {903value = new_value;904} else if (new_len == 0) {905value = old_value;906} else {907size_t length = old_len + 1 + new_len + 1;908char* buf = NEW_C_HEAP_ARRAY(char, length, mtArguments);909// each new setting adds another LINE to the switch:910jio_snprintf(buf, length, "%s\n%s", old_value, new_value);911value = buf;912free_this_too = buf;913}914(void) JVMFlagAccess::set_ccstr(flag, &value, origin);915// JVMFlag always returns a pointer that needs freeing.916FREE_C_HEAP_ARRAY(char, value);917// JVMFlag made its own copy, so I must delete my own temp. buffer.918FREE_C_HEAP_ARRAY(char, free_this_too);919return true;920}921922const char* Arguments::handle_aliases_and_deprecation(const char* arg, bool warn) {923const char* real_name = real_flag_name(arg);924JDK_Version since = JDK_Version();925switch (is_deprecated_flag(arg, &since)) {926case -1: {927// Obsolete or expired, so don't process normally,928// but allow for an obsolete flag we're still929// temporarily allowing.930if (!is_obsolete_flag(arg, &since)) {931return real_name;932}933// Note if we're not considered obsolete then we can't be expired either934// as obsoletion must come first.935return NULL;936}937case 0:938return real_name;939case 1: {940if (warn) {941char version[256];942since.to_string(version, sizeof(version));943if (real_name != arg) {944warning("Option %s was deprecated in version %s and will likely be removed in a future release. Use option %s instead.",945arg, version, real_name);946} else {947warning("Option %s was deprecated in version %s and will likely be removed in a future release.",948arg, version);949}950}951return real_name;952}953}954ShouldNotReachHere();955return NULL;956}957958bool Arguments::parse_argument(const char* arg, JVMFlagOrigin origin) {959960// range of acceptable characters spelled out for portability reasons961#define NAME_RANGE "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"962#define BUFLEN 255963char name[BUFLEN+1];964char dummy;965const char* real_name;966bool warn_if_deprecated = true;967968if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {969real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);970if (real_name == NULL) {971return false;972}973JVMFlag* flag = JVMFlag::find_flag(real_name);974return set_bool_flag(flag, false, origin);975}976if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {977real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);978if (real_name == NULL) {979return false;980}981JVMFlag* flag = JVMFlag::find_flag(real_name);982return set_bool_flag(flag, true, origin);983}984985char punct;986if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {987const char* value = strchr(arg, '=') + 1;988989// this scanf pattern matches both strings (handled here) and numbers (handled later))990real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);991if (real_name == NULL) {992return false;993}994JVMFlag* flag = JVMFlag::find_flag(real_name);995if (flag != NULL && flag->is_ccstr()) {996if (flag->ccstr_accumulates()) {997return append_to_string_flag(flag, value, origin);998} else {999if (value[0] == '\0') {1000value = NULL;1001}1002return set_string_flag(flag, value, origin);1003}1004} else {1005warn_if_deprecated = false; // if arg is deprecated, we've already done warning...1006}1007}10081009if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {1010const char* value = strchr(arg, '=') + 1;1011// -XX:Foo:=xxx will reset the string flag to the given value.1012if (value[0] == '\0') {1013value = NULL;1014}1015real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);1016if (real_name == NULL) {1017return false;1018}1019JVMFlag* flag = JVMFlag::find_flag(real_name);1020return set_string_flag(flag, value, origin);1021}10221023#define SIGNED_FP_NUMBER_RANGE "[-0123456789.eE+]"1024#define SIGNED_NUMBER_RANGE "[-0123456789]"1025#define NUMBER_RANGE "[0123456789eE+-]"1026char value[BUFLEN + 1];1027char value2[BUFLEN + 1];1028if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {1029// Looks like a floating-point number -- try again with more lenient format string1030if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {1031real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);1032if (real_name == NULL) {1033return false;1034}1035JVMFlag* flag = JVMFlag::find_flag(real_name);1036return set_fp_numeric_flag(flag, value, origin);1037}1038}10391040#define VALUE_RANGE "[-kmgtxKMGTX0123456789abcdefABCDEF]"1041if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {1042real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);1043if (real_name == NULL) {1044return false;1045}1046JVMFlag* flag = JVMFlag::find_flag(real_name);1047return set_numeric_flag(flag, value, origin);1048}10491050return false;1051}10521053void Arguments::add_string(char*** bldarray, int* count, const char* arg) {1054assert(bldarray != NULL, "illegal argument");10551056if (arg == NULL) {1057return;1058}10591060int new_count = *count + 1;10611062// expand the array and add arg to the last element1063if (*bldarray == NULL) {1064*bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtArguments);1065} else {1066*bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtArguments);1067}1068(*bldarray)[*count] = os::strdup_check_oom(arg);1069*count = new_count;1070}10711072void Arguments::build_jvm_args(const char* arg) {1073add_string(&_jvm_args_array, &_num_jvm_args, arg);1074}10751076void Arguments::build_jvm_flags(const char* arg) {1077add_string(&_jvm_flags_array, &_num_jvm_flags, arg);1078}10791080// utility function to return a string that concatenates all1081// strings in a given char** array1082const char* Arguments::build_resource_string(char** args, int count) {1083if (args == NULL || count == 0) {1084return NULL;1085}1086size_t length = 0;1087for (int i = 0; i < count; i++) {1088length += strlen(args[i]) + 1; // add 1 for a space or NULL terminating character1089}1090char* s = NEW_RESOURCE_ARRAY(char, length);1091char* dst = s;1092for (int j = 0; j < count; j++) {1093size_t offset = strlen(args[j]) + 1; // add 1 for a space or NULL terminating character1094jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with NULL character1095dst += offset;1096length -= offset;1097}1098return (const char*) s;1099}11001101void Arguments::print_on(outputStream* st) {1102st->print_cr("VM Arguments:");1103if (num_jvm_flags() > 0) {1104st->print("jvm_flags: "); print_jvm_flags_on(st);1105st->cr();1106}1107if (num_jvm_args() > 0) {1108st->print("jvm_args: "); print_jvm_args_on(st);1109st->cr();1110}1111st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");1112if (_java_class_path != NULL) {1113char* path = _java_class_path->value();1114st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );1115}1116st->print_cr("Launcher Type: %s", _sun_java_launcher);1117}11181119void Arguments::print_summary_on(outputStream* st) {1120// Print the command line. Environment variables that are helpful for1121// reproducing the problem are written later in the hs_err file.1122// flags are from setting file1123if (num_jvm_flags() > 0) {1124st->print_raw("Settings File: ");1125print_jvm_flags_on(st);1126st->cr();1127}1128// args are the command line and environment variable arguments.1129st->print_raw("Command Line: ");1130if (num_jvm_args() > 0) {1131print_jvm_args_on(st);1132}1133// this is the classfile and any arguments to the java program1134if (java_command() != NULL) {1135st->print("%s", java_command());1136}1137st->cr();1138}11391140void Arguments::print_jvm_flags_on(outputStream* st) {1141if (_num_jvm_flags > 0) {1142for (int i=0; i < _num_jvm_flags; i++) {1143st->print("%s ", _jvm_flags_array[i]);1144}1145}1146}11471148void Arguments::print_jvm_args_on(outputStream* st) {1149if (_num_jvm_args > 0) {1150for (int i=0; i < _num_jvm_args; i++) {1151st->print("%s ", _jvm_args_array[i]);1152}1153}1154}11551156bool Arguments::process_argument(const char* arg,1157jboolean ignore_unrecognized,1158JVMFlagOrigin origin) {1159JDK_Version since = JDK_Version();11601161if (parse_argument(arg, origin)) {1162return true;1163}11641165// Determine if the flag has '+', '-', or '=' characters.1166bool has_plus_minus = (*arg == '+' || *arg == '-');1167const char* const argname = has_plus_minus ? arg + 1 : arg;11681169size_t arg_len;1170const char* equal_sign = strchr(argname, '=');1171if (equal_sign == NULL) {1172arg_len = strlen(argname);1173} else {1174arg_len = equal_sign - argname;1175}11761177// Only make the obsolete check for valid arguments.1178if (arg_len <= BUFLEN) {1179// Construct a string which consists only of the argument name without '+', '-', or '='.1180char stripped_argname[BUFLEN+1]; // +1 for '\0'1181jio_snprintf(stripped_argname, arg_len+1, "%s", argname); // +1 for '\0'1182if (is_obsolete_flag(stripped_argname, &since)) {1183char version[256];1184since.to_string(version, sizeof(version));1185warning("Ignoring option %s; support was removed in %s", stripped_argname, version);1186return true;1187}1188}11891190// For locked flags, report a custom error message if available.1191// Otherwise, report the standard unrecognized VM option.1192const JVMFlag* found_flag = JVMFlag::find_declared_flag((const char*)argname, arg_len);1193if (found_flag != NULL) {1194char locked_message_buf[BUFLEN];1195JVMFlag::MsgType msg_type = found_flag->get_locked_message(locked_message_buf, BUFLEN);1196if (strlen(locked_message_buf) == 0) {1197if (found_flag->is_bool() && !has_plus_minus) {1198jio_fprintf(defaultStream::error_stream(),1199"Missing +/- setting for VM option '%s'\n", argname);1200} else if (!found_flag->is_bool() && has_plus_minus) {1201jio_fprintf(defaultStream::error_stream(),1202"Unexpected +/- setting in VM option '%s'\n", argname);1203} else {1204jio_fprintf(defaultStream::error_stream(),1205"Improperly specified VM option '%s'\n", argname);1206}1207} else {1208#ifdef PRODUCT1209bool mismatched = ((msg_type == JVMFlag::NOTPRODUCT_FLAG_BUT_PRODUCT_BUILD) ||1210(msg_type == JVMFlag::DEVELOPER_FLAG_BUT_PRODUCT_BUILD));1211if (ignore_unrecognized && mismatched) {1212return true;1213}1214#endif1215jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);1216}1217} else {1218if (ignore_unrecognized) {1219return true;1220}1221jio_fprintf(defaultStream::error_stream(),1222"Unrecognized VM option '%s'\n", argname);1223JVMFlag* fuzzy_matched = JVMFlag::fuzzy_match((const char*)argname, arg_len, true);1224if (fuzzy_matched != NULL) {1225jio_fprintf(defaultStream::error_stream(),1226"Did you mean '%s%s%s'? ",1227(fuzzy_matched->is_bool()) ? "(+/-)" : "",1228fuzzy_matched->name(),1229(fuzzy_matched->is_bool()) ? "" : "=<value>");1230}1231}12321233// allow for commandline "commenting out" options like -XX:#+Verbose1234return arg[0] == '#';1235}12361237bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {1238FILE* stream = fopen(file_name, "rb");1239if (stream == NULL) {1240if (should_exist) {1241jio_fprintf(defaultStream::error_stream(),1242"Could not open settings file %s\n", file_name);1243return false;1244} else {1245return true;1246}1247}12481249char token[1024];1250int pos = 0;12511252bool in_white_space = true;1253bool in_comment = false;1254bool in_quote = false;1255char quote_c = 0;1256bool result = true;12571258int c = getc(stream);1259while(c != EOF && pos < (int)(sizeof(token)-1)) {1260if (in_white_space) {1261if (in_comment) {1262if (c == '\n') in_comment = false;1263} else {1264if (c == '#') in_comment = true;1265else if (!isspace(c)) {1266in_white_space = false;1267token[pos++] = c;1268}1269}1270} else {1271if (c == '\n' || (!in_quote && isspace(c))) {1272// token ends at newline, or at unquoted whitespace1273// this allows a way to include spaces in string-valued options1274token[pos] = '\0';1275logOption(token);1276result &= process_argument(token, ignore_unrecognized, JVMFlagOrigin::CONFIG_FILE);1277build_jvm_flags(token);1278pos = 0;1279in_white_space = true;1280in_quote = false;1281} else if (!in_quote && (c == '\'' || c == '"')) {1282in_quote = true;1283quote_c = c;1284} else if (in_quote && (c == quote_c)) {1285in_quote = false;1286} else {1287token[pos++] = c;1288}1289}1290c = getc(stream);1291}1292if (pos > 0) {1293token[pos] = '\0';1294result &= process_argument(token, ignore_unrecognized, JVMFlagOrigin::CONFIG_FILE);1295build_jvm_flags(token);1296}1297fclose(stream);1298return result;1299}13001301//=============================================================================================================1302// Parsing of properties (-D)13031304const char* Arguments::get_property(const char* key) {1305return PropertyList_get_value(system_properties(), key);1306}13071308bool Arguments::add_property(const char* prop, PropertyWriteable writeable, PropertyInternal internal) {1309const char* eq = strchr(prop, '=');1310const char* key;1311const char* value = "";13121313if (eq == NULL) {1314// property doesn't have a value, thus use passed string1315key = prop;1316} else {1317// property have a value, thus extract it and save to the1318// allocated string1319size_t key_len = eq - prop;1320char* tmp_key = AllocateHeap(key_len + 1, mtArguments);13211322jio_snprintf(tmp_key, key_len + 1, "%s", prop);1323key = tmp_key;13241325value = &prop[key_len + 1];1326}13271328#if INCLUDE_CDS1329if (is_internal_module_property(key) ||1330strcmp(key, "jdk.module.main") == 0) {1331MetaspaceShared::disable_optimized_module_handling();1332log_info(cds)("optimized module handling: disabled due to incompatible property: %s=%s", key, value);1333}1334if (strcmp(key, "jdk.module.showModuleResolution") == 0 ||1335strcmp(key, "jdk.module.validation") == 0 ||1336strcmp(key, "java.system.class.loader") == 0) {1337MetaspaceShared::disable_full_module_graph();1338log_info(cds)("full module graph: disabled due to incompatible property: %s=%s", key, value);1339}1340#endif13411342if (strcmp(key, "java.compiler") == 0) {1343process_java_compiler_argument(value);1344// Record value in Arguments, but let it get passed to Java.1345} else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0) {1346// sun.java.launcher.is_altjvm property is1347// private and is processed in process_sun_java_launcher_properties();1348// the sun.java.launcher property is passed on to the java application1349} else if (strcmp(key, "sun.boot.library.path") == 0) {1350// append is true, writable is true, internal is false1351PropertyList_unique_add(&_system_properties, key, value, AppendProperty,1352WriteableProperty, ExternalProperty);1353} else {1354if (strcmp(key, "sun.java.command") == 0) {1355char *old_java_command = _java_command;1356_java_command = os::strdup_check_oom(value, mtArguments);1357if (old_java_command != NULL) {1358os::free(old_java_command);1359}1360} else if (strcmp(key, "java.vendor.url.bug") == 0) {1361// If this property is set on the command line then its value will be1362// displayed in VM error logs as the URL at which to submit such logs.1363// Normally the URL displayed in error logs is different from the value1364// of this system property, so a different property should have been1365// used here, but we leave this as-is in case someone depends upon it.1366const char* old_java_vendor_url_bug = _java_vendor_url_bug;1367// save it in _java_vendor_url_bug, so JVM fatal error handler can access1368// its value without going through the property list or making a Java call.1369_java_vendor_url_bug = os::strdup_check_oom(value, mtArguments);1370if (old_java_vendor_url_bug != NULL) {1371os::free((void *)old_java_vendor_url_bug);1372}1373}13741375// Create new property and add at the end of the list1376PropertyList_unique_add(&_system_properties, key, value, AddProperty, writeable, internal);1377}13781379if (key != prop) {1380// SystemProperty copy passed value, thus free previously allocated1381// memory1382FreeHeap((void *)key);1383}13841385return true;1386}13871388#if INCLUDE_CDS1389const char* unsupported_properties[] = { "jdk.module.limitmods",1390"jdk.module.upgrade.path",1391"jdk.module.patch.0" };1392const char* unsupported_options[] = { "--limit-modules",1393"--upgrade-module-path",1394"--patch-module"1395};1396void Arguments::check_unsupported_dumping_properties() {1397assert(is_dumping_archive(),1398"this function is only used with CDS dump time");1399assert(ARRAY_SIZE(unsupported_properties) == ARRAY_SIZE(unsupported_options), "must be");1400// If a vm option is found in the unsupported_options array, vm will exit with an error message.1401SystemProperty* sp = system_properties();1402while (sp != NULL) {1403for (uint i = 0; i < ARRAY_SIZE(unsupported_properties); i++) {1404if (strcmp(sp->key(), unsupported_properties[i]) == 0) {1405vm_exit_during_initialization(1406"Cannot use the following option when dumping the shared archive", unsupported_options[i]);1407}1408}1409sp = sp->next();1410}14111412// Check for an exploded module build in use with -Xshare:dump.1413if (!has_jimage()) {1414vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");1415}1416}14171418bool Arguments::check_unsupported_cds_runtime_properties() {1419assert(UseSharedSpaces, "this function is only used with -Xshare:{on,auto}");1420assert(ARRAY_SIZE(unsupported_properties) == ARRAY_SIZE(unsupported_options), "must be");1421if (ArchiveClassesAtExit != NULL) {1422// dynamic dumping, just return false for now.1423// check_unsupported_dumping_properties() will be called later to check the same set of1424// properties, and will exit the VM with the correct error message if the unsupported properties1425// are used.1426return false;1427}1428for (uint i = 0; i < ARRAY_SIZE(unsupported_properties); i++) {1429if (get_property(unsupported_properties[i]) != NULL) {1430if (RequireSharedSpaces) {1431warning("CDS is disabled when the %s option is specified.", unsupported_options[i]);1432}1433return true;1434}1435}1436return false;1437}1438#endif14391440//===========================================================================================================1441// Setting int/mixed/comp mode flags14421443void Arguments::set_mode_flags(Mode mode) {1444// Set up default values for all flags.1445// If you add a flag to any of the branches below,1446// add a default value for it here.1447set_java_compiler(false);1448_mode = mode;14491450// Ensure Agent_OnLoad has the correct initial values.1451// This may not be the final mode; mode may change later in onload phase.1452PropertyList_unique_add(&_system_properties, "java.vm.info",1453VM_Version::vm_info_string(), AddProperty, UnwriteableProperty, ExternalProperty);14541455UseInterpreter = true;1456UseCompiler = true;1457UseLoopCounter = true;14581459// Default values may be platform/compiler dependent -1460// use the saved values1461ClipInlining = Arguments::_ClipInlining;1462AlwaysCompileLoopMethods = Arguments::_AlwaysCompileLoopMethods;1463UseOnStackReplacement = Arguments::_UseOnStackReplacement;1464BackgroundCompilation = Arguments::_BackgroundCompilation;14651466// Change from defaults based on mode1467switch (mode) {1468default:1469ShouldNotReachHere();1470break;1471case _int:1472UseCompiler = false;1473UseLoopCounter = false;1474AlwaysCompileLoopMethods = false;1475UseOnStackReplacement = false;1476break;1477case _mixed:1478// same as default1479break;1480case _comp:1481UseInterpreter = false;1482BackgroundCompilation = false;1483ClipInlining = false;1484break;1485}1486}14871488// Conflict: required to use shared spaces (-Xshare:on), but1489// incompatible command line options were chosen.1490static void no_shared_spaces(const char* message) {1491if (RequireSharedSpaces) {1492jio_fprintf(defaultStream::error_stream(),1493"Class data sharing is inconsistent with other specified options.\n");1494vm_exit_during_initialization("Unable to use shared archive", message);1495} else {1496log_info(cds)("Unable to use shared archive: %s", message);1497FLAG_SET_DEFAULT(UseSharedSpaces, false);1498}1499}15001501void set_object_alignment() {1502// Object alignment.1503assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");1504MinObjAlignmentInBytes = ObjectAlignmentInBytes;1505assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");1506MinObjAlignment = MinObjAlignmentInBytes / HeapWordSize;1507assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");1508MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;15091510LogMinObjAlignmentInBytes = exact_log2(ObjectAlignmentInBytes);1511LogMinObjAlignment = LogMinObjAlignmentInBytes - LogHeapWordSize;15121513// Oop encoding heap max1514OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;1515}15161517size_t Arguments::max_heap_for_compressed_oops() {1518// Avoid sign flip.1519assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");1520// We need to fit both the NULL page and the heap into the memory budget, while1521// keeping alignment constraints of the heap. To guarantee the latter, as the1522// NULL page is located before the heap, we pad the NULL page to the conservative1523// maximum alignment that the GC may ever impose upon the heap.1524size_t displacement_due_to_null_page = align_up((size_t)os::vm_page_size(),1525_conservative_max_heap_alignment);15261527LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);1528NOT_LP64(ShouldNotReachHere(); return 0);1529}15301531void Arguments::set_use_compressed_oops() {1532#ifdef _LP641533// MaxHeapSize is not set up properly at this point, but1534// the only value that can override MaxHeapSize if we are1535// to use UseCompressedOops are InitialHeapSize and MinHeapSize.1536size_t max_heap_size = MAX3(MaxHeapSize, InitialHeapSize, MinHeapSize);15371538if (max_heap_size <= max_heap_for_compressed_oops()) {1539if (FLAG_IS_DEFAULT(UseCompressedOops)) {1540FLAG_SET_ERGO(UseCompressedOops, true);1541}1542} else {1543if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {1544warning("Max heap size too large for Compressed Oops");1545FLAG_SET_DEFAULT(UseCompressedOops, false);1546if (COMPRESSED_CLASS_POINTERS_DEPENDS_ON_COMPRESSED_OOPS) {1547FLAG_SET_DEFAULT(UseCompressedClassPointers, false);1548}1549}1550}1551#endif // _LP641552}155315541555// NOTE: set_use_compressed_klass_ptrs() must be called after calling1556// set_use_compressed_oops().1557void Arguments::set_use_compressed_klass_ptrs() {1558#ifdef _LP641559// On some architectures, the use of UseCompressedClassPointers implies the use of1560// UseCompressedOops. The reason is that the rheap_base register of said platforms1561// is reused to perform some optimized spilling, in order to use rheap_base as a1562// temp register. But by treating it as any other temp register, spilling can typically1563// be completely avoided instead. So it is better not to perform this trick. And by1564// not having that reliance, large heaps, or heaps not supporting compressed oops,1565// can still use compressed class pointers.1566if (COMPRESSED_CLASS_POINTERS_DEPENDS_ON_COMPRESSED_OOPS && !UseCompressedOops) {1567if (UseCompressedClassPointers) {1568warning("UseCompressedClassPointers requires UseCompressedOops");1569}1570FLAG_SET_DEFAULT(UseCompressedClassPointers, false);1571} else {1572// Turn on UseCompressedClassPointers too1573if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {1574FLAG_SET_ERGO(UseCompressedClassPointers, true);1575}1576// Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.1577if (UseCompressedClassPointers) {1578if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {1579warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");1580FLAG_SET_DEFAULT(UseCompressedClassPointers, false);1581}1582}1583}1584#endif // _LP641585}15861587void Arguments::set_conservative_max_heap_alignment() {1588// The conservative maximum required alignment for the heap is the maximum of1589// the alignments imposed by several sources: any requirements from the heap1590// itself and the maximum page size we may run the VM with.1591size_t heap_alignment = GCConfig::arguments()->conservative_max_heap_alignment();1592_conservative_max_heap_alignment = MAX4(heap_alignment,1593(size_t)os::vm_allocation_granularity(),1594os::max_page_size(),1595GCArguments::compute_heap_alignment());1596}15971598jint Arguments::set_ergonomics_flags() {1599GCConfig::initialize();16001601set_conservative_max_heap_alignment();16021603#ifdef _LP641604set_use_compressed_oops();16051606// set_use_compressed_klass_ptrs() must be called after calling1607// set_use_compressed_oops().1608set_use_compressed_klass_ptrs();16091610// Also checks that certain machines are slower with compressed oops1611// in vm_version initialization code.1612#endif // _LP6416131614return JNI_OK;1615}16161617size_t Arguments::limit_heap_by_allocatable_memory(size_t limit) {1618size_t max_allocatable;1619size_t result = limit;1620if (os::has_allocatable_memory_limit(&max_allocatable)) {1621// The AggressiveHeap check is a temporary workaround to avoid calling1622// GCarguments::heap_virtual_to_physical_ratio() before a GC has been1623// selected. This works because AggressiveHeap implies UseParallelGC1624// where we know the ratio will be 1. Once the AggressiveHeap option is1625// removed, this can be cleaned up.1626size_t heap_virtual_to_physical_ratio = (AggressiveHeap ? 1 : GCConfig::arguments()->heap_virtual_to_physical_ratio());1627size_t fraction = MaxVirtMemFraction * heap_virtual_to_physical_ratio;1628result = MIN2(result, max_allocatable / fraction);1629}1630return result;1631}16321633// Use static initialization to get the default before parsing1634static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;16351636void Arguments::set_heap_size() {1637julong phys_mem;16381639// If the user specified one of these options, they1640// want specific memory sizing so do not limit memory1641// based on compressed oops addressability.1642// Also, memory limits will be calculated based on1643// available os physical memory, not our MaxRAM limit,1644// unless MaxRAM is also specified.1645bool override_coop_limit = (!FLAG_IS_DEFAULT(MaxRAMPercentage) ||1646!FLAG_IS_DEFAULT(MaxRAMFraction) ||1647!FLAG_IS_DEFAULT(MinRAMPercentage) ||1648!FLAG_IS_DEFAULT(MinRAMFraction) ||1649!FLAG_IS_DEFAULT(InitialRAMPercentage) ||1650!FLAG_IS_DEFAULT(InitialRAMFraction) ||1651!FLAG_IS_DEFAULT(MaxRAM));1652if (override_coop_limit) {1653if (FLAG_IS_DEFAULT(MaxRAM)) {1654phys_mem = os::physical_memory();1655FLAG_SET_ERGO(MaxRAM, (uint64_t)phys_mem);1656} else {1657phys_mem = (julong)MaxRAM;1658}1659} else {1660phys_mem = FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)1661: (julong)MaxRAM;1662}166316641665// Convert deprecated flags1666if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&1667!FLAG_IS_DEFAULT(MaxRAMFraction))1668MaxRAMPercentage = 100.0 / MaxRAMFraction;16691670if (FLAG_IS_DEFAULT(MinRAMPercentage) &&1671!FLAG_IS_DEFAULT(MinRAMFraction))1672MinRAMPercentage = 100.0 / MinRAMFraction;16731674if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&1675!FLAG_IS_DEFAULT(InitialRAMFraction))1676InitialRAMPercentage = 100.0 / InitialRAMFraction;16771678// If the maximum heap size has not been set with -Xmx,1679// then set it as fraction of the size of physical memory,1680// respecting the maximum and minimum sizes of the heap.1681if (FLAG_IS_DEFAULT(MaxHeapSize)) {1682julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);1683const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);1684if (reasonable_min < MaxHeapSize) {1685// Small physical memory, so use a minimum fraction of it for the heap1686reasonable_max = reasonable_min;1687} else {1688// Not-small physical memory, so require a heap at least1689// as large as MaxHeapSize1690reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);1691}16921693if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {1694// Limit the heap size to ErgoHeapSizeLimit1695reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);1696}16971698#ifdef _LP641699if (UseCompressedOops || UseCompressedClassPointers) {1700// HeapBaseMinAddress can be greater than default but not less than.1701if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {1702if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {1703// matches compressed oops printing flags1704log_debug(gc, heap, coops)("HeapBaseMinAddress must be at least " SIZE_FORMAT1705" (" SIZE_FORMAT "G) which is greater than value given " SIZE_FORMAT,1706DefaultHeapBaseMinAddress,1707DefaultHeapBaseMinAddress/G,1708HeapBaseMinAddress);1709FLAG_SET_ERGO(HeapBaseMinAddress, DefaultHeapBaseMinAddress);1710}1711}1712}1713if (UseCompressedOops) {1714// Limit the heap size to the maximum possible when using compressed oops1715julong max_coop_heap = (julong)max_heap_for_compressed_oops();17161717if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {1718// Heap should be above HeapBaseMinAddress to get zero based compressed oops1719// but it should be not less than default MaxHeapSize.1720max_coop_heap -= HeapBaseMinAddress;1721}17221723// If user specified flags prioritizing os physical1724// memory limits, then disable compressed oops if1725// limits exceed max_coop_heap and UseCompressedOops1726// was not specified.1727if (reasonable_max > max_coop_heap) {1728if (FLAG_IS_ERGO(UseCompressedOops) && override_coop_limit) {1729log_info(cds)("UseCompressedOops and UseCompressedClassPointers have been disabled due to"1730" max heap " SIZE_FORMAT " > compressed oop heap " SIZE_FORMAT ". "1731"Please check the setting of MaxRAMPercentage %5.2f."1732,(size_t)reasonable_max, (size_t)max_coop_heap, MaxRAMPercentage);1733FLAG_SET_ERGO(UseCompressedOops, false);1734if (COMPRESSED_CLASS_POINTERS_DEPENDS_ON_COMPRESSED_OOPS) {1735FLAG_SET_ERGO(UseCompressedClassPointers, false);1736}1737} else {1738reasonable_max = MIN2(reasonable_max, max_coop_heap);1739}1740}1741}1742#endif // _LP6417431744reasonable_max = limit_heap_by_allocatable_memory(reasonable_max);17451746if (!FLAG_IS_DEFAULT(InitialHeapSize)) {1747// An initial heap size was specified on the command line,1748// so be sure that the maximum size is consistent. Done1749// after call to limit_heap_by_allocatable_memory because that1750// method might reduce the allocation size.1751reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);1752} else if (!FLAG_IS_DEFAULT(MinHeapSize)) {1753reasonable_max = MAX2(reasonable_max, (julong)MinHeapSize);1754}17551756log_trace(gc, heap)(" Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);1757FLAG_SET_ERGO(MaxHeapSize, (size_t)reasonable_max);1758}17591760// If the minimum or initial heap_size have not been set or requested to be set1761// ergonomically, set them accordingly.1762if (InitialHeapSize == 0 || MinHeapSize == 0) {1763julong reasonable_minimum = (julong)(OldSize + NewSize);17641765reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);17661767reasonable_minimum = limit_heap_by_allocatable_memory(reasonable_minimum);17681769if (InitialHeapSize == 0) {1770julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);1771reasonable_initial = limit_heap_by_allocatable_memory(reasonable_initial);17721773reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)MinHeapSize);1774reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);17751776FLAG_SET_ERGO(InitialHeapSize, (size_t)reasonable_initial);1777log_trace(gc, heap)(" Initial heap size " SIZE_FORMAT, InitialHeapSize);1778}1779// If the minimum heap size has not been set (via -Xms or -XX:MinHeapSize),1780// synchronize with InitialHeapSize to avoid errors with the default value.1781if (MinHeapSize == 0) {1782FLAG_SET_ERGO(MinHeapSize, MIN2((size_t)reasonable_minimum, InitialHeapSize));1783log_trace(gc, heap)(" Minimum heap size " SIZE_FORMAT, MinHeapSize);1784}1785}1786}17871788// This option inspects the machine and attempts to set various1789// parameters to be optimal for long-running, memory allocation1790// intensive jobs. It is intended for machines with large1791// amounts of cpu and memory.1792jint Arguments::set_aggressive_heap_flags() {1793// initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit1794// VM, but we may not be able to represent the total physical memory1795// available (like having 8gb of memory on a box but using a 32bit VM).1796// Thus, we need to make sure we're using a julong for intermediate1797// calculations.1798julong initHeapSize;1799julong total_memory = os::physical_memory();18001801if (total_memory < (julong) 256 * M) {1802jio_fprintf(defaultStream::error_stream(),1803"You need at least 256mb of memory to use -XX:+AggressiveHeap\n");1804vm_exit(1);1805}18061807// The heap size is half of available memory, or (at most)1808// all of possible memory less 160mb (leaving room for the OS1809// when using ISM). This is the maximum; because adaptive sizing1810// is turned on below, the actual space used may be smaller.18111812initHeapSize = MIN2(total_memory / (julong) 2,1813total_memory - (julong) 160 * M);18141815initHeapSize = limit_heap_by_allocatable_memory(initHeapSize);18161817if (FLAG_IS_DEFAULT(MaxHeapSize)) {1818if (FLAG_SET_CMDLINE(MaxHeapSize, initHeapSize) != JVMFlag::SUCCESS) {1819return JNI_EINVAL;1820}1821if (FLAG_SET_CMDLINE(InitialHeapSize, initHeapSize) != JVMFlag::SUCCESS) {1822return JNI_EINVAL;1823}1824if (FLAG_SET_CMDLINE(MinHeapSize, initHeapSize) != JVMFlag::SUCCESS) {1825return JNI_EINVAL;1826}1827}1828if (FLAG_IS_DEFAULT(NewSize)) {1829// Make the young generation 3/8ths of the total heap.1830if (FLAG_SET_CMDLINE(NewSize,1831((julong) MaxHeapSize / (julong) 8) * (julong) 3) != JVMFlag::SUCCESS) {1832return JNI_EINVAL;1833}1834if (FLAG_SET_CMDLINE(MaxNewSize, NewSize) != JVMFlag::SUCCESS) {1835return JNI_EINVAL;1836}1837}18381839#if !defined(_ALLBSD_SOURCE) && !defined(AIX) // UseLargePages is not yet supported on BSD and AIX.1840FLAG_SET_DEFAULT(UseLargePages, true);1841#endif18421843// Increase some data structure sizes for efficiency1844if (FLAG_SET_CMDLINE(BaseFootPrintEstimate, MaxHeapSize) != JVMFlag::SUCCESS) {1845return JNI_EINVAL;1846}1847if (FLAG_SET_CMDLINE(ResizeTLAB, false) != JVMFlag::SUCCESS) {1848return JNI_EINVAL;1849}1850if (FLAG_SET_CMDLINE(TLABSize, 256 * K) != JVMFlag::SUCCESS) {1851return JNI_EINVAL;1852}18531854// See the OldPLABSize comment below, but replace 'after promotion'1855// with 'after copying'. YoungPLABSize is the size of the survivor1856// space per-gc-thread buffers. The default is 4kw.1857if (FLAG_SET_CMDLINE(YoungPLABSize, 256 * K) != JVMFlag::SUCCESS) { // Note: this is in words1858return JNI_EINVAL;1859}18601861// OldPLABSize is the size of the buffers in the old gen that1862// UseParallelGC uses to promote live data that doesn't fit in the1863// survivor spaces. At any given time, there's one for each gc thread.1864// The default size is 1kw. These buffers are rarely used, since the1865// survivor spaces are usually big enough. For specjbb, however, there1866// are occasions when there's lots of live data in the young gen1867// and we end up promoting some of it. We don't have a definite1868// explanation for why bumping OldPLABSize helps, but the theory1869// is that a bigger PLAB results in retaining something like the1870// original allocation order after promotion, which improves mutator1871// locality. A minor effect may be that larger PLABs reduce the1872// number of PLAB allocation events during gc. The value of 8kw1873// was arrived at by experimenting with specjbb.1874if (FLAG_SET_CMDLINE(OldPLABSize, 8 * K) != JVMFlag::SUCCESS) { // Note: this is in words1875return JNI_EINVAL;1876}18771878// Enable parallel GC and adaptive generation sizing1879if (FLAG_SET_CMDLINE(UseParallelGC, true) != JVMFlag::SUCCESS) {1880return JNI_EINVAL;1881}18821883// Encourage steady state memory management1884if (FLAG_SET_CMDLINE(ThresholdTolerance, 100) != JVMFlag::SUCCESS) {1885return JNI_EINVAL;1886}18871888// This appears to improve mutator locality1889if (FLAG_SET_CMDLINE(ScavengeBeforeFullGC, false) != JVMFlag::SUCCESS) {1890return JNI_EINVAL;1891}18921893return JNI_OK;1894}18951896// This must be called after ergonomics.1897void Arguments::set_bytecode_flags() {1898if (!RewriteBytecodes) {1899FLAG_SET_DEFAULT(RewriteFrequentPairs, false);1900}1901}19021903// Aggressive optimization flags1904jint Arguments::set_aggressive_opts_flags() {1905#ifdef COMPILER21906if (AggressiveUnboxing) {1907if (FLAG_IS_DEFAULT(EliminateAutoBox)) {1908FLAG_SET_DEFAULT(EliminateAutoBox, true);1909} else if (!EliminateAutoBox) {1910// warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");1911AggressiveUnboxing = false;1912}1913if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {1914FLAG_SET_DEFAULT(DoEscapeAnalysis, true);1915} else if (!DoEscapeAnalysis) {1916// warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");1917AggressiveUnboxing = false;1918}1919}1920if (!FLAG_IS_DEFAULT(AutoBoxCacheMax)) {1921if (FLAG_IS_DEFAULT(EliminateAutoBox)) {1922FLAG_SET_DEFAULT(EliminateAutoBox, true);1923}1924// Feed the cache size setting into the JDK1925char buffer[1024];1926jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);1927if (!add_property(buffer)) {1928return JNI_ENOMEM;1929}1930}1931#endif19321933return JNI_OK;1934}19351936//===========================================================================================================1937// Parsing of java.compiler property19381939void Arguments::process_java_compiler_argument(const char* arg) {1940// For backwards compatibility, Djava.compiler=NONE or ""1941// causes us to switch to -Xint mode UNLESS -Xdebug1942// is also specified.1943if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {1944set_java_compiler(true); // "-Djava.compiler[=...]" most recently seen.1945}1946}19471948void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {1949_sun_java_launcher = os::strdup_check_oom(launcher);1950}19511952bool Arguments::created_by_java_launcher() {1953assert(_sun_java_launcher != NULL, "property must have value");1954return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;1955}19561957bool Arguments::sun_java_launcher_is_altjvm() {1958return _sun_java_launcher_is_altjvm;1959}19601961//===========================================================================================================1962// Parsing of main arguments19631964unsigned int addreads_count = 0;1965unsigned int addexports_count = 0;1966unsigned int addopens_count = 0;1967unsigned int addmods_count = 0;1968unsigned int patch_mod_count = 0;1969unsigned int enable_native_access_count = 0;19701971// Check the consistency of vm_init_args1972bool Arguments::check_vm_args_consistency() {1973// Method for adding checks for flag consistency.1974// The intent is to warn the user of all possible conflicts,1975// before returning an error.1976// Note: Needs platform-dependent factoring.1977bool status = true;19781979if (TLABRefillWasteFraction == 0) {1980jio_fprintf(defaultStream::error_stream(),1981"TLABRefillWasteFraction should be a denominator, "1982"not " SIZE_FORMAT "\n",1983TLABRefillWasteFraction);1984status = false;1985}19861987if (PrintNMTStatistics) {1988#if INCLUDE_NMT1989if (MemTracker::tracking_level() == NMT_off) {1990#endif // INCLUDE_NMT1991warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");1992PrintNMTStatistics = false;1993#if INCLUDE_NMT1994}1995#endif1996}19971998status = CompilerConfig::check_args_consistency(status);1999#if INCLUDE_JVMCI2000if (status && EnableJVMCI) {2001PropertyList_unique_add(&_system_properties, "jdk.internal.vm.ci.enabled", "true",2002AddProperty, UnwriteableProperty, InternalProperty);2003if (!create_numbered_module_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {2004return false;2005}2006}2007#endif20082009#ifndef SUPPORT_RESERVED_STACK_AREA2010if (StackReservedPages != 0) {2011FLAG_SET_CMDLINE(StackReservedPages, 0);2012warning("Reserved Stack Area not supported on this platform");2013}2014#endif20152016return status;2017}20182019bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,2020const char* option_type) {2021if (ignore) return false;20222023const char* spacer = " ";2024if (option_type == NULL) {2025option_type = ++spacer; // Set both to the empty string.2026}20272028jio_fprintf(defaultStream::error_stream(),2029"Unrecognized %s%soption: %s\n", option_type, spacer,2030option->optionString);2031return true;2032}20332034static const char* user_assertion_options[] = {2035"-da", "-ea", "-disableassertions", "-enableassertions", 02036};20372038static const char* system_assertion_options[] = {2039"-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 02040};20412042bool Arguments::parse_uintx(const char* value,2043uintx* uintx_arg,2044uintx min_size) {20452046// Check the sign first since atojulong() parses only unsigned values.2047bool value_is_positive = !(*value == '-');20482049if (value_is_positive) {2050julong n;2051bool good_return = atojulong(value, &n);2052if (good_return) {2053bool above_minimum = n >= min_size;2054bool value_is_too_large = n > max_uintx;20552056if (above_minimum && !value_is_too_large) {2057*uintx_arg = n;2058return true;2059}2060}2061}2062return false;2063}20642065bool Arguments::create_module_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {2066assert(is_internal_module_property(prop_name), "unknown module property: '%s'", prop_name);2067size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;2068char* property = AllocateHeap(prop_len, mtArguments);2069int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);2070if (ret < 0 || ret >= (int)prop_len) {2071FreeHeap(property);2072return false;2073}2074// These are not strictly writeable properties as they cannot be set via -Dprop=val. But that2075// is enforced by checking is_internal_module_property(). We need the property to be writeable so2076// that multiple occurrences of the associated flag just causes the existing property value to be2077// replaced ("last option wins"). Otherwise we would need to keep track of the flags and only convert2078// to a property after we have finished flag processing.2079bool added = add_property(property, WriteableProperty, internal);2080FreeHeap(property);2081return added;2082}20832084bool Arguments::create_numbered_module_property(const char* prop_base_name, const char* prop_value, unsigned int count) {2085assert(is_internal_module_property(prop_base_name), "unknown module property: '%s'", prop_base_name);2086const unsigned int props_count_limit = 1000;2087const int max_digits = 3;2088const int extra_symbols_count = 3; // includes '.', '=', '\0'20892090// Make sure count is < props_count_limit. Otherwise, memory allocation will be too small.2091if (count < props_count_limit) {2092size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + max_digits + extra_symbols_count;2093char* property = AllocateHeap(prop_len, mtArguments);2094int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);2095if (ret < 0 || ret >= (int)prop_len) {2096FreeHeap(property);2097jio_fprintf(defaultStream::error_stream(), "Failed to create property %s.%d=%s\n", prop_base_name, count, prop_value);2098return false;2099}2100bool added = add_property(property, UnwriteableProperty, InternalProperty);2101FreeHeap(property);2102return added;2103}21042105jio_fprintf(defaultStream::error_stream(), "Property count limit exceeded: %s, limit=%d\n", prop_base_name, props_count_limit);2106return false;2107}21082109Arguments::ArgsRange Arguments::parse_memory_size(const char* s,2110julong* long_arg,2111julong min_size,2112julong max_size) {2113if (!atojulong(s, long_arg)) return arg_unreadable;2114return check_memory_size(*long_arg, min_size, max_size);2115}21162117// Parse JavaVMInitArgs structure21182119jint Arguments::parse_vm_init_args(const JavaVMInitArgs *vm_options_args,2120const JavaVMInitArgs *java_tool_options_args,2121const JavaVMInitArgs *java_options_args,2122const JavaVMInitArgs *cmd_line_args) {2123bool patch_mod_javabase = false;21242125// Save default settings for some mode flags2126Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;2127Arguments::_UseOnStackReplacement = UseOnStackReplacement;2128Arguments::_ClipInlining = ClipInlining;2129Arguments::_BackgroundCompilation = BackgroundCompilation;21302131// Remember the default value of SharedBaseAddress.2132Arguments::_default_SharedBaseAddress = SharedBaseAddress;21332134// Setup flags for mixed which is the default2135set_mode_flags(_mixed);21362137// Parse args structure generated from java.base vm options resource2138jint result = parse_each_vm_init_arg(vm_options_args, &patch_mod_javabase, JVMFlagOrigin::JIMAGE_RESOURCE);2139if (result != JNI_OK) {2140return result;2141}21422143// Parse args structure generated from JAVA_TOOL_OPTIONS environment2144// variable (if present).2145result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR);2146if (result != JNI_OK) {2147return result;2148}21492150// Parse args structure generated from the command line flags.2151result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, JVMFlagOrigin::COMMAND_LINE);2152if (result != JNI_OK) {2153return result;2154}21552156// Parse args structure generated from the _JAVA_OPTIONS environment2157// variable (if present) (mimics classic VM)2158result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR);2159if (result != JNI_OK) {2160return result;2161}21622163// We need to ensure processor and memory resources have been properly2164// configured - which may rely on arguments we just processed - before2165// doing the final argument processing. Any argument processing that2166// needs to know about processor and memory resources must occur after2167// this point.21682169os::init_container_support();21702171// Do final processing now that all arguments have been parsed2172result = finalize_vm_init_args(patch_mod_javabase);2173if (result != JNI_OK) {2174return result;2175}21762177return JNI_OK;2178}21792180// Checks if name in command-line argument -agent{lib,path}:name[=options]2181// represents a valid JDWP agent. is_path==true denotes that we2182// are dealing with -agentpath (case where name is a path), otherwise with2183// -agentlib2184bool valid_jdwp_agent(char *name, bool is_path) {2185char *_name;2186const char *_jdwp = "jdwp";2187size_t _len_jdwp, _len_prefix;21882189if (is_path) {2190if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {2191return false;2192}21932194_name++; // skip past last path separator2195_len_prefix = strlen(JNI_LIB_PREFIX);21962197if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {2198return false;2199}22002201_name += _len_prefix;2202_len_jdwp = strlen(_jdwp);22032204if (strncmp(_name, _jdwp, _len_jdwp) == 0) {2205_name += _len_jdwp;2206}2207else {2208return false;2209}22102211if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {2212return false;2213}22142215return true;2216}22172218if (strcmp(name, _jdwp) == 0) {2219return true;2220}22212222return false;2223}22242225int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {2226// --patch-module=<module>=<file>(<pathsep><file>)*2227assert(patch_mod_tail != NULL, "Unexpected NULL patch-module value");2228// Find the equal sign between the module name and the path specification2229const char* module_equal = strchr(patch_mod_tail, '=');2230if (module_equal == NULL) {2231jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");2232return JNI_ERR;2233} else {2234// Pick out the module name2235size_t module_len = module_equal - patch_mod_tail;2236char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);2237if (module_name != NULL) {2238memcpy(module_name, patch_mod_tail, module_len);2239*(module_name + module_len) = '\0';2240// The path piece begins one past the module_equal sign2241add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);2242FREE_C_HEAP_ARRAY(char, module_name);2243if (!create_numbered_module_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {2244return JNI_ENOMEM;2245}2246} else {2247return JNI_ENOMEM;2248}2249}2250return JNI_OK;2251}22522253// Parse -Xss memory string parameter and convert to ThreadStackSize in K.2254jint Arguments::parse_xss(const JavaVMOption* option, const char* tail, intx* out_ThreadStackSize) {2255// The min and max sizes match the values in globals.hpp, but scaled2256// with K. The values have been chosen so that alignment with page2257// size doesn't change the max value, which makes the conversions2258// back and forth between Xss value and ThreadStackSize value easier.2259// The values have also been chosen to fit inside a 32-bit signed type.2260const julong min_ThreadStackSize = 0;2261const julong max_ThreadStackSize = 1 * M;22622263// Make sure the above values match the range set in globals.hpp2264const JVMTypedFlagLimit<intx>* limit = JVMFlagLimit::get_range_at(FLAG_MEMBER_ENUM(ThreadStackSize))->cast<intx>();2265assert(min_ThreadStackSize == static_cast<julong>(limit->min()), "must be");2266assert(max_ThreadStackSize == static_cast<julong>(limit->max()), "must be");22672268const julong min_size = min_ThreadStackSize * K;2269const julong max_size = max_ThreadStackSize * K;22702271assert(is_aligned(max_size, os::vm_page_size()), "Implementation assumption");22722273julong size = 0;2274ArgsRange errcode = parse_memory_size(tail, &size, min_size, max_size);2275if (errcode != arg_in_range) {2276bool silent = (option == NULL); // Allow testing to silence error messages2277if (!silent) {2278jio_fprintf(defaultStream::error_stream(),2279"Invalid thread stack size: %s\n", option->optionString);2280describe_range_error(errcode);2281}2282return JNI_EINVAL;2283}22842285// Internally track ThreadStackSize in units of 1024 bytes.2286const julong size_aligned = align_up(size, K);2287assert(size <= size_aligned,2288"Overflow: " JULONG_FORMAT " " JULONG_FORMAT,2289size, size_aligned);22902291const julong size_in_K = size_aligned / K;2292assert(size_in_K < (julong)max_intx,2293"size_in_K doesn't fit in the type of ThreadStackSize: " JULONG_FORMAT,2294size_in_K);22952296// Check that code expanding ThreadStackSize to a page aligned number of bytes won't overflow.2297const julong max_expanded = align_up(size_in_K * K, os::vm_page_size());2298assert(max_expanded < max_uintx && max_expanded >= size_in_K,2299"Expansion overflowed: " JULONG_FORMAT " " JULONG_FORMAT,2300max_expanded, size_in_K);23012302*out_ThreadStackSize = (intx)size_in_K;23032304return JNI_OK;2305}23062307jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, JVMFlagOrigin origin) {2308// For match_option to return remaining or value part of option string2309const char* tail;23102311// iterate over arguments2312for (int index = 0; index < args->nOptions; index++) {2313bool is_absolute_path = false; // for -agentpath vs -agentlib23142315const JavaVMOption* option = args->options + index;23162317if (!match_option(option, "-Djava.class.path", &tail) &&2318!match_option(option, "-Dsun.java.command", &tail) &&2319!match_option(option, "-Dsun.java.launcher", &tail)) {23202321// add all jvm options to the jvm_args string. This string2322// is used later to set the java.vm.args PerfData string constant.2323// the -Djava.class.path and the -Dsun.java.command options are2324// omitted from jvm_args string as each have their own PerfData2325// string constant object.2326build_jvm_args(option->optionString);2327}23282329// -verbose:[class/module/gc/jni]2330if (match_option(option, "-verbose", &tail)) {2331if (!strcmp(tail, ":class") || !strcmp(tail, "")) {2332LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));2333LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));2334} else if (!strcmp(tail, ":module")) {2335LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, load));2336LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, unload));2337} else if (!strcmp(tail, ":gc")) {2338LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(gc));2339} else if (!strcmp(tail, ":jni")) {2340LogConfiguration::configure_stdout(LogLevel::Debug, true, LOG_TAGS(jni, resolve));2341}2342// -da / -ea / -disableassertions / -enableassertions2343// These accept an optional class/package name separated by a colon, e.g.,2344// -da:java.lang.Thread.2345} else if (match_option(option, user_assertion_options, &tail, true)) {2346bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'2347if (*tail == '\0') {2348JavaAssertions::setUserClassDefault(enable);2349} else {2350assert(*tail == ':', "bogus match by match_option()");2351JavaAssertions::addOption(tail + 1, enable);2352}2353// -dsa / -esa / -disablesystemassertions / -enablesystemassertions2354} else if (match_option(option, system_assertion_options, &tail, false)) {2355bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'2356JavaAssertions::setSystemClassDefault(enable);2357// -bootclasspath:2358} else if (match_option(option, "-Xbootclasspath:", &tail)) {2359jio_fprintf(defaultStream::output_stream(),2360"-Xbootclasspath is no longer a supported option.\n");2361return JNI_EINVAL;2362// -bootclasspath/a:2363} else if (match_option(option, "-Xbootclasspath/a:", &tail)) {2364Arguments::append_sysclasspath(tail);2365#if INCLUDE_CDS2366MetaspaceShared::disable_optimized_module_handling();2367log_info(cds)("optimized module handling: disabled because bootclasspath was appended");2368#endif2369// -bootclasspath/p:2370} else if (match_option(option, "-Xbootclasspath/p:", &tail)) {2371jio_fprintf(defaultStream::output_stream(),2372"-Xbootclasspath/p is no longer a supported option.\n");2373return JNI_EINVAL;2374// -Xrun2375} else if (match_option(option, "-Xrun", &tail)) {2376if (tail != NULL) {2377const char* pos = strchr(tail, ':');2378size_t len = (pos == NULL) ? strlen(tail) : pos - tail;2379char* name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);2380jio_snprintf(name, len + 1, "%s", tail);23812382char *options = NULL;2383if(pos != NULL) {2384size_t len2 = strlen(pos+1) + 1; // options start after ':'. Final zero must be copied.2385options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);2386}2387#if !INCLUDE_JVMTI2388if (strcmp(name, "jdwp") == 0) {2389jio_fprintf(defaultStream::error_stream(),2390"Debugging agents are not supported in this VM\n");2391return JNI_ERR;2392}2393#endif // !INCLUDE_JVMTI2394add_init_library(name, options);2395}2396} else if (match_option(option, "--add-reads=", &tail)) {2397if (!create_numbered_module_property("jdk.module.addreads", tail, addreads_count++)) {2398return JNI_ENOMEM;2399}2400} else if (match_option(option, "--add-exports=", &tail)) {2401if (!create_numbered_module_property("jdk.module.addexports", tail, addexports_count++)) {2402return JNI_ENOMEM;2403}2404} else if (match_option(option, "--add-opens=", &tail)) {2405if (!create_numbered_module_property("jdk.module.addopens", tail, addopens_count++)) {2406return JNI_ENOMEM;2407}2408} else if (match_option(option, "--add-modules=", &tail)) {2409if (!create_numbered_module_property("jdk.module.addmods", tail, addmods_count++)) {2410return JNI_ENOMEM;2411}2412} else if (match_option(option, "--enable-native-access=", &tail)) {2413if (!create_numbered_module_property("jdk.module.enable.native.access", tail, enable_native_access_count++)) {2414return JNI_ENOMEM;2415}2416} else if (match_option(option, "--limit-modules=", &tail)) {2417if (!create_module_property("jdk.module.limitmods", tail, InternalProperty)) {2418return JNI_ENOMEM;2419}2420} else if (match_option(option, "--module-path=", &tail)) {2421if (!create_module_property("jdk.module.path", tail, ExternalProperty)) {2422return JNI_ENOMEM;2423}2424} else if (match_option(option, "--upgrade-module-path=", &tail)) {2425if (!create_module_property("jdk.module.upgrade.path", tail, ExternalProperty)) {2426return JNI_ENOMEM;2427}2428} else if (match_option(option, "--patch-module=", &tail)) {2429// --patch-module=<module>=<file>(<pathsep><file>)*2430int res = process_patch_mod_option(tail, patch_mod_javabase);2431if (res != JNI_OK) {2432return res;2433}2434} else if (match_option(option, "--illegal-access=", &tail)) {2435char version[256];2436JDK_Version::jdk(17).to_string(version, sizeof(version));2437warning("Ignoring option %s; support was removed in %s", option->optionString, version);2438// -agentlib and -agentpath2439} else if (match_option(option, "-agentlib:", &tail) ||2440(is_absolute_path = match_option(option, "-agentpath:", &tail))) {2441if(tail != NULL) {2442const char* pos = strchr(tail, '=');2443char* name;2444if (pos == NULL) {2445name = os::strdup_check_oom(tail, mtArguments);2446} else {2447size_t len = pos - tail;2448name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);2449memcpy(name, tail, len);2450name[len] = '\0';2451}24522453char *options = NULL;2454if(pos != NULL) {2455options = os::strdup_check_oom(pos + 1, mtArguments);2456}2457#if !INCLUDE_JVMTI2458if (valid_jdwp_agent(name, is_absolute_path)) {2459jio_fprintf(defaultStream::error_stream(),2460"Debugging agents are not supported in this VM\n");2461return JNI_ERR;2462}2463#endif // !INCLUDE_JVMTI2464add_init_agent(name, options, is_absolute_path);2465}2466// -javaagent2467} else if (match_option(option, "-javaagent:", &tail)) {2468#if !INCLUDE_JVMTI2469jio_fprintf(defaultStream::error_stream(),2470"Instrumentation agents are not supported in this VM\n");2471return JNI_ERR;2472#else2473if (tail != NULL) {2474size_t length = strlen(tail) + 1;2475char *options = NEW_C_HEAP_ARRAY(char, length, mtArguments);2476jio_snprintf(options, length, "%s", tail);2477add_instrument_agent("instrument", options, false);2478// java agents need module java.instrument2479if (!create_numbered_module_property("jdk.module.addmods", "java.instrument", addmods_count++)) {2480return JNI_ENOMEM;2481}2482}2483#endif // !INCLUDE_JVMTI2484// --enable_preview2485} else if (match_option(option, "--enable-preview")) {2486set_enable_preview();2487// -Xnoclassgc2488} else if (match_option(option, "-Xnoclassgc")) {2489if (FLAG_SET_CMDLINE(ClassUnloading, false) != JVMFlag::SUCCESS) {2490return JNI_EINVAL;2491}2492// -Xbatch2493} else if (match_option(option, "-Xbatch")) {2494if (FLAG_SET_CMDLINE(BackgroundCompilation, false) != JVMFlag::SUCCESS) {2495return JNI_EINVAL;2496}2497// -Xmn for compatibility with other JVM vendors2498} else if (match_option(option, "-Xmn", &tail)) {2499julong long_initial_young_size = 0;2500ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);2501if (errcode != arg_in_range) {2502jio_fprintf(defaultStream::error_stream(),2503"Invalid initial young generation size: %s\n", option->optionString);2504describe_range_error(errcode);2505return JNI_EINVAL;2506}2507if (FLAG_SET_CMDLINE(MaxNewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {2508return JNI_EINVAL;2509}2510if (FLAG_SET_CMDLINE(NewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {2511return JNI_EINVAL;2512}2513// -Xms2514} else if (match_option(option, "-Xms", &tail)) {2515julong size = 0;2516// an initial heap size of 0 means automatically determine2517ArgsRange errcode = parse_memory_size(tail, &size, 0);2518if (errcode != arg_in_range) {2519jio_fprintf(defaultStream::error_stream(),2520"Invalid initial heap size: %s\n", option->optionString);2521describe_range_error(errcode);2522return JNI_EINVAL;2523}2524if (FLAG_SET_CMDLINE(MinHeapSize, (size_t)size) != JVMFlag::SUCCESS) {2525return JNI_EINVAL;2526}2527if (FLAG_SET_CMDLINE(InitialHeapSize, (size_t)size) != JVMFlag::SUCCESS) {2528return JNI_EINVAL;2529}2530// -Xmx2531} else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {2532julong long_max_heap_size = 0;2533ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);2534if (errcode != arg_in_range) {2535jio_fprintf(defaultStream::error_stream(),2536"Invalid maximum heap size: %s\n", option->optionString);2537describe_range_error(errcode);2538return JNI_EINVAL;2539}2540if (FLAG_SET_CMDLINE(MaxHeapSize, (size_t)long_max_heap_size) != JVMFlag::SUCCESS) {2541return JNI_EINVAL;2542}2543// Xmaxf2544} else if (match_option(option, "-Xmaxf", &tail)) {2545char* err;2546int maxf = (int)(strtod(tail, &err) * 100);2547if (*err != '\0' || *tail == '\0') {2548jio_fprintf(defaultStream::error_stream(),2549"Bad max heap free percentage size: %s\n",2550option->optionString);2551return JNI_EINVAL;2552} else {2553if (FLAG_SET_CMDLINE(MaxHeapFreeRatio, maxf) != JVMFlag::SUCCESS) {2554return JNI_EINVAL;2555}2556}2557// Xminf2558} else if (match_option(option, "-Xminf", &tail)) {2559char* err;2560int minf = (int)(strtod(tail, &err) * 100);2561if (*err != '\0' || *tail == '\0') {2562jio_fprintf(defaultStream::error_stream(),2563"Bad min heap free percentage size: %s\n",2564option->optionString);2565return JNI_EINVAL;2566} else {2567if (FLAG_SET_CMDLINE(MinHeapFreeRatio, minf) != JVMFlag::SUCCESS) {2568return JNI_EINVAL;2569}2570}2571// -Xss2572} else if (match_option(option, "-Xss", &tail)) {2573intx value = 0;2574jint err = parse_xss(option, tail, &value);2575if (err != JNI_OK) {2576return err;2577}2578if (FLAG_SET_CMDLINE(ThreadStackSize, value) != JVMFlag::SUCCESS) {2579return JNI_EINVAL;2580}2581} else if (match_option(option, "-Xmaxjitcodesize", &tail) ||2582match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {2583julong long_ReservedCodeCacheSize = 0;25842585ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);2586if (errcode != arg_in_range) {2587jio_fprintf(defaultStream::error_stream(),2588"Invalid maximum code cache size: %s.\n", option->optionString);2589return JNI_EINVAL;2590}2591if (FLAG_SET_CMDLINE(ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != JVMFlag::SUCCESS) {2592return JNI_EINVAL;2593}2594// -green2595} else if (match_option(option, "-green")) {2596jio_fprintf(defaultStream::error_stream(),2597"Green threads support not available\n");2598return JNI_EINVAL;2599// -native2600} else if (match_option(option, "-native")) {2601// HotSpot always uses native threads, ignore silently for compatibility2602// -Xrs2603} else if (match_option(option, "-Xrs")) {2604// Classic/EVM option, new functionality2605if (FLAG_SET_CMDLINE(ReduceSignalUsage, true) != JVMFlag::SUCCESS) {2606return JNI_EINVAL;2607}2608// -Xprof2609} else if (match_option(option, "-Xprof")) {2610char version[256];2611// Obsolete in JDK 102612JDK_Version::jdk(10).to_string(version, sizeof(version));2613warning("Ignoring option %s; support was removed in %s", option->optionString, version);2614// -Xinternalversion2615} else if (match_option(option, "-Xinternalversion")) {2616jio_fprintf(defaultStream::output_stream(), "%s\n",2617VM_Version::internal_vm_info_string());2618vm_exit(0);2619#ifndef PRODUCT2620// -Xprintflags2621} else if (match_option(option, "-Xprintflags")) {2622JVMFlag::printFlags(tty, false);2623vm_exit(0);2624#endif2625// -D2626} else if (match_option(option, "-D", &tail)) {2627const char* value;2628if (match_option(option, "-Djava.endorsed.dirs=", &value) &&2629*value!= '\0' && strcmp(value, "\"\"") != 0) {2630// abort if -Djava.endorsed.dirs is set2631jio_fprintf(defaultStream::output_stream(),2632"-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"2633"in modular form will be supported via the concept of upgradeable modules.\n", value);2634return JNI_EINVAL;2635}2636if (match_option(option, "-Djava.ext.dirs=", &value) &&2637*value != '\0' && strcmp(value, "\"\"") != 0) {2638// abort if -Djava.ext.dirs is set2639jio_fprintf(defaultStream::output_stream(),2640"-Djava.ext.dirs=%s is not supported. Use -classpath instead.\n", value);2641return JNI_EINVAL;2642}2643// Check for module related properties. They must be set using the modules2644// options. For example: use "--add-modules=java.sql", not2645// "-Djdk.module.addmods=java.sql"2646if (is_internal_module_property(option->optionString + 2)) {2647needs_module_property_warning = true;2648continue;2649}2650if (!add_property(tail)) {2651return JNI_ENOMEM;2652}2653// Out of the box management support2654if (match_option(option, "-Dcom.sun.management", &tail)) {2655#if INCLUDE_MANAGEMENT2656if (FLAG_SET_CMDLINE(ManagementServer, true) != JVMFlag::SUCCESS) {2657return JNI_EINVAL;2658}2659// management agent in module jdk.management.agent2660if (!create_numbered_module_property("jdk.module.addmods", "jdk.management.agent", addmods_count++)) {2661return JNI_ENOMEM;2662}2663#else2664jio_fprintf(defaultStream::output_stream(),2665"-Dcom.sun.management is not supported in this VM.\n");2666return JNI_ERR;2667#endif2668}2669// -Xint2670} else if (match_option(option, "-Xint")) {2671set_mode_flags(_int);2672// -Xmixed2673} else if (match_option(option, "-Xmixed")) {2674set_mode_flags(_mixed);2675// -Xcomp2676} else if (match_option(option, "-Xcomp")) {2677// for testing the compiler; turn off all flags that inhibit compilation2678set_mode_flags(_comp);2679// -Xshare:dump2680} else if (match_option(option, "-Xshare:dump")) {2681if (FLAG_SET_CMDLINE(DumpSharedSpaces, true) != JVMFlag::SUCCESS) {2682return JNI_EINVAL;2683}2684// -Xshare:on2685} else if (match_option(option, "-Xshare:on")) {2686if (FLAG_SET_CMDLINE(UseSharedSpaces, true) != JVMFlag::SUCCESS) {2687return JNI_EINVAL;2688}2689if (FLAG_SET_CMDLINE(RequireSharedSpaces, true) != JVMFlag::SUCCESS) {2690return JNI_EINVAL;2691}2692// -Xshare:auto || -XX:ArchiveClassesAtExit=<archive file>2693} else if (match_option(option, "-Xshare:auto")) {2694if (FLAG_SET_CMDLINE(UseSharedSpaces, true) != JVMFlag::SUCCESS) {2695return JNI_EINVAL;2696}2697if (FLAG_SET_CMDLINE(RequireSharedSpaces, false) != JVMFlag::SUCCESS) {2698return JNI_EINVAL;2699}2700// -Xshare:off2701} else if (match_option(option, "-Xshare:off")) {2702if (FLAG_SET_CMDLINE(UseSharedSpaces, false) != JVMFlag::SUCCESS) {2703return JNI_EINVAL;2704}2705if (FLAG_SET_CMDLINE(RequireSharedSpaces, false) != JVMFlag::SUCCESS) {2706return JNI_EINVAL;2707}2708// -Xverify2709} else if (match_option(option, "-Xverify", &tail)) {2710if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {2711if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, true) != JVMFlag::SUCCESS) {2712return JNI_EINVAL;2713}2714if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {2715return JNI_EINVAL;2716}2717} else if (strcmp(tail, ":remote") == 0) {2718if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {2719return JNI_EINVAL;2720}2721if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {2722return JNI_EINVAL;2723}2724} else if (strcmp(tail, ":none") == 0) {2725if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {2726return JNI_EINVAL;2727}2728if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, false) != JVMFlag::SUCCESS) {2729return JNI_EINVAL;2730}2731warning("Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.");2732} else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {2733return JNI_EINVAL;2734}2735// -Xdebug2736} else if (match_option(option, "-Xdebug")) {2737// note this flag has been used, then ignore2738set_xdebug_mode(true);2739// -Xnoagent2740} else if (match_option(option, "-Xnoagent")) {2741// For compatibility with classic. HotSpot refuses to load the old style agent.dll.2742} else if (match_option(option, "-Xloggc:", &tail)) {2743// Deprecated flag to redirect GC output to a file. -Xloggc:<filename>2744log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);2745_gc_log_filename = os::strdup_check_oom(tail);2746} else if (match_option(option, "-Xlog", &tail)) {2747bool ret = false;2748if (strcmp(tail, ":help") == 0) {2749fileStream stream(defaultStream::output_stream());2750LogConfiguration::print_command_line_help(&stream);2751vm_exit(0);2752} else if (strcmp(tail, ":disable") == 0) {2753LogConfiguration::disable_logging();2754ret = true;2755} else if (strcmp(tail, ":async") == 0) {2756LogConfiguration::set_async_mode(true);2757ret = true;2758} else if (*tail == '\0') {2759ret = LogConfiguration::parse_command_line_arguments();2760assert(ret, "-Xlog without arguments should never fail to parse");2761} else if (*tail == ':') {2762ret = LogConfiguration::parse_command_line_arguments(tail + 1);2763}2764if (ret == false) {2765jio_fprintf(defaultStream::error_stream(),2766"Invalid -Xlog option '-Xlog%s', see error log for details.\n",2767tail);2768return JNI_EINVAL;2769}2770// JNI hooks2771} else if (match_option(option, "-Xcheck", &tail)) {2772if (!strcmp(tail, ":jni")) {2773#if !INCLUDE_JNI_CHECK2774warning("JNI CHECKING is not supported in this VM");2775#else2776CheckJNICalls = true;2777#endif // INCLUDE_JNI_CHECK2778} else if (is_bad_option(option, args->ignoreUnrecognized,2779"check")) {2780return JNI_EINVAL;2781}2782} else if (match_option(option, "vfprintf")) {2783_vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);2784} else if (match_option(option, "exit")) {2785_exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);2786} else if (match_option(option, "abort")) {2787_abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);2788// Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;2789// and the last option wins.2790} else if (match_option(option, "-XX:+NeverTenure")) {2791if (FLAG_SET_CMDLINE(NeverTenure, true) != JVMFlag::SUCCESS) {2792return JNI_EINVAL;2793}2794if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {2795return JNI_EINVAL;2796}2797if (FLAG_SET_CMDLINE(MaxTenuringThreshold, markWord::max_age + 1) != JVMFlag::SUCCESS) {2798return JNI_EINVAL;2799}2800} else if (match_option(option, "-XX:+AlwaysTenure")) {2801if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {2802return JNI_EINVAL;2803}2804if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {2805return JNI_EINVAL;2806}2807if (FLAG_SET_CMDLINE(MaxTenuringThreshold, 0) != JVMFlag::SUCCESS) {2808return JNI_EINVAL;2809}2810} else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {2811uintx max_tenuring_thresh = 0;2812if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {2813jio_fprintf(defaultStream::error_stream(),2814"Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);2815return JNI_EINVAL;2816}28172818if (FLAG_SET_CMDLINE(MaxTenuringThreshold, max_tenuring_thresh) != JVMFlag::SUCCESS) {2819return JNI_EINVAL;2820}28212822if (MaxTenuringThreshold == 0) {2823if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {2824return JNI_EINVAL;2825}2826if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {2827return JNI_EINVAL;2828}2829} else {2830if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {2831return JNI_EINVAL;2832}2833if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {2834return JNI_EINVAL;2835}2836}2837} else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {2838if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, false) != JVMFlag::SUCCESS) {2839return JNI_EINVAL;2840}2841if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, true) != JVMFlag::SUCCESS) {2842return JNI_EINVAL;2843}2844} else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {2845if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, false) != JVMFlag::SUCCESS) {2846return JNI_EINVAL;2847}2848if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, true) != JVMFlag::SUCCESS) {2849return JNI_EINVAL;2850}2851} else if (match_option(option, "-XX:+ErrorFileToStderr")) {2852if (FLAG_SET_CMDLINE(ErrorFileToStdout, false) != JVMFlag::SUCCESS) {2853return JNI_EINVAL;2854}2855if (FLAG_SET_CMDLINE(ErrorFileToStderr, true) != JVMFlag::SUCCESS) {2856return JNI_EINVAL;2857}2858} else if (match_option(option, "-XX:+ErrorFileToStdout")) {2859if (FLAG_SET_CMDLINE(ErrorFileToStderr, false) != JVMFlag::SUCCESS) {2860return JNI_EINVAL;2861}2862if (FLAG_SET_CMDLINE(ErrorFileToStdout, true) != JVMFlag::SUCCESS) {2863return JNI_EINVAL;2864}2865} else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {2866#if defined(DTRACE_ENABLED)2867if (FLAG_SET_CMDLINE(ExtendedDTraceProbes, true) != JVMFlag::SUCCESS) {2868return JNI_EINVAL;2869}2870if (FLAG_SET_CMDLINE(DTraceMethodProbes, true) != JVMFlag::SUCCESS) {2871return JNI_EINVAL;2872}2873if (FLAG_SET_CMDLINE(DTraceAllocProbes, true) != JVMFlag::SUCCESS) {2874return JNI_EINVAL;2875}2876if (FLAG_SET_CMDLINE(DTraceMonitorProbes, true) != JVMFlag::SUCCESS) {2877return JNI_EINVAL;2878}2879#else // defined(DTRACE_ENABLED)2880jio_fprintf(defaultStream::error_stream(),2881"ExtendedDTraceProbes flag is not applicable for this configuration\n");2882return JNI_EINVAL;2883#endif // defined(DTRACE_ENABLED)2884#ifdef ASSERT2885} else if (match_option(option, "-XX:+FullGCALot")) {2886if (FLAG_SET_CMDLINE(FullGCALot, true) != JVMFlag::SUCCESS) {2887return JNI_EINVAL;2888}2889// disable scavenge before parallel mark-compact2890if (FLAG_SET_CMDLINE(ScavengeBeforeFullGC, false) != JVMFlag::SUCCESS) {2891return JNI_EINVAL;2892}2893#endif2894#if !INCLUDE_MANAGEMENT2895} else if (match_option(option, "-XX:+ManagementServer")) {2896jio_fprintf(defaultStream::error_stream(),2897"ManagementServer is not supported in this VM.\n");2898return JNI_ERR;2899#endif // INCLUDE_MANAGEMENT2900#if INCLUDE_JVMCI2901} else if (match_option(option, "-XX:-EnableJVMCIProduct")) {2902if (EnableJVMCIProduct) {2903jio_fprintf(defaultStream::error_stream(),2904"-XX:-EnableJVMCIProduct cannot come after -XX:+EnableJVMCIProduct\n");2905return JNI_EINVAL;2906}2907} else if (match_option(option, "-XX:+EnableJVMCIProduct")) {2908// Just continue, since "-XX:+EnableJVMCIProduct" has been specified before2909if (EnableJVMCIProduct) {2910continue;2911}2912JVMFlag *jvmciFlag = JVMFlag::find_flag("EnableJVMCIProduct");2913// Allow this flag if it has been unlocked.2914if (jvmciFlag != NULL && jvmciFlag->is_unlocked()) {2915if (!JVMCIGlobals::enable_jvmci_product_mode(origin)) {2916jio_fprintf(defaultStream::error_stream(),2917"Unable to enable JVMCI in product mode");2918return JNI_ERR;2919}2920}2921// The flag was locked so process normally to report that error2922else if (!process_argument("EnableJVMCIProduct", args->ignoreUnrecognized, origin)) {2923return JNI_EINVAL;2924}2925#endif // INCLUDE_JVMCI2926#if INCLUDE_JFR2927} else if (match_jfr_option(&option)) {2928return JNI_EINVAL;2929#endif2930} else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx2931// Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have2932// already been handled2933if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&2934(strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {2935if (!process_argument(tail, args->ignoreUnrecognized, origin)) {2936return JNI_EINVAL;2937}2938}2939// Unknown option2940} else if (is_bad_option(option, args->ignoreUnrecognized)) {2941return JNI_ERR;2942}2943}29442945// PrintSharedArchiveAndExit will turn on2946// -Xshare:on2947// -Xlog:class+path=info2948if (PrintSharedArchiveAndExit) {2949if (FLAG_SET_CMDLINE(UseSharedSpaces, true) != JVMFlag::SUCCESS) {2950return JNI_EINVAL;2951}2952if (FLAG_SET_CMDLINE(RequireSharedSpaces, true) != JVMFlag::SUCCESS) {2953return JNI_EINVAL;2954}2955LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));2956}29572958fix_appclasspath();29592960return JNI_OK;2961}29622963void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {2964// For java.base check for duplicate --patch-module options being specified on the command line.2965// This check is only required for java.base, all other duplicate module specifications2966// will be checked during module system initialization. The module system initialization2967// will throw an ExceptionInInitializerError if this situation occurs.2968if (strcmp(module_name, JAVA_BASE_NAME) == 0) {2969if (*patch_mod_javabase) {2970vm_exit_during_initialization("Cannot specify " JAVA_BASE_NAME " more than once to --patch-module");2971} else {2972*patch_mod_javabase = true;2973}2974}29752976// Create GrowableArray lazily, only if --patch-module has been specified2977if (_patch_mod_prefix == NULL) {2978_patch_mod_prefix = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<ModulePatchPath*>(10, mtArguments);2979}29802981_patch_mod_prefix->push(new ModulePatchPath(module_name, path));2982}29832984// Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)2985//2986// This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar2987// in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".2988// Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty2989// path is treated as the current directory.2990//2991// This causes problems with CDS, which requires that all directories specified in the classpath2992// must be empty. In most cases, applications do NOT want to load classes from the current2993// directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up2994// scripts compatible with CDS.2995void Arguments::fix_appclasspath() {2996if (IgnoreEmptyClassPaths) {2997const char separator = *os::path_separator();2998const char* src = _java_class_path->value();29993000// skip over all the leading empty paths3001while (*src == separator) {3002src ++;3003}30043005char* copy = os::strdup_check_oom(src, mtArguments);30063007// trim all trailing empty paths3008for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {3009*tail = '\0';3010}30113012char from[3] = {separator, separator, '\0'};3013char to [2] = {separator, '\0'};3014while (StringUtils::replace_no_expand(copy, from, to) > 0) {3015// Keep replacing "::" -> ":" until we have no more "::" (non-windows)3016// Keep replacing ";;" -> ";" until we have no more ";;" (windows)3017}30183019_java_class_path->set_writeable_value(copy);3020FreeHeap(copy); // a copy was made by set_value, so don't need this anymore3021}3022}30233024jint Arguments::finalize_vm_init_args(bool patch_mod_javabase) {3025// check if the default lib/endorsed directory exists; if so, error3026char path[JVM_MAXPATHLEN];3027const char* fileSep = os::file_separator();3028jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);30293030DIR* dir = os::opendir(path);3031if (dir != NULL) {3032jio_fprintf(defaultStream::output_stream(),3033"<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"3034"in modular form will be supported via the concept of upgradeable modules.\n");3035os::closedir(dir);3036return JNI_ERR;3037}30383039jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);3040dir = os::opendir(path);3041if (dir != NULL) {3042jio_fprintf(defaultStream::output_stream(),3043"<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "3044"Use -classpath instead.\n.");3045os::closedir(dir);3046return JNI_ERR;3047}30483049// This must be done after all arguments have been processed3050// and the container support has been initialized since AggressiveHeap3051// relies on the amount of total memory available.3052if (AggressiveHeap) {3053jint result = set_aggressive_heap_flags();3054if (result != JNI_OK) {3055return result;3056}3057}30583059// This must be done after all arguments have been processed.3060// java_compiler() true means set to "NONE" or empty.3061if (java_compiler() && !xdebug_mode()) {3062// For backwards compatibility, we switch to interpreted mode if3063// -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was3064// not specified.3065set_mode_flags(_int);3066}30673068// CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),3069// but like -Xint, leave compilation thresholds unaffected.3070// With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.3071if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {3072set_mode_flags(_int);3073}30743075#ifdef ZERO3076// Zero always runs in interpreted mode3077set_mode_flags(_int);3078#endif30793080// eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set3081if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {3082FLAG_SET_ERGO(InitialTenuringThreshold, MaxTenuringThreshold);3083}30843085#if !COMPILER2_OR_JVMCI3086// Don't degrade server performance for footprint3087if (FLAG_IS_DEFAULT(UseLargePages) &&3088MaxHeapSize < LargePageHeapSizeThreshold) {3089// No need for large granularity pages w/small heaps.3090// Note that large pages are enabled/disabled for both the3091// Java heap and the code cache.3092FLAG_SET_DEFAULT(UseLargePages, false);3093}30943095UNSUPPORTED_OPTION(ProfileInterpreter);3096#endif30973098// Parse the CompilationMode flag3099if (!CompilationModeFlag::initialize()) {3100return JNI_ERR;3101}31023103if (!check_vm_args_consistency()) {3104return JNI_ERR;3105}31063107#if INCLUDE_CDS3108if (DumpSharedSpaces) {3109// Disable biased locking now as it interferes with the clean up of3110// the archived Klasses and Java string objects (at dump time only).3111UseBiasedLocking = false;31123113// Compiler threads may concurrently update the class metadata (such as method entries), so it's3114// unsafe with DumpSharedSpaces (which modifies the class metadata in place). Let's disable3115// compiler just to be safe.3116//3117// Note: this is not a concern for DynamicDumpSharedSpaces, which makes a copy of the class metadata3118// instead of modifying them in place. The copy is inaccessible to the compiler.3119// TODO: revisit the following for the static archive case.3120set_mode_flags(_int);3121}3122if (DumpSharedSpaces || ArchiveClassesAtExit != NULL) {3123// Always verify non-system classes during CDS dump3124if (!BytecodeVerificationRemote) {3125BytecodeVerificationRemote = true;3126log_info(cds)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");3127}3128}31293130// RecordDynamicDumpInfo is not compatible with ArchiveClassesAtExit3131if (ArchiveClassesAtExit != NULL && RecordDynamicDumpInfo) {3132log_info(cds)("RecordDynamicDumpInfo is for jcmd only, could not set with -XX:ArchiveClassesAtExit.");3133return JNI_ERR;3134}31353136if (ArchiveClassesAtExit == NULL && !RecordDynamicDumpInfo) {3137FLAG_SET_DEFAULT(DynamicDumpSharedSpaces, false);3138} else {3139FLAG_SET_DEFAULT(DynamicDumpSharedSpaces, true);3140}31413142if (UseSharedSpaces && patch_mod_javabase) {3143no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");3144}3145if (UseSharedSpaces && !DumpSharedSpaces && check_unsupported_cds_runtime_properties()) {3146FLAG_SET_DEFAULT(UseSharedSpaces, false);3147}3148#endif31493150#ifndef CAN_SHOW_REGISTERS_ON_ASSERT3151UNSUPPORTED_OPTION(ShowRegistersOnAssert);3152#endif // CAN_SHOW_REGISTERS_ON_ASSERT31533154return JNI_OK;3155}31563157// Helper class for controlling the lifetime of JavaVMInitArgs3158// objects. The contents of the JavaVMInitArgs are guaranteed to be3159// deleted on the destruction of the ScopedVMInitArgs object.3160class ScopedVMInitArgs : public StackObj {3161private:3162JavaVMInitArgs _args;3163char* _container_name;3164bool _is_set;3165char* _vm_options_file_arg;31663167public:3168ScopedVMInitArgs(const char *container_name) {3169_args.version = JNI_VERSION_1_2;3170_args.nOptions = 0;3171_args.options = NULL;3172_args.ignoreUnrecognized = false;3173_container_name = (char *)container_name;3174_is_set = false;3175_vm_options_file_arg = NULL;3176}31773178// Populates the JavaVMInitArgs object represented by this3179// ScopedVMInitArgs object with the arguments in options. The3180// allocated memory is deleted by the destructor. If this method3181// returns anything other than JNI_OK, then this object is in a3182// partially constructed state, and should be abandoned.3183jint set_args(const GrowableArrayView<JavaVMOption>* options) {3184_is_set = true;3185JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(3186JavaVMOption, options->length(), mtArguments);3187if (options_arr == NULL) {3188return JNI_ENOMEM;3189}3190_args.options = options_arr;31913192for (int i = 0; i < options->length(); i++) {3193options_arr[i] = options->at(i);3194options_arr[i].optionString = os::strdup(options_arr[i].optionString);3195if (options_arr[i].optionString == NULL) {3196// Rely on the destructor to do cleanup.3197_args.nOptions = i;3198return JNI_ENOMEM;3199}3200}32013202_args.nOptions = options->length();3203_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;3204return JNI_OK;3205}32063207JavaVMInitArgs* get() { return &_args; }3208char* container_name() { return _container_name; }3209bool is_set() { return _is_set; }3210bool found_vm_options_file_arg() { return _vm_options_file_arg != NULL; }3211char* vm_options_file_arg() { return _vm_options_file_arg; }32123213void set_vm_options_file_arg(const char *vm_options_file_arg) {3214if (_vm_options_file_arg != NULL) {3215os::free(_vm_options_file_arg);3216}3217_vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);3218}32193220~ScopedVMInitArgs() {3221if (_vm_options_file_arg != NULL) {3222os::free(_vm_options_file_arg);3223}3224if (_args.options == NULL) return;3225for (int i = 0; i < _args.nOptions; i++) {3226os::free(_args.options[i].optionString);3227}3228FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);3229}32303231// Insert options into this option list, to replace option at3232// vm_options_file_pos (-XX:VMOptionsFile)3233jint insert(const JavaVMInitArgs* args,3234const JavaVMInitArgs* args_to_insert,3235const int vm_options_file_pos) {3236assert(_args.options == NULL, "shouldn't be set yet");3237assert(args_to_insert->nOptions != 0, "there should be args to insert");3238assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");32393240int length = args->nOptions + args_to_insert->nOptions - 1;3241// Construct new option array3242GrowableArrayCHeap<JavaVMOption, mtArguments> options(length);3243for (int i = 0; i < args->nOptions; i++) {3244if (i == vm_options_file_pos) {3245// insert the new options starting at the same place as the3246// -XX:VMOptionsFile option3247for (int j = 0; j < args_to_insert->nOptions; j++) {3248options.push(args_to_insert->options[j]);3249}3250} else {3251options.push(args->options[i]);3252}3253}3254// make into options array3255return set_args(&options);3256}3257};32583259jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {3260return parse_options_environment_variable("_JAVA_OPTIONS", args);3261}32623263jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {3264return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);3265}32663267jint Arguments::parse_options_environment_variable(const char* name,3268ScopedVMInitArgs* vm_args) {3269char *buffer = ::getenv(name);32703271// Don't check this environment variable if user has special privileges3272// (e.g. unix su command).3273if (buffer == NULL || os::have_special_privileges()) {3274return JNI_OK;3275}32763277if ((buffer = os::strdup(buffer)) == NULL) {3278return JNI_ENOMEM;3279}32803281jio_fprintf(defaultStream::error_stream(),3282"Picked up %s: %s\n", name, buffer);32833284int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);32853286os::free(buffer);3287return retcode;3288}32893290jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {3291// read file into buffer3292int fd = ::open(file_name, O_RDONLY);3293if (fd < 0) {3294jio_fprintf(defaultStream::error_stream(),3295"Could not open options file '%s'\n",3296file_name);3297return JNI_ERR;3298}32993300struct stat stbuf;3301int retcode = os::stat(file_name, &stbuf);3302if (retcode != 0) {3303jio_fprintf(defaultStream::error_stream(),3304"Could not stat options file '%s'\n",3305file_name);3306os::close(fd);3307return JNI_ERR;3308}33093310if (stbuf.st_size == 0) {3311// tell caller there is no option data and that is ok3312os::close(fd);3313return JNI_OK;3314}33153316// '+ 1' for NULL termination even with max bytes3317size_t bytes_alloc = stbuf.st_size + 1;33183319char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);3320if (NULL == buf) {3321jio_fprintf(defaultStream::error_stream(),3322"Could not allocate read buffer for options file parse\n");3323os::close(fd);3324return JNI_ENOMEM;3325}33263327memset(buf, 0, bytes_alloc);33283329// Fill buffer3330ssize_t bytes_read = os::read(fd, (void *)buf, (unsigned)bytes_alloc);3331os::close(fd);3332if (bytes_read < 0) {3333FREE_C_HEAP_ARRAY(char, buf);3334jio_fprintf(defaultStream::error_stream(),3335"Could not read options file '%s'\n", file_name);3336return JNI_ERR;3337}33383339if (bytes_read == 0) {3340// tell caller there is no option data and that is ok3341FREE_C_HEAP_ARRAY(char, buf);3342return JNI_OK;3343}33443345retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);33463347FREE_C_HEAP_ARRAY(char, buf);3348return retcode;3349}33503351jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {3352// Construct option array3353GrowableArrayCHeap<JavaVMOption, mtArguments> options(2);33543355// some pointers to help with parsing3356char *buffer_end = buffer + buf_len;3357char *opt_hd = buffer;3358char *wrt = buffer;3359char *rd = buffer;33603361// parse all options3362while (rd < buffer_end) {3363// skip leading white space from the input string3364while (rd < buffer_end && isspace(*rd)) {3365rd++;3366}33673368if (rd >= buffer_end) {3369break;3370}33713372// Remember this is where we found the head of the token.3373opt_hd = wrt;33743375// Tokens are strings of non white space characters separated3376// by one or more white spaces.3377while (rd < buffer_end && !isspace(*rd)) {3378if (*rd == '\'' || *rd == '"') { // handle a quoted string3379int quote = *rd; // matching quote to look for3380rd++; // don't copy open quote3381while (rd < buffer_end && *rd != quote) {3382// include everything (even spaces)3383// up until the close quote3384*wrt++ = *rd++; // copy to option string3385}33863387if (rd < buffer_end) {3388rd++; // don't copy close quote3389} else {3390// did not see closing quote3391jio_fprintf(defaultStream::error_stream(),3392"Unmatched quote in %s\n", name);3393return JNI_ERR;3394}3395} else {3396*wrt++ = *rd++; // copy to option string3397}3398}33993400// steal a white space character and set it to NULL3401*wrt++ = '\0';3402// We now have a complete token34033404JavaVMOption option;3405option.optionString = opt_hd;3406option.extraInfo = NULL;34073408options.append(option); // Fill in option34093410rd++; // Advance to next character3411}34123413// Fill out JavaVMInitArgs structure.3414return vm_args->set_args(&options);3415}34163417jint Arguments::set_shared_spaces_flags_and_archive_paths() {3418if (DumpSharedSpaces) {3419if (RequireSharedSpaces) {3420warning("Cannot dump shared archive while using shared archive");3421}3422UseSharedSpaces = false;3423}3424#if INCLUDE_CDS3425// Initialize shared archive paths which could include both base and dynamic archive paths3426// This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.3427if (!init_shared_archive_paths()) {3428return JNI_ENOMEM;3429}3430#endif // INCLUDE_CDS3431return JNI_OK;3432}34333434#if INCLUDE_CDS3435// Sharing support3436// Construct the path to the archive3437char* Arguments::get_default_shared_archive_path() {3438char *default_archive_path;3439char jvm_path[JVM_MAXPATHLEN];3440os::jvm_path(jvm_path, sizeof(jvm_path));3441char *end = strrchr(jvm_path, *os::file_separator());3442if (end != NULL) *end = '\0';3443size_t jvm_path_len = strlen(jvm_path);3444size_t file_sep_len = strlen(os::file_separator());3445const size_t len = jvm_path_len + file_sep_len + 20;3446default_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);3447jio_snprintf(default_archive_path, len,3448LP64_ONLY(!UseCompressedOops ? "%s%sclasses_nocoops.jsa":) "%s%sclasses.jsa",3449jvm_path, os::file_separator());3450return default_archive_path;3451}34523453int Arguments::num_archives(const char* archive_path) {3454if (archive_path == NULL) {3455return 0;3456}3457int npaths = 1;3458char* p = (char*)archive_path;3459while (*p != '\0') {3460if (*p == os::path_separator()[0]) {3461npaths++;3462}3463p++;3464}3465return npaths;3466}34673468void Arguments::extract_shared_archive_paths(const char* archive_path,3469char** base_archive_path,3470char** top_archive_path) {3471char* begin_ptr = (char*)archive_path;3472char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);3473if (end_ptr == NULL || end_ptr == begin_ptr) {3474vm_exit_during_initialization("Base archive was not specified", archive_path);3475}3476size_t len = end_ptr - begin_ptr;3477char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);3478strncpy(cur_path, begin_ptr, len);3479cur_path[len] = '\0';3480FileMapInfo::check_archive((const char*)cur_path, true /*is_static*/);3481*base_archive_path = cur_path;34823483begin_ptr = ++end_ptr;3484if (*begin_ptr == '\0') {3485vm_exit_during_initialization("Top archive was not specified", archive_path);3486}3487end_ptr = strchr(begin_ptr, '\0');3488assert(end_ptr != NULL, "sanity");3489len = end_ptr - begin_ptr;3490cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);3491strncpy(cur_path, begin_ptr, len + 1);3492//cur_path[len] = '\0';3493FileMapInfo::check_archive((const char*)cur_path, false /*is_static*/);3494*top_archive_path = cur_path;3495}34963497bool Arguments::init_shared_archive_paths() {3498if (ArchiveClassesAtExit != NULL) {3499if (DumpSharedSpaces) {3500vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");3501}3502if (FLAG_SET_CMDLINE(DynamicDumpSharedSpaces, true) != JVMFlag::SUCCESS) {3503return false;3504}3505check_unsupported_dumping_properties();3506SharedDynamicArchivePath = os::strdup_check_oom(ArchiveClassesAtExit, mtArguments);3507} else {3508if (SharedDynamicArchivePath != nullptr) {3509os::free(SharedDynamicArchivePath);3510SharedDynamicArchivePath = nullptr;3511}3512}3513if (SharedArchiveFile == NULL) {3514SharedArchivePath = get_default_shared_archive_path();3515} else {3516int archives = num_archives(SharedArchiveFile);3517if (is_dumping_archive()) {3518if (archives > 1) {3519vm_exit_during_initialization(3520"Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");3521}3522if (DynamicDumpSharedSpaces) {3523if (os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {3524vm_exit_during_initialization(3525"Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",3526SharedArchiveFile);3527}3528}3529}3530if (!is_dumping_archive()){3531if (archives > 2) {3532vm_exit_during_initialization(3533"Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");3534}3535if (archives == 1) {3536char* temp_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);3537int name_size;3538bool success =3539FileMapInfo::get_base_archive_name_from_header(temp_archive_path, &name_size, &SharedArchivePath);3540if (!success) {3541SharedArchivePath = temp_archive_path;3542} else {3543SharedDynamicArchivePath = temp_archive_path;3544}3545} else {3546extract_shared_archive_paths((const char*)SharedArchiveFile,3547&SharedArchivePath, &SharedDynamicArchivePath);3548}3549} else { // CDS dumping3550SharedArchivePath = os::strdup_check_oom(SharedArchiveFile, mtArguments);3551}3552}3553return (SharedArchivePath != NULL);3554}3555#endif // INCLUDE_CDS35563557#ifndef PRODUCT3558// Determine whether LogVMOutput should be implicitly turned on.3559static bool use_vm_log() {3560if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||3561PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||3562PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||3563PrintAssembly || TraceDeoptimization || TraceDependencies ||3564(VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {3565return true;3566}35673568#ifdef COMPILER13569if (PrintC1Statistics) {3570return true;3571}3572#endif // COMPILER135733574#ifdef COMPILER23575if (PrintOptoAssembly || PrintOptoStatistics) {3576return true;3577}3578#endif // COMPILER235793580return false;3581}35823583#endif // PRODUCT35843585bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {3586for (int index = 0; index < args->nOptions; index++) {3587const JavaVMOption* option = args->options + index;3588const char* tail;3589if (match_option(option, "-XX:VMOptionsFile=", &tail)) {3590return true;3591}3592}3593return false;3594}35953596jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,3597const char* vm_options_file,3598const int vm_options_file_pos,3599ScopedVMInitArgs* vm_options_file_args,3600ScopedVMInitArgs* args_out) {3601jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);3602if (code != JNI_OK) {3603return code;3604}36053606if (vm_options_file_args->get()->nOptions < 1) {3607return JNI_OK;3608}36093610if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {3611jio_fprintf(defaultStream::error_stream(),3612"A VM options file may not refer to a VM options file. "3613"Specification of '-XX:VMOptionsFile=<file-name>' in the "3614"options file '%s' in options container '%s' is an error.\n",3615vm_options_file_args->vm_options_file_arg(),3616vm_options_file_args->container_name());3617return JNI_EINVAL;3618}36193620return args_out->insert(args, vm_options_file_args->get(),3621vm_options_file_pos);3622}36233624// Expand -XX:VMOptionsFile found in args_in as needed.3625// mod_args and args_out parameters may return values as needed.3626jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,3627ScopedVMInitArgs* mod_args,3628JavaVMInitArgs** args_out) {3629jint code = match_special_option_and_act(args_in, mod_args);3630if (code != JNI_OK) {3631return code;3632}36333634if (mod_args->is_set()) {3635// args_in contains -XX:VMOptionsFile and mod_args contains the3636// original options from args_in along with the options expanded3637// from the VMOptionsFile. Return a short-hand to the caller.3638*args_out = mod_args->get();3639} else {3640*args_out = (JavaVMInitArgs *)args_in; // no changes so use args_in3641}3642return JNI_OK;3643}36443645jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,3646ScopedVMInitArgs* args_out) {3647// Remaining part of option string3648const char* tail;3649ScopedVMInitArgs vm_options_file_args(args_out->container_name());36503651for (int index = 0; index < args->nOptions; index++) {3652const JavaVMOption* option = args->options + index;3653if (match_option(option, "-XX:Flags=", &tail)) {3654Arguments::set_jvm_flags_file(tail);3655continue;3656}3657if (match_option(option, "-XX:VMOptionsFile=", &tail)) {3658if (vm_options_file_args.found_vm_options_file_arg()) {3659jio_fprintf(defaultStream::error_stream(),3660"The option '%s' is already specified in the options "3661"container '%s' so the specification of '%s' in the "3662"same options container is an error.\n",3663vm_options_file_args.vm_options_file_arg(),3664vm_options_file_args.container_name(),3665option->optionString);3666return JNI_EINVAL;3667}3668vm_options_file_args.set_vm_options_file_arg(option->optionString);3669// If there's a VMOptionsFile, parse that3670jint code = insert_vm_options_file(args, tail, index,3671&vm_options_file_args, args_out);3672if (code != JNI_OK) {3673return code;3674}3675args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());3676if (args_out->is_set()) {3677// The VMOptions file inserted some options so switch 'args'3678// to the new set of options, and continue processing which3679// preserves "last option wins" semantics.3680args = args_out->get();3681// The first option from the VMOptionsFile replaces the3682// current option. So we back track to process the3683// replacement option.3684index--;3685}3686continue;3687}3688if (match_option(option, "-XX:+PrintVMOptions")) {3689PrintVMOptions = true;3690continue;3691}3692if (match_option(option, "-XX:-PrintVMOptions")) {3693PrintVMOptions = false;3694continue;3695}3696if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {3697IgnoreUnrecognizedVMOptions = true;3698continue;3699}3700if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {3701IgnoreUnrecognizedVMOptions = false;3702continue;3703}3704if (match_option(option, "-XX:+PrintFlagsInitial")) {3705JVMFlag::printFlags(tty, false);3706vm_exit(0);3707}3708if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {3709#if INCLUDE_NMT3710// The launcher did not setup nmt environment variable properly.3711if (!MemTracker::check_launcher_nmt_support(tail)) {3712warning("Native Memory Tracking did not setup properly, using wrong launcher?");3713}37143715// Verify if nmt option is valid.3716if (MemTracker::verify_nmt_option()) {3717// Late initialization, still in single-threaded mode.3718if (MemTracker::tracking_level() >= NMT_summary) {3719MemTracker::init();3720}3721} else {3722vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);3723}3724continue;3725#else3726jio_fprintf(defaultStream::error_stream(),3727"Native Memory Tracking is not supported in this VM\n");3728return JNI_ERR;3729#endif3730}37313732#ifndef PRODUCT3733if (match_option(option, "-XX:+PrintFlagsWithComments")) {3734JVMFlag::printFlags(tty, true);3735vm_exit(0);3736}3737#endif3738}3739return JNI_OK;3740}37413742static void print_options(const JavaVMInitArgs *args) {3743const char* tail;3744for (int index = 0; index < args->nOptions; index++) {3745const JavaVMOption *option = args->options + index;3746if (match_option(option, "-XX:", &tail)) {3747logOption(tail);3748}3749}3750}37513752bool Arguments::handle_deprecated_print_gc_flags() {3753if (PrintGC) {3754log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");3755}3756if (PrintGCDetails) {3757log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");3758}37593760if (_gc_log_filename != NULL) {3761// -Xloggc was used to specify a filename3762const char* gc_conf = PrintGCDetails ? "gc*" : "gc";37633764LogTarget(Error, logging) target;3765LogStream errstream(target);3766return LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, &errstream);3767} else if (PrintGC || PrintGCDetails) {3768LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));3769}3770return true;3771}37723773static void apply_debugger_ergo() {3774if (ReplayCompiles) {3775FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo, true);3776}37773778if (UseDebuggerErgo) {3779// Turn on sub-flags3780FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo1, true);3781FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo2, true);3782}37833784if (UseDebuggerErgo2) {3785// Debugging with limited number of CPUs3786FLAG_SET_ERGO_IF_DEFAULT(UseNUMA, false);3787FLAG_SET_ERGO_IF_DEFAULT(ConcGCThreads, 1);3788FLAG_SET_ERGO_IF_DEFAULT(ParallelGCThreads, 1);3789FLAG_SET_ERGO_IF_DEFAULT(CICompilerCount, 2);3790}3791}37923793// Parse entry point called from JNI_CreateJavaVM37943795jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {3796assert(verify_special_jvm_flags(false), "deprecated and obsolete flag table inconsistent");3797JVMFlag::check_all_flag_declarations();37983799// If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.3800const char* hotspotrc = ".hotspotrc";3801bool settings_file_specified = false;3802bool needs_hotspotrc_warning = false;3803ScopedVMInitArgs initial_vm_options_args("");3804ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");3805ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");38063807// Pointers to current working set of containers3808JavaVMInitArgs* cur_cmd_args;3809JavaVMInitArgs* cur_vm_options_args;3810JavaVMInitArgs* cur_java_options_args;3811JavaVMInitArgs* cur_java_tool_options_args;38123813// Containers for modified/expanded options3814ScopedVMInitArgs mod_cmd_args("cmd_line_args");3815ScopedVMInitArgs mod_vm_options_args("vm_options_args");3816ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");3817ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");381838193820jint code =3821parse_java_tool_options_environment_variable(&initial_java_tool_options_args);3822if (code != JNI_OK) {3823return code;3824}38253826code = parse_java_options_environment_variable(&initial_java_options_args);3827if (code != JNI_OK) {3828return code;3829}38303831// Parse the options in the /java.base/jdk/internal/vm/options resource, if present3832char *vmoptions = ClassLoader::lookup_vm_options();3833if (vmoptions != NULL) {3834code = parse_options_buffer("vm options resource", vmoptions, strlen(vmoptions), &initial_vm_options_args);3835FREE_C_HEAP_ARRAY(char, vmoptions);3836if (code != JNI_OK) {3837return code;3838}3839}38403841code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),3842&mod_java_tool_options_args,3843&cur_java_tool_options_args);3844if (code != JNI_OK) {3845return code;3846}38473848code = expand_vm_options_as_needed(initial_cmd_args,3849&mod_cmd_args,3850&cur_cmd_args);3851if (code != JNI_OK) {3852return code;3853}38543855code = expand_vm_options_as_needed(initial_java_options_args.get(),3856&mod_java_options_args,3857&cur_java_options_args);3858if (code != JNI_OK) {3859return code;3860}38613862code = expand_vm_options_as_needed(initial_vm_options_args.get(),3863&mod_vm_options_args,3864&cur_vm_options_args);3865if (code != JNI_OK) {3866return code;3867}38683869const char* flags_file = Arguments::get_jvm_flags_file();3870settings_file_specified = (flags_file != NULL);38713872if (IgnoreUnrecognizedVMOptions) {3873cur_cmd_args->ignoreUnrecognized = true;3874cur_java_tool_options_args->ignoreUnrecognized = true;3875cur_java_options_args->ignoreUnrecognized = true;3876}38773878// Parse specified settings file3879if (settings_file_specified) {3880if (!process_settings_file(flags_file, true,3881cur_cmd_args->ignoreUnrecognized)) {3882return JNI_EINVAL;3883}3884} else {3885#ifdef ASSERT3886// Parse default .hotspotrc settings file3887if (!process_settings_file(".hotspotrc", false,3888cur_cmd_args->ignoreUnrecognized)) {3889return JNI_EINVAL;3890}3891#else3892struct stat buf;3893if (os::stat(hotspotrc, &buf) == 0) {3894needs_hotspotrc_warning = true;3895}3896#endif3897}38983899if (PrintVMOptions) {3900print_options(cur_java_tool_options_args);3901print_options(cur_cmd_args);3902print_options(cur_java_options_args);3903}39043905// Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS3906jint result = parse_vm_init_args(cur_vm_options_args,3907cur_java_tool_options_args,3908cur_java_options_args,3909cur_cmd_args);39103911if (result != JNI_OK) {3912return result;3913}39143915// Delay warning until here so that we've had a chance to process3916// the -XX:-PrintWarnings flag3917if (needs_hotspotrc_warning) {3918warning("%s file is present but has been ignored. "3919"Run with -XX:Flags=%s to load the file.",3920hotspotrc, hotspotrc);3921}39223923if (needs_module_property_warning) {3924warning("Ignoring system property options whose names match the '-Djdk.module.*'."3925" names that are reserved for internal use.");3926}39273928#if defined(_ALLBSD_SOURCE) || defined(AIX) // UseLargePages is not yet supported on BSD and AIX.3929UNSUPPORTED_OPTION(UseLargePages);3930#endif39313932#if defined(AIX)3933UNSUPPORTED_OPTION_NULL(AllocateHeapAt);3934#endif39353936#ifndef PRODUCT3937if (TraceBytecodesAt != 0) {3938TraceBytecodes = true;3939}3940if (CountCompiledCalls) {3941if (UseCounterDecay) {3942warning("UseCounterDecay disabled because CountCalls is set");3943UseCounterDecay = false;3944}3945}3946#endif // PRODUCT39473948if (ScavengeRootsInCode == 0) {3949if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {3950warning("Forcing ScavengeRootsInCode non-zero");3951}3952ScavengeRootsInCode = 1;3953}39543955if (!handle_deprecated_print_gc_flags()) {3956return JNI_EINVAL;3957}39583959// Set object alignment values.3960set_object_alignment();39613962#if !INCLUDE_CDS3963if (DumpSharedSpaces || RequireSharedSpaces) {3964jio_fprintf(defaultStream::error_stream(),3965"Shared spaces are not supported in this VM\n");3966return JNI_ERR;3967}3968if (DumpLoadedClassList != NULL) {3969jio_fprintf(defaultStream::error_stream(),3970"DumpLoadedClassList is not supported in this VM\n");3971return JNI_ERR;3972}3973if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) ||3974log_is_enabled(Info, cds)) {3975warning("Shared spaces are not supported in this VM");3976FLAG_SET_DEFAULT(UseSharedSpaces, false);3977LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(cds));3978}3979no_shared_spaces("CDS Disabled");3980#endif // INCLUDE_CDS39813982if (TraceDependencies && VerifyDependencies) {3983if (!FLAG_IS_DEFAULT(TraceDependencies)) {3984warning("TraceDependencies results may be inflated by VerifyDependencies");3985}3986}39873988apply_debugger_ergo();39893990return JNI_OK;3991}39923993jint Arguments::apply_ergo() {3994// Set flags based on ergonomics.3995jint result = set_ergonomics_flags();3996if (result != JNI_OK) return result;39973998// Set heap size based on available physical memory3999set_heap_size();40004001GCConfig::arguments()->initialize();40024003result = set_shared_spaces_flags_and_archive_paths();4004if (result != JNI_OK) return result;40054006// Initialize Metaspace flags and alignments4007Metaspace::ergo_initialize();40084009if (!StringDedup::ergo_initialize()) {4010return JNI_EINVAL;4011}40124013// Set compiler flags after GC is selected and GC specific4014// flags (LoopStripMiningIter) are set.4015CompilerConfig::ergo_initialize();40164017// Set bytecode rewriting flags4018set_bytecode_flags();40194020// Set flags if aggressive optimization flags are enabled4021jint code = set_aggressive_opts_flags();4022if (code != JNI_OK) {4023return code;4024}40254026// Turn off biased locking for locking debug mode flags,4027// which are subtly different from each other but neither works with4028// biased locking4029if (UseHeavyMonitors4030#ifdef COMPILER14031|| !UseFastLocking4032#endif // COMPILER14033#if INCLUDE_JVMCI4034|| !JVMCIUseFastLocking4035#endif4036) {4037if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {4038// flag set to true on command line; warn the user that they4039// can't enable biased locking here4040warning("Biased Locking is not supported with locking debug flags"4041"; ignoring UseBiasedLocking flag." );4042}4043UseBiasedLocking = false;4044}40454046#ifdef ZERO4047// Clear flags not supported on zero.4048FLAG_SET_DEFAULT(ProfileInterpreter, false);4049FLAG_SET_DEFAULT(UseBiasedLocking, false);4050#endif // ZERO40514052if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {4053warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");4054DebugNonSafepoints = true;4055}40564057if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {4058warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");4059}40604061// Treat the odd case where local verification is enabled but remote4062// verification is not as if both were enabled.4063if (BytecodeVerificationLocal && !BytecodeVerificationRemote) {4064log_info(verification)("Turning on remote verification because local verification is on");4065FLAG_SET_DEFAULT(BytecodeVerificationRemote, true);4066}40674068#ifndef PRODUCT4069if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {4070if (use_vm_log()) {4071LogVMOutput = true;4072}4073}4074#endif // PRODUCT40754076if (PrintCommandLineFlags) {4077JVMFlag::printSetFlags(tty);4078}40794080// Apply CPU specific policy for the BiasedLocking4081if (UseBiasedLocking) {4082if (!VM_Version::use_biased_locking() &&4083!(FLAG_IS_CMDLINE(UseBiasedLocking))) {4084UseBiasedLocking = false;4085}4086}4087#ifdef COMPILER24088if (!UseBiasedLocking) {4089UseOptoBiasInlining = false;4090}40914092if (!FLAG_IS_DEFAULT(EnableVectorSupport) && !EnableVectorSupport) {4093if (!FLAG_IS_DEFAULT(EnableVectorReboxing) && EnableVectorReboxing) {4094warning("Disabling EnableVectorReboxing since EnableVectorSupport is turned off.");4095}4096FLAG_SET_DEFAULT(EnableVectorReboxing, false);40974098if (!FLAG_IS_DEFAULT(EnableVectorAggressiveReboxing) && EnableVectorAggressiveReboxing) {4099if (!EnableVectorReboxing) {4100warning("Disabling EnableVectorAggressiveReboxing since EnableVectorReboxing is turned off.");4101} else {4102warning("Disabling EnableVectorAggressiveReboxing since EnableVectorSupport is turned off.");4103}4104}4105FLAG_SET_DEFAULT(EnableVectorAggressiveReboxing, false);41064107if (!FLAG_IS_DEFAULT(UseVectorStubs) && UseVectorStubs) {4108warning("Disabling UseVectorStubs since EnableVectorSupport is turned off.");4109}4110FLAG_SET_DEFAULT(UseVectorStubs, false);4111}4112#endif // COMPILER241134114if (FLAG_IS_CMDLINE(DiagnoseSyncOnValueBasedClasses)) {4115if (DiagnoseSyncOnValueBasedClasses == ObjectSynchronizer::LOG_WARNING && !log_is_enabled(Info, valuebasedclasses)) {4116LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(valuebasedclasses));4117}4118}4119return JNI_OK;4120}41214122jint Arguments::adjust_after_os() {4123if (UseNUMA) {4124if (UseParallelGC) {4125if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {4126FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);4127}4128}4129}4130return JNI_OK;4131}41324133int Arguments::PropertyList_count(SystemProperty* pl) {4134int count = 0;4135while(pl != NULL) {4136count++;4137pl = pl->next();4138}4139return count;4140}41414142// Return the number of readable properties.4143int Arguments::PropertyList_readable_count(SystemProperty* pl) {4144int count = 0;4145while(pl != NULL) {4146if (pl->is_readable()) {4147count++;4148}4149pl = pl->next();4150}4151return count;4152}41534154const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {4155assert(key != NULL, "just checking");4156SystemProperty* prop;4157for (prop = pl; prop != NULL; prop = prop->next()) {4158if (strcmp(key, prop->key()) == 0) return prop->value();4159}4160return NULL;4161}41624163// Return the value of the requested property provided that it is a readable property.4164const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {4165assert(key != NULL, "just checking");4166SystemProperty* prop;4167// Return the property value if the keys match and the property is not internal or4168// it's the special internal property "jdk.boot.class.path.append".4169for (prop = pl; prop != NULL; prop = prop->next()) {4170if (strcmp(key, prop->key()) == 0) {4171if (!prop->internal()) {4172return prop->value();4173} else if (strcmp(key, "jdk.boot.class.path.append") == 0) {4174return prop->value();4175} else {4176// Property is internal and not jdk.boot.class.path.append so return NULL.4177return NULL;4178}4179}4180}4181return NULL;4182}41834184const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {4185int count = 0;4186const char* ret_val = NULL;41874188while(pl != NULL) {4189if(count >= index) {4190ret_val = pl->key();4191break;4192}4193count++;4194pl = pl->next();4195}41964197return ret_val;4198}41994200char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {4201int count = 0;4202char* ret_val = NULL;42034204while(pl != NULL) {4205if(count >= index) {4206ret_val = pl->value();4207break;4208}4209count++;4210pl = pl->next();4211}42124213return ret_val;4214}42154216void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {4217SystemProperty* p = *plist;4218if (p == NULL) {4219*plist = new_p;4220} else {4221while (p->next() != NULL) {4222p = p->next();4223}4224p->set_next(new_p);4225}4226}42274228void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,4229bool writeable, bool internal) {4230if (plist == NULL)4231return;42324233SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);4234PropertyList_add(plist, new_p);4235}42364237void Arguments::PropertyList_add(SystemProperty *element) {4238PropertyList_add(&_system_properties, element);4239}42404241// This add maintains unique property key in the list.4242void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,4243PropertyAppendable append, PropertyWriteable writeable,4244PropertyInternal internal) {4245if (plist == NULL)4246return;42474248// If property key exists and is writeable, then update with new value.4249// Trying to update a non-writeable property is silently ignored.4250SystemProperty* prop;4251for (prop = *plist; prop != NULL; prop = prop->next()) {4252if (strcmp(k, prop->key()) == 0) {4253if (append == AppendProperty) {4254prop->append_writeable_value(v);4255} else {4256prop->set_writeable_value(v);4257}4258return;4259}4260}42614262PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);4263}42644265// Copies src into buf, replacing "%%" with "%" and "%p" with pid4266// Returns true if all of the source pointed by src has been copied over to4267// the destination buffer pointed by buf. Otherwise, returns false.4268// Notes:4269// 1. If the length (buflen) of the destination buffer excluding the4270// NULL terminator character is not long enough for holding the expanded4271// pid characters, it also returns false instead of returning the partially4272// expanded one.4273// 2. The passed in "buflen" should be large enough to hold the null terminator.4274bool Arguments::copy_expand_pid(const char* src, size_t srclen,4275char* buf, size_t buflen) {4276const char* p = src;4277char* b = buf;4278const char* src_end = &src[srclen];4279char* buf_end = &buf[buflen - 1];42804281while (p < src_end && b < buf_end) {4282if (*p == '%') {4283switch (*(++p)) {4284case '%': // "%%" ==> "%"4285*b++ = *p++;4286break;4287case 'p': { // "%p" ==> current process id4288// buf_end points to the character before the last character so4289// that we could write '\0' to the end of the buffer.4290size_t buf_sz = buf_end - b + 1;4291int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());42924293// if jio_snprintf fails or the buffer is not long enough to hold4294// the expanded pid, returns false.4295if (ret < 0 || ret >= (int)buf_sz) {4296return false;4297} else {4298b += ret;4299assert(*b == '\0', "fail in copy_expand_pid");4300if (p == src_end && b == buf_end + 1) {4301// reach the end of the buffer.4302return true;4303}4304}4305p++;4306break;4307}4308default :4309*b++ = '%';4310}4311} else {4312*b++ = *p++;4313}4314}4315*b = '\0';4316return (p == src_end); // return false if not all of the source was copied4317}431843194320