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