1 /*
2 * Copyright (c) 2023, 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/aotMapLogger.hpp"
27 #include "cds/archiveHeapLoader.hpp"
28 #include "cds/cdsConfig.hpp"
29 #include "cds/classListWriter.hpp"
30 #include "cds/filemap.hpp"
31 #include "cds/heapShared.hpp"
32 #include "classfile/classLoaderDataShared.hpp"
33 #include "classfile/moduleEntry.hpp"
34 #include "code/aotCodeCache.hpp"
35 #include "include/jvm_io.h"
36 #include "logging/log.hpp"
37 #include "memory/universe.hpp"
38 #include "prims/jvmtiAgentList.hpp"
39 #include "runtime/arguments.hpp"
40 #include "runtime/globals.hpp"
41 #include "runtime/globals_extension.hpp"
42 #include "runtime/java.hpp"
43 #include "runtime/vmThread.hpp"
44 #include "utilities/defaultStream.hpp"
45 #include "utilities/formatBuffer.hpp"
46
47 bool CDSConfig::_is_dumping_static_archive = false;
48 bool CDSConfig::_is_dumping_preimage_static_archive = false;
49 bool CDSConfig::_is_dumping_final_static_archive = false;
50 bool CDSConfig::_is_dumping_dynamic_archive = false;
51 bool CDSConfig::_is_using_optimized_module_handling = true;
52 bool CDSConfig::_is_dumping_full_module_graph = true;
53 bool CDSConfig::_is_using_full_module_graph = true;
54 bool CDSConfig::_has_aot_linked_classes = false;
55 bool CDSConfig::_is_single_command_training = false;
56 bool CDSConfig::_has_temp_aot_config_file = false;
57 bool CDSConfig::_old_cds_flags_used = false;
58 bool CDSConfig::_new_aot_flags_used = false;
59 bool CDSConfig::_disable_heap_dumping = false;
60 bool CDSConfig::_is_at_aot_safepoint = false;
61
62 bool CDSConfig::_module_patching_disables_cds = false;
63 bool CDSConfig::_java_base_module_patching_disables_cds = false;
64
65 const char* CDSConfig::_default_archive_path = nullptr;
66 const char* CDSConfig::_input_static_archive_path = nullptr;
67 const char* CDSConfig::_input_dynamic_archive_path = nullptr;
68 const char* CDSConfig::_output_archive_path = nullptr;
69
70 JavaThread* CDSConfig::_dumper_thread = nullptr;
71
72 int CDSConfig::get_status() {
73 assert(Universe::is_fully_initialized(), "status is finalized only after Universe is initialized");
74 return (is_dumping_aot_linked_classes() ? IS_DUMPING_AOT_LINKED_CLASSES : 0) |
75 (is_dumping_archive() ? IS_DUMPING_ARCHIVE : 0) |
76 (is_dumping_method_handles() ? IS_DUMPING_METHOD_HANDLES : 0) |
77 (is_dumping_static_archive() ? IS_DUMPING_STATIC_ARCHIVE : 0) |
78 (is_logging_lambda_form_invokers() ? IS_LOGGING_LAMBDA_FORM_INVOKERS : 0) |
79 (is_using_archive() ? IS_USING_ARCHIVE : 0);
80 }
81
82 DEBUG_ONLY(static bool _cds_ergo_initialize_started = false);
83
84 void CDSConfig::ergo_initialize() {
85 DEBUG_ONLY(_cds_ergo_initialize_started = true);
86
87 if (is_dumping_static_archive() && !is_dumping_final_static_archive()) {
88 // Note: -Xshare and -XX:AOTMode flags are mutually exclusive.
89 // - Classic workflow: -Xshare:on and -Xshare:dump cannot take effect at the same time.
90 // - JEP 483 workflow: -XX:AOTMode:record and -XX:AOTMode=on cannot take effect at the same time.
91 // So we can never come to here with RequireSharedSpaces==true.
92 assert(!RequireSharedSpaces, "sanity");
93
94 // If dumping the classic archive, or making an AOT training run (dumping a preimage archive),
95 // for sanity, parse all classes from classfiles.
96 // TODO: in the future, if we want to support re-training on top of an existing AOT cache, this
97 // needs to be changed.
98 UseSharedSpaces = false;
99 }
100
101 // Initialize shared archive paths which could include both base and dynamic archive paths
102 // This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.
103 if (is_dumping_static_archive() || is_using_archive()) {
104 if (new_aot_flags_used()) {
105 ergo_init_aot_paths();
106 } else {
107 ergo_init_classic_archive_paths();
108 }
109 }
110
111 if (!is_dumping_heap()) {
112 _is_dumping_full_module_graph = false;
113 }
114
115 AOTMapLogger::ergo_initialize();
116 }
117
118 const char* CDSConfig::default_archive_path() {
119 // The path depends on UseCompressedOops, etc, which are set by GC ergonomics just
120 // before CDSConfig::ergo_initialize() is called.
121 assert(_cds_ergo_initialize_started, "sanity");
122 if (_default_archive_path == nullptr) {
123 stringStream tmp;
124 if (is_vm_statically_linked()) {
125 // It's easier to form the path using JAVA_HOME as os::jvm_path
126 // gives the path to the launcher executable on static JDK.
127 const char* subdir = WINDOWS_ONLY("bin") NOT_WINDOWS("lib");
128 tmp.print("%s%s%s%s%s%sclasses",
129 Arguments::get_java_home(), os::file_separator(),
130 subdir, os::file_separator(),
131 Abstract_VM_Version::vm_variant(), os::file_separator());
132 } else {
133 // Assume .jsa is in the same directory where libjvm resides on
134 // non-static JDK.
135 char jvm_path[JVM_MAXPATHLEN];
136 os::jvm_path(jvm_path, sizeof(jvm_path));
137 char *end = strrchr(jvm_path, *os::file_separator());
138 if (end != nullptr) *end = '\0';
139 tmp.print("%s%sclasses", jvm_path, os::file_separator());
140 }
141 #ifdef _LP64
142 if (!UseCompressedOops) {
143 tmp.print_raw("_nocoops");
144 }
145 if (UseCompactObjectHeaders) {
146 // Note that generation of xxx_coh.jsa variants require
147 // --enable-cds-archive-coh at build time
148 tmp.print_raw("_coh");
149 }
150 #endif
151 if (is_valhalla_preview()) {
152 tmp.print_raw("_valhalla");
153 }
154 tmp.print_raw(".jsa");
155 _default_archive_path = os::strdup(tmp.base());
156 }
157 return _default_archive_path;
158 }
159
160 int CDSConfig::num_archive_paths(const char* path_spec) {
161 if (path_spec == nullptr) {
162 return 0;
163 }
164 int npaths = 1;
165 char* p = (char*)path_spec;
166 while (*p != '\0') {
167 if (*p == os::path_separator()[0]) {
168 npaths++;
169 }
170 p++;
171 }
172 return npaths;
173 }
174
175 void CDSConfig::extract_archive_paths(const char* archive_path,
176 const char** base_archive_path,
177 const char** top_archive_path) {
178 char* begin_ptr = (char*)archive_path;
179 char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);
180 if (end_ptr == nullptr || end_ptr == begin_ptr) {
181 vm_exit_during_initialization("Base archive was not specified", archive_path);
182 }
183 size_t len = end_ptr - begin_ptr;
184 char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
185 strncpy(cur_path, begin_ptr, len);
186 cur_path[len] = '\0';
187 *base_archive_path = cur_path;
188
189 begin_ptr = ++end_ptr;
190 if (*begin_ptr == '\0') {
191 vm_exit_during_initialization("Top archive was not specified", archive_path);
192 }
193 end_ptr = strchr(begin_ptr, '\0');
194 assert(end_ptr != nullptr, "sanity");
195 len = end_ptr - begin_ptr;
196 cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
197 strncpy(cur_path, begin_ptr, len + 1);
198 *top_archive_path = cur_path;
199 }
200
201 void CDSConfig::ergo_init_classic_archive_paths() {
202 assert(_cds_ergo_initialize_started, "sanity");
203 if (ArchiveClassesAtExit != nullptr) {
204 assert(!RecordDynamicDumpInfo, "already checked");
205 if (is_dumping_static_archive()) {
206 vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");
207 }
208 check_unsupported_dumping_module_options();
209
210 if (os::same_files(default_archive_path(), ArchiveClassesAtExit)) {
211 vm_exit_during_initialization(
212 "Cannot specify the default CDS archive for -XX:ArchiveClassesAtExit", default_archive_path());
213 }
214 }
215
216 if (SharedArchiveFile == nullptr) {
217 _input_static_archive_path = default_archive_path();
218 if (is_dumping_static_archive()) {
219 _output_archive_path = _input_static_archive_path;
220 }
221 } else {
222 int num_archives = num_archive_paths(SharedArchiveFile);
223 assert(num_archives > 0, "must be");
224
225 if (is_dumping_archive() && num_archives > 1) {
226 vm_exit_during_initialization(
227 "Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");
228 }
229
230 if (is_dumping_static_archive()) {
231 assert(num_archives == 1, "just checked above");
232 // Static dump is simple: only one archive is allowed in SharedArchiveFile. This file
233 // will be overwritten regardless of its contents
234 _output_archive_path = SharedArchiveFile;
235 } else {
236 // SharedArchiveFile may specify one or two files. In case (c), the path for base.jsa
237 // is read from top.jsa
238 // (a) 1 file: -XX:SharedArchiveFile=base.jsa
239 // (b) 2 files: -XX:SharedArchiveFile=base.jsa:top.jsa
240 // (c) 2 files: -XX:SharedArchiveFile=top.jsa
241 //
242 // However, if either RecordDynamicDumpInfo or ArchiveClassesAtExit is used, we do not
243 // allow cases (b) and (c). Case (b) is already checked above.
244
245 if (num_archives > 2) {
246 vm_exit_during_initialization(
247 "Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");
248 }
249
250 if (num_archives == 1) {
251 const char* base_archive_path = nullptr;
252 bool success =
253 FileMapInfo::get_base_archive_name_from_header(SharedArchiveFile, &base_archive_path);
254 if (!success) {
255 // If +AutoCreateSharedArchive and the specified shared archive does not exist,
256 // regenerate the dynamic archive base on default archive.
257 if (AutoCreateSharedArchive && !os::file_exists(SharedArchiveFile)) {
258 enable_dumping_dynamic_archive(SharedArchiveFile);
259 FLAG_SET_ERGO(ArchiveClassesAtExit, SharedArchiveFile);
260 _input_static_archive_path = default_archive_path();
261 FLAG_SET_ERGO(SharedArchiveFile, nullptr);
262 } else {
263 if (AutoCreateSharedArchive) {
264 warning("-XX:+AutoCreateSharedArchive is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
265 AutoCreateSharedArchive = false;
266 }
267 aot_log_error(aot)("Not a valid %s (%s)", type_of_archive_being_loaded(), SharedArchiveFile);
268 Arguments::no_shared_spaces("invalid archive");
269 }
270 } else if (base_archive_path == nullptr) {
271 // User has specified a single archive, which is a static archive.
272 _input_static_archive_path = SharedArchiveFile;
273 } else {
274 // User has specified a single archive, which is a dynamic archive.
275 _input_dynamic_archive_path = SharedArchiveFile;
276 _input_static_archive_path = base_archive_path; // has been c-heap allocated.
277 }
278 } else {
279 extract_archive_paths(SharedArchiveFile,
280 &_input_static_archive_path, &_input_dynamic_archive_path);
281 if (_input_static_archive_path == nullptr) {
282 assert(_input_dynamic_archive_path == nullptr, "must be");
283 Arguments::no_shared_spaces("invalid archive");
284 }
285 }
286
287 if (_input_dynamic_archive_path != nullptr) {
288 // Check for case (c)
289 if (RecordDynamicDumpInfo) {
290 vm_exit_during_initialization("-XX:+RecordDynamicDumpInfo is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
291 SharedArchiveFile);
292 }
293 if (ArchiveClassesAtExit != nullptr) {
294 vm_exit_during_initialization("-XX:ArchiveClassesAtExit is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
295 SharedArchiveFile);
296 }
297 }
298
299 if (ArchiveClassesAtExit != nullptr && os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {
300 vm_exit_during_initialization(
301 "Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",
302 SharedArchiveFile);
303 }
304 }
305 }
306 }
307
308 void CDSConfig::check_internal_module_property(const char* key, const char* value) {
309 if (Arguments::is_incompatible_cds_internal_module_property(key) && !Arguments::patching_migrated_classes(key, value)) {
310 stop_using_optimized_module_handling();
311 aot_log_info(aot)("optimized module handling: disabled due to incompatible property: %s=%s", key, value);
312 }
313 }
314
315 void CDSConfig::check_incompatible_property(const char* key, const char* value) {
316 static const char* incompatible_properties[] = {
317 "java.system.class.loader",
318 "jdk.module.showModuleResolution",
319 "jdk.module.validation"
320 };
321
322 for (const char* property : incompatible_properties) {
323 if (strcmp(key, property) == 0) {
324 stop_dumping_full_module_graph();
325 stop_using_full_module_graph();
326 aot_log_info(aot)("full module graph: disabled due to incompatible property: %s=%s", key, value);
327 break;
328 }
329 }
330
331 }
332
333 // Returns any JVM command-line option, such as "--patch-module", that's not supported by CDS.
334 static const char* find_any_unsupported_module_option() {
335 // Note that arguments.cpp has translated the command-line options into properties. If we find an
336 // unsupported property, translate it back to its command-line option for better error reporting.
337
338 // The following properties are checked by Arguments::is_internal_module_property() and cannot be
339 // directly specified in the command-line.
340 static const char* unsupported_module_properties[] = {
341 "jdk.module.limitmods",
342 "jdk.module.upgrade.path"
343 };
344 static const char* unsupported_module_options[] = {
345 "--limit-modules",
346 "--upgrade-module-path"
347 };
348
349 assert(ARRAY_SIZE(unsupported_module_properties) == ARRAY_SIZE(unsupported_module_options), "must be");
350 SystemProperty* sp = Arguments::system_properties();
351 while (sp != nullptr) {
352 for (uint i = 0; i < ARRAY_SIZE(unsupported_module_properties); i++) {
353 if (strcmp(sp->key(), unsupported_module_properties[i]) == 0) {
354 return unsupported_module_options[i];
355 }
356 }
357 sp = sp->next();
358 }
359
360 return nullptr; // not found
361 }
362
363 void CDSConfig::check_unsupported_dumping_module_options() {
364 assert(is_dumping_archive(), "this function is only used with CDS dump time");
365 const char* option = find_any_unsupported_module_option();
366 if (option != nullptr) {
367 vm_exit_during_initialization("Cannot use the following option when dumping the shared archive", option);
368 }
369
370 if (module_patching_disables_cds()) {
371 vm_exit_during_initialization(
372 "Cannot use the following option when dumping the shared archive", "--patch-module");
373 }
374
375 // Check for an exploded module build in use with -Xshare:dump.
376 if (!Arguments::has_jimage()) {
377 vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
378 }
379 }
380
381 bool CDSConfig::has_unsupported_runtime_module_options() {
382 assert(is_using_archive(), "this function is only used with -Xshare:{on,auto}");
383 if (ArchiveClassesAtExit != nullptr) {
384 // dynamic dumping, just return false for now.
385 // check_unsupported_dumping_properties() will be called later to check the same set of
386 // properties, and will exit the VM with the correct error message if the unsupported properties
387 // are used.
388 return false;
389 }
390 const char* option = find_any_unsupported_module_option();
391 if (option != nullptr) {
392 if (RequireSharedSpaces) {
393 warning("CDS is disabled when the %s option is specified.", option);
394 } else {
395 if (new_aot_flags_used()) {
396 aot_log_warning(aot)("AOT cache is disabled when the %s option is specified.", option);
397 } else {
398 aot_log_info(aot)("CDS is disabled when the %s option is specified.", option);
399 }
400 }
401 return true;
402 }
403
404 if (module_patching_disables_cds()) {
405 if (RequireSharedSpaces) {
406 warning("CDS is disabled when the %s option is specified.", "--patch-module");
407 } else {
408 log_info(cds)("CDS is disabled when the %s option is specified.", "--patch-module");
409 }
410 return true;
411 }
412
413 return false;
414 }
415
416 #define CHECK_NEW_FLAG(f) check_new_flag(FLAG_IS_DEFAULT(f), #f)
417
418 void CDSConfig::check_new_flag(bool new_flag_is_default, const char* new_flag_name) {
419 if (old_cds_flags_used() && !new_flag_is_default) {
420 vm_exit_during_initialization(err_msg("Option %s cannot be used at the same time with "
421 "-Xshare:on, -Xshare:auto, -Xshare:off, -Xshare:dump, "
422 "DumpLoadedClassList, SharedClassListFile, or SharedArchiveFile",
423 new_flag_name));
424 }
425 }
426
427 #define CHECK_SINGLE_PATH(f) check_flag_single_path(#f, f)
428
429 void CDSConfig::check_flag_single_path(const char* flag_name, const char* value) {
430 if (value != nullptr && num_archive_paths(value) != 1) {
431 vm_exit_during_initialization(err_msg("Option %s must specify a single file name", flag_name));
432 }
433 }
434
435 void CDSConfig::check_aot_flags() {
436 if (!FLAG_IS_DEFAULT(DumpLoadedClassList) ||
437 !FLAG_IS_DEFAULT(SharedClassListFile) ||
438 !FLAG_IS_DEFAULT(SharedArchiveFile)) {
439 _old_cds_flags_used = true;
440 }
441
442 // "New" AOT flags must not be mixed with "classic" CDS flags such as -Xshare:dump
443 CHECK_NEW_FLAG(AOTCache);
444 CHECK_NEW_FLAG(AOTCacheOutput);
445 CHECK_NEW_FLAG(AOTConfiguration);
446 CHECK_NEW_FLAG(AOTMode);
447
448 CHECK_SINGLE_PATH(AOTCache);
449 CHECK_SINGLE_PATH(AOTCacheOutput);
450 CHECK_SINGLE_PATH(AOTConfiguration);
451
452 if (FLAG_IS_DEFAULT(AOTCache) && AOTAdapterCaching) {
453 log_debug(aot,codecache,init)("AOTCache is not specified - AOTAdapterCaching is ignored");
454 }
455 if (FLAG_IS_DEFAULT(AOTCache) && AOTStubCaching) {
456 log_debug(aot,codecache,init)("AOTCache is not specified - AOTStubCaching is ignored");
457 }
458
459 bool has_cache = !FLAG_IS_DEFAULT(AOTCache);
460 bool has_cache_output = !FLAG_IS_DEFAULT(AOTCacheOutput);
461 bool has_config = !FLAG_IS_DEFAULT(AOTConfiguration);
462 bool has_mode = !FLAG_IS_DEFAULT(AOTMode);
463
464 if (!has_cache && !has_cache_output && !has_config && !has_mode) {
465 // AOT flags are not used. Use classic CDS workflow
466 return;
467 }
468
469 if (has_cache && has_cache_output) {
470 vm_exit_during_initialization("Only one of AOTCache or AOTCacheOutput can be specified");
471 }
472
473 if (!has_cache && (!has_mode || strcmp(AOTMode, "auto") == 0)) {
474 if (has_cache_output) {
475 // If AOTCacheOutput has been set, effective mode is "record".
476 // Default value for AOTConfiguration, if necessary, will be assigned in check_aotmode_record().
477 log_info(aot)("Selected AOTMode=record because AOTCacheOutput is specified");
478 FLAG_SET_ERGO(AOTMode, "record");
479 }
480 }
481
482 // At least one AOT flag has been used
483 _new_aot_flags_used = true;
484
485 if (FLAG_IS_DEFAULT(AOTMode) || strcmp(AOTMode, "auto") == 0 || strcmp(AOTMode, "on") == 0) {
486 check_aotmode_auto_or_on();
487 } else if (strcmp(AOTMode, "off") == 0) {
488 check_aotmode_off();
489 } else if (strcmp(AOTMode, "record") == 0) {
490 check_aotmode_record();
491 } else {
492 assert(strcmp(AOTMode, "create") == 0, "checked by AOTModeConstraintFunc");
493 check_aotmode_create();
494 }
495 }
496
497 void CDSConfig::check_aotmode_off() {
498 UseSharedSpaces = false;
499 RequireSharedSpaces = false;
500 }
501
502 void CDSConfig::check_aotmode_auto_or_on() {
503 if (!FLAG_IS_DEFAULT(AOTConfiguration)) {
504 vm_exit_during_initialization(err_msg("AOTConfiguration can only be used with when AOTMode is record or create (selected AOTMode = %s)",
505 FLAG_IS_DEFAULT(AOTMode) ? "auto" : AOTMode));
506 }
507
508 UseSharedSpaces = true;
509 if (FLAG_IS_DEFAULT(AOTMode) || (strcmp(AOTMode, "auto") == 0)) {
510 RequireSharedSpaces = false;
511 } else {
512 assert(strcmp(AOTMode, "on") == 0, "already checked");
513 RequireSharedSpaces = true;
514 }
515 }
516
517 // %p substitution in AOTCache, AOTCacheOutput and AOTCacheConfiguration
518 static void substitute_aot_filename(JVMFlagsEnum flag_enum) {
519 JVMFlag* flag = JVMFlag::flag_from_enum(flag_enum);
520 const char* filename = flag->read<const char*>();
521 assert(filename != nullptr, "must not have default value");
522
523 // For simplicity, we don't allow %p/%t to be specified twice, because make_log_name()
524 // substitutes only the first occurrence. Otherwise, if we run with
525 // java -XX:AOTCacheOutput=%p%p.aot
526 // it will end up with both the pid of the training process and the assembly process.
527 const char* first_p = strstr(filename, "%p");
528 if (first_p != nullptr && strstr(first_p + 2, "%p") != nullptr) {
529 vm_exit_during_initialization(err_msg("%s cannot contain more than one %%p", flag->name()));
530 }
531 const char* first_t = strstr(filename, "%t");
532 if (first_t != nullptr && strstr(first_t + 2, "%t") != nullptr) {
533 vm_exit_during_initialization(err_msg("%s cannot contain more than one %%t", flag->name()));
534 }
535
536 // Note: with single-command training, %p will be the pid of the training process, not the
537 // assembly process.
538 const char* new_filename = make_log_name(filename, nullptr);
539 if (strcmp(filename, new_filename) != 0) {
540 JVMFlag::Error err = JVMFlagAccess::set_ccstr(flag, &new_filename, JVMFlagOrigin::ERGONOMIC);
541 assert(err == JVMFlag::SUCCESS, "must never fail");
542 }
543 FREE_C_HEAP_ARRAY(char, new_filename);
544 }
545
546 void CDSConfig::check_aotmode_record() {
547 bool has_config = !FLAG_IS_DEFAULT(AOTConfiguration);
548 bool has_output = !FLAG_IS_DEFAULT(AOTCacheOutput);
549
550 if (!has_output && !has_config) {
551 vm_exit_during_initialization("At least one of AOTCacheOutput and AOTConfiguration must be specified when using -XX:AOTMode=record");
552 }
553
554 if (has_output) {
555 _is_single_command_training = true;
556 substitute_aot_filename(FLAG_MEMBER_ENUM(AOTCacheOutput));
557 if (!has_config) {
558 // Too early; can't use resource allocation yet.
559 size_t len = strlen(AOTCacheOutput) + 10;
560 char* temp = AllocateHeap(len, mtArguments);
561 jio_snprintf(temp, len, "%s.config", AOTCacheOutput);
562 FLAG_SET_ERGO(AOTConfiguration, temp);
563 FreeHeap(temp);
564 _has_temp_aot_config_file = true;
565 }
566 }
567
568 if (!FLAG_IS_DEFAULT(AOTCache)) {
569 vm_exit_during_initialization("AOTCache must not be specified when using -XX:AOTMode=record");
570 }
571
572 substitute_aot_filename(FLAG_MEMBER_ENUM(AOTConfiguration));
573
574 UseSharedSpaces = false;
575 RequireSharedSpaces = false;
576 _is_dumping_static_archive = true;
577 _is_dumping_preimage_static_archive = true;
578
579 // At VM exit, the module graph may be contaminated with program states.
580 // We will rebuild the module graph when dumping the CDS final image.
581 disable_heap_dumping();
582 }
583
584 void CDSConfig::check_aotmode_create() {
585 if (FLAG_IS_DEFAULT(AOTConfiguration)) {
586 vm_exit_during_initialization("AOTConfiguration must be specified when using -XX:AOTMode=create");
587 }
588
589 bool has_cache = !FLAG_IS_DEFAULT(AOTCache);
590 bool has_cache_output = !FLAG_IS_DEFAULT(AOTCacheOutput);
591
592 assert(!(has_cache && has_cache_output), "already checked");
593
594 if (!has_cache && !has_cache_output) {
595 vm_exit_during_initialization("AOTCache or AOTCacheOutput must be specified when using -XX:AOTMode=create");
596 }
597
598 if (!has_cache) {
599 precond(has_cache_output);
600 FLAG_SET_ERGO(AOTCache, AOTCacheOutput);
601 }
602 // No need to check for (!has_cache_output), as we don't look at AOTCacheOutput after here.
603
604 substitute_aot_filename(FLAG_MEMBER_ENUM(AOTCache));
605
606 _is_dumping_final_static_archive = true;
607 UseSharedSpaces = true;
608 RequireSharedSpaces = true;
609
610 if (!FileMapInfo::is_preimage_static_archive(AOTConfiguration)) {
611 vm_exit_during_initialization("Must be a valid AOT configuration generated by the current JVM", AOTConfiguration);
612 }
613
614 CDSConfig::enable_dumping_static_archive();
615
616 // We don't load any agents in the assembly phase, so we can ensure that the agents
617 // cannot affect the contents of the AOT cache. E.g., we don't want the agents to
618 // redefine any cached classes. We also don't want the agents to modify heap objects that
619 // are cached.
620 //
621 // Since application is not executed in the assembly phase, there's no need to load
622 // the agents anyway -- no one will notice that the agents are not loaded.
623 log_info(aot)("Disabled all JVMTI agents during -XX:AOTMode=create");
624 JvmtiAgentList::disable_agent_list();
625 }
626
627 void CDSConfig::ergo_init_aot_paths() {
628 assert(_cds_ergo_initialize_started, "sanity");
629 if (is_dumping_static_archive()) {
630 if (is_dumping_preimage_static_archive()) {
631 _output_archive_path = AOTConfiguration;
632 } else {
633 assert(is_dumping_final_static_archive(), "must be");
634 _input_static_archive_path = AOTConfiguration;
635 _output_archive_path = AOTCache;
636 }
637 } else if (is_using_archive()) {
638 if (FLAG_IS_DEFAULT(AOTCache)) {
639 // Only -XX:AOTMode={auto,on} is specified
640 _input_static_archive_path = default_archive_path();
641 } else {
642 _input_static_archive_path = AOTCache;
643 }
644 }
645 }
646
647 bool CDSConfig::check_vm_args_consistency(bool mode_flag_cmd_line) {
648 assert(!_cds_ergo_initialize_started, "This is called earlier than CDSConfig::ergo_initialize()");
649
650 check_aot_flags();
651
652 if (!FLAG_IS_DEFAULT(AOTMode)) {
653 // Using any form of the new AOTMode switch enables enhanced optimizations.
654 FLAG_SET_ERGO_IF_DEFAULT(AOTClassLinking, true);
655 }
656
657 setup_compiler_args();
658
659 if (AOTClassLinking) {
660 // If AOTClassLinking is specified, enable all AOT optimizations by default.
661 FLAG_SET_ERGO_IF_DEFAULT(AOTInvokeDynamicLinking, true);
662 } else {
663 // AOTInvokeDynamicLinking depends on AOTClassLinking.
664 FLAG_SET_ERGO(AOTInvokeDynamicLinking, false);
665 }
666
667 if (is_dumping_static_archive()) {
668 if (is_dumping_preimage_static_archive()) {
669 // Don't tweak execution mode during AOT training run
670 } else if (is_dumping_final_static_archive()) {
671 if (Arguments::mode() == Arguments::_comp) {
672 // AOT assembly phase submits the non-blocking compilation requests
673 // for methods collected during training run, then waits for all compilations
674 // to complete. With -Xcomp, we block for each compilation request, which is
675 // counter-productive. Switching back to mixed mode improves testing time
676 // with AOT and -Xcomp.
677 Arguments::set_mode_flags(Arguments::_mixed);
678 }
679 } else if (!mode_flag_cmd_line) {
680 // By default, -Xshare:dump runs in interpreter-only mode, which is required for deterministic archive.
681 //
682 // If your classlist is large and you don't care about deterministic dumping, you can use
683 // -Xshare:dump -Xmixed to improve dumping speed.
684 Arguments::set_mode_flags(Arguments::_int);
685 } else if (Arguments::mode() == Arguments::_comp) {
686 // -Xcomp may use excessive CPU for the test tiers. Also, -Xshare:dump runs a small and fixed set of
687 // Java code, so there's not much benefit in running -Xcomp.
688 aot_log_info(aot)("reduced -Xcomp to -Xmixed for static dumping");
689 Arguments::set_mode_flags(Arguments::_mixed);
690 }
691
692 // String deduplication may cause CDS to iterate the strings in different order from one
693 // run to another which resulting in non-determinstic CDS archives.
694 // Disable UseStringDeduplication while dumping CDS archive.
695 UseStringDeduplication = false;
696 }
697
698 // RecordDynamicDumpInfo is not compatible with ArchiveClassesAtExit
699 if (ArchiveClassesAtExit != nullptr && RecordDynamicDumpInfo) {
700 jio_fprintf(defaultStream::output_stream(),
701 "-XX:+RecordDynamicDumpInfo cannot be used with -XX:ArchiveClassesAtExit.\n");
702 return false;
703 }
704
705 if (ArchiveClassesAtExit == nullptr && !RecordDynamicDumpInfo) {
706 disable_dumping_dynamic_archive();
707 } else {
708 enable_dumping_dynamic_archive(ArchiveClassesAtExit);
709 }
710
711 if (AutoCreateSharedArchive) {
712 if (SharedArchiveFile == nullptr) {
713 aot_log_warning(aot)("-XX:+AutoCreateSharedArchive requires -XX:SharedArchiveFile");
714 return false;
715 }
716 if (ArchiveClassesAtExit != nullptr) {
717 aot_log_warning(aot)("-XX:+AutoCreateSharedArchive does not work with ArchiveClassesAtExit");
718 return false;
719 }
720 }
721
722 if (is_using_archive() && java_base_module_patching_disables_cds() && module_patching_disables_cds()) {
723 Arguments::no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
724 }
725 if (is_using_archive() && has_unsupported_runtime_module_options()) {
726 UseSharedSpaces = false;
727 }
728
729 if (is_dumping_archive()) {
730 // Always verify non-system classes during CDS dump
731 if (!BytecodeVerificationRemote) {
732 BytecodeVerificationRemote = true;
733 aot_log_info(aot)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");
734 }
735 }
736
737 return true;
738 }
739
740 void CDSConfig::setup_compiler_args() {
741 // AOT profiles and AOT-compiled code are supported only in the JEP 483 workflow.
742 bool can_dump_profile_and_compiled_code = AOTClassLinking && new_aot_flags_used();
743
744 if (is_dumping_preimage_static_archive() && can_dump_profile_and_compiled_code) {
745 // JEP 483 workflow -- training
746 FLAG_SET_ERGO_IF_DEFAULT(AOTRecordTraining, true);
747 FLAG_SET_ERGO(AOTReplayTraining, false);
748 AOTCodeCache::disable_caching(); // No AOT code generation during training run
749 } else if (is_dumping_final_static_archive() && can_dump_profile_and_compiled_code) {
750 // JEP 483 workflow -- assembly
751 FLAG_SET_ERGO(AOTRecordTraining, false);
752 FLAG_SET_ERGO_IF_DEFAULT(AOTReplayTraining, true);
753 AOTCodeCache::enable_caching(); // Generate AOT code during assembly phase.
754 disable_dumping_aot_code(); // Don't dump AOT code until metadata and heap are dumped.
755 } else if (is_using_archive() && new_aot_flags_used()) {
756 // JEP 483 workflow -- production
757 FLAG_SET_ERGO(AOTRecordTraining, false);
758 FLAG_SET_ERGO_IF_DEFAULT(AOTReplayTraining, true);
759 AOTCodeCache::enable_caching();
760 } else {
761 FLAG_SET_ERGO(AOTReplayTraining, false);
762 FLAG_SET_ERGO(AOTRecordTraining, false);
763 AOTCodeCache::disable_caching();
764 }
765 }
766
767 void CDSConfig::prepare_for_dumping() {
768 assert(CDSConfig::is_dumping_archive(), "sanity");
769
770 if (is_dumping_dynamic_archive() && AOTClassLinking) {
771 if (FLAG_IS_CMDLINE(AOTClassLinking)) {
772 log_warning(cds)("AOTClassLinking is not supported for dynamic CDS archive");
773 }
774 FLAG_SET_ERGO(AOTClassLinking, false);
775 }
776
777 if (is_dumping_dynamic_archive() && !is_using_archive()) {
778 assert(!is_dumping_static_archive(), "cannot be dumping both static and dynamic archives");
779
780 // This could happen if SharedArchiveFile has failed to load:
781 // - -Xshare:off was specified
782 // - SharedArchiveFile points to an non-existent file.
783 // - SharedArchiveFile points to an archive that has failed CRC check
784 // - SharedArchiveFile is not specified and the VM doesn't have a compatible default archive
785
786 #define __THEMSG " is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info."
787 if (RecordDynamicDumpInfo) {
788 aot_log_error(aot)("-XX:+RecordDynamicDumpInfo%s", __THEMSG);
789 AOTMetaspace::unrecoverable_loading_error();
790 } else {
791 assert(ArchiveClassesAtExit != nullptr, "sanity");
792 aot_log_warning(aot)("-XX:ArchiveClassesAtExit" __THEMSG);
793 }
794 #undef __THEMSG
795 disable_dumping_dynamic_archive();
796 return;
797 }
798
799 check_unsupported_dumping_module_options();
800 }
801
802 bool CDSConfig::is_dumping_classic_static_archive() {
803 return _is_dumping_static_archive &&
804 !is_dumping_preimage_static_archive() &&
805 !is_dumping_final_static_archive();
806 }
807
808 bool CDSConfig::is_dumping_preimage_static_archive() {
809 return _is_dumping_preimage_static_archive;
810 }
811
812 bool CDSConfig::is_dumping_final_static_archive() {
813 return _is_dumping_final_static_archive;
814 }
815
816 void CDSConfig::enable_dumping_dynamic_archive(const char* output_path) {
817 _is_dumping_dynamic_archive = true;
818 if (output_path == nullptr) {
819 // output_path can be null when the VM is started with -XX:+RecordDynamicDumpInfo
820 // in anticipation of "jcmd VM.cds dynamic_dump", which will provide the actual
821 // output path.
822 _output_archive_path = nullptr;
823 } else {
824 _output_archive_path = os::strdup_check_oom(output_path, mtArguments);
825 }
826 }
827
828 bool CDSConfig::allow_only_single_java_thread() {
829 // See comments in JVM_StartThread()
830 return is_dumping_classic_static_archive() || is_dumping_final_static_archive();
831 }
832
833 bool CDSConfig::is_using_archive() {
834 return UseSharedSpaces;
835 }
836
837 bool CDSConfig::is_using_only_default_archive() {
838 return is_using_archive() &&
839 input_static_archive_path() != nullptr &&
840 default_archive_path() != nullptr &&
841 strcmp(input_static_archive_path(), default_archive_path()) == 0 &&
842 input_dynamic_archive_path() == nullptr;
843 }
844
845 bool CDSConfig::is_logging_lambda_form_invokers() {
846 return ClassListWriter::is_enabled() || is_dumping_dynamic_archive();
847 }
848
849 bool CDSConfig::is_dumping_regenerated_lambdaform_invokers() {
850 if (is_dumping_final_static_archive()) {
851 // No need to regenerate -- the lambda form invokers should have been regenerated
852 // in the preimage archive (if allowed)
853 return false;
854 } else if (is_dumping_dynamic_archive() && is_using_aot_linked_classes()) {
855 // The base archive has aot-linked classes that may have AOT-resolved CP references
856 // that point to the lambda form invokers in the base archive. Such pointers will
857 // be invalid if lambda form invokers are regenerated in the dynamic archive.
858 return false;
859 } else {
860 return is_dumping_archive();
861 }
862 }
863
864 void CDSConfig::stop_using_optimized_module_handling() {
865 _is_using_optimized_module_handling = false;
866 _is_dumping_full_module_graph = false; // This requires is_using_optimized_module_handling()
867 _is_using_full_module_graph = false; // This requires is_using_optimized_module_handling()
868 }
869
870
871 CDSConfig::DumperThreadMark::DumperThreadMark(JavaThread* current) {
872 assert(_dumper_thread == nullptr, "sanity");
873 _dumper_thread = current;
874 }
875
876 CDSConfig::DumperThreadMark::~DumperThreadMark() {
877 assert(_dumper_thread != nullptr, "sanity");
878 _dumper_thread = nullptr;
879 }
880
881 bool CDSConfig::current_thread_is_vm_or_dumper() {
882 Thread* t = Thread::current();
883 return t->is_VM_thread() || t == _dumper_thread;
884 }
885
886 bool CDSConfig::current_thread_is_dumper() {
887 return Thread::current() == _dumper_thread;
888 }
889
890 const char* CDSConfig::type_of_archive_being_loaded() {
891 if (is_dumping_final_static_archive()) {
892 return "AOT configuration file";
893 } else if (new_aot_flags_used()) {
894 return "AOT cache";
895 } else {
896 return "shared archive file";
897 }
898 }
899
900 const char* CDSConfig::type_of_archive_being_written() {
901 if (is_dumping_preimage_static_archive()) {
902 return "AOT configuration file";
903 } else if (new_aot_flags_used()) {
904 return "AOT cache";
905 } else {
906 return "shared archive file";
907 }
908 }
909
910 // If an incompatible VM options is found, return a text message that explains why
911 static const char* check_options_incompatible_with_dumping_heap() {
912 #if INCLUDE_CDS_JAVA_HEAP
913 if (!UseCompressedClassPointers) {
914 return "UseCompressedClassPointers must be true";
915 }
916
917 // Almost all GCs support heap region dump, except ZGC (so far).
918 if (UseZGC) {
919 return "ZGC is not supported";
920 }
921
922 return nullptr;
923 #else
924 return "JVM not configured for writing Java heap objects";
925 #endif
926 }
927
928 void CDSConfig::log_reasons_for_not_dumping_heap() {
929 const char* reason;
930
931 assert(!is_dumping_heap(), "sanity");
932
933 if (_disable_heap_dumping) {
934 reason = "Programmatically disabled";
935 } else {
936 reason = check_options_incompatible_with_dumping_heap();
937 }
938
939 assert(reason != nullptr, "sanity");
940 aot_log_info(aot)("Archived java heap is not supported: %s", reason);
941 }
942
943 // This is *Legacy* optimization for lambdas before JEP 483. May be removed in the future.
944 bool CDSConfig::is_dumping_lambdas_in_legacy_mode() {
945 return !is_dumping_method_handles();
946 }
947
948 bool CDSConfig::is_preserving_verification_constraints() {
949 // Verification dependencies are classes used in assignability checks by the
950 // bytecode verifier. In the following example, the verification dependencies
951 // for X are A and B.
952 //
953 // class X {
954 // A getA() { return new B(); }
955 // }
956 //
957 // With the AOT cache, we can ensure that all the verification dependencies
958 // (A and B in the above example) are unconditionally loaded during the bootstrap
959 // of the production run. This means that if a class was successfully verified
960 // in the assembly phase, all of the verifier's assignability checks will remain
961 // valid in the production run, so we don't need to verify aot-linked classes again.
962
963 if (is_dumping_preimage_static_archive()) { // writing AOT config
964 return AOTClassLinking;
965 } else if (is_dumping_final_static_archive()) { // writing AOT cache
966 return is_dumping_aot_linked_classes();
967 } else if (is_dumping_classic_static_archive()) {
968 return is_dumping_aot_linked_classes();
969 } else {
970 return false;
971 }
972 }
973
974 bool CDSConfig::is_old_class_for_verifier(const InstanceKlass* ik) {
975 return ik->major_version() < 50 /*JAVA_6_VERSION*/;
976 }
977
978 #if INCLUDE_CDS_JAVA_HEAP
979 bool CDSConfig::are_vm_options_incompatible_with_dumping_heap() {
980 return check_options_incompatible_with_dumping_heap() != nullptr;
981 }
982
983 bool CDSConfig::is_dumping_heap() {
984 if (is_valhalla_preview()) {
985 // Not working yet -- e.g., HeapShared::oop_hash() needs to be implemented for value oops
986 return false;
987 }
988 if (!(is_dumping_classic_static_archive() || is_dumping_final_static_archive())
989 || are_vm_options_incompatible_with_dumping_heap()
990 || _disable_heap_dumping) {
991 return false;
992 }
993 return true;
994 }
995
996 bool CDSConfig::is_loading_heap() {
997 return ArchiveHeapLoader::is_in_use();
998 }
999
1000 bool CDSConfig::is_using_full_module_graph() {
1001 if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
1002 return true;
1003 }
1004
1005 if (!_is_using_full_module_graph) {
1006 return false;
1007 }
1008
1009 if (is_using_archive() && ArchiveHeapLoader::can_use()) {
1010 // Classes used by the archived full module graph are loaded in JVMTI early phase.
1011 assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
1012 "CDS should be disabled if early class hooks are enabled");
1013 return true;
1014 } else {
1015 _is_using_full_module_graph = false;
1016 return false;
1017 }
1018 }
1019
1020 void CDSConfig::stop_dumping_full_module_graph(const char* reason) {
1021 if (_is_dumping_full_module_graph) {
1022 _is_dumping_full_module_graph = false;
1023 if (reason != nullptr) {
1024 aot_log_info(aot)("full module graph cannot be dumped: %s", reason);
1025 }
1026 }
1027 }
1028
1029 void CDSConfig::stop_using_full_module_graph(const char* reason) {
1030 assert(!ClassLoaderDataShared::is_full_module_graph_loaded(), "you call this function too late!");
1031 if (_is_using_full_module_graph) {
1032 _is_using_full_module_graph = false;
1033 if (reason != nullptr) {
1034 aot_log_info(aot)("full module graph cannot be loaded: %s", reason);
1035 }
1036 }
1037 }
1038
1039 bool CDSConfig::is_dumping_aot_linked_classes() {
1040 if (is_dumping_classic_static_archive() || is_dumping_final_static_archive()) {
1041 // FMG is required to guarantee that all cached boot/platform/app classes
1042 // are visible in the production run, so they can be unconditionally
1043 // loaded during VM bootstrap.
1044 return is_dumping_full_module_graph() && AOTClassLinking;
1045 } else {
1046 return false;
1047 }
1048 }
1049
1050 bool CDSConfig::is_using_aot_linked_classes() {
1051 // Make sure we have the exact same module graph as in the assembly phase, or else
1052 // some aot-linked classes may not be visible so cannot be loaded.
1053 return is_using_full_module_graph() && _has_aot_linked_classes;
1054 }
1055
1056 void CDSConfig::set_has_aot_linked_classes(bool has_aot_linked_classes) {
1057 _has_aot_linked_classes |= has_aot_linked_classes;
1058 }
1059
1060 bool CDSConfig::is_initing_classes_at_dump_time() {
1061 return is_dumping_heap() && is_dumping_aot_linked_classes();
1062 }
1063
1064 bool CDSConfig::is_dumping_invokedynamic() {
1065 // Requires is_dumping_aot_linked_classes(). Otherwise the classes of some archived heap
1066 // objects used by the archive indy callsites may be replaced at runtime.
1067 return AOTInvokeDynamicLinking && is_dumping_aot_linked_classes() && is_dumping_heap();
1068 }
1069
1070 // When we are dumping aot-linked classes and we are able to write archived heap objects, we automatically
1071 // enable the archiving of MethodHandles. This will in turn enable the archiving of MethodTypes and hidden
1072 // classes that are used in the implementation of MethodHandles.
1073 // Archived MethodHandles are required for higher-level optimizations such as AOT resolution of invokedynamic
1074 // and dynamic proxies.
1075 bool CDSConfig::is_dumping_method_handles() {
1076 return is_initing_classes_at_dump_time();
1077 }
1078
1079 #endif // INCLUDE_CDS_JAVA_HEAP
1080
1081 // AOT code generation and its archiving is disabled by default.
1082 // We enable it only in the final image dump after the metadata and heap are dumped.
1083 // This affects only JITed code because it may have embedded oops and metadata pointers
1084 // which AOT code encodes as offsets in final CDS archive regions.
1085
1086 static bool _is_dumping_aot_code = false;
1087
1088 bool CDSConfig::is_dumping_aot_code() {
1089 return _is_dumping_aot_code;
1090 }
1091
1092 void CDSConfig::disable_dumping_aot_code() {
1093 _is_dumping_aot_code = false;
1094 }
1095
1096 void CDSConfig::enable_dumping_aot_code() {
1097 _is_dumping_aot_code = true;
1098 }
1099
1100 bool CDSConfig::is_dumping_adapters() {
1101 return (AOTAdapterCaching && is_dumping_final_static_archive());
1102 }