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