1 /*
  2  * Copyright (c) 2023, 2024, 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 "precompiled.hpp"
 26 #include "cds/archiveHeapLoader.hpp"
 27 #include "cds/cdsConfig.hpp"
 28 #include "cds/cds_globals.hpp"
 29 #include "cds/classListWriter.hpp"
 30 #include "cds/heapShared.hpp"
 31 #include "cds/metaspaceShared.hpp"
 32 #include "classfile/classLoaderDataShared.hpp"
 33 #include "classfile/moduleEntry.hpp"
 34 #include "classfile/systemDictionaryShared.hpp"
 35 #include "include/jvm_io.h"
 36 #include "logging/log.hpp"
 37 #include "prims/jvmtiExport.hpp"
 38 #include "memory/universe.hpp"
 39 #include "runtime/arguments.hpp"
 40 #include "runtime/globals_extension.hpp"
 41 #include "runtime/java.hpp"
 42 #include "utilities/defaultStream.hpp"
 43 
 44 bool CDSConfig::_is_dumping_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_preloaded_classes = false;
 50 bool CDSConfig::_is_loading_invokedynamic = false;
 51 bool CDSConfig::_is_loading_packages = false;
 52 
 53 char* CDSConfig::_default_archive_path = nullptr;
 54 char* CDSConfig::_static_archive_path = nullptr;
 55 char* CDSConfig::_dynamic_archive_path = nullptr;
 56 
 57 int CDSConfig::get_status() {
 58   assert(Universe::is_fully_initialized(), "status is finalized only after Universe is initialized");
 59   return (is_dumping_archive()              ? IS_DUMPING_ARCHIVE : 0) |
 60          (is_dumping_static_archive()       ? IS_DUMPING_STATIC_ARCHIVE : 0) |
 61          (is_logging_lambda_form_invokers() ? IS_LOGGING_LAMBDA_FORM_INVOKERS : 0) |
 62          (is_using_archive()                ? IS_USING_ARCHIVE : 0) |
 63          (is_dumping_heap()                 ? IS_DUMPING_HEAP : 0) |
 64          (is_tracing_dynamic_proxy()        ? IS_LOGGING_DYNAMIC_PROXIES : 0) |
 65          (is_dumping_packages()             ? IS_DUMPING_PACKAGES : 0);
 66 }
 67 
 68 
 69 void CDSConfig::initialize() {
 70   if (is_dumping_static_archive() && !is_dumping_final_static_archive()) {
 71     if (RequireSharedSpaces) {
 72       warning("Cannot dump shared archive while using shared archive");
 73     }
 74     UseSharedSpaces = false;
 75   }
 76 
 77   // Initialize shared archive paths which could include both base and dynamic archive paths
 78   // This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.
 79   //
 80   // UseSharedSpaces may be disabled if -XX:SharedArchiveFile is invalid.
 81   if (is_dumping_static_archive() || UseSharedSpaces) {
 82     init_shared_archive_paths();
 83   }
 84 
 85   if (!is_dumping_heap()) {
 86     _is_dumping_full_module_graph = false;
 87   }
 88 }
 89 
 90 char* CDSConfig::default_archive_path() {
 91   if (_default_archive_path == nullptr) {
 92     char jvm_path[JVM_MAXPATHLEN];
 93     os::jvm_path(jvm_path, sizeof(jvm_path));
 94     char *end = strrchr(jvm_path, *os::file_separator());
 95     if (end != nullptr) *end = '\0';
 96     size_t jvm_path_len = strlen(jvm_path);
 97     size_t file_sep_len = strlen(os::file_separator());
 98     const size_t len = jvm_path_len + file_sep_len + 20;
 99     _default_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);
100     jio_snprintf(_default_archive_path, len,
101                 LP64_ONLY(!UseCompressedOops ? "%s%sclasses_nocoops.jsa":) "%s%sclasses.jsa",
102                 jvm_path, os::file_separator());
103   }
104   return _default_archive_path;
105 }
106 
107 int CDSConfig::num_archives(const char* archive_path) {
108   if (archive_path == nullptr) {
109     return 0;
110   }
111   int npaths = 1;
112   char* p = (char*)archive_path;
113   while (*p != '\0') {
114     if (*p == os::path_separator()[0]) {
115       npaths++;
116     }
117     p++;
118   }
119   return npaths;
120 }
121 
122 void CDSConfig::extract_shared_archive_paths(const char* archive_path,
123                                              char** base_archive_path,
124                                              char** top_archive_path) {
125   char* begin_ptr = (char*)archive_path;
126   char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);
127   if (end_ptr == nullptr || end_ptr == begin_ptr) {
128     vm_exit_during_initialization("Base archive was not specified", archive_path);
129   }
130   size_t len = end_ptr - begin_ptr;
131   char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
132   strncpy(cur_path, begin_ptr, len);
133   cur_path[len] = '\0';
134   *base_archive_path = cur_path;
135 
136   begin_ptr = ++end_ptr;
137   if (*begin_ptr == '\0') {
138     vm_exit_during_initialization("Top archive was not specified", archive_path);
139   }
140   end_ptr = strchr(begin_ptr, '\0');
141   assert(end_ptr != nullptr, "sanity");
142   len = end_ptr - begin_ptr;
143   cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
144   strncpy(cur_path, begin_ptr, len + 1);
145   *top_archive_path = cur_path;
146 }
147 
148 static void set_new_workflow_default_CachedCodeFile() {
149   size_t len = strlen(CacheDataStore) + 6;
150   char* file = AllocateHeap(len, mtArguments);
151   jio_snprintf(file, len, "%s.code", CacheDataStore);
152   FLAG_SET_ERGO(CachedCodeFile, file);
153 }
154 
155 void CDSConfig::init_shared_archive_paths() {
156   if (ArchiveClassesAtExit != nullptr) {
157     assert(!RecordDynamicDumpInfo, "already checked");
158     if (is_dumping_static_archive()) {
159       vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");
160     }
161     check_unsupported_dumping_module_options();
162 
163     if (os::same_files(default_archive_path(), ArchiveClassesAtExit)) {
164       vm_exit_during_initialization(
165         "Cannot specify the default CDS archive for -XX:ArchiveClassesAtExit", default_archive_path());
166     }
167   }
168 
169   if (SharedArchiveFile == nullptr) {
170     _static_archive_path = default_archive_path();
171   } else {
172     int archives = num_archives(SharedArchiveFile);
173     assert(archives > 0, "must be");
174 
175     if (is_dumping_archive() && archives > 1) {
176       vm_exit_during_initialization(
177         "Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");
178     }
179 
180     if (CDSPreimage != nullptr && archives > 1) {
181       vm_exit_during_initialization("CDSPreimage must point to a single file", CDSPreimage);
182     }
183 
184     if (is_dumping_static_archive()) {
185       assert(archives == 1, "must be");
186       // Static dump is simple: only one archive is allowed in SharedArchiveFile. This file
187       // will be overwritten no matter regardless of its contents
188       _static_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);
189     } else {
190       // SharedArchiveFile may specify one or two files. In case (c), the path for base.jsa
191       // is read from top.jsa
192       //    (a) 1 file:  -XX:SharedArchiveFile=base.jsa
193       //    (b) 2 files: -XX:SharedArchiveFile=base.jsa:top.jsa
194       //    (c) 2 files: -XX:SharedArchiveFile=top.jsa
195       //
196       // However, if either RecordDynamicDumpInfo or ArchiveClassesAtExit is used, we do not
197       // allow cases (b) and (c). Case (b) is already checked above.
198 
199       if (archives > 2) {
200         vm_exit_during_initialization(
201           "Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");
202       }
203       if (archives == 1) {
204         char* base_archive_path = nullptr;
205         bool success =
206           FileMapInfo::get_base_archive_name_from_header(SharedArchiveFile, &base_archive_path);
207         if (!success) {
208           if (CDSPreimage != nullptr) {
209             vm_exit_during_initialization("Unable to map shared spaces from CDSPreimage", CDSPreimage);
210           }
211 
212           // If +AutoCreateSharedArchive and the specified shared archive does not exist,
213           // regenerate the dynamic archive base on default archive.
214           if (AutoCreateSharedArchive && !os::file_exists(SharedArchiveFile)) {
215             enable_dumping_dynamic_archive();
216             ArchiveClassesAtExit = const_cast<char *>(SharedArchiveFile);
217             _static_archive_path = default_archive_path();
218             SharedArchiveFile = nullptr;
219           } else {
220             if (AutoCreateSharedArchive) {
221               warning("-XX:+AutoCreateSharedArchive is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
222               AutoCreateSharedArchive = false;
223             }
224             Arguments::no_shared_spaces("invalid archive");
225           }
226         } else if (base_archive_path == nullptr) {
227           // User has specified a single archive, which is a static archive.
228           _static_archive_path = const_cast<char *>(SharedArchiveFile);
229         } else {
230           // User has specified a single archive, which is a dynamic archive.
231           _dynamic_archive_path = const_cast<char *>(SharedArchiveFile);
232           _static_archive_path = base_archive_path; // has been c-heap allocated.
233         }
234       } else {
235         extract_shared_archive_paths((const char*)SharedArchiveFile,
236                                       &_static_archive_path, &_dynamic_archive_path);
237         if (_static_archive_path == nullptr) {
238           assert(_dynamic_archive_path == nullptr, "must be");
239           Arguments::no_shared_spaces("invalid archive");
240         }
241       }
242 
243       if (_dynamic_archive_path != nullptr) {
244         // Check for case (c)
245         if (RecordDynamicDumpInfo) {
246           vm_exit_during_initialization("-XX:+RecordDynamicDumpInfo is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
247                                         SharedArchiveFile);
248         }
249         if (ArchiveClassesAtExit != nullptr) {
250           vm_exit_during_initialization("-XX:ArchiveClassesAtExit is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
251                                         SharedArchiveFile);
252         }
253       }
254 
255       if (ArchiveClassesAtExit != nullptr && os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {
256           vm_exit_during_initialization(
257             "Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",
258             SharedArchiveFile);
259       }
260     }
261   }
262 }
263 
264 void CDSConfig::check_internal_module_property(const char* key, const char* value) {
265   if (Arguments::is_internal_module_property(key)) {
266     stop_using_optimized_module_handling();
267     log_info(cds)("optimized module handling: disabled due to incompatible property: %s=%s", key, value);
268   }
269 }
270 
271 void CDSConfig::check_incompatible_property(const char* key, const char* value) {
272   static const char* incompatible_properties[] = {
273     "java.system.class.loader",
274     "jdk.module.showModuleResolution",
275     "jdk.module.validation"
276   };
277 
278   for (const char* property : incompatible_properties) {
279     if (strcmp(key, property) == 0) {
280       stop_dumping_full_module_graph();
281       stop_using_full_module_graph();
282       log_info(cds)("full module graph: disabled due to incompatible property: %s=%s", key, value);
283       break;
284     }
285   }
286 
287 }
288 
289 // Returns any JVM command-line option, such as "--patch-module", that's not supported by CDS.
290 static const char* find_any_unsupported_module_option() {
291   // Note that arguments.cpp has translated the command-line options into properties. If we find an
292   // unsupported property, translate it back to its command-line option for better error reporting.
293 
294   // The following properties are checked by Arguments::is_internal_module_property() and cannot be
295   // directly specified in the command-line.
296   static const char* unsupported_module_properties[] = {
297     "jdk.module.limitmods",
298     "jdk.module.upgrade.path",
299     "jdk.module.patch.0"
300   };
301   static const char* unsupported_module_options[] = {
302     "--limit-modules",
303     "--upgrade-module-path",
304     "--patch-module"
305   };
306 
307   assert(ARRAY_SIZE(unsupported_module_properties) == ARRAY_SIZE(unsupported_module_options), "must be");
308   SystemProperty* sp = Arguments::system_properties();
309   while (sp != nullptr) {
310     for (uint i = 0; i < ARRAY_SIZE(unsupported_module_properties); i++) {
311       if (strcmp(sp->key(), unsupported_module_properties[i]) == 0) {
312         return unsupported_module_options[i];
313       }
314     }
315     sp = sp->next();
316   }
317 
318   return nullptr; // not found
319 }
320 
321 void CDSConfig::check_unsupported_dumping_module_options() {
322   assert(is_dumping_archive(), "this function is only used with CDS dump time");
323   const char* option = find_any_unsupported_module_option();
324   if (option != nullptr) {
325     vm_exit_during_initialization("Cannot use the following option when dumping the shared archive", option);
326   }
327   // Check for an exploded module build in use with -Xshare:dump.
328   if (!Arguments::has_jimage()) {
329     vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
330   }
331 }
332 
333 bool CDSConfig::has_unsupported_runtime_module_options() {
334   assert(UseSharedSpaces, "this function is only used with -Xshare:{on,auto}");
335   if (ArchiveClassesAtExit != nullptr) {
336     // dynamic dumping, just return false for now.
337     // check_unsupported_dumping_properties() will be called later to check the same set of
338     // properties, and will exit the VM with the correct error message if the unsupported properties
339     // are used.
340     return false;
341   }
342   const char* option = find_any_unsupported_module_option();
343   if (option != nullptr) {
344     if (RequireSharedSpaces) {
345       warning("CDS is disabled when the %s option is specified.", option);
346     } else {
347       log_info(cds)("CDS is disabled when the %s option is specified.", option);
348     }
349     return true;
350   }
351   return false;
352 }
353 
354 bool CDSConfig::check_vm_args_consistency(bool patch_mod_javabase, bool mode_flag_cmd_line) {
355   if (CacheDataStore != nullptr) {
356     if (FLAG_IS_DEFAULT(PreloadSharedClasses)) {
357       // New workflow - enable PreloadSharedClasses by default.
358       // TODO: make new workflow work, even when PreloadSharedClasses is false.
359       //
360       // NOTE: in old workflow, we cannot enable PreloadSharedClasses by default. That
361       // should be an opt-in option, per JEP nnn.
362       FLAG_SET_ERGO(PreloadSharedClasses, true);
363     }
364 
365     if (SharedArchiveFile != nullptr) {
366       vm_exit_during_initialization("CacheDataStore and SharedArchiveFile cannot be both specified");
367     }
368     if (!PreloadSharedClasses) {
369       // TODO: in the forked JVM, we should ensure all classes are loaded from the hotspot.cds.preimage.
370       // PreloadSharedClasses only loads the classes for built-in loaders. We need to load the classes
371       // for custom loaders as well.
372       vm_exit_during_initialization("CacheDataStore requires PreloadSharedClasses");
373     }
374 
375     if (CDSPreimage == nullptr) {
376       if (os::file_exists(CacheDataStore) /* && TODO: CDS file is valid*/) {
377         // The CacheDataStore is already up to date. Use it. Also turn on cached code by default.
378         SharedArchiveFile = CacheDataStore;
379         FLAG_SET_ERGO_IF_DEFAULT(ReplayTraining, true);
380         FLAG_SET_ERGO_IF_DEFAULT(LoadCachedCode, true);
381         if (LoadCachedCode && FLAG_IS_DEFAULT(CachedCodeFile)) {
382           set_new_workflow_default_CachedCodeFile();
383         }
384       } else {
385         // The preimage dumping phase -- run the app and write the preimage file
386         size_t len = strlen(CacheDataStore) + 10;
387         char* preimage = AllocateHeap(len, mtArguments);
388         jio_snprintf(preimage, len, "%s.preimage", CacheDataStore);
389 
390         UseSharedSpaces = false;
391         enable_dumping_static_archive();
392         SharedArchiveFile = preimage;
393         log_info(cds)("CacheDataStore needs to be updated. Writing %s file", SharedArchiveFile);
394 
395         // At VM exit, the module graph may be contaminated with program states. We should rebuild the
396         // module graph when dumping the CDS final image.
397         log_info(cds)("full module graph: disabled when writing CDS preimage");
398         HeapShared::disable_writing();
399         stop_dumping_full_module_graph();
400         FLAG_SET_ERGO(ArchiveInvokeDynamic, false);
401         FLAG_SET_ERGO(ArchivePackages, false);
402 
403         FLAG_SET_ERGO_IF_DEFAULT(RecordTraining, true);
404       }
405     } else {
406       // The final image dumping phase -- load the preimage and write the final image file
407       SharedArchiveFile = CDSPreimage;
408       UseSharedSpaces = true;
409       log_info(cds)("Generate CacheDataStore %s from CDSPreimage %s", CacheDataStore, CDSPreimage);
410       // Force -Xbatch for AOT compilation.
411       if (FLAG_SET_CMDLINE(BackgroundCompilation, false) != JVMFlag::SUCCESS) {
412         return false;
413       }
414       RecordTraining = false; // This will be updated inside MetaspaceShared::preload_and_dump()
415 
416       FLAG_SET_ERGO_IF_DEFAULT(ReplayTraining, true);
417       // Settings for AOT
418       FLAG_SET_ERGO_IF_DEFAULT(StoreCachedCode, true);
419       if (StoreCachedCode && FLAG_IS_DEFAULT(CachedCodeFile)) {
420         set_new_workflow_default_CachedCodeFile();
421         // Cannot dump cached code until metadata and heap are dumped.
422         disable_dumping_cached_code();
423       }
424     }
425   } else {
426     // Old workflow
427     if (CDSPreimage != nullptr) {
428       vm_exit_during_initialization("CDSPreimage must be specified only when CacheDataStore is specified");
429     }
430   }
431 
432   if (FLAG_IS_DEFAULT(UsePermanentHeapObjects)) {
433     if (StoreCachedCode || PreloadSharedClasses) {
434       FLAG_SET_ERGO(UsePermanentHeapObjects, true);
435     }
436   }
437 
438   if (LoadCachedCode) {
439     // This must be true. Cached code is hard-wired to use permanent objects.
440     UsePermanentHeapObjects = true;
441   }
442 
443   if (PreloadSharedClasses) {
444     // If PreloadSharedClasses is specified, enable all these optimizations by default.
445     FLAG_SET_ERGO_IF_DEFAULT(ArchiveDynamicProxies, true);
446     FLAG_SET_ERGO_IF_DEFAULT(ArchiveFieldReferences, true);
447     FLAG_SET_ERGO_IF_DEFAULT(ArchiveInvokeDynamic, true);
448     FLAG_SET_ERGO_IF_DEFAULT(ArchiveLoaderLookupCache, true);
449     FLAG_SET_ERGO_IF_DEFAULT(ArchiveMethodReferences, true);
450     FLAG_SET_ERGO_IF_DEFAULT(ArchivePackages, true);
451     FLAG_SET_ERGO_IF_DEFAULT(ArchiveReflectionData, true);
452   } else {
453     // All of these *might* depend on PreloadSharedClasses. Better be safe than sorry.
454     // TODO: more fine-grained handling.
455     FLAG_SET_ERGO(ArchiveDynamicProxies, false);
456     FLAG_SET_ERGO(ArchiveFieldReferences, false);
457     FLAG_SET_ERGO(ArchiveInvokeDynamic, false);
458     FLAG_SET_ERGO(ArchiveLoaderLookupCache, false);
459     FLAG_SET_ERGO(ArchiveMethodReferences, false);
460     FLAG_SET_ERGO(ArchivePackages, false);
461     FLAG_SET_ERGO(ArchiveReflectionData, false);
462   }
463 
464   if (is_dumping_static_archive()) {
465     if (is_dumping_preimage_static_archive() || is_dumping_final_static_archive()) {
466       // Don't tweak execution mode
467     } else if (!mode_flag_cmd_line) {
468       // By default, -Xshare:dump runs in interpreter-only mode, which is required for deterministic archive.
469       //
470       // If your classlist is large and you don't care about deterministic dumping, you can use
471       // -Xshare:dump -Xmixed to improve dumping speed.
472       Arguments::set_mode_flags(Arguments::_int);
473     } else if (Arguments::mode() == Arguments::_comp) {
474       // -Xcomp may use excessive CPU for the test tiers. Also, -Xshare:dump runs a small and fixed set of
475       // Java code, so there's not much benefit in running -Xcomp.
476       log_info(cds)("reduced -Xcomp to -Xmixed for static dumping");
477       Arguments::set_mode_flags(Arguments::_mixed);
478     }
479 
480     // String deduplication may cause CDS to iterate the strings in different order from one
481     // run to another which resulting in non-determinstic CDS archives.
482     // Disable UseStringDeduplication while dumping CDS archive.
483     UseStringDeduplication = false;
484 
485     Arguments::PropertyList_add(new SystemProperty("java.lang.invoke.MethodHandle.NO_SOFT_CACHE", "true", false));
486   } else {
487     // These flags flag are useful only when dumping static archive (which supports archived heap)
488     ArchiveInvokeDynamic = false;
489     ArchivePackages = false;
490   }
491 
492   // RecordDynamicDumpInfo is not compatible with ArchiveClassesAtExit
493   if (ArchiveClassesAtExit != nullptr && RecordDynamicDumpInfo) {
494     jio_fprintf(defaultStream::output_stream(),
495                 "-XX:+RecordDynamicDumpInfo cannot be used with -XX:ArchiveClassesAtExit.\n");
496     return false;
497   }
498 
499   if (ArchiveClassesAtExit == nullptr && !RecordDynamicDumpInfo) {
500     disable_dumping_dynamic_archive();
501   } else {
502     enable_dumping_dynamic_archive();
503   }
504 
505   if (AutoCreateSharedArchive) {
506     if (SharedArchiveFile == nullptr) {
507       log_warning(cds)("-XX:+AutoCreateSharedArchive requires -XX:SharedArchiveFile");
508       return false;
509     }
510     if (ArchiveClassesAtExit != nullptr) {
511       log_warning(cds)("-XX:+AutoCreateSharedArchive does not work with ArchiveClassesAtExit");
512       return false;
513     }
514   }
515 
516   if (UseSharedSpaces && patch_mod_javabase) {
517     Arguments::no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
518   }
519   if (UseSharedSpaces && has_unsupported_runtime_module_options()) {
520     UseSharedSpaces = false;
521   }
522 
523   if (is_dumping_archive()) {
524     // Always verify non-system classes during CDS dump
525     if (!BytecodeVerificationRemote) {
526       BytecodeVerificationRemote = true;
527       log_info(cds)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");
528     }
529   }
530 
531   if (!is_dumping_static_archive() || !PreloadSharedClasses) {
532     // FIXME -- is_dumping_heap() is not yet callable from here, as UseG1GC is not yet set by ergo!
533     //
534     // These optimizations require heap dumping and PreloadSharedClasses, or else
535     // the classes of some archived heap objects may be replaced at runtime.
536     ArchiveInvokeDynamic = false;
537     ArchivePackages = false;
538   }
539 
540   if (!ArchiveInvokeDynamic) {
541     ArchiveReflectionData = false; // reflection data use LambdaForm classes
542   }
543 
544   return true;
545 }
546 bool CDSConfig::is_dumping_classic_static_archive() {
547   return _is_dumping_static_archive && CacheDataStore == nullptr && CDSPreimage == nullptr;
548 }
549 
550 bool CDSConfig::is_dumping_preimage_static_archive() {
551   return _is_dumping_static_archive && CacheDataStore != nullptr && CDSPreimage == nullptr;
552 }
553 
554 bool CDSConfig::is_dumping_final_static_archive() {
555   if (CDSPreimage != nullptr) {
556     assert(CacheDataStore != nullptr, "must be"); // should have been properly initialized by arguments.cpp
557   }
558 
559   // Note: _is_dumping_static_archive is false! // FIXME -- refactor this so it makes more sense!
560   return CacheDataStore != nullptr && CDSPreimage != nullptr;
561 }
562 
563 bool CDSConfig::is_dumping_regenerated_lambdaform_invokers() {
564   if (is_dumping_final_static_archive()) {
565     // Not yet supported in new workflow -- the training data may point
566     // to a method in a lambdaform holder class that was not regenerated
567     // due to JDK-8318064.
568     return false;
569   } else {
570     return is_dumping_archive();
571   }
572 }
573 
574 bool CDSConfig::is_tracing_dynamic_proxy() {
575   return ClassListWriter::is_enabled() || is_dumping_preimage_static_archive();
576 }
577 
578 // Preserve all states that were examined used during dumptime verification, such
579 // that the verification result (pass or fail) cannot be changed at runtime.
580 //
581 // For example, if the verification of ik requires that class A must be a subtype of B,
582 // then this relationship between A and B cannot be changed at runtime. I.e., the app
583 // cannot load alternative versions of A and B such that A is not a subtype of B.
584 bool CDSConfig::preserve_all_dumptime_verification_states(const InstanceKlass* ik) {
585   return PreloadSharedClasses && SystemDictionaryShared::is_builtin(ik);
586 }
587 
588 bool CDSConfig::is_using_archive() {
589   return UseSharedSpaces; // TODO: UseSharedSpaces will be eventually replaced by CDSConfig::is_using_archive()
590 }
591 
592 bool CDSConfig::is_logging_lambda_form_invokers() {
593   return ClassListWriter::is_enabled() || is_dumping_dynamic_archive() || is_dumping_preimage_static_archive();
594 }
595 
596 void CDSConfig::stop_using_optimized_module_handling() {
597   _is_using_optimized_module_handling = false;
598   _is_dumping_full_module_graph = false; // This requires is_using_optimized_module_handling()
599   _is_using_full_module_graph = false; // This requires is_using_optimized_module_handling()
600 }
601 
602 #if INCLUDE_CDS_JAVA_HEAP
603 bool CDSConfig::is_dumping_heap() {
604   return is_dumping_static_archive() && !is_dumping_preimage_static_archive()
605     && HeapShared::can_write();
606 }
607 
608 bool CDSConfig::is_loading_heap() {
609   return ArchiveHeapLoader::is_in_use();
610 }
611 
612 bool CDSConfig::is_using_full_module_graph() {
613   if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
614     return true;
615   }
616 
617   if (!_is_using_full_module_graph) {
618     return false;
619   }
620 
621   if (UseSharedSpaces && ArchiveHeapLoader::can_use()) {
622     // Classes used by the archived full module graph are loaded in JVMTI early phase.
623     assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
624            "CDS should be disabled if early class hooks are enabled");
625     return true;
626   } else {
627     _is_using_full_module_graph = false;
628     return false;
629   }
630 }
631 
632 void CDSConfig::stop_dumping_full_module_graph(const char* reason) {
633   if (_is_dumping_full_module_graph) {
634     _is_dumping_full_module_graph = false;
635     if (reason != nullptr) {
636       log_info(cds)("full module graph cannot be dumped: %s", reason);
637     }
638   }
639 }
640 
641 void CDSConfig::stop_using_full_module_graph(const char* reason) {
642   assert(!ClassLoaderDataShared::is_full_module_graph_loaded(), "you call this function too late!");
643   if (_is_using_full_module_graph) {
644     _is_using_full_module_graph = false;
645     if (reason != nullptr) {
646       log_info(cds)("full module graph cannot be loaded: %s", reason);
647     }
648   }
649 }
650 
651 bool CDSConfig::is_loading_invokedynamic() {
652   return UseSharedSpaces && is_loading_heap() && _is_loading_invokedynamic;
653 }
654 
655 bool CDSConfig::is_dumping_dynamic_proxy() {
656   return is_dumping_full_module_graph() && is_dumping_invokedynamic();
657 }
658 
659 bool CDSConfig::is_initing_classes_at_dump_time() {
660   return is_dumping_heap() && PreloadSharedClasses;
661 }
662 
663 bool CDSConfig::is_dumping_invokedynamic() {
664   return ArchiveInvokeDynamic && is_dumping_heap();
665 }
666 
667 bool CDSConfig::is_dumping_packages() {
668   return ArchivePackages && is_dumping_heap();
669 }
670 
671 bool CDSConfig::is_loading_packages() {
672   return UseSharedSpaces && is_loading_heap() && _is_loading_packages;
673 }
674 #endif // INCLUDE_CDS_JAVA_HEAP
675 
676 // This is allowed by default. We disable it only in the final image dump before the
677 // metadata and heap are dumped.
678 static bool _is_dumping_cached_code = true;
679 
680 bool CDSConfig::is_dumping_cached_code() {
681   return _is_dumping_cached_code;
682 }
683 
684 void CDSConfig::disable_dumping_cached_code() {
685   _is_dumping_cached_code = false;
686 }
687 
688 void CDSConfig::enable_dumping_cached_code() {
689   _is_dumping_cached_code = true;
690 }