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