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