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