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