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