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