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