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