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/archiveHeapLoader.hpp"
 26 #include "cds/cdsConfig.hpp"
 27 #include "cds/classListWriter.hpp"
 28 #include "cds/filemap.hpp"
 29 #include "cds/heapShared.hpp"
 30 #include "classfile/classLoaderDataShared.hpp"
 31 #include "classfile/moduleEntry.hpp"
 32 #include "include/jvm_io.h"
 33 #include "logging/log.hpp"
 34 #include "memory/universe.hpp"
 35 #include "runtime/arguments.hpp"
 36 #include "runtime/globals_extension.hpp"
 37 #include "runtime/java.hpp"
 38 #include "runtime/vmThread.hpp"
 39 #include "utilities/defaultStream.hpp"
 40 #include "utilities/formatBuffer.hpp"
 41 
 42 bool CDSConfig::_is_dumping_static_archive = false;
 43 bool CDSConfig::_is_dumping_preimage_static_archive = false;
 44 bool CDSConfig::_is_dumping_final_static_archive = false;
 45 bool CDSConfig::_is_dumping_dynamic_archive = false;
 46 bool CDSConfig::_is_using_optimized_module_handling = true;
 47 bool CDSConfig::_is_dumping_full_module_graph = true;
 48 bool CDSConfig::_is_using_full_module_graph = true;
 49 bool CDSConfig::_has_aot_linked_classes = false;
 50 bool CDSConfig::_old_cds_flags_used = false;
 51 bool CDSConfig::_new_aot_flags_used = false;
 52 bool CDSConfig::_disable_heap_dumping = false;
 53 
 54 const char* CDSConfig::_default_archive_path = nullptr;
 55 const char* CDSConfig::_input_static_archive_path = nullptr;
 56 const char* CDSConfig::_input_dynamic_archive_path = nullptr;
 57 const char* CDSConfig::_output_archive_path = nullptr;
 58 
 59 JavaThread* CDSConfig::_dumper_thread = nullptr;
 60 
 61 int CDSConfig::get_status() {
 62   assert(Universe::is_fully_initialized(), "status is finalized only after Universe is initialized");
 63   return (is_dumping_archive()              ? IS_DUMPING_ARCHIVE : 0) |
 64          (is_dumping_method_handles()       ? IS_DUMPING_METHOD_HANDLES : 0) |
 65          (is_dumping_static_archive()       ? IS_DUMPING_STATIC_ARCHIVE : 0) |
 66          (is_logging_lambda_form_invokers() ? IS_LOGGING_LAMBDA_FORM_INVOKERS : 0) |
 67          (is_using_archive()                ? IS_USING_ARCHIVE : 0);
 68 }
 69 
 70 DEBUG_ONLY(static bool _cds_ergo_initialize_started = false);
 71 
 72 void CDSConfig::ergo_initialize() {
 73   DEBUG_ONLY(_cds_ergo_initialize_started = true);
 74 
 75   if (is_dumping_static_archive() && !is_dumping_final_static_archive()) {
 76     // Note: -Xshare and -XX:AOTMode flags are mutually exclusive.
 77     // - Classic workflow: -Xshare:on and -Xshare:dump cannot take effect at the same time.
 78     // - JEP 483 workflow: -XX:AOTMode:record and -XX:AOTMode=on cannot take effect at the same time.
 79     // So we can never come to here with RequireSharedSpaces==true.
 80     assert(!RequireSharedSpaces, "sanity");
 81 
 82     // If dumping the classic archive, or making an AOT training run (dumping a preimage archive),
 83     // for sanity, parse all classes from classfiles.
 84     // TODO: in the future, if we want to support re-training on top of an existing AOT cache, this
 85     // needs to be changed.
 86     UseSharedSpaces = false;
 87   }
 88 
 89   // Initialize shared archive paths which could include both base and dynamic archive paths
 90   // This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.
 91   if (is_dumping_static_archive() || is_using_archive()) {
 92     if (new_aot_flags_used()) {
 93       ergo_init_aot_paths();
 94     } else {
 95       ergo_init_classic_archive_paths();
 96     }
 97   }
 98 
 99   if (!is_dumping_heap()) {
100     _is_dumping_full_module_graph = false;
101   }
102 }
103 
104 const char* CDSConfig::default_archive_path() {
105   // The path depends on UseCompressedOops, etc, which are set by GC ergonomics just
106   // before CDSConfig::ergo_initialize() is called.
107   assert(_cds_ergo_initialize_started, "sanity");
108   if (_default_archive_path == nullptr) {
109     stringStream tmp;
110     const char* subdir = WINDOWS_ONLY("bin") NOT_WINDOWS("lib");
111     tmp.print("%s%s%s%s%s%sclasses", Arguments::get_java_home(), os::file_separator(), subdir,
112               os::file_separator(), Abstract_VM_Version::vm_variant(), os::file_separator());
113 #ifdef _LP64
114     if (!UseCompressedOops) {
115       tmp.print_raw("_nocoops");
116     }
117     if (UseCompactObjectHeaders) {
118       // Note that generation of xxx_coh.jsa variants require
119       // --enable-cds-archive-coh at build time
120       tmp.print_raw("_coh");
121     }
122 #endif
123     tmp.print_raw(".jsa");
124     _default_archive_path = os::strdup(tmp.base());
125   }
126   return _default_archive_path;
127 }
128 
129 int CDSConfig::num_archive_paths(const char* path_spec) {
130   if (path_spec == nullptr) {
131     return 0;
132   }
133   int npaths = 1;
134   char* p = (char*)path_spec;
135   while (*p != '\0') {
136     if (*p == os::path_separator()[0]) {
137       npaths++;
138     }
139     p++;
140   }
141   return npaths;
142 }
143 
144 void CDSConfig::extract_archive_paths(const char* archive_path,
145                                       const char** base_archive_path,
146                                       const char** top_archive_path) {
147   char* begin_ptr = (char*)archive_path;
148   char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);
149   if (end_ptr == nullptr || end_ptr == begin_ptr) {
150     vm_exit_during_initialization("Base archive was not specified", archive_path);
151   }
152   size_t len = end_ptr - begin_ptr;
153   char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
154   strncpy(cur_path, begin_ptr, len);
155   cur_path[len] = '\0';
156   *base_archive_path = cur_path;
157 
158   begin_ptr = ++end_ptr;
159   if (*begin_ptr == '\0') {
160     vm_exit_during_initialization("Top archive was not specified", archive_path);
161   }
162   end_ptr = strchr(begin_ptr, '\0');
163   assert(end_ptr != nullptr, "sanity");
164   len = end_ptr - begin_ptr;
165   cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
166   strncpy(cur_path, begin_ptr, len + 1);
167   *top_archive_path = cur_path;
168 }
169 
170 void CDSConfig::ergo_init_classic_archive_paths() {
171   assert(_cds_ergo_initialize_started, "sanity");
172   if (ArchiveClassesAtExit != nullptr) {
173     assert(!RecordDynamicDumpInfo, "already checked");
174     if (is_dumping_static_archive()) {
175       vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");
176     }
177     check_unsupported_dumping_module_options();
178 
179     if (os::same_files(default_archive_path(), ArchiveClassesAtExit)) {
180       vm_exit_during_initialization(
181         "Cannot specify the default CDS archive for -XX:ArchiveClassesAtExit", default_archive_path());
182     }
183   }
184 
185   if (SharedArchiveFile == nullptr) {
186     _input_static_archive_path = default_archive_path();
187     if (is_dumping_static_archive()) {
188       _output_archive_path = _input_static_archive_path;
189     }
190   } else {
191     int num_archives = num_archive_paths(SharedArchiveFile);
192     assert(num_archives > 0, "must be");
193 
194     if (is_dumping_archive() && num_archives > 1) {
195       vm_exit_during_initialization(
196         "Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");
197     }
198 
199     if (is_dumping_static_archive()) {
200       assert(num_archives == 1, "just checked above");
201       // Static dump is simple: only one archive is allowed in SharedArchiveFile. This file
202       // will be overwritten regardless of its contents
203       _output_archive_path = SharedArchiveFile;
204     } else {
205       // SharedArchiveFile may specify one or two files. In case (c), the path for base.jsa
206       // is read from top.jsa
207       //    (a) 1 file:  -XX:SharedArchiveFile=base.jsa
208       //    (b) 2 files: -XX:SharedArchiveFile=base.jsa:top.jsa
209       //    (c) 2 files: -XX:SharedArchiveFile=top.jsa
210       //
211       // However, if either RecordDynamicDumpInfo or ArchiveClassesAtExit is used, we do not
212       // allow cases (b) and (c). Case (b) is already checked above.
213 
214       if (num_archives > 2) {
215         vm_exit_during_initialization(
216           "Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");
217       }
218 
219       if (num_archives == 1) {
220         const char* base_archive_path = nullptr;
221         bool success =
222           FileMapInfo::get_base_archive_name_from_header(SharedArchiveFile, &base_archive_path);
223         if (!success) {
224           // If +AutoCreateSharedArchive and the specified shared archive does not exist,
225           // regenerate the dynamic archive base on default archive.
226           if (AutoCreateSharedArchive && !os::file_exists(SharedArchiveFile)) {
227             enable_dumping_dynamic_archive(SharedArchiveFile);
228             FLAG_SET_ERGO(ArchiveClassesAtExit, SharedArchiveFile);
229             _input_static_archive_path = default_archive_path();
230             FLAG_SET_ERGO(SharedArchiveFile, nullptr);
231          } else {
232             if (AutoCreateSharedArchive) {
233               warning("-XX:+AutoCreateSharedArchive is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
234               AutoCreateSharedArchive = false;
235             }
236             log_error(cds)("Not a valid archive (%s)", SharedArchiveFile);
237             Arguments::no_shared_spaces("invalid archive");
238           }
239         } else if (base_archive_path == nullptr) {
240           // User has specified a single archive, which is a static archive.
241           _input_static_archive_path = SharedArchiveFile;
242         } else {
243           // User has specified a single archive, which is a dynamic archive.
244           _input_dynamic_archive_path = SharedArchiveFile;
245           _input_static_archive_path = base_archive_path; // has been c-heap allocated.
246         }
247       } else {
248         extract_archive_paths(SharedArchiveFile,
249                               &_input_static_archive_path, &_input_dynamic_archive_path);
250         if (_input_static_archive_path == nullptr) {
251           assert(_input_dynamic_archive_path == nullptr, "must be");
252           Arguments::no_shared_spaces("invalid archive");
253         }
254       }
255 
256       if (_input_dynamic_archive_path != nullptr) {
257         // Check for case (c)
258         if (RecordDynamicDumpInfo) {
259           vm_exit_during_initialization("-XX:+RecordDynamicDumpInfo is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
260                                         SharedArchiveFile);
261         }
262         if (ArchiveClassesAtExit != nullptr) {
263           vm_exit_during_initialization("-XX:ArchiveClassesAtExit is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
264                                         SharedArchiveFile);
265         }
266       }
267 
268       if (ArchiveClassesAtExit != nullptr && os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {
269           vm_exit_during_initialization(
270             "Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",
271             SharedArchiveFile);
272       }
273     }
274   }
275 }
276 
277 void CDSConfig::check_internal_module_property(const char* key, const char* value) {
278   if (Arguments::is_incompatible_cds_internal_module_property(key)) {
279     stop_using_optimized_module_handling();
280     log_info(cds)("optimized module handling: disabled due to incompatible property: %s=%s", key, value);
281   }
282 }
283 
284 void CDSConfig::check_incompatible_property(const char* key, const char* value) {
285   static const char* incompatible_properties[] = {
286     "java.system.class.loader",
287     "jdk.module.showModuleResolution",
288     "jdk.module.validation"
289   };
290 
291   for (const char* property : incompatible_properties) {
292     if (strcmp(key, property) == 0) {
293       stop_dumping_full_module_graph();
294       stop_using_full_module_graph();
295       log_info(cds)("full module graph: disabled due to incompatible property: %s=%s", key, value);
296       break;
297     }
298   }
299 
300 }
301 
302 // Returns any JVM command-line option, such as "--patch-module", that's not supported by CDS.
303 static const char* find_any_unsupported_module_option() {
304   // Note that arguments.cpp has translated the command-line options into properties. If we find an
305   // unsupported property, translate it back to its command-line option for better error reporting.
306 
307   // The following properties are checked by Arguments::is_internal_module_property() and cannot be
308   // directly specified in the command-line.
309   static const char* unsupported_module_properties[] = {
310     "jdk.module.limitmods",
311     "jdk.module.upgrade.path",
312     "jdk.module.patch.0"
313   };
314   static const char* unsupported_module_options[] = {
315     "--limit-modules",
316     "--upgrade-module-path",
317     "--patch-module"
318   };
319 
320   assert(ARRAY_SIZE(unsupported_module_properties) == ARRAY_SIZE(unsupported_module_options), "must be");
321   SystemProperty* sp = Arguments::system_properties();
322   while (sp != nullptr) {
323     for (uint i = 0; i < ARRAY_SIZE(unsupported_module_properties); i++) {
324       if (strcmp(sp->key(), unsupported_module_properties[i]) == 0) {
325         return unsupported_module_options[i];
326       }
327     }
328     sp = sp->next();
329   }
330 
331   return nullptr; // not found
332 }
333 
334 void CDSConfig::check_unsupported_dumping_module_options() {
335   assert(is_dumping_archive(), "this function is only used with CDS dump time");
336   const char* option = find_any_unsupported_module_option();
337   if (option != nullptr) {
338     vm_exit_during_initialization("Cannot use the following option when dumping the shared archive", option);
339   }
340   // Check for an exploded module build in use with -Xshare:dump.
341   if (!Arguments::has_jimage()) {
342     vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
343   }
344 }
345 
346 bool CDSConfig::has_unsupported_runtime_module_options() {
347   assert(is_using_archive(), "this function is only used with -Xshare:{on,auto}");
348   if (ArchiveClassesAtExit != nullptr) {
349     // dynamic dumping, just return false for now.
350     // check_unsupported_dumping_properties() will be called later to check the same set of
351     // properties, and will exit the VM with the correct error message if the unsupported properties
352     // are used.
353     return false;
354   }
355   const char* option = find_any_unsupported_module_option();
356   if (option != nullptr) {
357     if (RequireSharedSpaces) {
358       warning("CDS is disabled when the %s option is specified.", option);
359     } else {
360       if (new_aot_flags_used()) {
361         log_warning(cds)("AOT cache is disabled when the %s option is specified.", option);
362       } else {
363         log_info(cds)("CDS is disabled when the %s option is specified.", option);
364       }
365     }
366     return true;
367   }
368   return false;
369 }
370 
371 #define CHECK_NEW_FLAG(f) check_new_flag(FLAG_IS_DEFAULT(f), #f)
372 
373 void CDSConfig::check_new_flag(bool new_flag_is_default, const char* new_flag_name) {
374   if (old_cds_flags_used() && !new_flag_is_default) {
375     vm_exit_during_initialization(err_msg("Option %s cannot be used at the same time with "
376                                           "-Xshare:on, -Xshare:auto, -Xshare:off, -Xshare:dump, "
377                                           "DumpLoadedClassList, SharedClassListFile, or SharedArchiveFile",
378                                           new_flag_name));
379   }
380 }
381 
382 #define CHECK_SINGLE_PATH(f) check_flag_single_path(#f, f)
383 
384 void CDSConfig::check_flag_single_path(const char* flag_name, const char* value) {
385   if (value != nullptr && num_archive_paths(value) != 1) {
386     vm_exit_during_initialization(err_msg("Option %s must specify a single file name", flag_name));
387   }
388 }
389 
390 void CDSConfig::check_aot_flags() {
391   if (!FLAG_IS_DEFAULT(DumpLoadedClassList) ||
392       !FLAG_IS_DEFAULT(SharedClassListFile) ||
393       !FLAG_IS_DEFAULT(SharedArchiveFile)) {
394     _old_cds_flags_used = true;
395   }
396 
397   // "New" AOT flags must not be mixed with "classic" flags such as -Xshare:dump
398   CHECK_NEW_FLAG(AOTCache);
399   CHECK_NEW_FLAG(AOTConfiguration);
400   CHECK_NEW_FLAG(AOTMode);
401 
402   CHECK_SINGLE_PATH(AOTCache);
403   CHECK_SINGLE_PATH(AOTConfiguration);
404 
405   if (FLAG_IS_DEFAULT(AOTCache) && AOTAdapterCaching) {
406     log_debug(aot,codecache,init)("AOTCache is not specified - AOTAdapterCaching is ignored");
407   }
408 
409   if (FLAG_IS_DEFAULT(AOTCache) && FLAG_IS_DEFAULT(AOTConfiguration) && FLAG_IS_DEFAULT(AOTMode)) {
410     // AOTCache/AOTConfiguration/AOTMode not used.
411     return;
412   } else {
413     _new_aot_flags_used = true;
414   }
415 
416   if (FLAG_IS_DEFAULT(AOTMode) || strcmp(AOTMode, "auto") == 0 || strcmp(AOTMode, "on") == 0) {
417     check_aotmode_auto_or_on();
418   } else if (strcmp(AOTMode, "off") == 0) {
419     check_aotmode_off();
420   } else {
421     // AOTMode is record or create
422     if (FLAG_IS_DEFAULT(AOTConfiguration)) {
423       vm_exit_during_initialization(err_msg("-XX:AOTMode=%s cannot be used without setting AOTConfiguration", AOTMode));
424     }
425 
426     if (strcmp(AOTMode, "record") == 0) {
427       check_aotmode_record();
428     } else {
429       assert(strcmp(AOTMode, "create") == 0, "checked by AOTModeConstraintFunc");
430       check_aotmode_create();
431     }
432   }
433 }
434 
435 void CDSConfig::check_aotmode_off() {
436   UseSharedSpaces = false;
437   RequireSharedSpaces = false;
438 }
439 
440 void CDSConfig::check_aotmode_auto_or_on() {
441   if (!FLAG_IS_DEFAULT(AOTConfiguration)) {
442     vm_exit_during_initialization("AOTConfiguration can only be used with -XX:AOTMode=record or -XX:AOTMode=create");
443   }
444 
445   UseSharedSpaces = true;
446   if (FLAG_IS_DEFAULT(AOTMode) || (strcmp(AOTMode, "auto") == 0)) {
447     RequireSharedSpaces = false;
448   } else {
449     assert(strcmp(AOTMode, "on") == 0, "already checked");
450     RequireSharedSpaces = true;
451   }
452 }
453 
454 void CDSConfig::check_aotmode_record() {
455   if (!FLAG_IS_DEFAULT(AOTCache)) {
456     vm_exit_during_initialization("AOTCache must not be specified when using -XX:AOTMode=record");
457   }
458 
459   UseSharedSpaces = false;
460   RequireSharedSpaces = false;
461   _is_dumping_static_archive = true;
462   _is_dumping_preimage_static_archive = true;
463 
464   // At VM exit, the module graph may be contaminated with program states.
465   // We will rebuild the module graph when dumping the CDS final image.
466   disable_heap_dumping();
467 }
468 
469 void CDSConfig::check_aotmode_create() {
470   if (FLAG_IS_DEFAULT(AOTCache)) {
471     vm_exit_during_initialization("AOTCache must be specified when using -XX:AOTMode=create");
472   }
473 
474   _is_dumping_final_static_archive = true;
475   UseSharedSpaces = true;
476   RequireSharedSpaces = true;
477 
478   if (!FileMapInfo::is_preimage_static_archive(AOTConfiguration)) {
479     vm_exit_during_initialization("Must be a valid AOT configuration generated by the current JVM", AOTConfiguration);
480   }
481 
482   CDSConfig::enable_dumping_static_archive();
483 }
484 
485 void CDSConfig::ergo_init_aot_paths() {
486   assert(_cds_ergo_initialize_started, "sanity");
487   if (is_dumping_static_archive()) {
488     if (is_dumping_preimage_static_archive()) {
489       _output_archive_path = AOTConfiguration;
490     } else {
491       assert(is_dumping_final_static_archive(), "must be");
492       _input_static_archive_path = AOTConfiguration;
493       _output_archive_path = AOTCache;
494     }
495   } else if (is_using_archive()) {
496     if (FLAG_IS_DEFAULT(AOTCache)) {
497       // Only -XX:AOTMode={auto,on} is specified
498       _input_static_archive_path = default_archive_path();
499     } else {
500       _input_static_archive_path = AOTCache;
501     }
502   }
503 }
504 
505 bool CDSConfig::check_vm_args_consistency(bool patch_mod_javabase, bool mode_flag_cmd_line) {
506   assert(!_cds_ergo_initialize_started, "This is called earlier than CDSConfig::ergo_initialize()");
507 
508   check_aot_flags();
509 
510   if (!FLAG_IS_DEFAULT(AOTMode)) {
511     // Using any form of the new AOTMode switch enables enhanced optimizations.
512     FLAG_SET_ERGO_IF_DEFAULT(AOTClassLinking, true);
513   }
514 
515   if (AOTClassLinking) {
516     // If AOTClassLinking is specified, enable all AOT optimizations by default.
517     FLAG_SET_ERGO_IF_DEFAULT(AOTInvokeDynamicLinking, true);
518   } else {
519     // AOTInvokeDynamicLinking depends on AOTClassLinking.
520     FLAG_SET_ERGO(AOTInvokeDynamicLinking, false);
521   }
522 
523   if (is_dumping_static_archive()) {
524     if (is_dumping_preimage_static_archive() || is_dumping_final_static_archive()) {
525       // Don't tweak execution mode
526     } else if (!mode_flag_cmd_line) {
527       // By default, -Xshare:dump runs in interpreter-only mode, which is required for deterministic archive.
528       //
529       // If your classlist is large and you don't care about deterministic dumping, you can use
530       // -Xshare:dump -Xmixed to improve dumping speed.
531       Arguments::set_mode_flags(Arguments::_int);
532     } else if (Arguments::mode() == Arguments::_comp) {
533       // -Xcomp may use excessive CPU for the test tiers. Also, -Xshare:dump runs a small and fixed set of
534       // Java code, so there's not much benefit in running -Xcomp.
535       log_info(cds)("reduced -Xcomp to -Xmixed for static dumping");
536       Arguments::set_mode_flags(Arguments::_mixed);
537     }
538 
539     // String deduplication may cause CDS to iterate the strings in different order from one
540     // run to another which resulting in non-determinstic CDS archives.
541     // Disable UseStringDeduplication while dumping CDS archive.
542     UseStringDeduplication = false;
543   }
544 
545   // RecordDynamicDumpInfo is not compatible with ArchiveClassesAtExit
546   if (ArchiveClassesAtExit != nullptr && RecordDynamicDumpInfo) {
547     jio_fprintf(defaultStream::output_stream(),
548                 "-XX:+RecordDynamicDumpInfo cannot be used with -XX:ArchiveClassesAtExit.\n");
549     return false;
550   }
551 
552   if (ArchiveClassesAtExit == nullptr && !RecordDynamicDumpInfo) {
553     disable_dumping_dynamic_archive();
554   } else {
555     enable_dumping_dynamic_archive(ArchiveClassesAtExit);
556   }
557 
558   if (AutoCreateSharedArchive) {
559     if (SharedArchiveFile == nullptr) {
560       log_warning(cds)("-XX:+AutoCreateSharedArchive requires -XX:SharedArchiveFile");
561       return false;
562     }
563     if (ArchiveClassesAtExit != nullptr) {
564       log_warning(cds)("-XX:+AutoCreateSharedArchive does not work with ArchiveClassesAtExit");
565       return false;
566     }
567   }
568 
569   if (is_using_archive() && patch_mod_javabase) {
570     Arguments::no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
571   }
572   if (is_using_archive() && has_unsupported_runtime_module_options()) {
573     UseSharedSpaces = false;
574   }
575 
576   if (is_dumping_archive()) {
577     // Always verify non-system classes during CDS dump
578     if (!BytecodeVerificationRemote) {
579       BytecodeVerificationRemote = true;
580       log_info(cds)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");
581     }
582   }
583 
584   return true;
585 }
586 
587 void CDSConfig::prepare_for_dumping() {
588   assert(CDSConfig::is_dumping_archive(), "sanity");
589 
590   if (is_dumping_dynamic_archive() && !is_using_archive()) {
591     assert(!is_dumping_static_archive(), "cannot be dumping both static and dynamic archives");
592 
593     // This could happen if SharedArchiveFile has failed to load:
594     // - -Xshare:off was specified
595     // - SharedArchiveFile points to an non-existent file.
596     // - SharedArchiveFile points to an archive that has failed CRC check
597     // - SharedArchiveFile is not specified and the VM doesn't have a compatible default archive
598 
599 #define __THEMSG " is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info."
600     if (RecordDynamicDumpInfo) {
601       log_error(cds)("-XX:+RecordDynamicDumpInfo%s", __THEMSG);
602       MetaspaceShared::unrecoverable_loading_error();
603     } else {
604       assert(ArchiveClassesAtExit != nullptr, "sanity");
605       log_warning(cds)("-XX:ArchiveClassesAtExit" __THEMSG);
606     }
607 #undef __THEMSG
608     disable_dumping_dynamic_archive();
609     return;
610   }
611 
612   check_unsupported_dumping_module_options();
613 }
614 
615 bool CDSConfig::is_dumping_classic_static_archive() {
616   return _is_dumping_static_archive &&
617     !is_dumping_preimage_static_archive() &&
618     !is_dumping_final_static_archive();
619 }
620 
621 bool CDSConfig::is_dumping_preimage_static_archive() {
622   return _is_dumping_preimage_static_archive;
623 }
624 
625 bool CDSConfig::is_dumping_final_static_archive() {
626   return _is_dumping_final_static_archive;
627 }
628 
629 void CDSConfig::enable_dumping_dynamic_archive(const char* output_path) {
630   _is_dumping_dynamic_archive = true;
631   if (output_path == nullptr) {
632     // output_path can be null when the VM is started with -XX:+RecordDynamicDumpInfo
633     // in anticipation of "jcmd VM.cds dynamic_dump", which will provide the actual
634     // output path.
635     _output_archive_path = nullptr;
636   } else {
637     _output_archive_path = os::strdup_check_oom(output_path, mtArguments);
638   }
639 }
640 
641 bool CDSConfig::allow_only_single_java_thread() {
642   // See comments in JVM_StartThread()
643   return is_dumping_classic_static_archive() || is_dumping_final_static_archive();
644 }
645 
646 bool CDSConfig::is_using_archive() {
647   return UseSharedSpaces;
648 }
649 
650 bool CDSConfig::is_logging_lambda_form_invokers() {
651   return ClassListWriter::is_enabled() || is_dumping_dynamic_archive();
652 }
653 
654 bool CDSConfig::is_dumping_regenerated_lambdaform_invokers() {
655   if (is_dumping_final_static_archive()) {
656     // No need to regenerate -- the lambda form invokers should have been regenerated
657     // in the preimage archive (if allowed)
658     return false;
659   } else if (is_dumping_dynamic_archive() && is_using_aot_linked_classes()) {
660     // The base archive has aot-linked classes that may have AOT-resolved CP references
661     // that point to the lambda form invokers in the base archive. Such pointers will
662     // be invalid if lambda form invokers are regenerated in the dynamic archive.
663     return false;
664   } else if (CDSConfig::is_dumping_method_handles()) {
665     // Work around JDK-8310831, as some methods in lambda form holder classes may not get generated.
666     return false;
667   } else {
668     return is_dumping_archive();
669   }
670 }
671 
672 void CDSConfig::stop_using_optimized_module_handling() {
673   _is_using_optimized_module_handling = false;
674   _is_dumping_full_module_graph = false; // This requires is_using_optimized_module_handling()
675   _is_using_full_module_graph = false; // This requires is_using_optimized_module_handling()
676 }
677 
678 
679 CDSConfig::DumperThreadMark::DumperThreadMark(JavaThread* current) {
680   assert(_dumper_thread == nullptr, "sanity");
681   _dumper_thread = current;
682 }
683 
684 CDSConfig::DumperThreadMark::~DumperThreadMark() {
685   assert(_dumper_thread != nullptr, "sanity");
686   _dumper_thread = nullptr;
687 }
688 
689 bool CDSConfig::current_thread_is_vm_or_dumper() {
690   Thread* t = Thread::current();
691   return t != nullptr && (t->is_VM_thread() || t == _dumper_thread);
692 }
693 
694 const char* CDSConfig::type_of_archive_being_loaded() {
695   if (is_dumping_final_static_archive()) {
696     return "AOT configuration file";
697   } else if (new_aot_flags_used()) {
698     return "AOT cache";
699   } else {
700     return "shared archive file";
701   }
702 }
703 
704 const char* CDSConfig::type_of_archive_being_written() {
705   if (is_dumping_preimage_static_archive()) {
706     return "AOT configuration file";
707   } else if (new_aot_flags_used()) {
708     return "AOT cache";
709   } else {
710     return "shared archive file";
711   }
712 }
713 
714 // If an incompatible VM options is found, return a text message that explains why
715 static const char* check_options_incompatible_with_dumping_heap() {
716 #if INCLUDE_CDS_JAVA_HEAP
717   if (!UseCompressedClassPointers) {
718     return "UseCompressedClassPointers must be true";
719   }
720 
721   // Almost all GCs support heap region dump, except ZGC (so far).
722   if (UseZGC) {
723     return "ZGC is not supported";
724   }
725 
726   return nullptr;
727 #else
728   return "JVM not configured for writing Java heap objects";
729 #endif
730 }
731 
732 void CDSConfig::log_reasons_for_not_dumping_heap() {
733   const char* reason;
734 
735   assert(!is_dumping_heap(), "sanity");
736 
737   if (_disable_heap_dumping) {
738     reason = "Programmatically disabled";
739   } else {
740     reason = check_options_incompatible_with_dumping_heap();
741   }
742 
743   assert(reason != nullptr, "sanity");
744   log_info(cds)("Archived java heap is not supported: %s", reason);
745 }
746 
747 // This is *Legacy* optimization for lambdas before JEP 483. May be removed in the future.
748 bool CDSConfig::is_dumping_lambdas_in_legacy_mode() {
749   return !is_dumping_method_handles();
750 }
751 
752 #if INCLUDE_CDS_JAVA_HEAP
753 bool CDSConfig::are_vm_options_incompatible_with_dumping_heap() {
754   return check_options_incompatible_with_dumping_heap() != nullptr;
755 }
756 
757 bool CDSConfig::is_dumping_heap() {
758   if (!(is_dumping_classic_static_archive() || is_dumping_final_static_archive())
759       || are_vm_options_incompatible_with_dumping_heap()
760       || _disable_heap_dumping) {
761     return false;
762   }
763   return true;
764 }
765 
766 bool CDSConfig::is_loading_heap() {
767   return ArchiveHeapLoader::is_in_use();
768 }
769 
770 bool CDSConfig::is_using_full_module_graph() {
771   if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
772     return true;
773   }
774 
775   if (!_is_using_full_module_graph) {
776     return false;
777   }
778 
779   if (is_using_archive() && ArchiveHeapLoader::can_use()) {
780     // Classes used by the archived full module graph are loaded in JVMTI early phase.
781     assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
782            "CDS should be disabled if early class hooks are enabled");
783     return true;
784   } else {
785     _is_using_full_module_graph = false;
786     return false;
787   }
788 }
789 
790 void CDSConfig::stop_dumping_full_module_graph(const char* reason) {
791   if (_is_dumping_full_module_graph) {
792     _is_dumping_full_module_graph = false;
793     if (reason != nullptr) {
794       log_info(cds)("full module graph cannot be dumped: %s", reason);
795     }
796   }
797 }
798 
799 void CDSConfig::stop_using_full_module_graph(const char* reason) {
800   assert(!ClassLoaderDataShared::is_full_module_graph_loaded(), "you call this function too late!");
801   if (_is_using_full_module_graph) {
802     _is_using_full_module_graph = false;
803     if (reason != nullptr) {
804       log_info(cds)("full module graph cannot be loaded: %s", reason);
805     }
806   }
807 }
808 
809 bool CDSConfig::is_dumping_aot_linked_classes() {
810   if (is_dumping_preimage_static_archive()) {
811     return false;
812   } else if (is_dumping_dynamic_archive()) {
813     return is_using_full_module_graph() && AOTClassLinking;
814   } else if (is_dumping_static_archive()) {
815     return is_dumping_full_module_graph() && AOTClassLinking;
816   } else {
817     return false;
818   }
819 }
820 
821 bool CDSConfig::is_using_aot_linked_classes() {
822   // Make sure we have the exact same module graph as in the assembly phase, or else
823   // some aot-linked classes may not be visible so cannot be loaded.
824   return is_using_full_module_graph() && _has_aot_linked_classes;
825 }
826 
827 void CDSConfig::set_has_aot_linked_classes(bool has_aot_linked_classes) {
828   _has_aot_linked_classes |= has_aot_linked_classes;
829 }
830 
831 bool CDSConfig::is_initing_classes_at_dump_time() {
832   return is_dumping_heap() && is_dumping_aot_linked_classes();
833 }
834 
835 bool CDSConfig::is_dumping_invokedynamic() {
836   // Requires is_dumping_aot_linked_classes(). Otherwise the classes of some archived heap
837   // objects used by the archive indy callsites may be replaced at runtime.
838   return AOTInvokeDynamicLinking && is_dumping_aot_linked_classes() && is_dumping_heap();
839 }
840 
841 // When we are dumping aot-linked classes and we are able to write archived heap objects, we automatically
842 // enable the archiving of MethodHandles. This will in turn enable the archiving of MethodTypes and hidden
843 // classes that are used in the implementation of MethodHandles.
844 // Archived MethodHandles are required for higher-level optimizations such as AOT resolution of invokedynamic
845 // and dynamic proxies.
846 bool CDSConfig::is_dumping_method_handles() {
847   return is_initing_classes_at_dump_time();
848 }
849 
850 #endif // INCLUDE_CDS_JAVA_HEAP
851 
852 // AOT code generation and its archiving is disabled by default.
853 // We enable it only in the final image dump after the metadata and heap are dumped.
854 // This affects only JITed code because it may have embedded oops and metadata pointers
855 // which AOT code encodes as offsets in final CDS archive regions.
856 
857 static bool _is_dumping_aot_code = false;
858 
859 bool CDSConfig::is_dumping_aot_code() {
860   return _is_dumping_aot_code;
861 }
862 
863 void CDSConfig::disable_dumping_aot_code() {
864   _is_dumping_aot_code = false;
865 }
866 
867 void CDSConfig::enable_dumping_aot_code() {
868   _is_dumping_aot_code = true;
869 }