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