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