1 /*
2 * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "jvm.h"
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 "gc/shared/gcArguments.hpp"
33 #include "gc/shared/gcConfig.hpp"
34 #include "logging/log.hpp"
35 #include "logging/logConfiguration.hpp"
36 #include "logging/logStream.hpp"
37 #include "logging/logTag.hpp"
38 #include "memory/allocation.inline.hpp"
39 #include "memory/filemap.hpp"
40 #include "oops/oop.inline.hpp"
41 #include "prims/jvmtiExport.hpp"
42 #include "runtime/arguments.hpp"
43 #include "runtime/flags/jvmFlag.hpp"
44 #include "runtime/flags/jvmFlagConstraintList.hpp"
45 #include "runtime/flags/jvmFlagRangeList.hpp"
46 #include "runtime/globals_extension.hpp"
47 #include "runtime/java.hpp"
48 #include "runtime/os.inline.hpp"
49 #include "runtime/safepoint.hpp"
50 #include "runtime/safepointMechanism.hpp"
51 #include "runtime/vm_version.hpp"
52 #include "services/management.hpp"
53 #include "services/memTracker.hpp"
54 #include "utilities/align.hpp"
55 #include "utilities/defaultStream.hpp"
56 #include "utilities/macros.hpp"
57 #include "utilities/powerOfTwo.hpp"
58 #include "utilities/stringUtils.hpp"
59 #if INCLUDE_JFR
60 #include "jfr/jfr.hpp"
61 #endif
62
63 #define DEFAULT_JAVA_LAUNCHER "generic"
64
65 char* Arguments::_jvm_flags_file = NULL;
66 char** Arguments::_jvm_flags_array = NULL;
67 int Arguments::_num_jvm_flags = 0;
68 char** Arguments::_jvm_args_array = NULL;
69 int Arguments::_num_jvm_args = 0;
70 char* Arguments::_java_command = NULL;
71 SystemProperty* Arguments::_system_properties = NULL;
72 const char* Arguments::_gc_log_filename = NULL;
73 size_t Arguments::_conservative_max_heap_alignment = 0;
74 Arguments::Mode Arguments::_mode = _mixed;
75 bool Arguments::_java_compiler = false;
76 bool Arguments::_xdebug_mode = false;
77 const char* Arguments::_java_vendor_url_bug = NULL;
78 const char* Arguments::_sun_java_launcher = DEFAULT_JAVA_LAUNCHER;
79 bool Arguments::_sun_java_launcher_is_altjvm = false;
80
81 // These parameters are reset in method parse_vm_init_args()
82 bool Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
83 bool Arguments::_UseOnStackReplacement = UseOnStackReplacement;
84 bool Arguments::_BackgroundCompilation = BackgroundCompilation;
85 bool Arguments::_ClipInlining = ClipInlining;
86 intx Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
87 intx Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
88 size_t Arguments::_default_SharedBaseAddress = SharedBaseAddress;
89
90 bool Arguments::_enable_preview = false;
91
92 char* Arguments::SharedArchivePath = NULL;
93 char* Arguments::SharedDynamicArchivePath = NULL;
94
95 AgentLibraryList Arguments::_libraryList;
96 AgentLibraryList Arguments::_agentList;
97
98 // These are not set by the JDK's built-in launchers, but they can be set by
99 // programs that embed the JVM using JNI_CreateJavaVM. See comments around
100 // JavaVMOption in jni.h.
101 abort_hook_t Arguments::_abort_hook = NULL;
102 exit_hook_t Arguments::_exit_hook = NULL;
103 vfprintf_hook_t Arguments::_vfprintf_hook = NULL;
104
105
106 SystemProperty *Arguments::_sun_boot_library_path = NULL;
107 SystemProperty *Arguments::_java_library_path = NULL;
108 SystemProperty *Arguments::_java_home = NULL;
109 SystemProperty *Arguments::_java_class_path = NULL;
110 SystemProperty *Arguments::_jdk_boot_class_path_append = NULL;
111 SystemProperty *Arguments::_vm_info = NULL;
112
113 GrowableArray<ModulePatchPath*> *Arguments::_patch_mod_prefix = NULL;
114 PathString *Arguments::_system_boot_class_path = NULL;
115 bool Arguments::_has_jimage = false;
116
117 char* Arguments::_ext_dirs = NULL;
118
set_value(const char * value)119 bool PathString::set_value(const char *value) {
120 if (_value != NULL) {
121 FreeHeap(_value);
122 }
123 _value = AllocateHeap(strlen(value)+1, mtArguments);
124 assert(_value != NULL, "Unable to allocate space for new path value");
125 if (_value != NULL) {
126 strcpy(_value, value);
127 } else {
128 // not able to allocate
129 return false;
130 }
131 return true;
132 }
133
append_value(const char * value)134 void PathString::append_value(const char *value) {
135 char *sp;
136 size_t len = 0;
137 if (value != NULL) {
138 len = strlen(value);
139 if (_value != NULL) {
140 len += strlen(_value);
141 }
142 sp = AllocateHeap(len+2, mtArguments);
143 assert(sp != NULL, "Unable to allocate space for new append path value");
144 if (sp != NULL) {
145 if (_value != NULL) {
146 strcpy(sp, _value);
147 strcat(sp, os::path_separator());
148 strcat(sp, value);
149 FreeHeap(_value);
150 } else {
151 strcpy(sp, value);
152 }
153 _value = sp;
154 }
155 }
156 }
157
PathString(const char * value)158 PathString::PathString(const char* value) {
159 if (value == NULL) {
160 _value = NULL;
161 } else {
162 _value = AllocateHeap(strlen(value)+1, mtArguments);
163 strcpy(_value, value);
164 }
165 }
166
~PathString()167 PathString::~PathString() {
168 if (_value != NULL) {
169 FreeHeap(_value);
170 _value = NULL;
171 }
172 }
173
ModulePatchPath(const char * module_name,const char * path)174 ModulePatchPath::ModulePatchPath(const char* module_name, const char* path) {
175 assert(module_name != NULL && path != NULL, "Invalid module name or path value");
176 size_t len = strlen(module_name) + 1;
177 _module_name = AllocateHeap(len, mtInternal);
178 strncpy(_module_name, module_name, len); // copy the trailing null
179 _path = new PathString(path);
180 }
181
~ModulePatchPath()182 ModulePatchPath::~ModulePatchPath() {
183 if (_module_name != NULL) {
184 FreeHeap(_module_name);
185 _module_name = NULL;
186 }
187 if (_path != NULL) {
188 delete _path;
189 _path = NULL;
190 }
191 }
192
SystemProperty(const char * key,const char * value,bool writeable,bool internal)193 SystemProperty::SystemProperty(const char* key, const char* value, bool writeable, bool internal) : PathString(value) {
194 if (key == NULL) {
195 _key = NULL;
196 } else {
197 _key = AllocateHeap(strlen(key)+1, mtArguments);
198 strcpy(_key, key);
199 }
200 _next = NULL;
201 _internal = internal;
202 _writeable = writeable;
203 }
204
AgentLibrary(const char * name,const char * options,bool is_absolute_path,void * os_lib,bool instrument_lib)205 AgentLibrary::AgentLibrary(const char* name, const char* options,
206 bool is_absolute_path, void* os_lib,
207 bool instrument_lib) {
208 _name = AllocateHeap(strlen(name)+1, mtArguments);
209 strcpy(_name, name);
210 if (options == NULL) {
211 _options = NULL;
212 } else {
213 _options = AllocateHeap(strlen(options)+1, mtArguments);
214 strcpy(_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 }
223
224 // Check if head of 'option' matches 'name', and sets 'tail' to the remaining
225 // part of the option string.
match_option(const JavaVMOption * option,const char * name,const char ** tail)226 static bool match_option(const JavaVMOption *option, const char* name,
227 const char** tail) {
228 size_t len = strlen(name);
229 if (strncmp(option->optionString, name, len) == 0) {
230 *tail = option->optionString + len;
231 return true;
232 } else {
233 return false;
234 }
235 }
236
237 // Check if 'option' matches 'name'. No "tail" is allowed.
match_option(const JavaVMOption * option,const char * name)238 static bool match_option(const JavaVMOption *option, const char* name) {
239 const char* tail = NULL;
240 bool result = match_option(option, name, &tail);
241 if (tail != NULL && *tail == '\0') {
242 return result;
243 } else {
244 return false;
245 }
246 }
247
248 // 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.
match_option(const JavaVMOption * option,const char ** names,const char ** tail,bool tail_allowed)251 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
252 bool tail_allowed) {
253 for (/* empty */; *names != NULL; ++names) {
254 if (match_option(option, *names, tail)) {
255 if (**tail == '\0' || (tail_allowed && **tail == ':')) {
256 return true;
257 }
258 }
259 }
260 return false;
261 }
262
263 #if INCLUDE_JFR
264 static bool _has_jfr_option = false; // is using JFR
265
266 // return true on failure
match_jfr_option(const JavaVMOption ** option)267 static bool match_jfr_option(const JavaVMOption** option) {
268 assert((*option)->optionString != NULL, "invariant");
269 char* tail = NULL;
270 if (match_option(*option, "-XX:StartFlightRecording", (const char**)&tail)) {
271 _has_jfr_option = true;
272 return Jfr::on_start_flight_recording_option(option, tail);
273 } else if (match_option(*option, "-XX:FlightRecorderOptions", (const char**)&tail)) {
274 _has_jfr_option = true;
275 return Jfr::on_flight_recorder_option(option, tail);
276 }
277 return false;
278 }
279
has_jfr_option()280 bool Arguments::has_jfr_option() {
281 return _has_jfr_option;
282 }
283 #endif
284
logOption(const char * opt)285 static void logOption(const char* opt) {
286 if (PrintVMOptions) {
287 jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
288 }
289 }
290
291 bool needs_module_property_warning = false;
292
293 #define MODULE_PROPERTY_PREFIX "jdk.module."
294 #define MODULE_PROPERTY_PREFIX_LEN 11
295 #define ADDEXPORTS "addexports"
296 #define ADDEXPORTS_LEN 10
297 #define ADDREADS "addreads"
298 #define ADDREADS_LEN 8
299 #define ADDOPENS "addopens"
300 #define ADDOPENS_LEN 8
301 #define PATCH "patch"
302 #define PATCH_LEN 5
303 #define ADDMODS "addmods"
304 #define ADDMODS_LEN 7
305 #define LIMITMODS "limitmods"
306 #define LIMITMODS_LEN 9
307 #define PATH "path"
308 #define PATH_LEN 4
309 #define UPGRADE_PATH "upgrade.path"
310 #define UPGRADE_PATH_LEN 12
311
add_init_library(const char * name,char * options)312 void Arguments::add_init_library(const char* name, char* options) {
313 _libraryList.add(new AgentLibrary(name, options, false, NULL));
314 }
315
add_init_agent(const char * name,char * options,bool absolute_path)316 void Arguments::add_init_agent(const char* name, char* options, bool absolute_path) {
317 _agentList.add(new AgentLibrary(name, options, absolute_path, NULL));
318 }
319
add_instrument_agent(const char * name,char * options,bool absolute_path)320 void Arguments::add_instrument_agent(const char* name, char* options, bool absolute_path) {
321 _agentList.add(new AgentLibrary(name, options, absolute_path, NULL, true));
322 }
323
324 // Late-binding agents not started via arguments
add_loaded_agent(AgentLibrary * agentLib)325 void Arguments::add_loaded_agent(AgentLibrary *agentLib) {
326 _agentList.add(agentLib);
327 }
328
329 // Return TRUE if option matches 'property', or 'property=', or 'property.'.
matches_property_suffix(const char * option,const char * property,size_t len)330 static bool matches_property_suffix(const char* option, const char* property, size_t len) {
331 return ((strncmp(option, property, len) == 0) &&
332 (option[len] == '=' || option[len] == '.' || option[len] == '\0'));
333 }
334
335 // Return true if property starts with "jdk.module." and its ensuing chars match
336 // any of the reserved module properties.
337 // property should be passed without the leading "-D".
is_internal_module_property(const char * property)338 bool Arguments::is_internal_module_property(const char* property) {
339 assert((strncmp(property, "-D", 2) != 0), "Unexpected leading -D");
340 if (strncmp(property, MODULE_PROPERTY_PREFIX, MODULE_PROPERTY_PREFIX_LEN) == 0) {
341 const char* property_suffix = property + MODULE_PROPERTY_PREFIX_LEN;
342 if (matches_property_suffix(property_suffix, ADDEXPORTS, ADDEXPORTS_LEN) ||
343 matches_property_suffix(property_suffix, ADDREADS, ADDREADS_LEN) ||
344 matches_property_suffix(property_suffix, ADDOPENS, ADDOPENS_LEN) ||
345 matches_property_suffix(property_suffix, PATCH, PATCH_LEN) ||
346 matches_property_suffix(property_suffix, ADDMODS, ADDMODS_LEN) ||
347 matches_property_suffix(property_suffix, LIMITMODS, LIMITMODS_LEN) ||
348 matches_property_suffix(property_suffix, PATH, PATH_LEN) ||
349 matches_property_suffix(property_suffix, UPGRADE_PATH, UPGRADE_PATH_LEN)) {
350 return true;
351 }
352 }
353 return false;
354 }
355
356 // Process java launcher properties.
process_sun_java_launcher_properties(JavaVMInitArgs * args)357 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
358 // See if sun.java.launcher or sun.java.launcher.is_altjvm is defined.
359 // Must do this before setting up other system properties,
360 // as some of them may depend on launcher type.
361 for (int index = 0; index < args->nOptions; index++) {
362 const JavaVMOption* option = args->options + index;
363 const char* tail;
364
365 if (match_option(option, "-Dsun.java.launcher=", &tail)) {
366 process_java_launcher_argument(tail, option->extraInfo);
367 continue;
368 }
369 if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
370 if (strcmp(tail, "true") == 0) {
371 _sun_java_launcher_is_altjvm = true;
372 }
373 continue;
374 }
375 }
376 }
377
378 // Initialize system properties key and value.
init_system_properties()379 void Arguments::init_system_properties() {
380
381 // Set up _system_boot_class_path which is not a property but
382 // relies heavily on argument processing and the jdk.boot.class.path.append
383 // property. It is used to store the underlying system boot class path.
384 _system_boot_class_path = new PathString(NULL);
385
386 PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
387 "Java Virtual Machine Specification", false));
388 PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(), false));
389 PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(), false));
390 PropertyList_add(&_system_properties, new SystemProperty("jdk.debug", VM_Version::jdk_debug_level(), false));
391
392 // Initialize the vm.info now, but it will need updating after argument parsing.
393 _vm_info = new SystemProperty("java.vm.info", VM_Version::vm_info_string(), true);
394
395 // Following are JVMTI agent writable properties.
396 // Properties values are set to NULL and they are
397 // os specific they are initialized in os::init_system_properties_values().
398 _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL, true);
399 _java_library_path = new SystemProperty("java.library.path", NULL, true);
400 _java_home = new SystemProperty("java.home", NULL, true);
401 _java_class_path = new SystemProperty("java.class.path", "", true);
402 // jdk.boot.class.path.append is a non-writeable, internal property.
403 // It can only be set by either:
404 // - -Xbootclasspath/a:
405 // - AddToBootstrapClassLoaderSearch during JVMTI OnLoad phase
406 _jdk_boot_class_path_append = new SystemProperty("jdk.boot.class.path.append", "", false, true);
407
408 // Add to System Property list.
409 PropertyList_add(&_system_properties, _sun_boot_library_path);
410 PropertyList_add(&_system_properties, _java_library_path);
411 PropertyList_add(&_system_properties, _java_home);
412 PropertyList_add(&_system_properties, _java_class_path);
413 PropertyList_add(&_system_properties, _jdk_boot_class_path_append);
414 PropertyList_add(&_system_properties, _vm_info);
415
416 // Set OS specific system properties values
417 os::init_system_properties_values();
418 }
419
420 // Update/Initialize System properties after JDK version number is known
init_version_specific_system_properties()421 void Arguments::init_version_specific_system_properties() {
422 enum { bufsz = 16 };
423 char buffer[bufsz];
424 const char* spec_vendor = "Oracle Corporation";
425 uint32_t spec_version = JDK_Version::current().major_version();
426
427 jio_snprintf(buffer, bufsz, UINT32_FORMAT, spec_version);
428
429 PropertyList_add(&_system_properties,
430 new SystemProperty("java.vm.specification.vendor", spec_vendor, false));
431 PropertyList_add(&_system_properties,
432 new SystemProperty("java.vm.specification.version", buffer, false));
433 PropertyList_add(&_system_properties,
434 new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(), false));
435 }
436
437 /*
438 * -XX argument processing:
439 *
440 * -XX arguments are defined in several places, such as:
441 * globals.hpp, globals_<cpu>.hpp, globals_<os>.hpp, <compiler>_globals.hpp, or <gc>_globals.hpp.
442 * -XX arguments are parsed in parse_argument().
443 * -XX argument bounds checking is done in check_vm_args_consistency().
444 *
445 * Over time -XX arguments may change. There are mechanisms to handle common cases:
446 *
447 * ALIASED: An option that is simply another name for another option. This is often
448 * part of the process of deprecating a flag, but not all aliases need
449 * to be deprecated.
450 *
451 * Create an alias for an option by adding the old and new option names to the
452 * "aliased_jvm_flags" table. Delete the old variable from globals.hpp (etc).
453 *
454 * DEPRECATED: An option that is supported, but a warning is printed to let the user know that
455 * support may be removed in the future. Both regular and aliased options may be
456 * deprecated.
457 *
458 * Add a deprecation warning for an option (or alias) by adding an entry in the
459 * "special_jvm_flags" table and setting the "deprecated_in" field.
460 * Often an option "deprecated" in one major release will
461 * be made "obsolete" in the next. In this case the entry should also have its
462 * "obsolete_in" field set.
463 *
464 * OBSOLETE: An option that has been removed (and deleted from globals.hpp), but is still accepted
465 * on the command line. A warning is printed to let the user know that option might not
466 * be accepted in the future.
467 *
468 * Add an obsolete warning for an option by adding an entry in the "special_jvm_flags"
469 * table and setting the "obsolete_in" field.
470 *
471 * EXPIRED: A deprecated or obsolete option that has an "accept_until" version less than or equal
472 * to the current JDK version. The system will flatly refuse to admit the existence of
473 * the flag. This allows a flag to die automatically over JDK releases.
474 *
475 * Note that manual cleanup of expired options should be done at major JDK version upgrades:
476 * - Newly expired options should be removed from the special_jvm_flags and aliased_jvm_flags tables.
477 * - Newly obsolete or expired deprecated options should have their global variable
478 * definitions removed (from globals.hpp, etc) and related implementations removed.
479 *
480 * Recommended approach for removing options:
481 *
482 * To remove options commonly used by customers (e.g. product -XX options), use
483 * the 3-step model adding major release numbers to the deprecate, obsolete and expire columns.
484 *
485 * To remove internal options (e.g. diagnostic, experimental, develop options), use
486 * a 2-step model adding major release numbers to the obsolete and expire columns.
487 *
488 * To change the name of an option, use the alias table as well as a 2-step
489 * model adding major release numbers to the deprecate and expire columns.
490 * Think twice about aliasing commonly used customer options.
491 *
492 * There are times when it is appropriate to leave a future release number as undefined.
493 *
494 * Tests: Aliases should be tested in VMAliasOptions.java.
495 * Deprecated options should be tested in VMDeprecatedOptions.java.
496 */
497
498 // The special_jvm_flags table declares options that are being deprecated and/or obsoleted. The
499 // "deprecated_in" or "obsolete_in" fields may be set to "undefined", but not both.
500 // When the JDK version reaches 'deprecated_in' limit, the JVM will process this flag on
501 // the command-line as usual, but will issue a warning.
502 // When the JDK version reaches 'obsolete_in' limit, the JVM will continue accepting this flag on
503 // the command-line, while issuing a warning and ignoring the flag value.
504 // Once the JDK version reaches 'expired_in' limit, the JVM will flatly refuse to admit the
505 // existence of the flag.
506 //
507 // MANUAL CLEANUP ON JDK VERSION UPDATES:
508 // This table ensures that the handling of options will update automatically when the JDK
509 // version is incremented, but the source code needs to be cleanup up manually:
510 // - As "deprecated" options age into "obsolete" or "expired" options, the associated "globals"
511 // variable should be removed, as well as users of the variable.
512 // - As "deprecated" options age into "obsolete" options, move the entry into the
513 // "Obsolete Flags" section of the table.
514 // - All expired options should be removed from the table.
515 static SpecialFlag const special_jvm_flags[] = {
516 // -------------- Deprecated Flags --------------
517 // --- Non-alias flags - sorted by obsolete_in then expired_in:
518 { "MaxGCMinorPauseMillis", JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
519 { "MaxRAMFraction", JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },
520 { "MinRAMFraction", JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },
521 { "InitialRAMFraction", JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },
522 { "UseMembar", JDK_Version::jdk(10), JDK_Version::jdk(12), JDK_Version::undefined() },
523 { "AllowRedefinitionToAddDeleteMethods", JDK_Version::jdk(13), JDK_Version::undefined(), JDK_Version::undefined() },
524 { "FlightRecorder", JDK_Version::jdk(13), JDK_Version::undefined(), JDK_Version::undefined() },
525 { "PrintVMQWaitTime", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
526 { "UseNewFieldLayout", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
527 { "ForceNUMA", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
528 { "UseBiasedLocking", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
529 { "BiasedLockingStartupDelay", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
530 { "PrintBiasedLockingStatistics", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
531 { "BiasedLockingBulkRebiasThreshold", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
532 { "BiasedLockingBulkRevokeThreshold", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
533 { "BiasedLockingDecayTime", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
534 { "UseOptoBiasInlining", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
535 { "PrintPreciseBiasedLockingStatistics", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
536 { "InitialBootClassLoaderMetaspaceSize", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
537 { "UseLargePagesInMetaspace", JDK_Version::jdk(15), JDK_Version::jdk(16), JDK_Version::jdk(17) },
538
539 // --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in:
540 { "DefaultMaxRAMFraction", JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
541 { "CreateMinidumpOnCrash", JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
542 { "TLABStats", JDK_Version::jdk(12), JDK_Version::undefined(), JDK_Version::undefined() },
543
544 // -------------- Obsolete Flags - sorted by expired_in --------------
545 { "PermSize", JDK_Version::undefined(), JDK_Version::jdk(8), JDK_Version::undefined() },
546 { "MaxPermSize", JDK_Version::undefined(), JDK_Version::jdk(8), JDK_Version::undefined() },
547 { "SharedReadWriteSize", JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
548 { "SharedReadOnlySize", JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
549 { "SharedMiscDataSize", JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
550 { "SharedMiscCodeSize", JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
551 { "BindGCTaskThreadsToCPUs", JDK_Version::undefined(), JDK_Version::jdk(14), JDK_Version::jdk(16) },
552 { "UseGCTaskAffinity", JDK_Version::undefined(), JDK_Version::jdk(14), JDK_Version::jdk(16) },
553 { "GCTaskTimeStampEntries", JDK_Version::undefined(), JDK_Version::jdk(14), JDK_Version::jdk(16) },
554 { "G1RSetScanBlockSize", JDK_Version::jdk(14), JDK_Version::jdk(15), JDK_Version::jdk(16) },
555 { "UseParallelOldGC", JDK_Version::jdk(14), JDK_Version::jdk(15), JDK_Version::jdk(16) },
556 { "CompactFields", JDK_Version::jdk(14), JDK_Version::jdk(15), JDK_Version::jdk(16) },
557 { "FieldsAllocationStyle", JDK_Version::jdk(14), JDK_Version::jdk(15), JDK_Version::jdk(16) },
558 #ifndef X86
559 { "UseSSE", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
560 #endif // !X86
561 { "UseAdaptiveGCBoundary", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
562 { "MonitorBound", JDK_Version::jdk(14), JDK_Version::jdk(15), JDK_Version::jdk(16) },
563 #ifdef AARCH64
564 { "UseBarriersForVolatile", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
565 #endif
566 { "UseLWPSynchronization", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
567 { "BranchOnRegister", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
568 { "LIRFillDelaySlots", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
569
570 #ifdef TEST_VERIFY_SPECIAL_JVM_FLAGS
571 // These entries will generate build errors. Their purpose is to test the macros.
572 { "dep > obs", JDK_Version::jdk(9), JDK_Version::jdk(8), JDK_Version::undefined() },
573 { "dep > exp ", JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(8) },
574 { "obs > exp ", JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(8) },
575 { "obs > exp", JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::jdk(10) },
576 { "not deprecated or obsolete", JDK_Version::undefined(), JDK_Version::undefined(), JDK_Version::jdk(9) },
577 { "dup option", JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
578 { "dup option", JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
579 #endif
580
581 #ifndef COMPILER2
582 // These flags were generally available, but are C2 only, now.
583 { "MaxInlineLevel", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
584 { "MaxRecursiveInlineLevel", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
585 { "InlineSmallCode", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
586 { "MaxInlineSize", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
587 { "FreqInlineSize", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
588 { "MaxTrivialSize", JDK_Version::undefined(), JDK_Version::jdk(15), JDK_Version::jdk(16) },
589 #endif
590
591 { NULL, JDK_Version(0), JDK_Version(0) }
592 };
593
594 // Flags that are aliases for other flags.
595 typedef struct {
596 const char* alias_name;
597 const char* real_name;
598 } AliasedFlag;
599
600 static AliasedFlag const aliased_jvm_flags[] = {
601 { "DefaultMaxRAMFraction", "MaxRAMFraction" },
602 { "CreateMinidumpOnCrash", "CreateCoredumpOnCrash" },
603 { NULL, NULL}
604 };
605
606 // NOTE: A compatibility request will be necessary for each alias to be removed.
607 static AliasedLoggingFlag const aliased_logging_flags[] = {
608 { "PrintSharedSpaces", LogLevel::Info, true, LOG_TAGS(cds) },
609 { "TraceBiasedLocking", LogLevel::Info, true, LOG_TAGS(biasedlocking) },
610 { "TraceClassLoading", LogLevel::Info, true, LOG_TAGS(class, load) },
611 { "TraceClassLoadingPreorder", LogLevel::Debug, true, LOG_TAGS(class, preorder) },
612 { "TraceClassPaths", LogLevel::Info, true, LOG_TAGS(class, path) },
613 { "TraceClassResolution", LogLevel::Debug, true, LOG_TAGS(class, resolve) },
614 { "TraceClassUnloading", LogLevel::Info, true, LOG_TAGS(class, unload) },
615 { "TraceExceptions", LogLevel::Info, true, LOG_TAGS(exceptions) },
616 { "TraceInvokeDynamic", LogLevel::Debug, true, LOG_TAGS(methodhandles, indy) },
617 { "TraceLoaderConstraints", LogLevel::Info, true, LOG_TAGS(class, loader, constraints) },
618 { "TraceMethodHandles", LogLevel::Info, true, LOG_TAGS(methodhandles) },
619 { "TraceMonitorInflation", LogLevel::Trace, true, LOG_TAGS(monitorinflation) },
620 { "TraceSafepointCleanupTime", LogLevel::Info, true, LOG_TAGS(safepoint, cleanup) },
621 { "TraceJVMTIObjectTagging", LogLevel::Debug, true, LOG_TAGS(jvmti, objecttagging) },
622 { "TraceRedefineClasses", LogLevel::Info, false, LOG_TAGS(redefine, class) },
623 { "PrintJNIResolving", LogLevel::Debug, true, LOG_TAGS(jni, resolve) },
624 { NULL, LogLevel::Off, false, LOG_TAGS(_NO_TAG) }
625 };
626
627 #ifndef PRODUCT
628 // These options are removed in jdk9. Remove this code for jdk10.
629 static AliasedFlag const removed_develop_logging_flags[] = {
630 { "TraceClassInitialization", "-Xlog:class+init" },
631 { "TraceClassLoaderData", "-Xlog:class+loader+data" },
632 { "TraceDefaultMethods", "-Xlog:defaultmethods=debug" },
633 { "TraceItables", "-Xlog:itables=debug" },
634 { "TraceMonitorMismatch", "-Xlog:monitormismatch=info" },
635 { "TraceSafepoint", "-Xlog:safepoint=debug" },
636 { "TraceStartupTime", "-Xlog:startuptime" },
637 { "TraceVMOperation", "-Xlog:vmoperation=debug" },
638 { "PrintVtables", "-Xlog:vtables=debug" },
639 { "VerboseVerification", "-Xlog:verification" },
640 { NULL, NULL }
641 };
642 #endif //PRODUCT
643
644 // Return true if "v" is less than "other", where "other" may be "undefined".
version_less_than(JDK_Version v,JDK_Version other)645 static bool version_less_than(JDK_Version v, JDK_Version other) {
646 assert(!v.is_undefined(), "must be defined");
647 if (!other.is_undefined() && v.compare(other) >= 0) {
648 return false;
649 } else {
650 return true;
651 }
652 }
653
lookup_special_flag(const char * flag_name,SpecialFlag & flag)654 static bool lookup_special_flag(const char *flag_name, SpecialFlag& flag) {
655 for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
656 if ((strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
657 flag = special_jvm_flags[i];
658 return true;
659 }
660 }
661 return false;
662 }
663
is_obsolete_flag(const char * flag_name,JDK_Version * version)664 bool Arguments::is_obsolete_flag(const char *flag_name, JDK_Version* version) {
665 assert(version != NULL, "Must provide a version buffer");
666 SpecialFlag flag;
667 if (lookup_special_flag(flag_name, flag)) {
668 if (!flag.obsolete_in.is_undefined()) {
669 if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {
670 *version = flag.obsolete_in;
671 // This flag may have been marked for obsoletion in this version, but we may not
672 // have actually removed it yet. Rather than ignoring it as soon as we reach
673 // this version we allow some time for the removal to happen. So if the flag
674 // still actually exists we process it as normal, but issue an adjusted warning.
675 const JVMFlag *real_flag = JVMFlag::find_declared_flag(flag_name);
676 if (real_flag != NULL) {
677 char version_str[256];
678 version->to_string(version_str, sizeof(version_str));
679 warning("Temporarily processing option %s; support is scheduled for removal in %s",
680 flag_name, version_str);
681 return false;
682 }
683 return true;
684 }
685 }
686 }
687 return false;
688 }
689
is_deprecated_flag(const char * flag_name,JDK_Version * version)690 int Arguments::is_deprecated_flag(const char *flag_name, JDK_Version* version) {
691 assert(version != NULL, "Must provide a version buffer");
692 SpecialFlag flag;
693 if (lookup_special_flag(flag_name, flag)) {
694 if (!flag.deprecated_in.is_undefined()) {
695 if (version_less_than(JDK_Version::current(), flag.obsolete_in) &&
696 version_less_than(JDK_Version::current(), flag.expired_in)) {
697 *version = flag.deprecated_in;
698 return 1;
699 } else {
700 return -1;
701 }
702 }
703 }
704 return 0;
705 }
706
707 #ifndef PRODUCT
removed_develop_logging_flag_name(const char * name)708 const char* Arguments::removed_develop_logging_flag_name(const char* name){
709 for (size_t i = 0; removed_develop_logging_flags[i].alias_name != NULL; i++) {
710 const AliasedFlag& flag = removed_develop_logging_flags[i];
711 if (strcmp(flag.alias_name, name) == 0) {
712 return flag.real_name;
713 }
714 }
715 return NULL;
716 }
717 #endif // PRODUCT
718
real_flag_name(const char * flag_name)719 const char* Arguments::real_flag_name(const char *flag_name) {
720 for (size_t i = 0; aliased_jvm_flags[i].alias_name != NULL; i++) {
721 const AliasedFlag& flag_status = aliased_jvm_flags[i];
722 if (strcmp(flag_status.alias_name, flag_name) == 0) {
723 return flag_status.real_name;
724 }
725 }
726 return flag_name;
727 }
728
729 #ifdef ASSERT
lookup_special_flag(const char * flag_name,size_t skip_index)730 static bool lookup_special_flag(const char *flag_name, size_t skip_index) {
731 for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
732 if ((i != skip_index) && (strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
733 return true;
734 }
735 }
736 return false;
737 }
738
739 // Verifies the correctness of the entries in the special_jvm_flags table.
740 // If there is a semantic error (i.e. a bug in the table) such as the obsoletion
741 // version being earlier than the deprecation version, then a warning is issued
742 // and verification fails - by returning false. If it is detected that the table
743 // is out of date, with respect to the current version, then ideally a warning is
744 // issued but verification does not fail. This allows the VM to operate when the
745 // version is first updated, without needing to update all the impacted flags at
746 // the same time. In practice we can't issue the warning immediately when the version
747 // is updated as it occurs for every test and some tests are not prepared to handle
748 // unexpected output - see 8196739. Instead we only check if the table is up-to-date
749 // if the check_globals flag is true, and in addition allow a grace period and only
750 // check for stale flags when we hit build 25 (which is far enough into the 6 month
751 // release cycle that all flag updates should have been processed, whilst still
752 // leaving time to make the change before RDP2).
753 // We use a gtest to call this, passing true, so that we can detect stale flags before
754 // the end of the release cycle.
755
756 static const int SPECIAL_FLAG_VALIDATION_BUILD = 25;
757
verify_special_jvm_flags(bool check_globals)758 bool Arguments::verify_special_jvm_flags(bool check_globals) {
759 bool success = true;
760 for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
761 const SpecialFlag& flag = special_jvm_flags[i];
762 if (lookup_special_flag(flag.name, i)) {
763 warning("Duplicate special flag declaration \"%s\"", flag.name);
764 success = false;
765 }
766 if (flag.deprecated_in.is_undefined() &&
767 flag.obsolete_in.is_undefined()) {
768 warning("Special flag entry \"%s\" must declare version deprecated and/or obsoleted in.", flag.name);
769 success = false;
770 }
771
772 if (!flag.deprecated_in.is_undefined()) {
773 if (!version_less_than(flag.deprecated_in, flag.obsolete_in)) {
774 warning("Special flag entry \"%s\" must be deprecated before obsoleted.", flag.name);
775 success = false;
776 }
777
778 if (!version_less_than(flag.deprecated_in, flag.expired_in)) {
779 warning("Special flag entry \"%s\" must be deprecated before expired.", flag.name);
780 success = false;
781 }
782 }
783
784 if (!flag.obsolete_in.is_undefined()) {
785 if (!version_less_than(flag.obsolete_in, flag.expired_in)) {
786 warning("Special flag entry \"%s\" must be obsoleted before expired.", flag.name);
787 success = false;
788 }
789
790 // if flag has become obsolete it should not have a "globals" flag defined anymore.
791 if (check_globals && VM_Version::vm_build_number() >= SPECIAL_FLAG_VALIDATION_BUILD &&
792 !version_less_than(JDK_Version::current(), flag.obsolete_in)) {
793 if (JVMFlag::find_declared_flag(flag.name) != NULL) {
794 warning("Global variable for obsolete special flag entry \"%s\" should be removed", flag.name);
795 success = false;
796 }
797 }
798
799 } else if (!flag.expired_in.is_undefined()) {
800 warning("Special flag entry \"%s\" must be explicitly obsoleted before expired.", flag.name);
801 success = false;
802 }
803
804 if (!flag.expired_in.is_undefined()) {
805 // if flag has become expired it should not have a "globals" flag defined anymore.
806 if (check_globals && VM_Version::vm_build_number() >= SPECIAL_FLAG_VALIDATION_BUILD &&
807 !version_less_than(JDK_Version::current(), flag.expired_in)) {
808 if (JVMFlag::find_declared_flag(flag.name) != NULL) {
809 warning("Global variable for expired flag entry \"%s\" should be removed", flag.name);
810 success = false;
811 }
812 }
813 }
814 }
815 return success;
816 }
817 #endif
818
819 // Parses a size specification string.
atojulong(const char * s,julong * result)820 bool Arguments::atojulong(const char *s, julong* result) {
821 julong n = 0;
822
823 // First char must be a digit. Don't allow negative numbers or leading spaces.
824 if (!isdigit(*s)) {
825 return false;
826 }
827
828 bool is_hex = (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'));
829 char* remainder;
830 errno = 0;
831 n = strtoull(s, &remainder, (is_hex ? 16 : 10));
832 if (errno != 0) {
833 return false;
834 }
835
836 // Fail if no number was read at all or if the remainder contains more than a single non-digit character.
837 if (remainder == s || strlen(remainder) > 1) {
838 return false;
839 }
840
841 switch (*remainder) {
842 case 'T': case 't':
843 *result = n * G * K;
844 // Check for overflow.
845 if (*result/((julong)G * K) != n) return false;
846 return true;
847 case 'G': case 'g':
848 *result = n * G;
849 if (*result/G != n) return false;
850 return true;
851 case 'M': case 'm':
852 *result = n * M;
853 if (*result/M != n) return false;
854 return true;
855 case 'K': case 'k':
856 *result = n * K;
857 if (*result/K != n) return false;
858 return true;
859 case '\0':
860 *result = n;
861 return true;
862 default:
863 return false;
864 }
865 }
866
check_memory_size(julong size,julong min_size,julong max_size)867 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size, julong max_size) {
868 if (size < min_size) return arg_too_small;
869 if (size > max_size) return arg_too_big;
870 return arg_in_range;
871 }
872
873 // Describe an argument out of range error
describe_range_error(ArgsRange errcode)874 void Arguments::describe_range_error(ArgsRange errcode) {
875 switch(errcode) {
876 case arg_too_big:
877 jio_fprintf(defaultStream::error_stream(),
878 "The specified size exceeds the maximum "
879 "representable size.\n");
880 break;
881 case arg_too_small:
882 case arg_unreadable:
883 case arg_in_range:
884 // do nothing for now
885 break;
886 default:
887 ShouldNotReachHere();
888 }
889 }
890
set_bool_flag(JVMFlag * flag,bool value,JVMFlag::Flags origin)891 static bool set_bool_flag(JVMFlag* flag, bool value, JVMFlag::Flags origin) {
892 if (JVMFlag::boolAtPut(flag, &value, origin) == JVMFlag::SUCCESS) {
893 return true;
894 } else {
895 return false;
896 }
897 }
898
set_fp_numeric_flag(JVMFlag * flag,char * value,JVMFlag::Flags origin)899 static bool set_fp_numeric_flag(JVMFlag* flag, char* value, JVMFlag::Flags origin) {
900 char* end;
901 errno = 0;
902 double v = strtod(value, &end);
903 if ((errno != 0) || (*end != 0)) {
904 return false;
905 }
906
907 if (JVMFlag::doubleAtPut(flag, &v, origin) == JVMFlag::SUCCESS) {
908 return true;
909 }
910 return false;
911 }
912
set_numeric_flag(JVMFlag * flag,char * value,JVMFlag::Flags origin)913 static bool set_numeric_flag(JVMFlag* flag, char* value, JVMFlag::Flags origin) {
914 julong v;
915 int int_v;
916 intx intx_v;
917 bool is_neg = false;
918
919 if (flag == NULL) {
920 return false;
921 }
922
923 // Check the sign first since atojulong() parses only unsigned values.
924 if (*value == '-') {
925 if (!flag->is_intx() && !flag->is_int()) {
926 return false;
927 }
928 value++;
929 is_neg = true;
930 }
931 if (!Arguments::atojulong(value, &v)) {
932 return false;
933 }
934 if (flag->is_int()) {
935 int_v = (int) v;
936 if (is_neg) {
937 int_v = -int_v;
938 }
939 return JVMFlag::intAtPut(flag, &int_v, origin) == JVMFlag::SUCCESS;
940 } else if (flag->is_uint()) {
941 uint uint_v = (uint) v;
942 return JVMFlag::uintAtPut(flag, &uint_v, origin) == JVMFlag::SUCCESS;
943 } else if (flag->is_intx()) {
944 intx_v = (intx) v;
945 if (is_neg) {
946 intx_v = -intx_v;
947 }
948 return JVMFlag::intxAtPut(flag, &intx_v, origin) == JVMFlag::SUCCESS;
949 } else if (flag->is_uintx()) {
950 uintx uintx_v = (uintx) v;
951 return JVMFlag::uintxAtPut(flag, &uintx_v, origin) == JVMFlag::SUCCESS;
952 } else if (flag->is_uint64_t()) {
953 uint64_t uint64_t_v = (uint64_t) v;
954 return JVMFlag::uint64_tAtPut(flag, &uint64_t_v, origin) == JVMFlag::SUCCESS;
955 } else if (flag->is_size_t()) {
956 size_t size_t_v = (size_t) v;
957 return JVMFlag::size_tAtPut(flag, &size_t_v, origin) == JVMFlag::SUCCESS;
958 } else if (flag->is_double()) {
959 double double_v = (double) v;
960 return JVMFlag::doubleAtPut(flag, &double_v, origin) == JVMFlag::SUCCESS;
961 } else {
962 return false;
963 }
964 }
965
set_string_flag(JVMFlag * flag,const char * value,JVMFlag::Flags origin)966 static bool set_string_flag(JVMFlag* flag, const char* value, JVMFlag::Flags origin) {
967 if (JVMFlag::ccstrAtPut(flag, &value, origin) != JVMFlag::SUCCESS) return false;
968 // Contract: JVMFlag always returns a pointer that needs freeing.
969 FREE_C_HEAP_ARRAY(char, value);
970 return true;
971 }
972
append_to_string_flag(JVMFlag * flag,const char * new_value,JVMFlag::Flags origin)973 static bool append_to_string_flag(JVMFlag* flag, const char* new_value, JVMFlag::Flags origin) {
974 const char* old_value = "";
975 if (JVMFlag::ccstrAt(flag, &old_value) != JVMFlag::SUCCESS) return false;
976 size_t old_len = old_value != NULL ? strlen(old_value) : 0;
977 size_t new_len = strlen(new_value);
978 const char* value;
979 char* free_this_too = NULL;
980 if (old_len == 0) {
981 value = new_value;
982 } else if (new_len == 0) {
983 value = old_value;
984 } else {
985 size_t length = old_len + 1 + new_len + 1;
986 char* buf = NEW_C_HEAP_ARRAY(char, length, mtArguments);
987 // each new setting adds another LINE to the switch:
988 jio_snprintf(buf, length, "%s\n%s", old_value, new_value);
989 value = buf;
990 free_this_too = buf;
991 }
992 (void) JVMFlag::ccstrAtPut(flag, &value, origin);
993 // JVMFlag always returns a pointer that needs freeing.
994 FREE_C_HEAP_ARRAY(char, value);
995 // JVMFlag made its own copy, so I must delete my own temp. buffer.
996 FREE_C_HEAP_ARRAY(char, free_this_too);
997 return true;
998 }
999
handle_aliases_and_deprecation(const char * arg,bool warn)1000 const char* Arguments::handle_aliases_and_deprecation(const char* arg, bool warn) {
1001 const char* real_name = real_flag_name(arg);
1002 JDK_Version since = JDK_Version();
1003 switch (is_deprecated_flag(arg, &since)) {
1004 case -1: {
1005 // Obsolete or expired, so don't process normally,
1006 // but allow for an obsolete flag we're still
1007 // temporarily allowing.
1008 if (!is_obsolete_flag(arg, &since)) {
1009 return real_name;
1010 }
1011 // Note if we're not considered obsolete then we can't be expired either
1012 // as obsoletion must come first.
1013 return NULL;
1014 }
1015 case 0:
1016 return real_name;
1017 case 1: {
1018 if (warn) {
1019 char version[256];
1020 since.to_string(version, sizeof(version));
1021 if (real_name != arg) {
1022 warning("Option %s was deprecated in version %s and will likely be removed in a future release. Use option %s instead.",
1023 arg, version, real_name);
1024 } else {
1025 warning("Option %s was deprecated in version %s and will likely be removed in a future release.",
1026 arg, version);
1027 }
1028 }
1029 return real_name;
1030 }
1031 }
1032 ShouldNotReachHere();
1033 return NULL;
1034 }
1035
log_deprecated_flag(const char * name,bool on,AliasedLoggingFlag alf)1036 void log_deprecated_flag(const char* name, bool on, AliasedLoggingFlag alf) {
1037 LogTagType tagSet[] = {alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5};
1038 // Set tagset string buffer at max size of 256, large enough for any alias tagset
1039 const int max_tagset_size = 256;
1040 int max_tagset_len = max_tagset_size - 1;
1041 char tagset_buffer[max_tagset_size];
1042 tagset_buffer[0] = '\0';
1043
1044 // Write tag-set for aliased logging option, in string list form
1045 int max_tags = sizeof(tagSet)/sizeof(tagSet[0]);
1046 for (int i = 0; i < max_tags && tagSet[i] != LogTag::__NO_TAG; i++) {
1047 if (i > 0) {
1048 strncat(tagset_buffer, "+", max_tagset_len - strlen(tagset_buffer));
1049 }
1050 strncat(tagset_buffer, LogTag::name(tagSet[i]), max_tagset_len - strlen(tagset_buffer));
1051 }
1052 if (!alf.exactMatch) {
1053 strncat(tagset_buffer, "*", max_tagset_len - strlen(tagset_buffer));
1054 }
1055 log_warning(arguments)("-XX:%s%s is deprecated. Will use -Xlog:%s=%s instead.",
1056 (on) ? "+" : "-",
1057 name,
1058 tagset_buffer,
1059 (on) ? LogLevel::name(alf.level) : "off");
1060 }
1061
catch_logging_aliases(const char * name,bool on)1062 AliasedLoggingFlag Arguments::catch_logging_aliases(const char* name, bool on){
1063 for (size_t i = 0; aliased_logging_flags[i].alias_name != NULL; i++) {
1064 const AliasedLoggingFlag& alf = aliased_logging_flags[i];
1065 if (strcmp(alf.alias_name, name) == 0) {
1066 log_deprecated_flag(name, on, alf);
1067 return alf;
1068 }
1069 }
1070 AliasedLoggingFlag a = {NULL, LogLevel::Off, false, LOG_TAGS(_NO_TAG)};
1071 return a;
1072 }
1073
parse_argument(const char * arg,JVMFlag::Flags origin)1074 bool Arguments::parse_argument(const char* arg, JVMFlag::Flags origin) {
1075
1076 // range of acceptable characters spelled out for portability reasons
1077 #define NAME_RANGE "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
1078 #define BUFLEN 255
1079 char name[BUFLEN+1];
1080 char dummy;
1081 const char* real_name;
1082 bool warn_if_deprecated = true;
1083
1084 if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
1085 AliasedLoggingFlag alf = catch_logging_aliases(name, false);
1086 if (alf.alias_name != NULL){
1087 LogConfiguration::configure_stdout(LogLevel::Off, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1088 return true;
1089 }
1090 real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1091 if (real_name == NULL) {
1092 return false;
1093 }
1094 JVMFlag* flag = JVMFlag::find_flag(real_name);
1095 return set_bool_flag(flag, false, origin);
1096 }
1097 if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
1098 AliasedLoggingFlag alf = catch_logging_aliases(name, true);
1099 if (alf.alias_name != NULL){
1100 LogConfiguration::configure_stdout(alf.level, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1101 return true;
1102 }
1103 real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1104 if (real_name == NULL) {
1105 return false;
1106 }
1107 JVMFlag* flag = JVMFlag::find_flag(real_name);
1108 return set_bool_flag(flag, true, origin);
1109 }
1110
1111 char punct;
1112 if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
1113 const char* value = strchr(arg, '=') + 1;
1114
1115 // this scanf pattern matches both strings (handled here) and numbers (handled later))
1116 AliasedLoggingFlag alf = catch_logging_aliases(name, true);
1117 if (alf.alias_name != NULL) {
1118 LogConfiguration::configure_stdout(alf.level, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1119 return true;
1120 }
1121 real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1122 if (real_name == NULL) {
1123 return false;
1124 }
1125 JVMFlag* flag = JVMFlag::find_flag(real_name);
1126 if (flag != NULL && flag->is_ccstr()) {
1127 if (flag->ccstr_accumulates()) {
1128 return append_to_string_flag(flag, value, origin);
1129 } else {
1130 if (value[0] == '\0') {
1131 value = NULL;
1132 }
1133 return set_string_flag(flag, value, origin);
1134 }
1135 } else {
1136 warn_if_deprecated = false; // if arg is deprecated, we've already done warning...
1137 }
1138 }
1139
1140 if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
1141 const char* value = strchr(arg, '=') + 1;
1142 // -XX:Foo:=xxx will reset the string flag to the given value.
1143 if (value[0] == '\0') {
1144 value = NULL;
1145 }
1146 real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1147 if (real_name == NULL) {
1148 return false;
1149 }
1150 JVMFlag* flag = JVMFlag::find_flag(real_name);
1151 return set_string_flag(flag, value, origin);
1152 }
1153
1154 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.eE+]"
1155 #define SIGNED_NUMBER_RANGE "[-0123456789]"
1156 #define NUMBER_RANGE "[0123456789eE+-]"
1157 char value[BUFLEN + 1];
1158 char value2[BUFLEN + 1];
1159 if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
1160 // Looks like a floating-point number -- try again with more lenient format string
1161 if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
1162 real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1163 if (real_name == NULL) {
1164 return false;
1165 }
1166 JVMFlag* flag = JVMFlag::find_flag(real_name);
1167 return set_fp_numeric_flag(flag, value, origin);
1168 }
1169 }
1170
1171 #define VALUE_RANGE "[-kmgtxKMGTX0123456789abcdefABCDEF]"
1172 if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
1173 real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1174 if (real_name == NULL) {
1175 return false;
1176 }
1177 JVMFlag* flag = JVMFlag::find_flag(real_name);
1178 return set_numeric_flag(flag, value, origin);
1179 }
1180
1181 return false;
1182 }
1183
add_string(char *** bldarray,int * count,const char * arg)1184 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
1185 assert(bldarray != NULL, "illegal argument");
1186
1187 if (arg == NULL) {
1188 return;
1189 }
1190
1191 int new_count = *count + 1;
1192
1193 // expand the array and add arg to the last element
1194 if (*bldarray == NULL) {
1195 *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtArguments);
1196 } else {
1197 *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtArguments);
1198 }
1199 (*bldarray)[*count] = os::strdup_check_oom(arg);
1200 *count = new_count;
1201 }
1202
build_jvm_args(const char * arg)1203 void Arguments::build_jvm_args(const char* arg) {
1204 add_string(&_jvm_args_array, &_num_jvm_args, arg);
1205 }
1206
build_jvm_flags(const char * arg)1207 void Arguments::build_jvm_flags(const char* arg) {
1208 add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
1209 }
1210
1211 // utility function to return a string that concatenates all
1212 // strings in a given char** array
build_resource_string(char ** args,int count)1213 const char* Arguments::build_resource_string(char** args, int count) {
1214 if (args == NULL || count == 0) {
1215 return NULL;
1216 }
1217 size_t length = 0;
1218 for (int i = 0; i < count; i++) {
1219 length += strlen(args[i]) + 1; // add 1 for a space or NULL terminating character
1220 }
1221 char* s = NEW_RESOURCE_ARRAY(char, length);
1222 char* dst = s;
1223 for (int j = 0; j < count; j++) {
1224 size_t offset = strlen(args[j]) + 1; // add 1 for a space or NULL terminating character
1225 jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with NULL character
1226 dst += offset;
1227 length -= offset;
1228 }
1229 return (const char*) s;
1230 }
1231
print_on(outputStream * st)1232 void Arguments::print_on(outputStream* st) {
1233 st->print_cr("VM Arguments:");
1234 if (num_jvm_flags() > 0) {
1235 st->print("jvm_flags: "); print_jvm_flags_on(st);
1236 st->cr();
1237 }
1238 if (num_jvm_args() > 0) {
1239 st->print("jvm_args: "); print_jvm_args_on(st);
1240 st->cr();
1241 }
1242 st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
1243 if (_java_class_path != NULL) {
1244 char* path = _java_class_path->value();
1245 st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
1246 }
1247 st->print_cr("Launcher Type: %s", _sun_java_launcher);
1248 }
1249
print_summary_on(outputStream * st)1250 void Arguments::print_summary_on(outputStream* st) {
1251 // Print the command line. Environment variables that are helpful for
1252 // reproducing the problem are written later in the hs_err file.
1253 // flags are from setting file
1254 if (num_jvm_flags() > 0) {
1255 st->print_raw("Settings File: ");
1256 print_jvm_flags_on(st);
1257 st->cr();
1258 }
1259 // args are the command line and environment variable arguments.
1260 st->print_raw("Command Line: ");
1261 if (num_jvm_args() > 0) {
1262 print_jvm_args_on(st);
1263 }
1264 // this is the classfile and any arguments to the java program
1265 if (java_command() != NULL) {
1266 st->print("%s", java_command());
1267 }
1268 st->cr();
1269 }
1270
print_jvm_flags_on(outputStream * st)1271 void Arguments::print_jvm_flags_on(outputStream* st) {
1272 if (_num_jvm_flags > 0) {
1273 for (int i=0; i < _num_jvm_flags; i++) {
1274 st->print("%s ", _jvm_flags_array[i]);
1275 }
1276 }
1277 }
1278
print_jvm_args_on(outputStream * st)1279 void Arguments::print_jvm_args_on(outputStream* st) {
1280 if (_num_jvm_args > 0) {
1281 for (int i=0; i < _num_jvm_args; i++) {
1282 st->print("%s ", _jvm_args_array[i]);
1283 }
1284 }
1285 }
1286
process_argument(const char * arg,jboolean ignore_unrecognized,JVMFlag::Flags origin)1287 bool Arguments::process_argument(const char* arg,
1288 jboolean ignore_unrecognized,
1289 JVMFlag::Flags origin) {
1290 JDK_Version since = JDK_Version();
1291
1292 if (parse_argument(arg, origin)) {
1293 return true;
1294 }
1295
1296 // Determine if the flag has '+', '-', or '=' characters.
1297 bool has_plus_minus = (*arg == '+' || *arg == '-');
1298 const char* const argname = has_plus_minus ? arg + 1 : arg;
1299
1300 size_t arg_len;
1301 const char* equal_sign = strchr(argname, '=');
1302 if (equal_sign == NULL) {
1303 arg_len = strlen(argname);
1304 } else {
1305 arg_len = equal_sign - argname;
1306 }
1307
1308 // Only make the obsolete check for valid arguments.
1309 if (arg_len <= BUFLEN) {
1310 // Construct a string which consists only of the argument name without '+', '-', or '='.
1311 char stripped_argname[BUFLEN+1]; // +1 for '\0'
1312 jio_snprintf(stripped_argname, arg_len+1, "%s", argname); // +1 for '\0'
1313 if (is_obsolete_flag(stripped_argname, &since)) {
1314 char version[256];
1315 since.to_string(version, sizeof(version));
1316 warning("Ignoring option %s; support was removed in %s", stripped_argname, version);
1317 return true;
1318 }
1319 #ifndef PRODUCT
1320 else {
1321 const char* replacement;
1322 if ((replacement = removed_develop_logging_flag_name(stripped_argname)) != NULL){
1323 log_warning(arguments)("%s has been removed. Please use %s instead.",
1324 stripped_argname,
1325 replacement);
1326 return false;
1327 }
1328 }
1329 #endif //PRODUCT
1330 }
1331
1332 // For locked flags, report a custom error message if available.
1333 // Otherwise, report the standard unrecognized VM option.
1334 const JVMFlag* found_flag = JVMFlag::find_declared_flag((const char*)argname, arg_len);
1335 if (found_flag != NULL) {
1336 char locked_message_buf[BUFLEN];
1337 JVMFlag::MsgType msg_type = found_flag->get_locked_message(locked_message_buf, BUFLEN);
1338 if (strlen(locked_message_buf) == 0) {
1339 if (found_flag->is_bool() && !has_plus_minus) {
1340 jio_fprintf(defaultStream::error_stream(),
1341 "Missing +/- setting for VM option '%s'\n", argname);
1342 } else if (!found_flag->is_bool() && has_plus_minus) {
1343 jio_fprintf(defaultStream::error_stream(),
1344 "Unexpected +/- setting in VM option '%s'\n", argname);
1345 } else {
1346 jio_fprintf(defaultStream::error_stream(),
1347 "Improperly specified VM option '%s'\n", argname);
1348 }
1349 } else {
1350 #ifdef PRODUCT
1351 bool mismatched = ((msg_type == JVMFlag::NOTPRODUCT_FLAG_BUT_PRODUCT_BUILD) ||
1352 (msg_type == JVMFlag::DEVELOPER_FLAG_BUT_PRODUCT_BUILD));
1353 if (ignore_unrecognized && mismatched) {
1354 return true;
1355 }
1356 #endif
1357 jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
1358 }
1359 } else {
1360 if (ignore_unrecognized) {
1361 return true;
1362 }
1363 jio_fprintf(defaultStream::error_stream(),
1364 "Unrecognized VM option '%s'\n", argname);
1365 JVMFlag* fuzzy_matched = JVMFlag::fuzzy_match((const char*)argname, arg_len, true);
1366 if (fuzzy_matched != NULL) {
1367 jio_fprintf(defaultStream::error_stream(),
1368 "Did you mean '%s%s%s'? ",
1369 (fuzzy_matched->is_bool()) ? "(+/-)" : "",
1370 fuzzy_matched->_name,
1371 (fuzzy_matched->is_bool()) ? "" : "=<value>");
1372 }
1373 }
1374
1375 // allow for commandline "commenting out" options like -XX:#+Verbose
1376 return arg[0] == '#';
1377 }
1378
process_settings_file(const char * file_name,bool should_exist,jboolean ignore_unrecognized)1379 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
1380 FILE* stream = fopen(file_name, "rb");
1381 if (stream == NULL) {
1382 if (should_exist) {
1383 jio_fprintf(defaultStream::error_stream(),
1384 "Could not open settings file %s\n", file_name);
1385 return false;
1386 } else {
1387 return true;
1388 }
1389 }
1390
1391 char token[1024];
1392 int pos = 0;
1393
1394 bool in_white_space = true;
1395 bool in_comment = false;
1396 bool in_quote = false;
1397 char quote_c = 0;
1398 bool result = true;
1399
1400 int c = getc(stream);
1401 while(c != EOF && pos < (int)(sizeof(token)-1)) {
1402 if (in_white_space) {
1403 if (in_comment) {
1404 if (c == '\n') in_comment = false;
1405 } else {
1406 if (c == '#') in_comment = true;
1407 else if (!isspace(c)) {
1408 in_white_space = false;
1409 token[pos++] = c;
1410 }
1411 }
1412 } else {
1413 if (c == '\n' || (!in_quote && isspace(c))) {
1414 // token ends at newline, or at unquoted whitespace
1415 // this allows a way to include spaces in string-valued options
1416 token[pos] = '\0';
1417 logOption(token);
1418 result &= process_argument(token, ignore_unrecognized, JVMFlag::CONFIG_FILE);
1419 build_jvm_flags(token);
1420 pos = 0;
1421 in_white_space = true;
1422 in_quote = false;
1423 } else if (!in_quote && (c == '\'' || c == '"')) {
1424 in_quote = true;
1425 quote_c = c;
1426 } else if (in_quote && (c == quote_c)) {
1427 in_quote = false;
1428 } else {
1429 token[pos++] = c;
1430 }
1431 }
1432 c = getc(stream);
1433 }
1434 if (pos > 0) {
1435 token[pos] = '\0';
1436 result &= process_argument(token, ignore_unrecognized, JVMFlag::CONFIG_FILE);
1437 build_jvm_flags(token);
1438 }
1439 fclose(stream);
1440 return result;
1441 }
1442
1443 //=============================================================================================================
1444 // Parsing of properties (-D)
1445
get_property(const char * key)1446 const char* Arguments::get_property(const char* key) {
1447 return PropertyList_get_value(system_properties(), key);
1448 }
1449
add_property(const char * prop,PropertyWriteable writeable,PropertyInternal internal)1450 bool Arguments::add_property(const char* prop, PropertyWriteable writeable, PropertyInternal internal) {
1451 const char* eq = strchr(prop, '=');
1452 const char* key;
1453 const char* value = "";
1454
1455 if (eq == NULL) {
1456 // property doesn't have a value, thus use passed string
1457 key = prop;
1458 } else {
1459 // property have a value, thus extract it and save to the
1460 // allocated string
1461 size_t key_len = eq - prop;
1462 char* tmp_key = AllocateHeap(key_len + 1, mtArguments);
1463
1464 jio_snprintf(tmp_key, key_len + 1, "%s", prop);
1465 key = tmp_key;
1466
1467 value = &prop[key_len + 1];
1468 }
1469
1470 #if INCLUDE_CDS
1471 if (is_internal_module_property(key) ||
1472 strcmp(key, "jdk.module.main") == 0) {
1473 MetaspaceShared::disable_optimized_module_handling();
1474 log_info(cds)("Using optimized module handling disabled due to incompatible property: %s=%s", key, value);
1475 }
1476 #endif
1477
1478 if (strcmp(key, "java.compiler") == 0) {
1479 process_java_compiler_argument(value);
1480 // Record value in Arguments, but let it get passed to Java.
1481 } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0) {
1482 // sun.java.launcher.is_altjvm property is
1483 // private and is processed in process_sun_java_launcher_properties();
1484 // the sun.java.launcher property is passed on to the java application
1485 } else if (strcmp(key, "sun.boot.library.path") == 0) {
1486 // append is true, writable is true, internal is false
1487 PropertyList_unique_add(&_system_properties, key, value, AppendProperty,
1488 WriteableProperty, ExternalProperty);
1489 } else {
1490 if (strcmp(key, "sun.java.command") == 0) {
1491 char *old_java_command = _java_command;
1492 _java_command = os::strdup_check_oom(value, mtArguments);
1493 if (old_java_command != NULL) {
1494 os::free(old_java_command);
1495 }
1496 } else if (strcmp(key, "java.vendor.url.bug") == 0) {
1497 // If this property is set on the command line then its value will be
1498 // displayed in VM error logs as the URL at which to submit such logs.
1499 // Normally the URL displayed in error logs is different from the value
1500 // of this system property, so a different property should have been
1501 // used here, but we leave this as-is in case someone depends upon it.
1502 const char* old_java_vendor_url_bug = _java_vendor_url_bug;
1503 // save it in _java_vendor_url_bug, so JVM fatal error handler can access
1504 // its value without going through the property list or making a Java call.
1505 _java_vendor_url_bug = os::strdup_check_oom(value, mtArguments);
1506 if (old_java_vendor_url_bug != NULL) {
1507 os::free((void *)old_java_vendor_url_bug);
1508 }
1509 }
1510
1511 // Create new property and add at the end of the list
1512 PropertyList_unique_add(&_system_properties, key, value, AddProperty, writeable, internal);
1513 }
1514
1515 if (key != prop) {
1516 // SystemProperty copy passed value, thus free previously allocated
1517 // memory
1518 FreeHeap((void *)key);
1519 }
1520
1521 return true;
1522 }
1523
1524 #if INCLUDE_CDS
1525 const char* unsupported_properties[] = { "jdk.module.limitmods",
1526 "jdk.module.upgrade.path",
1527 "jdk.module.patch.0" };
1528 const char* unsupported_options[] = { "--limit-modules",
1529 "--upgrade-module-path",
1530 "--patch-module"
1531 };
check_unsupported_dumping_properties()1532 void Arguments::check_unsupported_dumping_properties() {
1533 assert(is_dumping_archive(),
1534 "this function is only used with CDS dump time");
1535 assert(ARRAY_SIZE(unsupported_properties) == ARRAY_SIZE(unsupported_options), "must be");
1536 // If a vm option is found in the unsupported_options array, vm will exit with an error message.
1537 SystemProperty* sp = system_properties();
1538 while (sp != NULL) {
1539 for (uint i = 0; i < ARRAY_SIZE(unsupported_properties); i++) {
1540 if (strcmp(sp->key(), unsupported_properties[i]) == 0) {
1541 vm_exit_during_initialization(
1542 "Cannot use the following option when dumping the shared archive", unsupported_options[i]);
1543 }
1544 }
1545 sp = sp->next();
1546 }
1547
1548 // Check for an exploded module build in use with -Xshare:dump.
1549 if (!has_jimage()) {
1550 vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
1551 }
1552 }
1553
check_unsupported_cds_runtime_properties()1554 bool Arguments::check_unsupported_cds_runtime_properties() {
1555 assert(UseSharedSpaces, "this function is only used with -Xshare:{on,auto}");
1556 assert(ARRAY_SIZE(unsupported_properties) == ARRAY_SIZE(unsupported_options), "must be");
1557 if (ArchiveClassesAtExit != NULL) {
1558 // dynamic dumping, just return false for now.
1559 // check_unsupported_dumping_properties() will be called later to check the same set of
1560 // properties, and will exit the VM with the correct error message if the unsupported properties
1561 // are used.
1562 return false;
1563 }
1564 for (uint i = 0; i < ARRAY_SIZE(unsupported_properties); i++) {
1565 if (get_property(unsupported_properties[i]) != NULL) {
1566 if (RequireSharedSpaces) {
1567 warning("CDS is disabled when the %s option is specified.", unsupported_options[i]);
1568 }
1569 return true;
1570 }
1571 }
1572 return false;
1573 }
1574 #endif
1575
1576 //===========================================================================================================
1577 // Setting int/mixed/comp mode flags
1578
set_mode_flags(Mode mode)1579 void Arguments::set_mode_flags(Mode mode) {
1580 // Set up default values for all flags.
1581 // If you add a flag to any of the branches below,
1582 // add a default value for it here.
1583 set_java_compiler(false);
1584 _mode = mode;
1585
1586 // Ensure Agent_OnLoad has the correct initial values.
1587 // This may not be the final mode; mode may change later in onload phase.
1588 PropertyList_unique_add(&_system_properties, "java.vm.info",
1589 VM_Version::vm_info_string(), AddProperty, UnwriteableProperty, ExternalProperty);
1590
1591 UseInterpreter = true;
1592 UseCompiler = true;
1593 UseLoopCounter = true;
1594
1595 // Default values may be platform/compiler dependent -
1596 // use the saved values
1597 ClipInlining = Arguments::_ClipInlining;
1598 AlwaysCompileLoopMethods = Arguments::_AlwaysCompileLoopMethods;
1599 UseOnStackReplacement = Arguments::_UseOnStackReplacement;
1600 BackgroundCompilation = Arguments::_BackgroundCompilation;
1601 if (TieredCompilation) {
1602 if (FLAG_IS_DEFAULT(Tier3InvokeNotifyFreqLog)) {
1603 Tier3InvokeNotifyFreqLog = Arguments::_Tier3InvokeNotifyFreqLog;
1604 }
1605 if (FLAG_IS_DEFAULT(Tier4InvocationThreshold)) {
1606 Tier4InvocationThreshold = Arguments::_Tier4InvocationThreshold;
1607 }
1608 }
1609
1610 // Change from defaults based on mode
1611 switch (mode) {
1612 default:
1613 ShouldNotReachHere();
1614 break;
1615 case _int:
1616 UseCompiler = false;
1617 UseLoopCounter = false;
1618 AlwaysCompileLoopMethods = false;
1619 UseOnStackReplacement = false;
1620 break;
1621 case _mixed:
1622 // same as default
1623 break;
1624 case _comp:
1625 UseInterpreter = false;
1626 BackgroundCompilation = false;
1627 ClipInlining = false;
1628 // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1629 // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1630 // compile a level 4 (C2) and then continue executing it.
1631 if (TieredCompilation) {
1632 Tier3InvokeNotifyFreqLog = 0;
1633 Tier4InvocationThreshold = 0;
1634 }
1635 break;
1636 }
1637 }
1638
1639 // Conflict: required to use shared spaces (-Xshare:on), but
1640 // incompatible command line options were chosen.
no_shared_spaces(const char * message)1641 static void no_shared_spaces(const char* message) {
1642 if (RequireSharedSpaces) {
1643 jio_fprintf(defaultStream::error_stream(),
1644 "Class data sharing is inconsistent with other specified options.\n");
1645 vm_exit_during_initialization("Unable to use shared archive", message);
1646 } else {
1647 log_info(cds)("Unable to use shared archive: %s", message);
1648 FLAG_SET_DEFAULT(UseSharedSpaces, false);
1649 }
1650 }
1651
set_object_alignment()1652 void set_object_alignment() {
1653 // Object alignment.
1654 assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1655 MinObjAlignmentInBytes = ObjectAlignmentInBytes;
1656 assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1657 MinObjAlignment = MinObjAlignmentInBytes / HeapWordSize;
1658 assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1659 MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1660
1661 LogMinObjAlignmentInBytes = exact_log2(ObjectAlignmentInBytes);
1662 LogMinObjAlignment = LogMinObjAlignmentInBytes - LogHeapWordSize;
1663
1664 // Oop encoding heap max
1665 OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1666
1667 if (SurvivorAlignmentInBytes == 0) {
1668 SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1669 }
1670 }
1671
max_heap_for_compressed_oops()1672 size_t Arguments::max_heap_for_compressed_oops() {
1673 // Avoid sign flip.
1674 assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1675 // We need to fit both the NULL page and the heap into the memory budget, while
1676 // keeping alignment constraints of the heap. To guarantee the latter, as the
1677 // NULL page is located before the heap, we pad the NULL page to the conservative
1678 // maximum alignment that the GC may ever impose upon the heap.
1679 size_t displacement_due_to_null_page = align_up((size_t)os::vm_page_size(),
1680 _conservative_max_heap_alignment);
1681
1682 LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1683 NOT_LP64(ShouldNotReachHere(); return 0);
1684 }
1685
set_use_compressed_oops()1686 void Arguments::set_use_compressed_oops() {
1687 #ifndef ZERO
1688 #ifdef _LP64
1689 // MaxHeapSize is not set up properly at this point, but
1690 // the only value that can override MaxHeapSize if we are
1691 // to use UseCompressedOops are InitialHeapSize and MinHeapSize.
1692 size_t max_heap_size = MAX3(MaxHeapSize, InitialHeapSize, MinHeapSize);
1693
1694 if (max_heap_size <= max_heap_for_compressed_oops()) {
1695 if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1696 FLAG_SET_ERGO(UseCompressedOops, true);
1697 }
1698 } else {
1699 if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1700 warning("Max heap size too large for Compressed Oops");
1701 FLAG_SET_DEFAULT(UseCompressedOops, false);
1702 if (COMPRESSED_CLASS_POINTERS_DEPENDS_ON_COMPRESSED_OOPS) {
1703 FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1704 }
1705 }
1706 }
1707 #endif // _LP64
1708 #endif // ZERO
1709 }
1710
1711
1712 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1713 // set_use_compressed_oops().
set_use_compressed_klass_ptrs()1714 void Arguments::set_use_compressed_klass_ptrs() {
1715 #ifndef ZERO
1716 #ifdef _LP64
1717 // On some architectures, the use of UseCompressedClassPointers implies the use of
1718 // UseCompressedOops. The reason is that the rheap_base register of said platforms
1719 // is reused to perform some optimized spilling, in order to use rheap_base as a
1720 // temp register. But by treating it as any other temp register, spilling can typically
1721 // be completely avoided instead. So it is better not to perform this trick. And by
1722 // not having that reliance, large heaps, or heaps not supporting compressed oops,
1723 // can still use compressed class pointers.
1724 if (COMPRESSED_CLASS_POINTERS_DEPENDS_ON_COMPRESSED_OOPS && !UseCompressedOops) {
1725 if (UseCompressedClassPointers) {
1726 warning("UseCompressedClassPointers requires UseCompressedOops");
1727 }
1728 FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1729 } else {
1730 // Turn on UseCompressedClassPointers too
1731 if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1732 FLAG_SET_ERGO(UseCompressedClassPointers, true);
1733 }
1734 // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1735 if (UseCompressedClassPointers) {
1736 if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1737 warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1738 FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1739 }
1740 }
1741 }
1742 #endif // _LP64
1743 #endif // !ZERO
1744 }
1745
set_conservative_max_heap_alignment()1746 void Arguments::set_conservative_max_heap_alignment() {
1747 // The conservative maximum required alignment for the heap is the maximum of
1748 // the alignments imposed by several sources: any requirements from the heap
1749 // itself and the maximum page size we may run the VM with.
1750 size_t heap_alignment = GCConfig::arguments()->conservative_max_heap_alignment();
1751 _conservative_max_heap_alignment = MAX4(heap_alignment,
1752 (size_t)os::vm_allocation_granularity(),
1753 os::max_page_size(),
1754 GCArguments::compute_heap_alignment());
1755 }
1756
set_ergonomics_flags()1757 jint Arguments::set_ergonomics_flags() {
1758 GCConfig::initialize();
1759
1760 set_conservative_max_heap_alignment();
1761
1762 #ifndef ZERO
1763 #ifdef _LP64
1764 set_use_compressed_oops();
1765
1766 // set_use_compressed_klass_ptrs() must be called after calling
1767 // set_use_compressed_oops().
1768 set_use_compressed_klass_ptrs();
1769
1770 // Also checks that certain machines are slower with compressed oops
1771 // in vm_version initialization code.
1772 #endif // _LP64
1773 #endif // !ZERO
1774
1775 return JNI_OK;
1776 }
1777
limit_by_allocatable_memory(julong limit)1778 julong Arguments::limit_by_allocatable_memory(julong limit) {
1779 julong max_allocatable;
1780 julong result = limit;
1781 if (os::has_allocatable_memory_limit(&max_allocatable)) {
1782 result = MIN2(result, max_allocatable / MaxVirtMemFraction);
1783 }
1784 return result;
1785 }
1786
1787 // Use static initialization to get the default before parsing
1788 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1789
set_heap_size()1790 void Arguments::set_heap_size() {
1791 julong phys_mem;
1792
1793 // If the user specified one of these options, they
1794 // want specific memory sizing so do not limit memory
1795 // based on compressed oops addressability.
1796 // Also, memory limits will be calculated based on
1797 // available os physical memory, not our MaxRAM limit,
1798 // unless MaxRAM is also specified.
1799 bool override_coop_limit = (!FLAG_IS_DEFAULT(MaxRAMPercentage) ||
1800 !FLAG_IS_DEFAULT(MaxRAMFraction) ||
1801 !FLAG_IS_DEFAULT(MinRAMPercentage) ||
1802 !FLAG_IS_DEFAULT(MinRAMFraction) ||
1803 !FLAG_IS_DEFAULT(InitialRAMPercentage) ||
1804 !FLAG_IS_DEFAULT(InitialRAMFraction) ||
1805 !FLAG_IS_DEFAULT(MaxRAM));
1806 if (override_coop_limit) {
1807 if (FLAG_IS_DEFAULT(MaxRAM)) {
1808 phys_mem = os::physical_memory();
1809 FLAG_SET_ERGO(MaxRAM, (uint64_t)phys_mem);
1810 } else {
1811 phys_mem = (julong)MaxRAM;
1812 }
1813 } else {
1814 phys_mem = FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1815 : (julong)MaxRAM;
1816 }
1817
1818
1819 // Convert deprecated flags
1820 if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&
1821 !FLAG_IS_DEFAULT(MaxRAMFraction))
1822 MaxRAMPercentage = 100.0 / MaxRAMFraction;
1823
1824 if (FLAG_IS_DEFAULT(MinRAMPercentage) &&
1825 !FLAG_IS_DEFAULT(MinRAMFraction))
1826 MinRAMPercentage = 100.0 / MinRAMFraction;
1827
1828 if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&
1829 !FLAG_IS_DEFAULT(InitialRAMFraction))
1830 InitialRAMPercentage = 100.0 / InitialRAMFraction;
1831
1832 // If the maximum heap size has not been set with -Xmx,
1833 // then set it as fraction of the size of physical memory,
1834 // respecting the maximum and minimum sizes of the heap.
1835 if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1836 julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);
1837 const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);
1838 if (reasonable_min < MaxHeapSize) {
1839 // Small physical memory, so use a minimum fraction of it for the heap
1840 reasonable_max = reasonable_min;
1841 } else {
1842 // Not-small physical memory, so require a heap at least
1843 // as large as MaxHeapSize
1844 reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1845 }
1846
1847 if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1848 // Limit the heap size to ErgoHeapSizeLimit
1849 reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1850 }
1851
1852 #ifdef _LP64
1853 if (UseCompressedOops || UseCompressedClassPointers) {
1854 // HeapBaseMinAddress can be greater than default but not less than.
1855 if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1856 if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1857 // matches compressed oops printing flags
1858 log_debug(gc, heap, coops)("HeapBaseMinAddress must be at least " SIZE_FORMAT
1859 " (" SIZE_FORMAT "G) which is greater than value given " SIZE_FORMAT,
1860 DefaultHeapBaseMinAddress,
1861 DefaultHeapBaseMinAddress/G,
1862 HeapBaseMinAddress);
1863 FLAG_SET_ERGO(HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1864 }
1865 }
1866 }
1867 if (UseCompressedOops) {
1868 // Limit the heap size to the maximum possible when using compressed oops
1869 julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1870
1871 if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1872 // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1873 // but it should be not less than default MaxHeapSize.
1874 max_coop_heap -= HeapBaseMinAddress;
1875 }
1876
1877 // If user specified flags prioritizing os physical
1878 // memory limits, then disable compressed oops if
1879 // limits exceed max_coop_heap and UseCompressedOops
1880 // was not specified.
1881 if (reasonable_max > max_coop_heap) {
1882 if (FLAG_IS_ERGO(UseCompressedOops) && override_coop_limit) {
1883 log_info(cds)("UseCompressedOops and UseCompressedClassPointers have been disabled due to"
1884 " max heap " SIZE_FORMAT " > compressed oop heap " SIZE_FORMAT ". "
1885 "Please check the setting of MaxRAMPercentage %5.2f."
1886 ,(size_t)reasonable_max, (size_t)max_coop_heap, MaxRAMPercentage);
1887 FLAG_SET_ERGO(UseCompressedOops, false);
1888 if (COMPRESSED_CLASS_POINTERS_DEPENDS_ON_COMPRESSED_OOPS) {
1889 FLAG_SET_ERGO(UseCompressedClassPointers, false);
1890 }
1891 } else {
1892 reasonable_max = MIN2(reasonable_max, max_coop_heap);
1893 }
1894 }
1895 }
1896 #endif // _LP64
1897
1898 reasonable_max = limit_by_allocatable_memory(reasonable_max);
1899
1900 if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1901 // An initial heap size was specified on the command line,
1902 // so be sure that the maximum size is consistent. Done
1903 // after call to limit_by_allocatable_memory because that
1904 // method might reduce the allocation size.
1905 reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1906 } else if (!FLAG_IS_DEFAULT(MinHeapSize)) {
1907 reasonable_max = MAX2(reasonable_max, (julong)MinHeapSize);
1908 }
1909
1910 log_trace(gc, heap)(" Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1911 FLAG_SET_ERGO(MaxHeapSize, (size_t)reasonable_max);
1912 }
1913
1914 // If the minimum or initial heap_size have not been set or requested to be set
1915 // ergonomically, set them accordingly.
1916 if (InitialHeapSize == 0 || MinHeapSize == 0) {
1917 julong reasonable_minimum = (julong)(OldSize + NewSize);
1918
1919 reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1920
1921 reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1922
1923 if (InitialHeapSize == 0) {
1924 julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);
1925
1926 reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)MinHeapSize);
1927 reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1928
1929 reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
1930
1931 FLAG_SET_ERGO(InitialHeapSize, (size_t)reasonable_initial);
1932 log_trace(gc, heap)(" Initial heap size " SIZE_FORMAT, InitialHeapSize);
1933 }
1934 // If the minimum heap size has not been set (via -Xms or -XX:MinHeapSize),
1935 // synchronize with InitialHeapSize to avoid errors with the default value.
1936 if (MinHeapSize == 0) {
1937 FLAG_SET_ERGO(MinHeapSize, MIN2((size_t)reasonable_minimum, InitialHeapSize));
1938 log_trace(gc, heap)(" Minimum heap size " SIZE_FORMAT, MinHeapSize);
1939 }
1940 }
1941 }
1942
1943 // This option inspects the machine and attempts to set various
1944 // parameters to be optimal for long-running, memory allocation
1945 // intensive jobs. It is intended for machines with large
1946 // amounts of cpu and memory.
set_aggressive_heap_flags()1947 jint Arguments::set_aggressive_heap_flags() {
1948 // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
1949 // VM, but we may not be able to represent the total physical memory
1950 // available (like having 8gb of memory on a box but using a 32bit VM).
1951 // Thus, we need to make sure we're using a julong for intermediate
1952 // calculations.
1953 julong initHeapSize;
1954 julong total_memory = os::physical_memory();
1955
1956 if (total_memory < (julong) 256 * M) {
1957 jio_fprintf(defaultStream::error_stream(),
1958 "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
1959 vm_exit(1);
1960 }
1961
1962 // The heap size is half of available memory, or (at most)
1963 // all of possible memory less 160mb (leaving room for the OS
1964 // when using ISM). This is the maximum; because adaptive sizing
1965 // is turned on below, the actual space used may be smaller.
1966
1967 initHeapSize = MIN2(total_memory / (julong) 2,
1968 total_memory - (julong) 160 * M);
1969
1970 initHeapSize = limit_by_allocatable_memory(initHeapSize);
1971
1972 if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1973 if (FLAG_SET_CMDLINE(MaxHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1974 return JNI_EINVAL;
1975 }
1976 if (FLAG_SET_CMDLINE(InitialHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1977 return JNI_EINVAL;
1978 }
1979 if (FLAG_SET_CMDLINE(MinHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
1980 return JNI_EINVAL;
1981 }
1982 }
1983 if (FLAG_IS_DEFAULT(NewSize)) {
1984 // Make the young generation 3/8ths of the total heap.
1985 if (FLAG_SET_CMDLINE(NewSize,
1986 ((julong) MaxHeapSize / (julong) 8) * (julong) 3) != JVMFlag::SUCCESS) {
1987 return JNI_EINVAL;
1988 }
1989 if (FLAG_SET_CMDLINE(MaxNewSize, NewSize) != JVMFlag::SUCCESS) {
1990 return JNI_EINVAL;
1991 }
1992 }
1993
1994 #if !defined(_ALLBSD_SOURCE) && !defined(AIX) // UseLargePages is not yet supported on BSD and AIX.
1995 FLAG_SET_DEFAULT(UseLargePages, true);
1996 #endif
1997
1998 // Increase some data structure sizes for efficiency
1999 if (FLAG_SET_CMDLINE(BaseFootPrintEstimate, MaxHeapSize) != JVMFlag::SUCCESS) {
2000 return JNI_EINVAL;
2001 }
2002 if (FLAG_SET_CMDLINE(ResizeTLAB, false) != JVMFlag::SUCCESS) {
2003 return JNI_EINVAL;
2004 }
2005 if (FLAG_SET_CMDLINE(TLABSize, 256 * K) != JVMFlag::SUCCESS) {
2006 return JNI_EINVAL;
2007 }
2008
2009 // See the OldPLABSize comment below, but replace 'after promotion'
2010 // with 'after copying'. YoungPLABSize is the size of the survivor
2011 // space per-gc-thread buffers. The default is 4kw.
2012 if (FLAG_SET_CMDLINE(YoungPLABSize, 256 * K) != JVMFlag::SUCCESS) { // Note: this is in words
2013 return JNI_EINVAL;
2014 }
2015
2016 // OldPLABSize is the size of the buffers in the old gen that
2017 // UseParallelGC uses to promote live data that doesn't fit in the
2018 // survivor spaces. At any given time, there's one for each gc thread.
2019 // The default size is 1kw. These buffers are rarely used, since the
2020 // survivor spaces are usually big enough. For specjbb, however, there
2021 // are occasions when there's lots of live data in the young gen
2022 // and we end up promoting some of it. We don't have a definite
2023 // explanation for why bumping OldPLABSize helps, but the theory
2024 // is that a bigger PLAB results in retaining something like the
2025 // original allocation order after promotion, which improves mutator
2026 // locality. A minor effect may be that larger PLABs reduce the
2027 // number of PLAB allocation events during gc. The value of 8kw
2028 // was arrived at by experimenting with specjbb.
2029 if (FLAG_SET_CMDLINE(OldPLABSize, 8 * K) != JVMFlag::SUCCESS) { // Note: this is in words
2030 return JNI_EINVAL;
2031 }
2032
2033 // Enable parallel GC and adaptive generation sizing
2034 if (FLAG_SET_CMDLINE(UseParallelGC, true) != JVMFlag::SUCCESS) {
2035 return JNI_EINVAL;
2036 }
2037
2038 // Encourage steady state memory management
2039 if (FLAG_SET_CMDLINE(ThresholdTolerance, 100) != JVMFlag::SUCCESS) {
2040 return JNI_EINVAL;
2041 }
2042
2043 // This appears to improve mutator locality
2044 if (FLAG_SET_CMDLINE(ScavengeBeforeFullGC, false) != JVMFlag::SUCCESS) {
2045 return JNI_EINVAL;
2046 }
2047
2048 return JNI_OK;
2049 }
2050
2051 // This must be called after ergonomics.
set_bytecode_flags()2052 void Arguments::set_bytecode_flags() {
2053 if (!RewriteBytecodes) {
2054 FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
2055 }
2056 }
2057
2058 // Aggressive optimization flags
set_aggressive_opts_flags()2059 jint Arguments::set_aggressive_opts_flags() {
2060 #ifdef COMPILER2
2061 if (AggressiveUnboxing) {
2062 if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2063 FLAG_SET_DEFAULT(EliminateAutoBox, true);
2064 } else if (!EliminateAutoBox) {
2065 // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
2066 AggressiveUnboxing = false;
2067 }
2068 if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
2069 FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
2070 } else if (!DoEscapeAnalysis) {
2071 // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
2072 AggressiveUnboxing = false;
2073 }
2074 }
2075 if (!FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2076 if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2077 FLAG_SET_DEFAULT(EliminateAutoBox, true);
2078 }
2079 // Feed the cache size setting into the JDK
2080 char buffer[1024];
2081 jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
2082 if (!add_property(buffer)) {
2083 return JNI_ENOMEM;
2084 }
2085 }
2086 #endif
2087
2088 return JNI_OK;
2089 }
2090
2091 //===========================================================================================================
2092 // Parsing of java.compiler property
2093
process_java_compiler_argument(const char * arg)2094 void Arguments::process_java_compiler_argument(const char* arg) {
2095 // For backwards compatibility, Djava.compiler=NONE or ""
2096 // causes us to switch to -Xint mode UNLESS -Xdebug
2097 // is also specified.
2098 if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
2099 set_java_compiler(true); // "-Djava.compiler[=...]" most recently seen.
2100 }
2101 }
2102
process_java_launcher_argument(const char * launcher,void * extra_info)2103 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
2104 _sun_java_launcher = os::strdup_check_oom(launcher);
2105 }
2106
created_by_java_launcher()2107 bool Arguments::created_by_java_launcher() {
2108 assert(_sun_java_launcher != NULL, "property must have value");
2109 return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
2110 }
2111
sun_java_launcher_is_altjvm()2112 bool Arguments::sun_java_launcher_is_altjvm() {
2113 return _sun_java_launcher_is_altjvm;
2114 }
2115
2116 //===========================================================================================================
2117 // Parsing of main arguments
2118
2119 unsigned int addreads_count = 0;
2120 unsigned int addexports_count = 0;
2121 unsigned int addopens_count = 0;
2122 unsigned int addmods_count = 0;
2123 unsigned int patch_mod_count = 0;
2124
2125 // Check the consistency of vm_init_args
check_vm_args_consistency()2126 bool Arguments::check_vm_args_consistency() {
2127 // Method for adding checks for flag consistency.
2128 // The intent is to warn the user of all possible conflicts,
2129 // before returning an error.
2130 // Note: Needs platform-dependent factoring.
2131 bool status = true;
2132
2133 if (TLABRefillWasteFraction == 0) {
2134 jio_fprintf(defaultStream::error_stream(),
2135 "TLABRefillWasteFraction should be a denominator, "
2136 "not " SIZE_FORMAT "\n",
2137 TLABRefillWasteFraction);
2138 status = false;
2139 }
2140
2141 if (PrintNMTStatistics) {
2142 #if INCLUDE_NMT
2143 if (MemTracker::tracking_level() == NMT_off) {
2144 #endif // INCLUDE_NMT
2145 warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2146 PrintNMTStatistics = false;
2147 #if INCLUDE_NMT
2148 }
2149 #endif
2150 }
2151
2152 status = CompilerConfig::check_args_consistency(status);
2153 #if INCLUDE_JVMCI
2154 if (status && EnableJVMCI) {
2155 PropertyList_unique_add(&_system_properties, "jdk.internal.vm.ci.enabled", "true",
2156 AddProperty, UnwriteableProperty, InternalProperty);
2157 if (!create_numbered_module_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {
2158 return false;
2159 }
2160 }
2161 #endif
2162
2163 #ifndef SUPPORT_RESERVED_STACK_AREA
2164 if (StackReservedPages != 0) {
2165 FLAG_SET_CMDLINE(StackReservedPages, 0);
2166 warning("Reserved Stack Area not supported on this platform");
2167 }
2168 #endif
2169
2170 status = status && GCArguments::check_args_consistency();
2171
2172 return status;
2173 }
2174
is_bad_option(const JavaVMOption * option,jboolean ignore,const char * option_type)2175 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2176 const char* option_type) {
2177 if (ignore) return false;
2178
2179 const char* spacer = " ";
2180 if (option_type == NULL) {
2181 option_type = ++spacer; // Set both to the empty string.
2182 }
2183
2184 jio_fprintf(defaultStream::error_stream(),
2185 "Unrecognized %s%soption: %s\n", option_type, spacer,
2186 option->optionString);
2187 return true;
2188 }
2189
2190 static const char* user_assertion_options[] = {
2191 "-da", "-ea", "-disableassertions", "-enableassertions", 0
2192 };
2193
2194 static const char* system_assertion_options[] = {
2195 "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2196 };
2197
parse_uintx(const char * value,uintx * uintx_arg,uintx min_size)2198 bool Arguments::parse_uintx(const char* value,
2199 uintx* uintx_arg,
2200 uintx min_size) {
2201
2202 // Check the sign first since atojulong() parses only unsigned values.
2203 bool value_is_positive = !(*value == '-');
2204
2205 if (value_is_positive) {
2206 julong n;
2207 bool good_return = atojulong(value, &n);
2208 if (good_return) {
2209 bool above_minimum = n >= min_size;
2210 bool value_is_too_large = n > max_uintx;
2211
2212 if (above_minimum && !value_is_too_large) {
2213 *uintx_arg = n;
2214 return true;
2215 }
2216 }
2217 }
2218 return false;
2219 }
2220
create_module_property(const char * prop_name,const char * prop_value,PropertyInternal internal)2221 bool Arguments::create_module_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
2222 assert(is_internal_module_property(prop_name) ||
2223 strcmp(prop_name, "jdk.module.illegalAccess") == 0, "unknown module property: '%s'", prop_name);
2224 size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
2225 char* property = AllocateHeap(prop_len, mtArguments);
2226 int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);
2227 if (ret < 0 || ret >= (int)prop_len) {
2228 FreeHeap(property);
2229 return false;
2230 }
2231 // These are not strictly writeable properties as they cannot be set via -Dprop=val. But that
2232 // is enforced by checking is_internal_module_property(). We need the property to be writeable so
2233 // that multiple occurrences of the associated flag just causes the existing property value to be
2234 // replaced ("last option wins"). Otherwise we would need to keep track of the flags and only convert
2235 // to a property after we have finished flag processing.
2236 bool added = add_property(property, WriteableProperty, internal);
2237 FreeHeap(property);
2238 return added;
2239 }
2240
create_numbered_module_property(const char * prop_base_name,const char * prop_value,unsigned int count)2241 bool Arguments::create_numbered_module_property(const char* prop_base_name, const char* prop_value, unsigned int count) {
2242 assert(is_internal_module_property(prop_base_name), "unknown module property: '%s'", prop_base_name);
2243 const unsigned int props_count_limit = 1000;
2244 const int max_digits = 3;
2245 const int extra_symbols_count = 3; // includes '.', '=', '\0'
2246
2247 // Make sure count is < props_count_limit. Otherwise, memory allocation will be too small.
2248 if (count < props_count_limit) {
2249 size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + max_digits + extra_symbols_count;
2250 char* property = AllocateHeap(prop_len, mtArguments);
2251 int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);
2252 if (ret < 0 || ret >= (int)prop_len) {
2253 FreeHeap(property);
2254 jio_fprintf(defaultStream::error_stream(), "Failed to create property %s.%d=%s\n", prop_base_name, count, prop_value);
2255 return false;
2256 }
2257 bool added = add_property(property, UnwriteableProperty, InternalProperty);
2258 FreeHeap(property);
2259 return added;
2260 }
2261
2262 jio_fprintf(defaultStream::error_stream(), "Property count limit exceeded: %s, limit=%d\n", prop_base_name, props_count_limit);
2263 return false;
2264 }
2265
parse_memory_size(const char * s,julong * long_arg,julong min_size,julong max_size)2266 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2267 julong* long_arg,
2268 julong min_size,
2269 julong max_size) {
2270 if (!atojulong(s, long_arg)) return arg_unreadable;
2271 return check_memory_size(*long_arg, min_size, max_size);
2272 }
2273
2274 // Parse JavaVMInitArgs structure
2275
parse_vm_init_args(const JavaVMInitArgs * vm_options_args,const JavaVMInitArgs * java_tool_options_args,const JavaVMInitArgs * java_options_args,const JavaVMInitArgs * cmd_line_args)2276 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *vm_options_args,
2277 const JavaVMInitArgs *java_tool_options_args,
2278 const JavaVMInitArgs *java_options_args,
2279 const JavaVMInitArgs *cmd_line_args) {
2280 bool patch_mod_javabase = false;
2281
2282 // Save default settings for some mode flags
2283 Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2284 Arguments::_UseOnStackReplacement = UseOnStackReplacement;
2285 Arguments::_ClipInlining = ClipInlining;
2286 Arguments::_BackgroundCompilation = BackgroundCompilation;
2287 if (TieredCompilation) {
2288 Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2289 Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2290 }
2291
2292 // Remember the default value of SharedBaseAddress.
2293 Arguments::_default_SharedBaseAddress = SharedBaseAddress;
2294
2295 // Setup flags for mixed which is the default
2296 set_mode_flags(_mixed);
2297
2298 // Parse args structure generated from java.base vm options resource
2299 jint result = parse_each_vm_init_arg(vm_options_args, &patch_mod_javabase, JVMFlag::JIMAGE_RESOURCE);
2300 if (result != JNI_OK) {
2301 return result;
2302 }
2303
2304 // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2305 // variable (if present).
2306 result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, JVMFlag::ENVIRON_VAR);
2307 if (result != JNI_OK) {
2308 return result;
2309 }
2310
2311 // Parse args structure generated from the command line flags.
2312 result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, JVMFlag::COMMAND_LINE);
2313 if (result != JNI_OK) {
2314 return result;
2315 }
2316
2317 // Parse args structure generated from the _JAVA_OPTIONS environment
2318 // variable (if present) (mimics classic VM)
2319 result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, JVMFlag::ENVIRON_VAR);
2320 if (result != JNI_OK) {
2321 return result;
2322 }
2323
2324 // We need to ensure processor and memory resources have been properly
2325 // configured - which may rely on arguments we just processed - before
2326 // doing the final argument processing. Any argument processing that
2327 // needs to know about processor and memory resources must occur after
2328 // this point.
2329
2330 os::init_container_support();
2331
2332 // Do final processing now that all arguments have been parsed
2333 result = finalize_vm_init_args(patch_mod_javabase);
2334 if (result != JNI_OK) {
2335 return result;
2336 }
2337
2338 return JNI_OK;
2339 }
2340
2341 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2342 // represents a valid JDWP agent. is_path==true denotes that we
2343 // are dealing with -agentpath (case where name is a path), otherwise with
2344 // -agentlib
valid_jdwp_agent(char * name,bool is_path)2345 bool valid_jdwp_agent(char *name, bool is_path) {
2346 char *_name;
2347 const char *_jdwp = "jdwp";
2348 size_t _len_jdwp, _len_prefix;
2349
2350 if (is_path) {
2351 if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2352 return false;
2353 }
2354
2355 _name++; // skip past last path separator
2356 _len_prefix = strlen(JNI_LIB_PREFIX);
2357
2358 if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2359 return false;
2360 }
2361
2362 _name += _len_prefix;
2363 _len_jdwp = strlen(_jdwp);
2364
2365 if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2366 _name += _len_jdwp;
2367 }
2368 else {
2369 return false;
2370 }
2371
2372 if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2373 return false;
2374 }
2375
2376 return true;
2377 }
2378
2379 if (strcmp(name, _jdwp) == 0) {
2380 return true;
2381 }
2382
2383 return false;
2384 }
2385
process_patch_mod_option(const char * patch_mod_tail,bool * patch_mod_javabase)2386 int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {
2387 // --patch-module=<module>=<file>(<pathsep><file>)*
2388 assert(patch_mod_tail != NULL, "Unexpected NULL patch-module value");
2389 // Find the equal sign between the module name and the path specification
2390 const char* module_equal = strchr(patch_mod_tail, '=');
2391 if (module_equal == NULL) {
2392 jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");
2393 return JNI_ERR;
2394 } else {
2395 // Pick out the module name
2396 size_t module_len = module_equal - patch_mod_tail;
2397 char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);
2398 if (module_name != NULL) {
2399 memcpy(module_name, patch_mod_tail, module_len);
2400 *(module_name + module_len) = '\0';
2401 // The path piece begins one past the module_equal sign
2402 add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);
2403 FREE_C_HEAP_ARRAY(char, module_name);
2404 if (!create_numbered_module_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {
2405 return JNI_ENOMEM;
2406 }
2407 } else {
2408 return JNI_ENOMEM;
2409 }
2410 }
2411 return JNI_OK;
2412 }
2413
2414 // Parse -Xss memory string parameter and convert to ThreadStackSize in K.
parse_xss(const JavaVMOption * option,const char * tail,intx * out_ThreadStackSize)2415 jint Arguments::parse_xss(const JavaVMOption* option, const char* tail, intx* out_ThreadStackSize) {
2416 // The min and max sizes match the values in globals.hpp, but scaled
2417 // with K. The values have been chosen so that alignment with page
2418 // size doesn't change the max value, which makes the conversions
2419 // back and forth between Xss value and ThreadStackSize value easier.
2420 // The values have also been chosen to fit inside a 32-bit signed type.
2421 const julong min_ThreadStackSize = 0;
2422 const julong max_ThreadStackSize = 1 * M;
2423
2424 const julong min_size = min_ThreadStackSize * K;
2425 const julong max_size = max_ThreadStackSize * K;
2426
2427 assert(is_aligned(max_size, os::vm_page_size()), "Implementation assumption");
2428
2429 julong size = 0;
2430 ArgsRange errcode = parse_memory_size(tail, &size, min_size, max_size);
2431 if (errcode != arg_in_range) {
2432 bool silent = (option == NULL); // Allow testing to silence error messages
2433 if (!silent) {
2434 jio_fprintf(defaultStream::error_stream(),
2435 "Invalid thread stack size: %s\n", option->optionString);
2436 describe_range_error(errcode);
2437 }
2438 return JNI_EINVAL;
2439 }
2440
2441 // Internally track ThreadStackSize in units of 1024 bytes.
2442 const julong size_aligned = align_up(size, K);
2443 assert(size <= size_aligned,
2444 "Overflow: " JULONG_FORMAT " " JULONG_FORMAT,
2445 size, size_aligned);
2446
2447 const julong size_in_K = size_aligned / K;
2448 assert(size_in_K < (julong)max_intx,
2449 "size_in_K doesn't fit in the type of ThreadStackSize: " JULONG_FORMAT,
2450 size_in_K);
2451
2452 // Check that code expanding ThreadStackSize to a page aligned number of bytes won't overflow.
2453 const julong max_expanded = align_up(size_in_K * K, os::vm_page_size());
2454 assert(max_expanded < max_uintx && max_expanded >= size_in_K,
2455 "Expansion overflowed: " JULONG_FORMAT " " JULONG_FORMAT,
2456 max_expanded, size_in_K);
2457
2458 *out_ThreadStackSize = (intx)size_in_K;
2459
2460 return JNI_OK;
2461 }
2462
parse_each_vm_init_arg(const JavaVMInitArgs * args,bool * patch_mod_javabase,JVMFlag::Flags origin)2463 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, JVMFlag::Flags origin) {
2464 // For match_option to return remaining or value part of option string
2465 const char* tail;
2466
2467 // iterate over arguments
2468 for (int index = 0; index < args->nOptions; index++) {
2469 bool is_absolute_path = false; // for -agentpath vs -agentlib
2470
2471 const JavaVMOption* option = args->options + index;
2472
2473 if (!match_option(option, "-Djava.class.path", &tail) &&
2474 !match_option(option, "-Dsun.java.command", &tail) &&
2475 !match_option(option, "-Dsun.java.launcher", &tail)) {
2476
2477 // add all jvm options to the jvm_args string. This string
2478 // is used later to set the java.vm.args PerfData string constant.
2479 // the -Djava.class.path and the -Dsun.java.command options are
2480 // omitted from jvm_args string as each have their own PerfData
2481 // string constant object.
2482 build_jvm_args(option->optionString);
2483 }
2484
2485 // -verbose:[class/module/gc/jni]
2486 if (match_option(option, "-verbose", &tail)) {
2487 if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2488 LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));
2489 LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));
2490 } else if (!strcmp(tail, ":module")) {
2491 LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, load));
2492 LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, unload));
2493 } else if (!strcmp(tail, ":gc")) {
2494 LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(gc));
2495 } else if (!strcmp(tail, ":jni")) {
2496 LogConfiguration::configure_stdout(LogLevel::Debug, true, LOG_TAGS(jni, resolve));
2497 }
2498 // -da / -ea / -disableassertions / -enableassertions
2499 // These accept an optional class/package name separated by a colon, e.g.,
2500 // -da:java.lang.Thread.
2501 } else if (match_option(option, user_assertion_options, &tail, true)) {
2502 bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'
2503 if (*tail == '\0') {
2504 JavaAssertions::setUserClassDefault(enable);
2505 } else {
2506 assert(*tail == ':', "bogus match by match_option()");
2507 JavaAssertions::addOption(tail + 1, enable);
2508 }
2509 // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2510 } else if (match_option(option, system_assertion_options, &tail, false)) {
2511 bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'
2512 JavaAssertions::setSystemClassDefault(enable);
2513 // -bootclasspath:
2514 } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2515 jio_fprintf(defaultStream::output_stream(),
2516 "-Xbootclasspath is no longer a supported option.\n");
2517 return JNI_EINVAL;
2518 // -bootclasspath/a:
2519 } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2520 Arguments::append_sysclasspath(tail);
2521 #if INCLUDE_CDS
2522 MetaspaceShared::disable_optimized_module_handling();
2523 log_info(cds)("Using optimized module handling disabled due to bootclasspath was appended");
2524 #endif
2525 // -bootclasspath/p:
2526 } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2527 jio_fprintf(defaultStream::output_stream(),
2528 "-Xbootclasspath/p is no longer a supported option.\n");
2529 return JNI_EINVAL;
2530 // -Xrun
2531 } else if (match_option(option, "-Xrun", &tail)) {
2532 if (tail != NULL) {
2533 const char* pos = strchr(tail, ':');
2534 size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2535 char* name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2536 jio_snprintf(name, len + 1, "%s", tail);
2537
2538 char *options = NULL;
2539 if(pos != NULL) {
2540 size_t len2 = strlen(pos+1) + 1; // options start after ':'. Final zero must be copied.
2541 options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);
2542 }
2543 #if !INCLUDE_JVMTI
2544 if (strcmp(name, "jdwp") == 0) {
2545 jio_fprintf(defaultStream::error_stream(),
2546 "Debugging agents are not supported in this VM\n");
2547 return JNI_ERR;
2548 }
2549 #endif // !INCLUDE_JVMTI
2550 add_init_library(name, options);
2551 }
2552 } else if (match_option(option, "--add-reads=", &tail)) {
2553 if (!create_numbered_module_property("jdk.module.addreads", tail, addreads_count++)) {
2554 return JNI_ENOMEM;
2555 }
2556 } else if (match_option(option, "--add-exports=", &tail)) {
2557 if (!create_numbered_module_property("jdk.module.addexports", tail, addexports_count++)) {
2558 return JNI_ENOMEM;
2559 }
2560 } else if (match_option(option, "--add-opens=", &tail)) {
2561 if (!create_numbered_module_property("jdk.module.addopens", tail, addopens_count++)) {
2562 return JNI_ENOMEM;
2563 }
2564 } else if (match_option(option, "--add-modules=", &tail)) {
2565 if (!create_numbered_module_property("jdk.module.addmods", tail, addmods_count++)) {
2566 return JNI_ENOMEM;
2567 }
2568 } else if (match_option(option, "--limit-modules=", &tail)) {
2569 if (!create_module_property("jdk.module.limitmods", tail, InternalProperty)) {
2570 return JNI_ENOMEM;
2571 }
2572 } else if (match_option(option, "--module-path=", &tail)) {
2573 if (!create_module_property("jdk.module.path", tail, ExternalProperty)) {
2574 return JNI_ENOMEM;
2575 }
2576 } else if (match_option(option, "--upgrade-module-path=", &tail)) {
2577 if (!create_module_property("jdk.module.upgrade.path", tail, ExternalProperty)) {
2578 return JNI_ENOMEM;
2579 }
2580 } else if (match_option(option, "--patch-module=", &tail)) {
2581 // --patch-module=<module>=<file>(<pathsep><file>)*
2582 int res = process_patch_mod_option(tail, patch_mod_javabase);
2583 if (res != JNI_OK) {
2584 return res;
2585 }
2586 } else if (match_option(option, "--illegal-access=", &tail)) {
2587 if (!create_module_property("jdk.module.illegalAccess", tail, ExternalProperty)) {
2588 return JNI_ENOMEM;
2589 }
2590 // -agentlib and -agentpath
2591 } else if (match_option(option, "-agentlib:", &tail) ||
2592 (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2593 if(tail != NULL) {
2594 const char* pos = strchr(tail, '=');
2595 char* name;
2596 if (pos == NULL) {
2597 name = os::strdup_check_oom(tail, mtArguments);
2598 } else {
2599 size_t len = pos - tail;
2600 name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2601 memcpy(name, tail, len);
2602 name[len] = '\0';
2603 }
2604
2605 char *options = NULL;
2606 if(pos != NULL) {
2607 options = os::strdup_check_oom(pos + 1, mtArguments);
2608 }
2609 #if !INCLUDE_JVMTI
2610 if (valid_jdwp_agent(name, is_absolute_path)) {
2611 jio_fprintf(defaultStream::error_stream(),
2612 "Debugging agents are not supported in this VM\n");
2613 return JNI_ERR;
2614 }
2615 #endif // !INCLUDE_JVMTI
2616 add_init_agent(name, options, is_absolute_path);
2617 }
2618 // -javaagent
2619 } else if (match_option(option, "-javaagent:", &tail)) {
2620 #if !INCLUDE_JVMTI
2621 jio_fprintf(defaultStream::error_stream(),
2622 "Instrumentation agents are not supported in this VM\n");
2623 return JNI_ERR;
2624 #else
2625 if (tail != NULL) {
2626 size_t length = strlen(tail) + 1;
2627 char *options = NEW_C_HEAP_ARRAY(char, length, mtArguments);
2628 jio_snprintf(options, length, "%s", tail);
2629 add_instrument_agent("instrument", options, false);
2630 // java agents need module java.instrument
2631 if (!create_numbered_module_property("jdk.module.addmods", "java.instrument", addmods_count++)) {
2632 return JNI_ENOMEM;
2633 }
2634 }
2635 #endif // !INCLUDE_JVMTI
2636 // --enable_preview
2637 } else if (match_option(option, "--enable-preview")) {
2638 set_enable_preview();
2639 // -Xnoclassgc
2640 } else if (match_option(option, "-Xnoclassgc")) {
2641 if (FLAG_SET_CMDLINE(ClassUnloading, false) != JVMFlag::SUCCESS) {
2642 return JNI_EINVAL;
2643 }
2644 // -Xbatch
2645 } else if (match_option(option, "-Xbatch")) {
2646 if (FLAG_SET_CMDLINE(BackgroundCompilation, false) != JVMFlag::SUCCESS) {
2647 return JNI_EINVAL;
2648 }
2649 // -Xmn for compatibility with other JVM vendors
2650 } else if (match_option(option, "-Xmn", &tail)) {
2651 julong long_initial_young_size = 0;
2652 ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2653 if (errcode != arg_in_range) {
2654 jio_fprintf(defaultStream::error_stream(),
2655 "Invalid initial young generation size: %s\n", option->optionString);
2656 describe_range_error(errcode);
2657 return JNI_EINVAL;
2658 }
2659 if (FLAG_SET_CMDLINE(MaxNewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {
2660 return JNI_EINVAL;
2661 }
2662 if (FLAG_SET_CMDLINE(NewSize, (size_t)long_initial_young_size) != JVMFlag::SUCCESS) {
2663 return JNI_EINVAL;
2664 }
2665 // -Xms
2666 } else if (match_option(option, "-Xms", &tail)) {
2667 julong size = 0;
2668 // an initial heap size of 0 means automatically determine
2669 ArgsRange errcode = parse_memory_size(tail, &size, 0);
2670 if (errcode != arg_in_range) {
2671 jio_fprintf(defaultStream::error_stream(),
2672 "Invalid initial heap size: %s\n", option->optionString);
2673 describe_range_error(errcode);
2674 return JNI_EINVAL;
2675 }
2676 if (FLAG_SET_CMDLINE(MinHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
2677 return JNI_EINVAL;
2678 }
2679 if (FLAG_SET_CMDLINE(InitialHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
2680 return JNI_EINVAL;
2681 }
2682 // -Xmx
2683 } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2684 julong long_max_heap_size = 0;
2685 ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2686 if (errcode != arg_in_range) {
2687 jio_fprintf(defaultStream::error_stream(),
2688 "Invalid maximum heap size: %s\n", option->optionString);
2689 describe_range_error(errcode);
2690 return JNI_EINVAL;
2691 }
2692 if (FLAG_SET_CMDLINE(MaxHeapSize, (size_t)long_max_heap_size) != JVMFlag::SUCCESS) {
2693 return JNI_EINVAL;
2694 }
2695 // Xmaxf
2696 } else if (match_option(option, "-Xmaxf", &tail)) {
2697 char* err;
2698 int maxf = (int)(strtod(tail, &err) * 100);
2699 if (*err != '\0' || *tail == '\0') {
2700 jio_fprintf(defaultStream::error_stream(),
2701 "Bad max heap free percentage size: %s\n",
2702 option->optionString);
2703 return JNI_EINVAL;
2704 } else {
2705 if (FLAG_SET_CMDLINE(MaxHeapFreeRatio, maxf) != JVMFlag::SUCCESS) {
2706 return JNI_EINVAL;
2707 }
2708 }
2709 // Xminf
2710 } else if (match_option(option, "-Xminf", &tail)) {
2711 char* err;
2712 int minf = (int)(strtod(tail, &err) * 100);
2713 if (*err != '\0' || *tail == '\0') {
2714 jio_fprintf(defaultStream::error_stream(),
2715 "Bad min heap free percentage size: %s\n",
2716 option->optionString);
2717 return JNI_EINVAL;
2718 } else {
2719 if (FLAG_SET_CMDLINE(MinHeapFreeRatio, minf) != JVMFlag::SUCCESS) {
2720 return JNI_EINVAL;
2721 }
2722 }
2723 // -Xss
2724 } else if (match_option(option, "-Xss", &tail)) {
2725 intx value = 0;
2726 jint err = parse_xss(option, tail, &value);
2727 if (err != JNI_OK) {
2728 return err;
2729 }
2730 if (FLAG_SET_CMDLINE(ThreadStackSize, value) != JVMFlag::SUCCESS) {
2731 return JNI_EINVAL;
2732 }
2733 } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2734 match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2735 julong long_ReservedCodeCacheSize = 0;
2736
2737 ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2738 if (errcode != arg_in_range) {
2739 jio_fprintf(defaultStream::error_stream(),
2740 "Invalid maximum code cache size: %s.\n", option->optionString);
2741 return JNI_EINVAL;
2742 }
2743 if (FLAG_SET_CMDLINE(ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != JVMFlag::SUCCESS) {
2744 return JNI_EINVAL;
2745 }
2746 // -green
2747 } else if (match_option(option, "-green")) {
2748 jio_fprintf(defaultStream::error_stream(),
2749 "Green threads support not available\n");
2750 return JNI_EINVAL;
2751 // -native
2752 } else if (match_option(option, "-native")) {
2753 // HotSpot always uses native threads, ignore silently for compatibility
2754 // -Xrs
2755 } else if (match_option(option, "-Xrs")) {
2756 // Classic/EVM option, new functionality
2757 if (FLAG_SET_CMDLINE(ReduceSignalUsage, true) != JVMFlag::SUCCESS) {
2758 return JNI_EINVAL;
2759 }
2760 // -Xprof
2761 } else if (match_option(option, "-Xprof")) {
2762 char version[256];
2763 // Obsolete in JDK 10
2764 JDK_Version::jdk(10).to_string(version, sizeof(version));
2765 warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2766 // -Xinternalversion
2767 } else if (match_option(option, "-Xinternalversion")) {
2768 jio_fprintf(defaultStream::output_stream(), "%s\n",
2769 VM_Version::internal_vm_info_string());
2770 vm_exit(0);
2771 #ifndef PRODUCT
2772 // -Xprintflags
2773 } else if (match_option(option, "-Xprintflags")) {
2774 JVMFlag::printFlags(tty, false);
2775 vm_exit(0);
2776 #endif
2777 // -D
2778 } else if (match_option(option, "-D", &tail)) {
2779 const char* value;
2780 if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2781 *value!= '\0' && strcmp(value, "\"\"") != 0) {
2782 // abort if -Djava.endorsed.dirs is set
2783 jio_fprintf(defaultStream::output_stream(),
2784 "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2785 "in modular form will be supported via the concept of upgradeable modules.\n", value);
2786 return JNI_EINVAL;
2787 }
2788 if (match_option(option, "-Djava.ext.dirs=", &value) &&
2789 *value != '\0' && strcmp(value, "\"\"") != 0) {
2790 // abort if -Djava.ext.dirs is set
2791 jio_fprintf(defaultStream::output_stream(),
2792 "-Djava.ext.dirs=%s is not supported. Use -classpath instead.\n", value);
2793 return JNI_EINVAL;
2794 }
2795 // Check for module related properties. They must be set using the modules
2796 // options. For example: use "--add-modules=java.sql", not
2797 // "-Djdk.module.addmods=java.sql"
2798 if (is_internal_module_property(option->optionString + 2)) {
2799 needs_module_property_warning = true;
2800 continue;
2801 }
2802 if (!add_property(tail)) {
2803 return JNI_ENOMEM;
2804 }
2805 // Out of the box management support
2806 if (match_option(option, "-Dcom.sun.management", &tail)) {
2807 #if INCLUDE_MANAGEMENT
2808 if (FLAG_SET_CMDLINE(ManagementServer, true) != JVMFlag::SUCCESS) {
2809 return JNI_EINVAL;
2810 }
2811 // management agent in module jdk.management.agent
2812 if (!create_numbered_module_property("jdk.module.addmods", "jdk.management.agent", addmods_count++)) {
2813 return JNI_ENOMEM;
2814 }
2815 #else
2816 jio_fprintf(defaultStream::output_stream(),
2817 "-Dcom.sun.management is not supported in this VM.\n");
2818 return JNI_ERR;
2819 #endif
2820 }
2821 // -Xint
2822 } else if (match_option(option, "-Xint")) {
2823 set_mode_flags(_int);
2824 // -Xmixed
2825 } else if (match_option(option, "-Xmixed")) {
2826 set_mode_flags(_mixed);
2827 // -Xcomp
2828 } else if (match_option(option, "-Xcomp")) {
2829 // for testing the compiler; turn off all flags that inhibit compilation
2830 set_mode_flags(_comp);
2831 // -Xshare:dump
2832 } else if (match_option(option, "-Xshare:dump")) {
2833 if (FLAG_SET_CMDLINE(DumpSharedSpaces, true) != JVMFlag::SUCCESS) {
2834 return JNI_EINVAL;
2835 }
2836 // -Xshare:on
2837 } else if (match_option(option, "-Xshare:on")) {
2838 if (FLAG_SET_CMDLINE(UseSharedSpaces, true) != JVMFlag::SUCCESS) {
2839 return JNI_EINVAL;
2840 }
2841 if (FLAG_SET_CMDLINE(RequireSharedSpaces, true) != JVMFlag::SUCCESS) {
2842 return JNI_EINVAL;
2843 }
2844 // -Xshare:auto || -XX:ArchiveClassesAtExit=<archive file>
2845 } else if (match_option(option, "-Xshare:auto")) {
2846 if (FLAG_SET_CMDLINE(UseSharedSpaces, true) != JVMFlag::SUCCESS) {
2847 return JNI_EINVAL;
2848 }
2849 if (FLAG_SET_CMDLINE(RequireSharedSpaces, false) != JVMFlag::SUCCESS) {
2850 return JNI_EINVAL;
2851 }
2852 // -Xshare:off
2853 } else if (match_option(option, "-Xshare:off")) {
2854 if (FLAG_SET_CMDLINE(UseSharedSpaces, false) != JVMFlag::SUCCESS) {
2855 return JNI_EINVAL;
2856 }
2857 if (FLAG_SET_CMDLINE(RequireSharedSpaces, false) != JVMFlag::SUCCESS) {
2858 return JNI_EINVAL;
2859 }
2860 // -Xverify
2861 } else if (match_option(option, "-Xverify", &tail)) {
2862 if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
2863 if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, true) != JVMFlag::SUCCESS) {
2864 return JNI_EINVAL;
2865 }
2866 if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {
2867 return JNI_EINVAL;
2868 }
2869 } else if (strcmp(tail, ":remote") == 0) {
2870 if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {
2871 return JNI_EINVAL;
2872 }
2873 if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, true) != JVMFlag::SUCCESS) {
2874 return JNI_EINVAL;
2875 }
2876 } else if (strcmp(tail, ":none") == 0) {
2877 if (FLAG_SET_CMDLINE(BytecodeVerificationLocal, false) != JVMFlag::SUCCESS) {
2878 return JNI_EINVAL;
2879 }
2880 if (FLAG_SET_CMDLINE(BytecodeVerificationRemote, false) != JVMFlag::SUCCESS) {
2881 return JNI_EINVAL;
2882 }
2883 warning("Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.");
2884 } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
2885 return JNI_EINVAL;
2886 }
2887 // -Xdebug
2888 } else if (match_option(option, "-Xdebug")) {
2889 // note this flag has been used, then ignore
2890 set_xdebug_mode(true);
2891 // -Xnoagent
2892 } else if (match_option(option, "-Xnoagent")) {
2893 // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
2894 } else if (match_option(option, "-Xloggc:", &tail)) {
2895 // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
2896 log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
2897 _gc_log_filename = os::strdup_check_oom(tail);
2898 } else if (match_option(option, "-Xlog", &tail)) {
2899 bool ret = false;
2900 if (strcmp(tail, ":help") == 0) {
2901 fileStream stream(defaultStream::output_stream());
2902 LogConfiguration::print_command_line_help(&stream);
2903 vm_exit(0);
2904 } else if (strcmp(tail, ":disable") == 0) {
2905 LogConfiguration::disable_logging();
2906 ret = true;
2907 } else if (*tail == '\0') {
2908 ret = LogConfiguration::parse_command_line_arguments();
2909 assert(ret, "-Xlog without arguments should never fail to parse");
2910 } else if (*tail == ':') {
2911 ret = LogConfiguration::parse_command_line_arguments(tail + 1);
2912 }
2913 if (ret == false) {
2914 jio_fprintf(defaultStream::error_stream(),
2915 "Invalid -Xlog option '-Xlog%s', see error log for details.\n",
2916 tail);
2917 return JNI_EINVAL;
2918 }
2919 // JNI hooks
2920 } else if (match_option(option, "-Xcheck", &tail)) {
2921 if (!strcmp(tail, ":jni")) {
2922 #if !INCLUDE_JNI_CHECK
2923 warning("JNI CHECKING is not supported in this VM");
2924 #else
2925 CheckJNICalls = true;
2926 #endif // INCLUDE_JNI_CHECK
2927 } else if (is_bad_option(option, args->ignoreUnrecognized,
2928 "check")) {
2929 return JNI_EINVAL;
2930 }
2931 } else if (match_option(option, "vfprintf")) {
2932 _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
2933 } else if (match_option(option, "exit")) {
2934 _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
2935 } else if (match_option(option, "abort")) {
2936 _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
2937 // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
2938 // and the last option wins.
2939 } else if (match_option(option, "-XX:+NeverTenure")) {
2940 if (FLAG_SET_CMDLINE(NeverTenure, true) != JVMFlag::SUCCESS) {
2941 return JNI_EINVAL;
2942 }
2943 if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {
2944 return JNI_EINVAL;
2945 }
2946 if (FLAG_SET_CMDLINE(MaxTenuringThreshold, markWord::max_age + 1) != JVMFlag::SUCCESS) {
2947 return JNI_EINVAL;
2948 }
2949 } else if (match_option(option, "-XX:+AlwaysTenure")) {
2950 if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2951 return JNI_EINVAL;
2952 }
2953 if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {
2954 return JNI_EINVAL;
2955 }
2956 if (FLAG_SET_CMDLINE(MaxTenuringThreshold, 0) != JVMFlag::SUCCESS) {
2957 return JNI_EINVAL;
2958 }
2959 } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
2960 uintx max_tenuring_thresh = 0;
2961 if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
2962 jio_fprintf(defaultStream::error_stream(),
2963 "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
2964 return JNI_EINVAL;
2965 }
2966
2967 if (FLAG_SET_CMDLINE(MaxTenuringThreshold, max_tenuring_thresh) != JVMFlag::SUCCESS) {
2968 return JNI_EINVAL;
2969 }
2970
2971 if (MaxTenuringThreshold == 0) {
2972 if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2973 return JNI_EINVAL;
2974 }
2975 if (FLAG_SET_CMDLINE(AlwaysTenure, true) != JVMFlag::SUCCESS) {
2976 return JNI_EINVAL;
2977 }
2978 } else {
2979 if (FLAG_SET_CMDLINE(NeverTenure, false) != JVMFlag::SUCCESS) {
2980 return JNI_EINVAL;
2981 }
2982 if (FLAG_SET_CMDLINE(AlwaysTenure, false) != JVMFlag::SUCCESS) {
2983 return JNI_EINVAL;
2984 }
2985 }
2986 } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
2987 if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, false) != JVMFlag::SUCCESS) {
2988 return JNI_EINVAL;
2989 }
2990 if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, true) != JVMFlag::SUCCESS) {
2991 return JNI_EINVAL;
2992 }
2993 } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
2994 if (FLAG_SET_CMDLINE(DisplayVMOutputToStderr, false) != JVMFlag::SUCCESS) {
2995 return JNI_EINVAL;
2996 }
2997 if (FLAG_SET_CMDLINE(DisplayVMOutputToStdout, true) != JVMFlag::SUCCESS) {
2998 return JNI_EINVAL;
2999 }
3000 } else if (match_option(option, "-XX:+ErrorFileToStderr")) {
3001 if (FLAG_SET_CMDLINE(ErrorFileToStdout, false) != JVMFlag::SUCCESS) {
3002 return JNI_EINVAL;
3003 }
3004 if (FLAG_SET_CMDLINE(ErrorFileToStderr, true) != JVMFlag::SUCCESS) {
3005 return JNI_EINVAL;
3006 }
3007 } else if (match_option(option, "-XX:+ErrorFileToStdout")) {
3008 if (FLAG_SET_CMDLINE(ErrorFileToStderr, false) != JVMFlag::SUCCESS) {
3009 return JNI_EINVAL;
3010 }
3011 if (FLAG_SET_CMDLINE(ErrorFileToStdout, true) != JVMFlag::SUCCESS) {
3012 return JNI_EINVAL;
3013 }
3014 } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3015 #if defined(DTRACE_ENABLED)
3016 if (FLAG_SET_CMDLINE(ExtendedDTraceProbes, true) != JVMFlag::SUCCESS) {
3017 return JNI_EINVAL;
3018 }
3019 if (FLAG_SET_CMDLINE(DTraceMethodProbes, true) != JVMFlag::SUCCESS) {
3020 return JNI_EINVAL;
3021 }
3022 if (FLAG_SET_CMDLINE(DTraceAllocProbes, true) != JVMFlag::SUCCESS) {
3023 return JNI_EINVAL;
3024 }
3025 if (FLAG_SET_CMDLINE(DTraceMonitorProbes, true) != JVMFlag::SUCCESS) {
3026 return JNI_EINVAL;
3027 }
3028 #else // defined(DTRACE_ENABLED)
3029 jio_fprintf(defaultStream::error_stream(),
3030 "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3031 return JNI_EINVAL;
3032 #endif // defined(DTRACE_ENABLED)
3033 #ifdef ASSERT
3034 } else if (match_option(option, "-XX:+FullGCALot")) {
3035 if (FLAG_SET_CMDLINE(FullGCALot, true) != JVMFlag::SUCCESS) {
3036 return JNI_EINVAL;
3037 }
3038 // disable scavenge before parallel mark-compact
3039 if (FLAG_SET_CMDLINE(ScavengeBeforeFullGC, false) != JVMFlag::SUCCESS) {
3040 return JNI_EINVAL;
3041 }
3042 #endif
3043 #if !INCLUDE_MANAGEMENT
3044 } else if (match_option(option, "-XX:+ManagementServer")) {
3045 jio_fprintf(defaultStream::error_stream(),
3046 "ManagementServer is not supported in this VM.\n");
3047 return JNI_ERR;
3048 #endif // INCLUDE_MANAGEMENT
3049 #if INCLUDE_JVMCI
3050 } else if (match_option(option, "-XX:-EnableJVMCIProduct")) {
3051 if (EnableJVMCIProduct) {
3052 jio_fprintf(defaultStream::error_stream(),
3053 "-XX:-EnableJVMCIProduct cannot come after -XX:+EnableJVMCIProduct\n");
3054 return JNI_EINVAL;
3055 }
3056 } else if (match_option(option, "-XX:+EnableJVMCIProduct")) {
3057 // Just continue, since "-XX:+EnableJVMCIProduct" has been specified before
3058 if (EnableJVMCIProduct) {
3059 continue;
3060 }
3061 JVMFlag *jvmciFlag = JVMFlag::find_flag("EnableJVMCIProduct");
3062 // Allow this flag if it has been unlocked.
3063 if (jvmciFlag != NULL && jvmciFlag->is_unlocked()) {
3064 if (!JVMCIGlobals::enable_jvmci_product_mode(origin)) {
3065 jio_fprintf(defaultStream::error_stream(),
3066 "Unable to enable JVMCI in product mode");
3067 return JNI_ERR;
3068 }
3069 }
3070 // The flag was locked so process normally to report that error
3071 else if (!process_argument("EnableJVMCIProduct", args->ignoreUnrecognized, origin)) {
3072 return JNI_EINVAL;
3073 }
3074 #endif // INCLUDE_JVMCI
3075 #if INCLUDE_JFR
3076 } else if (match_jfr_option(&option)) {
3077 return JNI_EINVAL;
3078 #endif
3079 } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3080 // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
3081 // already been handled
3082 if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
3083 (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
3084 if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3085 return JNI_EINVAL;
3086 }
3087 }
3088 // Unknown option
3089 } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3090 return JNI_ERR;
3091 }
3092 }
3093
3094 // PrintSharedArchiveAndExit will turn on
3095 // -Xshare:on
3096 // -Xlog:class+path=info
3097 if (PrintSharedArchiveAndExit) {
3098 if (FLAG_SET_CMDLINE(UseSharedSpaces, true) != JVMFlag::SUCCESS) {
3099 return JNI_EINVAL;
3100 }
3101 if (FLAG_SET_CMDLINE(RequireSharedSpaces, true) != JVMFlag::SUCCESS) {
3102 return JNI_EINVAL;
3103 }
3104 LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));
3105 }
3106
3107 fix_appclasspath();
3108
3109 return JNI_OK;
3110 }
3111
add_patch_mod_prefix(const char * module_name,const char * path,bool * patch_mod_javabase)3112 void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {
3113 // For java.base check for duplicate --patch-module options being specified on the command line.
3114 // This check is only required for java.base, all other duplicate module specifications
3115 // will be checked during module system initialization. The module system initialization
3116 // will throw an ExceptionInInitializerError if this situation occurs.
3117 if (strcmp(module_name, JAVA_BASE_NAME) == 0) {
3118 if (*patch_mod_javabase) {
3119 vm_exit_during_initialization("Cannot specify " JAVA_BASE_NAME " more than once to --patch-module");
3120 } else {
3121 *patch_mod_javabase = true;
3122 }
3123 }
3124
3125 // Create GrowableArray lazily, only if --patch-module has been specified
3126 if (_patch_mod_prefix == NULL) {
3127 _patch_mod_prefix = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<ModulePatchPath*>(10, true);
3128 }
3129
3130 _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
3131 }
3132
3133 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3134 //
3135 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3136 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3137 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3138 // path is treated as the current directory.
3139 //
3140 // This causes problems with CDS, which requires that all directories specified in the classpath
3141 // must be empty. In most cases, applications do NOT want to load classes from the current
3142 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3143 // scripts compatible with CDS.
fix_appclasspath()3144 void Arguments::fix_appclasspath() {
3145 if (IgnoreEmptyClassPaths) {
3146 const char separator = *os::path_separator();
3147 const char* src = _java_class_path->value();
3148
3149 // skip over all the leading empty paths
3150 while (*src == separator) {
3151 src ++;
3152 }
3153
3154 char* copy = os::strdup_check_oom(src, mtArguments);
3155
3156 // trim all trailing empty paths
3157 for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3158 *tail = '\0';
3159 }
3160
3161 char from[3] = {separator, separator, '\0'};
3162 char to [2] = {separator, '\0'};
3163 while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3164 // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3165 // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3166 }
3167
3168 _java_class_path->set_writeable_value(copy);
3169 FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3170 }
3171 }
3172
finalize_vm_init_args(bool patch_mod_javabase)3173 jint Arguments::finalize_vm_init_args(bool patch_mod_javabase) {
3174 // check if the default lib/endorsed directory exists; if so, error
3175 char path[JVM_MAXPATHLEN];
3176 const char* fileSep = os::file_separator();
3177 jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3178
3179 DIR* dir = os::opendir(path);
3180 if (dir != NULL) {
3181 jio_fprintf(defaultStream::output_stream(),
3182 "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3183 "in modular form will be supported via the concept of upgradeable modules.\n");
3184 os::closedir(dir);
3185 return JNI_ERR;
3186 }
3187
3188 jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3189 dir = os::opendir(path);
3190 if (dir != NULL) {
3191 jio_fprintf(defaultStream::output_stream(),
3192 "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3193 "Use -classpath instead.\n.");
3194 os::closedir(dir);
3195 return JNI_ERR;
3196 }
3197
3198 // This must be done after all arguments have been processed
3199 // and the container support has been initialized since AggressiveHeap
3200 // relies on the amount of total memory available.
3201 if (AggressiveHeap) {
3202 jint result = set_aggressive_heap_flags();
3203 if (result != JNI_OK) {
3204 return result;
3205 }
3206 }
3207
3208 // This must be done after all arguments have been processed.
3209 // java_compiler() true means set to "NONE" or empty.
3210 if (java_compiler() && !xdebug_mode()) {
3211 // For backwards compatibility, we switch to interpreted mode if
3212 // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3213 // not specified.
3214 set_mode_flags(_int);
3215 }
3216
3217 // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3218 // but like -Xint, leave compilation thresholds unaffected.
3219 // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3220 if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3221 set_mode_flags(_int);
3222 }
3223
3224 // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3225 if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3226 FLAG_SET_ERGO(InitialTenuringThreshold, MaxTenuringThreshold);
3227 }
3228
3229 #if !COMPILER2_OR_JVMCI
3230 // Don't degrade server performance for footprint
3231 if (FLAG_IS_DEFAULT(UseLargePages) &&
3232 MaxHeapSize < LargePageHeapSizeThreshold) {
3233 // No need for large granularity pages w/small heaps.
3234 // Note that large pages are enabled/disabled for both the
3235 // Java heap and the code cache.
3236 FLAG_SET_DEFAULT(UseLargePages, false);
3237 }
3238
3239 UNSUPPORTED_OPTION(ProfileInterpreter);
3240 NOT_PRODUCT(UNSUPPORTED_OPTION(TraceProfileInterpreter));
3241 #endif
3242
3243
3244 #ifdef TIERED
3245 // Parse the CompilationMode flag
3246 if (!CompilationModeFlag::initialize()) {
3247 return JNI_ERR;
3248 }
3249 #else
3250 // Tiered compilation is undefined.
3251 UNSUPPORTED_OPTION(TieredCompilation);
3252 #endif
3253
3254 if (!check_vm_args_consistency()) {
3255 return JNI_ERR;
3256 }
3257
3258 #if INCLUDE_CDS
3259 if (DumpSharedSpaces) {
3260 // Disable biased locking now as it interferes with the clean up of
3261 // the archived Klasses and Java string objects (at dump time only).
3262 UseBiasedLocking = false;
3263
3264 // Compiler threads may concurrently update the class metadata (such as method entries), so it's
3265 // unsafe with DumpSharedSpaces (which modifies the class metadata in place). Let's disable
3266 // compiler just to be safe.
3267 //
3268 // Note: this is not a concern for DynamicDumpSharedSpaces, which makes a copy of the class metadata
3269 // instead of modifying them in place. The copy is inaccessible to the compiler.
3270 // TODO: revisit the following for the static archive case.
3271 set_mode_flags(_int);
3272 }
3273 if (DumpSharedSpaces || ArchiveClassesAtExit != NULL) {
3274 // Always verify non-system classes during CDS dump
3275 if (!BytecodeVerificationRemote) {
3276 BytecodeVerificationRemote = true;
3277 log_info(cds)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");
3278 }
3279 }
3280 if (ArchiveClassesAtExit == NULL) {
3281 FLAG_SET_DEFAULT(DynamicDumpSharedSpaces, false);
3282 }
3283 if (UseSharedSpaces && patch_mod_javabase) {
3284 no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
3285 }
3286 if (UseSharedSpaces && !DumpSharedSpaces && check_unsupported_cds_runtime_properties()) {
3287 FLAG_SET_DEFAULT(UseSharedSpaces, false);
3288 }
3289 #endif
3290
3291 #ifndef CAN_SHOW_REGISTERS_ON_ASSERT
3292 UNSUPPORTED_OPTION(ShowRegistersOnAssert);
3293 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
3294
3295 return JNI_OK;
3296 }
3297
3298 // Helper class for controlling the lifetime of JavaVMInitArgs
3299 // objects. The contents of the JavaVMInitArgs are guaranteed to be
3300 // deleted on the destruction of the ScopedVMInitArgs object.
3301 class ScopedVMInitArgs : public StackObj {
3302 private:
3303 JavaVMInitArgs _args;
3304 char* _container_name;
3305 bool _is_set;
3306 char* _vm_options_file_arg;
3307
3308 public:
ScopedVMInitArgs(const char * container_name)3309 ScopedVMInitArgs(const char *container_name) {
3310 _args.version = JNI_VERSION_1_2;
3311 _args.nOptions = 0;
3312 _args.options = NULL;
3313 _args.ignoreUnrecognized = false;
3314 _container_name = (char *)container_name;
3315 _is_set = false;
3316 _vm_options_file_arg = NULL;
3317 }
3318
3319 // Populates the JavaVMInitArgs object represented by this
3320 // ScopedVMInitArgs object with the arguments in options. The
3321 // allocated memory is deleted by the destructor. If this method
3322 // returns anything other than JNI_OK, then this object is in a
3323 // partially constructed state, and should be abandoned.
set_args(GrowableArray<JavaVMOption> * options)3324 jint set_args(GrowableArray<JavaVMOption>* options) {
3325 _is_set = true;
3326 JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3327 JavaVMOption, options->length(), mtArguments);
3328 if (options_arr == NULL) {
3329 return JNI_ENOMEM;
3330 }
3331 _args.options = options_arr;
3332
3333 for (int i = 0; i < options->length(); i++) {
3334 options_arr[i] = options->at(i);
3335 options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3336 if (options_arr[i].optionString == NULL) {
3337 // Rely on the destructor to do cleanup.
3338 _args.nOptions = i;
3339 return JNI_ENOMEM;
3340 }
3341 }
3342
3343 _args.nOptions = options->length();
3344 _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3345 return JNI_OK;
3346 }
3347
get()3348 JavaVMInitArgs* get() { return &_args; }
container_name()3349 char* container_name() { return _container_name; }
is_set()3350 bool is_set() { return _is_set; }
found_vm_options_file_arg()3351 bool found_vm_options_file_arg() { return _vm_options_file_arg != NULL; }
vm_options_file_arg()3352 char* vm_options_file_arg() { return _vm_options_file_arg; }
3353
set_vm_options_file_arg(const char * vm_options_file_arg)3354 void set_vm_options_file_arg(const char *vm_options_file_arg) {
3355 if (_vm_options_file_arg != NULL) {
3356 os::free(_vm_options_file_arg);
3357 }
3358 _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3359 }
3360
~ScopedVMInitArgs()3361 ~ScopedVMInitArgs() {
3362 if (_vm_options_file_arg != NULL) {
3363 os::free(_vm_options_file_arg);
3364 }
3365 if (_args.options == NULL) return;
3366 for (int i = 0; i < _args.nOptions; i++) {
3367 os::free(_args.options[i].optionString);
3368 }
3369 FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3370 }
3371
3372 // Insert options into this option list, to replace option at
3373 // vm_options_file_pos (-XX:VMOptionsFile)
insert(const JavaVMInitArgs * args,const JavaVMInitArgs * args_to_insert,const int vm_options_file_pos)3374 jint insert(const JavaVMInitArgs* args,
3375 const JavaVMInitArgs* args_to_insert,
3376 const int vm_options_file_pos) {
3377 assert(_args.options == NULL, "shouldn't be set yet");
3378 assert(args_to_insert->nOptions != 0, "there should be args to insert");
3379 assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3380
3381 int length = args->nOptions + args_to_insert->nOptions - 1;
3382 GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments)
3383 GrowableArray<JavaVMOption>(length, true); // Construct new option array
3384 for (int i = 0; i < args->nOptions; i++) {
3385 if (i == vm_options_file_pos) {
3386 // insert the new options starting at the same place as the
3387 // -XX:VMOptionsFile option
3388 for (int j = 0; j < args_to_insert->nOptions; j++) {
3389 options->push(args_to_insert->options[j]);
3390 }
3391 } else {
3392 options->push(args->options[i]);
3393 }
3394 }
3395 // make into options array
3396 jint result = set_args(options);
3397 delete options;
3398 return result;
3399 }
3400 };
3401
parse_java_options_environment_variable(ScopedVMInitArgs * args)3402 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3403 return parse_options_environment_variable("_JAVA_OPTIONS", args);
3404 }
3405
parse_java_tool_options_environment_variable(ScopedVMInitArgs * args)3406 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3407 return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3408 }
3409
parse_options_environment_variable(const char * name,ScopedVMInitArgs * vm_args)3410 jint Arguments::parse_options_environment_variable(const char* name,
3411 ScopedVMInitArgs* vm_args) {
3412 char *buffer = ::getenv(name);
3413
3414 // Don't check this environment variable if user has special privileges
3415 // (e.g. unix su command).
3416 if (buffer == NULL || os::have_special_privileges()) {
3417 return JNI_OK;
3418 }
3419
3420 if ((buffer = os::strdup(buffer)) == NULL) {
3421 return JNI_ENOMEM;
3422 }
3423
3424 jio_fprintf(defaultStream::error_stream(),
3425 "Picked up %s: %s\n", name, buffer);
3426
3427 int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3428
3429 os::free(buffer);
3430 return retcode;
3431 }
3432
parse_vm_options_file(const char * file_name,ScopedVMInitArgs * vm_args)3433 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3434 // read file into buffer
3435 int fd = ::open(file_name, O_RDONLY);
3436 if (fd < 0) {
3437 jio_fprintf(defaultStream::error_stream(),
3438 "Could not open options file '%s'\n",
3439 file_name);
3440 return JNI_ERR;
3441 }
3442
3443 struct stat stbuf;
3444 int retcode = os::stat(file_name, &stbuf);
3445 if (retcode != 0) {
3446 jio_fprintf(defaultStream::error_stream(),
3447 "Could not stat options file '%s'\n",
3448 file_name);
3449 os::close(fd);
3450 return JNI_ERR;
3451 }
3452
3453 if (stbuf.st_size == 0) {
3454 // tell caller there is no option data and that is ok
3455 os::close(fd);
3456 return JNI_OK;
3457 }
3458
3459 // '+ 1' for NULL termination even with max bytes
3460 size_t bytes_alloc = stbuf.st_size + 1;
3461
3462 char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3463 if (NULL == buf) {
3464 jio_fprintf(defaultStream::error_stream(),
3465 "Could not allocate read buffer for options file parse\n");
3466 os::close(fd);
3467 return JNI_ENOMEM;
3468 }
3469
3470 memset(buf, 0, bytes_alloc);
3471
3472 // Fill buffer
3473 ssize_t bytes_read = os::read(fd, (void *)buf, (unsigned)bytes_alloc);
3474 os::close(fd);
3475 if (bytes_read < 0) {
3476 FREE_C_HEAP_ARRAY(char, buf);
3477 jio_fprintf(defaultStream::error_stream(),
3478 "Could not read options file '%s'\n", file_name);
3479 return JNI_ERR;
3480 }
3481
3482 if (bytes_read == 0) {
3483 // tell caller there is no option data and that is ok
3484 FREE_C_HEAP_ARRAY(char, buf);
3485 return JNI_OK;
3486 }
3487
3488 retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3489
3490 FREE_C_HEAP_ARRAY(char, buf);
3491 return retcode;
3492 }
3493
parse_options_buffer(const char * name,char * buffer,const size_t buf_len,ScopedVMInitArgs * vm_args)3494 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3495 GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<JavaVMOption>(2, true); // Construct option array
3496
3497 // some pointers to help with parsing
3498 char *buffer_end = buffer + buf_len;
3499 char *opt_hd = buffer;
3500 char *wrt = buffer;
3501 char *rd = buffer;
3502
3503 // parse all options
3504 while (rd < buffer_end) {
3505 // skip leading white space from the input string
3506 while (rd < buffer_end && isspace(*rd)) {
3507 rd++;
3508 }
3509
3510 if (rd >= buffer_end) {
3511 break;
3512 }
3513
3514 // Remember this is where we found the head of the token.
3515 opt_hd = wrt;
3516
3517 // Tokens are strings of non white space characters separated
3518 // by one or more white spaces.
3519 while (rd < buffer_end && !isspace(*rd)) {
3520 if (*rd == '\'' || *rd == '"') { // handle a quoted string
3521 int quote = *rd; // matching quote to look for
3522 rd++; // don't copy open quote
3523 while (rd < buffer_end && *rd != quote) {
3524 // include everything (even spaces)
3525 // up until the close quote
3526 *wrt++ = *rd++; // copy to option string
3527 }
3528
3529 if (rd < buffer_end) {
3530 rd++; // don't copy close quote
3531 } else {
3532 // did not see closing quote
3533 jio_fprintf(defaultStream::error_stream(),
3534 "Unmatched quote in %s\n", name);
3535 delete options;
3536 return JNI_ERR;
3537 }
3538 } else {
3539 *wrt++ = *rd++; // copy to option string
3540 }
3541 }
3542
3543 // steal a white space character and set it to NULL
3544 *wrt++ = '\0';
3545 // We now have a complete token
3546
3547 JavaVMOption option;
3548 option.optionString = opt_hd;
3549 option.extraInfo = NULL;
3550
3551 options->append(option); // Fill in option
3552
3553 rd++; // Advance to next character
3554 }
3555
3556 // Fill out JavaVMInitArgs structure.
3557 jint status = vm_args->set_args(options);
3558
3559 delete options;
3560 return status;
3561 }
3562
set_shared_spaces_flags_and_archive_paths()3563 jint Arguments::set_shared_spaces_flags_and_archive_paths() {
3564 if (DumpSharedSpaces) {
3565 if (RequireSharedSpaces) {
3566 warning("Cannot dump shared archive while using shared archive");
3567 }
3568 UseSharedSpaces = false;
3569 }
3570 #if INCLUDE_CDS
3571 // Initialize shared archive paths which could include both base and dynamic archive paths
3572 // This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.
3573 if (!init_shared_archive_paths()) {
3574 return JNI_ENOMEM;
3575 }
3576 #endif // INCLUDE_CDS
3577 return JNI_OK;
3578 }
3579
3580 #if INCLUDE_CDS
3581 // Sharing support
3582 // Construct the path to the archive
get_default_shared_archive_path()3583 char* Arguments::get_default_shared_archive_path() {
3584 char *default_archive_path;
3585 char jvm_path[JVM_MAXPATHLEN];
3586 os::jvm_path(jvm_path, sizeof(jvm_path));
3587 char *end = strrchr(jvm_path, *os::file_separator());
3588 if (end != NULL) *end = '\0';
3589 size_t jvm_path_len = strlen(jvm_path);
3590 size_t file_sep_len = strlen(os::file_separator());
3591 const size_t len = jvm_path_len + file_sep_len + 20;
3592 default_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);
3593 jio_snprintf(default_archive_path, len,
3594 UseCompressedOops ? "%s%sclasses.jsa": "%s%sclasses_nocoops.jsa",
3595 jvm_path, os::file_separator());
3596 return default_archive_path;
3597 }
3598
num_archives(const char * archive_path)3599 int Arguments::num_archives(const char* archive_path) {
3600 if (archive_path == NULL) {
3601 return 0;
3602 }
3603 int npaths = 1;
3604 char* p = (char*)archive_path;
3605 while (*p != '\0') {
3606 if (*p == os::path_separator()[0]) {
3607 npaths++;
3608 }
3609 p++;
3610 }
3611 return npaths;
3612 }
3613
extract_shared_archive_paths(const char * archive_path,char ** base_archive_path,char ** top_archive_path)3614 void Arguments::extract_shared_archive_paths(const char* archive_path,
3615 char** base_archive_path,
3616 char** top_archive_path) {
3617 char* begin_ptr = (char*)archive_path;
3618 char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);
3619 if (end_ptr == NULL || end_ptr == begin_ptr) {
3620 vm_exit_during_initialization("Base archive was not specified", archive_path);
3621 }
3622 size_t len = end_ptr - begin_ptr;
3623 char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
3624 strncpy(cur_path, begin_ptr, len);
3625 cur_path[len] = '\0';
3626 FileMapInfo::check_archive((const char*)cur_path, true /*is_static*/);
3627 *base_archive_path = cur_path;
3628
3629 begin_ptr = ++end_ptr;
3630 if (*begin_ptr == '\0') {
3631 vm_exit_during_initialization("Top archive was not specified", archive_path);
3632 }
3633 end_ptr = strchr(begin_ptr, '\0');
3634 assert(end_ptr != NULL, "sanity");
3635 len = end_ptr - begin_ptr;
3636 cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
3637 strncpy(cur_path, begin_ptr, len + 1);
3638 //cur_path[len] = '\0';
3639 FileMapInfo::check_archive((const char*)cur_path, false /*is_static*/);
3640 *top_archive_path = cur_path;
3641 }
3642
init_shared_archive_paths()3643 bool Arguments::init_shared_archive_paths() {
3644 if (ArchiveClassesAtExit != NULL) {
3645 if (DumpSharedSpaces) {
3646 vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");
3647 }
3648 if (FLAG_SET_CMDLINE(DynamicDumpSharedSpaces, true) != JVMFlag::SUCCESS) {
3649 return false;
3650 }
3651 check_unsupported_dumping_properties();
3652 SharedDynamicArchivePath = os::strdup_check_oom(ArchiveClassesAtExit, mtArguments);
3653 }
3654 if (SharedArchiveFile == NULL) {
3655 SharedArchivePath = get_default_shared_archive_path();
3656 } else {
3657 int archives = num_archives(SharedArchiveFile);
3658 if (is_dumping_archive()) {
3659 if (archives > 1) {
3660 vm_exit_during_initialization(
3661 "Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");
3662 }
3663 if (DynamicDumpSharedSpaces) {
3664 if (os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {
3665 vm_exit_during_initialization(
3666 "Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",
3667 SharedArchiveFile);
3668 }
3669 }
3670 }
3671 if (!is_dumping_archive()){
3672 if (archives > 2) {
3673 vm_exit_during_initialization(
3674 "Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");
3675 }
3676 if (archives == 1) {
3677 char* temp_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);
3678 int name_size;
3679 bool success =
3680 FileMapInfo::get_base_archive_name_from_header(temp_archive_path, &name_size, &SharedArchivePath);
3681 if (!success) {
3682 SharedArchivePath = temp_archive_path;
3683 } else {
3684 SharedDynamicArchivePath = temp_archive_path;
3685 }
3686 } else {
3687 extract_shared_archive_paths((const char*)SharedArchiveFile,
3688 &SharedArchivePath, &SharedDynamicArchivePath);
3689 }
3690 } else { // CDS dumping
3691 SharedArchivePath = os::strdup_check_oom(SharedArchiveFile, mtArguments);
3692 }
3693 }
3694 return (SharedArchivePath != NULL);
3695 }
3696 #endif // INCLUDE_CDS
3697
3698 #ifndef PRODUCT
3699 // Determine whether LogVMOutput should be implicitly turned on.
use_vm_log()3700 static bool use_vm_log() {
3701 if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3702 PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3703 PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3704 PrintAssembly || TraceDeoptimization || TraceDependencies ||
3705 (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3706 return true;
3707 }
3708
3709 #ifdef COMPILER1
3710 if (PrintC1Statistics) {
3711 return true;
3712 }
3713 #endif // COMPILER1
3714
3715 #ifdef COMPILER2
3716 if (PrintOptoAssembly || PrintOptoStatistics) {
3717 return true;
3718 }
3719 #endif // COMPILER2
3720
3721 return false;
3722 }
3723
3724 #endif // PRODUCT
3725
args_contains_vm_options_file_arg(const JavaVMInitArgs * args)3726 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3727 for (int index = 0; index < args->nOptions; index++) {
3728 const JavaVMOption* option = args->options + index;
3729 const char* tail;
3730 if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3731 return true;
3732 }
3733 }
3734 return false;
3735 }
3736
insert_vm_options_file(const JavaVMInitArgs * args,const char * vm_options_file,const int vm_options_file_pos,ScopedVMInitArgs * vm_options_file_args,ScopedVMInitArgs * args_out)3737 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3738 const char* vm_options_file,
3739 const int vm_options_file_pos,
3740 ScopedVMInitArgs* vm_options_file_args,
3741 ScopedVMInitArgs* args_out) {
3742 jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
3743 if (code != JNI_OK) {
3744 return code;
3745 }
3746
3747 if (vm_options_file_args->get()->nOptions < 1) {
3748 return JNI_OK;
3749 }
3750
3751 if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
3752 jio_fprintf(defaultStream::error_stream(),
3753 "A VM options file may not refer to a VM options file. "
3754 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
3755 "options file '%s' in options container '%s' is an error.\n",
3756 vm_options_file_args->vm_options_file_arg(),
3757 vm_options_file_args->container_name());
3758 return JNI_EINVAL;
3759 }
3760
3761 return args_out->insert(args, vm_options_file_args->get(),
3762 vm_options_file_pos);
3763 }
3764
3765 // Expand -XX:VMOptionsFile found in args_in as needed.
3766 // mod_args and args_out parameters may return values as needed.
expand_vm_options_as_needed(const JavaVMInitArgs * args_in,ScopedVMInitArgs * mod_args,JavaVMInitArgs ** args_out)3767 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
3768 ScopedVMInitArgs* mod_args,
3769 JavaVMInitArgs** args_out) {
3770 jint code = match_special_option_and_act(args_in, mod_args);
3771 if (code != JNI_OK) {
3772 return code;
3773 }
3774
3775 if (mod_args->is_set()) {
3776 // args_in contains -XX:VMOptionsFile and mod_args contains the
3777 // original options from args_in along with the options expanded
3778 // from the VMOptionsFile. Return a short-hand to the caller.
3779 *args_out = mod_args->get();
3780 } else {
3781 *args_out = (JavaVMInitArgs *)args_in; // no changes so use args_in
3782 }
3783 return JNI_OK;
3784 }
3785
match_special_option_and_act(const JavaVMInitArgs * args,ScopedVMInitArgs * args_out)3786 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3787 ScopedVMInitArgs* args_out) {
3788 // Remaining part of option string
3789 const char* tail;
3790 ScopedVMInitArgs vm_options_file_args(args_out->container_name());
3791
3792 for (int index = 0; index < args->nOptions; index++) {
3793 const JavaVMOption* option = args->options + index;
3794 if (match_option(option, "-XX:Flags=", &tail)) {
3795 Arguments::set_jvm_flags_file(tail);
3796 continue;
3797 }
3798 if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3799 if (vm_options_file_args.found_vm_options_file_arg()) {
3800 jio_fprintf(defaultStream::error_stream(),
3801 "The option '%s' is already specified in the options "
3802 "container '%s' so the specification of '%s' in the "
3803 "same options container is an error.\n",
3804 vm_options_file_args.vm_options_file_arg(),
3805 vm_options_file_args.container_name(),
3806 option->optionString);
3807 return JNI_EINVAL;
3808 }
3809 vm_options_file_args.set_vm_options_file_arg(option->optionString);
3810 // If there's a VMOptionsFile, parse that
3811 jint code = insert_vm_options_file(args, tail, index,
3812 &vm_options_file_args, args_out);
3813 if (code != JNI_OK) {
3814 return code;
3815 }
3816 args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
3817 if (args_out->is_set()) {
3818 // The VMOptions file inserted some options so switch 'args'
3819 // to the new set of options, and continue processing which
3820 // preserves "last option wins" semantics.
3821 args = args_out->get();
3822 // The first option from the VMOptionsFile replaces the
3823 // current option. So we back track to process the
3824 // replacement option.
3825 index--;
3826 }
3827 continue;
3828 }
3829 if (match_option(option, "-XX:+PrintVMOptions")) {
3830 PrintVMOptions = true;
3831 continue;
3832 }
3833 if (match_option(option, "-XX:-PrintVMOptions")) {
3834 PrintVMOptions = false;
3835 continue;
3836 }
3837 if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3838 IgnoreUnrecognizedVMOptions = true;
3839 continue;
3840 }
3841 if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3842 IgnoreUnrecognizedVMOptions = false;
3843 continue;
3844 }
3845 if (match_option(option, "-XX:+PrintFlagsInitial")) {
3846 JVMFlag::printFlags(tty, false);
3847 vm_exit(0);
3848 }
3849 if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3850 #if INCLUDE_NMT
3851 // The launcher did not setup nmt environment variable properly.
3852 if (!MemTracker::check_launcher_nmt_support(tail)) {
3853 warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3854 }
3855
3856 // Verify if nmt option is valid.
3857 if (MemTracker::verify_nmt_option()) {
3858 // Late initialization, still in single-threaded mode.
3859 if (MemTracker::tracking_level() >= NMT_summary) {
3860 MemTracker::init();
3861 }
3862 } else {
3863 vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3864 }
3865 continue;
3866 #else
3867 jio_fprintf(defaultStream::error_stream(),
3868 "Native Memory Tracking is not supported in this VM\n");
3869 return JNI_ERR;
3870 #endif
3871 }
3872
3873 #ifndef PRODUCT
3874 if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3875 JVMFlag::printFlags(tty, true);
3876 vm_exit(0);
3877 }
3878 #endif
3879 }
3880 return JNI_OK;
3881 }
3882
print_options(const JavaVMInitArgs * args)3883 static void print_options(const JavaVMInitArgs *args) {
3884 const char* tail;
3885 for (int index = 0; index < args->nOptions; index++) {
3886 const JavaVMOption *option = args->options + index;
3887 if (match_option(option, "-XX:", &tail)) {
3888 logOption(tail);
3889 }
3890 }
3891 }
3892
handle_deprecated_print_gc_flags()3893 bool Arguments::handle_deprecated_print_gc_flags() {
3894 if (PrintGC) {
3895 log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
3896 }
3897 if (PrintGCDetails) {
3898 log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
3899 }
3900
3901 if (_gc_log_filename != NULL) {
3902 // -Xloggc was used to specify a filename
3903 const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
3904
3905 LogTarget(Error, logging) target;
3906 LogStream errstream(target);
3907 return LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, &errstream);
3908 } else if (PrintGC || PrintGCDetails) {
3909 LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
3910 }
3911 return true;
3912 }
3913
3914 // Parse entry point called from JNI_CreateJavaVM
3915
parse(const JavaVMInitArgs * initial_cmd_args)3916 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
3917 assert(verify_special_jvm_flags(false), "deprecated and obsolete flag table inconsistent");
3918
3919 // Initialize ranges and constraints
3920 JVMFlagRangeList::init();
3921 JVMFlagConstraintList::init();
3922
3923 // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3924 const char* hotspotrc = ".hotspotrc";
3925 bool settings_file_specified = false;
3926 bool needs_hotspotrc_warning = false;
3927 ScopedVMInitArgs initial_vm_options_args("");
3928 ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3929 ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
3930
3931 // Pointers to current working set of containers
3932 JavaVMInitArgs* cur_cmd_args;
3933 JavaVMInitArgs* cur_vm_options_args;
3934 JavaVMInitArgs* cur_java_options_args;
3935 JavaVMInitArgs* cur_java_tool_options_args;
3936
3937 // Containers for modified/expanded options
3938 ScopedVMInitArgs mod_cmd_args("cmd_line_args");
3939 ScopedVMInitArgs mod_vm_options_args("vm_options_args");
3940 ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3941 ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
3942
3943
3944 jint code =
3945 parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
3946 if (code != JNI_OK) {
3947 return code;
3948 }
3949
3950 code = parse_java_options_environment_variable(&initial_java_options_args);
3951 if (code != JNI_OK) {
3952 return code;
3953 }
3954
3955 // Parse the options in the /java.base/jdk/internal/vm/options resource, if present
3956 char *vmoptions = ClassLoader::lookup_vm_options();
3957 if (vmoptions != NULL) {
3958 code = parse_options_buffer("vm options resource", vmoptions, strlen(vmoptions), &initial_vm_options_args);
3959 FREE_C_HEAP_ARRAY(char, vmoptions);
3960 if (code != JNI_OK) {
3961 return code;
3962 }
3963 }
3964
3965 code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
3966 &mod_java_tool_options_args,
3967 &cur_java_tool_options_args);
3968 if (code != JNI_OK) {
3969 return code;
3970 }
3971
3972 code = expand_vm_options_as_needed(initial_cmd_args,
3973 &mod_cmd_args,
3974 &cur_cmd_args);
3975 if (code != JNI_OK) {
3976 return code;
3977 }
3978
3979 code = expand_vm_options_as_needed(initial_java_options_args.get(),
3980 &mod_java_options_args,
3981 &cur_java_options_args);
3982 if (code != JNI_OK) {
3983 return code;
3984 }
3985
3986 code = expand_vm_options_as_needed(initial_vm_options_args.get(),
3987 &mod_vm_options_args,
3988 &cur_vm_options_args);
3989 if (code != JNI_OK) {
3990 return code;
3991 }
3992
3993 const char* flags_file = Arguments::get_jvm_flags_file();
3994 settings_file_specified = (flags_file != NULL);
3995
3996 if (IgnoreUnrecognizedVMOptions) {
3997 cur_cmd_args->ignoreUnrecognized = true;
3998 cur_java_tool_options_args->ignoreUnrecognized = true;
3999 cur_java_options_args->ignoreUnrecognized = true;
4000 }
4001
4002 // Parse specified settings file
4003 if (settings_file_specified) {
4004 if (!process_settings_file(flags_file, true,
4005 cur_cmd_args->ignoreUnrecognized)) {
4006 return JNI_EINVAL;
4007 }
4008 } else {
4009 #ifdef ASSERT
4010 // Parse default .hotspotrc settings file
4011 if (!process_settings_file(".hotspotrc", false,
4012 cur_cmd_args->ignoreUnrecognized)) {
4013 return JNI_EINVAL;
4014 }
4015 #else
4016 struct stat buf;
4017 if (os::stat(hotspotrc, &buf) == 0) {
4018 needs_hotspotrc_warning = true;
4019 }
4020 #endif
4021 }
4022
4023 if (PrintVMOptions) {
4024 print_options(cur_java_tool_options_args);
4025 print_options(cur_cmd_args);
4026 print_options(cur_java_options_args);
4027 }
4028
4029 // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
4030 jint result = parse_vm_init_args(cur_vm_options_args,
4031 cur_java_tool_options_args,
4032 cur_java_options_args,
4033 cur_cmd_args);
4034
4035 if (result != JNI_OK) {
4036 return result;
4037 }
4038
4039 // Delay warning until here so that we've had a chance to process
4040 // the -XX:-PrintWarnings flag
4041 if (needs_hotspotrc_warning) {
4042 warning("%s file is present but has been ignored. "
4043 "Run with -XX:Flags=%s to load the file.",
4044 hotspotrc, hotspotrc);
4045 }
4046
4047 if (needs_module_property_warning) {
4048 warning("Ignoring system property options whose names match the '-Djdk.module.*'."
4049 " names that are reserved for internal use.");
4050 }
4051
4052 #if defined(_ALLBSD_SOURCE) || defined(AIX) // UseLargePages is not yet supported on BSD and AIX.
4053 UNSUPPORTED_OPTION(UseLargePages);
4054 #endif
4055
4056 #if defined(AIX)
4057 UNSUPPORTED_OPTION_NULL(AllocateHeapAt);
4058 UNSUPPORTED_OPTION_NULL(AllocateOldGenAt);
4059 #endif
4060
4061 #ifndef PRODUCT
4062 if (TraceBytecodesAt != 0) {
4063 TraceBytecodes = true;
4064 }
4065 if (CountCompiledCalls) {
4066 if (UseCounterDecay) {
4067 warning("UseCounterDecay disabled because CountCalls is set");
4068 UseCounterDecay = false;
4069 }
4070 }
4071 #endif // PRODUCT
4072
4073 if (ScavengeRootsInCode == 0) {
4074 if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4075 warning("Forcing ScavengeRootsInCode non-zero");
4076 }
4077 ScavengeRootsInCode = 1;
4078 }
4079
4080 if (!handle_deprecated_print_gc_flags()) {
4081 return JNI_EINVAL;
4082 }
4083
4084 // Set object alignment values.
4085 set_object_alignment();
4086
4087 #if !INCLUDE_CDS
4088 if (DumpSharedSpaces || RequireSharedSpaces) {
4089 jio_fprintf(defaultStream::error_stream(),
4090 "Shared spaces are not supported in this VM\n");
4091 return JNI_ERR;
4092 }
4093 if (DumpLoadedClassList != NULL) {
4094 jio_fprintf(defaultStream::error_stream(),
4095 "DumpLoadedClassList is not supported in this VM\n");
4096 return JNI_ERR;
4097 }
4098 if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) ||
4099 log_is_enabled(Info, cds)) {
4100 warning("Shared spaces are not supported in this VM");
4101 FLAG_SET_DEFAULT(UseSharedSpaces, false);
4102 LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(cds));
4103 }
4104 no_shared_spaces("CDS Disabled");
4105 #endif // INCLUDE_CDS
4106
4107 #ifndef TIERED
4108 if (FLAG_IS_CMDLINE(CompilationMode)) {
4109 warning("CompilationMode has no effect in non-tiered VMs");
4110 }
4111 #endif
4112
4113 return JNI_OK;
4114 }
4115
apply_ergo()4116 jint Arguments::apply_ergo() {
4117 // Set flags based on ergonomics.
4118 jint result = set_ergonomics_flags();
4119 if (result != JNI_OK) return result;
4120
4121 // Set heap size based on available physical memory
4122 set_heap_size();
4123
4124 GCConfig::arguments()->initialize();
4125
4126 result = set_shared_spaces_flags_and_archive_paths();
4127 if (result != JNI_OK) return result;
4128
4129 // Initialize Metaspace flags and alignments
4130 Metaspace::ergo_initialize();
4131
4132 // Set compiler flags after GC is selected and GC specific
4133 // flags (LoopStripMiningIter) are set.
4134 CompilerConfig::ergo_initialize();
4135
4136 // Set bytecode rewriting flags
4137 set_bytecode_flags();
4138
4139 // Set flags if aggressive optimization flags are enabled
4140 jint code = set_aggressive_opts_flags();
4141 if (code != JNI_OK) {
4142 return code;
4143 }
4144
4145 // Turn off biased locking for locking debug mode flags,
4146 // which are subtly different from each other but neither works with
4147 // biased locking
4148 if (UseHeavyMonitors
4149 #ifdef COMPILER1
4150 || !UseFastLocking
4151 #endif // COMPILER1
4152 #if INCLUDE_JVMCI
4153 || !JVMCIUseFastLocking
4154 #endif
4155 ) {
4156 if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4157 // flag set to true on command line; warn the user that they
4158 // can't enable biased locking here
4159 warning("Biased Locking is not supported with locking debug flags"
4160 "; ignoring UseBiasedLocking flag." );
4161 }
4162 UseBiasedLocking = false;
4163 }
4164
4165 #ifdef CC_INTERP
4166 // Clear flags not supported on zero.
4167 FLAG_SET_DEFAULT(ProfileInterpreter, false);
4168 FLAG_SET_DEFAULT(UseBiasedLocking, false);
4169 LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4170 LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4171 #endif // CC_INTERP
4172
4173 if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4174 warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4175 DebugNonSafepoints = true;
4176 }
4177
4178 if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4179 warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4180 }
4181
4182 // Treat the odd case where local verification is enabled but remote
4183 // verification is not as if both were enabled.
4184 if (BytecodeVerificationLocal && !BytecodeVerificationRemote) {
4185 log_info(verification)("Turning on remote verification because local verification is on");
4186 FLAG_SET_DEFAULT(BytecodeVerificationRemote, true);
4187 }
4188
4189 #ifndef PRODUCT
4190 if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4191 if (use_vm_log()) {
4192 LogVMOutput = true;
4193 }
4194 }
4195 #endif // PRODUCT
4196
4197 if (PrintCommandLineFlags) {
4198 JVMFlag::printSetFlags(tty);
4199 }
4200
4201 // Apply CPU specific policy for the BiasedLocking
4202 if (UseBiasedLocking) {
4203 if (!VM_Version::use_biased_locking() &&
4204 !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4205 UseBiasedLocking = false;
4206 }
4207 }
4208 #ifdef COMPILER2
4209 if (!UseBiasedLocking) {
4210 UseOptoBiasInlining = false;
4211 }
4212 #endif
4213
4214 return JNI_OK;
4215 }
4216
adjust_after_os()4217 jint Arguments::adjust_after_os() {
4218 if (UseNUMA) {
4219 if (UseParallelGC) {
4220 if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4221 FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4222 }
4223 }
4224 }
4225 return JNI_OK;
4226 }
4227
PropertyList_count(SystemProperty * pl)4228 int Arguments::PropertyList_count(SystemProperty* pl) {
4229 int count = 0;
4230 while(pl != NULL) {
4231 count++;
4232 pl = pl->next();
4233 }
4234 return count;
4235 }
4236
4237 // Return the number of readable properties.
PropertyList_readable_count(SystemProperty * pl)4238 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
4239 int count = 0;
4240 while(pl != NULL) {
4241 if (pl->is_readable()) {
4242 count++;
4243 }
4244 pl = pl->next();
4245 }
4246 return count;
4247 }
4248
PropertyList_get_value(SystemProperty * pl,const char * key)4249 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4250 assert(key != NULL, "just checking");
4251 SystemProperty* prop;
4252 for (prop = pl; prop != NULL; prop = prop->next()) {
4253 if (strcmp(key, prop->key()) == 0) return prop->value();
4254 }
4255 return NULL;
4256 }
4257
4258 // Return the value of the requested property provided that it is a readable property.
PropertyList_get_readable_value(SystemProperty * pl,const char * key)4259 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4260 assert(key != NULL, "just checking");
4261 SystemProperty* prop;
4262 // Return the property value if the keys match and the property is not internal or
4263 // it's the special internal property "jdk.boot.class.path.append".
4264 for (prop = pl; prop != NULL; prop = prop->next()) {
4265 if (strcmp(key, prop->key()) == 0) {
4266 if (!prop->internal()) {
4267 return prop->value();
4268 } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4269 return prop->value();
4270 } else {
4271 // Property is internal and not jdk.boot.class.path.append so return NULL.
4272 return NULL;
4273 }
4274 }
4275 }
4276 return NULL;
4277 }
4278
PropertyList_get_key_at(SystemProperty * pl,int index)4279 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4280 int count = 0;
4281 const char* ret_val = NULL;
4282
4283 while(pl != NULL) {
4284 if(count >= index) {
4285 ret_val = pl->key();
4286 break;
4287 }
4288 count++;
4289 pl = pl->next();
4290 }
4291
4292 return ret_val;
4293 }
4294
PropertyList_get_value_at(SystemProperty * pl,int index)4295 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4296 int count = 0;
4297 char* ret_val = NULL;
4298
4299 while(pl != NULL) {
4300 if(count >= index) {
4301 ret_val = pl->value();
4302 break;
4303 }
4304 count++;
4305 pl = pl->next();
4306 }
4307
4308 return ret_val;
4309 }
4310
PropertyList_add(SystemProperty ** plist,SystemProperty * new_p)4311 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4312 SystemProperty* p = *plist;
4313 if (p == NULL) {
4314 *plist = new_p;
4315 } else {
4316 while (p->next() != NULL) {
4317 p = p->next();
4318 }
4319 p->set_next(new_p);
4320 }
4321 }
4322
PropertyList_add(SystemProperty ** plist,const char * k,const char * v,bool writeable,bool internal)4323 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4324 bool writeable, bool internal) {
4325 if (plist == NULL)
4326 return;
4327
4328 SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4329 PropertyList_add(plist, new_p);
4330 }
4331
PropertyList_add(SystemProperty * element)4332 void Arguments::PropertyList_add(SystemProperty *element) {
4333 PropertyList_add(&_system_properties, element);
4334 }
4335
4336 // This add maintains unique property key in the list.
PropertyList_unique_add(SystemProperty ** plist,const char * k,const char * v,PropertyAppendable append,PropertyWriteable writeable,PropertyInternal internal)4337 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4338 PropertyAppendable append, PropertyWriteable writeable,
4339 PropertyInternal internal) {
4340 if (plist == NULL)
4341 return;
4342
4343 // If property key exists and is writeable, then update with new value.
4344 // Trying to update a non-writeable property is silently ignored.
4345 SystemProperty* prop;
4346 for (prop = *plist; prop != NULL; prop = prop->next()) {
4347 if (strcmp(k, prop->key()) == 0) {
4348 if (append == AppendProperty) {
4349 prop->append_writeable_value(v);
4350 } else {
4351 prop->set_writeable_value(v);
4352 }
4353 return;
4354 }
4355 }
4356
4357 PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4358 }
4359
4360 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4361 // Returns true if all of the source pointed by src has been copied over to
4362 // the destination buffer pointed by buf. Otherwise, returns false.
4363 // Notes:
4364 // 1. If the length (buflen) of the destination buffer excluding the
4365 // NULL terminator character is not long enough for holding the expanded
4366 // pid characters, it also returns false instead of returning the partially
4367 // expanded one.
4368 // 2. The passed in "buflen" should be large enough to hold the null terminator.
copy_expand_pid(const char * src,size_t srclen,char * buf,size_t buflen)4369 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4370 char* buf, size_t buflen) {
4371 const char* p = src;
4372 char* b = buf;
4373 const char* src_end = &src[srclen];
4374 char* buf_end = &buf[buflen - 1];
4375
4376 while (p < src_end && b < buf_end) {
4377 if (*p == '%') {
4378 switch (*(++p)) {
4379 case '%': // "%%" ==> "%"
4380 *b++ = *p++;
4381 break;
4382 case 'p': { // "%p" ==> current process id
4383 // buf_end points to the character before the last character so
4384 // that we could write '\0' to the end of the buffer.
4385 size_t buf_sz = buf_end - b + 1;
4386 int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4387
4388 // if jio_snprintf fails or the buffer is not long enough to hold
4389 // the expanded pid, returns false.
4390 if (ret < 0 || ret >= (int)buf_sz) {
4391 return false;
4392 } else {
4393 b += ret;
4394 assert(*b == '\0', "fail in copy_expand_pid");
4395 if (p == src_end && b == buf_end + 1) {
4396 // reach the end of the buffer.
4397 return true;
4398 }
4399 }
4400 p++;
4401 break;
4402 }
4403 default :
4404 *b++ = '%';
4405 }
4406 } else {
4407 *b++ = *p++;
4408 }
4409 }
4410 *b = '\0';
4411 return (p == src_end); // return false if not all of the source was copied
4412 }
4413