Path: blob/master/src/hotspot/share/runtime/arguments.cpp
64440 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/nmtCommon.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}19861987status = CompilerConfig::check_args_consistency(status);1988#if INCLUDE_JVMCI1989if (status && EnableJVMCI) {1990PropertyList_unique_add(&_system_properties, "jdk.internal.vm.ci.enabled", "true",1991AddProperty, UnwriteableProperty, InternalProperty);1992if (!create_numbered_module_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {1993return false;1994}1995}1996#endif19971998#ifndef SUPPORT_RESERVED_STACK_AREA1999if (StackReservedPages != 0) {2000FLAG_SET_CMDLINE(StackReservedPages, 0);2001warning("Reserved Stack Area not supported on this platform");2002}2003#endif20042005return status;2006}20072008bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,2009const char* option_type) {2010if (ignore) return false;20112012const char* spacer = " ";2013if (option_type == NULL) {2014option_type = ++spacer; // Set both to the empty string.2015}20162017jio_fprintf(defaultStream::error_stream(),2018"Unrecognized %s%soption: %s\n", option_type, spacer,2019option->optionString);2020return true;2021}20222023static const char* user_assertion_options[] = {2024"-da", "-ea", "-disableassertions", "-enableassertions", 02025};20262027static const char* system_assertion_options[] = {2028"-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 02029};20302031bool Arguments::parse_uintx(const char* value,2032uintx* uintx_arg,2033uintx min_size) {20342035// Check the sign first since atojulong() parses only unsigned values.2036bool value_is_positive = !(*value == '-');20372038if (value_is_positive) {2039julong n;2040bool good_return = atojulong(value, &n);2041if (good_return) {2042bool above_minimum = n >= min_size;2043bool value_is_too_large = n > max_uintx;20442045if (above_minimum && !value_is_too_large) {2046*uintx_arg = n;2047return true;2048}2049}2050}2051return false;2052}20532054bool Arguments::create_module_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {2055assert(is_internal_module_property(prop_name), "unknown module property: '%s'", prop_name);2056size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;2057char* property = AllocateHeap(prop_len, mtArguments);2058int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);2059if (ret < 0 || ret >= (int)prop_len) {2060FreeHeap(property);2061return false;2062}2063// These are not strictly writeable properties as they cannot be set via -Dprop=val. But that2064// is enforced by checking is_internal_module_property(). We need the property to be writeable so2065// that multiple occurrences of the associated flag just causes the existing property value to be2066// replaced ("last option wins"). Otherwise we would need to keep track of the flags and only convert2067// to a property after we have finished flag processing.2068bool added = add_property(property, WriteableProperty, internal);2069FreeHeap(property);2070return added;2071}20722073bool Arguments::create_numbered_module_property(const char* prop_base_name, const char* prop_value, unsigned int count) {2074assert(is_internal_module_property(prop_base_name), "unknown module property: '%s'", prop_base_name);2075const unsigned int props_count_limit = 1000;2076const int max_digits = 3;2077const int extra_symbols_count = 3; // includes '.', '=', '\0'20782079// Make sure count is < props_count_limit. Otherwise, memory allocation will be too small.2080if (count < props_count_limit) {2081size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + max_digits + extra_symbols_count;2082char* property = AllocateHeap(prop_len, mtArguments);2083int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);2084if (ret < 0 || ret >= (int)prop_len) {2085FreeHeap(property);2086jio_fprintf(defaultStream::error_stream(), "Failed to create property %s.%d=%s\n", prop_base_name, count, prop_value);2087return false;2088}2089bool added = add_property(property, UnwriteableProperty, InternalProperty);2090FreeHeap(property);2091return added;2092}20932094jio_fprintf(defaultStream::error_stream(), "Property count limit exceeded: %s, limit=%d\n", prop_base_name, props_count_limit);2095return false;2096}20972098Arguments::ArgsRange Arguments::parse_memory_size(const char* s,2099julong* long_arg,2100julong min_size,2101julong max_size) {2102if (!atojulong(s, long_arg)) return arg_unreadable;2103return check_memory_size(*long_arg, min_size, max_size);2104}21052106// Parse JavaVMInitArgs structure21072108jint Arguments::parse_vm_init_args(const JavaVMInitArgs *vm_options_args,2109const JavaVMInitArgs *java_tool_options_args,2110const JavaVMInitArgs *java_options_args,2111const JavaVMInitArgs *cmd_line_args) {2112bool patch_mod_javabase = false;21132114// Save default settings for some mode flags2115Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;2116Arguments::_UseOnStackReplacement = UseOnStackReplacement;2117Arguments::_ClipInlining = ClipInlining;2118Arguments::_BackgroundCompilation = BackgroundCompilation;21192120// Remember the default value of SharedBaseAddress.2121Arguments::_default_SharedBaseAddress = SharedBaseAddress;21222123// Setup flags for mixed which is the default2124set_mode_flags(_mixed);21252126// Parse args structure generated from java.base vm options resource2127jint result = parse_each_vm_init_arg(vm_options_args, &patch_mod_javabase, JVMFlagOrigin::JIMAGE_RESOURCE);2128if (result != JNI_OK) {2129return result;2130}21312132// Parse args structure generated from JAVA_TOOL_OPTIONS environment2133// variable (if present).2134result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR);2135if (result != JNI_OK) {2136return result;2137}21382139// Parse args structure generated from the command line flags.2140result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, JVMFlagOrigin::COMMAND_LINE);2141if (result != JNI_OK) {2142return result;2143}21442145// Parse args structure generated from the _JAVA_OPTIONS environment2146// variable (if present) (mimics classic VM)2147result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR);2148if (result != JNI_OK) {2149return result;2150}21512152// We need to ensure processor and memory resources have been properly2153// configured - which may rely on arguments we just processed - before2154// doing the final argument processing. Any argument processing that2155// needs to know about processor and memory resources must occur after2156// this point.21572158os::init_container_support();21592160// Do final processing now that all arguments have been parsed2161result = finalize_vm_init_args(patch_mod_javabase);2162if (result != JNI_OK) {2163return result;2164}21652166return JNI_OK;2167}21682169// Checks if name in command-line argument -agent{lib,path}:name[=options]2170// represents a valid JDWP agent. is_path==true denotes that we2171// are dealing with -agentpath (case where name is a path), otherwise with2172// -agentlib2173bool valid_jdwp_agent(char *name, bool is_path) {2174char *_name;2175const char *_jdwp = "jdwp";2176size_t _len_jdwp, _len_prefix;21772178if (is_path) {2179if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {2180return false;2181}21822183_name++; // skip past last path separator2184_len_prefix = strlen(JNI_LIB_PREFIX);21852186if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {2187return false;2188}21892190_name += _len_prefix;2191_len_jdwp = strlen(_jdwp);21922193if (strncmp(_name, _jdwp, _len_jdwp) == 0) {2194_name += _len_jdwp;2195}2196else {2197return false;2198}21992200if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {2201return false;2202}22032204return true;2205}22062207if (strcmp(name, _jdwp) == 0) {2208return true;2209}22102211return false;2212}22132214int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {2215// --patch-module=<module>=<file>(<pathsep><file>)*2216assert(patch_mod_tail != NULL, "Unexpected NULL patch-module value");2217// Find the equal sign between the module name and the path specification2218const char* module_equal = strchr(patch_mod_tail, '=');2219if (module_equal == NULL) {2220jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");2221return JNI_ERR;2222} else {2223// Pick out the module name2224size_t module_len = module_equal - patch_mod_tail;2225char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);2226if (module_name != NULL) {2227memcpy(module_name, patch_mod_tail, module_len);2228*(module_name + module_len) = '\0';2229// The path piece begins one past the module_equal sign2230add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);2231FREE_C_HEAP_ARRAY(char, module_name);2232if (!create_numbered_module_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {2233return JNI_ENOMEM;2234}2235} else {2236return JNI_ENOMEM;2237}2238}2239return JNI_OK;2240}22412242// Parse -Xss memory string parameter and convert to ThreadStackSize in K.2243jint Arguments::parse_xss(const JavaVMOption* option, const char* tail, intx* out_ThreadStackSize) {2244// The min and max sizes match the values in globals.hpp, but scaled2245// with K. The values have been chosen so that alignment with page2246// size doesn't change the max value, which makes the conversions2247// back and forth between Xss value and ThreadStackSize value easier.2248// The values have also been chosen to fit inside a 32-bit signed type.2249const julong min_ThreadStackSize = 0;2250const julong max_ThreadStackSize = 1 * M;22512252// Make sure the above values match the range set in globals.hpp2253const JVMTypedFlagLimit<intx>* limit = JVMFlagLimit::get_range_at(FLAG_MEMBER_ENUM(ThreadStackSize))->cast<intx>();2254assert(min_ThreadStackSize == static_cast<julong>(limit->min()), "must be");2255assert(max_ThreadStackSize == static_cast<julong>(limit->max()), "must be");22562257const julong min_size = min_ThreadStackSize * K;2258const julong max_size = max_ThreadStackSize * K;22592260assert(is_aligned(max_size, os::vm_page_size()), "Implementation assumption");22612262julong size = 0;2263ArgsRange errcode = parse_memory_size(tail, &size, min_size, max_size);2264if (errcode != arg_in_range) {2265bool silent = (option == NULL); // Allow testing to silence error messages2266if (!silent) {2267jio_fprintf(defaultStream::error_stream(),2268"Invalid thread stack size: %s\n", option->optionString);2269describe_range_error(errcode);2270}2271return JNI_EINVAL;2272}22732274// Internally track ThreadStackSize in units of 1024 bytes.2275const julong size_aligned = align_up(size, K);2276assert(size <= size_aligned,2277"Overflow: " JULONG_FORMAT " " JULONG_FORMAT,2278size, size_aligned);22792280const julong size_in_K = size_aligned / K;2281assert(size_in_K < (julong)max_intx,2282"size_in_K doesn't fit in the type of ThreadStackSize: " JULONG_FORMAT,2283size_in_K);22842285// Check that code expanding ThreadStackSize to a page aligned number of bytes won't overflow.2286const julong max_expanded = align_up(size_in_K * K, os::vm_page_size());2287assert(max_expanded < max_uintx && max_expanded >= size_in_K,2288"Expansion overflowed: " JULONG_FORMAT " " JULONG_FORMAT,2289max_expanded, size_in_K);22902291*out_ThreadStackSize = (intx)size_in_K;22922293return JNI_OK;2294}22952296jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, JVMFlagOrigin origin) {2297// For match_option to return remaining or value part of option string2298const char* tail;22992300// iterate over arguments2301for (int index = 0; index < args->nOptions; index++) {2302bool is_absolute_path = false; // for -agentpath vs -agentlib23032304const JavaVMOption* option = args->options + index;23052306if (!match_option(option, "-Djava.class.path", &tail) &&2307!match_option(option, "-Dsun.java.command", &tail) &&2308!match_option(option, "-Dsun.java.launcher", &tail)) {23092310// add all jvm options to the jvm_args string. This string2311// is used later to set the java.vm.args PerfData string constant.2312// the -Djava.class.path and the -Dsun.java.command options are2313// omitted from jvm_args string as each have their own PerfData2314// string constant object.2315build_jvm_args(option->optionString);2316}23172318// -verbose:[class/module/gc/jni]2319if (match_option(option, "-verbose", &tail)) {2320if (!strcmp(tail, ":class") || !strcmp(tail, "")) {2321LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));2322LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));2323} else if (!strcmp(tail, ":module")) {2324LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, load));2325LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, unload));2326} else if (!strcmp(tail, ":gc")) {2327LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(gc));2328} else if (!strcmp(tail, ":jni")) {2329LogConfiguration::configure_stdout(LogLevel::Debug, true, LOG_TAGS(jni, resolve));2330}2331// -da / -ea / -disableassertions / -enableassertions2332// These accept an optional class/package name separated by a colon, e.g.,2333// -da:java.lang.Thread.2334} else if (match_option(option, user_assertion_options, &tail, true)) {2335bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'2336if (*tail == '\0') {2337JavaAssertions::setUserClassDefault(enable);2338} else {2339assert(*tail == ':', "bogus match by match_option()");2340JavaAssertions::addOption(tail + 1, enable);2341}2342// -dsa / -esa / -disablesystemassertions / -enablesystemassertions2343} else if (match_option(option, system_assertion_options, &tail, false)) {2344bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'2345JavaAssertions::setSystemClassDefault(enable);2346// -bootclasspath:2347} else if (match_option(option, "-Xbootclasspath:", &tail)) {2348jio_fprintf(defaultStream::output_stream(),2349"-Xbootclasspath is no longer a supported option.\n");2350return JNI_EINVAL;2351// -bootclasspath/a:2352} else if (match_option(option, "-Xbootclasspath/a:", &tail)) {2353Arguments::append_sysclasspath(tail);2354#if INCLUDE_CDS2355MetaspaceShared::disable_optimized_module_handling();2356log_info(cds)("optimized module handling: disabled because bootclasspath was appended");2357#endif2358// -bootclasspath/p:2359} else if (match_option(option, "-Xbootclasspath/p:", &tail)) {2360jio_fprintf(defaultStream::output_stream(),2361"-Xbootclasspath/p is no longer a supported option.\n");2362return JNI_EINVAL;2363// -Xrun2364} else if (match_option(option, "-Xrun", &tail)) {2365if (tail != NULL) {2366const char* pos = strchr(tail, ':');2367size_t len = (pos == NULL) ? strlen(tail) : pos - tail;2368char* name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);2369jio_snprintf(name, len + 1, "%s", tail);23702371char *options = NULL;2372if(pos != NULL) {2373size_t len2 = strlen(pos+1) + 1; // options start after ':'. Final zero must be copied.2374options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);2375}2376#if !INCLUDE_JVMTI2377if (strcmp(name, "jdwp") == 0) {2378jio_fprintf(defaultStream::error_stream(),2379"Debugging agents are not supported in this VM\n");2380return JNI_ERR;2381}2382#endif // !INCLUDE_JVMTI2383add_init_library(name, options);2384}2385} else if (match_option(option, "--add-reads=", &tail)) {2386if (!create_numbered_module_property("jdk.module.addreads", tail, addreads_count++)) {2387return JNI_ENOMEM;2388}2389} else if (match_option(option, "--add-exports=", &tail)) {2390if (!create_numbered_module_property("jdk.module.addexports", tail, addexports_count++)) {2391return JNI_ENOMEM;2392}2393} else if (match_option(option, "--add-opens=", &tail)) {2394if (!create_numbered_module_property("jdk.module.addopens", tail, addopens_count++)) {2395return JNI_ENOMEM;2396}2397} else if (match_option(option, "--add-modules=", &tail)) {2398if (!create_numbered_module_property("jdk.module.addmods", tail, addmods_count++)) {2399return JNI_ENOMEM;2400}2401} else if (match_option(option, "--enable-native-access=", &tail)) {2402if (!create_numbered_module_property("jdk.module.enable.native.access", tail, enable_native_access_count++)) {2403return JNI_ENOMEM;2404}2405} else if (match_option(option, "--limit-modules=", &tail)) {2406if (!create_module_property("jdk.module.limitmods", tail, InternalProperty)) {2407return JNI_ENOMEM;2408}2409} else if (match_option(option, "--module-path=", &tail)) {2410if (!create_module_property("jdk.module.path", tail, ExternalProperty)) {2411return JNI_ENOMEM;2412}2413} else if (match_option(option, "--upgrade-module-path=", &tail)) {2414if (!create_module_property("jdk.module.upgrade.path", tail, ExternalProperty)) {2415return JNI_ENOMEM;2416}2417} else if (match_option(option, "--patch-module=", &tail)) {2418// --patch-module=<module>=<file>(<pathsep><file>)*2419int res = process_patch_mod_option(tail, patch_mod_javabase);2420if (res != JNI_OK) {2421return res;2422}2423} else if (match_option(option, "--illegal-access=", &tail)) {2424char version[256];2425JDK_Version::jdk(17).to_string(version, sizeof(version));2426warning("Ignoring option %s; support was removed in %s", option->optionString, version);2427// -agentlib and -agentpath2428} else if (match_option(option, "-agentlib:", &tail) ||2429(is_absolute_path = match_option(option, "-agentpath:", &tail))) {2430if(tail != NULL) {2431const char* pos = strchr(tail, '=');2432char* name;2433if (pos == NULL) {2434name = os::strdup_check_oom(tail, mtArguments);2435} else {2436size_t len = pos - tail;2437name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);2438memcpy(name, tail, len);2439name[len] = '\0';2440}24412442char *options = NULL;2443if(pos != NULL) {2444options = os::strdup_check_oom(pos + 1, mtArguments);2445}2446#if !INCLUDE_JVMTI2447if (valid_jdwp_agent(name, is_absolute_path)) {2448jio_fprintf(defaultStream::error_stream(),2449"Debugging agents are not supported in this VM\n");2450return JNI_ERR;2451}2452#endif // !INCLUDE_JVMTI2453add_init_agent(name, options, is_absolute_path);2454}2455// -javaagent2456} else if (match_option(option, "-javaagent:", &tail)) {2457#if !INCLUDE_JVMTI2458jio_fprintf(defaultStream::error_stream(),2459"Instrumentation agents are not supported in this VM\n");2460return JNI_ERR;2461#else2462if (tail != NULL) {2463size_t length = strlen(tail) + 1;2464char *options = NEW_C_HEAP_ARRAY(char, length, mtArguments);2465jio_snprintf(options, length, "%s", tail);2466add_instrument_agent("instrument", options, false);2467// java agents need module java.instrument2468if (!create_numbered_module_property("jdk.module.addmods", "java.instrument", addmods_count++)) {2469return JNI_ENOMEM;2470}2471}2472#endif // !INCLUDE_JVMTI2473// --enable_preview2474} else if (match_option(option, "--enable-preview")) {2475set_enable_preview();2476// -Xnoclassgc2477} else if (match_option(option, "-Xnoclassgc")) {2478if (FLAG_SET_CMDLINE(ClassUnloading, false) != JVMFlag::SUCCESS) {2479return JNI_EINVAL;2480}2481// -Xbatch2482} else if (match_option(option, "-Xbatch")) {2483if (FLAG_SET_CMDLINE(BackgroundCompilation, false) != JVMFlag::SUCCESS) {2484return JNI_EINVAL;2485}2486// -Xmn for compatibility with other JVM vendors2487} else if (match_option(option, "-Xmn", &tail)) {2488julong long_initial_young_size = 0;2489ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);2490if (errcode != arg_in_range) {2491jio_fprintf(defaultStream::error_stream(),2492"Invalid initial young generation size: %s\n", option->optionString);2493describe_range_error(errcode);2494return JNI_EINVAL;2495}2496if (FLAG_SET_CMDLINE(MaxNewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {2497return JNI_EINVAL;2498}2499if (FLAG_SET_CMDLINE(NewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {2500return JNI_EINVAL;2501}2502// -Xms2503} else if (match_option(option, "-Xms", &tail)) {2504julong size = 0;2505// an initial heap size of 0 means automatically determine2506ArgsRange errcode = parse_memory_size(tail, &size, 0);2507if (errcode != arg_in_range) {2508jio_fprintf(defaultStream::error_stream(),2509"Invalid initial heap size: %s\n", option->optionString);2510describe_range_error(errcode);2511return JNI_EINVAL;2512}2513if (FLAG_SET_CMDLINE(MinHeapSize, (size_t)size) != JVMFlag::SUCCESS) {2514return JNI_EINVAL;2515}2516if (FLAG_SET_CMDLINE(InitialHeapSize, (size_t)size) != JVMFlag::SUCCESS) {2517return JNI_EINVAL;2518}2519// -Xmx2520} else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {2521julong long_max_heap_size = 0;2522ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);2523if (errcode != arg_in_range) {2524jio_fprintf(defaultStream::error_stream(),2525"Invalid maximum heap size: %s\n", option->optionString);2526describe_range_error(errcode);2527return JNI_EINVAL;2528}2529if (FLAG_SET_CMDLINE(MaxHeapSize, (size_t)long_max_heap_size) != JVMFlag::SUCCESS) {2530return JNI_EINVAL;2531}2532// Xmaxf2533} else if (match_option(option, "-Xmaxf", &tail)) {2534char* err;2535int maxf = (int)(strtod(tail, &err) * 100);2536if (*err != '\0' || *tail == '\0') {2537jio_fprintf(defaultStream::error_stream(),2538"Bad max heap free percentage size: %s\n",2539option->optionString);2540return JNI_EINVAL;2541} else {2542if (FLAG_SET_CMDLINE(MaxHeapFreeRatio, maxf) != JVMFlag::SUCCESS) {2543return JNI_EINVAL;2544}2545}2546// Xminf2547} else if (match_option(option, "-Xminf", &tail)) {2548char* err;2549int minf = (int)(strtod(tail, &err) * 100);2550if (*err != '\0' || *tail == '\0') {2551jio_fprintf(defaultStream::error_stream(),2552"Bad min heap free percentage size: %s\n",2553option->optionString);2554return JNI_EINVAL;2555} else {2556if (FLAG_SET_CMDLINE(MinHeapFreeRatio, minf) != JVMFlag::SUCCESS) {2557return JNI_EINVAL;2558}2559}2560// -Xss2561} else if (match_option(option, "-Xss", &tail)) {2562intx value = 0;2563jint err = parse_xss(option, tail, &value);2564if (err != JNI_OK) {2565return err;2566}2567if (FLAG_SET_CMDLINE(ThreadStackSize, value) != JVMFlag::SUCCESS) {2568return JNI_EINVAL;2569}2570} else if (match_option(option, "-Xmaxjitcodesize", &tail) ||2571match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {2572julong long_ReservedCodeCacheSize = 0;25732574ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);2575if (errcode != arg_in_range) {2576jio_fprintf(defaultStream::error_stream(),2577"Invalid maximum code cache size: %s.\n", option->optionString);2578return JNI_EINVAL;2579}2580if (FLAG_SET_CMDLINE(ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != JVMFlag::SUCCESS) {2581return JNI_EINVAL;2582}2583// -green2584} else if (match_option(option, "-green")) {2585jio_fprintf(defaultStream::error_stream(),2586"Green threads support not available\n");2587return JNI_EINVAL;2588// -native2589} else if (match_option(option, "-native")) {2590// HotSpot always uses native threads, ignore silently for compatibility2591// -Xrs2592} else if (match_option(option, "-Xrs")) {2593// Classic/EVM option, new functionality2594if (FLAG_SET_CMDLINE(ReduceSignalUsage, true) != JVMFlag::SUCCESS) {2595return JNI_EINVAL;2596}2597// -Xprof2598} else if (match_option(option, "-Xprof")) {2599char version[256];2600// Obsolete in JDK 102601JDK_Version::jdk(10).to_string(version, sizeof(version));2602warning("Ignoring option %s; support was removed in %s", option->optionString, version);2603// -Xinternalversion2604} else if (match_option(option, "-Xinternalversion")) {2605jio_fprintf(defaultStream::output_stream(), "%s\n",2606VM_Version::internal_vm_info_string());2607vm_exit(0);2608#ifndef PRODUCT2609// -Xprintflags2610} else if (match_option(option, "-Xprintflags")) {2611JVMFlag::printFlags(tty, false);2612vm_exit(0);2613#endif2614// -D2615} else if (match_option(option, "-D", &tail)) {2616const char* value;2617if (match_option(option, "-Djava.endorsed.dirs=", &value) &&2618*value!= '\0' && strcmp(value, "\"\"") != 0) {2619// abort if -Djava.endorsed.dirs is set2620jio_fprintf(defaultStream::output_stream(),2621"-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"2622"in modular form will be supported via the concept of upgradeable modules.\n", value);2623return JNI_EINVAL;2624}2625if (match_option(option, "-Djava.ext.dirs=", &value) &&2626*value != '\0' && strcmp(value, "\"\"") != 0) {2627// abort if -Djava.ext.dirs is set2628jio_fprintf(defaultStream::output_stream(),2629"-Djava.ext.dirs=%s is not supported. Use -classpath instead.\n", value);2630return JNI_EINVAL;2631}2632// Check for module related properties. They must be set using the modules2633// options. For example: use "--add-modules=java.sql", not2634// "-Djdk.module.addmods=java.sql"2635if (is_internal_module_property(option->optionString + 2)) {2636needs_module_property_warning = true;2637continue;2638}2639if (!add_property(tail)) {2640return JNI_ENOMEM;2641}2642// Out of the box management support2643if (match_option(option, "-Dcom.sun.management", &tail)) {2644#if INCLUDE_MANAGEMENT2645if (FLAG_SET_CMDLINE(ManagementServer, true) != JVMFlag::SUCCESS) {2646return JNI_EINVAL;2647}2648// management agent in module jdk.management.agent2649if (!create_numbered_module_property("jdk.module.addmods", "jdk.management.agent", addmods_count++)) {2650return JNI_ENOMEM;2651}2652#else2653jio_fprintf(defaultStream::output_stream(),2654"-Dcom.sun.management is not supported in this VM.\n");2655return JNI_ERR;2656#endif2657}2658// -Xint2659} else if (match_option(option, "-Xint")) {2660set_mode_flags(_int);2661// -Xmixed2662} else if (match_option(option, "-Xmixed")) {2663set_mode_flags(_mixed);2664// -Xcomp2665} else if (match_option(option, "-Xcomp")) {2666// for testing the compiler; turn off all flags that inhibit compilation2667set_mode_flags(_comp);2668// -Xshare:dump2669} else if (match_option(option, "-Xshare:dump")) {2670if (FLAG_SET_CMDLINE(DumpSharedSpaces, true) != JVMFlag::SUCCESS) {2671return JNI_EINVAL;2672}2673// -Xshare:on2674} else if (match_option(option, "-Xshare:on")) {2675if (FLAG_SET_CMDLINE(UseSharedSpaces, true) != JVMFlag::SUCCESS) {2676return JNI_EINVAL;2677}2678if (FLAG_SET_CMDLINE(RequireSharedSpaces, true) != JVMFlag::SUCCESS) {2679return JNI_EINVAL;2680}2681// -Xshare:auto || -XX:ArchiveClassesAtExit=<archive file>2682} else if (match_option(option, "-Xshare:auto")) {2683if (FLAG_SET_CMDLINE(UseSharedSpaces, true) != JVMFlag::SUCCESS) {2684return JNI_EINVAL;2685}2686if (FLAG_SET_CMDLINE(RequireSharedSpaces, false) != JVMFlag::SUCCESS) {2687return JNI_EINVAL;2688}2689// -Xshare:off2690} else if (match_option(option, "-Xshare:off")) {2691if (FLAG_SET_CMDLINE(UseSharedSpaces, false) != JVMFlag::SUCCESS) {2692return JNI_EINVAL;2693}2694if (FLAG_SET_CMDLINE(RequireSharedSpaces, false) != JVMFlag::SUCCESS) {2695return JNI_EINVAL;2696}2697// -Xverify2698} else if (match_option(option, "-Xverify", &tail)) {2699if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {2700if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, true) != JVMFlag::SUCCESS) {2701return JNI_EINVAL;2702}2703if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {2704return JNI_EINVAL;2705}2706} else if (strcmp(tail, ":remote") == 0) {2707if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {2708return JNI_EINVAL;2709}2710if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {2711return JNI_EINVAL;2712}2713} else if (strcmp(tail, ":none") == 0) {2714if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {2715return JNI_EINVAL;2716}2717if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, false) != JVMFlag::SUCCESS) {2718return JNI_EINVAL;2719}2720warning("Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.");2721} else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {2722return JNI_EINVAL;2723}2724// -Xdebug2725} else if (match_option(option, "-Xdebug")) {2726// note this flag has been used, then ignore2727set_xdebug_mode(true);2728// -Xnoagent2729} else if (match_option(option, "-Xnoagent")) {2730// For compatibility with classic. HotSpot refuses to load the old style agent.dll.2731} else if (match_option(option, "-Xloggc:", &tail)) {2732// Deprecated flag to redirect GC output to a file. -Xloggc:<filename>2733log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);2734_gc_log_filename = os::strdup_check_oom(tail);2735} else if (match_option(option, "-Xlog", &tail)) {2736bool ret = false;2737if (strcmp(tail, ":help") == 0) {2738fileStream stream(defaultStream::output_stream());2739LogConfiguration::print_command_line_help(&stream);2740vm_exit(0);2741} else if (strcmp(tail, ":disable") == 0) {2742LogConfiguration::disable_logging();2743ret = true;2744} else if (strcmp(tail, ":async") == 0) {2745LogConfiguration::set_async_mode(true);2746ret = true;2747} else if (*tail == '\0') {2748ret = LogConfiguration::parse_command_line_arguments();2749assert(ret, "-Xlog without arguments should never fail to parse");2750} else if (*tail == ':') {2751ret = LogConfiguration::parse_command_line_arguments(tail + 1);2752}2753if (ret == false) {2754jio_fprintf(defaultStream::error_stream(),2755"Invalid -Xlog option '-Xlog%s', see error log for details.\n",2756tail);2757return JNI_EINVAL;2758}2759// JNI hooks2760} else if (match_option(option, "-Xcheck", &tail)) {2761if (!strcmp(tail, ":jni")) {2762#if !INCLUDE_JNI_CHECK2763warning("JNI CHECKING is not supported in this VM");2764#else2765CheckJNICalls = true;2766#endif // INCLUDE_JNI_CHECK2767} else if (is_bad_option(option, args->ignoreUnrecognized,2768"check")) {2769return JNI_EINVAL;2770}2771} else if (match_option(option, "vfprintf")) {2772_vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);2773} else if (match_option(option, "exit")) {2774_exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);2775} else if (match_option(option, "abort")) {2776_abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);2777// Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;2778// and the last option wins.2779} else if (match_option(option, "-XX:+NeverTenure")) {2780if (FLAG_SET_CMDLINE(NeverTenure, true) != JVMFlag::SUCCESS) {2781return JNI_EINVAL;2782}2783if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {2784return JNI_EINVAL;2785}2786if (FLAG_SET_CMDLINE(MaxTenuringThreshold, markWord::max_age + 1) != JVMFlag::SUCCESS) {2787return JNI_EINVAL;2788}2789} else if (match_option(option, "-XX:+AlwaysTenure")) {2790if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {2791return JNI_EINVAL;2792}2793if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {2794return JNI_EINVAL;2795}2796if (FLAG_SET_CMDLINE(MaxTenuringThreshold, 0) != JVMFlag::SUCCESS) {2797return JNI_EINVAL;2798}2799} else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {2800uintx max_tenuring_thresh = 0;2801if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {2802jio_fprintf(defaultStream::error_stream(),2803"Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);2804return JNI_EINVAL;2805}28062807if (FLAG_SET_CMDLINE(MaxTenuringThreshold, max_tenuring_thresh) != JVMFlag::SUCCESS) {2808return JNI_EINVAL;2809}28102811if (MaxTenuringThreshold == 0) {2812if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {2813return JNI_EINVAL;2814}2815if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {2816return JNI_EINVAL;2817}2818} else {2819if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {2820return JNI_EINVAL;2821}2822if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {2823return JNI_EINVAL;2824}2825}2826} else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {2827if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, false) != JVMFlag::SUCCESS) {2828return JNI_EINVAL;2829}2830if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, true) != JVMFlag::SUCCESS) {2831return JNI_EINVAL;2832}2833} else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {2834if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, false) != JVMFlag::SUCCESS) {2835return JNI_EINVAL;2836}2837if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, true) != JVMFlag::SUCCESS) {2838return JNI_EINVAL;2839}2840} else if (match_option(option, "-XX:+ErrorFileToStderr")) {2841if (FLAG_SET_CMDLINE(ErrorFileToStdout, false) != JVMFlag::SUCCESS) {2842return JNI_EINVAL;2843}2844if (FLAG_SET_CMDLINE(ErrorFileToStderr, true) != JVMFlag::SUCCESS) {2845return JNI_EINVAL;2846}2847} else if (match_option(option, "-XX:+ErrorFileToStdout")) {2848if (FLAG_SET_CMDLINE(ErrorFileToStderr, false) != JVMFlag::SUCCESS) {2849return JNI_EINVAL;2850}2851if (FLAG_SET_CMDLINE(ErrorFileToStdout, true) != JVMFlag::SUCCESS) {2852return JNI_EINVAL;2853}2854} else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {2855#if defined(DTRACE_ENABLED)2856if (FLAG_SET_CMDLINE(ExtendedDTraceProbes, true) != JVMFlag::SUCCESS) {2857return JNI_EINVAL;2858}2859if (FLAG_SET_CMDLINE(DTraceMethodProbes, true) != JVMFlag::SUCCESS) {2860return JNI_EINVAL;2861}2862if (FLAG_SET_CMDLINE(DTraceAllocProbes, true) != JVMFlag::SUCCESS) {2863return JNI_EINVAL;2864}2865if (FLAG_SET_CMDLINE(DTraceMonitorProbes, true) != JVMFlag::SUCCESS) {2866return JNI_EINVAL;2867}2868#else // defined(DTRACE_ENABLED)2869jio_fprintf(defaultStream::error_stream(),2870"ExtendedDTraceProbes flag is not applicable for this configuration\n");2871return JNI_EINVAL;2872} else if (match_option(option, "-XX:+DTraceMethodProbes")) {2873jio_fprintf(defaultStream::error_stream(),2874"DTraceMethodProbes flag is not applicable for this configuration\n");2875return JNI_EINVAL;2876} else if (match_option(option, "-XX:+DTraceAllocProbes")) {2877jio_fprintf(defaultStream::error_stream(),2878"DTraceAllocProbes flag is not applicable for this configuration\n");2879return JNI_EINVAL;2880} else if (match_option(option, "-XX:+DTraceMonitorProbes")) {2881jio_fprintf(defaultStream::error_stream(),2882"DTraceMonitorProbes flag is not applicable for this configuration\n");2883return JNI_EINVAL;2884#endif // defined(DTRACE_ENABLED)2885#ifdef ASSERT2886} else if (match_option(option, "-XX:+FullGCALot")) {2887if (FLAG_SET_CMDLINE(FullGCALot, true) != JVMFlag::SUCCESS) {2888return JNI_EINVAL;2889}2890// disable scavenge before parallel mark-compact2891if (FLAG_SET_CMDLINE(ScavengeBeforeFullGC, false) != JVMFlag::SUCCESS) {2892return JNI_EINVAL;2893}2894#endif2895#if !INCLUDE_MANAGEMENT2896} else if (match_option(option, "-XX:+ManagementServer")) {2897jio_fprintf(defaultStream::error_stream(),2898"ManagementServer is not supported in this VM.\n");2899return JNI_ERR;2900#endif // INCLUDE_MANAGEMENT2901#if INCLUDE_JVMCI2902} else if (match_option(option, "-XX:-EnableJVMCIProduct")) {2903if (EnableJVMCIProduct) {2904jio_fprintf(defaultStream::error_stream(),2905"-XX:-EnableJVMCIProduct cannot come after -XX:+EnableJVMCIProduct\n");2906return JNI_EINVAL;2907}2908} else if (match_option(option, "-XX:+EnableJVMCIProduct")) {2909// Just continue, since "-XX:+EnableJVMCIProduct" has been specified before2910if (EnableJVMCIProduct) {2911continue;2912}2913JVMFlag *jvmciFlag = JVMFlag::find_flag("EnableJVMCIProduct");2914// Allow this flag if it has been unlocked.2915if (jvmciFlag != NULL && jvmciFlag->is_unlocked()) {2916if (!JVMCIGlobals::enable_jvmci_product_mode(origin)) {2917jio_fprintf(defaultStream::error_stream(),2918"Unable to enable JVMCI in product mode");2919return JNI_ERR;2920}2921}2922// The flag was locked so process normally to report that error2923else if (!process_argument("EnableJVMCIProduct", args->ignoreUnrecognized, origin)) {2924return JNI_EINVAL;2925}2926#endif // INCLUDE_JVMCI2927#if INCLUDE_JFR2928} else if (match_jfr_option(&option)) {2929return JNI_EINVAL;2930#endif2931} else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx2932// Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have2933// already been handled2934if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&2935(strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {2936if (!process_argument(tail, args->ignoreUnrecognized, origin)) {2937return JNI_EINVAL;2938}2939}2940// Unknown option2941} else if (is_bad_option(option, args->ignoreUnrecognized)) {2942return JNI_ERR;2943}2944}29452946// PrintSharedArchiveAndExit will turn on2947// -Xshare:on2948// -Xlog:class+path=info2949if (PrintSharedArchiveAndExit) {2950if (FLAG_SET_CMDLINE(UseSharedSpaces, true) != JVMFlag::SUCCESS) {2951return JNI_EINVAL;2952}2953if (FLAG_SET_CMDLINE(RequireSharedSpaces, true) != JVMFlag::SUCCESS) {2954return JNI_EINVAL;2955}2956LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));2957}29582959fix_appclasspath();29602961return JNI_OK;2962}29632964void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {2965// For java.base check for duplicate --patch-module options being specified on the command line.2966// This check is only required for java.base, all other duplicate module specifications2967// will be checked during module system initialization. The module system initialization2968// will throw an ExceptionInInitializerError if this situation occurs.2969if (strcmp(module_name, JAVA_BASE_NAME) == 0) {2970if (*patch_mod_javabase) {2971vm_exit_during_initialization("Cannot specify " JAVA_BASE_NAME " more than once to --patch-module");2972} else {2973*patch_mod_javabase = true;2974}2975}29762977// Create GrowableArray lazily, only if --patch-module has been specified2978if (_patch_mod_prefix == NULL) {2979_patch_mod_prefix = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<ModulePatchPath*>(10, mtArguments);2980}29812982_patch_mod_prefix->push(new ModulePatchPath(module_name, path));2983}29842985// Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)2986//2987// This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar2988// in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".2989// Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty2990// path is treated as the current directory.2991//2992// This causes problems with CDS, which requires that all directories specified in the classpath2993// must be empty. In most cases, applications do NOT want to load classes from the current2994// directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up2995// scripts compatible with CDS.2996void Arguments::fix_appclasspath() {2997if (IgnoreEmptyClassPaths) {2998const char separator = *os::path_separator();2999const char* src = _java_class_path->value();30003001// skip over all the leading empty paths3002while (*src == separator) {3003src ++;3004}30053006char* copy = os::strdup_check_oom(src, mtArguments);30073008// trim all trailing empty paths3009for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {3010*tail = '\0';3011}30123013char from[3] = {separator, separator, '\0'};3014char to [2] = {separator, '\0'};3015while (StringUtils::replace_no_expand(copy, from, to) > 0) {3016// Keep replacing "::" -> ":" until we have no more "::" (non-windows)3017// Keep replacing ";;" -> ";" until we have no more ";;" (windows)3018}30193020_java_class_path->set_writeable_value(copy);3021FreeHeap(copy); // a copy was made by set_value, so don't need this anymore3022}3023}30243025jint Arguments::finalize_vm_init_args(bool patch_mod_javabase) {3026// check if the default lib/endorsed directory exists; if so, error3027char path[JVM_MAXPATHLEN];3028const char* fileSep = os::file_separator();3029jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);30303031DIR* dir = os::opendir(path);3032if (dir != NULL) {3033jio_fprintf(defaultStream::output_stream(),3034"<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"3035"in modular form will be supported via the concept of upgradeable modules.\n");3036os::closedir(dir);3037return JNI_ERR;3038}30393040jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);3041dir = os::opendir(path);3042if (dir != NULL) {3043jio_fprintf(defaultStream::output_stream(),3044"<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "3045"Use -classpath instead.\n.");3046os::closedir(dir);3047return JNI_ERR;3048}30493050// This must be done after all arguments have been processed3051// and the container support has been initialized since AggressiveHeap3052// relies on the amount of total memory available.3053if (AggressiveHeap) {3054jint result = set_aggressive_heap_flags();3055if (result != JNI_OK) {3056return result;3057}3058}30593060// This must be done after all arguments have been processed.3061// java_compiler() true means set to "NONE" or empty.3062if (java_compiler() && !xdebug_mode()) {3063// For backwards compatibility, we switch to interpreted mode if3064// -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was3065// not specified.3066set_mode_flags(_int);3067}30683069// CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),3070// but like -Xint, leave compilation thresholds unaffected.3071// With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.3072if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {3073set_mode_flags(_int);3074}30753076#ifdef ZERO3077// Zero always runs in interpreted mode3078set_mode_flags(_int);3079#endif30803081// eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set3082if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {3083FLAG_SET_ERGO(InitialTenuringThreshold, MaxTenuringThreshold);3084}30853086#if !COMPILER2_OR_JVMCI3087// Don't degrade server performance for footprint3088if (FLAG_IS_DEFAULT(UseLargePages) &&3089MaxHeapSize < LargePageHeapSizeThreshold) {3090// No need for large granularity pages w/small heaps.3091// Note that large pages are enabled/disabled for both the3092// Java heap and the code cache.3093FLAG_SET_DEFAULT(UseLargePages, false);3094}30953096UNSUPPORTED_OPTION(ProfileInterpreter);3097#endif30983099// Parse the CompilationMode flag3100if (!CompilationModeFlag::initialize()) {3101return JNI_ERR;3102}31033104if (!check_vm_args_consistency()) {3105return JNI_ERR;3106}31073108#if INCLUDE_CDS3109if (DumpSharedSpaces) {3110// Disable biased locking now as it interferes with the clean up of3111// the archived Klasses and Java string objects (at dump time only).3112UseBiasedLocking = false;31133114// Compiler threads may concurrently update the class metadata (such as method entries), so it's3115// unsafe with DumpSharedSpaces (which modifies the class metadata in place). Let's disable3116// compiler just to be safe.3117//3118// Note: this is not a concern for DynamicDumpSharedSpaces, which makes a copy of the class metadata3119// instead of modifying them in place. The copy is inaccessible to the compiler.3120// TODO: revisit the following for the static archive case.3121set_mode_flags(_int);3122}3123if (DumpSharedSpaces || ArchiveClassesAtExit != NULL) {3124// Always verify non-system classes during CDS dump3125if (!BytecodeVerificationRemote) {3126BytecodeVerificationRemote = true;3127log_info(cds)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");3128}3129}31303131// RecordDynamicDumpInfo is not compatible with ArchiveClassesAtExit3132if (ArchiveClassesAtExit != NULL && RecordDynamicDumpInfo) {3133log_info(cds)("RecordDynamicDumpInfo is for jcmd only, could not set with -XX:ArchiveClassesAtExit.");3134return JNI_ERR;3135}31363137if (ArchiveClassesAtExit == NULL && !RecordDynamicDumpInfo) {3138FLAG_SET_DEFAULT(DynamicDumpSharedSpaces, false);3139} else {3140FLAG_SET_DEFAULT(DynamicDumpSharedSpaces, true);3141}31423143if (UseSharedSpaces && patch_mod_javabase) {3144no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");3145}3146if (UseSharedSpaces && !DumpSharedSpaces && check_unsupported_cds_runtime_properties()) {3147FLAG_SET_DEFAULT(UseSharedSpaces, false);3148}3149#endif31503151#ifndef CAN_SHOW_REGISTERS_ON_ASSERT3152UNSUPPORTED_OPTION(ShowRegistersOnAssert);3153#endif // CAN_SHOW_REGISTERS_ON_ASSERT31543155return JNI_OK;3156}31573158// Helper class for controlling the lifetime of JavaVMInitArgs3159// objects. The contents of the JavaVMInitArgs are guaranteed to be3160// deleted on the destruction of the ScopedVMInitArgs object.3161class ScopedVMInitArgs : public StackObj {3162private:3163JavaVMInitArgs _args;3164char* _container_name;3165bool _is_set;3166char* _vm_options_file_arg;31673168public:3169ScopedVMInitArgs(const char *container_name) {3170_args.version = JNI_VERSION_1_2;3171_args.nOptions = 0;3172_args.options = NULL;3173_args.ignoreUnrecognized = false;3174_container_name = (char *)container_name;3175_is_set = false;3176_vm_options_file_arg = NULL;3177}31783179// Populates the JavaVMInitArgs object represented by this3180// ScopedVMInitArgs object with the arguments in options. The3181// allocated memory is deleted by the destructor. If this method3182// returns anything other than JNI_OK, then this object is in a3183// partially constructed state, and should be abandoned.3184jint set_args(const GrowableArrayView<JavaVMOption>* options) {3185_is_set = true;3186JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(3187JavaVMOption, options->length(), mtArguments);3188if (options_arr == NULL) {3189return JNI_ENOMEM;3190}3191_args.options = options_arr;31923193for (int i = 0; i < options->length(); i++) {3194options_arr[i] = options->at(i);3195options_arr[i].optionString = os::strdup(options_arr[i].optionString);3196if (options_arr[i].optionString == NULL) {3197// Rely on the destructor to do cleanup.3198_args.nOptions = i;3199return JNI_ENOMEM;3200}3201}32023203_args.nOptions = options->length();3204_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;3205return JNI_OK;3206}32073208JavaVMInitArgs* get() { return &_args; }3209char* container_name() { return _container_name; }3210bool is_set() { return _is_set; }3211bool found_vm_options_file_arg() { return _vm_options_file_arg != NULL; }3212char* vm_options_file_arg() { return _vm_options_file_arg; }32133214void set_vm_options_file_arg(const char *vm_options_file_arg) {3215if (_vm_options_file_arg != NULL) {3216os::free(_vm_options_file_arg);3217}3218_vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);3219}32203221~ScopedVMInitArgs() {3222if (_vm_options_file_arg != NULL) {3223os::free(_vm_options_file_arg);3224}3225if (_args.options == NULL) return;3226for (int i = 0; i < _args.nOptions; i++) {3227os::free(_args.options[i].optionString);3228}3229FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);3230}32313232// Insert options into this option list, to replace option at3233// vm_options_file_pos (-XX:VMOptionsFile)3234jint insert(const JavaVMInitArgs* args,3235const JavaVMInitArgs* args_to_insert,3236const int vm_options_file_pos) {3237assert(_args.options == NULL, "shouldn't be set yet");3238assert(args_to_insert->nOptions != 0, "there should be args to insert");3239assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");32403241int length = args->nOptions + args_to_insert->nOptions - 1;3242// Construct new option array3243GrowableArrayCHeap<JavaVMOption, mtArguments> options(length);3244for (int i = 0; i < args->nOptions; i++) {3245if (i == vm_options_file_pos) {3246// insert the new options starting at the same place as the3247// -XX:VMOptionsFile option3248for (int j = 0; j < args_to_insert->nOptions; j++) {3249options.push(args_to_insert->options[j]);3250}3251} else {3252options.push(args->options[i]);3253}3254}3255// make into options array3256return set_args(&options);3257}3258};32593260jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {3261return parse_options_environment_variable("_JAVA_OPTIONS", args);3262}32633264jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {3265return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);3266}32673268jint Arguments::parse_options_environment_variable(const char* name,3269ScopedVMInitArgs* vm_args) {3270char *buffer = ::getenv(name);32713272// Don't check this environment variable if user has special privileges3273// (e.g. unix su command).3274if (buffer == NULL || os::have_special_privileges()) {3275return JNI_OK;3276}32773278if ((buffer = os::strdup(buffer)) == NULL) {3279return JNI_ENOMEM;3280}32813282jio_fprintf(defaultStream::error_stream(),3283"Picked up %s: %s\n", name, buffer);32843285int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);32863287os::free(buffer);3288return retcode;3289}32903291jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {3292// read file into buffer3293int fd = ::open(file_name, O_RDONLY);3294if (fd < 0) {3295jio_fprintf(defaultStream::error_stream(),3296"Could not open options file '%s'\n",3297file_name);3298return JNI_ERR;3299}33003301struct stat stbuf;3302int retcode = os::stat(file_name, &stbuf);3303if (retcode != 0) {3304jio_fprintf(defaultStream::error_stream(),3305"Could not stat options file '%s'\n",3306file_name);3307os::close(fd);3308return JNI_ERR;3309}33103311if (stbuf.st_size == 0) {3312// tell caller there is no option data and that is ok3313os::close(fd);3314return JNI_OK;3315}33163317// '+ 1' for NULL termination even with max bytes3318size_t bytes_alloc = stbuf.st_size + 1;33193320char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);3321if (NULL == buf) {3322jio_fprintf(defaultStream::error_stream(),3323"Could not allocate read buffer for options file parse\n");3324os::close(fd);3325return JNI_ENOMEM;3326}33273328memset(buf, 0, bytes_alloc);33293330// Fill buffer3331ssize_t bytes_read = os::read(fd, (void *)buf, (unsigned)bytes_alloc);3332os::close(fd);3333if (bytes_read < 0) {3334FREE_C_HEAP_ARRAY(char, buf);3335jio_fprintf(defaultStream::error_stream(),3336"Could not read options file '%s'\n", file_name);3337return JNI_ERR;3338}33393340if (bytes_read == 0) {3341// tell caller there is no option data and that is ok3342FREE_C_HEAP_ARRAY(char, buf);3343return JNI_OK;3344}33453346retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);33473348FREE_C_HEAP_ARRAY(char, buf);3349return retcode;3350}33513352jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {3353// Construct option array3354GrowableArrayCHeap<JavaVMOption, mtArguments> options(2);33553356// some pointers to help with parsing3357char *buffer_end = buffer + buf_len;3358char *opt_hd = buffer;3359char *wrt = buffer;3360char *rd = buffer;33613362// parse all options3363while (rd < buffer_end) {3364// skip leading white space from the input string3365while (rd < buffer_end && isspace(*rd)) {3366rd++;3367}33683369if (rd >= buffer_end) {3370break;3371}33723373// Remember this is where we found the head of the token.3374opt_hd = wrt;33753376// Tokens are strings of non white space characters separated3377// by one or more white spaces.3378while (rd < buffer_end && !isspace(*rd)) {3379if (*rd == '\'' || *rd == '"') { // handle a quoted string3380int quote = *rd; // matching quote to look for3381rd++; // don't copy open quote3382while (rd < buffer_end && *rd != quote) {3383// include everything (even spaces)3384// up until the close quote3385*wrt++ = *rd++; // copy to option string3386}33873388if (rd < buffer_end) {3389rd++; // don't copy close quote3390} else {3391// did not see closing quote3392jio_fprintf(defaultStream::error_stream(),3393"Unmatched quote in %s\n", name);3394return JNI_ERR;3395}3396} else {3397*wrt++ = *rd++; // copy to option string3398}3399}34003401// steal a white space character and set it to NULL3402*wrt++ = '\0';3403// We now have a complete token34043405JavaVMOption option;3406option.optionString = opt_hd;3407option.extraInfo = NULL;34083409options.append(option); // Fill in option34103411rd++; // Advance to next character3412}34133414// Fill out JavaVMInitArgs structure.3415return vm_args->set_args(&options);3416}34173418jint Arguments::set_shared_spaces_flags_and_archive_paths() {3419if (DumpSharedSpaces) {3420if (RequireSharedSpaces) {3421warning("Cannot dump shared archive while using shared archive");3422}3423UseSharedSpaces = false;3424}3425#if INCLUDE_CDS3426// Initialize shared archive paths which could include both base and dynamic archive paths3427// This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.3428if (!init_shared_archive_paths()) {3429return JNI_ENOMEM;3430}3431#endif // INCLUDE_CDS3432return JNI_OK;3433}34343435#if INCLUDE_CDS3436// Sharing support3437// Construct the path to the archive3438char* Arguments::get_default_shared_archive_path() {3439char *default_archive_path;3440char jvm_path[JVM_MAXPATHLEN];3441os::jvm_path(jvm_path, sizeof(jvm_path));3442char *end = strrchr(jvm_path, *os::file_separator());3443if (end != NULL) *end = '\0';3444size_t jvm_path_len = strlen(jvm_path);3445size_t file_sep_len = strlen(os::file_separator());3446const size_t len = jvm_path_len + file_sep_len + 20;3447default_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);3448jio_snprintf(default_archive_path, len,3449LP64_ONLY(!UseCompressedOops ? "%s%sclasses_nocoops.jsa":) "%s%sclasses.jsa",3450jvm_path, os::file_separator());3451return default_archive_path;3452}34533454int Arguments::num_archives(const char* archive_path) {3455if (archive_path == NULL) {3456return 0;3457}3458int npaths = 1;3459char* p = (char*)archive_path;3460while (*p != '\0') {3461if (*p == os::path_separator()[0]) {3462npaths++;3463}3464p++;3465}3466return npaths;3467}34683469void Arguments::extract_shared_archive_paths(const char* archive_path,3470char** base_archive_path,3471char** top_archive_path) {3472char* begin_ptr = (char*)archive_path;3473char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);3474if (end_ptr == NULL || end_ptr == begin_ptr) {3475vm_exit_during_initialization("Base archive was not specified", archive_path);3476}3477size_t len = end_ptr - begin_ptr;3478char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);3479strncpy(cur_path, begin_ptr, len);3480cur_path[len] = '\0';3481FileMapInfo::check_archive((const char*)cur_path, true /*is_static*/);3482*base_archive_path = cur_path;34833484begin_ptr = ++end_ptr;3485if (*begin_ptr == '\0') {3486vm_exit_during_initialization("Top archive was not specified", archive_path);3487}3488end_ptr = strchr(begin_ptr, '\0');3489assert(end_ptr != NULL, "sanity");3490len = end_ptr - begin_ptr;3491cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);3492strncpy(cur_path, begin_ptr, len + 1);3493//cur_path[len] = '\0';3494FileMapInfo::check_archive((const char*)cur_path, false /*is_static*/);3495*top_archive_path = cur_path;3496}34973498bool Arguments::init_shared_archive_paths() {3499if (ArchiveClassesAtExit != NULL) {3500if (DumpSharedSpaces) {3501vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");3502}3503if (FLAG_SET_CMDLINE(DynamicDumpSharedSpaces, true) != JVMFlag::SUCCESS) {3504return false;3505}3506check_unsupported_dumping_properties();3507SharedDynamicArchivePath = os::strdup_check_oom(ArchiveClassesAtExit, mtArguments);3508} else {3509if (SharedDynamicArchivePath != nullptr) {3510os::free(SharedDynamicArchivePath);3511SharedDynamicArchivePath = nullptr;3512}3513}3514if (SharedArchiveFile == NULL) {3515SharedArchivePath = get_default_shared_archive_path();3516} else {3517int archives = num_archives(SharedArchiveFile);3518if (is_dumping_archive()) {3519if (archives > 1) {3520vm_exit_during_initialization(3521"Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");3522}3523if (DynamicDumpSharedSpaces) {3524if (os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {3525vm_exit_during_initialization(3526"Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",3527SharedArchiveFile);3528}3529}3530}3531if (!is_dumping_archive()){3532if (archives > 2) {3533vm_exit_during_initialization(3534"Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");3535}3536if (archives == 1) {3537char* temp_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);3538int name_size;3539bool success =3540FileMapInfo::get_base_archive_name_from_header(temp_archive_path, &name_size, &SharedArchivePath);3541if (!success) {3542SharedArchivePath = temp_archive_path;3543} else {3544SharedDynamicArchivePath = temp_archive_path;3545}3546} else {3547extract_shared_archive_paths((const char*)SharedArchiveFile,3548&SharedArchivePath, &SharedDynamicArchivePath);3549}3550} else { // CDS dumping3551SharedArchivePath = os::strdup_check_oom(SharedArchiveFile, mtArguments);3552}3553}3554return (SharedArchivePath != NULL);3555}3556#endif // INCLUDE_CDS35573558#ifndef PRODUCT3559// Determine whether LogVMOutput should be implicitly turned on.3560static bool use_vm_log() {3561if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||3562PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||3563PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||3564PrintAssembly || TraceDeoptimization || TraceDependencies ||3565(VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {3566return true;3567}35683569#ifdef COMPILER13570if (PrintC1Statistics) {3571return true;3572}3573#endif // COMPILER135743575#ifdef COMPILER23576if (PrintOptoAssembly || PrintOptoStatistics) {3577return true;3578}3579#endif // COMPILER235803581return false;3582}35833584#endif // PRODUCT35853586bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {3587for (int index = 0; index < args->nOptions; index++) {3588const JavaVMOption* option = args->options + index;3589const char* tail;3590if (match_option(option, "-XX:VMOptionsFile=", &tail)) {3591return true;3592}3593}3594return false;3595}35963597jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,3598const char* vm_options_file,3599const int vm_options_file_pos,3600ScopedVMInitArgs* vm_options_file_args,3601ScopedVMInitArgs* args_out) {3602jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);3603if (code != JNI_OK) {3604return code;3605}36063607if (vm_options_file_args->get()->nOptions < 1) {3608return JNI_OK;3609}36103611if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {3612jio_fprintf(defaultStream::error_stream(),3613"A VM options file may not refer to a VM options file. "3614"Specification of '-XX:VMOptionsFile=<file-name>' in the "3615"options file '%s' in options container '%s' is an error.\n",3616vm_options_file_args->vm_options_file_arg(),3617vm_options_file_args->container_name());3618return JNI_EINVAL;3619}36203621return args_out->insert(args, vm_options_file_args->get(),3622vm_options_file_pos);3623}36243625// Expand -XX:VMOptionsFile found in args_in as needed.3626// mod_args and args_out parameters may return values as needed.3627jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,3628ScopedVMInitArgs* mod_args,3629JavaVMInitArgs** args_out) {3630jint code = match_special_option_and_act(args_in, mod_args);3631if (code != JNI_OK) {3632return code;3633}36343635if (mod_args->is_set()) {3636// args_in contains -XX:VMOptionsFile and mod_args contains the3637// original options from args_in along with the options expanded3638// from the VMOptionsFile. Return a short-hand to the caller.3639*args_out = mod_args->get();3640} else {3641*args_out = (JavaVMInitArgs *)args_in; // no changes so use args_in3642}3643return JNI_OK;3644}36453646jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,3647ScopedVMInitArgs* args_out) {3648// Remaining part of option string3649const char* tail;3650ScopedVMInitArgs vm_options_file_args(args_out->container_name());36513652for (int index = 0; index < args->nOptions; index++) {3653const JavaVMOption* option = args->options + index;3654if (match_option(option, "-XX:Flags=", &tail)) {3655Arguments::set_jvm_flags_file(tail);3656continue;3657}3658if (match_option(option, "-XX:VMOptionsFile=", &tail)) {3659if (vm_options_file_args.found_vm_options_file_arg()) {3660jio_fprintf(defaultStream::error_stream(),3661"The option '%s' is already specified in the options "3662"container '%s' so the specification of '%s' in the "3663"same options container is an error.\n",3664vm_options_file_args.vm_options_file_arg(),3665vm_options_file_args.container_name(),3666option->optionString);3667return JNI_EINVAL;3668}3669vm_options_file_args.set_vm_options_file_arg(option->optionString);3670// If there's a VMOptionsFile, parse that3671jint code = insert_vm_options_file(args, tail, index,3672&vm_options_file_args, args_out);3673if (code != JNI_OK) {3674return code;3675}3676args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());3677if (args_out->is_set()) {3678// The VMOptions file inserted some options so switch 'args'3679// to the new set of options, and continue processing which3680// preserves "last option wins" semantics.3681args = args_out->get();3682// The first option from the VMOptionsFile replaces the3683// current option. So we back track to process the3684// replacement option.3685index--;3686}3687continue;3688}3689if (match_option(option, "-XX:+PrintVMOptions")) {3690PrintVMOptions = true;3691continue;3692}3693if (match_option(option, "-XX:-PrintVMOptions")) {3694PrintVMOptions = false;3695continue;3696}3697if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {3698IgnoreUnrecognizedVMOptions = true;3699continue;3700}3701if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {3702IgnoreUnrecognizedVMOptions = false;3703continue;3704}3705if (match_option(option, "-XX:+PrintFlagsInitial")) {3706JVMFlag::printFlags(tty, false);3707vm_exit(0);3708}37093710#ifndef PRODUCT3711if (match_option(option, "-XX:+PrintFlagsWithComments")) {3712JVMFlag::printFlags(tty, true);3713vm_exit(0);3714}3715#endif3716}3717return JNI_OK;3718}37193720static void print_options(const JavaVMInitArgs *args) {3721const char* tail;3722for (int index = 0; index < args->nOptions; index++) {3723const JavaVMOption *option = args->options + index;3724if (match_option(option, "-XX:", &tail)) {3725logOption(tail);3726}3727}3728}37293730bool Arguments::handle_deprecated_print_gc_flags() {3731if (PrintGC) {3732log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");3733}3734if (PrintGCDetails) {3735log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");3736}37373738if (_gc_log_filename != NULL) {3739// -Xloggc was used to specify a filename3740const char* gc_conf = PrintGCDetails ? "gc*" : "gc";37413742LogTarget(Error, logging) target;3743LogStream errstream(target);3744return LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, &errstream);3745} else if (PrintGC || PrintGCDetails) {3746LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));3747}3748return true;3749}37503751static void apply_debugger_ergo() {3752if (ReplayCompiles) {3753FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo, true);3754}37553756if (UseDebuggerErgo) {3757// Turn on sub-flags3758FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo1, true);3759FLAG_SET_ERGO_IF_DEFAULT(UseDebuggerErgo2, true);3760}37613762if (UseDebuggerErgo2) {3763// Debugging with limited number of CPUs3764FLAG_SET_ERGO_IF_DEFAULT(UseNUMA, false);3765FLAG_SET_ERGO_IF_DEFAULT(ConcGCThreads, 1);3766FLAG_SET_ERGO_IF_DEFAULT(ParallelGCThreads, 1);3767FLAG_SET_ERGO_IF_DEFAULT(CICompilerCount, 2);3768}3769}37703771// Parse entry point called from JNI_CreateJavaVM37723773jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {3774assert(verify_special_jvm_flags(false), "deprecated and obsolete flag table inconsistent");3775JVMFlag::check_all_flag_declarations();37763777// If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.3778const char* hotspotrc = ".hotspotrc";3779bool settings_file_specified = false;3780bool needs_hotspotrc_warning = false;3781ScopedVMInitArgs initial_vm_options_args("");3782ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");3783ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");37843785// Pointers to current working set of containers3786JavaVMInitArgs* cur_cmd_args;3787JavaVMInitArgs* cur_vm_options_args;3788JavaVMInitArgs* cur_java_options_args;3789JavaVMInitArgs* cur_java_tool_options_args;37903791// Containers for modified/expanded options3792ScopedVMInitArgs mod_cmd_args("cmd_line_args");3793ScopedVMInitArgs mod_vm_options_args("vm_options_args");3794ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");3795ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");379637973798jint code =3799parse_java_tool_options_environment_variable(&initial_java_tool_options_args);3800if (code != JNI_OK) {3801return code;3802}38033804code = parse_java_options_environment_variable(&initial_java_options_args);3805if (code != JNI_OK) {3806return code;3807}38083809// Parse the options in the /java.base/jdk/internal/vm/options resource, if present3810char *vmoptions = ClassLoader::lookup_vm_options();3811if (vmoptions != NULL) {3812code = parse_options_buffer("vm options resource", vmoptions, strlen(vmoptions), &initial_vm_options_args);3813FREE_C_HEAP_ARRAY(char, vmoptions);3814if (code != JNI_OK) {3815return code;3816}3817}38183819code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),3820&mod_java_tool_options_args,3821&cur_java_tool_options_args);3822if (code != JNI_OK) {3823return code;3824}38253826code = expand_vm_options_as_needed(initial_cmd_args,3827&mod_cmd_args,3828&cur_cmd_args);3829if (code != JNI_OK) {3830return code;3831}38323833code = expand_vm_options_as_needed(initial_java_options_args.get(),3834&mod_java_options_args,3835&cur_java_options_args);3836if (code != JNI_OK) {3837return code;3838}38393840code = expand_vm_options_as_needed(initial_vm_options_args.get(),3841&mod_vm_options_args,3842&cur_vm_options_args);3843if (code != JNI_OK) {3844return code;3845}38463847const char* flags_file = Arguments::get_jvm_flags_file();3848settings_file_specified = (flags_file != NULL);38493850if (IgnoreUnrecognizedVMOptions) {3851cur_cmd_args->ignoreUnrecognized = true;3852cur_java_tool_options_args->ignoreUnrecognized = true;3853cur_java_options_args->ignoreUnrecognized = true;3854}38553856// Parse specified settings file3857if (settings_file_specified) {3858if (!process_settings_file(flags_file, true,3859cur_cmd_args->ignoreUnrecognized)) {3860return JNI_EINVAL;3861}3862} else {3863#ifdef ASSERT3864// Parse default .hotspotrc settings file3865if (!process_settings_file(".hotspotrc", false,3866cur_cmd_args->ignoreUnrecognized)) {3867return JNI_EINVAL;3868}3869#else3870struct stat buf;3871if (os::stat(hotspotrc, &buf) == 0) {3872needs_hotspotrc_warning = true;3873}3874#endif3875}38763877if (PrintVMOptions) {3878print_options(cur_java_tool_options_args);3879print_options(cur_cmd_args);3880print_options(cur_java_options_args);3881}38823883// Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS3884jint result = parse_vm_init_args(cur_vm_options_args,3885cur_java_tool_options_args,3886cur_java_options_args,3887cur_cmd_args);38883889if (result != JNI_OK) {3890return result;3891}38923893// Delay warning until here so that we've had a chance to process3894// the -XX:-PrintWarnings flag3895if (needs_hotspotrc_warning) {3896warning("%s file is present but has been ignored. "3897"Run with -XX:Flags=%s to load the file.",3898hotspotrc, hotspotrc);3899}39003901if (needs_module_property_warning) {3902warning("Ignoring system property options whose names match the '-Djdk.module.*'."3903" names that are reserved for internal use.");3904}39053906#if defined(_ALLBSD_SOURCE) || defined(AIX) // UseLargePages is not yet supported on BSD and AIX.3907UNSUPPORTED_OPTION(UseLargePages);3908#endif39093910#if defined(AIX)3911UNSUPPORTED_OPTION_NULL(AllocateHeapAt);3912#endif39133914#ifndef PRODUCT3915if (TraceBytecodesAt != 0) {3916TraceBytecodes = true;3917}3918if (CountCompiledCalls) {3919if (UseCounterDecay) {3920warning("UseCounterDecay disabled because CountCalls is set");3921UseCounterDecay = false;3922}3923}3924#endif // PRODUCT39253926if (ScavengeRootsInCode == 0) {3927if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {3928warning("Forcing ScavengeRootsInCode non-zero");3929}3930ScavengeRootsInCode = 1;3931}39323933if (!handle_deprecated_print_gc_flags()) {3934return JNI_EINVAL;3935}39363937// Set object alignment values.3938set_object_alignment();39393940#if !INCLUDE_CDS3941if (DumpSharedSpaces || RequireSharedSpaces) {3942jio_fprintf(defaultStream::error_stream(),3943"Shared spaces are not supported in this VM\n");3944return JNI_ERR;3945}3946if (DumpLoadedClassList != NULL) {3947jio_fprintf(defaultStream::error_stream(),3948"DumpLoadedClassList is not supported in this VM\n");3949return JNI_ERR;3950}3951if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) ||3952log_is_enabled(Info, cds)) {3953warning("Shared spaces are not supported in this VM");3954FLAG_SET_DEFAULT(UseSharedSpaces, false);3955LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(cds));3956}3957no_shared_spaces("CDS Disabled");3958#endif // INCLUDE_CDS39593960#if INCLUDE_NMT3961// Verify NMT arguments3962const NMT_TrackingLevel lvl = NMTUtil::parse_tracking_level(NativeMemoryTracking);3963if (lvl == NMT_unknown) {3964jio_fprintf(defaultStream::error_stream(),3965"Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);3966return JNI_ERR;3967}3968if (PrintNMTStatistics && lvl == NMT_off) {3969warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");3970FLAG_SET_DEFAULT(PrintNMTStatistics, false);3971}3972#else3973if (!FLAG_IS_DEFAULT(NativeMemoryTracking) || PrintNMTStatistics) {3974warning("Native Memory Tracking is not supported in this VM");3975FLAG_SET_DEFAULT(NativeMemoryTracking, "off");3976FLAG_SET_DEFAULT(PrintNMTStatistics, false);3977}3978#endif // INCLUDE_NMT39793980if (TraceDependencies && VerifyDependencies) {3981if (!FLAG_IS_DEFAULT(TraceDependencies)) {3982warning("TraceDependencies results may be inflated by VerifyDependencies");3983}3984}39853986apply_debugger_ergo();39873988return JNI_OK;3989}39903991jint Arguments::apply_ergo() {3992// Set flags based on ergonomics.3993jint result = set_ergonomics_flags();3994if (result != JNI_OK) return result;39953996// Set heap size based on available physical memory3997set_heap_size();39983999GCConfig::arguments()->initialize();40004001result = set_shared_spaces_flags_and_archive_paths();4002if (result != JNI_OK) return result;40034004// Initialize Metaspace flags and alignments4005Metaspace::ergo_initialize();40064007if (!StringDedup::ergo_initialize()) {4008return JNI_EINVAL;4009}40104011// Set compiler flags after GC is selected and GC specific4012// flags (LoopStripMiningIter) are set.4013CompilerConfig::ergo_initialize();40144015// Set bytecode rewriting flags4016set_bytecode_flags();40174018// Set flags if aggressive optimization flags are enabled4019jint code = set_aggressive_opts_flags();4020if (code != JNI_OK) {4021return code;4022}40234024// Turn off biased locking for locking debug mode flags,4025// which are subtly different from each other but neither works with4026// biased locking4027if (UseHeavyMonitors4028#ifdef COMPILER14029|| !UseFastLocking4030#endif // COMPILER14031#if INCLUDE_JVMCI4032|| !JVMCIUseFastLocking4033#endif4034) {4035if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {4036// flag set to true on command line; warn the user that they4037// can't enable biased locking here4038warning("Biased Locking is not supported with locking debug flags"4039"; ignoring UseBiasedLocking flag." );4040}4041UseBiasedLocking = false;4042}40434044#ifdef ZERO4045// Clear flags not supported on zero.4046FLAG_SET_DEFAULT(ProfileInterpreter, false);4047FLAG_SET_DEFAULT(UseBiasedLocking, false);40484049if (LogTouchedMethods) {4050warning("LogTouchedMethods is not supported for Zero");4051FLAG_SET_DEFAULT(LogTouchedMethods, false);4052}4053#endif // ZERO40544055if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {4056warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");4057DebugNonSafepoints = true;4058}40594060if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {4061warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");4062}40634064// Treat the odd case where local verification is enabled but remote4065// verification is not as if both were enabled.4066if (BytecodeVerificationLocal && !BytecodeVerificationRemote) {4067log_info(verification)("Turning on remote verification because local verification is on");4068FLAG_SET_DEFAULT(BytecodeVerificationRemote, true);4069}40704071#ifndef PRODUCT4072if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {4073if (use_vm_log()) {4074LogVMOutput = true;4075}4076}4077#endif // PRODUCT40784079if (PrintCommandLineFlags) {4080JVMFlag::printSetFlags(tty);4081}40824083// Apply CPU specific policy for the BiasedLocking4084if (UseBiasedLocking) {4085if (!VM_Version::use_biased_locking() &&4086!(FLAG_IS_CMDLINE(UseBiasedLocking))) {4087UseBiasedLocking = false;4088}4089}4090#ifdef COMPILER24091if (!UseBiasedLocking) {4092UseOptoBiasInlining = false;4093}40944095if (!FLAG_IS_DEFAULT(EnableVectorSupport) && !EnableVectorSupport) {4096if (!FLAG_IS_DEFAULT(EnableVectorReboxing) && EnableVectorReboxing) {4097warning("Disabling EnableVectorReboxing since EnableVectorSupport is turned off.");4098}4099FLAG_SET_DEFAULT(EnableVectorReboxing, false);41004101if (!FLAG_IS_DEFAULT(EnableVectorAggressiveReboxing) && EnableVectorAggressiveReboxing) {4102if (!EnableVectorReboxing) {4103warning("Disabling EnableVectorAggressiveReboxing since EnableVectorReboxing is turned off.");4104} else {4105warning("Disabling EnableVectorAggressiveReboxing since EnableVectorSupport is turned off.");4106}4107}4108FLAG_SET_DEFAULT(EnableVectorAggressiveReboxing, false);41094110if (!FLAG_IS_DEFAULT(UseVectorStubs) && UseVectorStubs) {4111warning("Disabling UseVectorStubs since EnableVectorSupport is turned off.");4112}4113FLAG_SET_DEFAULT(UseVectorStubs, false);4114}4115#endif // COMPILER241164117if (FLAG_IS_CMDLINE(DiagnoseSyncOnValueBasedClasses)) {4118if (DiagnoseSyncOnValueBasedClasses == ObjectSynchronizer::LOG_WARNING && !log_is_enabled(Info, valuebasedclasses)) {4119LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(valuebasedclasses));4120}4121}4122return JNI_OK;4123}41244125jint Arguments::adjust_after_os() {4126if (UseNUMA) {4127if (UseParallelGC) {4128if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {4129FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);4130}4131}4132}4133return JNI_OK;4134}41354136int Arguments::PropertyList_count(SystemProperty* pl) {4137int count = 0;4138while(pl != NULL) {4139count++;4140pl = pl->next();4141}4142return count;4143}41444145// Return the number of readable properties.4146int Arguments::PropertyList_readable_count(SystemProperty* pl) {4147int count = 0;4148while(pl != NULL) {4149if (pl->is_readable()) {4150count++;4151}4152pl = pl->next();4153}4154return count;4155}41564157const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {4158assert(key != NULL, "just checking");4159SystemProperty* prop;4160for (prop = pl; prop != NULL; prop = prop->next()) {4161if (strcmp(key, prop->key()) == 0) return prop->value();4162}4163return NULL;4164}41654166// Return the value of the requested property provided that it is a readable property.4167const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {4168assert(key != NULL, "just checking");4169SystemProperty* prop;4170// Return the property value if the keys match and the property is not internal or4171// it's the special internal property "jdk.boot.class.path.append".4172for (prop = pl; prop != NULL; prop = prop->next()) {4173if (strcmp(key, prop->key()) == 0) {4174if (!prop->internal()) {4175return prop->value();4176} else if (strcmp(key, "jdk.boot.class.path.append") == 0) {4177return prop->value();4178} else {4179// Property is internal and not jdk.boot.class.path.append so return NULL.4180return NULL;4181}4182}4183}4184return NULL;4185}41864187const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {4188int count = 0;4189const char* ret_val = NULL;41904191while(pl != NULL) {4192if(count >= index) {4193ret_val = pl->key();4194break;4195}4196count++;4197pl = pl->next();4198}41994200return ret_val;4201}42024203char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {4204int count = 0;4205char* ret_val = NULL;42064207while(pl != NULL) {4208if(count >= index) {4209ret_val = pl->value();4210break;4211}4212count++;4213pl = pl->next();4214}42154216return ret_val;4217}42184219void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {4220SystemProperty* p = *plist;4221if (p == NULL) {4222*plist = new_p;4223} else {4224while (p->next() != NULL) {4225p = p->next();4226}4227p->set_next(new_p);4228}4229}42304231void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,4232bool writeable, bool internal) {4233if (plist == NULL)4234return;42354236SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);4237PropertyList_add(plist, new_p);4238}42394240void Arguments::PropertyList_add(SystemProperty *element) {4241PropertyList_add(&_system_properties, element);4242}42434244// This add maintains unique property key in the list.4245void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,4246PropertyAppendable append, PropertyWriteable writeable,4247PropertyInternal internal) {4248if (plist == NULL)4249return;42504251// If property key exists and is writeable, then update with new value.4252// Trying to update a non-writeable property is silently ignored.4253SystemProperty* prop;4254for (prop = *plist; prop != NULL; prop = prop->next()) {4255if (strcmp(k, prop->key()) == 0) {4256if (append == AppendProperty) {4257prop->append_writeable_value(v);4258} else {4259prop->set_writeable_value(v);4260}4261return;4262}4263}42644265PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);4266}42674268// Copies src into buf, replacing "%%" with "%" and "%p" with pid4269// Returns true if all of the source pointed by src has been copied over to4270// the destination buffer pointed by buf. Otherwise, returns false.4271// Notes:4272// 1. If the length (buflen) of the destination buffer excluding the4273// NULL terminator character is not long enough for holding the expanded4274// pid characters, it also returns false instead of returning the partially4275// expanded one.4276// 2. The passed in "buflen" should be large enough to hold the null terminator.4277bool Arguments::copy_expand_pid(const char* src, size_t srclen,4278char* buf, size_t buflen) {4279const char* p = src;4280char* b = buf;4281const char* src_end = &src[srclen];4282char* buf_end = &buf[buflen - 1];42834284while (p < src_end && b < buf_end) {4285if (*p == '%') {4286switch (*(++p)) {4287case '%': // "%%" ==> "%"4288*b++ = *p++;4289break;4290case 'p': { // "%p" ==> current process id4291// buf_end points to the character before the last character so4292// that we could write '\0' to the end of the buffer.4293size_t buf_sz = buf_end - b + 1;4294int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());42954296// if jio_snprintf fails or the buffer is not long enough to hold4297// the expanded pid, returns false.4298if (ret < 0 || ret >= (int)buf_sz) {4299return false;4300} else {4301b += ret;4302assert(*b == '\0', "fail in copy_expand_pid");4303if (p == src_end && b == buf_end + 1) {4304// reach the end of the buffer.4305return true;4306}4307}4308p++;4309break;4310}4311default :4312*b++ = '%';4313}4314} else {4315*b++ = *p++;4316}4317}4318*b = '\0';4319return (p == src_end); // return false if not all of the source was copied4320}432143224323