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