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