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