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