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/cds_globals.hpp"
 28 #include "cds/classListWriter.hpp"
 29 #include "cds/heapShared.hpp"
 30 #include "cds/metaspaceShared.hpp"
 31 #include "classfile/classLoaderDataShared.hpp"
 32 #include "classfile/moduleEntry.hpp"
 33 #include "classfile/systemDictionaryShared.hpp"
 34 #include "code/SCCache.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 "runtime/vmThread.hpp"
 43 #include "utilities/defaultStream.hpp"
 44 #include "utilities/formatBuffer.hpp"
 45 
 46 bool CDSConfig::_is_dumping_static_archive = false;
 47 bool CDSConfig::_is_dumping_dynamic_archive = false;
 48 bool CDSConfig::_is_using_optimized_module_handling = true;
 49 bool CDSConfig::_is_dumping_full_module_graph = true;
 50 bool CDSConfig::_is_using_full_module_graph = true;
 51 bool CDSConfig::_has_aot_linked_classes = false;
 52 bool CDSConfig::_has_archived_invokedynamic = false;
 53 bool CDSConfig::_is_loading_packages = false;
 54 bool CDSConfig::_is_loading_protection_domains = false;
 55 bool CDSConfig::_is_security_manager_allowed = false;
 56 bool CDSConfig::_old_cds_flags_used = false;
 57 bool CDSConfig::_disable_heap_dumping = false;
 58 
 59 char* CDSConfig::_default_archive_path = nullptr;
 60 char* CDSConfig::_static_archive_path = nullptr;
 61 char* CDSConfig::_dynamic_archive_path = nullptr;
 62 
 63 JavaThread* CDSConfig::_dumper_thread = nullptr;
 64 
 65 int CDSConfig::get_status() {
 66   assert(Universe::is_fully_initialized(), "status is finalized only after Universe is initialized");
 67   return (is_dumping_archive()              ? IS_DUMPING_ARCHIVE : 0) |
 68          (is_dumping_static_archive()       ? IS_DUMPING_STATIC_ARCHIVE : 0) |
 69          (is_logging_lambda_form_invokers() ? IS_LOGGING_LAMBDA_FORM_INVOKERS : 0) |
 70          (is_using_archive()                ? IS_USING_ARCHIVE : 0) |
 71          (is_dumping_heap()                 ? IS_DUMPING_HEAP : 0) |
 72          (is_logging_dynamic_proxies()      ? IS_LOGGING_DYNAMIC_PROXIES : 0) |
 73          (is_dumping_packages()             ? IS_DUMPING_PACKAGES : 0) |
 74          (is_dumping_protection_domains()   ? IS_DUMPING_PROTECTION_DOMAINS : 0);
 75 }
 76 
 77 void CDSConfig::initialize() {
 78   if (is_dumping_static_archive() && !is_dumping_final_static_archive()) {
 79     UseSharedSpaces = false;
 80   }
 81 
 82   // Initialize shared archive paths which could include both base and dynamic archive paths
 83   // This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.
 84   //
 85   // UseSharedSpaces may be disabled if -XX:SharedArchiveFile is invalid.
 86   if (is_dumping_static_archive() || is_using_archive()) {
 87     init_shared_archive_paths();
 88   }
 89 
 90   if (!is_dumping_heap()) {
 91     _is_dumping_full_module_graph = false;
 92   }
 93 }
 94 
 95 char* CDSConfig::default_archive_path() {
 96   if (_default_archive_path == nullptr) {
 97     char jvm_path[JVM_MAXPATHLEN];
 98     os::jvm_path(jvm_path, sizeof(jvm_path));
 99     char *end = strrchr(jvm_path, *os::file_separator());
100     if (end != nullptr) *end = '\0';
101     stringStream tmp;
102     tmp.print("%s%sclasses", jvm_path, os::file_separator());
103 #ifdef _LP64
104     if (!UseCompressedOops) {
105       tmp.print_raw("_nocoops");
106     }
107     if (UseCompactObjectHeaders) {
108       // Note that generation of xxx_coh.jsa variants require
109       // --enable-cds-archive-coh at build time
110       tmp.print_raw("_coh");
111     }
112 #endif
113     tmp.print_raw(".jsa");
114     _default_archive_path = os::strdup(tmp.base());
115   }
116   return _default_archive_path;
117 }
118 
119 int CDSConfig::num_archives(const char* archive_path) {
120   if (archive_path == nullptr) {
121     return 0;
122   }
123   int npaths = 1;
124   char* p = (char*)archive_path;
125   while (*p != '\0') {
126     if (*p == os::path_separator()[0]) {
127       npaths++;
128     }
129     p++;
130   }
131   return npaths;
132 }
133 
134 void CDSConfig::extract_shared_archive_paths(const char* archive_path,
135                                              char** base_archive_path,
136                                              char** top_archive_path) {
137   char* begin_ptr = (char*)archive_path;
138   char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);
139   if (end_ptr == nullptr || end_ptr == begin_ptr) {
140     vm_exit_during_initialization("Base archive was not specified", archive_path);
141   }
142   size_t len = end_ptr - begin_ptr;
143   char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
144   strncpy(cur_path, begin_ptr, len);
145   cur_path[len] = '\0';
146   *base_archive_path = cur_path;
147 
148   begin_ptr = ++end_ptr;
149   if (*begin_ptr == '\0') {
150     vm_exit_during_initialization("Top archive was not specified", archive_path);
151   }
152   end_ptr = strchr(begin_ptr, '\0');
153   assert(end_ptr != nullptr, "sanity");
154   len = end_ptr - begin_ptr;
155   cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
156   strncpy(cur_path, begin_ptr, len + 1);
157   *top_archive_path = cur_path;
158 }
159 
160 static void set_new_workflow_default_CachedCodeFile() {
161   size_t len = strlen(CacheDataStore) + 6;
162   char* file = AllocateHeap(len, mtArguments);
163   jio_snprintf(file, len, "%s.code", CacheDataStore);
164   FLAG_SET_ERGO(CachedCodeFile, file);
165 }
166 
167 void CDSConfig::init_shared_archive_paths() {
168   if (ArchiveClassesAtExit != nullptr) {
169     assert(!RecordDynamicDumpInfo, "already checked");
170     if (is_dumping_static_archive()) {
171       vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");
172     }
173     check_unsupported_dumping_module_options();
174 
175     if (os::same_files(default_archive_path(), ArchiveClassesAtExit)) {
176       vm_exit_during_initialization(
177         "Cannot specify the default CDS archive for -XX:ArchiveClassesAtExit", default_archive_path());
178     }
179   }
180 
181   if (SharedArchiveFile == nullptr) {
182     _static_archive_path = default_archive_path();
183   } else {
184     int archives = num_archives(SharedArchiveFile);
185     assert(archives > 0, "must be");
186 
187     if (is_dumping_archive() && archives > 1) {
188       vm_exit_during_initialization(
189         "Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");
190     }
191 
192     if (CDSPreimage != nullptr && archives > 1) {
193       vm_exit_during_initialization("CDSPreimage must point to a single file", CDSPreimage);
194     }
195 
196     if (is_dumping_static_archive()) {
197       assert(archives == 1, "must be");
198       // Static dump is simple: only one archive is allowed in SharedArchiveFile. This file
199       // will be overwritten no matter regardless of its contents
200       _static_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);
201     } else {
202       // SharedArchiveFile may specify one or two files. In case (c), the path for base.jsa
203       // is read from top.jsa
204       //    (a) 1 file:  -XX:SharedArchiveFile=base.jsa
205       //    (b) 2 files: -XX:SharedArchiveFile=base.jsa:top.jsa
206       //    (c) 2 files: -XX:SharedArchiveFile=top.jsa
207       //
208       // However, if either RecordDynamicDumpInfo or ArchiveClassesAtExit is used, we do not
209       // allow cases (b) and (c). Case (b) is already checked above.
210 
211       if (archives > 2) {
212         vm_exit_during_initialization(
213           "Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");
214       }
215       if (archives == 1) {
216         char* base_archive_path = nullptr;
217         bool success =
218           FileMapInfo::get_base_archive_name_from_header(SharedArchiveFile, &base_archive_path);
219         if (!success) {
220           if (CDSPreimage != nullptr) {
221             vm_exit_during_initialization("Unable to map shared spaces from CDSPreimage", CDSPreimage);
222           }
223 
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();
228             ArchiveClassesAtExit = const_cast<char *>(SharedArchiveFile);
229             _static_archive_path = default_archive_path();
230             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             Arguments::no_shared_spaces("invalid archive");
237           }
238         } else if (base_archive_path == nullptr) {
239           // User has specified a single archive, which is a static archive.
240           _static_archive_path = const_cast<char *>(SharedArchiveFile);
241         } else {
242           // User has specified a single archive, which is a dynamic archive.
243           _dynamic_archive_path = const_cast<char *>(SharedArchiveFile);
244           _static_archive_path = base_archive_path; // has been c-heap allocated.
245         }
246       } else {
247         extract_shared_archive_paths((const char*)SharedArchiveFile,
248                                       &_static_archive_path, &_dynamic_archive_path);
249         if (_static_archive_path == nullptr) {
250           assert(_dynamic_archive_path == nullptr, "must be");
251           Arguments::no_shared_spaces("invalid archive");
252         }
253       }
254 
255       if (_dynamic_archive_path != nullptr) {
256         // Check for case (c)
257         if (RecordDynamicDumpInfo) {
258           vm_exit_during_initialization("-XX:+RecordDynamicDumpInfo is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
259                                         SharedArchiveFile);
260         }
261         if (ArchiveClassesAtExit != nullptr) {
262           vm_exit_during_initialization("-XX:ArchiveClassesAtExit is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
263                                         SharedArchiveFile);
264         }
265       }
266 
267       if (ArchiveClassesAtExit != nullptr && os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {
268           vm_exit_during_initialization(
269             "Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",
270             SharedArchiveFile);
271       }
272     }
273   }
274 }
275 
276 static char* bad_module_prop_key   = nullptr;
277 static char* bad_module_prop_value = nullptr;
278 
279 void CDSConfig::check_internal_module_property(const char* key, const char* value) {
280   if (Arguments::is_incompatible_cds_internal_module_property(key)) {
281     stop_using_optimized_module_handling();
282     if (bad_module_prop_key == nullptr) {
283       // We don't want to print an unconditional warning here, as we are still processing the command line.
284       // A later argument may specify something like -Xshare:off, which makes such a warning irrelevant.
285       //
286       // Instead, we save the info so we can warn when necessary: we are doing it only during CacheDataStore
287       // creation for now, but could add it to other places.
288       bad_module_prop_key   = os::strdup(key);
289       bad_module_prop_value = os::strdup(value);
290     }
291     log_info(cds)("optimized module handling/full module graph: disabled due to incompatible property: %s=%s", key, value);
292   }
293 }
294 
295 void CDSConfig::check_incompatible_property(const char* key, const char* value) {
296   static const char* incompatible_properties[] = {
297     "java.system.class.loader",
298     "jdk.module.showModuleResolution",
299     "jdk.module.validation"
300   };
301 
302   for (const char* property : incompatible_properties) {
303     if (strcmp(key, property) == 0) {
304       stop_dumping_full_module_graph();
305       stop_using_full_module_graph();
306       log_info(cds)("full module graph: disabled due to incompatible property: %s=%s", key, value);
307       break;
308     }
309   }
310 
311   // Match the logic in java/lang/System.java, but we need to know this before the System class is initialized.
312   if (strcmp(key, "java.security.manager") == 0) {
313     if (strcmp(value, "disallowed") != 0) {
314       _is_security_manager_allowed = true;
315     }
316   }
317 }
318 
319 // Returns any JVM command-line option, such as "--patch-module", that's not supported by CDS.
320 static const char* find_any_unsupported_module_option() {
321   // Note that arguments.cpp has translated the command-line options into properties. If we find an
322   // unsupported property, translate it back to its command-line option for better error reporting.
323 
324   // The following properties are checked by Arguments::is_internal_module_property() and cannot be
325   // directly specified in the command-line.
326   static const char* unsupported_module_properties[] = {
327     "jdk.module.limitmods",
328     "jdk.module.upgrade.path",
329     "jdk.module.patch.0"
330   };
331   static const char* unsupported_module_options[] = {
332     "--limit-modules",
333     "--upgrade-module-path",
334     "--patch-module"
335   };
336 
337   assert(ARRAY_SIZE(unsupported_module_properties) == ARRAY_SIZE(unsupported_module_options), "must be");
338   SystemProperty* sp = Arguments::system_properties();
339   while (sp != nullptr) {
340     for (uint i = 0; i < ARRAY_SIZE(unsupported_module_properties); i++) {
341       if (strcmp(sp->key(), unsupported_module_properties[i]) == 0) {
342         return unsupported_module_options[i];
343       }
344     }
345     sp = sp->next();
346   }
347 
348   return nullptr; // not found
349 }
350 
351 void CDSConfig::check_unsupported_dumping_module_options() {
352   assert(is_dumping_archive(), "this function is only used with CDS dump time");
353   const char* option = find_any_unsupported_module_option();
354   if (option != nullptr) {
355     vm_exit_during_initialization("Cannot use the following option when dumping the shared archive", option);
356   }
357   // Check for an exploded module build in use with -Xshare:dump.
358   if (!Arguments::has_jimage()) {
359     vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
360   }
361 }
362 
363 bool CDSConfig::has_unsupported_runtime_module_options() {
364   assert(is_using_archive(), "this function is only used with -Xshare:{on,auto}");
365   if (ArchiveClassesAtExit != nullptr) {
366     // dynamic dumping, just return false for now.
367     // check_unsupported_dumping_properties() will be called later to check the same set of
368     // properties, and will exit the VM with the correct error message if the unsupported properties
369     // are used.
370     return false;
371   }
372   const char* option = find_any_unsupported_module_option();
373   if (option != nullptr) {
374     if (RequireSharedSpaces) {
375       warning("CDS is disabled when the %s option is specified.", option);
376     } else {
377       log_info(cds)("CDS is disabled when the %s option is specified.", option);
378     }
379     return true;
380   }
381   return false;
382 }
383 
384 #define CHECK_ALIAS(f) check_flag_alias(FLAG_IS_DEFAULT(f), #f)
385 
386 void CDSConfig::check_flag_alias(bool alias_is_default, const char* alias_name) {
387   if (_old_cds_flags_used && !alias_is_default) {
388     vm_exit_during_initialization(err_msg("Option %s cannot be used at the same time with "
389                                           "-Xshare:on, -Xshare:auto, -Xshare:off, -Xshare:dump, "
390                                           "DumpLoadedClassList, SharedClassListFile, or SharedArchiveFile",
391                                           alias_name));
392   }
393 }
394 
395 void CDSConfig::check_flag_aliases() {
396   if (!FLAG_IS_DEFAULT(DumpLoadedClassList) ||
397       !FLAG_IS_DEFAULT(SharedClassListFile) ||
398       !FLAG_IS_DEFAULT(SharedArchiveFile)) {
399     _old_cds_flags_used = true;
400   }
401 
402   CHECK_ALIAS(AOTCache);
403   CHECK_ALIAS(AOTConfiguration);
404   CHECK_ALIAS(AOTMode);
405 
406   if (FLAG_IS_DEFAULT(AOTCache) && FLAG_IS_DEFAULT(AOTConfiguration) && FLAG_IS_DEFAULT(AOTMode)) {
407     // Aliases not used.
408     return;
409   }
410 
411   if (FLAG_IS_DEFAULT(AOTMode) || strcmp(AOTMode, "auto") == 0 || strcmp(AOTMode, "on") == 0) {
412     if (!FLAG_IS_DEFAULT(AOTConfiguration)) {
413       vm_exit_during_initialization("AOTConfiguration can only be used with -XX:AOTMode=record or -XX:AOTMode=create");
414     }
415 
416     if (!FLAG_IS_DEFAULT(AOTCache)) {
417       assert(FLAG_IS_DEFAULT(SharedArchiveFile), "already checked");
418       FLAG_SET_ERGO(SharedArchiveFile, AOTCache);
419     }
420 
421     UseSharedSpaces = true;
422     if (FLAG_IS_DEFAULT(AOTMode) || (strcmp(AOTMode, "auto") == 0)) {
423       RequireSharedSpaces = false;
424     } else {
425       assert(strcmp(AOTMode, "on") == 0, "already checked");
426       RequireSharedSpaces = true;
427     }
428   } else if (strcmp(AOTMode, "off") == 0) {
429     UseSharedSpaces = false;
430     RequireSharedSpaces = false;
431   } else {
432     // AOTMode is record or create
433     if (FLAG_IS_DEFAULT(AOTConfiguration)) {
434       vm_exit_during_initialization(err_msg("-XX:AOTMode=%s cannot be used without setting AOTConfiguration", AOTMode));
435     }
436 
437     if (strcmp(AOTMode, "record") == 0) {
438       if (!FLAG_IS_DEFAULT(AOTCache)) {
439         vm_exit_during_initialization("AOTCache must not be specified when using -XX:AOTMode=record");
440       }
441 
442       assert(FLAG_IS_DEFAULT(DumpLoadedClassList), "already checked");
443       FLAG_SET_ERGO(DumpLoadedClassList, AOTConfiguration);
444       UseSharedSpaces = false;
445       RequireSharedSpaces = false;
446     } else {
447       assert(strcmp(AOTMode, "create") == 0, "checked by AOTModeConstraintFunc");
448       if (FLAG_IS_DEFAULT(AOTCache)) {
449         vm_exit_during_initialization("AOTCache must be specified when using -XX:AOTMode=create");
450       }
451 
452       assert(FLAG_IS_DEFAULT(SharedClassListFile), "already checked");
453       FLAG_SET_ERGO(SharedClassListFile, AOTConfiguration);
454       assert(FLAG_IS_DEFAULT(SharedArchiveFile), "already checked");
455       FLAG_SET_ERGO(SharedArchiveFile, AOTCache);
456 
457       CDSConfig::enable_dumping_static_archive();
458     }
459   }
460 }
461 
462 bool CDSConfig::check_vm_args_consistency(bool patch_mod_javabase, bool mode_flag_cmd_line, bool xshare_auto_cmd_line) {
463   check_flag_aliases();
464 
465   if (!FLAG_IS_DEFAULT(AOTMode)) {
466     // Using any form of the new AOTMode switch enables enhanced optimizations.
467     FLAG_SET_ERGO_IF_DEFAULT(AOTClassLinking, true);
468   }
469 
470   if (CacheDataStore != nullptr) {
471     // Leyden temp work-around:
472     //
473     // By default, when using CacheDataStore, use the HeapBasedNarrowOop mode so that
474     // AOT code can be always work regardless of runtime heap range.
475     //
476     // If you are *absolutely sure* that the CompressedOops::mode() will be the same
477     // between training and production runs (e.g., if you specify -Xmx128m
478     // for both training and production runs, and you know the OS will always reserve
479     // the heap under 4GB), you can explicitly disable this with:
480     //     java -XX:-UseCompatibleCompressedOops -XX:CacheDataStore=...
481     // However, this is risky and there's a chance that the production run will be slower
482     // because it is unable to load the AOT code cache.
483 #ifdef _LP64
484     // FLAG_SET_ERGO_IF_DEFAULT(UseCompatibleCompressedOops, true); // FIXME @iklam - merge with mainline - UseCompatibleCompressedOops
485 #endif
486 
487     // Leyden temp: make sure the user knows if CDS archive somehow fails to load.
488     if (UseSharedSpaces && !xshare_auto_cmd_line) {
489       log_info(cds)("Enabled -Xshare:on by default for troubleshooting Leyden prototype");
490       RequireSharedSpaces = true;
491     }
492 
493     if (FLAG_IS_DEFAULT(AOTClassLinking)) {
494       // New workflow - enable AOTClassLinking by default.
495       // TODO: make new workflow work, even when AOTClassLinking is false.
496       //
497       // NOTE: in old workflow, we cannot enable AOTClassLinking by default. That
498       // should be an opt-in option, per JEP nnn.
499       FLAG_SET_ERGO(AOTClassLinking, true);
500     }
501 
502     if (SharedArchiveFile != nullptr) {
503       vm_exit_during_initialization("CacheDataStore and SharedArchiveFile cannot be both specified");
504     }
505     if (!AOTClassLinking) {
506       // TODO: in the forked JVM, we should ensure all classes are loaded from the hotspot.cds.preimage.
507       // AOTClassLinking only loads the classes for built-in loaders. We need to load the classes
508       // for custom loaders as well.
509       vm_exit_during_initialization("CacheDataStore requires AOTClassLinking");
510     }
511 
512     if (CDSPreimage == nullptr) {
513       if (os::file_exists(CacheDataStore) /* && TODO: CDS file is valid*/) {
514         // The CacheDataStore is already up to date. Use it. Also turn on cached code by default.
515         SharedArchiveFile = CacheDataStore;
516         FLAG_SET_ERGO_IF_DEFAULT(ReplayTraining, true);
517         FLAG_SET_ERGO_IF_DEFAULT(LoadCachedCode, true);
518         if (LoadCachedCode && FLAG_IS_DEFAULT(CachedCodeFile)) {
519           set_new_workflow_default_CachedCodeFile();
520         }
521       } else {
522         // The preimage dumping phase -- run the app and write the preimage file
523         size_t len = strlen(CacheDataStore) + 10;
524         char* preimage = AllocateHeap(len, mtArguments);
525         jio_snprintf(preimage, len, "%s.preimage", CacheDataStore);
526 
527         UseSharedSpaces = false;
528         enable_dumping_static_archive();
529         SharedArchiveFile = preimage;
530         log_info(cds)("CacheDataStore needs to be updated. Writing %s file", SharedArchiveFile);
531 
532         // At VM exit, the module graph may be contaminated with program states. We should rebuild the
533         // module graph when dumping the CDS final image.
534         log_info(cds)("full module graph: disabled when writing CDS preimage");
535         disable_heap_dumping();
536         stop_dumping_full_module_graph();
537         FLAG_SET_ERGO(ArchivePackages, false);
538         FLAG_SET_ERGO(ArchiveProtectionDomains, false);
539 
540         FLAG_SET_ERGO_IF_DEFAULT(RecordTraining, true);
541       }
542     } else {
543       // The final image dumping phase -- load the preimage and write the final image file
544       SharedArchiveFile = CDSPreimage;
545       UseSharedSpaces = true;
546       log_info(cds)("Generate CacheDataStore %s from CDSPreimage %s", CacheDataStore, CDSPreimage);
547       // Force -Xbatch for AOT compilation.
548       if (FLAG_SET_CMDLINE(BackgroundCompilation, false) != JVMFlag::SUCCESS) {
549         return false;
550       }
551       RecordTraining = false; // This will be updated inside MetaspaceShared::preload_and_dump()
552 
553       FLAG_SET_ERGO_IF_DEFAULT(ReplayTraining, true);
554       // Settings for AOT
555       FLAG_SET_ERGO_IF_DEFAULT(StoreCachedCode, true);
556       if (StoreCachedCode && FLAG_IS_DEFAULT(CachedCodeFile)) {
557         set_new_workflow_default_CachedCodeFile();
558         // Cannot dump cached code until metadata and heap are dumped.
559         disable_dumping_cached_code();
560       }
561       if (StoreCachedCode) {
562         log_info(cds)("ArchiveAdapters is enabled");
563         FLAG_SET_ERGO_IF_DEFAULT(ArchiveAdapters, true);
564       }
565     }
566   } else {
567     // Old workflow
568     if (CDSPreimage != nullptr) {
569       vm_exit_during_initialization("CDSPreimage must be specified only when CacheDataStore is specified");
570     }
571   }
572 
573   if (FLAG_IS_DEFAULT(UsePermanentHeapObjects)) {
574     if (StoreCachedCode || AOTClassLinking) {
575       FLAG_SET_ERGO(UsePermanentHeapObjects, true);
576     }
577   }
578 
579   if (LoadCachedCode) {
580     // This must be true. Cached code is hard-wired to use permanent objects.
581     UsePermanentHeapObjects = true;
582   }
583 
584   if (AOTClassLinking) {
585     // If AOTClassLinking is specified, enable all these optimizations by default.
586     FLAG_SET_ERGO_IF_DEFAULT(AOTInvokeDynamicLinking, true);
587     FLAG_SET_ERGO_IF_DEFAULT(ArchiveDynamicProxies, true);
588     FLAG_SET_ERGO_IF_DEFAULT(ArchiveLoaderLookupCache, true);
589     FLAG_SET_ERGO_IF_DEFAULT(ArchivePackages, true);
590     FLAG_SET_ERGO_IF_DEFAULT(ArchiveProtectionDomains, true);
591     FLAG_SET_ERGO_IF_DEFAULT(ArchiveReflectionData, true);
592   } else {
593     // All of these *might* depend on AOTClassLinking. Better be safe than sorry.
594     // TODO: more fine-grained handling.
595     FLAG_SET_ERGO(AOTInvokeDynamicLinking, false);
596     FLAG_SET_ERGO(ArchiveDynamicProxies, false);
597     FLAG_SET_ERGO(ArchiveLoaderLookupCache, false);
598     FLAG_SET_ERGO(ArchivePackages, false);
599     FLAG_SET_ERGO(ArchiveProtectionDomains, false);
600     FLAG_SET_ERGO(ArchiveReflectionData, false);
601   }
602 
603 #ifdef _WINDOWS
604   // This optimization is not working on Windows for some reason. See JDK-8338604.
605   FLAG_SET_ERGO(ArchiveReflectionData, false);
606 #endif
607 
608   if (is_dumping_static_archive()) {
609     if (is_dumping_preimage_static_archive() || is_dumping_final_static_archive()) {
610       // Don't tweak execution mode
611     } else if (!mode_flag_cmd_line) {
612       // By default, -Xshare:dump runs in interpreter-only mode, which is required for deterministic archive.
613       //
614       // If your classlist is large and you don't care about deterministic dumping, you can use
615       // -Xshare:dump -Xmixed to improve dumping speed.
616       Arguments::set_mode_flags(Arguments::_int);
617     } else if (Arguments::mode() == Arguments::_comp) {
618       // -Xcomp may use excessive CPU for the test tiers. Also, -Xshare:dump runs a small and fixed set of
619       // Java code, so there's not much benefit in running -Xcomp.
620       log_info(cds)("reduced -Xcomp to -Xmixed for static dumping");
621       Arguments::set_mode_flags(Arguments::_mixed);
622     }
623 
624     // String deduplication may cause CDS to iterate the strings in different order from one
625     // run to another which resulting in non-determinstic CDS archives.
626     // Disable UseStringDeduplication while dumping CDS archive.
627     UseStringDeduplication = false;
628 
629     // Don't use SoftReferences so that objects used by java.lang.invoke tables can be archived.
630     Arguments::PropertyList_add(new SystemProperty("java.lang.invoke.MethodHandleNatives.USE_SOFT_CACHE", "false", false));
631   }
632 
633   // RecordDynamicDumpInfo is not compatible with ArchiveClassesAtExit
634   if (ArchiveClassesAtExit != nullptr && RecordDynamicDumpInfo) {
635     jio_fprintf(defaultStream::output_stream(),
636                 "-XX:+RecordDynamicDumpInfo cannot be used with -XX:ArchiveClassesAtExit.\n");
637     return false;
638   }
639 
640   if (ArchiveClassesAtExit == nullptr && !RecordDynamicDumpInfo) {
641     disable_dumping_dynamic_archive();
642   } else {
643     enable_dumping_dynamic_archive();
644   }
645 
646   if (AutoCreateSharedArchive) {
647     if (SharedArchiveFile == nullptr) {
648       log_warning(cds)("-XX:+AutoCreateSharedArchive requires -XX:SharedArchiveFile");
649       return false;
650     }
651     if (ArchiveClassesAtExit != nullptr) {
652       log_warning(cds)("-XX:+AutoCreateSharedArchive does not work with ArchiveClassesAtExit");
653       return false;
654     }
655   }
656 
657   if (is_using_archive() && patch_mod_javabase) {
658     Arguments::no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
659   }
660   if (is_using_archive() && has_unsupported_runtime_module_options()) {
661     UseSharedSpaces = false;
662   }
663 
664   if (is_dumping_archive()) {
665     // Always verify non-system classes during CDS dump
666     if (!BytecodeVerificationRemote) {
667       BytecodeVerificationRemote = true;
668       log_info(cds)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");
669     }
670   }
671 
672   if (AOTClassLinking) {
673     if ((is_dumping_preimage_static_archive() && !is_using_optimized_module_handling()) ||
674         (is_dumping_final_static_archive()    && !is_dumping_full_module_graph())) {
675       if (bad_module_prop_key != nullptr) {
676         log_warning(cds)("optimized module handling/full module graph: disabled due to incompatible property: %s=%s",
677                          bad_module_prop_key, bad_module_prop_value);
678       }
679       vm_exit_during_initialization("CacheDataStore cannot be created because AOTClassLinking is enabled but full module graph is disabled");
680     }
681   }
682 
683   return true;
684 }
685 
686 bool CDSConfig::is_dumping_classic_static_archive() {
687   return _is_dumping_static_archive && CacheDataStore == nullptr && CDSPreimage == nullptr;
688 }
689 
690 bool CDSConfig::is_dumping_preimage_static_archive() {
691   return _is_dumping_static_archive && CacheDataStore != nullptr && CDSPreimage == nullptr;
692 }
693 
694 bool CDSConfig::is_dumping_preimage_static_archive_with_triggers() {
695   return (!FLAG_IS_DEFAULT(AOTEndTrainingOnMethodEntry)) && is_dumping_preimage_static_archive();
696 }
697 
698 bool CDSConfig::is_dumping_final_static_archive() {
699   if (CDSPreimage != nullptr) {
700     assert(CacheDataStore != nullptr, "must be"); // should have been properly initialized by arguments.cpp
701   }
702 
703   // Note: _is_dumping_static_archive is false! // FIXME -- refactor this so it makes more sense!
704   return CacheDataStore != nullptr && CDSPreimage != nullptr;
705 }
706 
707 bool CDSConfig::allow_only_single_java_thread() {
708   // See comments in JVM_StartThread()
709   return is_dumping_classic_static_archive() || is_dumping_final_static_archive();
710 }
711 
712 bool CDSConfig::is_dumping_regenerated_lambdaform_invokers() {
713   if (is_dumping_final_static_archive()) {
714     // Not yet supported in new workflow -- the training data may point
715     // to a method in a lambdaform holder class that was not regenerated
716     // due to JDK-8318064.
717     return false;
718   } else {
719     return is_dumping_archive();
720   }
721 }
722 
723 bool CDSConfig::is_logging_dynamic_proxies() {
724   return ClassListWriter::is_enabled() || is_dumping_preimage_static_archive();
725 }
726 
727 // Preserve all states that were examined used during dumptime verification, such
728 // that the verification result (pass or fail) cannot be changed at runtime.
729 //
730 // For example, if the verification of ik requires that class A must be a subtype of B,
731 // then this relationship between A and B cannot be changed at runtime. I.e., the app
732 // cannot load alternative versions of A and B such that A is not a subtype of B.
733 bool CDSConfig::preserve_all_dumptime_verification_states(const InstanceKlass* ik) {
734   return is_dumping_aot_linked_classes() && SystemDictionaryShared::is_builtin(ik);
735 }
736 
737 bool CDSConfig::is_using_archive() {
738   return UseSharedSpaces;
739 }
740 
741 bool CDSConfig::is_logging_lambda_form_invokers() {
742   return ClassListWriter::is_enabled() || is_dumping_dynamic_archive() || is_dumping_preimage_static_archive();
743 }
744 
745 void CDSConfig::stop_using_optimized_module_handling() {
746   _is_using_optimized_module_handling = false;
747   _is_dumping_full_module_graph = false; // This requires is_using_optimized_module_handling()
748   _is_using_full_module_graph = false; // This requires is_using_optimized_module_handling()
749 }
750 
751 
752 CDSConfig::DumperThreadMark::DumperThreadMark(JavaThread* current) {
753   assert(_dumper_thread == nullptr, "sanity");
754   _dumper_thread = current;
755 }
756 
757 CDSConfig::DumperThreadMark::~DumperThreadMark() {
758   assert(_dumper_thread != nullptr, "sanity");
759   _dumper_thread = nullptr;
760 }
761 
762 bool CDSConfig::current_thread_is_vm_or_dumper() {
763   Thread* t = Thread::current();
764   return t != nullptr && (t->is_VM_thread() || t == _dumper_thread);
765 }
766 
767 // If an incompatible VM options is found, return a text message that explains why
768 static const char* check_options_incompatible_with_dumping_heap() {
769 #if INCLUDE_CDS_JAVA_HEAP
770   if (!UseCompressedClassPointers) {
771     return "UseCompressedClassPointers must be true";
772   }
773 
774   // Almost all GCs support heap region dump, except ZGC (so far).
775   if (UseZGC) {
776     return "ZGC is not supported";
777   }
778 
779   return nullptr;
780 #else
781   return "JVM not configured for writing Java heap objects";
782 #endif
783 }
784 
785 void CDSConfig::log_reasons_for_not_dumping_heap() {
786   const char* reason;
787 
788   assert(!is_dumping_heap(), "sanity");
789 
790   if (_disable_heap_dumping) {
791     reason = "Programmatically disabled";
792   } else {
793     reason = check_options_incompatible_with_dumping_heap();
794   }
795 
796   assert(reason != nullptr, "sanity");
797   log_info(cds)("Archived java heap is not supported: %s", reason);
798 }
799 
800 #if INCLUDE_CDS_JAVA_HEAP
801 bool CDSConfig::are_vm_options_incompatible_with_dumping_heap() {
802   return check_options_incompatible_with_dumping_heap() != nullptr;
803 }
804 
805 
806 bool CDSConfig::is_dumping_heap() {
807   if (!(is_dumping_classic_static_archive() || is_dumping_final_static_archive())
808       || are_vm_options_incompatible_with_dumping_heap()
809       || _disable_heap_dumping) {
810     return false;
811   }
812 
813   return true;
814 }
815 
816 bool CDSConfig::is_loading_heap() {
817   return ArchiveHeapLoader::is_in_use();
818 }
819 
820 bool CDSConfig::is_using_full_module_graph() {
821   if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
822     return true;
823   }
824 
825   if (!_is_using_full_module_graph) {
826     return false;
827   }
828 
829   if (is_using_archive() && ArchiveHeapLoader::can_use()) {
830     // Classes used by the archived full module graph are loaded in JVMTI early phase.
831     assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
832            "CDS should be disabled if early class hooks are enabled");
833     return true;
834   } else {
835     _is_using_full_module_graph = false;
836     return false;
837   }
838 }
839 
840 void CDSConfig::stop_dumping_full_module_graph(const char* reason) {
841   if (_is_dumping_full_module_graph) {
842     _is_dumping_full_module_graph = false;
843     if (reason != nullptr) {
844       log_info(cds)("full module graph cannot be dumped: %s", reason);
845     }
846   }
847 }
848 
849 void CDSConfig::stop_using_full_module_graph(const char* reason) {
850   assert(!ClassLoaderDataShared::is_full_module_graph_loaded(), "you call this function too late!");
851   if (_is_using_full_module_graph) {
852     _is_using_full_module_graph = false;
853     if (reason != nullptr) {
854       log_info(cds)("full module graph cannot be loaded: %s", reason);
855     }
856   }
857 }
858 
859 bool CDSConfig::is_dumping_aot_linked_classes() {
860   if (is_dumping_preimage_static_archive()) {
861     return AOTClassLinking;
862   } else if (is_dumping_dynamic_archive()) {
863     return is_using_full_module_graph() && AOTClassLinking;
864   } else if (is_dumping_static_archive()) {
865     return is_dumping_full_module_graph() && AOTClassLinking;
866   } else {
867     return false;
868   }
869 }
870 
871 bool CDSConfig::is_using_aot_linked_classes() {
872   if (is_dumping_final_static_archive()) {
873     // We assume that the final image is being dumped with the exact same module graph as the training run,
874     // so all aot-linked classes can be loaded.
875     return _has_aot_linked_classes;
876   }
877   // Make sure we have the exact same module graph as in the assembly phase, or else
878   // some aot-linked classes may not be visible so cannot be loaded.
879   return is_using_full_module_graph() && _has_aot_linked_classes;
880 }
881 
882 bool CDSConfig::is_dumping_dynamic_proxies() {
883   return is_dumping_full_module_graph() && is_dumping_invokedynamic() && ArchiveDynamicProxies;
884 }
885 
886 void CDSConfig::set_has_aot_linked_classes(bool has_aot_linked_classes) {
887   _has_aot_linked_classes |= has_aot_linked_classes;
888 }
889 
890 bool CDSConfig::is_initing_classes_at_dump_time() {
891   return is_dumping_heap() && is_dumping_aot_linked_classes();
892 }
893 
894 bool CDSConfig::is_dumping_invokedynamic() {
895   // Requires is_dumping_aot_linked_classes(). Otherwise the classes of some archived heap
896   // objects used by the archive indy callsites may be replaced at runtime.
897   return AOTInvokeDynamicLinking && is_dumping_aot_linked_classes() && is_dumping_heap();
898 }
899 
900 bool CDSConfig::is_dumping_packages() {
901   return ArchivePackages && is_dumping_heap();
902 }
903 
904 bool CDSConfig::is_loading_packages() {
905   return UseSharedSpaces && is_using_full_module_graph() && _is_loading_packages;
906 }
907 
908 bool CDSConfig::is_dumping_protection_domains() {
909   if (_is_security_manager_allowed) {
910     // For sanity, don't archive PDs. TODO: can this be relaxed?
911     return false;
912   }
913   // Archived PDs for the modules will reference their java.lang.Module, which must
914   // also be archived.
915   return ArchiveProtectionDomains && is_dumping_full_module_graph();
916 }
917 
918 bool CDSConfig::is_loading_protection_domains() {
919   if (_is_security_manager_allowed) {
920     // For sanity, don't used any archived PDs. TODO: can this be relaxed?
921     return false;
922   }
923   return UseSharedSpaces && is_using_full_module_graph() && _is_loading_protection_domains;
924 }
925 
926 bool CDSConfig::is_dumping_reflection_data() {
927   // reflection data use LambdaForm classes
928   return ArchiveReflectionData && is_dumping_invokedynamic();
929 }
930 
931 bool CDSConfig::is_loading_invokedynamic() {
932   return UseSharedSpaces && is_using_full_module_graph() && _has_archived_invokedynamic;
933 }
934 
935 #endif // INCLUDE_CDS_JAVA_HEAP
936 
937 // This is allowed by default. We disable it only in the final image dump before the
938 // metadata and heap are dumped.
939 static bool _is_dumping_cached_code = true;
940 
941 bool CDSConfig::is_dumping_cached_code() {
942   return _is_dumping_cached_code;
943 }
944 
945 void CDSConfig::disable_dumping_cached_code() {
946   _is_dumping_cached_code = false;
947 }
948 
949 void CDSConfig::enable_dumping_cached_code() {
950   _is_dumping_cached_code = true;
951 }
952 
953 bool CDSConfig::is_dumping_adapters() {
954   return (ArchiveAdapters && is_dumping_final_static_archive());
955 }