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