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