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