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) && FLAG_IS_DEFAULT(AOTConfiguration) && FLAG_IS_DEFAULT(AOTMode)) {
406     // AOTCache/AOTConfiguration/AOTMode not used.
407     return;
408   } else {
409     _new_aot_flags_used = true;
410   }
411 
412   if (FLAG_IS_DEFAULT(AOTMode) || strcmp(AOTMode, "auto") == 0 || strcmp(AOTMode, "on") == 0) {
413     check_aotmode_auto_or_on();
414   } else if (strcmp(AOTMode, "off") == 0) {
415     check_aotmode_off();
416   } else {
417     // AOTMode is record or create
418     if (FLAG_IS_DEFAULT(AOTConfiguration)) {
419       vm_exit_during_initialization(err_msg("-XX:AOTMode=%s cannot be used without setting AOTConfiguration", AOTMode));
420     }
421 
422     if (strcmp(AOTMode, "record") == 0) {
423       check_aotmode_record();
424     } else {
425       assert(strcmp(AOTMode, "create") == 0, "checked by AOTModeConstraintFunc");
426       check_aotmode_create();
427     }
428   }
429 }
430 
431 void CDSConfig::check_aotmode_off() {
432   UseSharedSpaces = false;
433   RequireSharedSpaces = false;
434 }
435 
436 void CDSConfig::check_aotmode_auto_or_on() {
437   if (!FLAG_IS_DEFAULT(AOTConfiguration)) {
438     vm_exit_during_initialization("AOTConfiguration can only be used with -XX:AOTMode=record or -XX:AOTMode=create");
439   }
440 
441   UseSharedSpaces = true;
442   if (FLAG_IS_DEFAULT(AOTMode) || (strcmp(AOTMode, "auto") == 0)) {
443     RequireSharedSpaces = false;
444   } else {
445     assert(strcmp(AOTMode, "on") == 0, "already checked");
446     RequireSharedSpaces = true;
447   }
448 }
449 
450 void CDSConfig::check_aotmode_record() {
451   if (!FLAG_IS_DEFAULT(AOTCache)) {
452     vm_exit_during_initialization("AOTCache must not be specified when using -XX:AOTMode=record");
453   }
454 
455   UseSharedSpaces = false;
456   RequireSharedSpaces = false;
457   _is_dumping_static_archive = true;
458   _is_dumping_preimage_static_archive = true;
459 
460   // At VM exit, the module graph may be contaminated with program states.
461   // We will rebuild the module graph when dumping the CDS final image.
462   disable_heap_dumping();
463 }
464 
465 void CDSConfig::check_aotmode_create() {
466   if (FLAG_IS_DEFAULT(AOTCache)) {
467     vm_exit_during_initialization("AOTCache must be specified when using -XX:AOTMode=create");
468   }
469 
470   _is_dumping_final_static_archive = true;
471   UseSharedSpaces = true;
472   RequireSharedSpaces = true;
473 
474   if (!FileMapInfo::is_preimage_static_archive(AOTConfiguration)) {
475     vm_exit_during_initialization("Must be a valid AOT configuration generated by the current JVM", AOTConfiguration);
476   }
477 
478   CDSConfig::enable_dumping_static_archive();
479 }
480 
481 void CDSConfig::ergo_init_aot_paths() {
482   assert(_cds_ergo_initialize_started, "sanity");
483   if (is_dumping_static_archive()) {
484     if (is_dumping_preimage_static_archive()) {
485       _output_archive_path = AOTConfiguration;
486     } else {
487       assert(is_dumping_final_static_archive(), "must be");
488       _input_static_archive_path = AOTConfiguration;
489       _output_archive_path = AOTCache;
490     }
491   } else if (is_using_archive()) {
492     if (FLAG_IS_DEFAULT(AOTCache)) {
493       // Only -XX:AOTMode={auto,on} is specified
494       _input_static_archive_path = default_archive_path();
495     } else {
496       _input_static_archive_path = AOTCache;
497     }
498   }
499 }
500 
501 bool CDSConfig::check_vm_args_consistency(bool patch_mod_javabase, bool mode_flag_cmd_line) {
502   assert(!_cds_ergo_initialize_started, "This is called earlier than CDSConfig::ergo_initialize()");
503 
504   check_aot_flags();
505 
506   if (!FLAG_IS_DEFAULT(AOTMode)) {
507     // Using any form of the new AOTMode switch enables enhanced optimizations.
508     FLAG_SET_ERGO_IF_DEFAULT(AOTClassLinking, true);
509   }
510 
511   if (AOTClassLinking) {
512     // If AOTClassLinking is specified, enable all AOT optimizations by default.
513     FLAG_SET_ERGO_IF_DEFAULT(AOTInvokeDynamicLinking, true);
514   } else {
515     // AOTInvokeDynamicLinking depends on AOTClassLinking.
516     FLAG_SET_ERGO(AOTInvokeDynamicLinking, false);
517   }
518 
519   if (is_dumping_static_archive()) {
520     if (is_dumping_preimage_static_archive()) {
521       // Don't tweak execution mode
522     } else if (!mode_flag_cmd_line) {
523       // By default, -Xshare:dump runs in interpreter-only mode, which is required for deterministic archive.
524       //
525       // If your classlist is large and you don't care about deterministic dumping, you can use
526       // -Xshare:dump -Xmixed to improve dumping speed.
527       Arguments::set_mode_flags(Arguments::_int);
528     } else if (Arguments::mode() == Arguments::_comp) {
529       // -Xcomp may use excessive CPU for the test tiers. Also, -Xshare:dump runs a small and fixed set of
530       // Java code, so there's not much benefit in running -Xcomp.
531       log_info(cds)("reduced -Xcomp to -Xmixed for static dumping");
532       Arguments::set_mode_flags(Arguments::_mixed);
533     }
534 
535     // String deduplication may cause CDS to iterate the strings in different order from one
536     // run to another which resulting in non-determinstic CDS archives.
537     // Disable UseStringDeduplication while dumping CDS archive.
538     UseStringDeduplication = false;
539   }
540 
541   // RecordDynamicDumpInfo is not compatible with ArchiveClassesAtExit
542   if (ArchiveClassesAtExit != nullptr && RecordDynamicDumpInfo) {
543     jio_fprintf(defaultStream::output_stream(),
544                 "-XX:+RecordDynamicDumpInfo cannot be used with -XX:ArchiveClassesAtExit.\n");
545     return false;
546   }
547 
548   if (ArchiveClassesAtExit == nullptr && !RecordDynamicDumpInfo) {
549     disable_dumping_dynamic_archive();
550   } else {
551     enable_dumping_dynamic_archive(ArchiveClassesAtExit);
552   }
553 
554   if (AutoCreateSharedArchive) {
555     if (SharedArchiveFile == nullptr) {
556       log_warning(cds)("-XX:+AutoCreateSharedArchive requires -XX:SharedArchiveFile");
557       return false;
558     }
559     if (ArchiveClassesAtExit != nullptr) {
560       log_warning(cds)("-XX:+AutoCreateSharedArchive does not work with ArchiveClassesAtExit");
561       return false;
562     }
563   }
564 
565   if (is_using_archive() && patch_mod_javabase) {
566     Arguments::no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
567   }
568   if (is_using_archive() && has_unsupported_runtime_module_options()) {
569     UseSharedSpaces = false;
570   }
571 
572   if (is_dumping_archive()) {
573     // Always verify non-system classes during CDS dump
574     if (!BytecodeVerificationRemote) {
575       BytecodeVerificationRemote = true;
576       log_info(cds)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");
577     }
578   }
579 
580   return true;
581 }
582 
583 void CDSConfig::prepare_for_dumping() {
584   assert(CDSConfig::is_dumping_archive(), "sanity");
585 
586   if (is_dumping_dynamic_archive() && !is_using_archive()) {
587     assert(!is_dumping_static_archive(), "cannot be dumping both static and dynamic archives");
588 
589     // This could happen if SharedArchiveFile has failed to load:
590     // - -Xshare:off was specified
591     // - SharedArchiveFile points to an non-existent file.
592     // - SharedArchiveFile points to an archive that has failed CRC check
593     // - SharedArchiveFile is not specified and the VM doesn't have a compatible default archive
594 
595 #define __THEMSG " is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info."
596     if (RecordDynamicDumpInfo) {
597       log_error(cds)("-XX:+RecordDynamicDumpInfo%s", __THEMSG);
598       MetaspaceShared::unrecoverable_loading_error();
599     } else {
600       assert(ArchiveClassesAtExit != nullptr, "sanity");
601       log_warning(cds)("-XX:ArchiveClassesAtExit" __THEMSG);
602     }
603 #undef __THEMSG
604     disable_dumping_dynamic_archive();
605     return;
606   }
607 
608   check_unsupported_dumping_module_options();
609 }
610 
611 bool CDSConfig::is_dumping_classic_static_archive() {
612   return _is_dumping_static_archive &&
613     !is_dumping_preimage_static_archive() &&
614     !is_dumping_final_static_archive();
615 }
616 
617 bool CDSConfig::is_dumping_preimage_static_archive() {
618   return _is_dumping_preimage_static_archive;
619 }
620 
621 bool CDSConfig::is_dumping_final_static_archive() {
622   return _is_dumping_final_static_archive;
623 }
624 
625 void CDSConfig::enable_dumping_dynamic_archive(const char* output_path) {
626   _is_dumping_dynamic_archive = true;
627   if (output_path == nullptr) {
628     // output_path can be null when the VM is started with -XX:+RecordDynamicDumpInfo
629     // in anticipation of "jcmd VM.cds dynamic_dump", which will provide the actual
630     // output path.
631     _output_archive_path = nullptr;
632   } else {
633     _output_archive_path = os::strdup_check_oom(output_path, mtArguments);
634   }
635 }
636 
637 bool CDSConfig::allow_only_single_java_thread() {
638   // See comments in JVM_StartThread()
639   return is_dumping_classic_static_archive() || is_dumping_final_static_archive();
640 }
641 
642 bool CDSConfig::is_using_archive() {
643   return UseSharedSpaces;
644 }
645 
646 bool CDSConfig::is_logging_lambda_form_invokers() {
647   return ClassListWriter::is_enabled() || is_dumping_dynamic_archive();
648 }
649 
650 bool CDSConfig::is_dumping_regenerated_lambdaform_invokers() {
651   if (is_dumping_final_static_archive()) {
652     // No need to regenerate -- the lambda form invokers should have been regenerated
653     // in the preimage archive (if allowed)
654     return false;
655   } else if (is_dumping_dynamic_archive() && is_using_aot_linked_classes()) {
656     // The base archive has aot-linked classes that may have AOT-resolved CP references
657     // that point to the lambda form invokers in the base archive. Such pointers will
658     // be invalid if lambda form invokers are regenerated in the dynamic archive.
659     return false;
660   } else if (CDSConfig::is_dumping_method_handles()) {
661     // Work around JDK-8310831, as some methods in lambda form holder classes may not get generated.
662     return false;
663   } else {
664     return is_dumping_archive();
665   }
666 }
667 
668 void CDSConfig::stop_using_optimized_module_handling() {
669   _is_using_optimized_module_handling = false;
670   _is_dumping_full_module_graph = false; // This requires is_using_optimized_module_handling()
671   _is_using_full_module_graph = false; // This requires is_using_optimized_module_handling()
672 }
673 
674 
675 CDSConfig::DumperThreadMark::DumperThreadMark(JavaThread* current) {
676   assert(_dumper_thread == nullptr, "sanity");
677   _dumper_thread = current;
678 }
679 
680 CDSConfig::DumperThreadMark::~DumperThreadMark() {
681   assert(_dumper_thread != nullptr, "sanity");
682   _dumper_thread = nullptr;
683 }
684 
685 bool CDSConfig::current_thread_is_vm_or_dumper() {
686   Thread* t = Thread::current();
687   return t != nullptr && (t->is_VM_thread() || t == _dumper_thread);
688 }
689 
690 const char* CDSConfig::type_of_archive_being_loaded() {
691   if (is_dumping_final_static_archive()) {
692     return "AOT configuration file";
693   } else if (new_aot_flags_used()) {
694     return "AOT cache";
695   } else {
696     return "shared archive file";
697   }
698 }
699 
700 const char* CDSConfig::type_of_archive_being_written() {
701   if (is_dumping_preimage_static_archive()) {
702     return "AOT configuration file";
703   } else if (new_aot_flags_used()) {
704     return "AOT cache";
705   } else {
706     return "shared archive file";
707   }
708 }
709 
710 // If an incompatible VM options is found, return a text message that explains why
711 static const char* check_options_incompatible_with_dumping_heap() {
712 #if INCLUDE_CDS_JAVA_HEAP
713   if (!UseCompressedClassPointers) {
714     return "UseCompressedClassPointers must be true";
715   }
716 
717   // Almost all GCs support heap region dump, except ZGC (so far).
718   if (UseZGC) {
719     return "ZGC is not supported";
720   }
721 
722   return nullptr;
723 #else
724   return "JVM not configured for writing Java heap objects";
725 #endif
726 }
727 
728 void CDSConfig::log_reasons_for_not_dumping_heap() {
729   const char* reason;
730 
731   assert(!is_dumping_heap(), "sanity");
732 
733   if (_disable_heap_dumping) {
734     reason = "Programmatically disabled";
735   } else {
736     reason = check_options_incompatible_with_dumping_heap();
737   }
738 
739   assert(reason != nullptr, "sanity");
740   log_info(cds)("Archived java heap is not supported: %s", reason);
741 }
742 
743 // This is *Legacy* optimization for lambdas before JEP 483. May be removed in the future.
744 bool CDSConfig::is_dumping_lambdas_in_legacy_mode() {
745   return !is_dumping_method_handles();
746 }
747 
748 #if INCLUDE_CDS_JAVA_HEAP
749 bool CDSConfig::are_vm_options_incompatible_with_dumping_heap() {
750   return check_options_incompatible_with_dumping_heap() != nullptr;
751 }
752 
753 bool CDSConfig::is_dumping_heap() {
754   if (!(is_dumping_classic_static_archive() || is_dumping_final_static_archive())
755       || are_vm_options_incompatible_with_dumping_heap()
756       || _disable_heap_dumping) {
757     return false;
758   }
759   return true;
760 }
761 
762 bool CDSConfig::is_loading_heap() {
763   return ArchiveHeapLoader::is_in_use();
764 }
765 
766 bool CDSConfig::is_using_full_module_graph() {
767   if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
768     return true;
769   }
770 
771   if (!_is_using_full_module_graph) {
772     return false;
773   }
774 
775   if (is_using_archive() && ArchiveHeapLoader::can_use()) {
776     // Classes used by the archived full module graph are loaded in JVMTI early phase.
777     assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
778            "CDS should be disabled if early class hooks are enabled");
779     return true;
780   } else {
781     _is_using_full_module_graph = false;
782     return false;
783   }
784 }
785 
786 void CDSConfig::stop_dumping_full_module_graph(const char* reason) {
787   if (_is_dumping_full_module_graph) {
788     _is_dumping_full_module_graph = false;
789     if (reason != nullptr) {
790       log_info(cds)("full module graph cannot be dumped: %s", reason);
791     }
792   }
793 }
794 
795 void CDSConfig::stop_using_full_module_graph(const char* reason) {
796   assert(!ClassLoaderDataShared::is_full_module_graph_loaded(), "you call this function too late!");
797   if (_is_using_full_module_graph) {
798     _is_using_full_module_graph = false;
799     if (reason != nullptr) {
800       log_info(cds)("full module graph cannot be loaded: %s", reason);
801     }
802   }
803 }
804 
805 bool CDSConfig::is_dumping_aot_linked_classes() {
806   if (is_dumping_preimage_static_archive()) {
807     return false;
808   } else if (is_dumping_dynamic_archive()) {
809     return is_using_full_module_graph() && AOTClassLinking;
810   } else if (is_dumping_static_archive()) {
811     return is_dumping_full_module_graph() && AOTClassLinking;
812   } else {
813     return false;
814   }
815 }
816 
817 bool CDSConfig::is_using_aot_linked_classes() {
818   // Make sure we have the exact same module graph as in the assembly phase, or else
819   // some aot-linked classes may not be visible so cannot be loaded.
820   return is_using_full_module_graph() && _has_aot_linked_classes;
821 }
822 
823 void CDSConfig::set_has_aot_linked_classes(bool has_aot_linked_classes) {
824   _has_aot_linked_classes |= has_aot_linked_classes;
825 }
826 
827 bool CDSConfig::is_initing_classes_at_dump_time() {
828   return is_dumping_heap() && is_dumping_aot_linked_classes();
829 }
830 
831 bool CDSConfig::is_dumping_invokedynamic() {
832   // Requires is_dumping_aot_linked_classes(). Otherwise the classes of some archived heap
833   // objects used by the archive indy callsites may be replaced at runtime.
834   return AOTInvokeDynamicLinking && is_dumping_aot_linked_classes() && is_dumping_heap();
835 }
836 
837 // When we are dumping aot-linked classes and we are able to write archived heap objects, we automatically
838 // enable the archiving of MethodHandles. This will in turn enable the archiving of MethodTypes and hidden
839 // classes that are used in the implementation of MethodHandles.
840 // Archived MethodHandles are required for higher-level optimizations such as AOT resolution of invokedynamic
841 // and dynamic proxies.
842 bool CDSConfig::is_dumping_method_handles() {
843   return is_initing_classes_at_dump_time();
844 }
845 
846 #endif // INCLUDE_CDS_JAVA_HEAP