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