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