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