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