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