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