< prev index next >

src/hotspot/share/cds/metaspaceShared.cpp

Print this page

   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/aotArtifactFinder.hpp"
  26 #include "cds/aotClassInitializer.hpp"
  27 #include "cds/aotClassLinker.hpp"
  28 #include "cds/aotClassLocation.hpp"
  29 #include "cds/aotConstantPoolResolver.hpp"
  30 #include "cds/aotLinkedClassBulkLoader.hpp"
  31 #include "cds/aotLogging.hpp"
  32 #include "cds/aotReferenceObjSupport.hpp"
  33 #include "cds/archiveBuilder.hpp"
  34 #include "cds/archiveHeapLoader.hpp"
  35 #include "cds/archiveHeapWriter.hpp"
  36 #include "cds/cds_globals.hpp"
  37 #include "cds/cdsConfig.hpp"
  38 #include "cds/cdsProtectionDomain.hpp"
  39 #include "cds/classListParser.hpp"
  40 #include "cds/classListWriter.hpp"
  41 #include "cds/cppVtables.hpp"
  42 #include "cds/dumpAllocStats.hpp"
  43 #include "cds/dynamicArchive.hpp"
  44 #include "cds/filemap.hpp"
  45 #include "cds/finalImageRecipes.hpp"
  46 #include "cds/heapShared.hpp"
  47 #include "cds/lambdaFormInvokers.hpp"
  48 #include "cds/lambdaProxyClassDictionary.hpp"
  49 #include "cds/metaspaceShared.hpp"
  50 #include "classfile/classLoaderDataGraph.hpp"
  51 #include "classfile/classLoaderDataShared.hpp"
  52 #include "classfile/classLoaderExt.hpp"
  53 #include "classfile/javaClasses.inline.hpp"
  54 #include "classfile/loaderConstraints.hpp"
  55 #include "classfile/modules.hpp"
  56 #include "classfile/placeholders.hpp"
  57 #include "classfile/stringTable.hpp"
  58 #include "classfile/symbolTable.hpp"
  59 #include "classfile/systemDictionary.hpp"
  60 #include "classfile/systemDictionaryShared.hpp"
  61 #include "classfile/vmClasses.hpp"
  62 #include "classfile/vmSymbols.hpp"
  63 #include "code/aotCodeCache.hpp"
  64 #include "code/codeCache.hpp"


  65 #include "gc/shared/gcVMOperations.hpp"
  66 #include "interpreter/bytecodeStream.hpp"
  67 #include "interpreter/bytecodes.hpp"
  68 #include "jvm_io.h"
  69 #include "logging/log.hpp"
  70 #include "logging/logMessage.hpp"
  71 #include "logging/logStream.hpp"
  72 #include "memory/memoryReserver.hpp"
  73 #include "memory/metaspace.hpp"
  74 #include "memory/metaspaceClosure.hpp"
  75 #include "memory/oopFactory.hpp"
  76 #include "memory/resourceArea.hpp"
  77 #include "memory/universe.hpp"
  78 #include "nmt/memTracker.hpp"
  79 #include "oops/compressedKlass.hpp"
  80 #include "oops/instanceMirrorKlass.hpp"
  81 #include "oops/klass.inline.hpp"

  82 #include "oops/objArrayOop.hpp"
  83 #include "oops/oop.inline.hpp"
  84 #include "oops/oopHandle.hpp"
  85 #include "oops/trainingData.hpp"
  86 #include "prims/jvmtiExport.hpp"

  87 #include "runtime/arguments.hpp"
  88 #include "runtime/globals.hpp"
  89 #include "runtime/globals_extension.hpp"
  90 #include "runtime/handles.inline.hpp"
  91 #include "runtime/javaCalls.hpp"
  92 #include "runtime/os.inline.hpp"
  93 #include "runtime/safepointVerifiers.hpp"
  94 #include "runtime/sharedRuntime.hpp"
  95 #include "runtime/vmOperations.hpp"
  96 #include "runtime/vmThread.hpp"
  97 #include "sanitizers/leak.hpp"

  98 #include "utilities/align.hpp"
  99 #include "utilities/bitMap.inline.hpp"
 100 #include "utilities/defaultStream.hpp"
 101 #include "utilities/macros.hpp"
 102 #include "utilities/ostream.hpp"
 103 #include "utilities/resourceHash.hpp"
 104 
 105 #include <sys/stat.h>
 106 
 107 ReservedSpace MetaspaceShared::_symbol_rs;
 108 VirtualSpace MetaspaceShared::_symbol_vs;
 109 bool MetaspaceShared::_archive_loading_failed = false;
 110 bool MetaspaceShared::_remapped_readwrite = false;
 111 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
 112 intx MetaspaceShared::_relocation_delta;
 113 char* MetaspaceShared::_requested_base_address;
 114 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr;
 115 bool MetaspaceShared::_use_optimized_module_handling = true;


 116 
 117 // The CDS archive is divided into the following regions:
 118 //     rw  - read-write metadata
 119 //     ro  - read-only metadata and read-only tables
 120 //     hp  - heap region
 121 //     bm  - bitmap for relocating the above 7 regions.
 122 //
 123 // The rw and ro regions are linearly allocated, in the order of rw->ro.
 124 // These regions are aligned with MetaspaceShared::core_region_alignment().
 125 //
 126 // These 2 regions are populated in the following steps:
 127 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 128 //     temporarily allocated outside of the shared regions.
 129 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
 130 // [2] C++ vtables are copied into the rw region.
 131 // [3] ArchiveBuilder copies RW metadata into the rw region.
 132 // [4] ArchiveBuilder copies RO metadata into the ro region.
 133 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 134 //     are copied into the ro region as read-only tables.
 135 //

 276   }
 277 
 278   // Arguments::default_SharedBaseAddress() is hard-coded in cds_globals.hpp. It must be carefully
 279   // picked that (a) the align_up() below will always return a valid value; (b) none of
 280   // the following asserts will fail.
 281   aot_log_warning(aot)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
 282                    p2i((void*)SharedBaseAddress), err,
 283                    p2i((void*)Arguments::default_SharedBaseAddress()));
 284 
 285   specified_base = (char*)Arguments::default_SharedBaseAddress();
 286   aligned_base = align_up(specified_base, alignment);
 287 
 288   // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
 289   assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
 290   assert(shared_base_valid(aligned_base), "Sanity");
 291   return aligned_base;
 292 }
 293 
 294 void MetaspaceShared::initialize_for_static_dump() {
 295   assert(CDSConfig::is_dumping_static_archive(), "sanity");

















 296   aot_log_info(aot)("Core region alignment: %zu", core_region_alignment());
 297   // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
 298   // to avoid address space wrap around.
 299   size_t cds_max;
 300   const size_t reserve_alignment = core_region_alignment();
 301 
 302 #ifdef _LP64
 303   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 304   cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
 305 #else
 306   // We don't support archives larger than 256MB on 32-bit due to limited
 307   //  virtual address space.
 308   cds_max = align_down(256*M, reserve_alignment);
 309 #endif
 310 
 311   _requested_base_address = compute_shared_base(cds_max);
 312   SharedBaseAddress = (size_t)_requested_base_address;
 313 
 314   size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
 315   _symbol_rs = MemoryReserver::reserve(symbol_rs_size,

 720       _mirrors.at(i).release(Universe::vm_global());
 721     }
 722   }
 723 
 724   void do_cld(ClassLoaderData* cld) {
 725     assert(cld->is_alive(), "must be");
 726   }
 727 
 728   void do_klass(Klass* k) {
 729     if (k->is_instance_klass()) {
 730       _mirrors.append(OopHandle(Universe::vm_global(), k->java_mirror()));
 731     }
 732   }
 733 
 734   const GrowableArray<OopHandle>* mirrors() const { return &_mirrors; }
 735 };
 736 
 737 // Check if we can eagerly link this class at dump time, so we can avoid the
 738 // runtime linking overhead (especially verification)
 739 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {



 740   if (!ik->can_be_verified_at_dumptime()) {
 741     // For old classes, try to leave them in the unlinked state, so
 742     // we can still store them in the archive. They must be
 743     // linked/verified at runtime.
 744     return false;
 745   }
 746   if (CDSConfig::is_dumping_dynamic_archive() && ik->defined_by_other_loaders()) {
 747     // Linking of unregistered classes at this stage may cause more
 748     // classes to be resolved, resulting in calls to ClassLoader.loadClass()
 749     // that may not be expected by custom class loaders.
 750     //
 751     // It's OK to do this for the built-in loaders as we know they can
 752     // tolerate this.
 753     return false;
 754   }
 755   return true;
 756 }
 757 
 758 void MetaspaceShared::link_shared_classes(TRAPS) {
 759   AOTClassLinker::initialize();
 760   AOTClassInitializer::init_test_class(CHECK);
 761 
 762   while (true) {
 763     ResourceMark rm(THREAD);
 764     CollectClassesForLinking collect_classes;
 765     bool has_linked = false;
 766     const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
 767     for (int i = 0; i < mirrors->length(); i++) {
 768       OopHandle mirror = mirrors->at(i);
 769       InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve()));
 770       if (may_be_eagerly_linked(ik)) {
 771         has_linked |= try_link_class(THREAD, ik);
 772       }



 773     }
 774 
 775     if (!has_linked) {
 776       break;
 777     }
 778     // Class linking includes verification which may load more classes.
 779     // Keep scanning until we have linked no more classes.
 780   }
 781 
 782   // Eargerly resolve all string constants in constant pools
 783   {
 784     ResourceMark rm(THREAD);
 785     CollectClassesForLinking collect_classes;
 786     const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
 787     for (int i = 0; i < mirrors->length(); i++) {
 788       OopHandle mirror = mirrors->at(i);
 789       InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve()));
 790       AOTConstantPoolResolver::preresolve_string_cp_entries(ik, CHECK);



 791     }
 792   }
 793 
 794   if (CDSConfig::is_dumping_final_static_archive()) {
 795     FinalImageRecipes::apply_recipes(CHECK);
 796   }
 797 }
 798 
 799 // Preload classes from a list, populate the shared spaces and dump to a
 800 // file.
 801 void MetaspaceShared::preload_and_dump(TRAPS) {
 802   CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
 803   ResourceMark rm(THREAD);
 804  HandleMark hm(THREAD);
 805 
 806  if (CDSConfig::is_dumping_final_static_archive() && AOTPrintTrainingInfo) {
 807    tty->print_cr("==================== archived_training_data ** before dumping ====================");
 808    TrainingData::print_archived_training_data_on(tty);
 809  }
 810 
 811   StaticArchiveBuilder builder;
 812   preload_and_dump_impl(builder, THREAD);
 813   if (HAS_PENDING_EXCEPTION) {
 814     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 815       aot_log_error(aot)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 816                      "%zuM", MaxHeapSize/M);
 817       MetaspaceShared::writing_error();
 818     } else {
 819       oop message = java_lang_Throwable::message(PENDING_EXCEPTION);
 820       aot_log_error(aot)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 821                          message == nullptr ? "(null)" : java_lang_String::as_utf8_string(message));
 822       MetaspaceShared::writing_error(err_msg("Unexpected exception, use -Xlog:aot%s,exceptions=trace for detail",
 823                                              CDSConfig::new_aot_flags_used() ? "" : ",cds"));
 824     }



 825   }
 826 
 827   if (CDSConfig::new_aot_flags_used()) {
 828     if (CDSConfig::is_dumping_preimage_static_archive()) {
 829       // We are in the JVM that runs the training run. Continue execution,
 830       // so that it can finish all clean-up and return the correct exit
 831       // code to the OS.
 832     } else {
 833       // The JLI launcher only recognizes the "old" -Xshare:dump flag.
 834       // When the new -XX:AOTMode=create flag is used, we can't return
 835       // to the JLI launcher, as the launcher will fail when trying to
 836       // run the main class, which is not what we want.
 837       struct stat st;
 838       if (os::stat(AOTCache, &st) != 0) {
 839         tty->print_cr("AOTCache creation failed: %s", AOTCache);
 840         vm_exit(0);
 841       } else {
 842         tty->print_cr("AOTCache creation is complete: %s " INT64_FORMAT " bytes", AOTCache, (int64_t)(st.st_size));
 843         vm_exit(0);
 844       }

 903     }
 904   }
 905 
 906   // Some classes are used at CDS runtime but are not loaded, and therefore archived, at
 907   // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they
 908   // are archived.
 909   exercise_runtime_cds_code(CHECK);
 910 
 911   aot_log_info(aot)("Loading classes to share: done.");
 912 }
 913 
 914 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) {
 915   // Exercise the manifest processing code
 916   const char* dummy = "Manifest-Version: 1.0\n";
 917   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 918 
 919   // Exercise FileSystem and URL code
 920   CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
 921 }
 922 


















 923 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {







 924   if (CDSConfig::is_dumping_classic_static_archive()) {
 925     // We are running with -Xshare:dump
 926     preload_classes(CHECK);
 927 
 928     if (SharedArchiveConfigFile) {
 929       log_info(aot)("Reading extra data from %s ...", SharedArchiveConfigFile);
 930       read_extra_data(THREAD, SharedArchiveConfigFile);
 931       log_info(aot)("Reading extra data: done.");
 932     }
 933   }
 934 
 935   if (CDSConfig::is_dumping_preimage_static_archive()) {
 936     log_info(aot)("Reading lambda form invokers from JDK default classlist ...");
 937     char default_classlist[JVM_MAXPATHLEN];
 938     get_default_classlist(default_classlist, JVM_MAXPATHLEN);
 939     struct stat statbuf;
 940     if (os::stat(default_classlist, &statbuf) == 0) {
 941       ClassListParser::parse_classlist(default_classlist,
 942                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
 943     }

 970   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 971   // fails verification, all other interfaces that were not specified in the classlist but
 972   // are implemented by K are not verified.
 973   link_shared_classes(CHECK);
 974   log_info(aot)("Rewriting and linking classes: done");
 975   TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
 976 
 977   if (CDSConfig::is_dumping_regenerated_lambdaform_invokers()) {
 978     LambdaFormInvokers::regenerate_holder_classes(CHECK);
 979   }
 980 
 981 #if INCLUDE_CDS_JAVA_HEAP
 982   if (CDSConfig::is_dumping_heap()) {
 983     ArchiveHeapWriter::init();
 984 
 985     if (CDSConfig::is_dumping_full_module_graph()) {
 986       ClassLoaderDataShared::ensure_module_entry_tables_exist();
 987       HeapShared::reset_archived_object_states(CHECK);
 988     }
 989 




 990     AOTReferenceObjSupport::initialize(CHECK);
 991     AOTReferenceObjSupport::stabilize_cached_reference_objects(CHECK);
 992 
 993     if (CDSConfig::is_initing_classes_at_dump_time()) {
 994       // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
 995       // to null, and it will be initialized again at runtime.
 996       log_debug(aot)("Resetting Class::reflectionFactory");
 997       TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
 998       Symbol* method_sig = vmSymbols::void_method_signature();
 999       JavaValue result(T_VOID);
1000       JavaCalls::call_static(&result, vmClasses::Class_klass(),
1001                              method_name, method_sig, CHECK);
1002 
1003       // Perhaps there is a way to avoid hard-coding these names here.
1004       // See discussion in JDK-8342481.
1005     }
1006 
1007     // Do this at the very end, when no Java code will be executed. Otherwise
1008     // some new strings may be added to the intern table.
1009     StringTable::allocate_shared_strings_array(CHECK);
1010   } else {
1011     log_info(aot)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
1012     CDSConfig::stop_using_optimized_module_handling();
1013   }
1014 #endif
1015 
1016   VM_PopulateDumpSharedSpace op(builder);
1017   VMThread::execute(&op);














1018 
1019   if (AOTCodeCache::is_on_for_dump() && CDSConfig::is_dumping_final_static_archive()) {
1020     CDSConfig::enable_dumping_aot_code();
1021     {
1022       builder.start_ac_region();
1023       // Write the contents to AOT code region and close AOTCodeCache before packing the region
1024       AOTCodeCache::close();
1025       builder.end_ac_region();




1026     }
1027     CDSConfig::disable_dumping_aot_code();
1028   }
1029 
1030   bool status = write_static_archive(&builder, op.map_info(), op.heap_info());
1031   if (status && CDSConfig::is_dumping_preimage_static_archive()) {
1032     tty->print_cr("%s AOTConfiguration recorded: %s",
1033                   CDSConfig::has_temp_aot_config_file() ? "Temporary" : "", AOTConfiguration);
1034     if (CDSConfig::is_single_command_training()) {
1035       fork_and_dump_final_static_archive(CHECK);




1036     }
1037   }
1038 
1039   if (!status) {
1040     THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
1041   }
1042 }
1043 
1044 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
1045   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1046   // without runtime relocation.
1047   builder->relocate_to_requested();
1048 
1049   map_info->open_as_output();
1050   if (!map_info->is_open()) {
1051     return false;
1052   }
1053   builder->write_archive(map_info, heap_info);
1054 
1055   if (AllowArchivingWithJavaAgent) {

1086     // CDS$ProcessLauncher::execWithJavaToolOptions() must unset CLASSPATH, which has
1087     // a higher priority than -Djava.class.path=
1088   }
1089 
1090   // Pass all arguments. These include those from JAVA_TOOL_OPTIONS and _JAVA_OPTIONS.
1091   for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1092     const char* arg = Arguments::jvm_args_array()[i];
1093     if (strstr(arg, "-XX:AOTCacheOutput=") == arg || // arg starts with ...
1094         strstr(arg, "-XX:AOTConfiguration=") == arg ||
1095         strstr(arg, "-XX:AOTMode=") == arg) {
1096       // Filter these out. They wiill be set below.
1097     } else {
1098       append_args(&args, arg, CHECK_0);
1099     }
1100   }
1101 
1102   // Note: because we are running in AOTMode=record, JDK_AOT_VM_OPTIONS have not been
1103   // parsed, so they are not in Arguments::jvm_args_array. If JDK_AOT_VM_OPTIONS is in
1104   // the environment, it will be inherited and parsed by the child JVM process
1105   // in Arguments::parse_java_tool_options_environment_variable().
1106   precond(strcmp(AOTMode, "record") == 0);
1107 
1108   // We don't pass Arguments::jvm_flags_array(), as those will be added by
1109   // the child process when it loads .hotspotrc
1110 
1111   {









1112     // If AOTCacheOutput contains %p, it should have been already substituted with the
1113     // pid of the training process.
1114     stringStream ss;
1115     ss.print("-XX:AOTCacheOutput=");
1116     ss.print_raw(AOTCacheOutput);
1117     append_args(&args, ss.freeze(), CHECK_0);
1118   }
1119   {
1120     // If AOTCacheConfiguration contains %p, it should have been already substituted with the
1121     // pid of the training process.
1122     // If AOTCacheConfiguration was not explicitly specified, it should have been assigned a
1123     // temporary file name.
1124     stringStream ss;
1125     ss.print("-XX:AOTConfiguration=");
1126     ss.print_raw(AOTConfiguration);
1127     append_args(&args, ss.freeze(), CHECK_0);
1128   }
1129 
1130   append_args(&args, "-XX:AOTMode=create", CHECK_0);

1131 
1132   Symbol* klass_name = SymbolTable::new_symbol("jdk/internal/misc/CDS$ProcessLauncher");
1133   Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, CHECK_0);
1134   Symbol* methodName = SymbolTable::new_symbol("execWithJavaToolOptions");
1135   Symbol* methodSignature = SymbolTable::new_symbol("(Ljava/lang/String;[Ljava/lang/String;)I");
1136 
1137   Handle launcher = java_lang_String::create_from_str(java_launcher_path, CHECK_0);
1138   objArrayOop array = oopFactory::new_objArray(vmClasses::String_klass(), args.length(), CHECK_0);
1139   for (int i = 0; i < args.length(); i++) {
1140     array->obj_at_put(i, args.at(i)());
1141   }
1142   objArrayHandle launcher_args(THREAD, array);
1143 
1144   // The following call will pass all options inside the JAVA_TOOL_OPTIONS env variable to
1145   // the child process. It will also clear the _JAVA_OPTIONS and CLASSPATH env variables for
1146   // the child process.
1147   //
1148   // Note: the env variables are set only for the child process. They are not changed
1149   // for the current process. See java.lang.ProcessBuilder::environment().
1150   JavaValue result(T_OBJECT);
1151   JavaCallArguments javacall_args(2);
1152   javacall_args.push_oop(launcher);
1153   javacall_args.push_oop(launcher_args);
1154   JavaCalls::call_static(&result,
1155                           InstanceKlass::cast(k),
1156                           methodName,
1157                           methodSignature,
1158                           &javacall_args,
1159                           CHECK_0);
1160   return result.get_jint();
1161 }
1162 















































































1163 void MetaspaceShared::fork_and_dump_final_static_archive(TRAPS) {
1164   assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1165 
1166   ResourceMark rm;
1167   stringStream ss;
1168   print_java_launcher(&ss);
1169   const char* cmd = ss.freeze();
1170   tty->print_cr("Launching child process %s to assemble AOT cache %s using configuration %s", cmd, AOTCacheOutput, AOTConfiguration);
1171   int status = exec_jvm_with_java_tool_options(cmd, CHECK);
1172   if (status != 0) {
1173     log_error(aot)("Child process failed; status = %d", status);
1174     // We leave the temp config file for debugging
1175   } else if (CDSConfig::has_temp_aot_config_file()) {
1176     const char* tmp_config = AOTConfiguration;
1177     // On Windows, need WRITE permission to remove the file.
1178     WINDOWS_ONLY(chmod(tmp_config, _S_IREAD | _S_IWRITE));
1179     status = remove(tmp_config);
1180     if (status != 0) {
1181       log_error(aot)("Failed to remove temporary AOT configuration file %s", tmp_config);
1182     } else {

1213     if (HAS_PENDING_EXCEPTION) {
1214       ResourceMark rm(THREAD);
1215       aot_log_warning(aot)("Preload Warning: Verification failed for %s",
1216                     ik->external_name());
1217       CLEAR_PENDING_EXCEPTION;
1218       SystemDictionaryShared::set_class_has_failed_verification(ik);
1219     } else {
1220       assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity");
1221       ik->compute_has_loops_flag_for_methods();
1222     }
1223     BytecodeVerificationLocal = saved;
1224     return true;
1225   } else {
1226     return false;
1227   }
1228 }
1229 
1230 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1231   if (CDSConfig::is_dumping_heap()) {
1232     HeapShared::write_heap(&_heap_info);
1233   } else {
1234     CDSConfig::log_reasons_for_not_dumping_heap();
1235   }
1236 }
1237 
1238 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
1239   assert(base <= static_top && static_top <= top, "must be");
1240   _shared_metaspace_static_top = static_top;
1241   MetaspaceObj::set_shared_metaspace_range(base, top);
1242 }
1243 
1244 bool MetaspaceShared::is_shared_dynamic(void* p) {
1245   if ((p < MetaspaceObj::shared_metaspace_top()) &&
1246       (p >= _shared_metaspace_static_top)) {
1247     return true;
1248   } else {
1249     return false;
1250   }
1251 }
1252 
1253 bool MetaspaceShared::is_shared_static(void* p) {

1305 // This function is called when the JVM is unable to write the specified CDS archive due to an
1306 // unrecoverable error.
1307 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1308   writing_error(message);
1309   vm_direct_exit(1);
1310 }
1311 
1312 // This function is called when the JVM is unable to write the specified CDS archive due to a
1313 // an error. The error will be propagated
1314 void MetaspaceShared::writing_error(const char* message) {
1315   aot_log_error(aot)("An error has occurred while writing the shared archive file.");
1316   if (message != nullptr) {
1317     aot_log_error(aot)("%s", message);
1318   }
1319 }
1320 
1321 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1322   assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1323   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1324 
1325   FileMapInfo* static_mapinfo = open_static_archive();
1326   FileMapInfo* dynamic_mapinfo = nullptr;
1327 
1328   if (static_mapinfo != nullptr) {
1329     aot_log_info(aot)("Core region alignment: %zu", static_mapinfo->core_region_alignment());
1330     dynamic_mapinfo = open_dynamic_archive();
1331 
1332     aot_log_info(aot)("ArchiveRelocationMode: %d", ArchiveRelocationMode);
1333 
1334     // First try to map at the requested address
1335     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1336     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1337       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1338       // by the OS.
1339       aot_log_info(aot)("Try to map archive(s) at an alternative address");
1340       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1341     }
1342   }
1343 
1344   if (result == MAP_ARCHIVE_SUCCESS) {
1345     bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());

1348     // Register CDS memory region with LSan.
1349     LSAN_REGISTER_ROOT_REGION(cds_base, cds_end - cds_base);
1350     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
1351     _relocation_delta = static_mapinfo->relocation_delta();
1352     _requested_base_address = static_mapinfo->requested_base_address();
1353     if (dynamic_mapped) {
1354       // turn AutoCreateSharedArchive off if successfully mapped
1355       AutoCreateSharedArchive = false;
1356     }
1357   } else {
1358     set_shared_metaspace_range(nullptr, nullptr, nullptr);
1359     if (CDSConfig::is_dumping_dynamic_archive()) {
1360       aot_log_warning(aot)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1361     }
1362     UseSharedSpaces = false;
1363     // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1364     AutoCreateSharedArchive = false;
1365     CDSConfig::disable_dumping_dynamic_archive();
1366     if (PrintSharedArchiveAndExit) {
1367       MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");






1368     } else {
1369       if (RequireSharedSpaces) {
1370         MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1371       } else {
1372         report_loading_error("Unable to map shared spaces");
1373       }
1374     }
1375   }
1376 
1377   // If mapping failed and -XShare:on, the vm should exit
1378   bool has_failed = false;
1379   if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1380     has_failed = true;
1381     delete static_mapinfo;
1382   }
1383   if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1384     has_failed = true;
1385     delete dynamic_mapinfo;
1386   }
1387   if (RequireSharedSpaces && has_failed) {

1388       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1389   }
1390 }
1391 
1392 FileMapInfo* MetaspaceShared::open_static_archive() {




1393   const char* static_archive = CDSConfig::input_static_archive_path();
1394   assert(static_archive != nullptr, "sanity");
1395   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1396   if (!mapinfo->open_as_input()) {
1397     delete(mapinfo);
1398     return nullptr;


1399   }
1400   return mapinfo;
1401 }
1402 
1403 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1404   if (CDSConfig::is_dumping_dynamic_archive()) {
1405     return nullptr;
1406   }
1407   const char* dynamic_archive = CDSConfig::input_dynamic_archive_path();
1408   if (dynamic_archive == nullptr) {
1409     return nullptr;
1410   }
1411 
1412   FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1413   if (!mapinfo->open_as_input()) {
1414     delete(mapinfo);
1415     if (RequireSharedSpaces) {
1416       MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1417     }
1418     return nullptr;
1419   }
1420   return mapinfo;

1866       MemoryReserver::release(archive_space_rs);
1867       archive_space_rs = {};
1868     }
1869     if (class_space_rs.is_reserved()) {
1870       aot_log_debug(aot)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1871       MemoryReserver::release(class_space_rs);
1872       class_space_rs = {};
1873     }
1874   }
1875 }
1876 
1877 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
1878 static int archive_regions_count = 2;
1879 
1880 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1881   assert(CDSConfig::is_using_archive(), "must be runtime");
1882   if (mapinfo == nullptr) {
1883     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1884   }
1885 




1886   mapinfo->set_is_mapped(false);
1887   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1888     report_loading_error("Unable to map CDS archive -- core_region_alignment() expected: %zu"
1889                          " actual: %zu", mapinfo->core_region_alignment(), core_region_alignment());
1890     return MAP_ARCHIVE_OTHER_FAILURE;
1891   }
1892 
1893   MapArchiveResult result =
1894     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1895 
1896   if (result != MAP_ARCHIVE_SUCCESS) {
1897     unmap_archive(mapinfo);
1898     return result;
1899   }
1900 
1901   if (!mapinfo->validate_class_location()) {
1902     unmap_archive(mapinfo);
1903     return MAP_ARCHIVE_OTHER_FAILURE;
1904   }
1905 

   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/aotCacheAccess.hpp"
  26 #include "cds/aotClassInitializer.hpp"
  27 #include "cds/aotArtifactFinder.hpp"
  28 #include "cds/aotClassInitializer.hpp"
  29 #include "cds/aotClassLinker.hpp"
  30 #include "cds/aotClassLocation.hpp"
  31 #include "cds/aotConstantPoolResolver.hpp"
  32 #include "cds/aotLinkedClassBulkLoader.hpp"
  33 #include "cds/aotLogging.hpp"
  34 #include "cds/aotReferenceObjSupport.hpp"
  35 #include "cds/archiveBuilder.hpp"
  36 #include "cds/archiveHeapLoader.hpp"
  37 #include "cds/archiveHeapWriter.hpp"
  38 #include "cds/cds_globals.hpp"
  39 #include "cds/cdsConfig.hpp"
  40 #include "cds/cdsProtectionDomain.hpp"
  41 #include "cds/classListParser.hpp"
  42 #include "cds/classListWriter.hpp"
  43 #include "cds/cppVtables.hpp"
  44 #include "cds/dumpAllocStats.hpp"
  45 #include "cds/dynamicArchive.hpp"
  46 #include "cds/filemap.hpp"
  47 #include "cds/finalImageRecipes.hpp"
  48 #include "cds/heapShared.hpp"
  49 #include "cds/lambdaFormInvokers.hpp"
  50 #include "cds/lambdaProxyClassDictionary.hpp"
  51 #include "cds/metaspaceShared.hpp"
  52 #include "classfile/classLoaderDataGraph.hpp"
  53 #include "classfile/classLoaderDataShared.hpp"
  54 #include "classfile/classLoaderExt.hpp"
  55 #include "classfile/javaClasses.inline.hpp"
  56 #include "classfile/loaderConstraints.hpp"
  57 #include "classfile/modules.hpp"
  58 #include "classfile/placeholders.hpp"
  59 #include "classfile/stringTable.hpp"
  60 #include "classfile/symbolTable.hpp"
  61 #include "classfile/systemDictionary.hpp"
  62 #include "classfile/systemDictionaryShared.hpp"
  63 #include "classfile/vmClasses.hpp"
  64 #include "classfile/vmSymbols.hpp"
  65 #include "code/aotCodeCache.hpp"
  66 #include "code/codeCache.hpp"
  67 #include "compiler/compileBroker.hpp"
  68 #include "compiler/precompiler.hpp"
  69 #include "gc/shared/gcVMOperations.hpp"
  70 #include "interpreter/bytecodeStream.hpp"
  71 #include "interpreter/bytecodes.hpp"
  72 #include "jvm_io.h"
  73 #include "logging/log.hpp"
  74 #include "logging/logMessage.hpp"
  75 #include "logging/logStream.hpp"
  76 #include "memory/memoryReserver.hpp"
  77 #include "memory/metaspace.hpp"
  78 #include "memory/metaspaceClosure.hpp"
  79 #include "memory/oopFactory.hpp"
  80 #include "memory/resourceArea.hpp"
  81 #include "memory/universe.hpp"
  82 #include "nmt/memTracker.hpp"
  83 #include "oops/compressedKlass.hpp"
  84 #include "oops/instanceMirrorKlass.hpp"
  85 #include "oops/klass.inline.hpp"
  86 #include "oops/method.inline.hpp"
  87 #include "oops/objArrayOop.hpp"
  88 #include "oops/oop.inline.hpp"
  89 #include "oops/oopHandle.hpp"
  90 #include "oops/trainingData.hpp"
  91 #include "prims/jvmtiExport.hpp"
  92 #include "prims/whitebox.hpp"
  93 #include "runtime/arguments.hpp"
  94 #include "runtime/globals.hpp"
  95 #include "runtime/globals_extension.hpp"
  96 #include "runtime/handles.inline.hpp"
  97 #include "runtime/javaCalls.hpp"
  98 #include "runtime/os.inline.hpp"
  99 #include "runtime/safepointVerifiers.hpp"
 100 #include "runtime/sharedRuntime.hpp"
 101 #include "runtime/vmOperations.hpp"
 102 #include "runtime/vmThread.hpp"
 103 #include "sanitizers/leak.hpp"
 104 #include "services/management.hpp"
 105 #include "utilities/align.hpp"
 106 #include "utilities/bitMap.inline.hpp"
 107 #include "utilities/defaultStream.hpp"
 108 #include "utilities/macros.hpp"
 109 #include "utilities/ostream.hpp"
 110 #include "utilities/resourceHash.hpp"
 111 
 112 #include <sys/stat.h>
 113 
 114 ReservedSpace MetaspaceShared::_symbol_rs;
 115 VirtualSpace MetaspaceShared::_symbol_vs;
 116 bool MetaspaceShared::_archive_loading_failed = false;
 117 bool MetaspaceShared::_remapped_readwrite = false;
 118 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
 119 intx MetaspaceShared::_relocation_delta;
 120 char* MetaspaceShared::_requested_base_address;
 121 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr;
 122 bool MetaspaceShared::_use_optimized_module_handling = true;
 123 int volatile MetaspaceShared::_preimage_static_archive_dumped = 0;
 124 jlong MetaspaceShared::_preimage_static_archive_recording_duration = 0;
 125 
 126 // The CDS archive is divided into the following regions:
 127 //     rw  - read-write metadata
 128 //     ro  - read-only metadata and read-only tables
 129 //     hp  - heap region
 130 //     bm  - bitmap for relocating the above 7 regions.
 131 //
 132 // The rw and ro regions are linearly allocated, in the order of rw->ro.
 133 // These regions are aligned with MetaspaceShared::core_region_alignment().
 134 //
 135 // These 2 regions are populated in the following steps:
 136 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 137 //     temporarily allocated outside of the shared regions.
 138 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
 139 // [2] C++ vtables are copied into the rw region.
 140 // [3] ArchiveBuilder copies RW metadata into the rw region.
 141 // [4] ArchiveBuilder copies RO metadata into the ro region.
 142 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 143 //     are copied into the ro region as read-only tables.
 144 //

 285   }
 286 
 287   // Arguments::default_SharedBaseAddress() is hard-coded in cds_globals.hpp. It must be carefully
 288   // picked that (a) the align_up() below will always return a valid value; (b) none of
 289   // the following asserts will fail.
 290   aot_log_warning(aot)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
 291                    p2i((void*)SharedBaseAddress), err,
 292                    p2i((void*)Arguments::default_SharedBaseAddress()));
 293 
 294   specified_base = (char*)Arguments::default_SharedBaseAddress();
 295   aligned_base = align_up(specified_base, alignment);
 296 
 297   // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
 298   assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
 299   assert(shared_base_valid(aligned_base), "Sanity");
 300   return aligned_base;
 301 }
 302 
 303 void MetaspaceShared::initialize_for_static_dump() {
 304   assert(CDSConfig::is_dumping_static_archive(), "sanity");
 305 
 306   if (CDSConfig::is_dumping_preimage_static_archive() || CDSConfig::is_dumping_final_static_archive()) {
 307     if (!((UseG1GC || UseParallelGC || UseSerialGC || UseEpsilonGC || UseShenandoahGC) && UseCompressedClassPointers)) {
 308       const char* error;
 309       if (CDSConfig::is_experimental_leyden_workflow()) {
 310         error = "Cannot create the CacheDataStore";
 311       } else if (CDSConfig::is_dumping_preimage_static_archive()) {
 312         error = "Cannot create the AOT configuration file";
 313       } else {
 314         error = "Cannot create the AOT cache";
 315       }
 316 
 317       vm_exit_during_initialization(error,
 318                                     "UseCompressedClassPointers must be enabled, and collector must be G1, Parallel, Serial, Epsilon, or Shenandoah");
 319     }
 320   }
 321 
 322   aot_log_info(aot)("Core region alignment: %zu", core_region_alignment());
 323   // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
 324   // to avoid address space wrap around.
 325   size_t cds_max;
 326   const size_t reserve_alignment = core_region_alignment();
 327 
 328 #ifdef _LP64
 329   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 330   cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
 331 #else
 332   // We don't support archives larger than 256MB on 32-bit due to limited
 333   //  virtual address space.
 334   cds_max = align_down(256*M, reserve_alignment);
 335 #endif
 336 
 337   _requested_base_address = compute_shared_base(cds_max);
 338   SharedBaseAddress = (size_t)_requested_base_address;
 339 
 340   size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
 341   _symbol_rs = MemoryReserver::reserve(symbol_rs_size,

 746       _mirrors.at(i).release(Universe::vm_global());
 747     }
 748   }
 749 
 750   void do_cld(ClassLoaderData* cld) {
 751     assert(cld->is_alive(), "must be");
 752   }
 753 
 754   void do_klass(Klass* k) {
 755     if (k->is_instance_klass()) {
 756       _mirrors.append(OopHandle(Universe::vm_global(), k->java_mirror()));
 757     }
 758   }
 759 
 760   const GrowableArray<OopHandle>* mirrors() const { return &_mirrors; }
 761 };
 762 
 763 // Check if we can eagerly link this class at dump time, so we can avoid the
 764 // runtime linking overhead (especially verification)
 765 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
 766   if (CDSConfig::preserve_all_dumptime_verification_states(ik)) {
 767     assert(ik->can_be_verified_at_dumptime(), "sanity");
 768   }
 769   if (!ik->can_be_verified_at_dumptime()) {
 770     // For old classes, try to leave them in the unlinked state, so
 771     // we can still store them in the archive. They must be
 772     // linked/verified at runtime.
 773     return false;
 774   }
 775   if (CDSConfig::is_dumping_dynamic_archive() && ik->defined_by_other_loaders()) {
 776     // Linking of unregistered classes at this stage may cause more
 777     // classes to be resolved, resulting in calls to ClassLoader.loadClass()
 778     // that may not be expected by custom class loaders.
 779     //
 780     // It's OK to do this for the built-in loaders as we know they can
 781     // tolerate this.
 782     return false;
 783   }
 784   return true;
 785 }
 786 
 787 void MetaspaceShared::link_shared_classes(TRAPS) {
 788   AOTClassLinker::initialize();
 789   AOTClassInitializer::init_test_class(CHECK);
 790 
 791   while (true) {
 792     ResourceMark rm(THREAD);
 793     CollectClassesForLinking collect_classes;
 794     bool has_linked = false;
 795     const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
 796     for (int i = 0; i < mirrors->length(); i++) {
 797       OopHandle mirror = mirrors->at(i);
 798       InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve()));
 799       if (may_be_eagerly_linked(ik)) {
 800         has_linked |= try_link_class(THREAD, ik);
 801       }
 802       if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) {
 803         AOTClassInitializer::maybe_preinit_class(ik, CHECK);
 804       }
 805     }
 806 
 807     if (!has_linked) {
 808       break;
 809     }
 810     // Class linking includes verification which may load more classes.
 811     // Keep scanning until we have linked no more classes.
 812   }
 813 
 814   // Eargerly resolve all string constants in constant pools
 815   {
 816     ResourceMark rm(THREAD);
 817     CollectClassesForLinking collect_classes;
 818     const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
 819     for (int i = 0; i < mirrors->length(); i++) {
 820       OopHandle mirror = mirrors->at(i);
 821       InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve()));
 822       AOTConstantPoolResolver::preresolve_string_cp_entries(ik, CHECK);
 823       if (CDSConfig::is_dumping_preimage_static_archive()) {
 824         FinalImageRecipes::add_reflection_data_flags(ik, CHECK);
 825       }
 826     }
 827   }
 828 
 829   if (CDSConfig::is_dumping_final_static_archive()) {
 830     FinalImageRecipes::apply_recipes(CHECK);
 831   }
 832 }
 833 
 834 // Preload classes from a list, populate the shared spaces and dump to a
 835 // file.
 836 void MetaspaceShared::preload_and_dump(TRAPS) {
 837   CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
 838   ResourceMark rm(THREAD);
 839   HandleMark hm(THREAD);
 840 
 841   if (CDSConfig::is_dumping_final_static_archive() && AOTPrintTrainingInfo) {
 842     tty->print_cr("==================== archived_training_data ** before dumping ====================");
 843     TrainingData::print_archived_training_data_on(tty);
 844   }
 845 
 846   StaticArchiveBuilder builder;
 847   preload_and_dump_impl(builder, THREAD);
 848   if (HAS_PENDING_EXCEPTION) {
 849     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 850       aot_log_error(aot)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 851                      "%zuM", MaxHeapSize/M);
 852       MetaspaceShared::writing_error();
 853     } else {
 854       oop message = java_lang_Throwable::message(PENDING_EXCEPTION);
 855       aot_log_error(aot)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 856                          message == nullptr ? "(null)" : java_lang_String::as_utf8_string(message));
 857       MetaspaceShared::writing_error(err_msg("Unexpected exception, use -Xlog:aot%s,exceptions=trace for detail",
 858                                              CDSConfig::new_aot_flags_used() ? "" : ",cds"));
 859     }
 860     if (CDSConfig::is_experimental_leyden_workflow()) {
 861       vm_exit(1);
 862     }
 863   }
 864 
 865   if (CDSConfig::new_aot_flags_used()) {
 866     if (CDSConfig::is_dumping_preimage_static_archive()) {
 867       // We are in the JVM that runs the training run. Continue execution,
 868       // so that it can finish all clean-up and return the correct exit
 869       // code to the OS.
 870     } else {
 871       // The JLI launcher only recognizes the "old" -Xshare:dump flag.
 872       // When the new -XX:AOTMode=create flag is used, we can't return
 873       // to the JLI launcher, as the launcher will fail when trying to
 874       // run the main class, which is not what we want.
 875       struct stat st;
 876       if (os::stat(AOTCache, &st) != 0) {
 877         tty->print_cr("AOTCache creation failed: %s", AOTCache);
 878         vm_exit(0);
 879       } else {
 880         tty->print_cr("AOTCache creation is complete: %s " INT64_FORMAT " bytes", AOTCache, (int64_t)(st.st_size));
 881         vm_exit(0);
 882       }

 941     }
 942   }
 943 
 944   // Some classes are used at CDS runtime but are not loaded, and therefore archived, at
 945   // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they
 946   // are archived.
 947   exercise_runtime_cds_code(CHECK);
 948 
 949   aot_log_info(aot)("Loading classes to share: done.");
 950 }
 951 
 952 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) {
 953   // Exercise the manifest processing code
 954   const char* dummy = "Manifest-Version: 1.0\n";
 955   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 956 
 957   // Exercise FileSystem and URL code
 958   CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
 959 }
 960 
 961 bool MetaspaceShared::is_recording_preimage_static_archive() {
 962   if (CDSConfig::is_dumping_preimage_static_archive()) {
 963       return _preimage_static_archive_dumped == 0;
 964   }
 965   return false;
 966 }
 967 
 968 jlong MetaspaceShared::get_preimage_static_archive_recording_duration() {
 969   if (CDSConfig::is_dumping_preimage_static_archive()) {
 970     if (_preimage_static_archive_recording_duration == 0) {
 971       // The recording has not yet finished so return the current elapsed time.
 972       return Management::ticks_to_ms(os::elapsed_counter());
 973     }
 974     return _preimage_static_archive_recording_duration;
 975   }
 976   return 0;
 977 }
 978 
 979 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
 980   if (CDSConfig::is_dumping_preimage_static_archive()) {
 981     if (Atomic::cmpxchg(&_preimage_static_archive_dumped, 0, 1) != 0) {
 982       return;
 983     }
 984     _preimage_static_archive_recording_duration = Management::ticks_to_ms(os::elapsed_counter());
 985   }
 986 
 987   if (CDSConfig::is_dumping_classic_static_archive()) {
 988     // We are running with -Xshare:dump
 989     preload_classes(CHECK);
 990 
 991     if (SharedArchiveConfigFile) {
 992       log_info(aot)("Reading extra data from %s ...", SharedArchiveConfigFile);
 993       read_extra_data(THREAD, SharedArchiveConfigFile);
 994       log_info(aot)("Reading extra data: done.");
 995     }
 996   }
 997 
 998   if (CDSConfig::is_dumping_preimage_static_archive()) {
 999     log_info(aot)("Reading lambda form invokers from JDK default classlist ...");
1000     char default_classlist[JVM_MAXPATHLEN];
1001     get_default_classlist(default_classlist, JVM_MAXPATHLEN);
1002     struct stat statbuf;
1003     if (os::stat(default_classlist, &statbuf) == 0) {
1004       ClassListParser::parse_classlist(default_classlist,
1005                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
1006     }

1033   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1034   // fails verification, all other interfaces that were not specified in the classlist but
1035   // are implemented by K are not verified.
1036   link_shared_classes(CHECK);
1037   log_info(aot)("Rewriting and linking classes: done");
1038   TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
1039 
1040   if (CDSConfig::is_dumping_regenerated_lambdaform_invokers()) {
1041     LambdaFormInvokers::regenerate_holder_classes(CHECK);
1042   }
1043 
1044 #if INCLUDE_CDS_JAVA_HEAP
1045   if (CDSConfig::is_dumping_heap()) {
1046     ArchiveHeapWriter::init();
1047 
1048     if (CDSConfig::is_dumping_full_module_graph()) {
1049       ClassLoaderDataShared::ensure_module_entry_tables_exist();
1050       HeapShared::reset_archived_object_states(CHECK);
1051     }
1052 
1053     if (ArchiveLoaderLookupCache) {
1054       SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK);
1055     }
1056 
1057     AOTReferenceObjSupport::initialize(CHECK);
1058     AOTReferenceObjSupport::stabilize_cached_reference_objects(CHECK);
1059 
1060     if (CDSConfig::is_initing_classes_at_dump_time()) {
1061       // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
1062       // to null, and it will be initialized again at runtime.
1063       log_debug(aot)("Resetting Class::reflectionFactory");
1064       TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
1065       Symbol* method_sig = vmSymbols::void_method_signature();
1066       JavaValue result(T_VOID);
1067       JavaCalls::call_static(&result, vmClasses::Class_klass(),
1068                              method_name, method_sig, CHECK);
1069 
1070       // Perhaps there is a way to avoid hard-coding these names here.
1071       // See discussion in JDK-8342481.
1072     }
1073 
1074     // Do this at the very end, when no Java code will be executed. Otherwise
1075     // some new strings may be added to the intern table.
1076     StringTable::allocate_shared_strings_array(CHECK);
1077   } else {
1078     log_info(aot)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
1079     CDSConfig::stop_using_optimized_module_handling();
1080   }
1081 #endif
1082 
1083   VM_PopulateDumpSharedSpace op(builder);
1084   VMThread::execute(&op);
1085   FileMapInfo* mapinfo = op.map_info();
1086   ArchiveHeapInfo* heap_info = op.heap_info();
1087 
1088   if (CDSConfig::is_dumping_final_static_archive()) {
1089     if (AOTCodeCache::is_caching_enabled()) {
1090       if (log_is_enabled(Info, cds, jit)) {
1091         AOTCacheAccess::test_heap_access_api();
1092       }
1093 
1094       // We have just created the final image. Let's run the AOT compiler
1095       if (AOTPrintTrainingInfo) {
1096         tty->print_cr("==================== archived_training_data ** after dumping ====================");
1097         TrainingData::print_archived_training_data_on(tty);
1098       }
1099 
1100       CDSConfig::enable_dumping_aot_code();
1101       {
1102         builder.start_ac_region();
1103         if (AOTCodeCache::is_dumping_code()) {
1104           Precompiler::compile_cached_code(&builder, CHECK);
1105         }
1106         // Write the contents to aot code region and close AOTCodeCache before packing the region
1107         AOTCodeCache::close();
1108         builder.end_ac_region();
1109       }
1110       CDSConfig::disable_dumping_aot_code();
1111     }

1112   }
1113 
1114   bool status = write_static_archive(&builder, mapinfo, heap_info);
1115   if (status && CDSConfig::is_dumping_preimage_static_archive()) {
1116     if (CDSConfig::is_experimental_leyden_workflow()) {
1117       fork_and_dump_final_static_archive_experimental_leyden_workflow(CHECK);
1118     } else {
1119       tty->print_cr("%s AOTConfiguration recorded: %s",
1120                     CDSConfig::has_temp_aot_config_file() ? "Temporary" : "", AOTConfiguration);
1121       if (CDSConfig::is_single_command_training()) {
1122         fork_and_dump_final_static_archive(CHECK);
1123       }
1124     }
1125   }
1126 
1127   if (!status) {
1128     THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
1129   }
1130 }
1131 
1132 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
1133   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1134   // without runtime relocation.
1135   builder->relocate_to_requested();
1136 
1137   map_info->open_as_output();
1138   if (!map_info->is_open()) {
1139     return false;
1140   }
1141   builder->write_archive(map_info, heap_info);
1142 
1143   if (AllowArchivingWithJavaAgent) {

1174     // CDS$ProcessLauncher::execWithJavaToolOptions() must unset CLASSPATH, which has
1175     // a higher priority than -Djava.class.path=
1176   }
1177 
1178   // Pass all arguments. These include those from JAVA_TOOL_OPTIONS and _JAVA_OPTIONS.
1179   for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1180     const char* arg = Arguments::jvm_args_array()[i];
1181     if (strstr(arg, "-XX:AOTCacheOutput=") == arg || // arg starts with ...
1182         strstr(arg, "-XX:AOTConfiguration=") == arg ||
1183         strstr(arg, "-XX:AOTMode=") == arg) {
1184       // Filter these out. They wiill be set below.
1185     } else {
1186       append_args(&args, arg, CHECK_0);
1187     }
1188   }
1189 
1190   // Note: because we are running in AOTMode=record, JDK_AOT_VM_OPTIONS have not been
1191   // parsed, so they are not in Arguments::jvm_args_array. If JDK_AOT_VM_OPTIONS is in
1192   // the environment, it will be inherited and parsed by the child JVM process
1193   // in Arguments::parse_java_tool_options_environment_variable().

1194 
1195   // We don't pass Arguments::jvm_flags_array(), as those will be added by
1196   // the child process when it loads .hotspotrc
1197 
1198   if (CDSConfig::is_experimental_leyden_workflow()) {
1199     stringStream ss;
1200     ss.print("-XX:CDSPreimage=");
1201     ss.print_raw(CDSPreimage);
1202     append_args(&args, ss.freeze(), CHECK_0);
1203   } else {
1204 
1205    precond(strcmp(AOTMode, "record") == 0);
1206 
1207    {
1208     // If AOTCacheOutput contains %p, it should have been already substituted with the
1209     // pid of the training process.
1210     stringStream ss;
1211     ss.print("-XX:AOTCacheOutput=");
1212     ss.print_raw(AOTCacheOutput);
1213     append_args(&args, ss.freeze(), CHECK_0);
1214    }
1215    {
1216     // If AOTCacheConfiguration contains %p, it should have been already substituted with the
1217     // pid of the training process.
1218     // If AOTCacheConfiguration was not explicitly specified, it should have been assigned a
1219     // temporary file name.
1220     stringStream ss;
1221     ss.print("-XX:AOTConfiguration=");
1222     ss.print_raw(AOTConfiguration);
1223     append_args(&args, ss.freeze(), CHECK_0);
1224    }
1225 
1226    append_args(&args, "-XX:AOTMode=create", CHECK_0);
1227   }
1228 
1229   Symbol* klass_name = SymbolTable::new_symbol("jdk/internal/misc/CDS$ProcessLauncher");
1230   Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, CHECK_0);
1231   Symbol* methodName = SymbolTable::new_symbol("execWithJavaToolOptions");
1232   Symbol* methodSignature = SymbolTable::new_symbol("(Ljava/lang/String;[Ljava/lang/String;)I");
1233 
1234   Handle launcher = java_lang_String::create_from_str(java_launcher_path, CHECK_0);
1235   objArrayOop array = oopFactory::new_objArray(vmClasses::String_klass(), args.length(), CHECK_0);
1236   for (int i = 0; i < args.length(); i++) {
1237     array->obj_at_put(i, args.at(i)());
1238   }
1239   objArrayHandle launcher_args(THREAD, array);
1240 
1241   // The following call will pass all options inside the JAVA_TOOL_OPTIONS env variable to
1242   // the child process. It will also clear the _JAVA_OPTIONS and CLASSPATH env variables for
1243   // the child process.
1244   //
1245   // Note: the env variables are set only for the child process. They are not changed
1246   // for the current process. See java.lang.ProcessBuilder::environment().
1247   JavaValue result(T_OBJECT);
1248   JavaCallArguments javacall_args(2);
1249   javacall_args.push_oop(launcher);
1250   javacall_args.push_oop(launcher_args);
1251   JavaCalls::call_static(&result,
1252                           InstanceKlass::cast(k),
1253                           methodName,
1254                           methodSignature,
1255                           &javacall_args,
1256                           CHECK_0);
1257   return result.get_jint();
1258 }
1259 
1260 // This is for debugging purposes only (-XX:+CDSManualFinalImage) so we don't bother
1261 // quoating any special characters. The user should avoid using special chars.
1262 static void print_vm_arguments(outputStream* st) {
1263   const char* cp = Arguments::get_appclasspath();
1264   if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1265     st->print(" -cp ");  st->print_raw(cp);
1266   }
1267   for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1268     st->print(" %s", Arguments::jvm_args_array()[i]);
1269   }
1270 }
1271 
1272 void MetaspaceShared::fork_and_dump_final_static_archive_experimental_leyden_workflow(TRAPS) {
1273   assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1274 
1275   ResourceMark rm;
1276   stringStream ss;
1277   print_java_launcher(&ss);
1278 
1279   if (CDSManualFinalImage) {
1280     print_vm_arguments(&ss);
1281     ss.print(" -XX:CDSPreimage=%s", SharedArchiveFile);
1282     const char* cmd = ss.freeze();
1283 
1284     tty->print_cr("-XX:+CDSManualFinalImage is specified");
1285     tty->print_cr("Please manually execute the following command to create the final CDS image:");
1286     tty->print("    "); tty->print_raw_cr(cmd);
1287 
1288     // The following is useful if the dumping was trigger by a script that builds
1289     // a complex command-line.
1290     tty->print_cr("Note: to recreate the preimage only:");
1291     tty->print_cr("    rm -f %s", CacheDataStore);
1292     tty->print("    ");
1293     print_java_launcher(tty);
1294     print_vm_arguments(tty);
1295     if (Arguments::java_command() != nullptr) {
1296       tty->print(" %s", Arguments::java_command());
1297     }
1298     tty->cr();
1299   } else {
1300     const char* cmd = ss.freeze();
1301     log_info(cds)("Launching child process to create final CDS image:");
1302     log_info(cds)("    %s", cmd);
1303     int status = exec_jvm_with_java_tool_options(cmd, CHECK);
1304     if (status != 0) {
1305       log_error(cds)("Child process finished; status = %d", status);
1306       log_error(cds)("To reproduce the error");
1307       ResourceMark rm;
1308       LogStream ls(Log(cds)::error());
1309       ls.print("    "); ls.print_raw_cr(cmd);
1310 
1311       // The following is useful if the dumping was trigger by a script that builds
1312       // a complex command-line.
1313       ls.print_cr("Note: to recreate the preimage only:");
1314       ls.print_cr("    rm -f %s", CacheDataStore);
1315       ls.print("    ");
1316       print_java_launcher(&ls);
1317       print_vm_arguments(&ls);
1318       ls.print(" -XX:+UnlockDiagnosticVMOptions -XX:+CDSManualFinalImage");
1319       if (Arguments::java_command() != nullptr) {
1320         ls.print(" %s", Arguments::java_command());
1321       }
1322       ls.cr();
1323 
1324       vm_direct_exit(status);
1325     } else {
1326       log_info(cds)("Child process finished; status = %d", status);
1327       // On Windows, need WRITE permission to remove the file.
1328       WINDOWS_ONLY(chmod(CDSPreimage, _S_IREAD | _S_IWRITE));
1329       status = remove(CDSPreimage);
1330       if (status != 0) {
1331         log_error(cds)("Failed to remove CDSPreimage file %s", CDSPreimage);
1332       } else {
1333         log_info(cds)("Removed CDSPreimage file %s", CDSPreimage);
1334       }
1335     }
1336   }
1337 }
1338 
1339 void MetaspaceShared::fork_and_dump_final_static_archive(TRAPS) {
1340   assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1341 
1342   ResourceMark rm;
1343   stringStream ss;
1344   print_java_launcher(&ss);
1345   const char* cmd = ss.freeze();
1346   tty->print_cr("Launching child process %s to assemble AOT cache %s using configuration %s", cmd, AOTCacheOutput, AOTConfiguration);
1347   int status = exec_jvm_with_java_tool_options(cmd, CHECK);
1348   if (status != 0) {
1349     log_error(aot)("Child process failed; status = %d", status);
1350     // We leave the temp config file for debugging
1351   } else if (CDSConfig::has_temp_aot_config_file()) {
1352     const char* tmp_config = AOTConfiguration;
1353     // On Windows, need WRITE permission to remove the file.
1354     WINDOWS_ONLY(chmod(tmp_config, _S_IREAD | _S_IWRITE));
1355     status = remove(tmp_config);
1356     if (status != 0) {
1357       log_error(aot)("Failed to remove temporary AOT configuration file %s", tmp_config);
1358     } else {

1389     if (HAS_PENDING_EXCEPTION) {
1390       ResourceMark rm(THREAD);
1391       aot_log_warning(aot)("Preload Warning: Verification failed for %s",
1392                     ik->external_name());
1393       CLEAR_PENDING_EXCEPTION;
1394       SystemDictionaryShared::set_class_has_failed_verification(ik);
1395     } else {
1396       assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity");
1397       ik->compute_has_loops_flag_for_methods();
1398     }
1399     BytecodeVerificationLocal = saved;
1400     return true;
1401   } else {
1402     return false;
1403   }
1404 }
1405 
1406 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1407   if (CDSConfig::is_dumping_heap()) {
1408     HeapShared::write_heap(&_heap_info);
1409   } else if (!CDSConfig::is_dumping_preimage_static_archive()) {
1410     CDSConfig::log_reasons_for_not_dumping_heap();
1411   }
1412 }
1413 
1414 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
1415   assert(base <= static_top && static_top <= top, "must be");
1416   _shared_metaspace_static_top = static_top;
1417   MetaspaceObj::set_shared_metaspace_range(base, top);
1418 }
1419 
1420 bool MetaspaceShared::is_shared_dynamic(void* p) {
1421   if ((p < MetaspaceObj::shared_metaspace_top()) &&
1422       (p >= _shared_metaspace_static_top)) {
1423     return true;
1424   } else {
1425     return false;
1426   }
1427 }
1428 
1429 bool MetaspaceShared::is_shared_static(void* p) {

1481 // This function is called when the JVM is unable to write the specified CDS archive due to an
1482 // unrecoverable error.
1483 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1484   writing_error(message);
1485   vm_direct_exit(1);
1486 }
1487 
1488 // This function is called when the JVM is unable to write the specified CDS archive due to a
1489 // an error. The error will be propagated
1490 void MetaspaceShared::writing_error(const char* message) {
1491   aot_log_error(aot)("An error has occurred while writing the shared archive file.");
1492   if (message != nullptr) {
1493     aot_log_error(aot)("%s", message);
1494   }
1495 }
1496 
1497 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1498   assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1499   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1500 
1501   FileMapInfo* static_mapinfo = FileMapInfo::current_info();
1502   FileMapInfo* dynamic_mapinfo = nullptr;
1503 
1504   if (static_mapinfo != nullptr) {
1505     aot_log_info(aot)("Core region alignment: %zu", static_mapinfo->core_region_alignment());
1506     dynamic_mapinfo = open_dynamic_archive();
1507 
1508     aot_log_info(aot)("ArchiveRelocationMode: %d", ArchiveRelocationMode);
1509 
1510     // First try to map at the requested address
1511     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1512     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1513       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1514       // by the OS.
1515       aot_log_info(aot)("Try to map archive(s) at an alternative address");
1516       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1517     }
1518   }
1519 
1520   if (result == MAP_ARCHIVE_SUCCESS) {
1521     bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());

1524     // Register CDS memory region with LSan.
1525     LSAN_REGISTER_ROOT_REGION(cds_base, cds_end - cds_base);
1526     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
1527     _relocation_delta = static_mapinfo->relocation_delta();
1528     _requested_base_address = static_mapinfo->requested_base_address();
1529     if (dynamic_mapped) {
1530       // turn AutoCreateSharedArchive off if successfully mapped
1531       AutoCreateSharedArchive = false;
1532     }
1533   } else {
1534     set_shared_metaspace_range(nullptr, nullptr, nullptr);
1535     if (CDSConfig::is_dumping_dynamic_archive()) {
1536       aot_log_warning(aot)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1537     }
1538     UseSharedSpaces = false;
1539     // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1540     AutoCreateSharedArchive = false;
1541     CDSConfig::disable_dumping_dynamic_archive();
1542     if (PrintSharedArchiveAndExit) {
1543       MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1544     } else if (RequireSharedSpaces) {
1545       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1546     } else if (CDSConfig::is_dumping_final_static_archive()) {
1547       assert(CDSPreimage != nullptr, "must be");
1548       log_error(cds)("Unable to map shared spaces for CDSPreimage = %s", CDSPreimage);
1549       MetaspaceShared::unrecoverable_loading_error();
1550     } else {
1551       report_loading_error("Unable to map shared spaces");




1552     }
1553   }
1554 
1555   // If mapping failed and -XShare:on, the vm should exit
1556   bool has_failed = false;
1557   if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1558     has_failed = true;
1559     delete static_mapinfo;
1560   }
1561   if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1562     has_failed = true;
1563     delete dynamic_mapinfo;
1564   }
1565   if (RequireSharedSpaces && has_failed) {
1566     // static archive mapped but dynamic archive failed
1567       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1568   }
1569 }
1570 
1571 // This is called very early at VM start up to get the size of the cached_code region
1572 void MetaspaceShared::open_static_archive() {
1573   if (!UseSharedSpaces) { // FIXME -- is this still needed??
1574     return;
1575   }
1576   const char* static_archive = CDSConfig::input_static_archive_path();
1577   assert(static_archive != nullptr, "sanity");
1578   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1579   if (!mapinfo->open_as_input()) {
1580     delete(mapinfo);
1581   } else {
1582     FileMapRegion* r = mapinfo->region_at(MetaspaceShared::ac);
1583     AOTCacheAccess::set_aot_code_region_size(r->used_aligned());
1584   }

1585 }
1586 
1587 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1588   if (CDSConfig::is_dumping_dynamic_archive()) {
1589     return nullptr;
1590   }
1591   const char* dynamic_archive = CDSConfig::input_dynamic_archive_path();
1592   if (dynamic_archive == nullptr) {
1593     return nullptr;
1594   }
1595 
1596   FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1597   if (!mapinfo->open_as_input()) {
1598     delete(mapinfo);
1599     if (RequireSharedSpaces) {
1600       MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1601     }
1602     return nullptr;
1603   }
1604   return mapinfo;

2050       MemoryReserver::release(archive_space_rs);
2051       archive_space_rs = {};
2052     }
2053     if (class_space_rs.is_reserved()) {
2054       aot_log_debug(aot)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
2055       MemoryReserver::release(class_space_rs);
2056       class_space_rs = {};
2057     }
2058   }
2059 }
2060 
2061 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
2062 static int archive_regions_count = 2;
2063 
2064 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
2065   assert(CDSConfig::is_using_archive(), "must be runtime");
2066   if (mapinfo == nullptr) {
2067     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
2068   }
2069 
2070   if (!mapinfo->validate_aot_class_linking()) {
2071     return MAP_ARCHIVE_OTHER_FAILURE;
2072   }
2073 
2074   mapinfo->set_is_mapped(false);
2075   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
2076     report_loading_error("Unable to map CDS archive -- core_region_alignment() expected: %zu"
2077                          " actual: %zu", mapinfo->core_region_alignment(), core_region_alignment());
2078     return MAP_ARCHIVE_OTHER_FAILURE;
2079   }
2080 
2081   MapArchiveResult result =
2082     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
2083 
2084   if (result != MAP_ARCHIVE_SUCCESS) {
2085     unmap_archive(mapinfo);
2086     return result;
2087   }
2088 
2089   if (!mapinfo->validate_class_location()) {
2090     unmap_archive(mapinfo);
2091     return MAP_ARCHIVE_OTHER_FAILURE;
2092   }
2093 
< prev index next >