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/filemap.hpp"
  30 #include "cds/heapShared.hpp"
  31 #include "cds/metaspaceShared.hpp"
  32 #include "classfile/classLoaderDataShared.hpp"
  33 #include "classfile/moduleEntry.hpp"
  34 #include "classfile/systemDictionaryShared.hpp"
  35 #include "code/SCCache.hpp"
  36 #include "include/jvm_io.h"
  37 #include "logging/log.hpp"
  38 #include "prims/jvmtiExport.hpp"
  39 #include "memory/universe.hpp"
  40 #include "runtime/arguments.hpp"
  41 #include "runtime/globals_extension.hpp"
  42 #include "runtime/java.hpp"
  43 #include "runtime/vmThread.hpp"
  44 #include "utilities/defaultStream.hpp"
  45 #include "utilities/formatBuffer.hpp"
  46 
  47 bool CDSConfig::_is_dumping_static_archive = false;
  48 bool CDSConfig::_is_dumping_preimage_static_archive = false;
  49 bool CDSConfig::_is_dumping_final_static_archive = false;
  50 bool CDSConfig::_is_dumping_dynamic_archive = false;
  51 bool CDSConfig::_is_using_optimized_module_handling = true;
  52 bool CDSConfig::_is_dumping_full_module_graph = true;
  53 bool CDSConfig::_is_using_full_module_graph = true;
  54 bool CDSConfig::_has_aot_linked_classes = false;
  55 bool CDSConfig::_is_one_step_training = false;
  56 bool CDSConfig::_has_temp_aot_config_file = false;
  57 bool CDSConfig::_is_loading_packages = false;
  58 bool CDSConfig::_is_loading_protection_domains = false;
  59 bool CDSConfig::_is_security_manager_allowed = false;
  60 bool CDSConfig::_old_cds_flags_used = false;
  61 bool CDSConfig::_new_aot_flags_used = false;
  62 bool CDSConfig::_experimental_leyden_flags_used = false;
  63 bool CDSConfig::_disable_heap_dumping = false;
  64 
  65 const char* CDSConfig::_default_archive_path = nullptr;
  66 const char* CDSConfig::_input_static_archive_path = nullptr;
  67 const char* CDSConfig::_input_dynamic_archive_path = nullptr;
  68 const char* CDSConfig::_output_archive_path = nullptr;
  69 
  70 JavaThread* CDSConfig::_dumper_thread = nullptr;
  71 
  72 int CDSConfig::get_status() {
  73   assert(Universe::is_fully_initialized(), "status is finalized only after Universe is initialized");
  74   return (is_dumping_archive()              ? IS_DUMPING_ARCHIVE : 0) |
  75          (is_dumping_method_handles()       ? IS_DUMPING_METHOD_HANDLES : 0) |
  76          (is_dumping_static_archive()       ? IS_DUMPING_STATIC_ARCHIVE : 0) |
  77          (is_logging_lambda_form_invokers() ? IS_LOGGING_LAMBDA_FORM_INVOKERS : 0) |
  78          (is_using_archive()                ? IS_USING_ARCHIVE : 0) |
  79          (is_dumping_heap()                 ? IS_DUMPING_HEAP : 0) |
  80          (is_logging_dynamic_proxies()      ? IS_LOGGING_DYNAMIC_PROXIES : 0) |
  81          (is_dumping_packages()             ? IS_DUMPING_PACKAGES : 0) |
  82          (is_dumping_protection_domains()   ? IS_DUMPING_PROTECTION_DOMAINS : 0);
  83 }
  84 
  85 DEBUG_ONLY(static bool _cds_ergo_initialize_started = false);
  86 
  87 void CDSConfig::ergo_initialize() {
  88   DEBUG_ONLY(_cds_ergo_initialize_started = true);
  89 
  90   if (is_dumping_static_archive() && !is_dumping_final_static_archive()) {
  91     // If dumping the classic archive, or making an AOT training run (dumping a preimage archive),
  92     // for sanity, parse all classes from classfiles.
  93     // TODO: in the future, if we want to support re-training on top of an existing AOT cache, this
  94     // needs to be changed.
  95     if (RequireSharedSpaces) {
  96       if (is_experimental_leyden_workflow()) {
  97         log_info(cds)("-Xshare:on flag is ignored when creating a CacheDataStore");
  98       } else {
  99         // -Xshare and -XX:AOTMode flags are mutually exclusive:
 100         //   Class workflow: -Xshare:on and -Xshare:dump cannot take effect at the same time.
 101         //   JEP 483 workflow: -XX:AOTMode:record and -XX:AOTMode=on cannot take effect at the same time.
 102         ShouldNotReachHere();
 103       }
 104     }
 105     UseSharedSpaces = false;
 106   }
 107 
 108   // Initialize shared archive paths which could include both base and dynamic archive paths
 109   // This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.
 110   if (is_dumping_static_archive() || is_using_archive()) {
 111     if (new_aot_flags_used()) {
 112       ergo_init_aot_paths();
 113     } else if (is_experimental_leyden_workflow()) {
 114       ergo_init_experimental_leyden_paths();
 115     } else {
 116       ergo_init_classic_archive_paths();
 117     }
 118   }
 119 
 120   if (!is_dumping_heap()) {
 121     _is_dumping_full_module_graph = false;
 122   }
 123 }
 124 
 125 const char* CDSConfig::default_archive_path() {
 126   // The path depends on UseCompressedOops, etc, which are set by GC ergonomics just
 127   // before CDSConfig::ergo_initialize() is called.
 128   assert(_cds_ergo_initialize_started, "sanity");
 129   if (_default_archive_path == nullptr) {
 130     stringStream tmp;
 131     const char* subdir = WINDOWS_ONLY("bin") NOT_WINDOWS("lib");
 132     tmp.print("%s%s%s%s%s%sclasses", Arguments::get_java_home(), os::file_separator(), subdir,
 133               os::file_separator(), Abstract_VM_Version::vm_variant(), os::file_separator());
 134 #ifdef _LP64
 135     if (!UseCompressedOops) {
 136       tmp.print_raw("_nocoops");
 137     }
 138     if (UseCompactObjectHeaders) {
 139       // Note that generation of xxx_coh.jsa variants require
 140       // --enable-cds-archive-coh at build time
 141       tmp.print_raw("_coh");
 142     }
 143 #endif
 144     tmp.print_raw(".jsa");
 145     _default_archive_path = os::strdup(tmp.base());
 146   }
 147   return _default_archive_path;
 148 }
 149 
 150 int CDSConfig::num_archive_paths(const char* path_spec) {
 151   if (path_spec == nullptr) {
 152     return 0;
 153   }
 154   int npaths = 1;
 155   char* p = (char*)path_spec;
 156   while (*p != '\0') {
 157     if (*p == os::path_separator()[0]) {
 158       npaths++;
 159     }
 160     p++;
 161   }
 162   return npaths;
 163 }
 164 
 165 void CDSConfig::extract_archive_paths(const char* archive_path,
 166                                       const char** base_archive_path,
 167                                       const char** top_archive_path) {
 168   char* begin_ptr = (char*)archive_path;
 169   char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);
 170   if (end_ptr == nullptr || end_ptr == begin_ptr) {
 171     vm_exit_during_initialization("Base archive was not specified", archive_path);
 172   }
 173   size_t len = end_ptr - begin_ptr;
 174   char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
 175   strncpy(cur_path, begin_ptr, len);
 176   cur_path[len] = '\0';
 177   *base_archive_path = cur_path;
 178 
 179   begin_ptr = ++end_ptr;
 180   if (*begin_ptr == '\0') {
 181     vm_exit_during_initialization("Top archive was not specified", archive_path);
 182   }
 183   end_ptr = strchr(begin_ptr, '\0');
 184   assert(end_ptr != nullptr, "sanity");
 185   len = end_ptr - begin_ptr;
 186   cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
 187   strncpy(cur_path, begin_ptr, len + 1);
 188   *top_archive_path = cur_path;
 189 }
 190 
 191 void CDSConfig::ergo_init_classic_archive_paths() {
 192   assert(_cds_ergo_initialize_started, "sanity");
 193   if (ArchiveClassesAtExit != nullptr) {
 194     assert(!RecordDynamicDumpInfo, "already checked");
 195     if (is_dumping_static_archive()) {
 196       vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");
 197     }
 198     check_unsupported_dumping_module_options();
 199 
 200     if (os::same_files(default_archive_path(), ArchiveClassesAtExit)) {
 201       vm_exit_during_initialization(
 202         "Cannot specify the default CDS archive for -XX:ArchiveClassesAtExit", default_archive_path());
 203     }
 204   }
 205 
 206   if (SharedArchiveFile == nullptr) {
 207     _input_static_archive_path = default_archive_path();
 208     if (is_dumping_static_archive()) {
 209       _output_archive_path = _input_static_archive_path;
 210     }
 211   } else {
 212     int num_archives = num_archive_paths(SharedArchiveFile);
 213     assert(num_archives > 0, "must be");
 214 
 215     if (is_dumping_archive() && num_archives > 1) {
 216       vm_exit_during_initialization(
 217         "Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");
 218     }
 219 
 220     if (is_dumping_static_archive()) {
 221       assert(num_archives == 1, "just checked above");
 222       // Static dump is simple: only one archive is allowed in SharedArchiveFile. This file
 223       // will be overwritten regardless of its contents
 224       _output_archive_path = SharedArchiveFile;
 225     } else {
 226       // SharedArchiveFile may specify one or two files. In case (c), the path for base.jsa
 227       // is read from top.jsa
 228       //    (a) 1 file:  -XX:SharedArchiveFile=base.jsa
 229       //    (b) 2 files: -XX:SharedArchiveFile=base.jsa:top.jsa
 230       //    (c) 2 files: -XX:SharedArchiveFile=top.jsa
 231       //
 232       // However, if either RecordDynamicDumpInfo or ArchiveClassesAtExit is used, we do not
 233       // allow cases (b) and (c). Case (b) is already checked above.
 234 
 235       if (num_archives > 2) {
 236         vm_exit_during_initialization(
 237           "Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");
 238       }
 239 
 240       if (num_archives == 1) {
 241         const char* base_archive_path = nullptr;
 242         bool success =
 243           FileMapInfo::get_base_archive_name_from_header(SharedArchiveFile, &base_archive_path);
 244         if (!success) {
 245           // If +AutoCreateSharedArchive and the specified shared archive does not exist,
 246           // regenerate the dynamic archive base on default archive.
 247           if (AutoCreateSharedArchive && !os::file_exists(SharedArchiveFile)) {
 248             enable_dumping_dynamic_archive(SharedArchiveFile);
 249             FLAG_SET_ERGO(ArchiveClassesAtExit, SharedArchiveFile);
 250             _input_static_archive_path = default_archive_path();
 251             FLAG_SET_ERGO(SharedArchiveFile, nullptr);
 252          } else {
 253             if (AutoCreateSharedArchive) {
 254               warning("-XX:+AutoCreateSharedArchive is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
 255               AutoCreateSharedArchive = false;
 256             }
 257             log_error(cds)("Not a valid archive (%s)", SharedArchiveFile);
 258             Arguments::no_shared_spaces("invalid archive");
 259           }
 260         } else if (base_archive_path == nullptr) {
 261           // User has specified a single archive, which is a static archive.
 262           _input_static_archive_path = SharedArchiveFile;
 263         } else {
 264           // User has specified a single archive, which is a dynamic archive.
 265           _input_dynamic_archive_path = SharedArchiveFile;
 266           _input_static_archive_path = base_archive_path; // has been c-heap allocated.
 267         }
 268       } else {
 269         extract_archive_paths(SharedArchiveFile,
 270                               &_input_static_archive_path, &_input_dynamic_archive_path);
 271         if (_input_static_archive_path == nullptr) {
 272           assert(_input_dynamic_archive_path == nullptr, "must be");
 273           Arguments::no_shared_spaces("invalid archive");
 274         }
 275       }
 276 
 277       if (_input_dynamic_archive_path != nullptr) {
 278         // Check for case (c)
 279         if (RecordDynamicDumpInfo) {
 280           vm_exit_during_initialization("-XX:+RecordDynamicDumpInfo is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
 281                                         SharedArchiveFile);
 282         }
 283         if (ArchiveClassesAtExit != nullptr) {
 284           vm_exit_during_initialization("-XX:ArchiveClassesAtExit is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
 285                                         SharedArchiveFile);
 286         }
 287       }
 288 
 289       if (ArchiveClassesAtExit != nullptr && os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {
 290           vm_exit_during_initialization(
 291             "Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",
 292             SharedArchiveFile);
 293       }
 294     }
 295   }
 296 }
 297 
 298 static char* bad_module_prop_key   = nullptr;
 299 static char* bad_module_prop_value = nullptr;
 300 
 301 void CDSConfig::check_internal_module_property(const char* key, const char* value) {
 302   if (Arguments::is_incompatible_cds_internal_module_property(key)) {
 303     stop_using_optimized_module_handling();
 304     if (bad_module_prop_key == nullptr) {
 305       // We don't want to print an unconditional warning here, as we are still processing the command line.
 306       // A later argument may specify something like -Xshare:off, which makes such a warning irrelevant.
 307       //
 308       // Instead, we save the info so we can warn when necessary: we are doing it only during CacheDataStore
 309       // creation for now, but could add it to other places.
 310       bad_module_prop_key   = os::strdup(key);
 311       bad_module_prop_value = os::strdup(value);
 312     }
 313     log_info(cds)("optimized module handling/full module graph: disabled due to incompatible property: %s=%s", key, value);
 314   }
 315 }
 316 
 317 void CDSConfig::check_incompatible_property(const char* key, const char* value) {
 318   static const char* incompatible_properties[] = {
 319     "java.system.class.loader",
 320     "jdk.module.showModuleResolution",
 321     "jdk.module.validation"
 322   };
 323 
 324   for (const char* property : incompatible_properties) {
 325     if (strcmp(key, property) == 0) {
 326       stop_dumping_full_module_graph();
 327       stop_using_full_module_graph();
 328       log_info(cds)("full module graph: disabled due to incompatible property: %s=%s", key, value);
 329       break;
 330     }
 331   }
 332 
 333   // Match the logic in java/lang/System.java, but we need to know this before the System class is initialized.
 334   if (strcmp(key, "java.security.manager") == 0) {
 335     if (strcmp(value, "disallowed") != 0) {
 336       _is_security_manager_allowed = true;
 337     }
 338   }
 339 }
 340 
 341 // Returns any JVM command-line option, such as "--patch-module", that's not supported by CDS.
 342 static const char* find_any_unsupported_module_option() {
 343   // Note that arguments.cpp has translated the command-line options into properties. If we find an
 344   // unsupported property, translate it back to its command-line option for better error reporting.
 345 
 346   // The following properties are checked by Arguments::is_internal_module_property() and cannot be
 347   // directly specified in the command-line.
 348   static const char* unsupported_module_properties[] = {
 349     "jdk.module.limitmods",
 350     "jdk.module.upgrade.path",
 351     "jdk.module.patch.0"
 352   };
 353   static const char* unsupported_module_options[] = {
 354     "--limit-modules",
 355     "--upgrade-module-path",
 356     "--patch-module"
 357   };
 358 
 359   assert(ARRAY_SIZE(unsupported_module_properties) == ARRAY_SIZE(unsupported_module_options), "must be");
 360   SystemProperty* sp = Arguments::system_properties();
 361   while (sp != nullptr) {
 362     for (uint i = 0; i < ARRAY_SIZE(unsupported_module_properties); i++) {
 363       if (strcmp(sp->key(), unsupported_module_properties[i]) == 0) {
 364         return unsupported_module_options[i];
 365       }
 366     }
 367     sp = sp->next();
 368   }
 369 
 370   return nullptr; // not found
 371 }
 372 
 373 void CDSConfig::check_unsupported_dumping_module_options() {
 374   assert(is_dumping_archive(), "this function is only used with CDS dump time");
 375   const char* option = find_any_unsupported_module_option();
 376   if (option != nullptr) {
 377     vm_exit_during_initialization("Cannot use the following option when dumping the shared archive", option);
 378   }
 379   // Check for an exploded module build in use with -Xshare:dump.
 380   if (!Arguments::has_jimage()) {
 381     vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
 382   }
 383 }
 384 
 385 bool CDSConfig::has_unsupported_runtime_module_options() {
 386   assert(is_using_archive(), "this function is only used with -Xshare:{on,auto}");
 387   if (ArchiveClassesAtExit != nullptr) {
 388     // dynamic dumping, just return false for now.
 389     // check_unsupported_dumping_properties() will be called later to check the same set of
 390     // properties, and will exit the VM with the correct error message if the unsupported properties
 391     // are used.
 392     return false;
 393   }
 394   const char* option = find_any_unsupported_module_option();
 395   if (option != nullptr) {
 396     if (RequireSharedSpaces) {
 397       warning("CDS is disabled when the %s option is specified.", option);
 398     } else {
 399       if (new_aot_flags_used()) {
 400         log_warning(cds)("AOT cache is disabled when the %s option is specified.", option);
 401       } else {
 402         log_info(cds)("CDS is disabled when the %s option is specified.", option);
 403       }
 404     }
 405     return true;
 406   }
 407   return false;
 408 }
 409 
 410 #define CHECK_NEW_FLAG(f) check_new_flag(FLAG_IS_DEFAULT(f), #f)
 411 
 412 void CDSConfig::check_new_flag(bool new_flag_is_default, const char* new_flag_name) {
 413   if (old_cds_flags_used() && !new_flag_is_default) {
 414     vm_exit_during_initialization(err_msg("Option %s cannot be used at the same time with "
 415                                           "-Xshare:on, -Xshare:auto, -Xshare:off, -Xshare:dump, "
 416                                           "DumpLoadedClassList, SharedClassListFile, or SharedArchiveFile",
 417                                           new_flag_name));
 418   }
 419   if (experimental_leyden_flags_used() && !new_flag_is_default) {
 420     vm_exit_during_initialization(err_msg("Option %s cannot be used at the same time with "
 421                                           "CacheDataStore, CDSManualFinalImage, or CDSPreimage",
 422                                           new_flag_name));
 423   }
 424 }
 425 
 426 #define CHECK_SINGLE_PATH(f) check_flag_single_path(#f, f)
 427 
 428 void CDSConfig::check_flag_single_path(const char* flag_name, const char* value) {
 429   if (value != nullptr && num_archive_paths(value) != 1) {
 430     vm_exit_during_initialization(err_msg("Option %s must specify a single file name", flag_name));
 431   }
 432 }
 433 
 434 void CDSConfig::check_aot_flags() {
 435   if (!FLAG_IS_DEFAULT(DumpLoadedClassList) ||
 436       !FLAG_IS_DEFAULT(SharedClassListFile) ||
 437       !FLAG_IS_DEFAULT(SharedArchiveFile)) {
 438     _old_cds_flags_used = true;
 439   }
 440   if (!FLAG_IS_DEFAULT(CacheDataStore) ||
 441       !FLAG_IS_DEFAULT(CDSManualFinalImage) ||
 442       !FLAG_IS_DEFAULT(CDSPreimage)) {
 443     _experimental_leyden_flags_used = true;
 444   }
 445 
 446   // "New" AOT flags must not be mixed with "classic" CDS flags such as -Xshare:dump
 447   CHECK_NEW_FLAG(AOTCache);
 448   CHECK_NEW_FLAG(AOTCacheOutput);
 449   CHECK_NEW_FLAG(AOTConfiguration);
 450   CHECK_NEW_FLAG(AOTMode);
 451 
 452   CHECK_SINGLE_PATH(AOTCache);
 453   CHECK_SINGLE_PATH(AOTCacheOutput);
 454   CHECK_SINGLE_PATH(AOTConfiguration);
 455 
 456   if (FLAG_IS_DEFAULT(AOTCache) &&
 457       FLAG_IS_DEFAULT(AOTMode)) {
 458     bool has_cache_output = !FLAG_IS_DEFAULT(AOTCacheOutput);
 459     bool has_config = !FLAG_IS_DEFAULT(AOTConfiguration);
 460     if (!has_cache_output && !has_config) {
 461       // AOT flags are not used. Use classic CDS workflow
 462       return;
 463     } else if (has_cache_output) {
 464       // If AOTCacheOutput has been set, default mode is "record".
 465       // Default value for AOTConfiguration, if necessary, will be assigned in check_aotmode_record().
 466       FLAG_SET_ERGO(AOTMode, "record");
 467     }
 468   }
 469 
 470   // At least one AOT flag has been used
 471  _new_aot_flags_used = true;
 472 
 473   if (FLAG_IS_DEFAULT(AOTMode) || strcmp(AOTMode, "auto") == 0 || strcmp(AOTMode, "on") == 0) {
 474     check_aotmode_auto_or_on();
 475   } else if (strcmp(AOTMode, "off") == 0) {
 476     check_aotmode_off();
 477   } else if (strcmp(AOTMode, "record") == 0) {
 478     check_aotmode_record();
 479   } else {
 480     assert(strcmp(AOTMode, "create") == 0, "checked by AOTModeConstraintFunc");
 481     check_aotmode_create();
 482   }
 483 }
 484 
 485 void CDSConfig::check_aotmode_off() {
 486   UseSharedSpaces = false;
 487   RequireSharedSpaces = false;
 488 }
 489 
 490 void CDSConfig::check_aotmode_auto_or_on() {
 491   if (!FLAG_IS_DEFAULT(AOTConfiguration)) {
 492     vm_exit_during_initialization("AOTConfiguration can only be used with -XX:AOTMode=record or -XX:AOTMode=create");
 493   }
 494 
 495   UseSharedSpaces = true;
 496   if (FLAG_IS_DEFAULT(AOTMode) || (strcmp(AOTMode, "auto") == 0)) {
 497     RequireSharedSpaces = false;
 498   } else {
 499     assert(strcmp(AOTMode, "on") == 0, "already checked");
 500     RequireSharedSpaces = true;
 501   }
 502 }
 503 
 504 void CDSConfig::check_aotmode_record() {
 505   bool has_config = !FLAG_IS_DEFAULT(AOTConfiguration);
 506   bool has_output = !FLAG_IS_DEFAULT(AOTCacheOutput);
 507 
 508   if (has_output) {
 509     _is_one_step_training = true;
 510     if (!has_config) {
 511       // Too early; can't use resource allocation yet.
 512       size_t len = strlen(AOTCacheOutput) + 10;
 513       char* temp = AllocateHeap(len, mtArguments);
 514       jio_snprintf(temp, len, "%s.config", AOTCacheOutput);
 515       FLAG_SET_ERGO(AOTConfiguration, temp);
 516       FreeHeap(temp);
 517       _has_temp_aot_config_file = true;
 518     }
 519   } else {
 520     if (!has_config) {
 521       vm_exit_during_initialization("-XX:AOTMode=record cannot be used without setting AOTCacheOutput or AOTConfiguration");
 522     }
 523   }
 524 
 525   if (!FLAG_IS_DEFAULT(AOTCache)) {
 526     vm_exit_during_initialization("AOTCache must not be specified when using -XX:AOTMode=record");
 527   }
 528 
 529   UseSharedSpaces = false;
 530   RequireSharedSpaces = false;
 531   _is_dumping_static_archive = true;
 532   _is_dumping_preimage_static_archive = true;
 533 
 534   // At VM exit, the module graph may be contaminated with program states.
 535   // We will rebuild the module graph when dumping the CDS final image.
 536   disable_heap_dumping();
 537 }
 538 
 539 void CDSConfig::check_aotmode_create() {
 540   if (FLAG_IS_DEFAULT(AOTConfiguration)) {
 541     vm_exit_during_initialization("-XX:AOTMode=create cannot be used without setting AOTConfiguration");
 542   }
 543 
 544   bool has_cache = !FLAG_IS_DEFAULT(AOTCache);
 545   bool has_cache_output = !FLAG_IS_DEFAULT(AOTCacheOutput);
 546 
 547   if (!has_cache && !has_cache_output) {
 548     vm_exit_during_initialization("AOTCache or AOTCacheOutput must be specified when using -XX:AOTMode=create");
 549   } else if (has_cache && has_cache_output && strcmp(AOTCache, AOTCacheOutput) != 0) {
 550     vm_exit_during_initialization("AOTCache and AOTCacheOutput have different values");
 551   }
 552 
 553   if (!has_cache) {
 554     precond(has_cache_output);
 555     FLAG_SET_ERGO(AOTCache, AOTCacheOutput);
 556   }
 557 
 558   _is_dumping_final_static_archive = true;
 559   UseSharedSpaces = true;
 560   RequireSharedSpaces = true;
 561 
 562   if (!FileMapInfo::is_preimage_static_archive(AOTConfiguration)) {
 563     vm_exit_during_initialization("Must be a valid AOT configuration generated by the current JVM", AOTConfiguration);
 564   }
 565 
 566   CDSConfig::enable_dumping_static_archive();
 567 }
 568 
 569 void CDSConfig::ergo_init_aot_paths() {
 570   assert(_cds_ergo_initialize_started, "sanity");
 571   if (is_dumping_static_archive()) {
 572     if (is_dumping_preimage_static_archive()) {
 573       _output_archive_path = AOTConfiguration;
 574     } else {
 575       assert(is_dumping_final_static_archive(), "must be");
 576       _input_static_archive_path = AOTConfiguration;
 577       _output_archive_path = AOTCache;
 578     }
 579   } else if (is_using_archive()) {
 580     if (FLAG_IS_DEFAULT(AOTCache)) {
 581       // Only -XX:AOTMode={auto,on} is specified
 582       _input_static_archive_path = default_archive_path();
 583     } else {
 584       _input_static_archive_path = AOTCache;
 585     }
 586   }
 587 }
 588 
 589 void CDSConfig::ergo_init_experimental_leyden_paths() {
 590   assert(_cds_ergo_initialize_started, "sanity");
 591   if (is_dumping_static_archive()) {
 592     if (is_dumping_preimage_static_archive()) {
 593       _output_archive_path = CDSPreimage;
 594     } else {
 595       assert(is_dumping_final_static_archive(), "must be");
 596       _input_static_archive_path = CDSPreimage;
 597       _output_archive_path = CacheDataStore;
 598     }
 599   } else if (is_using_archive()) {
 600     _input_static_archive_path = CacheDataStore;
 601   }
 602 }
 603 
 604 bool CDSConfig::check_vm_args_consistency(bool patch_mod_javabase, bool mode_flag_cmd_line, bool xshare_auto_cmd_line) {
 605   assert(!_cds_ergo_initialize_started, "This is called earlier than CDSConfig::ergo_initialize()");
 606 
 607   check_aot_flags();
 608 
 609   if (!FLAG_IS_DEFAULT(AOTMode)) {
 610     // Using any form of the new AOTMode switch enables enhanced optimizations.
 611     FLAG_SET_ERGO_IF_DEFAULT(AOTClassLinking, true);
 612   }
 613 
 614   if (CacheDataStore != nullptr) {
 615     if (!setup_experimental_leyden_workflow(xshare_auto_cmd_line)) {
 616       return false;
 617     }
 618   } else {
 619     if (CDSPreimage != nullptr) {
 620       vm_exit_during_initialization("CDSPreimage must be specified only when CacheDataStore is specified");
 621     }
 622 
 623     setup_compiler_args();
 624   }
 625 
 626   if (AOTClassLinking) {
 627     // If AOTClassLinking is specified, enable all these optimizations by default.
 628     FLAG_SET_ERGO_IF_DEFAULT(AOTInvokeDynamicLinking, true);
 629     FLAG_SET_ERGO_IF_DEFAULT(ArchiveDynamicProxies, true);
 630     FLAG_SET_ERGO_IF_DEFAULT(ArchiveLoaderLookupCache, true);
 631     FLAG_SET_ERGO_IF_DEFAULT(ArchivePackages, true);
 632     FLAG_SET_ERGO_IF_DEFAULT(ArchiveProtectionDomains, true);
 633     FLAG_SET_ERGO_IF_DEFAULT(ArchiveReflectionData, true);
 634   } else {
 635     // All of these *might* depend on AOTClassLinking. Better be safe than sorry.
 636     FLAG_SET_ERGO(AOTInvokeDynamicLinking, false);
 637     FLAG_SET_ERGO(ArchiveDynamicProxies, false);
 638     FLAG_SET_ERGO(ArchiveLoaderLookupCache, false);
 639     FLAG_SET_ERGO(ArchivePackages, false);
 640     FLAG_SET_ERGO(ArchiveProtectionDomains, false);
 641     FLAG_SET_ERGO(ArchiveReflectionData, false);
 642 
 643     if (CDSConfig::is_dumping_archive()) {
 644       FLAG_SET_ERGO(AOTRecordTraining, false);
 645       FLAG_SET_ERGO(AOTReplayTraining, false);
 646       FLAG_SET_ERGO(StoreCachedCode, false);
 647       FLAG_SET_ERGO(LoadCachedCode, false);
 648     }
 649   }
 650 
 651   if (StoreCachedCode) {
 652     log_info(cds)("ArchiveAdapters is enabled");
 653     FLAG_SET_ERGO_IF_DEFAULT(ArchiveAdapters, true);
 654   }
 655 
 656 #ifdef _WINDOWS
 657   // This optimization is not working on Windows for some reason. See JDK-8338604.
 658   FLAG_SET_ERGO(ArchiveReflectionData, false);
 659 #endif
 660 
 661   if (is_dumping_static_archive()) {
 662     if (is_dumping_preimage_static_archive() || is_dumping_final_static_archive()) {
 663       // Don't tweak execution mode
 664     } else if (!mode_flag_cmd_line) {
 665       // By default, -Xshare:dump runs in interpreter-only mode, which is required for deterministic archive.
 666       //
 667       // If your classlist is large and you don't care about deterministic dumping, you can use
 668       // -Xshare:dump -Xmixed to improve dumping speed.
 669       Arguments::set_mode_flags(Arguments::_int);
 670     } else if (Arguments::mode() == Arguments::_comp) {
 671       // -Xcomp may use excessive CPU for the test tiers. Also, -Xshare:dump runs a small and fixed set of
 672       // Java code, so there's not much benefit in running -Xcomp.
 673       log_info(cds)("reduced -Xcomp to -Xmixed for static dumping");
 674       Arguments::set_mode_flags(Arguments::_mixed);
 675     }
 676 
 677     // String deduplication may cause CDS to iterate the strings in different order from one
 678     // run to another which resulting in non-determinstic CDS archives.
 679     // Disable UseStringDeduplication while dumping CDS archive.
 680     UseStringDeduplication = false;
 681   }
 682 
 683   // RecordDynamicDumpInfo is not compatible with ArchiveClassesAtExit
 684   if (ArchiveClassesAtExit != nullptr && RecordDynamicDumpInfo) {
 685     jio_fprintf(defaultStream::output_stream(),
 686                 "-XX:+RecordDynamicDumpInfo cannot be used with -XX:ArchiveClassesAtExit.\n");
 687     return false;
 688   }
 689 
 690   if (ArchiveClassesAtExit == nullptr && !RecordDynamicDumpInfo) {
 691     disable_dumping_dynamic_archive();
 692   } else {
 693     enable_dumping_dynamic_archive(ArchiveClassesAtExit);
 694   }
 695 
 696   if (AutoCreateSharedArchive) {
 697     if (SharedArchiveFile == nullptr) {
 698       log_warning(cds)("-XX:+AutoCreateSharedArchive requires -XX:SharedArchiveFile");
 699       return false;
 700     }
 701     if (ArchiveClassesAtExit != nullptr) {
 702       log_warning(cds)("-XX:+AutoCreateSharedArchive does not work with ArchiveClassesAtExit");
 703       return false;
 704     }
 705   }
 706 
 707   if (is_using_archive() && patch_mod_javabase) {
 708     Arguments::no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
 709   }
 710   if (is_using_archive() && has_unsupported_runtime_module_options()) {
 711     UseSharedSpaces = false;
 712   }
 713 
 714   if (is_dumping_archive()) {
 715     // Always verify non-system classes during CDS dump
 716     if (!BytecodeVerificationRemote) {
 717       BytecodeVerificationRemote = true;
 718       log_info(cds)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");
 719     }
 720   }
 721 
 722   if (AOTClassLinking) {
 723     if (is_dumping_final_static_archive() && !is_dumping_full_module_graph()) {
 724       if (bad_module_prop_key != nullptr) {
 725         log_warning(cds)("optimized module handling/full module graph: disabled due to incompatible property: %s=%s",
 726                          bad_module_prop_key, bad_module_prop_value);
 727       }
 728       if (is_experimental_leyden_workflow()) {
 729         vm_exit_during_initialization("CacheDataStore cannot be created because AOTClassLinking is enabled but full module graph is disabled");
 730       } else {
 731         vm_exit_during_initialization("AOT cache cannot be created because AOTClassLinking is enabled but full module graph is disabled");
 732       }
 733     }
 734   }
 735 
 736   return true;
 737 }
 738 
 739 void CDSConfig::setup_compiler_args() {
 740   // AOT profiles and AOT-compiled methods are supported only in the JEP 483 workflow.
 741   bool can_dump_profile_and_compiled_code = AOTClassLinking && new_aot_flags_used();
 742 
 743   if (is_dumping_preimage_static_archive() && can_dump_profile_and_compiled_code) {
 744     // JEP 483 workflow -- training
 745     FLAG_SET_ERGO_IF_DEFAULT(AOTRecordTraining, true);
 746     FLAG_SET_ERGO(AOTReplayTraining, false);
 747     FLAG_SET_ERGO(StoreCachedCode, false);
 748     FLAG_SET_ERGO(LoadCachedCode, false);
 749   } else if (is_dumping_final_static_archive() && can_dump_profile_and_compiled_code) {
 750     // JEP 483 workflow -- assembly
 751     FLAG_SET_ERGO(AOTRecordTraining, false); // This will be updated inside MetaspaceShared::preload_and_dump()
 752     FLAG_SET_ERGO_IF_DEFAULT(AOTReplayTraining, true);
 753     FLAG_SET_ERGO_IF_DEFAULT(StoreCachedCode, true);
 754     FLAG_SET_ERGO(LoadCachedCode, false);
 755     disable_dumping_cached_code(); // Cannot dump cached code until metadata and heap are dumped.
 756   } else if (is_using_archive() && new_aot_flags_used()) {
 757     // JEP 483 workflow -- production
 758     FLAG_SET_ERGO(AOTRecordTraining, false);
 759     FLAG_SET_ERGO_IF_DEFAULT(AOTReplayTraining, true);
 760     FLAG_SET_ERGO(StoreCachedCode, false);
 761     FLAG_SET_ERGO_IF_DEFAULT(LoadCachedCode, true);
 762 
 763     if (UseSharedSpaces && FLAG_IS_DEFAULT(AOTMode)) {
 764       log_info(cds)("Enabled -XX:AOTMode=on by default for troubleshooting Leyden prototype");
 765       RequireSharedSpaces = true;
 766     }
 767   } else {
 768     FLAG_SET_ERGO(AOTReplayTraining, false);
 769     FLAG_SET_ERGO(AOTRecordTraining, false);
 770     FLAG_SET_ERGO(StoreCachedCode, false);
 771     FLAG_SET_ERGO(LoadCachedCode, false);
 772   }
 773 }
 774 
 775 // Ergo set-up of various flags used by the experimental workflow that uses -XX:CacheDataStore. This workflow
 776 // is deprecated and will be removed from Leyden.
 777 bool CDSConfig::setup_experimental_leyden_workflow(bool xshare_auto_cmd_line) {
 778   // Leyden temp work-around:
 779   //
 780   // By default, when using CacheDataStore, use the HeapBasedNarrowOop mode so that
 781   // AOT code can be always work regardless of runtime heap range.
 782   //
 783   // If you are *absolutely sure* that the CompressedOops::mode() will be the same
 784   // between training and production runs (e.g., if you specify -Xmx128m
 785   // for both training and production runs, and you know the OS will always reserve
 786   // the heap under 4GB), you can explicitly disable this with:
 787   //     java -XX:-UseCompatibleCompressedOops -XX:CacheDataStore=...
 788   // However, this is risky and there's a chance that the production run will be slower
 789   // because it is unable to load the AOT code cache.
 790 #ifdef _LP64
 791   // FLAG_SET_ERGO_IF_DEFAULT(UseCompatibleCompressedOops, true); // FIXME @iklam - merge with mainline - UseCompatibleCompressedOops
 792 #endif
 793 
 794   if (FLAG_IS_DEFAULT(AOTClassLinking)) {
 795     FLAG_SET_ERGO(AOTClassLinking, true);
 796   }
 797 
 798   if (SharedArchiveFile != nullptr) {
 799     vm_exit_during_initialization("CacheDataStore and SharedArchiveFile cannot be both specified");
 800   }
 801   if (!AOTClassLinking) {
 802     vm_exit_during_initialization("CacheDataStore requires AOTClassLinking");
 803   }
 804 
 805   if (CDSPreimage == nullptr) {
 806     if (os::file_exists(CacheDataStore) /* && TODO: Need to check if CDS file is valid*/) {
 807       // The CacheDataStore is already up to date. Use it. Also turn on cached code by default.
 808       FLAG_SET_ERGO_IF_DEFAULT(AOTReplayTraining, true);
 809       FLAG_SET_ERGO_IF_DEFAULT(LoadCachedCode, true);
 810 
 811       // Leyden temp: make sure the user knows if CDS archive somehow fails to load.
 812       if (UseSharedSpaces && !xshare_auto_cmd_line) {
 813         log_info(cds)("Enabled -Xshare:on by default for troubleshooting Leyden prototype");
 814         RequireSharedSpaces = true;
 815       }
 816     } else {
 817       // The preimage dumping phase -- run the app and write the preimage file
 818       size_t len = strlen(CacheDataStore) + 10;
 819       char* preimage = AllocateHeap(len, mtArguments);
 820       jio_snprintf(preimage, len, "%s.preimage", CacheDataStore);
 821 
 822       UseSharedSpaces = false;
 823       enable_dumping_static_archive();
 824       CDSPreimage = preimage;
 825       log_info(cds)("CacheDataStore needs to be updated. Writing %s file", CDSPreimage);
 826 
 827       // At VM exit, the module graph may be contaminated with program states. We should rebuild the
 828       // module graph when dumping the CDS final image.
 829       log_info(cds)("full module graph: disabled when writing CDS preimage");
 830       disable_heap_dumping();
 831       stop_dumping_full_module_graph();
 832       FLAG_SET_ERGO(ArchivePackages, false);
 833       FLAG_SET_ERGO(ArchiveProtectionDomains, false);
 834       FLAG_SET_ERGO_IF_DEFAULT(AOTRecordTraining, true);
 835       _is_dumping_static_archive = true;
 836       _is_dumping_preimage_static_archive = true;
 837     }
 838   } else {
 839     // The final image dumping phase -- load the preimage and write the final image file
 840     UseSharedSpaces = true;
 841     log_info(cds)("Generate CacheDataStore %s from CDSPreimage %s", CacheDataStore, CDSPreimage);
 842     // Force -Xbatch for AOT compilation.
 843     if (FLAG_SET_CMDLINE(BackgroundCompilation, false) != JVMFlag::SUCCESS) {
 844       return false;
 845     }
 846     AOTRecordTraining = false; // This will be updated inside MetaspaceShared::preload_and_dump()
 847 
 848     FLAG_SET_ERGO_IF_DEFAULT(AOTReplayTraining, true);
 849     // Settings for AOT
 850     FLAG_SET_ERGO_IF_DEFAULT(StoreCachedCode, true);
 851     if (StoreCachedCode) {
 852       // Cannot dump cached code until metadata and heap are dumped.
 853       disable_dumping_cached_code();
 854     }
 855     _is_dumping_static_archive = true;
 856     _is_dumping_final_static_archive = true;
 857   }
 858 
 859   return true;
 860 }
 861 
 862 void CDSConfig::prepare_for_dumping() {
 863   assert(CDSConfig::is_dumping_archive(), "sanity");
 864 
 865   if (is_dumping_dynamic_archive() && !is_using_archive()) {
 866     assert(!is_dumping_static_archive(), "cannot be dumping both static and dynamic archives");
 867 
 868     // This could happen if SharedArchiveFile has failed to load:
 869     // - -Xshare:off was specified
 870     // - SharedArchiveFile points to an non-existent file.
 871     // - SharedArchiveFile points to an archive that has failed CRC check
 872     // - SharedArchiveFile is not specified and the VM doesn't have a compatible default archive
 873 
 874 #define __THEMSG " is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info."
 875     if (RecordDynamicDumpInfo) {
 876       log_error(cds)("-XX:+RecordDynamicDumpInfo%s", __THEMSG);
 877       MetaspaceShared::unrecoverable_loading_error();
 878     } else {
 879       assert(ArchiveClassesAtExit != nullptr, "sanity");
 880       log_warning(cds)("-XX:ArchiveClassesAtExit" __THEMSG);
 881     }
 882 #undef __THEMSG
 883     disable_dumping_dynamic_archive();
 884     return;
 885   }
 886 
 887   check_unsupported_dumping_module_options();
 888 }
 889 
 890 bool CDSConfig::is_dumping_classic_static_archive() {
 891   return _is_dumping_static_archive &&
 892     !is_dumping_preimage_static_archive() &&
 893     !is_dumping_final_static_archive();
 894 }
 895 
 896 bool CDSConfig::is_dumping_preimage_static_archive() {
 897   return _is_dumping_preimage_static_archive;
 898 }
 899 
 900 bool CDSConfig::is_dumping_preimage_static_archive_with_triggers() {
 901   return (!FLAG_IS_DEFAULT(AOTEndTrainingOnMethodEntry)) && is_dumping_preimage_static_archive();
 902 }
 903 
 904 bool CDSConfig::is_dumping_final_static_archive() {
 905   return _is_dumping_final_static_archive;
 906 }
 907 
 908 void CDSConfig::enable_dumping_dynamic_archive(const char* output_path) {
 909   _is_dumping_dynamic_archive = true;
 910   if (output_path == nullptr) {
 911     // output_path can be null when the VM is started with -XX:+RecordDynamicDumpInfo
 912     // in anticipation of "jcmd VM.cds dynamic_dump", which will provide the actual
 913     // output path.
 914     _output_archive_path = nullptr;
 915   } else {
 916     _output_archive_path = os::strdup_check_oom(output_path, mtArguments);
 917   }
 918 }
 919 
 920 bool CDSConfig::allow_only_single_java_thread() {
 921   // See comments in JVM_StartThread()
 922   return is_dumping_classic_static_archive() || is_dumping_final_static_archive();
 923 }
 924 
 925 bool CDSConfig::is_logging_dynamic_proxies() {
 926   return ClassListWriter::is_enabled() || is_dumping_preimage_static_archive();
 927 }
 928 
 929 // Preserve all states that were examined used during dumptime verification, such
 930 // that the verification result (pass or fail) cannot be changed at runtime.
 931 //
 932 // For example, if the verification of ik requires that class A must be a subtype of B,
 933 // then this relationship between A and B cannot be changed at runtime. I.e., the app
 934 // cannot load alternative versions of A and B such that A is not a subtype of B.
 935 bool CDSConfig::preserve_all_dumptime_verification_states(const InstanceKlass* ik) {
 936   return is_dumping_aot_linked_classes() && SystemDictionaryShared::is_builtin(ik);
 937 }
 938 
 939 bool CDSConfig::is_using_archive() {
 940   return UseSharedSpaces;
 941 }
 942 
 943 bool CDSConfig::is_logging_lambda_form_invokers() {
 944   return ClassListWriter::is_enabled() || is_dumping_dynamic_archive() || is_dumping_preimage_static_archive();
 945 }
 946 
 947 bool CDSConfig::is_dumping_regenerated_lambdaform_invokers() {
 948   if (is_dumping_final_static_archive()) {
 949     // No need to regenerate -- the lambda form invokers should have been regenerated
 950     // in the preimage archive (if allowed)
 951     return false;
 952   } else if (is_dumping_dynamic_archive() && is_using_aot_linked_classes()) {
 953     // The base archive has aot-linked classes that may have AOT-resolved CP references
 954     // that point to the lambda form invokers in the base archive. Such pointers will
 955     // be invalid if lambda form invokers are regenerated in the dynamic archive.
 956     return false;
 957   } else if (CDSConfig::is_dumping_method_handles()) {
 958     // Work around JDK-8310831, as some methods in lambda form holder classes may not get generated.
 959     return false;
 960   } else {
 961     return is_dumping_archive();
 962   }
 963 }
 964 
 965 void CDSConfig::stop_using_optimized_module_handling() {
 966   _is_using_optimized_module_handling = false;
 967   _is_dumping_full_module_graph = false; // This requires is_using_optimized_module_handling()
 968   _is_using_full_module_graph = false; // This requires is_using_optimized_module_handling()
 969 }
 970 
 971 
 972 CDSConfig::DumperThreadMark::DumperThreadMark(JavaThread* current) {
 973   assert(_dumper_thread == nullptr, "sanity");
 974   _dumper_thread = current;
 975 }
 976 
 977 CDSConfig::DumperThreadMark::~DumperThreadMark() {
 978   assert(_dumper_thread != nullptr, "sanity");
 979   _dumper_thread = nullptr;
 980 }
 981 
 982 bool CDSConfig::current_thread_is_vm_or_dumper() {
 983   Thread* t = Thread::current();
 984   return t != nullptr && (t->is_VM_thread() || t == _dumper_thread);
 985 }
 986 
 987 const char* CDSConfig::type_of_archive_being_loaded() {
 988   if (is_dumping_final_static_archive()) {
 989     return "AOT configuration file";
 990   } else if (new_aot_flags_used()) {
 991     return "AOT cache";
 992   } else {
 993     return "shared archive file";
 994   }
 995 }
 996 
 997 const char* CDSConfig::type_of_archive_being_written() {
 998   if (is_dumping_preimage_static_archive()) {
 999     return "AOT configuration file";
1000   } else if (new_aot_flags_used()) {
1001     return "AOT cache";
1002   } else {
1003     return "shared archive file";
1004   }
1005 }
1006 
1007 // If an incompatible VM options is found, return a text message that explains why
1008 static const char* check_options_incompatible_with_dumping_heap() {
1009 #if INCLUDE_CDS_JAVA_HEAP
1010   if (!UseCompressedClassPointers) {
1011     return "UseCompressedClassPointers must be true";
1012   }
1013 
1014   // Almost all GCs support heap region dump, except ZGC (so far).
1015   if (UseZGC) {
1016     return "ZGC is not supported";
1017   }
1018 
1019   return nullptr;
1020 #else
1021   return "JVM not configured for writing Java heap objects";
1022 #endif
1023 }
1024 
1025 void CDSConfig::log_reasons_for_not_dumping_heap() {
1026   const char* reason;
1027 
1028   assert(!is_dumping_heap(), "sanity");
1029 
1030   if (_disable_heap_dumping) {
1031     reason = "Programmatically disabled";
1032   } else {
1033     reason = check_options_incompatible_with_dumping_heap();
1034   }
1035 
1036   assert(reason != nullptr, "sanity");
1037   log_info(cds)("Archived java heap is not supported: %s", reason);
1038 }
1039 
1040 // This is *Legacy* optimization for lambdas before JEP 483. May be removed in the future.
1041 bool CDSConfig::is_dumping_lambdas_in_legacy_mode() {
1042   return !is_dumping_method_handles();
1043 }
1044 
1045 #if INCLUDE_CDS_JAVA_HEAP
1046 bool CDSConfig::are_vm_options_incompatible_with_dumping_heap() {
1047   return check_options_incompatible_with_dumping_heap() != nullptr;
1048 }
1049 
1050 bool CDSConfig::is_dumping_heap() {
1051   if (!(is_dumping_classic_static_archive() || is_dumping_final_static_archive())
1052       || are_vm_options_incompatible_with_dumping_heap()
1053       || _disable_heap_dumping) {
1054     return false;
1055   }
1056   return true;
1057 }
1058 
1059 bool CDSConfig::is_loading_heap() {
1060   return ArchiveHeapLoader::is_in_use();
1061 }
1062 
1063 bool CDSConfig::is_using_full_module_graph() {
1064   if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
1065     return true;
1066   }
1067 
1068   if (!_is_using_full_module_graph) {
1069     return false;
1070   }
1071 
1072   if (is_using_archive() && ArchiveHeapLoader::can_use()) {
1073     // Classes used by the archived full module graph are loaded in JVMTI early phase.
1074     assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
1075            "CDS should be disabled if early class hooks are enabled");
1076     return true;
1077   } else {
1078     _is_using_full_module_graph = false;
1079     return false;
1080   }
1081 }
1082 
1083 void CDSConfig::stop_dumping_full_module_graph(const char* reason) {
1084   if (_is_dumping_full_module_graph) {
1085     _is_dumping_full_module_graph = false;
1086     if (reason != nullptr) {
1087       log_info(cds)("full module graph cannot be dumped: %s", reason);
1088     }
1089   }
1090 }
1091 
1092 void CDSConfig::stop_using_full_module_graph(const char* reason) {
1093   assert(!ClassLoaderDataShared::is_full_module_graph_loaded(), "you call this function too late!");
1094   if (_is_using_full_module_graph) {
1095     _is_using_full_module_graph = false;
1096     if (reason != nullptr) {
1097       log_info(cds)("full module graph cannot be loaded: %s", reason);
1098     }
1099   }
1100 }
1101 
1102 bool CDSConfig::is_dumping_aot_linked_classes() {
1103   if (is_dumping_preimage_static_archive()) {
1104     return false;
1105   } else if (is_dumping_dynamic_archive()) {
1106     return is_using_full_module_graph() && AOTClassLinking;
1107   } else if (is_dumping_static_archive()) {
1108     return is_dumping_full_module_graph() && AOTClassLinking;
1109   } else {
1110     return false;
1111   }
1112 }
1113 
1114 bool CDSConfig::is_using_aot_linked_classes() {
1115   if (is_dumping_final_static_archive()) {
1116     // We assume that the final image is being dumped with the exact same module graph as the training run,
1117     // so all aot-linked classes can be loaded.
1118     return _has_aot_linked_classes;
1119   }
1120   // Make sure we have the exact same module graph as in the assembly phase, or else
1121   // some aot-linked classes may not be visible so cannot be loaded.
1122   return is_using_full_module_graph() && _has_aot_linked_classes;
1123 }
1124 
1125 bool CDSConfig::is_dumping_dynamic_proxies() {
1126   return is_dumping_full_module_graph() && is_dumping_invokedynamic() && ArchiveDynamicProxies;
1127 }
1128 
1129 void CDSConfig::set_has_aot_linked_classes(bool has_aot_linked_classes) {
1130   _has_aot_linked_classes |= has_aot_linked_classes;
1131 }
1132 
1133 bool CDSConfig::is_initing_classes_at_dump_time() {
1134   return is_dumping_heap() && is_dumping_aot_linked_classes();
1135 }
1136 
1137 bool CDSConfig::is_dumping_invokedynamic() {
1138   // Requires is_dumping_aot_linked_classes(). Otherwise the classes of some archived heap
1139   // objects used by the archive indy callsites may be replaced at runtime.
1140   return AOTInvokeDynamicLinking && is_dumping_aot_linked_classes() && is_dumping_heap();
1141 }
1142 
1143 bool CDSConfig::is_dumping_packages() {
1144   return ArchivePackages && is_dumping_heap();
1145 }
1146 
1147 bool CDSConfig::is_loading_packages() {
1148   return UseSharedSpaces && is_using_full_module_graph() && _is_loading_packages;
1149 }
1150 
1151 bool CDSConfig::is_dumping_protection_domains() {
1152   if (_is_security_manager_allowed) {
1153     // For sanity, don't archive PDs. TODO: can this be relaxed?
1154     return false;
1155   }
1156   // Archived PDs for the modules will reference their java.lang.Module, which must
1157   // also be archived.
1158   return ArchiveProtectionDomains && is_dumping_full_module_graph();
1159 }
1160 
1161 bool CDSConfig::is_loading_protection_domains() {
1162   if (_is_security_manager_allowed) {
1163     // For sanity, don't used any archived PDs. TODO: can this be relaxed?
1164     return false;
1165   }
1166   return UseSharedSpaces && is_using_full_module_graph() && _is_loading_protection_domains;
1167 }
1168 
1169 bool CDSConfig::is_dumping_reflection_data() {
1170   // reflection data use LambdaForm classes
1171   return ArchiveReflectionData && is_dumping_invokedynamic();
1172 }
1173 
1174 // When we are dumping aot-linked classes and we are able to write archived heap objects, we automatically
1175 // enable the archiving of MethodHandles. This will in turn enable the archiving of MethodTypes and hidden
1176 // classes that are used in the implementation of MethodHandles.
1177 // Archived MethodHandles are required for higher-level optimizations such as AOT resolution of invokedynamic
1178 // and dynamic proxies.
1179 bool CDSConfig::is_dumping_method_handles() {
1180   return is_initing_classes_at_dump_time();
1181 }
1182 
1183 #endif // INCLUDE_CDS_JAVA_HEAP
1184 
1185 // This is allowed by default. We disable it only in the final image dump before the
1186 // metadata and heap are dumped.
1187 static bool _is_dumping_cached_code = true;
1188 
1189 bool CDSConfig::is_dumping_cached_code() {
1190   return _is_dumping_cached_code;
1191 }
1192 
1193 void CDSConfig::disable_dumping_cached_code() {
1194   _is_dumping_cached_code = false;
1195 }
1196 
1197 void CDSConfig::enable_dumping_cached_code() {
1198   _is_dumping_cached_code = true;
1199 }
1200 
1201 bool CDSConfig::is_dumping_adapters() {
1202   return (ArchiveAdapters && is_dumping_final_static_archive());
1203 }
1204 
1205 bool CDSConfig::is_experimental_leyden_workflow() {
1206   return CacheDataStore != nullptr || CDSPreimage != nullptr;
1207 }