1 /*
2 * Copyright (c) 2012, 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/aotArtifactFinder.hpp"
26 #include "cds/aotCacheAccess.hpp"
27 #include "cds/aotClassInitializer.hpp"
28 #include "cds/aotClassLinker.hpp"
29 #include "cds/aotClassLocation.hpp"
30 #include "cds/aotConstantPoolResolver.hpp"
31 #include "cds/aotLinkedClassBulkLoader.hpp"
32 #include "cds/aotLogging.hpp"
33 #include "cds/aotMapLogger.hpp"
34 #include "cds/aotMappedHeapLoader.hpp"
35 #include "cds/aotMetaspace.hpp"
36 #include "cds/aotReferenceObjSupport.hpp"
37 #include "cds/archiveBuilder.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.inline.hpp"
49 #include "cds/lambdaFormInvokers.hpp"
50 #include "cds/lambdaProxyClassDictionary.hpp"
51 #include "classfile/classLoaderDataGraph.hpp"
52 #include "classfile/classLoaderDataShared.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 "compiler/compileBroker.hpp"
66 #include "compiler/precompiler.hpp"
67 #include "gc/shared/gcVMOperations.hpp"
68 #include "interpreter/bytecodes.hpp"
69 #include "interpreter/bytecodeStream.hpp"
70 #include "jvm_io.h"
71 #include "logging/log.hpp"
72 #include "logging/logMessage.hpp"
73 #include "logging/logStream.hpp"
74 #include "memory/memoryReserver.hpp"
75 #include "memory/metaspace.hpp"
76 #include "memory/metaspaceClosure.hpp"
77 #include "memory/oopFactory.hpp"
78 #include "memory/resourceArea.hpp"
79 #include "memory/universe.hpp"
80 #include "nmt/memTracker.hpp"
81 #include "oops/compressedKlass.hpp"
82 #include "oops/constantPool.inline.hpp"
83 #include "oops/instanceMirrorKlass.hpp"
84 #include "oops/klass.inline.hpp"
85 #include "oops/method.inline.hpp"
86 #include "oops/objArrayOop.hpp"
87 #include "oops/oop.inline.hpp"
88 #include "oops/oopHandle.hpp"
89 #include "oops/resolvedFieldEntry.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/hashTable.hpp"
109 #include "utilities/macros.hpp"
110 #include "utilities/ostream.hpp"
111
112 #include <sys/stat.h>
113
114 ReservedSpace AOTMetaspace::_symbol_rs;
115 VirtualSpace AOTMetaspace::_symbol_vs;
116 bool AOTMetaspace::_archive_loading_failed = false;
117 bool AOTMetaspace::_remapped_readwrite = false;
118 void* AOTMetaspace::_aot_metaspace_static_top = nullptr;
119 intx AOTMetaspace::_relocation_delta;
120 char* AOTMetaspace::_requested_base_address;
121 Array<Method*>* AOTMetaspace::_archived_method_handle_intrinsics = nullptr;
122 bool AOTMetaspace::_use_optimized_module_handling = true;
123 int volatile AOTMetaspace::_preimage_static_archive_dumped = 0;
124 jlong AOTMetaspace::_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 AOTMetaspace::core_region_alignment().
134 //
135 // These 2 regions are populated in the following steps:
136 // [0] All classes are loaded in AOTMetaspace::load_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 //
145 // The heap region is written by HeapShared::write_heap().
146 //
147 // The bitmap region is used to relocate the ro/rw/hp regions.
148
149 static DumpRegion _symbol_region("symbols");
150
151 char* AOTMetaspace::symbol_space_alloc(size_t num_bytes) {
152 return _symbol_region.allocate(num_bytes);
153 }
154
155 // os::vm_allocation_granularity() is usually 4K for most OSes. However, some platforms
156 // such as linux-aarch64 and macos-x64 ...
157 // it can be either 4K or 64K and on macos-aarch64 it is 16K. To generate archives that are
158 // compatible for both settings, an alternative cds core region alignment can be enabled
159 // at building time:
160 // --enable-compactible-cds-alignment
161 // Upon successful configuration, the compactible alignment then can be defined in:
162 // os_linux_aarch64.cpp
163 // os_bsd_x86.cpp
164 size_t AOTMetaspace::core_region_alignment() {
165 return os::cds_core_region_alignment();
166 }
167
168 size_t AOTMetaspace::protection_zone_size() {
169 return os::cds_core_region_alignment();
170 }
171
172 static bool shared_base_valid(char* shared_base) {
173 // We check user input for SharedBaseAddress at dump time.
174
175 // At CDS runtime, "shared_base" will be the (attempted) mapping start. It will also
176 // be the encoding base, since the headers of archived base objects (and with Lilliput,
177 // the prototype mark words) carry pre-computed narrow Klass IDs that refer to the mapping
178 // start as base.
179 //
180 // On AARCH64, The "shared_base" may not be later usable as encoding base, depending on the
181 // total size of the reserved area and the precomputed_narrow_klass_shift. This is checked
182 // before reserving memory. Here we weed out values already known to be invalid later.
183 return AARCH64_ONLY(is_aligned(shared_base, 4 * G)) NOT_AARCH64(true);
184 }
185
186 class DumpClassListCLDClosure : public CLDClosure {
187 static const int INITIAL_TABLE_SIZE = 1987;
188 static const int MAX_TABLE_SIZE = 61333;
189
190 fileStream *_stream;
191 ResizeableHashTable<InstanceKlass*, bool,
192 AnyObj::C_HEAP, mtClassShared> _dumped_classes;
193
194 void dump(InstanceKlass* ik) {
195 bool created;
196 _dumped_classes.put_if_absent(ik, &created);
197 if (!created) {
198 return;
199 }
200 if (_dumped_classes.maybe_grow()) {
201 log_info(aot, hashtables)("Expanded _dumped_classes table to %d", _dumped_classes.table_size());
202 }
203 if (ik->super()) {
204 dump(ik->super());
205 }
206 Array<InstanceKlass*>* interfaces = ik->local_interfaces();
207 int len = interfaces->length();
208 for (int i = 0; i < len; i++) {
209 dump(interfaces->at(i));
210 }
211 ClassListWriter::write_to_stream(ik, _stream);
212 }
213
214 public:
215 DumpClassListCLDClosure(fileStream* f)
216 : CLDClosure(), _dumped_classes(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE) {
217 _stream = f;
218 }
219
220 void do_cld(ClassLoaderData* cld) {
221 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
222 if (klass->is_instance_klass()) {
223 dump(InstanceKlass::cast(klass));
224 }
225 }
226 }
227 };
228
229 void AOTMetaspace::dump_loaded_classes(const char* file_name, TRAPS) {
230 fileStream stream(file_name, "w");
231 if (stream.is_open()) {
232 MutexLocker lock(ClassLoaderDataGraph_lock);
233 MutexLocker lock2(ClassListFile_lock, Mutex::_no_safepoint_check_flag);
234 DumpClassListCLDClosure collect_classes(&stream);
235 ClassLoaderDataGraph::loaded_cld_do(&collect_classes);
236 } else {
237 THROW_MSG(vmSymbols::java_io_IOException(), "Failed to open file");
238 }
239 }
240
241 static bool shared_base_too_high(char* specified_base, char* aligned_base, size_t cds_max) {
242 // Caller should have checked that aligned_base was successfully aligned and is not nullptr.
243 // Comparing specified_base with nullptr is UB.
244 assert(aligned_base != nullptr, "sanity");
245 assert(aligned_base >= specified_base, "sanity");
246
247 if (max_uintx - uintx(aligned_base) < uintx(cds_max)) {
248 // Not enough address space to hold an archive of cds_max bytes from aligned_base.
249 return true;
250 } else {
251 return false;
252 }
253 }
254
255 static char* compute_shared_base(size_t cds_max) {
256 char* specified_base = (char*)SharedBaseAddress;
257 size_t alignment = AOTMetaspace::core_region_alignment();
258 if (UseCompressedClassPointers && CompressedKlassPointers::needs_class_space()) {
259 alignment = MAX2(alignment, Metaspace::reserve_alignment());
260 }
261
262 if (SharedBaseAddress == 0) {
263 // Special meaning of -XX:SharedBaseAddress=0 -> Always map archive at os-selected address.
264 return specified_base;
265 }
266
267 char* aligned_base = can_align_up(specified_base, alignment)
268 ? align_up(specified_base, alignment)
269 : nullptr;
270
271 if (aligned_base != specified_base) {
272 aot_log_info(aot)("SharedBaseAddress (" INTPTR_FORMAT ") aligned up to " INTPTR_FORMAT,
273 p2i(specified_base), p2i(aligned_base));
274 }
275
276 const char* err = nullptr;
277 if (aligned_base == nullptr) {
278 err = "too high";
279 } else if (shared_base_too_high(specified_base, aligned_base, cds_max)) {
280 err = "too high";
281 } else if (!shared_base_valid(aligned_base)) {
282 err = "invalid for this platform";
283 } else {
284 return aligned_base;
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 AOTMetaspace::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 (!((UseEpsilonGC || UseG1GC || UseParallelGC || UseSerialGC || UseShenandoahGC || UseZGC) && UseCompressedClassPointers)) {
308 const char* error;
309 if (CDSConfig::is_dumping_preimage_static_archive()) {
310 error = "Cannot create the AOT configuration file";
311 } else {
312 error = "Cannot create the AOT cache";
313 }
314
315 vm_exit_during_initialization(error,
316 "UseCompressedClassPointers must be enabled, and collector must be "
317 "Epsilon, G1, Parallel, Serial, Shenandoah, or ZGC");
318 }
319 }
320
321 aot_log_info(aot)("Core region alignment: %zu", core_region_alignment());
322 // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
323 // to avoid address space wrap around.
324 size_t cds_max;
325 const size_t reserve_alignment = core_region_alignment();
326
327 #ifdef _LP64
328 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
329 cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
330 #else
331 // We don't support archives larger than 256MB on 32-bit due to limited
332 // virtual address space.
333 cds_max = align_down(256*M, reserve_alignment);
334 #endif
335
336 _requested_base_address = compute_shared_base(cds_max);
337 SharedBaseAddress = (size_t)_requested_base_address;
338
339 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
340 _symbol_rs = MemoryReserver::reserve(symbol_rs_size,
341 os::vm_allocation_granularity(),
342 os::vm_page_size(),
343 mtClassShared);
344 if (!_symbol_rs.is_reserved()) {
345 aot_log_error(aot)("Unable to reserve memory for symbols: %zu bytes.", symbol_rs_size);
346 AOTMetaspace::unrecoverable_writing_error();
347 }
348 _symbol_region.init(&_symbol_rs, &_symbol_vs);
349 }
350
351 // Called by universe_post_init()
352 void AOTMetaspace::post_initialize(TRAPS) {
353 if (CDSConfig::is_using_archive()) {
354 FileMapInfo *static_mapinfo = FileMapInfo::current_info();
355 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
356
357 if (AOTMapLogger::is_logging_at_bootstrap()) {
358 // The map logging needs to be done here, as it requires some stubs on Windows,
359 // which are not generated until the end of init_globals().
360 AOTMapLogger::runtime_log(static_mapinfo, dynamic_mapinfo);
361 }
362
363 // Close any open file descriptors. However, mmap'ed pages will remain in memory.
364 static_mapinfo->close();
365
366 if (HeapShared::is_loading() && HeapShared::is_loading_mapping_mode()) {
367 static_mapinfo->unmap_region(AOTMetaspace::bm);
368 }
369
370 if (dynamic_mapinfo != nullptr) {
371 dynamic_mapinfo->close();
372 dynamic_mapinfo->unmap_region(AOTMetaspace::bm);
373 }
374
375 int size = AOTClassLocationConfig::runtime()->length();
376 if (size > 0) {
377 CDSProtectionDomain::allocate_shared_data_arrays(size, CHECK);
378 }
379 }
380 }
381
382 // Extra java.lang.Strings to be added to the archive
383 static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = nullptr;
384 // Extra Symbols to be added to the archive
385 static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = nullptr;
386 // Methods managed by SystemDictionary::find_method_handle_intrinsic() to be added to the archive
387 static GrowableArray<Method*>* _pending_method_handle_intrinsics = nullptr;
388
389 void AOTMetaspace::read_extra_data(JavaThread* current, const char* filename) {
390 _extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000);
391 _extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000);
392
393 HashtableTextDump reader(filename);
394 reader.check_version("VERSION: 1.0");
395
396 while (reader.remain() > 0) {
397 int utf8_length;
398 int prefix_type = reader.scan_prefix(&utf8_length);
399 ResourceMark rm(current);
400 if (utf8_length == 0x7fffffff) {
401 // buf_len will overflown 32-bit value.
402 aot_log_error(aot)("string length too large: %d", utf8_length);
403 AOTMetaspace::unrecoverable_loading_error();
404 }
405 int buf_len = utf8_length+1;
406 char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
407 reader.get_utf8(utf8_buffer, utf8_length);
408 utf8_buffer[utf8_length] = '\0';
409
410 if (prefix_type == HashtableTextDump::SymbolPrefix) {
411 _extra_symbols->append(SymbolTable::new_permanent_symbol(utf8_buffer));
412 } else{
413 assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity");
414 ExceptionMark em(current);
415 JavaThread* THREAD = current; // For exception macros.
416 oop str = StringTable::intern(utf8_buffer, THREAD);
417
418 if (HAS_PENDING_EXCEPTION) {
419 log_warning(aot, heap)("[line %d] extra interned string allocation failed; size too large: %d",
420 reader.last_line_no(), utf8_length);
421 CLEAR_PENDING_EXCEPTION;
422 } else {
423 #if INCLUDE_CDS_JAVA_HEAP
424 if (HeapShared::is_string_too_large_to_archive(str)) {
425 log_warning(aot, heap)("[line %d] extra interned string ignored; size too large: %d",
426 reader.last_line_no(), utf8_length);
427 continue;
428 }
429 // Make sure this string is included in the dumped interned string table.
430 assert(str != nullptr, "must succeed");
431 _extra_interned_strings->append(OopHandle(Universe::vm_global(), str));
432 #endif
433 }
434 }
435 }
436 }
437
438 void AOTMetaspace::make_method_handle_intrinsics_shareable() {
439 for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
440 Method* m = ArchiveBuilder::current()->get_buffered_addr(_pending_method_handle_intrinsics->at(i));
441 m->remove_unshareable_info();
442 // Each method has its own constant pool (which is distinct from m->method_holder()->constants());
443 m->constants()->remove_unshareable_info();
444 }
445 }
446
447 void AOTMetaspace::write_method_handle_intrinsics() {
448 int len = _pending_method_handle_intrinsics->length();
449 _archived_method_handle_intrinsics = ArchiveBuilder::new_ro_array<Method*>(len);
450 int word_size = _archived_method_handle_intrinsics->size();
451 for (int i = 0; i < len; i++) {
452 Method* m = _pending_method_handle_intrinsics->at(i);
453 ArchiveBuilder::current()->write_pointer_in_buffer(_archived_method_handle_intrinsics->adr_at(i), m);
454 word_size += m->size() + m->constMethod()->size() + m->constants()->size();
455 if (m->constants()->cache() != nullptr) {
456 word_size += m->constants()->cache()->size();
457 }
458 }
459 log_info(aot)("Archived %d method handle intrinsics (%d bytes)", len, word_size * BytesPerWord);
460 }
461
462 // About "serialize" --
463 //
464 // This is (probably a badly named) way to read/write a data stream of pointers and
465 // miscellaneous data from/to the shared archive file. The usual code looks like this:
466 //
467 // // These two global C++ variables are initialized during dump time.
468 // static int _archived_int;
469 // static MetaspaceObj* archived_ptr;
470 //
471 // void MyClass::serialize(SerializeClosure* soc) {
472 // soc->do_int(&_archived_int);
473 // soc->do_int(&_archived_ptr);
474 // }
475 //
476 // At dumptime, these two variables are stored into the CDS archive.
477 // At runtime, these two variables are loaded from the CDS archive.
478 // In addition, the pointer is relocated as necessary.
479 //
480 // Some of the xxx::serialize() functions may have side effects and assume that
481 // the archive is already mapped. For example, SymbolTable::serialize_shared_table_header()
482 // unconditionally makes the set of archived symbols available. Therefore, we put most
483 // of these xxx::serialize() functions inside AOTMetaspace::serialize(), which
484 // is called AFTER we made the decision to map the archive.
485 //
486 // However, some of the "serialized" data are used to decide whether an archive should
487 // be mapped or not (e.g., for checking if the -Djdk.module.main property is compatible
488 // with the archive). The xxx::serialize() functions for these data must be put inside
489 // AOTMetaspace::early_serialize(). Such functions must not produce side effects that
490 // assume we will always decides to map the archive.
491
492 void AOTMetaspace::early_serialize(SerializeClosure* soc) {
493 int tag = 0;
494 soc->do_tag(--tag);
495 CDS_JAVA_HEAP_ONLY(Modules::serialize_archived_module_info(soc);)
496 soc->do_tag(666);
497 }
498
499 void AOTMetaspace::serialize(SerializeClosure* soc) {
500 int tag = 0;
501 soc->do_tag(--tag);
502
503 // Verify the sizes of various metadata in the system.
504 soc->do_tag(sizeof(Method));
505 soc->do_tag(sizeof(ConstMethod));
506 soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
507 soc->do_tag(sizeof(ConstantPool));
508 soc->do_tag(sizeof(ConstantPoolCache));
509 soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
510 soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
511 soc->do_tag(sizeof(Symbol));
512
513 // Need to do this first, as subsequent steps may call virtual functions
514 // in archived Metadata objects.
515 CppVtables::serialize(soc);
516 soc->do_tag(--tag);
517
518 // Dump/restore miscellaneous metadata.
519 JavaClasses::serialize_offsets(soc);
520 Universe::serialize(soc);
521 soc->do_tag(--tag);
522
523 // Dump/restore references to commonly used names and signatures.
524 vmSymbols::serialize(soc);
525 soc->do_tag(--tag);
526
527 // Dump/restore the symbol/string/subgraph_info tables
528 SymbolTable::serialize_shared_table_header(soc);
529 StringTable::serialize_shared_table_header(soc);
530 HeapShared::serialize_tables(soc);
531 SystemDictionaryShared::serialize_dictionary_headers(soc);
532 AOTLinkedClassBulkLoader::serialize(soc);
533 FinalImageRecipes::serialize(soc);
534 TrainingData::serialize(soc);
535 InstanceMirrorKlass::serialize_offsets(soc);
536
537 // Dump/restore well known classes (pointers)
538 SystemDictionaryShared::serialize_vm_classes(soc);
539 soc->do_tag(--tag);
540
541 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
542 soc->do_ptr((void**)&_archived_method_handle_intrinsics);
543
544 LambdaFormInvokers::serialize(soc);
545 AdapterHandlerLibrary::serialize_shared_table_header(soc);
546
547 soc->do_tag(666);
548 }
549
550 // In AOTCache workflow, when dumping preimage, the constant pool entries are stored in unresolved state.
551 // So the fast version of getfield/putfield needs to be converted to nofast version.
552 // When dumping the final image in the assembly phase, these nofast versions are converted back to fast versions
553 // if the constant pool entry refered by these bytecodes is stored in resolved state.
554 // Same principle applies to static and dynamic archives. If the constant pool entry is in resolved state, then
555 // the fast version of the bytecodes can be preserved, else use the nofast version.
556 //
557 // The fast versions of aload_0 (i.e. _fast_Xaccess_0) merges the bytecode pair (aload_0, fast_Xgetfield).
558 // If the fast version of aload_0 is preserved in AOTCache, then the JVMTI notifications for field access and
559 // breakpoint events will be skipped for the second bytecode (fast_Xgetfield) in the pair.
560 // Same holds for fast versions of iload_0. So for these bytecodes, nofast version is used.
561 static void rewrite_bytecodes(const methodHandle& method) {
562 ConstantPool* cp = method->constants();
563 BytecodeStream bcs(method);
564 Bytecodes::Code new_code;
565
566 LogStreamHandle(Trace, aot, resolve) lsh;
567 if (lsh.is_enabled()) {
568 lsh.print("Rewriting bytecodes for ");
569 method()->print_external_name(&lsh);
570 lsh.print("\n");
571 }
572
573 while (!bcs.is_last_bytecode()) {
574 Bytecodes::Code opcode = bcs.next();
575 // Use current opcode as the default value of new_code
576 new_code = opcode;
577 switch(opcode) {
578 case Bytecodes::_getfield: {
579 uint rfe_index = bcs.get_index_u2();
580 bool is_resolved = cp->is_resolved(rfe_index, opcode);
581 if (is_resolved) {
582 assert(!CDSConfig::is_dumping_preimage_static_archive(), "preimage should not have resolved field references");
583 ResolvedFieldEntry* rfe = cp->resolved_field_entry_at(bcs.get_index_u2());
584 switch(rfe->tos_state()) {
585 case btos:
586 // fallthrough
587 case ztos: new_code = Bytecodes::_fast_bgetfield; break;
588 case atos: new_code = Bytecodes::_fast_agetfield; break;
589 case itos: new_code = Bytecodes::_fast_igetfield; break;
590 case ctos: new_code = Bytecodes::_fast_cgetfield; break;
591 case stos: new_code = Bytecodes::_fast_sgetfield; break;
592 case ltos: new_code = Bytecodes::_fast_lgetfield; break;
593 case ftos: new_code = Bytecodes::_fast_fgetfield; break;
594 case dtos: new_code = Bytecodes::_fast_dgetfield; break;
595 default:
596 ShouldNotReachHere();
597 break;
598 }
599 } else {
600 new_code = Bytecodes::_nofast_getfield;
601 }
602 break;
603 }
604 case Bytecodes::_putfield: {
605 uint rfe_index = bcs.get_index_u2();
606 bool is_resolved = cp->is_resolved(rfe_index, opcode);
607 if (is_resolved) {
608 assert(!CDSConfig::is_dumping_preimage_static_archive(), "preimage should not have resolved field references");
609 ResolvedFieldEntry* rfe = cp->resolved_field_entry_at(bcs.get_index_u2());
610 switch(rfe->tos_state()) {
611 case btos: new_code = Bytecodes::_fast_bputfield; break;
612 case ztos: new_code = Bytecodes::_fast_zputfield; break;
613 case atos: new_code = Bytecodes::_fast_aputfield; break;
614 case itos: new_code = Bytecodes::_fast_iputfield; break;
615 case ctos: new_code = Bytecodes::_fast_cputfield; break;
616 case stos: new_code = Bytecodes::_fast_sputfield; break;
617 case ltos: new_code = Bytecodes::_fast_lputfield; break;
618 case ftos: new_code = Bytecodes::_fast_fputfield; break;
619 case dtos: new_code = Bytecodes::_fast_dputfield; break;
620 default:
621 ShouldNotReachHere();
622 break;
623 }
624 } else {
625 new_code = Bytecodes::_nofast_putfield;
626 }
627 break;
628 }
629 case Bytecodes::_aload_0:
630 // Revert _fast_Xaccess_0 or _aload_0 to _nofast_aload_0
631 new_code = Bytecodes::_nofast_aload_0;
632 break;
633 case Bytecodes::_iload:
634 if (!bcs.is_wide()) {
635 new_code = Bytecodes::_nofast_iload;
636 }
637 break;
638 default:
639 break;
640 }
641 if (opcode != new_code) {
642 *bcs.bcp() = new_code;
643 if (lsh.is_enabled()) {
644 lsh.print_cr("%d:%s -> %s", bcs.bci(), Bytecodes::name(opcode), Bytecodes::name(new_code));
645 }
646 }
647 }
648 }
649
650 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
651 // at run time by RewriteBytecodes/RewriteFrequentPairs
652 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
653 void AOTMetaspace::rewrite_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
654 for (int i = 0; i < ik->methods()->length(); i++) {
655 methodHandle m(thread, ik->methods()->at(i));
656 if (ik->can_be_verified_at_dumptime() && ik->is_linked()) {
657 rewrite_bytecodes(m);
658 }
659 Fingerprinter fp(m);
660 // The side effect of this call sets method's fingerprint field.
661 fp.fingerprint();
662 }
663 }
664
665 class VM_PopulateDumpSharedSpace : public VM_Operation {
666 private:
667 ArchiveMappedHeapInfo _mapped_heap_info;
668 ArchiveStreamedHeapInfo _streamed_heap_info;
669 FileMapInfo* _map_info;
670 StaticArchiveBuilder& _builder;
671
672 void dump_java_heap_objects();
673 void dump_shared_symbol_table(GrowableArray<Symbol*>* symbols) {
674 log_info(aot)("Dumping symbol table ...");
675 SymbolTable::write_to_archive(symbols);
676 }
677 char* dump_early_read_only_tables();
678 char* dump_read_only_tables(AOTClassLocationConfig*& cl_config);
679
680 public:
681
682 VM_PopulateDumpSharedSpace(StaticArchiveBuilder& b) :
683 VM_Operation(), _mapped_heap_info(), _streamed_heap_info(), _map_info(nullptr), _builder(b) {}
684
685 bool skip_operation() const { return false; }
686
687 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
688 ArchiveMappedHeapInfo* mapped_heap_info() { return &_mapped_heap_info; }
689 ArchiveStreamedHeapInfo* streamed_heap_info() { return &_streamed_heap_info; }
690 FileMapInfo* map_info() const { return _map_info; }
691 void doit(); // outline because gdb sucks
692 bool allow_nested_vm_operations() const { return true; }
693 }; // class VM_PopulateDumpSharedSpace
694
695 class StaticArchiveBuilder : public ArchiveBuilder {
696 public:
697 StaticArchiveBuilder() : ArchiveBuilder() {}
698
699 virtual void iterate_roots(MetaspaceClosure* it) {
700 AOTArtifactFinder::all_cached_classes_do(it);
701 SystemDictionaryShared::dumptime_classes_do(it);
702 Universe::metaspace_pointers_do(it);
703 vmSymbols::metaspace_pointers_do(it);
704 TrainingData::iterate_roots(it);
705
706 // The above code should find all the symbols that are referenced by the
707 // archived classes. We just need to add the extra symbols which
708 // may not be used by any of the archived classes -- these are usually
709 // symbols that we anticipate to be used at run time, so we can store
710 // them in the RO region, to be shared across multiple processes.
711 if (_extra_symbols != nullptr) {
712 for (int i = 0; i < _extra_symbols->length(); i++) {
713 it->push(_extra_symbols->adr_at(i));
714 }
715 }
716
717 for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
718 it->push(_pending_method_handle_intrinsics->adr_at(i));
719 }
720 }
721 };
722
723 char* VM_PopulateDumpSharedSpace::dump_early_read_only_tables() {
724 ArchiveBuilder::OtherROAllocMark mark;
725
726 CDS_JAVA_HEAP_ONLY(Modules::dump_archived_module_info());
727
728 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
729 char* start = ro_region->top();
730 WriteClosure wc(ro_region);
731 AOTMetaspace::early_serialize(&wc);
732 return start;
733 }
734
735 char* VM_PopulateDumpSharedSpace::dump_read_only_tables(AOTClassLocationConfig*& cl_config) {
736 ArchiveBuilder::OtherROAllocMark mark;
737
738 SystemDictionaryShared::write_to_archive();
739 cl_config = AOTClassLocationConfig::dumptime()->write_to_archive();
740 AOTClassLinker::write_to_archive();
741 if (CDSConfig::is_dumping_preimage_static_archive()) {
742 FinalImageRecipes::record_recipes();
743 }
744
745 TrainingData::dump_training_data();
746
747 AOTMetaspace::write_method_handle_intrinsics();
748
749 // Write lambform lines into archive
750 LambdaFormInvokers::dump_static_archive_invokers();
751
752 if (CDSConfig::is_dumping_adapters()) {
753 AdapterHandlerLibrary::dump_aot_adapter_table();
754 }
755
756 // Write the other data to the output array.
757 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
758 char* start = ro_region->top();
759 WriteClosure wc(ro_region);
760 AOTMetaspace::serialize(&wc);
761
762 return start;
763 }
764
765 void VM_PopulateDumpSharedSpace::doit() {
766 CDSConfig::set_is_at_aot_safepoint(true);
767
768 if (!CDSConfig::is_dumping_final_static_archive()) {
769 guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
770 }
771
772 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
773
774 _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
775 if (CDSConfig::is_dumping_method_handles()) {
776 // When dumping AOT-linked classes, some classes may have direct references to a method handle
777 // intrinsic. The easiest thing is to save all of them into the AOT cache.
778 SystemDictionary::get_all_method_handle_intrinsics(_pending_method_handle_intrinsics);
779 }
780
781 AOTClassLocationConfig::dumptime_check_nonempty_dirs();
782
783 NOT_PRODUCT(SystemDictionary::verify();)
784
785 // Block concurrent class unloading from changing the _dumptime_table
786 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
787
788 _builder.gather_source_objs();
789 _builder.reserve_buffer();
790
791 CppVtables::dumptime_init(&_builder);
792
793 _builder.sort_metadata_objs();
794 _builder.dump_rw_metadata();
795 _builder.dump_ro_metadata();
796 _builder.relocate_metaspaceobj_embedded_pointers();
797
798 log_info(aot)("Make classes shareable");
799 _builder.make_klasses_shareable();
800 AOTMetaspace::make_method_handle_intrinsics_shareable();
801
802 dump_java_heap_objects();
803 dump_shared_symbol_table(_builder.symbols());
804
805 char* early_serialized_data = dump_early_read_only_tables();
806 AOTClassLocationConfig* cl_config;
807 char* serialized_data = dump_read_only_tables(cl_config);
808
809 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
810 log_info(aot)("Adjust lambda proxy class dictionary");
811 LambdaProxyClassDictionary::adjust_dumptime_table();
812 }
813
814 log_info(cds)("Make training data shareable");
815 _builder.make_training_data_shareable();
816
817 // The vtable clones contain addresses of the current process.
818 // We don't want to write these addresses into the archive.
819 CppVtables::zero_archived_vtables();
820
821 // Write the archive file
822 if (CDSConfig::is_dumping_final_static_archive()) {
823 FileMapInfo::free_current_info(); // FIXME: should not free current info
824 }
825 const char* static_archive = CDSConfig::output_archive_path();
826 assert(static_archive != nullptr, "sanity");
827 _map_info = new FileMapInfo(static_archive, true);
828 _map_info->populate_header(AOTMetaspace::core_region_alignment());
829 _map_info->set_early_serialized_data(early_serialized_data);
830 _map_info->set_serialized_data(serialized_data);
831 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
832 _map_info->header()->set_class_location_config(cl_config);
833
834 HeapShared::delete_tables_with_raw_oops();
835 CDSConfig::set_is_at_aot_safepoint(false);
836 }
837
838 class CollectClassesForLinking : public KlassClosure {
839 GrowableArray<OopHandle> _mirrors;
840
841 public:
842 CollectClassesForLinking() : _mirrors() {
843 // ClassLoaderDataGraph::loaded_classes_do_keepalive() requires ClassLoaderDataGraph_lock.
844 // We cannot link the classes while holding this lock (or else we may run into deadlock).
845 // Therefore, we need to first collect all the classes, keeping them alive by
846 // holding onto their java_mirrors in global OopHandles. We then link the classes after
847 // releasing the lock.
848 MutexLocker lock(ClassLoaderDataGraph_lock);
849 ClassLoaderDataGraph::loaded_classes_do_keepalive(this);
850 }
851
852 ~CollectClassesForLinking() {
853 for (int i = 0; i < _mirrors.length(); i++) {
854 _mirrors.at(i).release(Universe::vm_global());
855 }
856 }
857
858 void do_cld(ClassLoaderData* cld) {
859 assert(cld->is_alive(), "must be");
860 }
861
862 void do_klass(Klass* k) {
863 if (k->is_instance_klass()) {
864 _mirrors.append(OopHandle(Universe::vm_global(), k->java_mirror()));
865 }
866 }
867
868 const GrowableArray<OopHandle>* mirrors() const { return &_mirrors; }
869 };
870
871 // Check if we can eagerly link this class at dump time, so we can avoid the
872 // runtime linking overhead (especially verification)
873 bool AOTMetaspace::may_be_eagerly_linked(InstanceKlass* ik) {
874 if (!ik->can_be_verified_at_dumptime()) {
875 // For old classes, try to leave them in the unlinked state, so
876 // we can still store them in the archive. They must be
877 // linked/verified at runtime.
878 return false;
879 }
880 if (CDSConfig::is_dumping_dynamic_archive() && ik->defined_by_other_loaders()) {
881 // Linking of unregistered classes at this stage may cause more
882 // classes to be resolved, resulting in calls to ClassLoader.loadClass()
883 // that may not be expected by custom class loaders.
884 //
885 // It's OK to do this for the built-in loaders as we know they can
886 // tolerate this.
887 return false;
888 }
889 return true;
890 }
891
892 void AOTMetaspace::link_all_loaded_classes(JavaThread* current) {
893 while (true) {
894 ResourceMark rm(current);
895 CollectClassesForLinking collect_classes;
896 bool has_linked = false;
897 const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
898 for (int i = 0; i < mirrors->length(); i++) {
899 OopHandle mirror = mirrors->at(i);
900 InstanceKlass* ik = java_lang_Class::as_InstanceKlass(mirror.resolve());
901 if (may_be_eagerly_linked(ik)) {
902 has_linked |= try_link_class(current, ik);
903 }
904 if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) {
905 AOTClassInitializer::maybe_preinit_class(ik, current);
906 }
907 }
908
909 if (!has_linked) {
910 break;
911 }
912 // Class linking includes verification which may load more classes.
913 // Keep scanning until we have linked no more classes.
914 }
915 }
916
917 void AOTMetaspace::link_shared_classes(TRAPS) {
918 AOTClassLinker::initialize();
919 AOTClassInitializer::init_test_class(CHECK);
920
921 if (CDSConfig::is_dumping_final_static_archive()) {
922 // - Load and link all classes used in the training run.
923 // - Initialize @AOTSafeClassInitializer classes that were
924 // initialized in the training run.
925 // - Perform per-class optimization such as AOT-resolution of
926 // constant pool entries that were resolved during the training run.
927 FinalImageRecipes::apply_recipes(CHECK);
928
929 // Because the AOT assembly phase does not run the same exact code as in the
930 // training run (e.g., we use different lambda form invoker classes;
931 // generated lambda form classes are not recorded in FinalImageRecipes),
932 // the recipes do not cover all classes that have been loaded so far. As
933 // a result, we might have some unlinked classes at this point. Since we
934 // require cached classes to be linked, all such classes will be linked
935 // by the following step.
936 }
937
938 link_all_loaded_classes(THREAD);
939
940 // Eargerly resolve all string constants in constant pools
941 {
942 ResourceMark rm(THREAD);
943 CollectClassesForLinking collect_classes;
944 const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
945 for (int i = 0; i < mirrors->length(); i++) {
946 OopHandle mirror = mirrors->at(i);
947 InstanceKlass* ik = java_lang_Class::as_InstanceKlass(mirror.resolve());
948 AOTConstantPoolResolver::preresolve_string_cp_entries(ik, CHECK);
949 if (CDSConfig::is_dumping_preimage_static_archive()) {
950 FinalImageRecipes::add_reflection_data_flags(ik, CHECK);
951 }
952 }
953 }
954 }
955
956 void AOTMetaspace::dump_static_archive(TRAPS) {
957 CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
958 ResourceMark rm(THREAD);
959 HandleMark hm(THREAD);
960
961 if (CDSConfig::is_dumping_final_static_archive() && AOTPrintTrainingInfo) {
962 tty->print_cr("==================== archived_training_data ** before dumping ====================");
963 TrainingData::print_archived_training_data_on(tty);
964 }
965
966 StaticArchiveBuilder builder;
967 dump_static_archive_impl(builder, THREAD);
968 if (HAS_PENDING_EXCEPTION) {
969 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
970 aot_log_error(aot)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
971 "%zuM", MaxHeapSize/M);
972 AOTMetaspace::writing_error();
973 } else {
974 oop message = java_lang_Throwable::message(PENDING_EXCEPTION);
975 aot_log_error(aot)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
976 message == nullptr ? "(null)" : java_lang_String::as_utf8_string(message));
977 AOTMetaspace::writing_error(err_msg("Unexpected exception, use -Xlog:aot%s,exceptions=trace for detail",
978 CDSConfig::new_aot_flags_used() ? "" : ",cds"));
979 }
980 }
981
982 if (CDSConfig::new_aot_flags_used()) {
983 if (CDSConfig::is_dumping_preimage_static_archive()) {
984 // We are in the JVM that runs the training run. Continue execution,
985 // so that it can finish all clean-up and return the correct exit
986 // code to the OS.
987 } else {
988 // The JLI launcher only recognizes the "old" -Xshare:dump flag.
989 // When the new -XX:AOTMode=create flag is used, we can't return
990 // to the JLI launcher, as the launcher will fail when trying to
991 // run the main class, which is not what we want.
992 struct stat st;
993 if (os::stat(AOTCache, &st) != 0) {
994 tty->print_cr("AOTCache creation failed: %s", AOTCache);
995 } else {
996 tty->print_cr("AOTCache creation is complete: %s " INT64_FORMAT " bytes", AOTCache, (int64_t)(st.st_size));
997 }
998 vm_direct_exit(0);
999 }
1000 }
1001 }
1002
1003 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
1004 void AOTMetaspace::adjust_heap_sizes_for_dumping() {
1005 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
1006 return;
1007 }
1008 // CDS heap dumping requires all string oops to have an offset
1009 // from the heap bottom that can be encoded in 32-bit.
1010 julong max_heap_size = (julong)(4 * G);
1011
1012 if (MinHeapSize > max_heap_size) {
1013 log_debug(aot)("Setting MinHeapSize to 4G for CDS dumping, original size = %zuM", MinHeapSize/M);
1014 FLAG_SET_ERGO(MinHeapSize, max_heap_size);
1015 }
1016 if (InitialHeapSize > max_heap_size) {
1017 log_debug(aot)("Setting InitialHeapSize to 4G for CDS dumping, original size = %zuM", InitialHeapSize/M);
1018 FLAG_SET_ERGO(InitialHeapSize, max_heap_size);
1019 }
1020 if (MaxHeapSize > max_heap_size) {
1021 log_debug(aot)("Setting MaxHeapSize to 4G for CDS dumping, original size = %zuM", MaxHeapSize/M);
1022 FLAG_SET_ERGO(MaxHeapSize, max_heap_size);
1023 }
1024 }
1025 #endif // INCLUDE_CDS_JAVA_HEAP && _LP64
1026
1027 void AOTMetaspace::get_default_classlist(char* default_classlist, const size_t buf_size) {
1028 const char* filesep = os::file_separator();
1029 jio_snprintf(default_classlist, buf_size, "%s%slib%sclasslist",
1030 Arguments::get_java_home(), filesep, filesep);
1031 }
1032
1033 void AOTMetaspace::load_classes(TRAPS) {
1034 char default_classlist[JVM_MAXPATHLEN];
1035 const char* classlist_path;
1036
1037 get_default_classlist(default_classlist, JVM_MAXPATHLEN);
1038 if (SharedClassListFile == nullptr) {
1039 classlist_path = default_classlist;
1040 } else {
1041 classlist_path = SharedClassListFile;
1042 }
1043
1044 aot_log_info(aot)("Loading classes to share ...");
1045 ClassListParser::parse_classlist(classlist_path,
1046 ClassListParser::_parse_all, CHECK);
1047 if (ExtraSharedClassListFile) {
1048 ClassListParser::parse_classlist(ExtraSharedClassListFile,
1049 ClassListParser::_parse_all, CHECK);
1050 }
1051 if (classlist_path != default_classlist) {
1052 struct stat statbuf;
1053 if (os::stat(default_classlist, &statbuf) == 0) {
1054 // File exists, let's use it.
1055 ClassListParser::parse_classlist(default_classlist,
1056 ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
1057 }
1058 }
1059
1060 // Some classes are used at CDS runtime but are not yet loaded at this point.
1061 // We can perform dummmy calls to these classes at dumptime to ensure they
1062 // are archived.
1063 exercise_runtime_cds_code(CHECK);
1064
1065 aot_log_info(aot)("Loading classes to share: done.");
1066 }
1067
1068 void AOTMetaspace::exercise_runtime_cds_code(TRAPS) {
1069 // Exercise the manifest processing code
1070 const char* dummy = "Manifest-Version: 1.0\n";
1071 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
1072
1073 // Exercise FileSystem and URL code
1074 CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
1075 }
1076
1077 bool AOTMetaspace::is_recording_preimage_static_archive() {
1078 if (CDSConfig::is_dumping_preimage_static_archive()) {
1079 return _preimage_static_archive_dumped == 0;
1080 }
1081 return false;
1082 }
1083
1084 jlong AOTMetaspace::get_preimage_static_archive_recording_duration() {
1085 if (CDSConfig::is_dumping_preimage_static_archive()) {
1086 if (_preimage_static_archive_recording_duration == 0) {
1087 // The recording has not yet finished so return the current elapsed time.
1088 return Management::ticks_to_ms(os::elapsed_counter());
1089 }
1090 return _preimage_static_archive_recording_duration;
1091 }
1092 return 0;
1093 }
1094
1095 void AOTMetaspace::dump_static_archive_impl(StaticArchiveBuilder& builder, TRAPS) {
1096 if (CDSConfig::is_dumping_preimage_static_archive()) {
1097 if (AtomicAccess::cmpxchg(&_preimage_static_archive_dumped, 0, 1) != 0) {
1098 return;
1099 }
1100 _preimage_static_archive_recording_duration = Management::ticks_to_ms(os::elapsed_counter());
1101 }
1102
1103 if (CDSConfig::is_dumping_classic_static_archive()) {
1104 // We are running with -Xshare:dump
1105 load_classes(CHECK);
1106
1107 if (SharedArchiveConfigFile) {
1108 log_info(aot)("Reading extra data from %s ...", SharedArchiveConfigFile);
1109 read_extra_data(THREAD, SharedArchiveConfigFile);
1110 log_info(aot)("Reading extra data: done.");
1111 }
1112 }
1113
1114 if (CDSConfig::is_dumping_preimage_static_archive()) {
1115 log_info(aot)("Reading lambda form invokers from JDK default classlist ...");
1116 char default_classlist[JVM_MAXPATHLEN];
1117 get_default_classlist(default_classlist, JVM_MAXPATHLEN);
1118 struct stat statbuf;
1119 if (os::stat(default_classlist, &statbuf) == 0) {
1120 ClassListParser::parse_classlist(default_classlist,
1121 ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
1122 }
1123 }
1124
1125 #if INCLUDE_CDS_JAVA_HEAP
1126 if (CDSConfig::is_dumping_heap()) {
1127 assert(CDSConfig::allow_only_single_java_thread(), "Required");
1128 if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
1129 report_loading_error("archivedBootLayer not available, disabling full module graph");
1130 CDSConfig::stop_dumping_full_module_graph();
1131 }
1132 // Do this before link_shared_classes(), as the following line may load new classes.
1133 HeapShared::init_for_dumping(CHECK);
1134 }
1135 #endif
1136
1137 if (CDSConfig::is_dumping_final_static_archive()) {
1138 if (ExtraSharedClassListFile) {
1139 log_info(aot)("Loading extra classes from %s ...", ExtraSharedClassListFile);
1140 ClassListParser::parse_classlist(ExtraSharedClassListFile,
1141 ClassListParser::_parse_all, CHECK);
1142 }
1143 }
1144
1145 // Rewrite and link classes
1146 log_info(aot)("Rewriting and linking classes ...");
1147
1148 // Link any classes which got missed. This would happen if we have loaded classes that
1149 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1150 // fails verification, all other interfaces that were not specified in the classlist but
1151 // are implemented by K are not verified.
1152 link_shared_classes(CHECK);
1153 log_info(aot)("Rewriting and linking classes: done");
1154 TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
1155
1156 if (CDSConfig::is_dumping_regenerated_lambdaform_invokers()) {
1157 LambdaFormInvokers::regenerate_holder_classes(CHECK);
1158 }
1159
1160 #if INCLUDE_CDS_JAVA_HEAP
1161 if (CDSConfig::is_dumping_heap()) {
1162 HeapShared::init_heap_writer();
1163 if (CDSConfig::is_dumping_full_module_graph()) {
1164 ClassLoaderDataShared::ensure_module_entry_tables_exist();
1165 HeapShared::reset_archived_object_states(CHECK);
1166 }
1167
1168 if (ArchiveLoaderLookupCache) {
1169 SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK);
1170 }
1171
1172 AOTReferenceObjSupport::initialize(CHECK);
1173 AOTReferenceObjSupport::stabilize_cached_reference_objects(CHECK);
1174
1175 if (CDSConfig::is_initing_classes_at_dump_time()) {
1176 // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
1177 // to null, and it will be initialized again at runtime.
1178 log_debug(aot)("Resetting Class::reflectionFactory");
1179 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
1180 Symbol* method_sig = vmSymbols::void_method_signature();
1181 JavaValue result(T_VOID);
1182 JavaCalls::call_static(&result, vmClasses::Class_klass(),
1183 method_name, method_sig, CHECK);
1184
1185 // Perhaps there is a way to avoid hard-coding these names here.
1186 // See discussion in JDK-8342481.
1187 }
1188
1189 if (HeapShared::is_writing_mapping_mode()) {
1190 // Do this at the very end, when no Java code will be executed. Otherwise
1191 // some new strings may be added to the intern table.
1192 StringTable::allocate_shared_strings_array(CHECK);
1193 }
1194 } else {
1195 log_info(aot)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
1196 CDSConfig::stop_using_optimized_module_handling();
1197 }
1198 #endif
1199
1200 VM_PopulateDumpSharedSpace op(builder);
1201 VMThread::execute(&op);
1202
1203 if (CDSConfig::is_dumping_final_static_archive()) {
1204 if (AOTCodeCache::is_caching_enabled()) {
1205 // We have just created the final image. Let's run the AOT compiler
1206 if (AOTPrintTrainingInfo) {
1207 tty->print_cr("==================== archived_training_data ** after dumping ====================");
1208 TrainingData::print_archived_training_data_on(tty);
1209 }
1210
1211 {
1212 builder.start_ac_region();
1213 if (AOTCodeCache::is_dumping_code()) {
1214 CDSConfig::enable_dumping_aot_code();
1215 log_info(aot)("Compiling AOT code");
1216 Precompiler::compile_aot_code(&builder, CHECK);
1217 log_info(aot)("Finished compiling AOT code");
1218 CDSConfig::disable_dumping_aot_code();
1219 }
1220 // Write the contents to aot code region and close AOTCodeCache before packing the region
1221 AOTCodeCache::close();
1222 log_info(aot)("Dumped AOT code Cache");
1223 builder.end_ac_region();
1224 }
1225 }
1226 }
1227
1228 bool status = write_static_archive(&builder, op.map_info(), op.mapped_heap_info(), op.streamed_heap_info());
1229 if (status && CDSConfig::is_dumping_preimage_static_archive()) {
1230 tty->print_cr("%s AOTConfiguration recorded: %s",
1231 CDSConfig::has_temp_aot_config_file() ? "Temporary" : "", AOTConfiguration);
1232 if (CDSConfig::is_single_command_training()) {
1233 fork_and_dump_final_static_archive(CHECK);
1234 }
1235 }
1236
1237 if (!status) {
1238 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
1239 }
1240 }
1241
1242 bool AOTMetaspace::write_static_archive(ArchiveBuilder* builder,
1243 FileMapInfo* map_info,
1244 ArchiveMappedHeapInfo* mapped_heap_info,
1245 ArchiveStreamedHeapInfo* streamed_heap_info) {
1246 // relocate the data so that it can be mapped to AOTMetaspace::requested_base_address()
1247 // without runtime relocation.
1248 builder->relocate_to_requested();
1249
1250 map_info->open_as_output();
1251 if (!map_info->is_open()) {
1252 return false;
1253 }
1254 builder->write_archive(map_info, mapped_heap_info, streamed_heap_info);
1255 return true;
1256 }
1257
1258 static void print_java_launcher(outputStream* st) {
1259 st->print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator());
1260 }
1261
1262 static void append_args(GrowableArray<Handle>* args, const char* arg, TRAPS) {
1263 Handle string = java_lang_String::create_from_str(arg, CHECK);
1264 args->append(string);
1265 }
1266
1267 // Pass all options in Arguments::jvm_args_array() to a child JVM process
1268 // using the JAVA_TOOL_OPTIONS environment variable.
1269 static int exec_jvm_with_java_tool_options(const char* java_launcher_path, TRAPS) {
1270 ResourceMark rm(THREAD);
1271 HandleMark hm(THREAD);
1272 GrowableArray<Handle> args;
1273
1274 const char* cp = Arguments::get_appclasspath();
1275 if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1276 // We cannot use "-cp", because "-cp" is only interpreted by the java launcher,
1277 // and is not interpreter by arguments.cpp when it loads args from JAVA_TOOL_OPTIONS
1278 stringStream ss;
1279 ss.print("-Djava.class.path=");
1280 ss.print_raw(cp);
1281 append_args(&args, ss.freeze(), CHECK_0);
1282 // CDS$ProcessLauncher::execWithJavaToolOptions() must unset CLASSPATH, which has
1283 // a higher priority than -Djava.class.path=
1284 }
1285
1286 // Pass all arguments. These include those from JAVA_TOOL_OPTIONS and _JAVA_OPTIONS.
1287 for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1288 const char* arg = Arguments::jvm_args_array()[i];
1289 if (strstr(arg, "-XX:AOTCacheOutput=") == arg || // arg starts with ...
1290 strstr(arg, "-XX:AOTConfiguration=") == arg ||
1291 strstr(arg, "-XX:AOTMode=") == arg) {
1292 // Filter these out. They wiill be set below.
1293 } else {
1294 append_args(&args, arg, CHECK_0);
1295 }
1296 }
1297
1298 // Note: because we are running in AOTMode=record, JDK_AOT_VM_OPTIONS have not been
1299 // parsed, so they are not in Arguments::jvm_args_array. If JDK_AOT_VM_OPTIONS is in
1300 // the environment, it will be inherited and parsed by the child JVM process
1301 // in Arguments::parse_java_tool_options_environment_variable().
1302 precond(strcmp(AOTMode, "record") == 0);
1303
1304 // We don't pass Arguments::jvm_flags_array(), as those will be added by
1305 // the child process when it loads .hotspotrc
1306
1307 {
1308 // If AOTCacheOutput contains %p, it should have been already substituted with the
1309 // pid of the training process.
1310 stringStream ss;
1311 ss.print("-XX:AOTCacheOutput=");
1312 ss.print_raw(AOTCacheOutput);
1313 append_args(&args, ss.freeze(), CHECK_0);
1314 }
1315 {
1316 // If AOTCacheConfiguration contains %p, it should have been already substituted with the
1317 // pid of the training process.
1318 // If AOTCacheConfiguration was not explicitly specified, it should have been assigned a
1319 // temporary file name.
1320 stringStream ss;
1321 ss.print("-XX:AOTConfiguration=");
1322 ss.print_raw(AOTConfiguration);
1323 append_args(&args, ss.freeze(), CHECK_0);
1324 }
1325
1326 append_args(&args, "-XX:AOTMode=create", CHECK_0);
1327
1328 Symbol* klass_name = SymbolTable::new_symbol("jdk/internal/misc/CDS$ProcessLauncher");
1329 Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, CHECK_0);
1330 Symbol* methodName = SymbolTable::new_symbol("execWithJavaToolOptions");
1331 Symbol* methodSignature = SymbolTable::new_symbol("(Ljava/lang/String;[Ljava/lang/String;)I");
1332
1333 Handle launcher = java_lang_String::create_from_str(java_launcher_path, CHECK_0);
1334 objArrayOop array = oopFactory::new_objArray(vmClasses::String_klass(), args.length(), CHECK_0);
1335 for (int i = 0; i < args.length(); i++) {
1336 array->obj_at_put(i, args.at(i)());
1337 }
1338 objArrayHandle launcher_args(THREAD, array);
1339
1340 // The following call will pass all options inside the JAVA_TOOL_OPTIONS env variable to
1341 // the child process. It will also clear the _JAVA_OPTIONS and CLASSPATH env variables for
1342 // the child process.
1343 //
1344 // Note: the env variables are set only for the child process. They are not changed
1345 // for the current process. See java.lang.ProcessBuilder::environment().
1346 JavaValue result(T_OBJECT);
1347 JavaCallArguments javacall_args(2);
1348 javacall_args.push_oop(launcher);
1349 javacall_args.push_oop(launcher_args);
1350 JavaCalls::call_static(&result,
1351 InstanceKlass::cast(k),
1352 methodName,
1353 methodSignature,
1354 &javacall_args,
1355 CHECK_0);
1356 return result.get_jint();
1357 }
1358
1359 void AOTMetaspace::fork_and_dump_final_static_archive(TRAPS) {
1360 assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1361
1362 ResourceMark rm;
1363 stringStream ss;
1364 print_java_launcher(&ss);
1365 const char* cmd = ss.freeze();
1366 tty->print_cr("Launching child process %s to assemble AOT cache %s using configuration %s", cmd, AOTCacheOutput, AOTConfiguration);
1367 int status = exec_jvm_with_java_tool_options(cmd, CHECK);
1368 if (status != 0) {
1369 log_error(aot)("Child process failed; status = %d", status);
1370 // We leave the temp config file for debugging
1371 } else if (CDSConfig::has_temp_aot_config_file()) {
1372 const char* tmp_config = AOTConfiguration;
1373 // On Windows, need WRITE permission to remove the file.
1374 WINDOWS_ONLY(chmod(tmp_config, _S_IREAD | _S_IWRITE));
1375 status = remove(tmp_config);
1376 if (status != 0) {
1377 log_error(aot)("Failed to remove temporary AOT configuration file %s", tmp_config);
1378 } else {
1379 tty->print_cr("Removed temporary AOT configuration file %s", tmp_config);
1380 }
1381 }
1382 }
1383
1384 // Returns true if the class's status has changed.
1385 bool AOTMetaspace::try_link_class(JavaThread* current, InstanceKlass* ik) {
1386 ExceptionMark em(current);
1387 JavaThread* THREAD = current; // For exception macros.
1388 assert(CDSConfig::is_dumping_archive(), "sanity");
1389
1390 if (ik->in_aot_cache() && !CDSConfig::is_dumping_final_static_archive()) {
1391 assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1392 return false;
1393 }
1394
1395 if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1396 !SystemDictionaryShared::has_class_failed_verification(ik)) {
1397 bool saved = BytecodeVerificationLocal;
1398 if (ik->defined_by_other_loaders() && ik->class_loader() == nullptr) {
1399 // The verification decision is based on BytecodeVerificationRemote
1400 // for non-system classes. Since we are using the null classloader
1401 // to load non-system classes for customized class loaders during dumping,
1402 // we need to temporarily change BytecodeVerificationLocal to be the same as
1403 // BytecodeVerificationRemote. Note this can cause the parent system
1404 // classes also being verified. The extra overhead is acceptable during
1405 // dumping.
1406 BytecodeVerificationLocal = BytecodeVerificationRemote;
1407 }
1408 ik->link_class(THREAD);
1409 if (HAS_PENDING_EXCEPTION) {
1410 ResourceMark rm(THREAD);
1411 aot_log_warning(aot)("Preload Warning: Verification failed for %s",
1412 ik->external_name());
1413 CLEAR_PENDING_EXCEPTION;
1414 SystemDictionaryShared::set_class_has_failed_verification(ik);
1415 } else {
1416 assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity");
1417 ik->compute_has_loops_flag_for_methods();
1418 }
1419 BytecodeVerificationLocal = saved;
1420 return true;
1421 } else {
1422 return false;
1423 }
1424 }
1425
1426 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1427 if (CDSConfig::is_dumping_heap()) {
1428 HeapShared::write_heap(&_mapped_heap_info, &_streamed_heap_info);
1429 } else if (!CDSConfig::is_dumping_preimage_static_archive()) {
1430 CDSConfig::log_reasons_for_not_dumping_heap();
1431 }
1432 }
1433
1434 void AOTMetaspace::set_aot_metaspace_range(void* base, void *static_top, void* top) {
1435 assert(base <= static_top && static_top <= top, "must be");
1436 _aot_metaspace_static_top = static_top;
1437 MetaspaceObj::set_aot_metaspace_range(base, top);
1438 }
1439
1440 bool AOTMetaspace::in_aot_cache_dynamic_region(void* p) {
1441 if ((p < MetaspaceObj::aot_metaspace_top()) &&
1442 (p >= _aot_metaspace_static_top)) {
1443 return true;
1444 } else {
1445 return false;
1446 }
1447 }
1448
1449 bool AOTMetaspace::in_aot_cache_static_region(void* p) {
1450 if (in_aot_cache(p) && !in_aot_cache_dynamic_region(p)) {
1451 return true;
1452 } else {
1453 return false;
1454 }
1455 }
1456
1457 // This function is called when the JVM is unable to load the specified archive(s) due to one
1458 // of the following conditions.
1459 // - There's an error that indicates that the archive(s) files were corrupt or otherwise damaged.
1460 // - When -XX:+RequireSharedSpaces is specified, AND the JVM cannot load the archive(s) due
1461 // to version or classpath mismatch.
1462 void AOTMetaspace::unrecoverable_loading_error(const char* message) {
1463 report_loading_error("%s", message);
1464
1465 if (CDSConfig::is_dumping_final_static_archive()) {
1466 vm_exit_during_initialization("Must be a valid AOT configuration generated by the current JVM", AOTConfiguration);
1467 } else if (CDSConfig::new_aot_flags_used()) {
1468 vm_exit_during_initialization("Unable to use AOT cache.", nullptr);
1469 } else {
1470 vm_exit_during_initialization("Unable to use shared archive. Unrecoverable archive loading error (run with -Xlog:aot,cds for details)", message);
1471 }
1472 }
1473
1474 void AOTMetaspace::report_loading_error(const char* format, ...) {
1475 // When using AOT cache, errors messages are always printed on the error channel.
1476 LogStream ls_aot(LogLevel::Error, LogTagSetMapping<LOG_TAGS(aot)>::tagset());
1477
1478 // If we are loading load the default CDS archive, it may fail due to incompatible VM options.
1479 // Print at the info level to avoid excessive verbosity.
1480 // However, if the user has specified a CDS archive (or AOT cache), they would be interested in
1481 // knowing that the loading fails, so we print at the error level.
1482 LogLevelType level = (!CDSConfig::is_using_archive() || CDSConfig::is_using_only_default_archive()) ?
1483 LogLevel::Info : LogLevel::Error;
1484 LogStream ls_cds(level, LogTagSetMapping<LOG_TAGS(cds)>::tagset());
1485
1486 LogStream& ls = CDSConfig::new_aot_flags_used() ? ls_aot : ls_cds;
1487 if (!ls.is_enabled()) {
1488 return;
1489 }
1490
1491 va_list ap;
1492 va_start(ap, format);
1493
1494 static bool printed_error = false;
1495 if (!printed_error) { // No need for locks. Loading error checks happen only in main thread.
1496 ls.print_cr("An error has occurred while processing the %s. Run with -Xlog:%s for details.",
1497 CDSConfig::type_of_archive_being_loaded(), CDSConfig::new_aot_flags_used() ? "aot" : "aot,cds");
1498 printed_error = true;
1499 }
1500 ls.vprint_cr(format, ap);
1501
1502 va_end(ap);
1503 }
1504
1505 // This function is called when the JVM is unable to write the specified CDS archive due to an
1506 // unrecoverable error.
1507 void AOTMetaspace::unrecoverable_writing_error(const char* message) {
1508 writing_error(message);
1509 vm_direct_exit(1);
1510 }
1511
1512 // This function is called when the JVM is unable to write the specified CDS archive due to a
1513 // an error. The error will be propagated
1514 void AOTMetaspace::writing_error(const char* message) {
1515 aot_log_error(aot)("An error has occurred while writing the shared archive file.");
1516 if (message != nullptr) {
1517 aot_log_error(aot)("%s", message);
1518 }
1519 }
1520
1521 void AOTMetaspace::initialize_runtime_shared_and_meta_spaces() {
1522 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1523 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1524
1525 FileMapInfo* static_mapinfo = FileMapInfo::current_info();
1526 FileMapInfo* dynamic_mapinfo = nullptr;
1527
1528 if (static_mapinfo != nullptr) {
1529 aot_log_info(aot)("Core region alignment: %zu", static_mapinfo->core_region_alignment());
1530 dynamic_mapinfo = open_dynamic_archive();
1531
1532 aot_log_info(aot)("ArchiveRelocationMode: %d", ArchiveRelocationMode);
1533
1534 // First try to map at the requested address
1535 result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1536 if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1537 // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1538 // by the OS.
1539 aot_log_info(aot)("Try to map archive(s) at an alternative address");
1540 result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1541 }
1542 }
1543
1544 if (result == MAP_ARCHIVE_SUCCESS) {
1545 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1546 char* cds_base = static_mapinfo->mapped_base();
1547 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
1548 // Register CDS memory region with LSan.
1549 LSAN_REGISTER_ROOT_REGION(cds_base, cds_end - cds_base);
1550 set_aot_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
1551 _relocation_delta = static_mapinfo->relocation_delta();
1552 _requested_base_address = static_mapinfo->requested_base_address();
1553 if (dynamic_mapped) {
1554 // turn AutoCreateSharedArchive off if successfully mapped
1555 AutoCreateSharedArchive = false;
1556 }
1557 } else {
1558 set_aot_metaspace_range(nullptr, nullptr, nullptr);
1559 if (CDSConfig::is_dumping_dynamic_archive()) {
1560 aot_log_warning(aot)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1561 }
1562 UseSharedSpaces = false;
1563 // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1564 AutoCreateSharedArchive = false;
1565 CDSConfig::disable_dumping_dynamic_archive();
1566 if (PrintSharedArchiveAndExit) {
1567 AOTMetaspace::unrecoverable_loading_error("Unable to use shared archive.");
1568 } else {
1569 if (RequireSharedSpaces) {
1570 AOTMetaspace::unrecoverable_loading_error("Unable to map shared spaces");
1571 } else {
1572 report_loading_error("Unable to map shared spaces");
1573 }
1574 }
1575 }
1576
1577 // If mapping failed and -XShare:on, the vm should exit
1578 bool has_failed = false;
1579 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1580 has_failed = true;
1581 delete static_mapinfo;
1582 }
1583 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1584 has_failed = true;
1585 delete dynamic_mapinfo;
1586 }
1587 if (RequireSharedSpaces && has_failed) {
1588 // static archive mapped but dynamic archive failed
1589 AOTMetaspace::unrecoverable_loading_error("Unable to map shared spaces");
1590 }
1591 }
1592
1593 // This is called very early at VM start up to get the size of the cached_code region
1594 void AOTMetaspace::open_static_archive() {
1595 if (!UseSharedSpaces) { // FIXME -- is this still needed??
1596 return;
1597 }
1598 const char* static_archive = CDSConfig::input_static_archive_path();
1599 assert(static_archive != nullptr, "sanity");
1600 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1601 if (!mapinfo->open_as_input()) {
1602 delete(mapinfo);
1603 log_info(cds)("Opening of static archive %s failed", static_archive);
1604 } else {
1605 FileMapRegion* r = mapinfo->region_at(AOTMetaspace::ac);
1606 AOTCacheAccess::set_aot_code_region_size(r->used_aligned());
1607 }
1608 }
1609
1610 FileMapInfo* AOTMetaspace::open_dynamic_archive() {
1611 if (CDSConfig::is_dumping_dynamic_archive()) {
1612 return nullptr;
1613 }
1614 const char* dynamic_archive = CDSConfig::input_dynamic_archive_path();
1615 if (dynamic_archive == nullptr) {
1616 return nullptr;
1617 }
1618
1619 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1620 if (!mapinfo->open_as_input()) {
1621 delete(mapinfo);
1622 if (RequireSharedSpaces) {
1623 AOTMetaspace::unrecoverable_loading_error("Failed to initialize dynamic archive");
1624 }
1625 return nullptr;
1626 }
1627 return mapinfo;
1628 }
1629
1630 // use_requested_addr:
1631 // true = map at FileMapHeader::_requested_base_address
1632 // false = map at an alternative address picked by OS.
1633 MapArchiveResult AOTMetaspace::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
1634 bool use_requested_addr) {
1635 if (use_requested_addr && static_mapinfo->requested_base_address() == nullptr) {
1636 aot_log_info(aot)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
1637 return MAP_ARCHIVE_MMAP_FAILURE;
1638 }
1639
1640 PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1641 // For product build only -- this is for benchmarking the cost of doing relocation.
1642 // For debug builds, the check is done below, after reserving the space, for better test coverage
1643 // (see comment below).
1644 aot_log_info(aot)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1645 return MAP_ARCHIVE_MMAP_FAILURE;
1646 });
1647
1648 if (ArchiveRelocationMode == 2 && !use_requested_addr) {
1649 aot_log_info(aot)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
1650 return MAP_ARCHIVE_MMAP_FAILURE;
1651 };
1652
1653 if (dynamic_mapinfo != nullptr) {
1654 // Ensure that the OS won't be able to allocate new memory spaces between the two
1655 // archives, or else it would mess up the simple comparison in MetaspaceObj::in_aot_cache().
1656 assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
1657 }
1658
1659 ReservedSpace total_space_rs, archive_space_rs, class_space_rs;
1660 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1661 size_t prot_zone_size = 0;
1662 char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo,
1663 dynamic_mapinfo,
1664 use_requested_addr,
1665 total_space_rs,
1666 archive_space_rs,
1667 class_space_rs);
1668 if (mapped_base_address == nullptr) {
1669 result = MAP_ARCHIVE_MMAP_FAILURE;
1670 aot_log_debug(aot)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
1671 } else {
1672
1673 if (Metaspace::using_class_space()) {
1674 prot_zone_size = protection_zone_size();
1675 }
1676
1677 #ifdef ASSERT
1678 // Some sanity checks after reserving address spaces for archives
1679 // and class space.
1680 assert(archive_space_rs.is_reserved(), "Sanity");
1681 if (Metaspace::using_class_space()) {
1682 assert(archive_space_rs.base() == mapped_base_address &&
1683 archive_space_rs.size() > protection_zone_size(),
1684 "Archive space must lead and include the protection zone");
1685 // Class space must closely follow the archive space. Both spaces
1686 // must be aligned correctly.
1687 assert(class_space_rs.is_reserved() && class_space_rs.size() > 0,
1688 "A class space should have been reserved");
1689 assert(class_space_rs.base() >= archive_space_rs.end(),
1690 "class space should follow the cds archive space");
1691 assert(is_aligned(archive_space_rs.base(),
1692 core_region_alignment()),
1693 "Archive space misaligned");
1694 assert(is_aligned(class_space_rs.base(),
1695 Metaspace::reserve_alignment()),
1696 "class space misaligned");
1697 }
1698 #endif // ASSERT
1699
1700 aot_log_info(aot)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (%zu) bytes%s",
1701 p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size(),
1702 (prot_zone_size > 0 ? " (includes protection zone)" : ""));
1703 aot_log_info(aot)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (%zu) bytes",
1704 p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
1705
1706 if (AOTMetaspace::use_windows_memory_mapping()) {
1707 // We have now reserved address space for the archives, and will map in
1708 // the archive files into this space.
1709 //
1710 // Special handling for Windows: on Windows we cannot map a file view
1711 // into an existing memory mapping. So, we unmap the address range we
1712 // just reserved again, which will make it available for mapping the
1713 // archives.
1714 // Reserving this range has not been for naught however since it makes
1715 // us reasonably sure the address range is available.
1716 //
1717 // But still it may fail, since between unmapping the range and mapping
1718 // in the archive someone else may grab the address space. Therefore
1719 // there is a fallback in FileMap::map_region() where we just read in
1720 // the archive files sequentially instead of mapping it in. We couple
1721 // this with use_requested_addr, since we're going to patch all the
1722 // pointers anyway so there's no benefit to mmap.
1723 if (use_requested_addr) {
1724 assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows");
1725 aot_log_info(aot)("Windows mmap workaround: releasing archive space.");
1726 MemoryReserver::release(archive_space_rs);
1727 // Mark as not reserved
1728 archive_space_rs = {};
1729 // The protection zone is part of the archive:
1730 // See comment above, the Windows way of loading CDS is to mmap the individual
1731 // parts of the archive into the address region we just vacated. The protection
1732 // zone will not be mapped (and, in fact, does not exist as physical region in
1733 // the archive). Therefore, after removing the archive space above, we must
1734 // re-reserve the protection zone part lest something else gets mapped into that
1735 // area later.
1736 if (prot_zone_size > 0) {
1737 assert(prot_zone_size >= os::vm_allocation_granularity(), "must be"); // not just page size!
1738 char* p = os::attempt_reserve_memory_at(mapped_base_address, prot_zone_size,
1739 mtClassShared);
1740 assert(p == mapped_base_address || p == nullptr, "must be");
1741 if (p == nullptr) {
1742 aot_log_debug(aot)("Failed to re-reserve protection zone");
1743 return MAP_ARCHIVE_MMAP_FAILURE;
1744 }
1745 }
1746 }
1747 }
1748
1749 if (prot_zone_size > 0) {
1750 os::commit_memory(mapped_base_address, prot_zone_size, false); // will later be protected
1751 // Before mapping the core regions into the newly established address space, we mark
1752 // start and the end of the future protection zone with canaries. That way we easily
1753 // catch mapping errors (accidentally mapping data into the future protection zone).
1754 *(mapped_base_address) = 'P';
1755 *(mapped_base_address + prot_zone_size - 1) = 'P';
1756 }
1757
1758 MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
1759 MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
1760 map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
1761
1762 DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1763 // This is for simulating mmap failures at the requested address. In
1764 // debug builds, we do it here (after all archives have possibly been
1765 // mapped), so we can thoroughly test the code for failure handling
1766 // (releasing all allocated resource, etc).
1767 aot_log_info(aot)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1768 if (static_result == MAP_ARCHIVE_SUCCESS) {
1769 static_result = MAP_ARCHIVE_MMAP_FAILURE;
1770 }
1771 if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1772 dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
1773 }
1774 });
1775
1776 if (static_result == MAP_ARCHIVE_SUCCESS) {
1777 if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1778 result = MAP_ARCHIVE_SUCCESS;
1779 } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
1780 assert(dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped(), "must have failed");
1781 // No need to retry mapping the dynamic archive again, as it will never succeed
1782 // (bad file, etc) -- just keep the base archive.
1783 log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
1784 dynamic_mapinfo->full_path());
1785 result = MAP_ARCHIVE_SUCCESS;
1786 // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
1787 // easy API to do that right now.
1788 } else {
1789 result = MAP_ARCHIVE_MMAP_FAILURE;
1790 }
1791 } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
1792 result = MAP_ARCHIVE_OTHER_FAILURE;
1793 } else {
1794 result = MAP_ARCHIVE_MMAP_FAILURE;
1795 }
1796 }
1797
1798 if (result == MAP_ARCHIVE_SUCCESS) {
1799 SharedBaseAddress = (size_t)mapped_base_address;
1800 #ifdef _LP64
1801 if (Metaspace::using_class_space()) {
1802 assert(prot_zone_size > 0 &&
1803 *(mapped_base_address) == 'P' &&
1804 *(mapped_base_address + prot_zone_size - 1) == 'P',
1805 "Protection zone was overwritten?");
1806 // Set up ccs in metaspace.
1807 Metaspace::initialize_class_space(class_space_rs);
1808
1809 // Set up compressed Klass pointer encoding: the encoding range must
1810 // cover both archive and class space.
1811 const address klass_range_start = (address)mapped_base_address;
1812 const size_t klass_range_size = (address)class_space_rs.end() - klass_range_start;
1813 if (INCLUDE_CDS_JAVA_HEAP || UseCompactObjectHeaders) {
1814 // The CDS archive may contain narrow Klass IDs that were precomputed at archive generation time:
1815 // - every archived java object header (only if INCLUDE_CDS_JAVA_HEAP)
1816 // - every archived Klass' prototype (only if +UseCompactObjectHeaders)
1817 //
1818 // In order for those IDs to still be valid, we need to dictate base and shift: base should be the
1819 // mapping start (including protection zone), shift should be the shift used at archive generation time.
1820 CompressedKlassPointers::initialize_for_given_encoding(
1821 klass_range_start, klass_range_size,
1822 klass_range_start, ArchiveBuilder::precomputed_narrow_klass_shift() // precomputed encoding, see ArchiveBuilder
1823 );
1824 assert(CompressedKlassPointers::base() == klass_range_start, "must be");
1825 } else {
1826 // Let JVM freely choose encoding base and shift
1827 CompressedKlassPointers::initialize(klass_range_start, klass_range_size);
1828 assert(CompressedKlassPointers::base() == nullptr ||
1829 CompressedKlassPointers::base() == klass_range_start, "must be");
1830 }
1831 // Establish protection zone, but only if we need one
1832 if (CompressedKlassPointers::base() == klass_range_start) {
1833 CompressedKlassPointers::establish_protection_zone(klass_range_start, prot_zone_size);
1834 }
1835
1836 if (static_mapinfo->can_use_heap_region()) {
1837 if (static_mapinfo->object_streaming_mode()) {
1838 HeapShared::initialize_loading_mode(HeapArchiveMode::_streaming);
1839 } else {
1840 // map_or_load_heap_region() compares the current narrow oop and klass encodings
1841 // with the archived ones, so it must be done after all encodings are determined.
1842 static_mapinfo->map_or_load_heap_region();
1843 HeapShared::initialize_loading_mode(HeapArchiveMode::_mapping);
1844 }
1845 } else {
1846 FileMapRegion* r = static_mapinfo->region_at(AOTMetaspace::hp);
1847 if (r->used() > 0) {
1848 if (static_mapinfo->object_streaming_mode()) {
1849 AOTMetaspace::report_loading_error("Cannot use CDS heap data.");
1850 } else {
1851 if (!UseCompressedOops && !AOTMappedHeapLoader::can_map()) {
1852 AOTMetaspace::report_loading_error("Cannot use CDS heap data. Selected GC not compatible -XX:-UseCompressedOops");
1853 } else {
1854 AOTMetaspace::report_loading_error("Cannot use CDS heap data. UseEpsilonGC, UseG1GC, UseSerialGC, UseParallelGC, or UseShenandoahGC are required.");
1855 }
1856 }
1857 }
1858 }
1859 }
1860 #endif // _LP64
1861 log_info(aot)("initial optimized module handling: %s", CDSConfig::is_using_optimized_module_handling() ? "enabled" : "disabled");
1862 log_info(aot)("initial full module graph: %s", CDSConfig::is_using_full_module_graph() ? "enabled" : "disabled");
1863 } else {
1864 unmap_archive(static_mapinfo);
1865 unmap_archive(dynamic_mapinfo);
1866 release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1867 }
1868
1869 return result;
1870 }
1871
1872
1873 // This will reserve two address spaces suitable to house Klass structures, one
1874 // for the cds archives (static archive and optionally dynamic archive) and
1875 // optionally one move for ccs.
1876 //
1877 // Since both spaces must fall within the compressed class pointer encoding
1878 // range, they are allocated close to each other.
1879 //
1880 // Space for archives will be reserved first, followed by a potential gap,
1881 // followed by the space for ccs:
1882 //
1883 // +-- Base address A B End
1884 // | | | |
1885 // v v v v
1886 // +-------------+--------------+ +----------------------+
1887 // | static arc | [dyn. arch] | [gap] | compr. class space |
1888 // +-------------+--------------+ +----------------------+
1889 //
1890 // (The gap may result from different alignment requirements between metaspace
1891 // and CDS)
1892 //
1893 // If UseCompressedClassPointers is disabled, only one address space will be
1894 // reserved:
1895 //
1896 // +-- Base address End
1897 // | |
1898 // v v
1899 // +-------------+--------------+
1900 // | static arc | [dyn. arch] |
1901 // +-------------+--------------+
1902 //
1903 // Base address: If use_archive_base_addr address is true, the Base address is
1904 // determined by the address stored in the static archive. If
1905 // use_archive_base_addr address is false, this base address is determined
1906 // by the platform.
1907 //
1908 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
1909 // suitable to en/decode narrow Klass pointers: the base will be valid for
1910 // encoding, the range [Base, End) and not surpass the max. range for that encoding.
1911 //
1912 // Return:
1913 //
1914 // - On success:
1915 // - total_space_rs will be reserved as whole for archive_space_rs and
1916 // class_space_rs if UseCompressedClassPointers is true.
1917 // On Windows, try reserve archive_space_rs and class_space_rs
1918 // separately first if use_archive_base_addr is true.
1919 // - archive_space_rs will be reserved and large enough to host static and
1920 // if needed dynamic archive: [Base, A).
1921 // archive_space_rs.base and size will be aligned to CDS reserve
1922 // granularity.
1923 // - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
1924 // be reserved. Its start address will be aligned to metaspace reserve
1925 // alignment, which may differ from CDS alignment. It will follow the cds
1926 // archive space, close enough such that narrow class pointer encoding
1927 // covers both spaces.
1928 // If UseCompressedClassPointers=0, class_space_rs remains unreserved.
1929 // - On error: null is returned and the spaces remain unreserved.
1930 char* AOTMetaspace::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
1931 FileMapInfo* dynamic_mapinfo,
1932 bool use_archive_base_addr,
1933 ReservedSpace& total_space_rs,
1934 ReservedSpace& archive_space_rs,
1935 ReservedSpace& class_space_rs) {
1936
1937 address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : nullptr);
1938 const size_t archive_space_alignment = core_region_alignment();
1939
1940 // Size and requested location of the archive_space_rs (for both static and dynamic archives)
1941 size_t archive_end_offset = (dynamic_mapinfo == nullptr) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
1942 size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
1943
1944 if (!Metaspace::using_class_space()) {
1945 // Get the simple case out of the way first:
1946 // no compressed class space, simple allocation.
1947
1948 // When running without class space, requested archive base should be aligned to cds core alignment.
1949 assert(is_aligned(base_address, archive_space_alignment),
1950 "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.",
1951 p2i(base_address), archive_space_alignment);
1952
1953 archive_space_rs = MemoryReserver::reserve((char*)base_address,
1954 archive_space_size,
1955 archive_space_alignment,
1956 os::vm_page_size(),
1957 mtNone);
1958 if (archive_space_rs.is_reserved()) {
1959 assert(base_address == nullptr ||
1960 (address)archive_space_rs.base() == base_address, "Sanity");
1961 // Register archive space with NMT.
1962 MemTracker::record_virtual_memory_tag(archive_space_rs, mtClassShared);
1963 return archive_space_rs.base();
1964 }
1965 return nullptr;
1966 }
1967
1968 #ifdef _LP64
1969
1970 // Complex case: two spaces adjacent to each other, both to be addressable
1971 // with narrow class pointers.
1972 // We reserve the whole range spanning both spaces, then split that range up.
1973
1974 const size_t class_space_alignment = Metaspace::reserve_alignment();
1975
1976 // When running with class space, requested archive base must satisfy both cds core alignment
1977 // and class space alignment.
1978 const size_t base_address_alignment = MAX2(class_space_alignment, archive_space_alignment);
1979 assert(is_aligned(base_address, base_address_alignment),
1980 "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.",
1981 p2i(base_address), base_address_alignment);
1982
1983 size_t class_space_size = CompressedClassSpaceSize;
1984 assert(CompressedClassSpaceSize > 0 &&
1985 is_aligned(CompressedClassSpaceSize, class_space_alignment),
1986 "CompressedClassSpaceSize malformed: %zu", CompressedClassSpaceSize);
1987
1988 const size_t ccs_begin_offset = align_up(archive_space_size, class_space_alignment);
1989 const size_t gap_size = ccs_begin_offset - archive_space_size;
1990
1991 // Reduce class space size if it would not fit into the Klass encoding range
1992 constexpr size_t max_encoding_range_size = 4 * G;
1993 guarantee(archive_space_size < max_encoding_range_size - class_space_alignment, "Archive too large");
1994 if ((archive_space_size + gap_size + class_space_size) > max_encoding_range_size) {
1995 class_space_size = align_down(max_encoding_range_size - archive_space_size - gap_size, class_space_alignment);
1996 log_info(metaspace)("CDS initialization: reducing class space size from %zu to %zu",
1997 CompressedClassSpaceSize, class_space_size);
1998 FLAG_SET_ERGO(CompressedClassSpaceSize, class_space_size);
1999 }
2000
2001 const size_t total_range_size =
2002 archive_space_size + gap_size + class_space_size;
2003
2004 // Test that class space base address plus shift can be decoded by aarch64, when restored.
2005 const int precomputed_narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift();
2006 if (!CompressedKlassPointers::check_klass_decode_mode(base_address, precomputed_narrow_klass_shift,
2007 total_range_size)) {
2008 aot_log_info(aot)("CDS initialization: Cannot use SharedBaseAddress " PTR_FORMAT " with precomputed shift %d.",
2009 p2i(base_address), precomputed_narrow_klass_shift);
2010 use_archive_base_addr = false;
2011 }
2012
2013 assert(total_range_size > ccs_begin_offset, "must be");
2014 if (use_windows_memory_mapping() && use_archive_base_addr) {
2015 if (base_address != nullptr) {
2016 // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).
2017 // Hence, we optimistically reserve archive space and class space side-by-side. We only
2018 // do this for use_archive_base_addr=true since for use_archive_base_addr=false case
2019 // caller will not split the combined space for mapping, instead read the archive data
2020 // via sequential file IO.
2021 address ccs_base = base_address + archive_space_size + gap_size;
2022 archive_space_rs = MemoryReserver::reserve((char*)base_address,
2023 archive_space_size,
2024 archive_space_alignment,
2025 os::vm_page_size(),
2026 mtNone);
2027 class_space_rs = MemoryReserver::reserve((char*)ccs_base,
2028 class_space_size,
2029 class_space_alignment,
2030 os::vm_page_size(),
2031 mtNone);
2032 }
2033 if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {
2034 release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
2035 return nullptr;
2036 }
2037 MemTracker::record_virtual_memory_tag(archive_space_rs, mtClassShared);
2038 MemTracker::record_virtual_memory_tag(class_space_rs, mtClass);
2039 } else {
2040 if (use_archive_base_addr && base_address != nullptr) {
2041 total_space_rs = MemoryReserver::reserve((char*) base_address,
2042 total_range_size,
2043 base_address_alignment,
2044 os::vm_page_size(),
2045 mtNone);
2046 } else {
2047 // We did not manage to reserve at the preferred address, or were instructed to relocate. In that
2048 // case we reserve wherever possible, but the start address needs to be encodable as narrow Klass
2049 // encoding base since the archived heap objects contain narrow Klass IDs pre-calculated toward the start
2050 // of the shared Metaspace. That prevents us from using zero-based encoding and therefore we won't
2051 // try allocating in low-address regions.
2052 total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size, false /* optimize_for_zero_base */);
2053 }
2054
2055 if (!total_space_rs.is_reserved()) {
2056 return nullptr;
2057 }
2058
2059 // Paranoid checks:
2060 assert(!use_archive_base_addr || (address)total_space_rs.base() == base_address,
2061 "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));
2062 assert(is_aligned(total_space_rs.base(), base_address_alignment), "Sanity");
2063 assert(total_space_rs.size() == total_range_size, "Sanity");
2064
2065 // Now split up the space into ccs and cds archive. For simplicity, just leave
2066 // the gap reserved at the end of the archive space. Do not do real splitting.
2067 archive_space_rs = total_space_rs.first_part(ccs_begin_offset,
2068 (size_t)archive_space_alignment);
2069 class_space_rs = total_space_rs.last_part(ccs_begin_offset);
2070 MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),
2071 ccs_begin_offset, mtClassShared, mtClass);
2072 }
2073 assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
2074 assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
2075 assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
2076 assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
2077
2078
2079 return archive_space_rs.base();
2080
2081 #else
2082 ShouldNotReachHere();
2083 return nullptr;
2084 #endif
2085
2086 }
2087
2088 void AOTMetaspace::release_reserved_spaces(ReservedSpace& total_space_rs,
2089 ReservedSpace& archive_space_rs,
2090 ReservedSpace& class_space_rs) {
2091 if (total_space_rs.is_reserved()) {
2092 aot_log_debug(aot)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));
2093 MemoryReserver::release(total_space_rs);
2094 total_space_rs = {};
2095 } else {
2096 if (archive_space_rs.is_reserved()) {
2097 aot_log_debug(aot)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
2098 MemoryReserver::release(archive_space_rs);
2099 archive_space_rs = {};
2100 }
2101 if (class_space_rs.is_reserved()) {
2102 aot_log_debug(aot)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
2103 MemoryReserver::release(class_space_rs);
2104 class_space_rs = {};
2105 }
2106 }
2107 }
2108
2109 static int archive_regions[] = { AOTMetaspace::rw, AOTMetaspace::ro };
2110 static int archive_regions_count = 2;
2111
2112 MapArchiveResult AOTMetaspace::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
2113 assert(CDSConfig::is_using_archive(), "must be runtime");
2114 if (mapinfo == nullptr) {
2115 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
2116 }
2117
2118 if (!mapinfo->validate_aot_class_linking()) {
2119 return MAP_ARCHIVE_OTHER_FAILURE;
2120 }
2121
2122 mapinfo->set_is_mapped(false);
2123 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
2124 report_loading_error("Unable to map CDS archive -- core_region_alignment() expected: %zu"
2125 " actual: %zu", mapinfo->core_region_alignment(), core_region_alignment());
2126 return MAP_ARCHIVE_OTHER_FAILURE;
2127 }
2128
2129 MapArchiveResult result =
2130 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
2131
2132 if (result != MAP_ARCHIVE_SUCCESS) {
2133 unmap_archive(mapinfo);
2134 return result;
2135 }
2136
2137 if (!mapinfo->validate_class_location()) {
2138 unmap_archive(mapinfo);
2139 return MAP_ARCHIVE_OTHER_FAILURE;
2140 }
2141
2142 if (mapinfo->is_static()) {
2143 // Currently, only static archive uses early serialized data.
2144 char* buffer = mapinfo->early_serialized_data();
2145 intptr_t* array = (intptr_t*)buffer;
2146 ReadClosure rc(&array, (intptr_t)mapped_base_address);
2147 early_serialize(&rc);
2148 }
2149
2150 if (!mapinfo->validate_aot_class_linking()) {
2151 unmap_archive(mapinfo);
2152 return MAP_ARCHIVE_OTHER_FAILURE;
2153 }
2154
2155 mapinfo->set_is_mapped(true);
2156 return MAP_ARCHIVE_SUCCESS;
2157 }
2158
2159 void AOTMetaspace::unmap_archive(FileMapInfo* mapinfo) {
2160 assert(CDSConfig::is_using_archive(), "must be runtime");
2161 if (mapinfo != nullptr) {
2162 mapinfo->unmap_regions(archive_regions, archive_regions_count);
2163 mapinfo->unmap_region(AOTMetaspace::bm);
2164 mapinfo->set_is_mapped(false);
2165 }
2166 }
2167
2168 // For -XX:PrintSharedArchiveAndExit
2169 class CountSharedSymbols : public SymbolClosure {
2170 private:
2171 size_t _count;
2172 public:
2173 CountSharedSymbols() : _count(0) {}
2174 void do_symbol(Symbol** sym) {
2175 _count++;
2176 }
2177 size_t total() { return _count; }
2178
2179 };
2180
2181 // Read the miscellaneous data from the shared file, and
2182 // serialize it out to its various destinations.
2183
2184 void AOTMetaspace::initialize_shared_spaces() {
2185 FileMapInfo *static_mapinfo = FileMapInfo::current_info();
2186 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
2187
2188 // Verify various attributes of the archive, plus initialize the
2189 // shared string/symbol tables.
2190 char* buffer = static_mapinfo->serialized_data();
2191 intptr_t* array = (intptr_t*)buffer;
2192 ReadClosure rc(&array, (intptr_t)SharedBaseAddress);
2193 serialize(&rc);
2194
2195 // Finish initializing the heap dump mode used in the archive
2196 // Heap initialization can be done only after vtables are initialized by ReadClosure.
2197 HeapShared::finalize_initialization(static_mapinfo);
2198 Universe::load_archived_object_instances();
2199
2200 AOTCodeCache::initialize();
2201
2202 if (dynamic_mapinfo != nullptr) {
2203 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
2204 ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress);
2205 DynamicArchive::serialize(&rc);
2206 DynamicArchive::setup_array_klasses();
2207 }
2208
2209 LogStreamHandle(Info, aot) lsh;
2210 if (lsh.is_enabled()) {
2211 lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes",
2212 BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()),
2213 static_mapinfo->header()->has_aot_linked_classes() ? "has" : "no");
2214 if (dynamic_mapinfo != nullptr) {
2215 lsh.print(", dynamic archive: %s aot-linked classes",
2216 dynamic_mapinfo->header()->has_aot_linked_classes() ? "has" : "no");
2217 }
2218 lsh.print_cr(")");
2219 }
2220
2221 // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
2222 if (CDSConfig::is_dumping_dynamic_archive()) {
2223 // Read stored LF format lines stored in static archive
2224 LambdaFormInvokers::read_static_archive_invokers();
2225 }
2226
2227 if (PrintSharedArchiveAndExit) {
2228 // Print archive names
2229 if (dynamic_mapinfo != nullptr) {
2230 tty->print_cr("\n\nBase archive name: %s", CDSConfig::input_static_archive_path());
2231 tty->print_cr("Base archive version %d", static_mapinfo->version());
2232 } else {
2233 tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
2234 tty->print_cr("Static archive version %d", static_mapinfo->version());
2235 }
2236
2237 SystemDictionaryShared::print_shared_archive(tty);
2238 if (dynamic_mapinfo != nullptr) {
2239 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
2240 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
2241 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
2242 }
2243
2244 TrainingData::print_archived_training_data_on(tty);
2245
2246 AOTCodeCache::print_on(tty);
2247
2248 // collect shared symbols and strings
2249 CountSharedSymbols cl;
2250 SymbolTable::shared_symbols_do(&cl);
2251 tty->print_cr("Number of shared symbols: %zu", cl.total());
2252 if (HeapShared::is_loading_mapping_mode()) {
2253 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
2254 }
2255 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
2256 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
2257 tty->print_cr("archive is invalid");
2258 vm_exit(1);
2259 } else {
2260 tty->print_cr("archive is valid");
2261 vm_exit(0);
2262 }
2263 }
2264 }
2265
2266 // JVM/TI RedefineClasses() support:
2267 bool AOTMetaspace::remap_shared_readonly_as_readwrite() {
2268 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2269
2270 if (CDSConfig::is_using_archive()) {
2271 // remap the shared readonly space to shared readwrite, private
2272 FileMapInfo* mapinfo = FileMapInfo::current_info();
2273 if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2274 return false;
2275 }
2276 if (FileMapInfo::dynamic_info() != nullptr) {
2277 mapinfo = FileMapInfo::dynamic_info();
2278 if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2279 return false;
2280 }
2281 }
2282 _remapped_readwrite = true;
2283 }
2284 return true;
2285 }
2286
2287 void AOTMetaspace::print_on(outputStream* st) {
2288 if (CDSConfig::is_using_archive()) {
2289 st->print("CDS archive(s) mapped at: ");
2290 address base = (address)MetaspaceObj::aot_metaspace_base();
2291 address static_top = (address)_aot_metaspace_static_top;
2292 address top = (address)MetaspaceObj::aot_metaspace_top();
2293 st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
2294 st->print("size %zu, ", top - base);
2295 st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, ArchiveRelocationMode);
2296 } else {
2297 st->print("CDS archive(s) not mapped");
2298 }
2299 st->cr();
2300 }