1 /*
2 * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25
26 #include "asm/macroAssembler.hpp"
27 #include "cds/aotCacheAccess.hpp"
28 #include "cds/aotMetaspace.hpp"
29 #include "cds/cds_globals.hpp"
30 #include "cds/cdsConfig.hpp"
31 #include "cds/heapShared.hpp"
32 #include "ci/ciUtilities.hpp"
33 #include "classfile/javaAssertions.hpp"
34 #include "code/aotCodeCache.hpp"
35 #include "code/codeCache.hpp"
36 #include "gc/shared/barrierSetAssembler.hpp"
37 #include "gc/shared/barrierSetNMethod.hpp"
38 #include "gc/shared/cardTableBarrierSet.hpp"
39 #include "gc/shared/gcConfig.hpp"
40 #include "logging/logStream.hpp"
41 #include "memory/memoryReserver.hpp"
42 #include "prims/jvmtiThreadState.hpp"
43 #include "prims/upcallLinker.hpp"
44 #include "runtime/deoptimization.hpp"
45 #include "runtime/flags/flagSetting.hpp"
46 #include "runtime/globals_extension.hpp"
47 #include "runtime/icache.hpp"
48 #include "runtime/java.hpp"
49 #include "runtime/mutexLocker.hpp"
50 #include "runtime/os.inline.hpp"
51 #include "runtime/sharedRuntime.hpp"
52 #include "runtime/stubInfo.hpp"
53 #include "runtime/stubRoutines.hpp"
54 #include "utilities/copy.hpp"
55 #ifdef COMPILER1
56 #include "c1/c1_Runtime1.hpp"
57 #endif
58 #ifdef COMPILER2
59 #include "opto/runtime.hpp"
60 #endif
61 #if INCLUDE_G1GC
62 #include "gc/g1/g1BarrierSetRuntime.hpp"
63 #include "gc/g1/g1HeapRegion.hpp"
64 #endif
65 #if INCLUDE_SHENANDOAHGC
66 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
67 #include "gc/shenandoah/shenandoahRuntime.hpp"
68 #endif
69 #if INCLUDE_ZGC
70 #include "gc/z/zBarrierSetRuntime.hpp"
71 #endif
72
73 #include <errno.h>
74 #include <sys/stat.h>
75
76 const char* aot_code_entry_kind_name[] = {
77 #define DECL_KIND_STRING(kind) XSTR(kind),
78 DO_AOTCODEENTRY_KIND(DECL_KIND_STRING)
79 #undef DECL_KIND_STRING
80 };
81
82 // Stream to printing AOTCodeCache loading failure.
83 // Print to error channel when -XX:AOTMode is set to "on"
84 static LogStream& load_failure_log() {
85 static LogStream err_stream(LogLevel::Error, LogTagSetMapping<LOG_TAGS(aot, codecache, init)>::tagset());
86 static LogStream dbg_stream(LogLevel::Debug, LogTagSetMapping<LOG_TAGS(aot, codecache, init)>::tagset());
87 if (RequireSharedSpaces || AbortVMOnAOTCodeFailure) {
88 return err_stream;
89 } else {
90 return dbg_stream;
91 }
92 }
93
94 // Report AOT code cache failure and exit VM
95 // if (AOTMode is `on` and AbortVMOnAOTCodeFailure is default)
96 // or AbortVMOnAOTCodeFailure is `true`.
97 //
98 // Note, specifying -XX:-AbortVMOnAOTCodeFailure on command line
99 // will prevent aborting VM when AOTMode is `on`. It is used for testing.
100
101 static void report_load_failure() {
102 bool abort_vm = AbortVMOnAOTCodeFailure ||
103 (FLAG_IS_DEFAULT(AbortVMOnAOTCodeFailure) && RequireSharedSpaces);
104 if (abort_vm) {
105 vm_exit_during_initialization("Unable to use AOT Code Cache.", nullptr);
106 }
107 load_failure_log().print_cr("Unable to use AOT Code Cache.");
108 AOTCodeCache::disable_caching();
109 }
110
111 static void report_store_failure() {
112 if (AbortVMOnAOTCodeFailure) {
113 tty->print_cr("Unable to create AOT Code Cache.");
114 vm_abort(false);
115 }
116 log_error(aot, codecache, exit)("Unable to create AOT Code Cache.");
117 AOTCodeCache::disable_caching();
118 }
119
120 // The sequence of AOT code caching flags and parametters settings.
121 //
122 // 1. The initial AOT code caching flags setting is done
123 // during call to CDSConfig::check_vm_args_consistency().
124 //
125 // 2. The earliest AOT code state check done in compilationPolicy_init()
126 // where we set number of compiler threads for AOT assembly phase.
127 //
128 // 3. We determine presence of AOT code in AOT Cache in
129 // AOTMetaspace::open_static_archive() which is calles
130 // after compilationPolicy_init() but before codeCache_init().
131 //
132 // 4. AOTCodeCache::initialize() is called during universe_init()
133 // and does final AOT state and flags settings.
134 //
135 // 5. Finally AOTCodeCache::init2() is called after universe_init()
136 // when all GC settings are finalized.
137
138 // Next methods determine which action we do with AOT code depending
139 // on phase of AOT process: assembly or production.
140
141 bool AOTCodeCache::is_dumping_adapter() {
142 return AOTAdapterCaching && is_on_for_dump();
143 }
144
145 bool AOTCodeCache::is_using_adapter() {
146 return AOTAdapterCaching && is_on_for_use();
147 }
148
149 bool AOTCodeCache::is_dumping_stub() {
150 return AOTStubCaching && is_on_for_dump();
151 }
152
153 bool AOTCodeCache::is_using_stub() {
154 return AOTStubCaching && is_on_for_use();
155 }
156
157 // Next methods could be called regardless AOT code cache status.
158 // Initially they are called during flags parsing and finilized
159 // in AOTCodeCache::initialize().
160 void AOTCodeCache::enable_caching() {
161 FLAG_SET_ERGO_IF_DEFAULT(AOTStubCaching, true);
162 FLAG_SET_ERGO_IF_DEFAULT(AOTAdapterCaching, true);
163 }
164
165 void AOTCodeCache::disable_caching() {
166 FLAG_SET_ERGO(AOTStubCaching, false);
167 FLAG_SET_ERGO(AOTAdapterCaching, false);
168 }
169
170 bool AOTCodeCache::is_caching_enabled() {
171 return AOTStubCaching || AOTAdapterCaching;
172 }
173
174 static uint32_t encode_id(AOTCodeEntry::Kind kind, int id) {
175 assert(AOTCodeEntry::is_valid_entry_kind(kind), "invalid AOTCodeEntry kind %d", (int)kind);
176 // There can be a conflict of id between an Adapter and *Blob, but that should not cause any functional issue
177 // becasue both id and kind are used to find an entry, and that combination should be unique
178 if (kind == AOTCodeEntry::Adapter) {
179 return id;
180 } else if (kind == AOTCodeEntry::SharedBlob) {
181 assert(StubInfo::is_shared(static_cast<BlobId>(id)), "not a shared blob id %d", id);
182 return id;
183 } else if (kind == AOTCodeEntry::C1Blob) {
184 assert(StubInfo::is_c1(static_cast<BlobId>(id)), "not a c1 blob id %d", id);
185 return id;
186 } else if (kind == AOTCodeEntry::C2Blob) {
187 assert(StubInfo::is_c2(static_cast<BlobId>(id)), "not a c2 blob id %d", id);
188 return id;
189 } else {
190 // kind must be AOTCodeEntry::StubGenBlob
191 assert(StubInfo::is_stubgen(static_cast<BlobId>(id)), "not a stubgen blob id %d", id);
192 return id;
193 }
194 }
195
196 static uint _max_aot_code_size = 0;
197 uint AOTCodeCache::max_aot_code_size() {
198 return _max_aot_code_size;
199 }
200
201 // It is called from AOTMetaspace::initialize_shared_spaces()
202 // which is called from universe_init().
203 // At this point all AOT class linking seetings are finilized
204 // and AOT cache is open so we can map AOT code region.
205 void AOTCodeCache::initialize() {
206 #if defined(ZERO) || !(defined(AMD64) || defined(AARCH64))
207 log_info(aot, codecache, init)("AOT Code Cache is not supported on this platform.");
208 disable_caching();
209 return;
210 #else
211 if (FLAG_IS_DEFAULT(AOTCache)) {
212 log_info(aot, codecache, init)("AOT Code Cache is not used: AOTCache is not specified.");
213 disable_caching();
214 return; // AOTCache must be specified to dump and use AOT code
215 }
216
217 if (VerifyOops) {
218 // Disable AOT stubs caching when VerifyOops flag is on.
219 // Verify oops code generated a lot of C strings which overflow
220 // AOT C string table (which has fixed size).
221 // AOT C string table will be reworked later to handle such cases.
222 //
223 // Note: AOT adapters are not affected - they don't have oop operations.
224 log_info(aot, codecache, init)("AOT Stubs Caching is not supported with VerifyOops.");
225 FLAG_SET_ERGO(AOTStubCaching, false);
226 }
227
228 bool is_dumping = false;
229 bool is_using = false;
230 if (CDSConfig::is_dumping_final_static_archive() && CDSConfig::is_dumping_aot_linked_classes()) {
231 is_dumping = true;
232 enable_caching();
233 is_dumping = is_caching_enabled();
234 } else if (CDSConfig::is_using_archive() && CDSConfig::is_using_aot_linked_classes()) {
235 enable_caching();
236 is_using = is_caching_enabled();
237 } else {
238 log_info(aot, codecache, init)("AOT Code Cache is not used: AOT Class Linking is not used.");
239 disable_caching();
240 return; // nothing to do
241 }
242 if (!(is_dumping || is_using)) {
243 disable_caching();
244 return; // AOT code caching disabled on command line
245 }
246 _max_aot_code_size = AOTCodeMaxSize;
247 if (!FLAG_IS_DEFAULT(AOTCodeMaxSize)) {
248 if (!is_aligned(AOTCodeMaxSize, os::vm_allocation_granularity())) {
249 _max_aot_code_size = align_up(AOTCodeMaxSize, os::vm_allocation_granularity());
250 log_debug(aot,codecache,init)("Max AOT Code Cache size is aligned up to %uK", (int)(max_aot_code_size()/K));
251 }
252 }
253 size_t aot_code_size = is_using ? AOTCacheAccess::get_aot_code_region_size() : 0;
254 if (is_using && aot_code_size == 0) {
255 log_info(aot, codecache, init)("AOT Code Cache is empty");
256 disable_caching();
257 return;
258 }
259 if (!open_cache(is_dumping, is_using)) {
260 if (is_using) {
261 report_load_failure();
262 } else {
263 report_store_failure();
264 }
265 return;
266 }
267 if (is_dumping) {
268 FLAG_SET_DEFAULT(ForceUnreachable, true);
269 }
270 FLAG_SET_DEFAULT(DelayCompilerStubsGeneration, false);
271 #endif // defined(AMD64) || defined(AARCH64)
272 }
273
274 static AOTCodeCache* opened_cache = nullptr; // Use this until we verify the cache
275 AOTCodeCache* AOTCodeCache::_cache = nullptr;
276 DEBUG_ONLY( bool AOTCodeCache::_passed_init2 = false; )
277
278 // It is called after universe_init() when all GC settings are finalized.
279 void AOTCodeCache::init2() {
280 DEBUG_ONLY( _passed_init2 = true; )
281 if (opened_cache == nullptr) {
282 return;
283 }
284 if (!opened_cache->verify_config()) {
285 delete opened_cache;
286 opened_cache = nullptr;
287 report_load_failure();
288 return;
289 }
290
291 // initialize aot runtime constants as appropriate to this runtime
292 AOTRuntimeConstants::initialize_from_runtime();
293
294 // initialize the table of external routines so we can save
295 // generated code blobs that reference them
296 AOTCodeAddressTable* table = opened_cache->_table;
297 assert(table != nullptr, "should be initialized already");
298 table->init_extrs();
299
300 // Now cache and address table are ready for AOT code generation
301 _cache = opened_cache;
302 }
303
304 bool AOTCodeCache::open_cache(bool is_dumping, bool is_using) {
305 opened_cache = new AOTCodeCache(is_dumping, is_using);
306 if (opened_cache->failed()) {
307 delete opened_cache;
308 opened_cache = nullptr;
309 return false;
310 }
311 return true;
312 }
313
314 // Called after continuations_init() when continuation stub callouts
315 // have been initialized
316 void AOTCodeCache::init3() {
317 if (opened_cache == nullptr) {
318 return;
319 }
320 // initialize external routines for continuations so we can save
321 // generated continuation blob that references them
322 AOTCodeAddressTable* table = opened_cache->_table;
323 assert(table != nullptr, "should be initialized already");
324 table->init_extrs2();
325 }
326
327 void AOTCodeCache::dump() {
328 if (is_on()) {
329 assert(is_on_for_dump(), "should be called only when dumping AOT code");
330 MutexLocker ml(Compile_lock);
331 _cache->finish_write();
332 }
333 }
334
335 #define DATA_ALIGNMENT HeapWordSize
336
337 AOTCodeCache::AOTCodeCache(bool is_dumping, bool is_using) :
338 _load_header(nullptr),
339 _load_buffer(nullptr),
340 _store_buffer(nullptr),
341 _C_store_buffer(nullptr),
342 _write_position(0),
343 _load_size(0),
344 _store_size(0),
345 _for_use(is_using),
346 _for_dump(is_dumping),
347 _failed(false),
348 _lookup_failed(false),
349 _table(nullptr),
350 _load_entries(nullptr),
351 _search_entries(nullptr),
352 _store_entries(nullptr),
353 _C_strings_buf(nullptr),
354 _store_entries_cnt(0)
355 {
356 // Read header at the begining of cache
357 if (_for_use) {
358 // Read cache
359 size_t load_size = AOTCacheAccess::get_aot_code_region_size();
360 ReservedSpace rs = MemoryReserver::reserve(load_size, mtCode);
361 if (!rs.is_reserved()) {
362 log_warning(aot, codecache, init)("Failed to reserved %u bytes of memory for mapping AOT code region into AOT Code Cache", (uint)load_size);
363 set_failed();
364 return;
365 }
366 if (!AOTCacheAccess::map_aot_code_region(rs)) {
367 log_warning(aot, codecache, init)("Failed to read/mmap cached code region into AOT Code Cache");
368 set_failed();
369 return;
370 }
371
372 _load_size = (uint)load_size;
373 _load_buffer = (char*)rs.base();
374 assert(is_aligned(_load_buffer, DATA_ALIGNMENT), "load_buffer is not aligned");
375 log_debug(aot, codecache, init)("Mapped %u bytes at address " INTPTR_FORMAT " at AOT Code Cache", _load_size, p2i(_load_buffer));
376
377 _load_header = (Header*)addr(0);
378 if (!_load_header->verify(_load_size)) {
379 set_failed();
380 return;
381 }
382 log_info (aot, codecache, init)("Loaded %u AOT code entries from AOT Code Cache", _load_header->entries_count());
383 log_debug(aot, codecache, init)(" Adapters: total=%u", _load_header->adapters_count());
384 log_debug(aot, codecache, init)(" Shared Blobs: total=%u", _load_header->shared_blobs_count());
385 log_debug(aot, codecache, init)(" StubGen Blobs: total=%d", _load_header->stubgen_blobs_count());
386 log_debug(aot, codecache, init)(" C1 Blobs: total=%u", _load_header->C1_blobs_count());
387 log_debug(aot, codecache, init)(" C2 Blobs: total=%u", _load_header->C2_blobs_count());
388 log_debug(aot, codecache, init)(" AOT code cache size: %u bytes", _load_header->cache_size());
389
390 // Read strings
391 load_strings();
392 }
393 if (_for_dump) {
394 _C_store_buffer = NEW_C_HEAP_ARRAY(char, max_aot_code_size() + DATA_ALIGNMENT, mtCode);
395 _store_buffer = align_up(_C_store_buffer, DATA_ALIGNMENT);
396 // Entries allocated at the end of buffer in reverse (as on stack).
397 _store_entries = (AOTCodeEntry*)align_up(_C_store_buffer + max_aot_code_size(), DATA_ALIGNMENT);
398 log_debug(aot, codecache, init)("Allocated store buffer at address " INTPTR_FORMAT " of size %u", p2i(_store_buffer), max_aot_code_size());
399 }
400 _table = new AOTCodeAddressTable();
401 }
402
403 void AOTCodeCache::add_stub_entries(StubId stub_id, address start, GrowableArray<address> *entries, int begin_idx) {
404 EntryId entry_id = StubInfo::entry_base(stub_id);
405 add_stub_entry(entry_id, start);
406 // skip past first entry
407 entry_id = StubInfo::next_in_stub(stub_id, entry_id);
408 // now check for any more entries
409 int count = StubInfo::entry_count(stub_id) - 1;
410 assert(start != nullptr, "invalid start address for stub %s", StubInfo::name(stub_id));
411 assert(entries == nullptr || begin_idx + count <= entries->length(), "sanity");
412 // write any extra entries
413 for (int i = 0; i < count; i++) {
414 assert(entry_id != EntryId::NO_ENTRYID, "not enough entries for stub %s", StubInfo::name(stub_id));
415 address a = entries->at(begin_idx + i);
416 add_stub_entry(entry_id, a);
417 entry_id = StubInfo::next_in_stub(stub_id, entry_id);
418 }
419 assert(entry_id == EntryId::NO_ENTRYID, "too many entries for stub %s", StubInfo::name(stub_id));
420 }
421
422 void AOTCodeCache::add_stub_entry(EntryId entry_id, address a) {
423 if (a != nullptr) {
424 if (_table != nullptr) {
425 log_trace(aot, codecache, stubs)("Publishing stub entry %s at address " INTPTR_FORMAT, StubInfo::name(entry_id), p2i(a));
426 return _table->add_stub_entry(entry_id, a);
427 }
428 }
429 }
430
431 void AOTCodeCache::set_shared_stubs_complete() {
432 AOTCodeAddressTable* table = addr_table();
433 if (table != nullptr) {
434 table->set_shared_stubs_complete();
435 }
436 }
437
438 void AOTCodeCache::set_c1_stubs_complete() {
439 AOTCodeAddressTable* table = addr_table();
440 if (table != nullptr) {
441 table->set_c1_stubs_complete();
442 }
443 }
444
445 void AOTCodeCache::set_c2_stubs_complete() {
446 AOTCodeAddressTable* table = addr_table();
447 if (table != nullptr) {
448 table->set_c2_stubs_complete();
449 }
450 }
451
452 void AOTCodeCache::set_stubgen_stubs_complete() {
453 AOTCodeAddressTable* table = addr_table();
454 if (table != nullptr) {
455 table->set_stubgen_stubs_complete();
456 }
457 }
458
459 void AOTCodeCache::Config::record(uint cpu_features_offset) {
460
461 #define AOTCODECACHE_SAVE_VAR(type, name) _saved_ ## name = name;
462 #define AOTCODECACHE_SAVE_FUN(type, name, fun) _saved_ ## name = fun;
463
464 AOTCODECACHE_CONFIGS_DO(AOTCODECACHE_SAVE_VAR, AOTCODECACHE_SAVE_FUN);
465
466 // Special configs that cannot be checked with macros
467 _compressedOopBase = CompressedOops::base();
468 _compressedOopShift = CompressedOops::shift();
469
470 #if defined(X86) && !defined(ZERO)
471 _useUnalignedLoadStores = UseUnalignedLoadStores;
472 #endif
473
474 #if defined(AARCH64) && !defined(ZERO)
475 _avoidUnalignedAccesses = AvoidUnalignedAccesses;
476 #endif
477
478 _cpu_features_offset = cpu_features_offset;
479 }
480
481 bool AOTCodeCache::Config::verify_cpu_features(AOTCodeCache* cache) const {
482 LogStreamHandle(Debug, aot, codecache, init) log;
483 uint offset = _cpu_features_offset;
484 uint cpu_features_size = *(uint *)cache->addr(offset);
485 assert(cpu_features_size == (uint)VM_Version::cpu_features_size(), "must be");
486 offset += sizeof(uint);
487
488 void* cached_cpu_features_buffer = (void *)cache->addr(offset);
489 if (log.is_enabled()) {
490 ResourceMark rm; // required for stringStream::as_string()
491 stringStream ss;
492 VM_Version::get_cpu_features_name(cached_cpu_features_buffer, ss);
493 log.print_cr("CPU features recorded in AOTCodeCache: %s", ss.as_string());
494 }
495
496 if (!VM_Version::verify_aot_code_cache_features(cached_cpu_features_buffer)) {
497 if (load_failure_log().is_enabled()) {
498 ResourceMark rm; // required for stringStream::as_string()
499 load_failure_log().print_cr("AOT Code Cache disabled: cpu features are incompatible");
500 char* runtime_cpu_features = NEW_RESOURCE_ARRAY(char, VM_Version::cpu_features_size());
501 VM_Version::store_cpu_features(runtime_cpu_features);
502
503 stringStream missing_features;
504 VM_Version::get_missing_features_name(cached_cpu_features_buffer, runtime_cpu_features, missing_features);
505 if (!missing_features.is_empty()) {
506 load_failure_log().print_cr("cpu features that are required: \"%s\"", missing_features.as_string());
507 }
508
509 stringStream additional_features;
510 VM_Version::get_missing_features_name(runtime_cpu_features, cached_cpu_features_buffer, additional_features);
511 if (!additional_features.is_empty()) {
512 load_failure_log().print("cpu features that are additional: \"%s\"", additional_features.as_string());
513 }
514 load_failure_log().print_cr("");
515 }
516 return false;
517 }
518 return true;
519 }
520
521 #define AOTCODECACHE_DISABLED_MSG "AOT Code Cache disabled: it was created with %s = "
522
523 // Special case, print "GC = ..." to be more understandable.
524 inline void log_config_mismatch(CollectedHeap::Name saved, CollectedHeap::Name current, const char* name/*unused*/) {
525 load_failure_log().print_cr("AOT Code Cache disabled: it was created with GC = \"%s\" vs current \"%s\"",
526 GCConfig::hs_err_name(saved), GCConfig::hs_err_name(current));
527 }
528
529 inline void log_config_mismatch(bool saved, bool current, const char* name) {
530 load_failure_log().print_cr(AOTCODECACHE_DISABLED_MSG "%s vs current %s", name,
531 saved ? "true" : "false", current ? "true" : "false");
532 }
533
534 inline void log_config_mismatch(int saved, int current, const char* name) {
535 load_failure_log().print_cr(AOTCODECACHE_DISABLED_MSG "%d vs current %d", name, saved, current);
536 }
537
538 inline void log_config_mismatch(uint saved, uint current, const char* name) {
539 load_failure_log().print_cr(AOTCODECACHE_DISABLED_MSG "%u vs current %u", name, saved, current);
540 }
541
542 #ifdef _LP64
543 inline void log_config_mismatch(intx saved, intx current, const char* name) {
544 load_failure_log().print_cr(AOTCODECACHE_DISABLED_MSG "%zd vs current %zd", name, saved, current);
545 }
546
547 inline void log_config_mismatch(uintx saved, uintx current, const char* name) {
548 load_failure_log().print_cr(AOTCODECACHE_DISABLED_MSG "%zu vs current %zu", name, saved, current);
549 }
550 #endif
551
552 template <typename T>
553 bool check_config(T saved, T current, const char* name) {
554 if (saved != current) {
555 log_config_mismatch(saved, current, name);
556 return false;
557 } else {
558 return true;
559 }
560 }
561
562 bool AOTCodeCache::Config::verify(AOTCodeCache* cache) const {
563 // check CPU features before checking flags that may be
564 // auto-configured in response to them
565 if (!verify_cpu_features(cache)) {
566 return false;
567 }
568
569 // Tests for config options which might affect validity of adapters,
570 // stubs or nmethods. Currently we take a pessemistic stand and
571 // drop the whole cache if any of these are changed.
572
573 #define AOTCODECACHE_CHECK_VAR(type, name) \
574 if (!check_config(_saved_ ## name, name, #name)) { return false; }
575 #define AOTCODECACHE_CHECK_FUN(type, name, fun) \
576 if (!check_config(_saved_ ## name, fun, #fun)) { return false; }
577
578 AOTCODECACHE_CONFIGS_DO(AOTCODECACHE_CHECK_VAR, AOTCODECACHE_CHECK_FUN);
579
580 // Special configs that cannot be checked with macros
581 #define COMPRESSED_OOPS_HINT "Consider adding -XX:+AOTCompatibleOopCompression when creating the AOT cache"
582
583 if ((_compressedOopBase == nullptr || CompressedOops::base() == nullptr) && (_compressedOopBase != CompressedOops::base())) {
584 load_failure_log().print_cr("AOT Code Cache disabled: incompatible CompressedOops::base(): %p vs current %p",
585 _compressedOopBase, CompressedOops::base());
586 load_failure_log().print_cr(COMPRESSED_OOPS_HINT);
587 return false;
588 }
589
590 if (!check_config(_compressedOopShift, CompressedOops::shift(), "CompressedOops::shift()")) {
591 load_failure_log().print_cr(COMPRESSED_OOPS_HINT);
592 return false;
593 }
594
595 #if defined(X86) && !defined(ZERO)
596 // switching off UseUnalignedLoadStores can affect validity of fill
597 // stubs
598 if (_useUnalignedLoadStores && !UseUnalignedLoadStores) {
599 log_config_mismatch(_useUnalignedLoadStores, UseUnalignedLoadStores, "UseUnalignedLoadStores");
600 return false;
601 }
602 #endif // defined(X86) && !defined(ZERO)
603
604 #if defined(AARCH64) && !defined(ZERO)
605 // switching on AvoidUnalignedAccesses may affect validity of array
606 // copy stubs and nmethods
607 if (!_avoidUnalignedAccesses && AvoidUnalignedAccesses) {
608 log_config_mismatch(_avoidUnalignedAccesses, AvoidUnalignedAccesses, "AvoidUnalignedAccesses");
609 return false;
610 }
611 #endif // defined(AARCH64) && !defined(ZERO)
612
613 return true;
614 }
615
616 bool AOTCodeCache::Header::verify(uint load_size) const {
617 if (_version != AOT_CODE_VERSION) {
618 load_failure_log().print_cr("AOT Code Cache disabled: different AOT Code version %d vs %d recorded in AOT Code header", AOT_CODE_VERSION, _version);
619 return false;
620 }
621 if (load_size < _cache_size) {
622 load_failure_log().print_cr("AOT Code Cache disabled: AOT Code Cache size %d < %d recorded in AOT Code header", load_size, _cache_size);
623 return false;
624 }
625 return true;
626 }
627
628 AOTCodeCache* AOTCodeCache::open_for_use() {
629 if (AOTCodeCache::is_on_for_use()) {
630 return AOTCodeCache::cache();
631 }
632 return nullptr;
633 }
634
635 AOTCodeCache* AOTCodeCache::open_for_dump() {
636 if (AOTCodeCache::is_on_for_dump()) {
637 AOTCodeCache* cache = AOTCodeCache::cache();
638 cache->clear_lookup_failed(); // Reset bit
639 return cache;
640 }
641 return nullptr;
642 }
643
644 void copy_bytes(const char* from, address to, uint size) {
645 assert((int)size > 0, "sanity");
646 memcpy(to, from, size);
647 log_trace(aot, codecache)("Copied %d bytes from " INTPTR_FORMAT " to " INTPTR_FORMAT, size, p2i(from), p2i(to));
648 }
649
650 AOTCodeReader::AOTCodeReader(AOTCodeCache* cache, AOTCodeEntry* entry) {
651 _cache = cache;
652 _entry = entry;
653 _load_buffer = cache->cache_buffer();
654 _read_position = 0;
655 _lookup_failed = false;
656 _name = nullptr;
657 _reloc_data = nullptr;
658 _reloc_count = 0;
659 _oop_maps = nullptr;
660 _entry_kind = AOTCodeEntry::None;
661 _stub_data = nullptr;
662 _id = -1;
663 }
664
665 void AOTCodeReader::set_read_position(uint pos) {
666 if (pos == _read_position) {
667 return;
668 }
669 assert(pos < _cache->load_size(), "offset:%d >= file size:%d", pos, _cache->load_size());
670 _read_position = pos;
671 }
672
673 uint AOTCodeReader::align_read_int() {
674 return align_up(_read_position, sizeof(int));
675 }
676
677 bool AOTCodeCache::set_write_position(uint pos) {
678 if (pos == _write_position) {
679 return true;
680 }
681 if (_store_size < _write_position) {
682 _store_size = _write_position; // Adjust during write
683 }
684 assert(pos < _store_size, "offset:%d >= file size:%d", pos, _store_size);
685 _write_position = pos;
686 return true;
687 }
688
689 static char align_buffer[256] = { 0 };
690
691 bool AOTCodeCache::align_write_bytes(uint alignment) {
692 uint padding = alignment - (_write_position & (alignment - 1));
693 if (padding == alignment) {
694 return true;
695 }
696 uint n = write_bytes((const void*)&align_buffer, padding);
697 if (n != padding) {
698 return false;
699 }
700 log_trace(aot, codecache)("Adjust write alignment to %d bytes in AOT Code Cache", alignment);
701 return true;
702 }
703
704 bool AOTCodeCache::align_write() {
705 // We are not executing code from cache - we copy it by bytes first.
706 // No need for big alignment (or at all).
707 return align_write_bytes(DATA_ALIGNMENT);
708 }
709
710 bool AOTCodeCache::align_write_int() {
711 return align_write_bytes(sizeof(int));
712 }
713
714 // Check to see if AOT code cache has required space to store "nbytes" of data
715 address AOTCodeCache::reserve_bytes(uint nbytes) {
716 assert(for_dump(), "Code Cache file is not created");
717 uint new_position = _write_position + nbytes;
718 if (new_position >= (uint)((char*)_store_entries - _store_buffer)) {
719 log_warning(aot,codecache)("Failed to ensure %d bytes at offset %d in AOT Code Cache. Increase AOTCodeMaxSize.",
720 nbytes, _write_position);
721 set_failed();
722 report_store_failure();
723 return nullptr;
724 }
725 address buffer = (address)(_store_buffer + _write_position);
726 log_trace(aot, codecache)("Reserved %d bytes at offset %d in AOT Code Cache", nbytes, _write_position);
727 _write_position += nbytes;
728 if (_store_size < _write_position) {
729 _store_size = _write_position;
730 }
731 return buffer;
732 }
733
734 uint AOTCodeCache::write_bytes(const void* buffer, uint nbytes) {
735 assert(for_dump(), "Code Cache file is not created");
736 if (nbytes == 0) {
737 return 0;
738 }
739 uint new_position = _write_position + nbytes;
740 if (new_position >= (uint)((char*)_store_entries - _store_buffer)) {
741 log_warning(aot, codecache)("Failed to write %d bytes at offset %d to AOT Code Cache. Increase AOTCodeMaxSize.",
742 nbytes, _write_position);
743 set_failed();
744 report_store_failure();
745 return 0;
746 }
747 copy_bytes((const char* )buffer, (address)(_store_buffer + _write_position), nbytes);
748 log_trace(aot, codecache)("Wrote %d bytes at offset %d to AOT Code Cache", nbytes, _write_position);
749 _write_position += nbytes;
750 if (_store_size < _write_position) {
751 _store_size = _write_position;
752 }
753 return nbytes;
754 }
755
756 void* AOTCodeEntry::operator new(size_t x, AOTCodeCache* cache) {
757 return (void*)(cache->add_entry());
758 }
759
760 static bool check_entry(AOTCodeEntry::Kind kind, uint id, AOTCodeEntry* entry) {
761 if (entry->kind() == kind) {
762 assert(entry->id() == id, "sanity");
763 return true; // Found
764 }
765 return false;
766 }
767
768 AOTCodeEntry* AOTCodeCache::find_entry(AOTCodeEntry::Kind kind, uint id) {
769 assert(_for_use, "sanity");
770 uint count = _load_header->entries_count();
771 if (_load_entries == nullptr) {
772 // Read it
773 _search_entries = (uint*)addr(_load_header->entries_offset()); // [id, index]
774 _load_entries = (AOTCodeEntry*)(_search_entries + 2 * count);
775 log_debug(aot, codecache, init)("Read %d entries table at offset %d from AOT Code Cache", count, _load_header->entries_offset());
776 }
777 // Binary search
778 int l = 0;
779 int h = count - 1;
780 while (l <= h) {
781 int mid = (l + h) >> 1;
782 int ix = mid * 2;
783 uint is = _search_entries[ix];
784 if (is == id) {
785 int index = _search_entries[ix + 1];
786 AOTCodeEntry* entry = &(_load_entries[index]);
787 if (check_entry(kind, id, entry)) {
788 return entry; // Found
789 }
790 // Linear search around to handle id collission
791 for (int i = mid - 1; i >= l; i--) { // search back
792 ix = i * 2;
793 is = _search_entries[ix];
794 if (is != id) {
795 break;
796 }
797 index = _search_entries[ix + 1];
798 AOTCodeEntry* entry = &(_load_entries[index]);
799 if (check_entry(kind, id, entry)) {
800 return entry; // Found
801 }
802 }
803 for (int i = mid + 1; i <= h; i++) { // search forward
804 ix = i * 2;
805 is = _search_entries[ix];
806 if (is != id) {
807 break;
808 }
809 index = _search_entries[ix + 1];
810 AOTCodeEntry* entry = &(_load_entries[index]);
811 if (check_entry(kind, id, entry)) {
812 return entry; // Found
813 }
814 }
815 break; // Not found match
816 } else if (is < id) {
817 l = mid + 1;
818 } else {
819 h = mid - 1;
820 }
821 }
822 return nullptr;
823 }
824
825 extern "C" {
826 static int uint_cmp(const void *i, const void *j) {
827 uint a = *(uint *)i;
828 uint b = *(uint *)j;
829 return a > b ? 1 : a < b ? -1 : 0;
830 }
831 }
832
833 void AOTCodeCache::store_cpu_features(char*& buffer, uint buffer_size) {
834 uint* size_ptr = (uint *)buffer;
835 *size_ptr = buffer_size;
836 buffer += sizeof(uint);
837
838 VM_Version::store_cpu_features(buffer);
839 log_debug(aot, codecache, exit)("CPU features recorded in AOTCodeCache: %s", VM_Version::features_string());
840 buffer += buffer_size;
841 buffer = align_up(buffer, DATA_ALIGNMENT);
842 }
843
844 bool AOTCodeCache::finish_write() {
845 if (!align_write()) {
846 return false;
847 }
848 uint strings_offset = _write_position;
849 int strings_count = store_strings();
850 if (strings_count < 0) {
851 return false;
852 }
853 if (!align_write()) {
854 return false;
855 }
856 uint strings_size = _write_position - strings_offset;
857
858 uint entries_count = 0; // Number of entrant (useful) code entries
859 uint entries_offset = _write_position;
860
861 uint store_count = _store_entries_cnt;
862 if (store_count > 0) {
863 uint header_size = (uint)align_up(sizeof(AOTCodeCache::Header), DATA_ALIGNMENT);
864 uint code_count = store_count;
865 uint search_count = code_count * 2;
866 uint search_size = search_count * sizeof(uint);
867 uint entries_size = (uint)align_up(code_count * sizeof(AOTCodeEntry), DATA_ALIGNMENT); // In bytes
868 // _write_position includes size of code and strings
869 uint code_alignment = code_count * DATA_ALIGNMENT; // We align_up code size when storing it.
870 uint cpu_features_size = VM_Version::cpu_features_size();
871 uint total_cpu_features_size = sizeof(uint) + cpu_features_size; // sizeof(uint) to store cpu_features_size
872 uint total_size = header_size + _write_position + code_alignment + search_size + entries_size +
873 align_up(total_cpu_features_size, DATA_ALIGNMENT);
874 assert(total_size < max_aot_code_size(), "AOT Code size (" UINT32_FORMAT " bytes) is greater than AOTCodeMaxSize(" UINT32_FORMAT " bytes).", total_size, max_aot_code_size());
875
876 // Allocate in AOT Cache buffer
877 char* buffer = (char *)AOTCacheAccess::allocate_aot_code_region(total_size + DATA_ALIGNMENT);
878 char* start = align_up(buffer, DATA_ALIGNMENT);
879 char* current = start + header_size; // Skip header
880
881 uint cpu_features_offset = current - start;
882 store_cpu_features(current, cpu_features_size);
883 assert(is_aligned(current, DATA_ALIGNMENT), "sanity check");
884 assert(current < start + total_size, "sanity check");
885
886 // Create ordered search table for entries [id, index];
887 uint* search = NEW_C_HEAP_ARRAY(uint, search_count, mtCode);
888
889 AOTCodeEntry* entries_address = _store_entries; // Pointer to latest entry
890 uint adapters_count = 0;
891 uint shared_blobs_count = 0;
892 uint stubgen_blobs_count = 0;
893 uint C1_blobs_count = 0;
894 uint C2_blobs_count = 0;
895 uint max_size = 0;
896 // AOTCodeEntry entries were allocated in reverse in store buffer.
897 // Process them in reverse order to cache first code first.
898 for (int i = store_count - 1; i >= 0; i--) {
899 entries_address[i].set_next(nullptr); // clear pointers before storing data
900 uint size = align_up(entries_address[i].size(), DATA_ALIGNMENT);
901 if (size > max_size) {
902 max_size = size;
903 }
904 copy_bytes((_store_buffer + entries_address[i].offset()), (address)current, size);
905 entries_address[i].set_offset(current - start); // New offset
906 current += size;
907 uint n = write_bytes(&(entries_address[i]), sizeof(AOTCodeEntry));
908 if (n != sizeof(AOTCodeEntry)) {
909 FREE_C_HEAP_ARRAY(search);
910 return false;
911 }
912 search[entries_count*2 + 0] = entries_address[i].id();
913 search[entries_count*2 + 1] = entries_count;
914 entries_count++;
915 AOTCodeEntry::Kind kind = entries_address[i].kind();
916 if (kind == AOTCodeEntry::Adapter) {
917 adapters_count++;
918 } else if (kind == AOTCodeEntry::SharedBlob) {
919 shared_blobs_count++;
920 } else if (kind == AOTCodeEntry::StubGenBlob) {
921 stubgen_blobs_count++;
922 } else if (kind == AOTCodeEntry::C1Blob) {
923 C1_blobs_count++;
924 } else if (kind == AOTCodeEntry::C2Blob) {
925 C2_blobs_count++;
926 }
927 }
928 if (entries_count == 0) {
929 log_info(aot, codecache, exit)("AOT Code Cache was not created: no entires");
930 FREE_C_HEAP_ARRAY(search);
931 return true; // Nothing to write
932 }
933 assert(entries_count <= store_count, "%d > %d", entries_count, store_count);
934 // Write strings
935 if (strings_count > 0) {
936 copy_bytes((_store_buffer + strings_offset), (address)current, strings_size);
937 strings_offset = (current - start); // New offset
938 current += strings_size;
939 }
940
941 uint new_entries_offset = (current - start); // New offset
942 // Sort and store search table
943 qsort(search, entries_count, 2*sizeof(uint), uint_cmp);
944 search_size = 2 * entries_count * sizeof(uint);
945 copy_bytes((const char*)search, (address)current, search_size);
946 FREE_C_HEAP_ARRAY(search);
947 current += search_size;
948
949 // Write entries
950 entries_size = entries_count * sizeof(AOTCodeEntry); // New size
951 copy_bytes((_store_buffer + entries_offset), (address)current, entries_size);
952 current += entries_size;
953 uint size = (current - start);
954 assert(size <= total_size, "%d > %d", size , total_size);
955
956 log_debug(aot, codecache, exit)(" Adapters: total=%u", adapters_count);
957 log_debug(aot, codecache, exit)(" Shared Blobs: total=%d", shared_blobs_count);
958 log_debug(aot, codecache, exit)(" StubGen Blobs: total=%d", stubgen_blobs_count);
959 log_debug(aot, codecache, exit)(" C1 Blobs: total=%d", C1_blobs_count);
960 log_debug(aot, codecache, exit)(" C2 Blobs: total=%d", C2_blobs_count);
961 log_debug(aot, codecache, exit)(" AOT code cache size: %u bytes, max entry's size: %u bytes", size, max_size);
962
963 // Finalize header
964 AOTCodeCache::Header* header = (AOTCodeCache::Header*)start;
965 header->init(size, (uint)strings_count, strings_offset,
966 entries_count, new_entries_offset,
967 adapters_count, shared_blobs_count,
968 stubgen_blobs_count, C1_blobs_count,
969 C2_blobs_count, cpu_features_offset);
970
971 log_info(aot, codecache, exit)("Wrote %d AOT code entries to AOT Code Cache", entries_count);
972 }
973 return true;
974 }
975
976 //------------------Store/Load AOT code ----------------------
977
978 bool AOTCodeCache::store_code_blob(CodeBlob& blob, AOTCodeEntry::Kind entry_kind, uint id, const char* name, AOTStubData* stub_data, CodeBuffer* code_buffer) {
979 assert(AOTCodeEntry::is_valid_entry_kind(entry_kind), "invalid entry_kind %d", entry_kind);
980
981 // we only expect stub data and a code buffer for a multi stub blob
982 assert(AOTCodeEntry::is_multi_stub_blob(entry_kind) == (stub_data != nullptr),
983 "entry_kind %d does not match stub_data pointer %p",
984 entry_kind, stub_data);
985
986 assert((stub_data == nullptr) == (code_buffer == nullptr),
987 "stub data and code buffer must both be null or both non null");
988
989 // If this is a stub and the cache is on for either load or dump we
990 // need to insert the stub entries into the AOTCacheAddressTable so
991 // that relocs which refer to entries defined by this blob get
992 // translated correctly.
993 //
994 // Entry insertion needs to be be done up front before writing the
995 // blob because some blobs rely on internal daisy-chain references
996 // from one entry to another.
997 //
998 // Entry insertion also needs to be done even if the cache is open
999 // for use but not for dump. This may be needed when an archived
1000 // blob omits some entries -- either because of a config change or a
1001 // load failure -- with the result that the entries end up being
1002 // generated. These generated entry addresses may be needed to
1003 // resolve references from subsequently loaded blobs (for either
1004 // stubs or nmethods).
1005
1006 if (is_on() && AOTCodeEntry::is_blob(entry_kind)) {
1007 publish_stub_addresses(blob, (BlobId)id, stub_data);
1008 }
1009
1010 AOTCodeCache* cache = open_for_dump();
1011 if (cache == nullptr) {
1012 return false;
1013 }
1014 if (AOTCodeEntry::is_adapter(entry_kind) && !is_dumping_adapter()) {
1015 return false;
1016 }
1017 if (AOTCodeEntry::is_blob(entry_kind) && !is_dumping_stub()) {
1018 return false;
1019 }
1020 log_debug(aot, codecache, stubs)("Writing blob '%s' (id=%u, kind=%s) to AOT Code Cache", name, id, aot_code_entry_kind_name[entry_kind]);
1021
1022 #ifdef ASSERT
1023 LogStreamHandle(Trace, aot, codecache, stubs) log;
1024 if (log.is_enabled()) {
1025 FlagSetting fs(PrintRelocations, true);
1026 blob.print_on(&log);
1027 }
1028 #endif
1029 // we need to take a lock to prevent race between compiler threads generating AOT code
1030 // and the main thread generating adapter
1031 MutexLocker ml(Compile_lock);
1032 if (!is_on()) {
1033 return false; // AOT code cache was already dumped and closed.
1034 }
1035 if (!cache->align_write()) {
1036 return false;
1037 }
1038 uint entry_position = cache->_write_position;
1039
1040 uint blob_offset = cache->_write_position - entry_position;
1041 // Code blob's size is aligned to oopSize
1042 address archive_buffer = cache->reserve_bytes(blob.size());
1043 if (archive_buffer == nullptr) {
1044 return false;
1045 }
1046 CodeBlob::archive_blob(&blob, archive_buffer);
1047
1048 // For a relocatable code blob its relocations are linked from the
1049 // blob. However, for a non-relocatable (stubgen) blob we only have
1050 // transient relocations attached to the code buffer that are added
1051 // in order to support AOT-load time patching. in either case, we
1052 // need to explicitly save these relocs when storing the blob to the
1053 // archive so we can then reload them and reattach them to either
1054 // the blob or to a code buffer when we reload the blob into a
1055 // production JVM.
1056 //
1057 // Either way we are then in a position to iterate over the relocs
1058 // and AOT patch the ones that refer to code that may move between
1059 // assembly and production time. We also need to save and restore
1060 // AOT address table indexes for the target addresses of affected
1061 // relocs. That happens below.
1062
1063 int reloc_count;
1064 address reloc_data;
1065 if (AOTCodeEntry::is_multi_stub_blob(entry_kind)) {
1066 CodeSection* cs = code_buffer->code_section(CodeBuffer::SECT_INSTS);
1067 reloc_count = (cs->has_locs() ? cs->locs_count() : 0);
1068 reloc_data = (reloc_count > 0 ? (address)cs->locs_start() : nullptr);
1069 } else {
1070 reloc_count = blob.relocation_size() / sizeof(relocInfo);
1071 reloc_data = (address)blob.relocation_begin();
1072 }
1073 uint n = cache->write_bytes(&reloc_count, sizeof(int));
1074 if (n != sizeof(int)) {
1075 return false;
1076 }
1077 if (AOTCodeEntry::is_multi_stub_blob(entry_kind)) {
1078 // align to heap word size before writing the relocs so we can
1079 // install them into a code buffer when they get restored
1080 if (!cache->align_write()) {
1081 return false;
1082 }
1083 }
1084 uint reloc_data_size = (uint)(reloc_count * sizeof(relocInfo));
1085 n = cache->write_bytes(reloc_data, reloc_data_size);
1086 if (n != reloc_data_size) {
1087 return false;
1088 }
1089
1090 bool has_oop_maps = false;
1091 if (blob.oop_maps() != nullptr) {
1092 if (!cache->write_oop_map_set(blob)) {
1093 return false;
1094 }
1095 has_oop_maps = true;
1096 }
1097
1098 // In the case of a multi-stub blob we need to write start, end,
1099 // secondary entries and extras. For any other blob entry addresses
1100 // beyond the blob start will be stored in the blob as offsets.
1101 if (stub_data != nullptr) {
1102 if (!cache->write_stub_data(blob, stub_data)) {
1103 return false;
1104 }
1105 }
1106
1107 // now we have added all the other data we can write details of any
1108 // extra the AOT relocations
1109
1110 bool write_ok = true;
1111 if (AOTCodeEntry::is_multi_stub_blob(entry_kind)) {
1112 if (reloc_count > 0) {
1113 CodeSection* cs = code_buffer->code_section(CodeBuffer::SECT_INSTS);
1114 RelocIterator iter(cs);
1115 write_ok = cache->write_relocations(blob, iter);
1116 }
1117 } else {
1118 RelocIterator iter(&blob);
1119 write_ok = cache->write_relocations(blob, iter);
1120 }
1121
1122 if (!write_ok) {
1123 if (!cache->failed()) {
1124 // We may miss an address in AOT table - skip this code blob.
1125 cache->set_write_position(entry_position);
1126 }
1127 return false;
1128 }
1129
1130 #ifndef PRODUCT
1131 // Write asm remarks after relocation info
1132 if (!cache->write_asm_remarks(blob)) {
1133 return false;
1134 }
1135 if (!cache->write_dbg_strings(blob)) {
1136 return false;
1137 }
1138 #endif /* PRODUCT */
1139
1140 // Write name after code comments
1141 uint name_offset = cache->_write_position - entry_position;
1142 uint name_size = (uint)strlen(name) + 1; // Includes '/0'
1143 n = cache->write_bytes(name, name_size);
1144 if (n != name_size) {
1145 return false;
1146 }
1147
1148 uint entry_size = cache->_write_position - entry_position;
1149
1150 AOTCodeEntry* entry = new(cache) AOTCodeEntry(entry_kind, encode_id(entry_kind, id),
1151 entry_position, entry_size, name_offset, name_size,
1152 blob_offset, has_oop_maps, blob.content_begin());
1153 log_debug(aot, codecache, stubs)("Wrote code blob '%s' (id=%u, kind=%s) to AOT Code Cache", name, id, aot_code_entry_kind_name[entry_kind]);
1154 return true;
1155 }
1156
1157 bool AOTCodeCache::store_code_blob(CodeBlob& blob, AOTCodeEntry::Kind entry_kind, uint id, const char* name) {
1158 assert(!AOTCodeEntry::is_blob(entry_kind),
1159 "wrong entry kind for numeric id %d", id);
1160 return store_code_blob(blob, entry_kind, (uint)id, name, nullptr, nullptr);
1161 }
1162
1163 bool AOTCodeCache::store_code_blob(CodeBlob& blob, AOTCodeEntry::Kind entry_kind, BlobId id) {
1164 assert(AOTCodeEntry::is_single_stub_blob(entry_kind),
1165 "wrong entry kind for blob id %s", StubInfo::name(id));
1166 return store_code_blob(blob, entry_kind, (uint)id, StubInfo::name(id), nullptr, nullptr);
1167 }
1168
1169 bool AOTCodeCache::store_code_blob(CodeBlob& blob, AOTCodeEntry::Kind entry_kind, BlobId id, AOTStubData* stub_data, CodeBuffer* code_buffer) {
1170 assert(AOTCodeEntry::is_multi_stub_blob(entry_kind),
1171 "wrong entry kind for multi stub blob id %s", StubInfo::name(id));
1172 return store_code_blob(blob, entry_kind, (uint)id, StubInfo::name(id), stub_data, code_buffer);
1173 }
1174
1175 bool AOTCodeCache::write_stub_data(CodeBlob &blob, AOTStubData *stub_data) {
1176 if (!align_write_int()) {
1177 return false;
1178 }
1179 BlobId blob_id = stub_data->blob_id();
1180 StubId stub_id = StubInfo::stub_base(blob_id);
1181 address blob_base = blob.code_begin();
1182 int stub_cnt = StubInfo::stub_count(blob_id);
1183 int n;
1184
1185 LogStreamHandle(Trace, aot, codecache, stubs) log;
1186
1187 if (log.is_enabled()) {
1188 log.print_cr("======== Stub data starts at offset %d", _write_position);
1189 }
1190
1191 for (int i = 0; i < stub_cnt; i++, stub_id = StubInfo::next_in_blob(blob_id, stub_id)) {
1192 // for each stub we find in the ranges list we write an int
1193 // sequence <stubid,start,end,N,offset1, ... offsetN> where
1194 //
1195 // - start_pos is the stub start address encoded as a code section offset
1196 //
1197 // - end is the stub end address encoded as an offset from start
1198 //
1199 // - N counts the number of stub-local entries/extras
1200 //
1201 // - offseti is a stub-local entry/extra address encoded as len for
1202 // a null address otherwise as an offset in range [1,len-1]
1203
1204 StubAddrRange& range = stub_data->get_range(i);
1205 GrowableArray<address>& addresses = stub_data->address_array();
1206 int base = range.start_index();
1207 if (base >= 0) {
1208 n = write_bytes(&stub_id, sizeof(StubId));
1209 if (n != sizeof(StubId)) {
1210 return false;
1211 }
1212 address start = addresses.at(base);
1213 assert (blob_base <= start, "sanity");
1214 uint offset = (uint)(start - blob_base);
1215 n = write_bytes(&offset, sizeof(uint));
1216 if (n != sizeof(int)) {
1217 return false;
1218 }
1219 address end = addresses.at(base + 1);
1220 assert (start < end, "sanity");
1221 offset = (uint)(end - start);
1222 n = write_bytes(&offset, sizeof(uint));
1223 if (n != sizeof(int)) {
1224 return false;
1225 }
1226 // write number of secondary and extra entries
1227 int count = range.count() - 2;
1228 n = write_bytes(&count, sizeof(int));
1229 if (n != sizeof(int)) {
1230 return false;
1231 }
1232 for (int j = 0; j < count; j++) {
1233 address next = addresses.at(base + 2 + j);
1234 if (next != nullptr) {
1235 // n.b. This maps next == end to the stub length which
1236 // means we will reconstitute the address as nullptr. That
1237 // happens when we have a handler range covers the end of
1238 // a stub and needs to be handled specially by the client
1239 // that restores the extras.
1240 assert(start <= next && next <= end, "sanity");
1241 offset = (uint)(next - start);
1242 } else {
1243 // this can happen when a stub is not generated or an
1244 // extra is the common handler target
1245 offset = NULL_ADDRESS_MARKER;
1246 }
1247 n = write_bytes(&offset, sizeof(uint));
1248 if (n != sizeof(int)) {
1249 return false;
1250 }
1251 }
1252 if (log.is_enabled()) {
1253 log.print_cr("======== wrote stub %s and %d addresses up to offset %d",
1254 StubInfo::name(stub_id), range.count(), _write_position);
1255 }
1256 }
1257 }
1258 // we should have exhausted all stub ids in the blob
1259 assert(stub_id == StubId::NO_STUBID, "sanity");
1260 // write NO_STUBID as an end marker
1261 n = write_bytes(&stub_id, sizeof(StubId));
1262 if (n != sizeof(StubId)) {
1263 return false;
1264 }
1265
1266 if (log.is_enabled()) {
1267 log.print_cr("======== Stub data ends at offset %d", _write_position);
1268 }
1269
1270 return true;
1271 }
1272
1273 CodeBlob* AOTCodeCache::load_code_blob(AOTCodeEntry::Kind entry_kind, uint id, const char* name, AOTStubData* stub_data) {
1274 AOTCodeCache* cache = open_for_use();
1275 if (cache == nullptr) {
1276 return nullptr;
1277 }
1278 assert(AOTCodeEntry::is_valid_entry_kind(entry_kind), "invalid entry_kind %d", entry_kind);
1279
1280 assert(AOTCodeEntry::is_multi_stub_blob(entry_kind) == (stub_data != nullptr),
1281 "entry_kind %d does not match stub_data pointer %p",
1282 entry_kind, stub_data);
1283
1284 if (AOTCodeEntry::is_adapter(entry_kind) && !is_using_adapter()) {
1285 return nullptr;
1286 }
1287 if (AOTCodeEntry::is_blob(entry_kind) && !is_using_stub()) {
1288 return nullptr;
1289 }
1290 log_debug(aot, codecache, stubs)("Reading blob '%s' (id=%u, kind=%s) from AOT Code Cache", name, id, aot_code_entry_kind_name[entry_kind]);
1291
1292 AOTCodeEntry* entry = cache->find_entry(entry_kind, encode_id(entry_kind, id));
1293 if (entry == nullptr) {
1294 return nullptr;
1295 }
1296 AOTCodeReader reader(cache, entry);
1297 CodeBlob* blob = reader.compile_code_blob(name, entry_kind, id, stub_data);
1298
1299 log_debug(aot, codecache, stubs)("%sRead blob '%s' (id=%u, kind=%s) from AOT Code Cache",
1300 (blob == nullptr? "Failed to " : ""), name, id, aot_code_entry_kind_name[entry_kind]);
1301 return blob;
1302 }
1303
1304 CodeBlob* AOTCodeCache::load_code_blob(AOTCodeEntry::Kind entry_kind, uint id, const char* name) {
1305 assert(!AOTCodeEntry::is_blob(entry_kind),
1306 "wrong entry kind for numeric id %d", id);
1307 return load_code_blob(entry_kind, (uint)id, name, nullptr);
1308 }
1309
1310 CodeBlob* AOTCodeCache::load_code_blob(AOTCodeEntry::Kind entry_kind, BlobId id) {
1311 assert(AOTCodeEntry::is_single_stub_blob(entry_kind),
1312 "wrong entry kind for blob id %s", StubInfo::name(id));
1313 return load_code_blob(entry_kind, (uint)id, StubInfo::name(id), nullptr);
1314 }
1315
1316 CodeBlob* AOTCodeCache::load_code_blob(AOTCodeEntry::Kind entry_kind, BlobId id, AOTStubData* stub_data) {
1317 assert(AOTCodeEntry::is_multi_stub_blob(entry_kind),
1318 "wrong entry kind for blob id %s", StubInfo::name(id));
1319 return load_code_blob(entry_kind, (uint)id, StubInfo::name(id), stub_data);
1320 }
1321
1322 CodeBlob* AOTCodeReader::compile_code_blob(const char* name, AOTCodeEntry::Kind entry_kind, int id, AOTStubData* stub_data) {
1323 uint entry_position = _entry->offset();
1324
1325 // Read name
1326 uint name_offset = entry_position + _entry->name_offset();
1327 uint name_size = _entry->name_size(); // Includes '/0'
1328 const char* stored_name = addr(name_offset);
1329
1330 if (strncmp(stored_name, name, (name_size - 1)) != 0) {
1331 log_warning(aot, codecache, stubs)("Saved blob's name '%s' is different from the expected name '%s'",
1332 stored_name, name);
1333 set_lookup_failed(); // Skip this blob
1334 return nullptr;
1335 }
1336 _name = stored_name;
1337
1338 // Read archived code blob and related info
1339 uint offset = entry_position + _entry->blob_offset();
1340 CodeBlob* archived_blob = (CodeBlob*)addr(offset);
1341 offset += archived_blob->size();
1342
1343 _reloc_count = *(int*)addr(offset);
1344 offset += sizeof(int);
1345 if (AOTCodeEntry::is_multi_stub_blob(entry_kind)) {
1346 // position of relocs will have been aligned to heap word size so
1347 // we can install them into a code buffer
1348 offset = align_up(offset, DATA_ALIGNMENT);
1349 }
1350 _reloc_data = (address)addr(offset);
1351 offset += _reloc_count * sizeof(relocInfo);
1352 set_read_position(offset);
1353
1354 if (_entry->has_oop_maps()) {
1355 _oop_maps = read_oop_map_set();
1356 }
1357
1358 // record current context for use by that callback
1359 _stub_data = stub_data;
1360 _entry_kind = entry_kind;
1361 _id = id;
1362
1363 // CodeBlob::restore() calls AOTCodeReader::restore()
1364
1365 CodeBlob* code_blob = CodeBlob::create(archived_blob, this);
1366
1367 if (code_blob == nullptr) { // no space left in CodeCache
1368 return nullptr;
1369 }
1370
1371 #ifdef ASSERT
1372 LogStreamHandle(Trace, aot, codecache, stubs) log;
1373 if (log.is_enabled()) {
1374 FlagSetting fs(PrintRelocations, true);
1375 code_blob->print_on(&log);
1376 }
1377 #endif
1378 return code_blob;
1379 }
1380
1381 void AOTCodeReader::restore(CodeBlob* code_blob) {
1382 precond(AOTCodeCache::is_on_for_use());
1383 precond(_name != nullptr);
1384 precond(_reloc_data != nullptr);
1385
1386 code_blob->set_name(_name);
1387 // Saved relocations need restoring except for the case of a
1388 // multi-stub blob which has no runtime relocations. However, we may
1389 // still have saved some (re-)load time relocs that were attached to
1390 // the generator's code buffer. We don't attach them to the blob but
1391 // they get processed below by fix_relocations.
1392 if (!AOTCodeEntry::is_multi_stub_blob(_entry_kind)) {
1393 code_blob->restore_mutable_data(_reloc_data);
1394 }
1395 code_blob->set_oop_maps(_oop_maps);
1396
1397 // if this is a multi stub blob load its entries
1398 if (AOTCodeEntry::is_blob(_entry_kind)) {
1399 BlobId blob_id = static_cast<BlobId>(_id);
1400 if (StubInfo::is_stubgen(blob_id)) {
1401 assert(_stub_data != nullptr, "sanity");
1402 read_stub_data(code_blob, _stub_data);
1403 }
1404 // publish entries found either in stub_data or as offsets in blob
1405 AOTCodeCache::publish_stub_addresses(*code_blob, blob_id, _stub_data);
1406 }
1407
1408 // Now that all the entry points are in the address table we can
1409 // read all the extra reloc info and fix up any addresses that need
1410 // patching to adjust for a new location in a new JVM. We can be
1411 // sure to correctly update all runtime references, including
1412 // cross-linked stubs that are internally daisy-chained. If
1413 // relocation fails and we have to re-generate any of the stubs then
1414 // the entry points for newly generated stubs will get updated,
1415 // ensuring that any other stubs or nmethods we need to relocate
1416 // will use the correct address.
1417
1418 // if we have a relocatable code blob then the relocs are already
1419 // attached to the blob and we can iterate over it to find the ones
1420 // we need to patch. With a non-relocatable code blob we need to
1421 // wrap it with a CodeBuffer and then reattach the relocs to the
1422 // code buffer.
1423
1424 if (AOTCodeEntry::is_multi_stub_blob(_entry_kind)) {
1425 // the blob doesn't have any proper runtime relocs but we can
1426 // reinstate the AOT-load time relocs we saved from the code
1427 // buffer that generated this blob in a new code buffer and use
1428 // the latter to iterate over them
1429 if (_reloc_count > 0) {
1430 CodeBuffer code_buffer(code_blob);
1431 relocInfo* locs = (relocInfo*)_reloc_data;
1432 code_buffer.insts()->initialize_shared_locs(locs, _reloc_count);
1433 code_buffer.insts()->set_locs_end(locs + _reloc_count);
1434 CodeSection *cs = code_buffer.code_section(CodeBuffer::SECT_INSTS);
1435 RelocIterator reloc_iter(cs);
1436 fix_relocations(code_blob, reloc_iter);
1437 }
1438 } else {
1439 // the AOT-load time relocs will be in the blob's restored relocs
1440 RelocIterator reloc_iter(code_blob);
1441 fix_relocations(code_blob, reloc_iter);
1442 }
1443
1444 #ifndef PRODUCT
1445 code_blob->asm_remarks().init();
1446 read_asm_remarks(code_blob->asm_remarks());
1447 code_blob->dbg_strings().init();
1448 read_dbg_strings(code_blob->dbg_strings());
1449 #endif // PRODUCT
1450 }
1451
1452 void AOTCodeReader::read_stub_data(CodeBlob* code_blob, AOTStubData* stub_data) {
1453 GrowableArray<address>& addresses = stub_data->address_array();
1454 // Read the list of stub ids and associated start, end, secondary
1455 // and extra addresses and install them in the stub data.
1456 //
1457 // Also insert all start and secondary addresses into the AOTCache
1458 // address table so we correctly relocate this blob and any followng
1459 // blobs/nmethods.
1460 //
1461 // n.b. if an error occurs and we need to regenerate any of these
1462 // stubs the address table will be updated as a side-effect of
1463 // regeneration.
1464
1465 address blob_base = code_blob->code_begin();
1466 uint blob_size = (uint)(code_blob->code_end() - blob_base);
1467 uint offset = align_read_int();
1468 LogStreamHandle(Trace, aot, codecache, stubs) log;
1469 if (log.is_enabled()) {
1470 log.print_cr("======== Stub data starts at offset %d", offset);
1471 }
1472 // read stub and entries until we see NO_STUBID
1473 StubId stub_id = *(StubId*)addr(offset); offset += sizeof(StubId);
1474 // we ought to have at least one saved stub in the blob
1475 assert(stub_id != StubId::NO_STUBID, "blob %s contains no stubs!", StubInfo::name(stub_data->blob_id()));
1476 while (stub_id != StubId::NO_STUBID) {
1477 assert(StubInfo::blob(stub_id) == stub_data->blob_id(), "sanity");
1478 int idx = StubInfo::stubgen_offset_in_blob(stub_data->blob_id(), stub_id);
1479 StubAddrRange& range = stub_data->get_range(idx);
1480 // we should only see a stub once
1481 assert(range.start_index() < 0, "repeated entry for stub %s", StubInfo::name(stub_id));
1482 int address_base = addresses.length();
1483 // start is an offset from the blob base
1484 uint start = *(uint*)addr(offset); offset += sizeof(uint);
1485 assert(start < blob_size, "stub %s start offset %d exceeds buffer length %d", StubInfo::name(stub_id), start, blob_size);
1486 address stub_start = blob_base + start;
1487 addresses.append(stub_start);
1488 // end is an offset from the stub start
1489 uint end = *(uint*)addr(offset); offset += sizeof(uint);
1490 assert(start + end <= blob_size, "stub %s end offset %d exceeds remaining buffer length %d", StubInfo::name(stub_id), end, blob_size - start);
1491 addresses.append(stub_start + end);
1492 // read count of secondary entries plus extras
1493 int entries_count = *(int*)addr(offset); offset += sizeof(int);
1494 assert(entries_count >= (StubInfo::entry_count(stub_id) - 1), "not enough entries for %s", StubInfo::name(stub_id));
1495 for (int i = 0; i < entries_count; i++) {
1496 // entry offset is an offset from the stub start less than or
1497 // equal to end
1498 uint entry = *(uint*)addr(offset); offset += sizeof(uint);
1499 if (entry <= end) {
1500 // entry addresses may not address end but extras can
1501 assert(entry < end || i >= StubInfo::entry_count(stub_id),
1502 "entry offset 0x%x exceeds stub length 0x%x for stub %s",
1503 entry, end, StubInfo::name(stub_id));
1504 addresses.append(stub_start + entry);
1505 } else {
1506 // special case: entry encodes a nullptr
1507 assert(entry == AOTCodeCache::NULL_ADDRESS_MARKER, "stub %s entry offset %d lies beyond stub end %d and does not equal NULL_ADDRESS_MARKER", StubInfo::name(stub_id), entry, end);
1508 addresses.append(nullptr);
1509 }
1510 }
1511 if (log.is_enabled()) {
1512 log.print_cr("======== read stub %s and %d addresses up to offset %d",
1513 StubInfo::name(stub_id), 2 + entries_count, offset);
1514 }
1515 range.init_entry(address_base, 2 + entries_count);
1516 // move on to next stub or NO_STUBID
1517 stub_id = *(StubId*)addr(offset); offset += sizeof(StubId);
1518 }
1519 if (log.is_enabled()) {
1520 log.print_cr("======== Stub data ends at offset %d", offset);
1521 }
1522
1523 set_read_position(offset);
1524 }
1525
1526 void AOTCodeCache::publish_external_addresses(GrowableArray<address>& addresses) {
1527 DEBUG_ONLY( _passed_init2 = true; )
1528 if (opened_cache == nullptr) {
1529 return;
1530 }
1531
1532 cache()->_table->add_external_addresses(addresses);
1533 }
1534
1535 void AOTCodeCache::publish_stub_addresses(CodeBlob &code_blob, BlobId blob_id, AOTStubData *stub_data) {
1536 if (stub_data != nullptr) {
1537 // register all entries in stub
1538 assert(StubInfo::stub_count(blob_id) > 1,
1539 "multiple stub data provided for single stub blob %s",
1540 StubInfo::name(blob_id));
1541 assert(blob_id == stub_data->blob_id(),
1542 "blob id %s does not match id in stub data %s",
1543 StubInfo::name(blob_id),
1544 StubInfo::name(stub_data->blob_id()));
1545 // iterate over all stubs in the blob
1546 StubId stub_id = StubInfo::stub_base(blob_id);
1547 int stub_cnt = StubInfo::stub_count(blob_id);
1548 GrowableArray<address>& addresses = stub_data->address_array();
1549 for (int i = 0; i < stub_cnt; i++) {
1550 assert(stub_id != StubId::NO_STUBID, "sanity");
1551 StubAddrRange& range = stub_data->get_range(i);
1552 int base = range.start_index();
1553 if (base >= 0) {
1554 cache()->add_stub_entries(stub_id, addresses.at(base), &addresses, base + 2);
1555 }
1556 stub_id = StubInfo::next_in_blob(blob_id, stub_id);
1557 }
1558 // we should have exhausted all stub ids in the blob
1559 assert(stub_id == StubId::NO_STUBID, "sanity");
1560 } else {
1561 // register entry or entries for a single stub blob
1562 StubId stub_id = StubInfo::stub_base(blob_id);
1563 assert(StubInfo::stub_count(blob_id) == 1,
1564 "multiple stub blob %s provided without stub data",
1565 StubInfo::name(blob_id));
1566 address start = code_blob.code_begin();
1567 if (StubInfo::entry_count(stub_id) == 1) {
1568 assert(!code_blob.is_deoptimization_stub(), "expecting multiple entries for stub %s", StubInfo::name(stub_id));
1569 // register the blob base address as the only entry
1570 cache()->add_stub_entries(stub_id, start);
1571 } else {
1572 assert(code_blob.is_deoptimization_stub(), "only expecting one entry for stub %s", StubInfo::name(stub_id));
1573 DeoptimizationBlob *deopt_blob = code_blob.as_deoptimization_blob();
1574 assert(deopt_blob->unpack() == start, "unexpected offset 0x%x for deopt stub entry", (int)(deopt_blob->unpack() - start));
1575 GrowableArray<address> addresses;
1576 addresses.append(deopt_blob->unpack_with_exception());
1577 addresses.append(deopt_blob->unpack_with_reexecution());
1578 addresses.append(deopt_blob->unpack_with_exception_in_tls());
1579 cache()->add_stub_entries(stub_id, start, &addresses, 0);
1580 }
1581 }
1582 }
1583
1584 // ------------ process code and data --------------
1585
1586 // Can't use -1. It is valid value for jump to iteself destination
1587 // used by static call stub: see NativeJump::jump_destination().
1588 #define BAD_ADDRESS_ID -2
1589
1590 bool AOTCodeCache::write_relocations(CodeBlob& code_blob, RelocIterator& iter) {
1591 if (!align_write_int()) {
1592 return false;
1593 }
1594 GrowableArray<uint> reloc_data;
1595 LogStreamHandle(Trace, aot, codecache, reloc) log;
1596 while (iter.next()) {
1597 int idx = reloc_data.append(0); // default value
1598 switch (iter.type()) {
1599 case relocInfo::none:
1600 break;
1601 case relocInfo::runtime_call_type: {
1602 // Record offset of runtime destination
1603 CallRelocation* r = (CallRelocation*)iter.reloc();
1604 address dest = r->destination();
1605 if (dest == r->addr()) { // possible call via trampoline on Aarch64
1606 dest = (address)-1; // do nothing in this case when loading this relocation
1607 }
1608 int id = _table->id_for_address(dest, iter, &code_blob);
1609 if (id == BAD_ADDRESS_ID) {
1610 return false;
1611 }
1612 reloc_data.at_put(idx, id);
1613 break;
1614 }
1615 case relocInfo::runtime_call_w_cp_type:
1616 log_debug(aot, codecache, reloc)("runtime_call_w_cp_type relocation is not implemented");
1617 return false;
1618 case relocInfo::external_word_type: {
1619 // Record offset of runtime target
1620 address target = ((external_word_Relocation*)iter.reloc())->target();
1621 int id = _table->id_for_address(target, iter, &code_blob);
1622 if (id == BAD_ADDRESS_ID) {
1623 return false;
1624 }
1625 reloc_data.at_put(idx, id);
1626 break;
1627 }
1628 case relocInfo::internal_word_type:
1629 break;
1630 case relocInfo::section_word_type:
1631 break;
1632 case relocInfo::post_call_nop_type:
1633 break;
1634 default:
1635 log_debug(aot, codecache, reloc)("relocation %d unimplemented", (int)iter.type());
1636 return false;
1637 break;
1638 }
1639 if (log.is_enabled()) {
1640 iter.print_current_on(&log);
1641 }
1642 }
1643
1644 // Write additional relocation data: uint per relocation
1645 // Write the count first
1646 int count = reloc_data.length();
1647 write_bytes(&count, sizeof(int));
1648 if (log.is_enabled()) {
1649 log.print_cr("======== extra relocations count=%d", count);
1650 log.print( " {");
1651 }
1652 bool first = true;
1653 for (GrowableArrayIterator<uint> iter = reloc_data.begin();
1654 iter != reloc_data.end(); ++iter) {
1655 uint value = *iter;
1656 int n = write_bytes(&value, sizeof(uint));
1657 if (n != sizeof(uint)) {
1658 return false;
1659 }
1660 if (log.is_enabled()) {
1661 if (first) {
1662 first = false;
1663 log.print("%d", value);
1664 } else {
1665 log.print(", %d", value);
1666 }
1667 }
1668 }
1669 if (log.is_enabled()) {
1670 log.print_cr("}");
1671 }
1672 return true;
1673 }
1674
1675 void AOTCodeReader::fix_relocations(CodeBlob *code_blob, RelocIterator& iter) {
1676 uint offset = align_read_int();
1677 int reloc_count = *(int*)addr(offset);
1678 offset += sizeof(int);
1679 uint* reloc_data = (uint*)addr(offset);
1680 offset += (reloc_count * sizeof(uint));
1681 set_read_position(offset);
1682
1683 LogStreamHandle(Trace, aot, codecache, reloc) log;
1684 if (log.is_enabled()) {
1685 log.print_cr("======== extra relocations count=%d", reloc_count);
1686 log.print(" {");
1687 for(int i = 0; i < reloc_count; i++) {
1688 if (i == 0) {
1689 log.print("%d", reloc_data[i]);
1690 } else {
1691 log.print(", %d", reloc_data[i]);
1692 }
1693 }
1694 log.print_cr("}");
1695 }
1696
1697 int j = 0;
1698 while (iter.next()) {
1699 switch (iter.type()) {
1700 case relocInfo::none:
1701 break;
1702 case relocInfo::runtime_call_type: {
1703 address dest = _cache->address_for_id(reloc_data[j]);
1704 if (dest != (address)-1) {
1705 ((CallRelocation*)iter.reloc())->set_destination(dest);
1706 }
1707 break;
1708 }
1709 case relocInfo::runtime_call_w_cp_type:
1710 // this relocation should not be in cache (see write_relocations)
1711 assert(false, "runtime_call_w_cp_type relocation is not implemented");
1712 break;
1713 case relocInfo::external_word_type: {
1714 address target = _cache->address_for_id(reloc_data[j]);
1715 // Add external address to global table
1716 int index = ExternalsRecorder::find_index(target);
1717 // Update index in relocation
1718 Relocation::add_jint(iter.data(), index);
1719 external_word_Relocation* reloc = (external_word_Relocation*)iter.reloc();
1720 assert(reloc->target() == target, "sanity");
1721 reloc->set_value(target); // Patch address in the code
1722 break;
1723 }
1724 case relocInfo::internal_word_type: {
1725 internal_word_Relocation* r = (internal_word_Relocation*)iter.reloc();
1726 r->fix_relocation_after_aot_load(aot_code_entry()->dumptime_content_start_addr(), code_blob->content_begin());
1727 break;
1728 }
1729 case relocInfo::section_word_type: {
1730 section_word_Relocation* r = (section_word_Relocation*)iter.reloc();
1731 r->fix_relocation_after_aot_load(aot_code_entry()->dumptime_content_start_addr(), code_blob->content_begin());
1732 break;
1733 }
1734 case relocInfo::post_call_nop_type:
1735 break;
1736 default:
1737 assert(false,"relocation %d unimplemented", (int)iter.type());
1738 break;
1739 }
1740 if (log.is_enabled()) {
1741 iter.print_current_on(&log);
1742 }
1743 j++;
1744 }
1745 assert(j == reloc_count, "sanity");
1746 }
1747
1748 bool AOTCodeCache::write_oop_map_set(CodeBlob& cb) {
1749 if (!align_write_int()) {
1750 return false;
1751 }
1752 ImmutableOopMapSet* oopmaps = cb.oop_maps();
1753 int oopmaps_size = oopmaps->nr_of_bytes();
1754 if (!write_bytes(&oopmaps_size, sizeof(int))) {
1755 return false;
1756 }
1757 uint n = write_bytes(oopmaps, oopmaps->nr_of_bytes());
1758 if (n != (uint)oopmaps->nr_of_bytes()) {
1759 return false;
1760 }
1761 return true;
1762 }
1763
1764 ImmutableOopMapSet* AOTCodeReader::read_oop_map_set() {
1765 uint offset = align_read_int();
1766 int size = *(int *)addr(offset);
1767 offset += sizeof(int);
1768 ImmutableOopMapSet* oopmaps = (ImmutableOopMapSet *)addr(offset);
1769 offset += size;
1770 set_read_position(offset);
1771 return oopmaps;
1772 }
1773
1774 #ifndef PRODUCT
1775 bool AOTCodeCache::write_asm_remarks(CodeBlob& cb) {
1776 if (!align_write_int()) {
1777 return false;
1778 }
1779 // Write asm remarks
1780 uint* count_ptr = (uint *)reserve_bytes(sizeof(uint));
1781 if (count_ptr == nullptr) {
1782 return false;
1783 }
1784 uint count = 0;
1785 bool result = cb.asm_remarks().iterate([&] (uint offset, const char* str) -> bool {
1786 log_trace(aot, codecache, stubs)("asm remark offset=%d, str='%s'", offset, str);
1787 uint n = write_bytes(&offset, sizeof(uint));
1788 if (n != sizeof(uint)) {
1789 return false;
1790 }
1791 const char* cstr = add_C_string(str);
1792 int id = _table->id_for_C_string((address)cstr);
1793 assert(id != BAD_ADDRESS_ID, "asm remark string '%s' not found in AOTCodeAddressTable", str);
1794 n = write_bytes(&id, sizeof(int));
1795 if (n != sizeof(int)) {
1796 return false;
1797 }
1798 count += 1;
1799 return true;
1800 });
1801 *count_ptr = count;
1802 return result;
1803 }
1804
1805 void AOTCodeReader::read_asm_remarks(AsmRemarks& asm_remarks) {
1806 // Read asm remarks
1807 uint offset = align_read_int();
1808 uint count = *(uint *)addr(offset);
1809 offset += sizeof(uint);
1810 for (uint i = 0; i < count; i++) {
1811 uint remark_offset = *(uint *)addr(offset);
1812 offset += sizeof(uint);
1813 int remark_string_id = *(uint *)addr(offset);
1814 offset += sizeof(int);
1815 const char* remark = (const char*)_cache->address_for_C_string(remark_string_id);
1816 asm_remarks.insert(remark_offset, remark);
1817 }
1818 set_read_position(offset);
1819 }
1820
1821 bool AOTCodeCache::write_dbg_strings(CodeBlob& cb) {
1822 if (!align_write_int()) {
1823 return false;
1824 }
1825 // Write dbg strings
1826 uint* count_ptr = (uint *)reserve_bytes(sizeof(uint));
1827 if (count_ptr == nullptr) {
1828 return false;
1829 }
1830 uint count = 0;
1831 bool result = cb.dbg_strings().iterate([&] (const char* str) -> bool {
1832 log_trace(aot, codecache, stubs)("dbg string=%s", str);
1833 const char* cstr = add_C_string(str);
1834 int id = _table->id_for_C_string((address)cstr);
1835 assert(id != BAD_ADDRESS_ID, "db string '%s' not found in AOTCodeAddressTable", str);
1836 uint n = write_bytes(&id, sizeof(int));
1837 if (n != sizeof(int)) {
1838 return false;
1839 }
1840 count += 1;
1841 return true;
1842 });
1843 *count_ptr = count;
1844 return result;
1845 }
1846
1847 void AOTCodeReader::read_dbg_strings(DbgStrings& dbg_strings) {
1848 // Read dbg strings
1849 uint offset = align_read_int();
1850 uint count = *(uint *)addr(offset);
1851 offset += sizeof(uint);
1852 for (uint i = 0; i < count; i++) {
1853 int string_id = *(uint *)addr(offset);
1854 offset += sizeof(int);
1855 const char* str = (const char*)_cache->address_for_C_string(string_id);
1856 dbg_strings.insert(str);
1857 }
1858 set_read_position(offset);
1859 }
1860 #endif // PRODUCT
1861
1862 //======================= AOTCodeAddressTable ===============
1863
1864 // address table ids for generated routine entry adresses, external
1865 // addresses and C string addresses are partitioned into positive
1866 // integer ranges defined by the following positive base and max
1867 // values i.e. [_extrs_base, _extrs_base + _extrs_max -1],
1868 // [_stubs_base, _stubs_base + _stubs_max -1], [_c_str_base,
1869 // _c_str_base + _c_str_max -1],
1870
1871 #define _extrs_max 380
1872 #define _stubs_max static_cast<int>(EntryId::NUM_ENTRYIDS)
1873
1874 #define _extrs_base 0
1875 #define _stubs_base (_extrs_base + _extrs_max)
1876 #define _all_max (_stubs_base + _stubs_max)
1877
1878 // setter for external addresses and string addresses inserts new
1879 // addresses in the order they are encountered them which must remain
1880 // the same across an assembly run and subsequent production run
1881
1882 #define ADD_EXTERNAL_ADDRESS(addr) \
1883 { \
1884 hash_address((address) addr, _extrs_base + _extrs_length); \
1885 _extrs_addr[_extrs_length++] = (address) (addr); \
1886 assert(_extrs_length <= _extrs_max, "increase size"); \
1887 }
1888
1889 // insert into to the address hash table the index of an external
1890 // address or a stub address in the list of external or stub
1891 // addresses, respectively, keyed by the relevant address
1892
1893 void AOTCodeAddressTable::hash_address(address addr, int idx) {
1894 // only do this if we have a non-null address to record and the
1895 // cache is open for dumping
1896 if (addr == nullptr) {
1897 return;
1898 }
1899 // check opened_cache because this can be called before the cache is
1900 // properly initialized and only continue when dumping is enabled
1901 if (opened_cache != nullptr && opened_cache->for_dump()) {
1902 if (_hash_table == nullptr) {
1903 _hash_table = new (mtCode) AOTCodeAddressHashTable();
1904 }
1905 assert(_hash_table->get(addr) == nullptr, "repeated insert of address " INTPTR_FORMAT, p2i(addr));
1906 _hash_table->put(addr, idx);
1907 log_trace(aot, codecache)("Address " INTPTR_FORMAT " inserted into AOT Code Cache address hash table with index '%d'",
1908 p2i(addr), idx);
1909 }
1910 }
1911
1912 static bool initializing_extrs = false;
1913
1914 void AOTCodeAddressTable::init_extrs() {
1915 if (_extrs_complete || initializing_extrs) return; // Done already
1916
1917 initializing_extrs = true;
1918 _extrs_addr = NEW_C_HEAP_ARRAY(address, _extrs_max, mtCode);
1919
1920 _extrs_length = 0;
1921
1922 {
1923 // Required by initial stubs
1924 ADD_EXTERNAL_ADDRESS(SharedRuntime::exception_handler_for_return_address); // used by forward_exception
1925 ADD_EXTERNAL_ADDRESS(CompressedOops::base_addr()); // used by call_stub
1926 ADD_EXTERNAL_ADDRESS(Thread::current); // used by call_stub
1927 ADD_EXTERNAL_ADDRESS(SharedRuntime::throw_StackOverflowError);
1928 ADD_EXTERNAL_ADDRESS(SharedRuntime::throw_delayed_StackOverflowError);
1929 }
1930
1931 // Record addresses of VM runtime methods
1932 ADD_EXTERNAL_ADDRESS(SharedRuntime::fixup_callers_callsite);
1933 ADD_EXTERNAL_ADDRESS(SharedRuntime::handle_wrong_method);
1934 ADD_EXTERNAL_ADDRESS(SharedRuntime::handle_wrong_method_abstract);
1935 ADD_EXTERNAL_ADDRESS(SharedRuntime::handle_wrong_method_ic_miss);
1936 #if defined(AARCH64) && !defined(ZERO)
1937 ADD_EXTERNAL_ADDRESS(JavaThread::aarch64_get_thread_helper);
1938 ADD_EXTERNAL_ADDRESS(BarrierSetAssembler::patching_epoch_addr());
1939 #endif
1940
1941 #ifndef PRODUCT
1942 ADD_EXTERNAL_ADDRESS(&SharedRuntime::_jbyte_array_copy_ctr); // used by arraycopy stub on arm32 and x86_64
1943 ADD_EXTERNAL_ADDRESS(&SharedRuntime::_jshort_array_copy_ctr); // used by arraycopy stub
1944 ADD_EXTERNAL_ADDRESS(&SharedRuntime::_jint_array_copy_ctr); // used by arraycopy stub
1945 ADD_EXTERNAL_ADDRESS(&SharedRuntime::_jlong_array_copy_ctr); // used by arraycopy stub
1946 ADD_EXTERNAL_ADDRESS(&SharedRuntime::_oop_array_copy_ctr); // used by arraycopy stub
1947 ADD_EXTERNAL_ADDRESS(&SharedRuntime::_checkcast_array_copy_ctr); // used by arraycopy stub
1948 ADD_EXTERNAL_ADDRESS(&SharedRuntime::_unsafe_array_copy_ctr); // used by arraycopy stub
1949 ADD_EXTERNAL_ADDRESS(&SharedRuntime::_generic_array_copy_ctr); // used by arraycopy stub
1950 ADD_EXTERNAL_ADDRESS(&SharedRuntime::_unsafe_set_memory_ctr); // used by arraycopy stub
1951 #endif /* PRODUCT */
1952
1953 ADD_EXTERNAL_ADDRESS(SharedRuntime::enable_stack_reserved_zone);
1954
1955 #if defined(AMD64) && !defined(ZERO)
1956 ADD_EXTERNAL_ADDRESS(SharedRuntime::montgomery_multiply);
1957 ADD_EXTERNAL_ADDRESS(SharedRuntime::montgomery_square);
1958 #endif // defined(AMD64) && !defined(ZERO)
1959
1960 ADD_EXTERNAL_ADDRESS(SharedRuntime::d2f);
1961 ADD_EXTERNAL_ADDRESS(SharedRuntime::d2i);
1962 ADD_EXTERNAL_ADDRESS(SharedRuntime::d2l);
1963 ADD_EXTERNAL_ADDRESS(SharedRuntime::dcos);
1964 ADD_EXTERNAL_ADDRESS(SharedRuntime::dexp);
1965 ADD_EXTERNAL_ADDRESS(SharedRuntime::dlog);
1966 ADD_EXTERNAL_ADDRESS(SharedRuntime::dlog10);
1967 ADD_EXTERNAL_ADDRESS(SharedRuntime::dpow);
1968 #ifndef ZERO
1969 ADD_EXTERNAL_ADDRESS(SharedRuntime::drem);
1970 #endif
1971 ADD_EXTERNAL_ADDRESS(SharedRuntime::dsin);
1972 ADD_EXTERNAL_ADDRESS(SharedRuntime::dtan);
1973 ADD_EXTERNAL_ADDRESS(SharedRuntime::f2i);
1974 ADD_EXTERNAL_ADDRESS(SharedRuntime::f2l);
1975 #ifndef ZERO
1976 ADD_EXTERNAL_ADDRESS(SharedRuntime::frem);
1977 #endif
1978 ADD_EXTERNAL_ADDRESS(SharedRuntime::l2d);
1979 ADD_EXTERNAL_ADDRESS(SharedRuntime::l2f);
1980 ADD_EXTERNAL_ADDRESS(SharedRuntime::ldiv);
1981 ADD_EXTERNAL_ADDRESS(SharedRuntime::lmul);
1982 ADD_EXTERNAL_ADDRESS(SharedRuntime::lrem);
1983
1984 #if INCLUDE_JVMTI
1985 ADD_EXTERNAL_ADDRESS(&JvmtiExport::_should_notify_object_alloc);
1986 #endif /* INCLUDE_JVMTI */
1987
1988 ADD_EXTERNAL_ADDRESS(ThreadIdentifier::unsafe_offset());
1989 // already added
1990 // ADD_EXTERNAL_ADDRESS(Thread::current);
1991
1992 ADD_EXTERNAL_ADDRESS(os::javaTimeMillis);
1993 ADD_EXTERNAL_ADDRESS(os::javaTimeNanos);
1994 #ifndef PRODUCT
1995 ADD_EXTERNAL_ADDRESS(os::breakpoint);
1996 #endif
1997
1998 ADD_EXTERNAL_ADDRESS(StubRoutines::crc_table_addr());
1999 #ifndef PRODUCT
2000 ADD_EXTERNAL_ADDRESS(&SharedRuntime::_partial_subtype_ctr);
2001 #endif
2002
2003 #if INCLUDE_JFR
2004 ADD_EXTERNAL_ADDRESS(JfrIntrinsicSupport::write_checkpoint);
2005 ADD_EXTERNAL_ADDRESS(JfrIntrinsicSupport::return_lease);
2006 #endif
2007
2008 ADD_EXTERNAL_ADDRESS(UpcallLinker::handle_uncaught_exception); // used by upcall_stub_exception_handler
2009
2010 {
2011 // Required by Shared blobs
2012 ADD_EXTERNAL_ADDRESS(Deoptimization::fetch_unroll_info);
2013 ADD_EXTERNAL_ADDRESS(Deoptimization::unpack_frames);
2014 ADD_EXTERNAL_ADDRESS(SafepointSynchronize::handle_polling_page_exception);
2015 ADD_EXTERNAL_ADDRESS(SharedRuntime::resolve_opt_virtual_call_C);
2016 ADD_EXTERNAL_ADDRESS(SharedRuntime::resolve_virtual_call_C);
2017 ADD_EXTERNAL_ADDRESS(SharedRuntime::resolve_static_call_C);
2018 // already added
2019 // ADD_EXTERNAL_ADDRESS(SharedRuntime::throw_delayed_StackOverflowError);
2020 ADD_EXTERNAL_ADDRESS(SharedRuntime::throw_AbstractMethodError);
2021 ADD_EXTERNAL_ADDRESS(SharedRuntime::throw_IncompatibleClassChangeError);
2022 ADD_EXTERNAL_ADDRESS(SharedRuntime::throw_NullPointerException_at_call);
2023 }
2024
2025 #ifdef COMPILER1
2026 {
2027 // Required by C1 blobs
2028 ADD_EXTERNAL_ADDRESS(static_cast<int (*)(oopDesc*)>(SharedRuntime::dtrace_object_alloc));
2029 ADD_EXTERNAL_ADDRESS(SharedRuntime::register_finalizer);
2030 ADD_EXTERNAL_ADDRESS(Runtime1::is_instance_of);
2031 ADD_EXTERNAL_ADDRESS(Runtime1::exception_handler_for_pc);
2032 ADD_EXTERNAL_ADDRESS(Runtime1::check_abort_on_vm_exception);
2033 ADD_EXTERNAL_ADDRESS(Runtime1::new_instance);
2034 ADD_EXTERNAL_ADDRESS(Runtime1::counter_overflow);
2035 ADD_EXTERNAL_ADDRESS(Runtime1::new_type_array);
2036 ADD_EXTERNAL_ADDRESS(Runtime1::new_object_array);
2037 ADD_EXTERNAL_ADDRESS(Runtime1::new_multi_array);
2038 ADD_EXTERNAL_ADDRESS(Runtime1::throw_range_check_exception);
2039 ADD_EXTERNAL_ADDRESS(Runtime1::throw_index_exception);
2040 ADD_EXTERNAL_ADDRESS(Runtime1::throw_div0_exception);
2041 ADD_EXTERNAL_ADDRESS(Runtime1::throw_null_pointer_exception);
2042 ADD_EXTERNAL_ADDRESS(Runtime1::throw_array_store_exception);
2043 ADD_EXTERNAL_ADDRESS(Runtime1::throw_class_cast_exception);
2044 ADD_EXTERNAL_ADDRESS(Runtime1::throw_incompatible_class_change_error);
2045 ADD_EXTERNAL_ADDRESS(Runtime1::monitorenter);
2046 ADD_EXTERNAL_ADDRESS(Runtime1::monitorexit);
2047 ADD_EXTERNAL_ADDRESS(Runtime1::deoptimize);
2048 ADD_EXTERNAL_ADDRESS(Runtime1::access_field_patching);
2049 ADD_EXTERNAL_ADDRESS(Runtime1::move_klass_patching);
2050 ADD_EXTERNAL_ADDRESS(Runtime1::move_mirror_patching);
2051 ADD_EXTERNAL_ADDRESS(Runtime1::move_appendix_patching);
2052 ADD_EXTERNAL_ADDRESS(Runtime1::predicate_failed_trap);
2053 ADD_EXTERNAL_ADDRESS(Runtime1::unimplemented_entry);
2054 // already added
2055 // ADD_EXTERNAL_ADDRESS(Thread::current);
2056 ADD_EXTERNAL_ADDRESS(CompressedKlassPointers::base_addr());
2057 }
2058 #endif
2059
2060 #ifdef COMPILER2
2061 {
2062 // Required by C2 blobs
2063 ADD_EXTERNAL_ADDRESS(Deoptimization::uncommon_trap);
2064 ADD_EXTERNAL_ADDRESS(OptoRuntime::handle_exception_C);
2065 ADD_EXTERNAL_ADDRESS(OptoRuntime::new_instance_C);
2066 ADD_EXTERNAL_ADDRESS(OptoRuntime::new_array_C);
2067 ADD_EXTERNAL_ADDRESS(OptoRuntime::new_array_nozero_C);
2068 ADD_EXTERNAL_ADDRESS(OptoRuntime::multianewarray2_C);
2069 ADD_EXTERNAL_ADDRESS(OptoRuntime::multianewarray3_C);
2070 ADD_EXTERNAL_ADDRESS(OptoRuntime::multianewarray4_C);
2071 ADD_EXTERNAL_ADDRESS(OptoRuntime::multianewarray5_C);
2072 ADD_EXTERNAL_ADDRESS(OptoRuntime::multianewarrayN_C);
2073 ADD_EXTERNAL_ADDRESS(OptoRuntime::complete_monitor_locking_C);
2074 ADD_EXTERNAL_ADDRESS(OptoRuntime::monitor_notify_C);
2075 ADD_EXTERNAL_ADDRESS(OptoRuntime::monitor_notifyAll_C);
2076 ADD_EXTERNAL_ADDRESS(OptoRuntime::rethrow_C);
2077 ADD_EXTERNAL_ADDRESS(OptoRuntime::slow_arraycopy_C);
2078 ADD_EXTERNAL_ADDRESS(OptoRuntime::register_finalizer_C);
2079 ADD_EXTERNAL_ADDRESS(OptoRuntime::vthread_end_first_transition_C);
2080 ADD_EXTERNAL_ADDRESS(OptoRuntime::vthread_start_final_transition_C);
2081 ADD_EXTERNAL_ADDRESS(OptoRuntime::vthread_start_transition_C);
2082 ADD_EXTERNAL_ADDRESS(OptoRuntime::vthread_end_transition_C);
2083 // already added for
2084 #if defined(AARCH64) && ! defined(PRODUCT)
2085 ADD_EXTERNAL_ADDRESS(JavaThread::verify_cross_modify_fence_failure);
2086 #endif // AARCH64 && !PRODUCT
2087 }
2088 #endif // COMPILER2
2089
2090 #if INCLUDE_G1GC
2091 ADD_EXTERNAL_ADDRESS(G1BarrierSetRuntime::write_ref_field_pre_entry);
2092 ADD_EXTERNAL_ADDRESS(G1BarrierSetRuntime::write_ref_array_pre_narrow_oop_entry); // used by arraycopy stubs
2093 ADD_EXTERNAL_ADDRESS(G1BarrierSetRuntime::write_ref_array_pre_oop_entry); // used by arraycopy stubs
2094 ADD_EXTERNAL_ADDRESS(G1BarrierSetRuntime::write_ref_array_post_entry); // used by arraycopy stubs
2095 ADD_EXTERNAL_ADDRESS(BarrierSetNMethod::nmethod_stub_entry_barrier); // used by method_entry_barrier
2096
2097 #endif
2098 #if INCLUDE_SHENANDOAHGC
2099 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::write_barrier_pre);
2100 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::write_barrier_pre_narrow);
2101 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::load_reference_barrier_strong);
2102 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::load_reference_barrier_strong_narrow);
2103 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::load_reference_barrier_strong_narrow_narrow);
2104 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::load_reference_barrier_weak);
2105 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::load_reference_barrier_weak_narrow);
2106 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::load_reference_barrier_weak_narrow_narrow);
2107 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::load_reference_barrier_phantom);
2108 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::load_reference_barrier_phantom_narrow);
2109 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::load_reference_barrier_phantom_narrow_narrow);
2110 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::arraycopy_barrier_oop);
2111 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::arraycopy_barrier_narrow_oop);
2112 ADD_EXTERNAL_ADDRESS(ShenandoahRuntime::clone);
2113 #endif
2114 #if INCLUDE_ZGC
2115 ADD_EXTERNAL_ADDRESS(ZBarrierSetRuntime::load_barrier_on_oop_field_preloaded_addr());
2116 ADD_EXTERNAL_ADDRESS(ZBarrierSetRuntime::load_barrier_on_oop_field_preloaded_store_good_addr());
2117 ADD_EXTERNAL_ADDRESS(ZBarrierSetRuntime::load_barrier_on_weak_oop_field_preloaded_addr());
2118 ADD_EXTERNAL_ADDRESS(ZBarrierSetRuntime::load_barrier_on_phantom_oop_field_preloaded_addr());
2119 ADD_EXTERNAL_ADDRESS(ZBarrierSetRuntime::no_keepalive_load_barrier_on_weak_oop_field_preloaded_addr());
2120 ADD_EXTERNAL_ADDRESS(ZBarrierSetRuntime::no_keepalive_load_barrier_on_phantom_oop_field_preloaded_addr());
2121 ADD_EXTERNAL_ADDRESS(ZBarrierSetRuntime::store_barrier_on_oop_field_with_healing_addr());
2122 ADD_EXTERNAL_ADDRESS(ZBarrierSetRuntime::store_barrier_on_oop_field_without_healing_addr());
2123 ADD_EXTERNAL_ADDRESS(ZBarrierSetRuntime::no_keepalive_store_barrier_on_oop_field_without_healing_addr());
2124 ADD_EXTERNAL_ADDRESS(ZBarrierSetRuntime::store_barrier_on_native_oop_field_without_healing_addr());
2125 ADD_EXTERNAL_ADDRESS(ZBarrierSetRuntime::load_barrier_on_oop_array_addr());
2126
2127 ADD_EXTERNAL_ADDRESS(ZPointerVectorLoadBadMask);
2128 ADD_EXTERNAL_ADDRESS(ZPointerVectorStoreBadMask);
2129 ADD_EXTERNAL_ADDRESS(ZPointerVectorStoreGoodMask);
2130 #if defined(AMD64)
2131 ADD_EXTERNAL_ADDRESS(&ZPointerLoadShift);
2132 ADD_EXTERNAL_ADDRESS(&ZPointerLoadShiftTable);
2133 #endif
2134 #endif
2135 #ifndef ZERO
2136 #if defined(AMD64) || defined(AARCH64) || defined(RISCV64)
2137 ADD_EXTERNAL_ADDRESS(MacroAssembler::debug64);
2138 #endif // defined(AMD64) || defined(AARCH64) || defined(RISCV64)
2139 #if defined(AMD64)
2140 ADD_EXTERNAL_ADDRESS(warning);
2141 #endif // defined(AMD64)
2142 #endif // ZERO
2143
2144 // addresses of fields in AOT runtime constants area
2145 address* p = AOTRuntimeConstants::field_addresses_list();
2146 while (*p != nullptr) {
2147 address to_add = (address)*p++;
2148 ADD_EXTERNAL_ADDRESS(to_add);
2149 }
2150
2151 log_debug(aot, codecache, init)("External addresses opened and recorded");
2152 // allocate storage for stub entries
2153 _stubs_addr = NEW_C_HEAP_ARRAY(address, _stubs_max, mtCode);
2154 log_debug(aot, codecache, init)("Stub addresses opened");
2155 }
2156
2157 void AOTCodeAddressTable::init_extrs2() {
2158 assert(initializing_extrs && !_extrs_complete,
2159 "invalid sequence for init_extrs2");
2160
2161 {
2162 ADD_EXTERNAL_ADDRESS(Continuation::prepare_thaw); // used by cont_thaw
2163 ADD_EXTERNAL_ADDRESS(Continuation::thaw_entry()); // used by cont_thaw
2164 ADD_EXTERNAL_ADDRESS(ContinuationEntry::thaw_call_pc_address()); // used by cont_preempt_stub
2165 }
2166 _extrs_complete = true;
2167 initializing_extrs = false;
2168 log_debug(aot, codecache, init)("External addresses recorded and closed");
2169 }
2170
2171 void AOTCodeAddressTable::add_external_addresses(GrowableArray<address>& addresses) {
2172 assert(initializing_extrs && !_extrs_complete,
2173 "invalid sequence for add_external_addresses");
2174 for (int i = 0; i < addresses.length(); i++) {
2175 ADD_EXTERNAL_ADDRESS(addresses.at(i));
2176 }
2177 log_debug(aot, codecache, init)("Recorded %d additional external addresses",
2178 addresses.length());
2179 }
2180
2181 void AOTCodeAddressTable::add_stub_entry(EntryId entry_id, address a) {
2182 assert(_extrs_complete || initializing_extrs,
2183 "recording stub entry address before external addresses complete");
2184 assert(!(StubInfo::is_shared(StubInfo::stub(entry_id)) && _shared_stubs_complete), "too late to add shared entry");
2185 assert(!(StubInfo::is_stubgen(StubInfo::stub(entry_id)) && _stubgen_stubs_complete), "too late to add stubgen entry");
2186 assert(!(StubInfo::is_c1(StubInfo::stub(entry_id)) && _c1_stubs_complete), "too late to add c1 entry");
2187 assert(!(StubInfo::is_c2(StubInfo::stub(entry_id)) && _c2_stubs_complete), "too late to add c2 entry");
2188 log_debug(aot, stubs)("Recording address 0x%p for %s entry %s", a, StubInfo::name(StubInfo::stubgroup(entry_id)), StubInfo::name(entry_id));
2189 int idx = static_cast<int>(entry_id);
2190 hash_address(a, _stubs_base + idx);
2191 _stubs_addr[idx] = a;
2192 }
2193
2194 void AOTCodeAddressTable::set_shared_stubs_complete() {
2195 assert(!_shared_stubs_complete, "repeated close for shared stubs!");
2196 _shared_stubs_complete = true;
2197 log_debug(aot, codecache, init)("Shared stubs closed");
2198 }
2199
2200 void AOTCodeAddressTable::set_c1_stubs_complete() {
2201 assert(!_c1_stubs_complete, "repeated close for c1 stubs!");
2202 _c1_stubs_complete = true;
2203 log_debug(aot, codecache, init)("C1 stubs closed");
2204 }
2205
2206 void AOTCodeAddressTable::set_c2_stubs_complete() {
2207 assert(!_c2_stubs_complete, "repeated close for c2 stubs!");
2208 _c2_stubs_complete = true;
2209 log_debug(aot, codecache, init)("C2 stubs closed");
2210 }
2211
2212 void AOTCodeAddressTable::set_stubgen_stubs_complete() {
2213 assert(!_stubgen_stubs_complete, "repeated close for stubgen stubs!");
2214 _stubgen_stubs_complete = true;
2215 log_debug(aot, codecache, init)("StubGen stubs closed");
2216 }
2217
2218 #ifdef PRODUCT
2219 #define MAX_STR_COUNT 200
2220 #else
2221 #define MAX_STR_COUNT 2000
2222 #endif
2223 #define _c_str_max MAX_STR_COUNT
2224 static const int _c_str_base = _all_max;
2225
2226 static const char* _C_strings_in[MAX_STR_COUNT] = {nullptr}; // Incoming strings
2227 static const char* _C_strings[MAX_STR_COUNT] = {nullptr}; // Our duplicates
2228 static int _C_strings_count = 0;
2229 static int _C_strings_s[MAX_STR_COUNT] = {0};
2230 static int _C_strings_id[MAX_STR_COUNT] = {0};
2231 static int _C_strings_used = 0;
2232
2233 void AOTCodeCache::load_strings() {
2234 uint strings_count = _load_header->strings_count();
2235 if (strings_count == 0) {
2236 return;
2237 }
2238 if (strings_count > MAX_STR_COUNT) {
2239 fatal("Invalid strings_count loaded from AOT Code Cache: %d > MAX_STR_COUNT [%d]", strings_count, MAX_STR_COUNT);
2240 return;
2241 }
2242 uint strings_offset = _load_header->strings_offset();
2243 uint* string_lengths = (uint*)addr(strings_offset);
2244 strings_offset += (strings_count * sizeof(uint));
2245 uint strings_size = _load_header->entries_offset() - strings_offset;
2246 // We have to keep cached strings longer than _cache buffer
2247 // because they are refernced from compiled code which may
2248 // still be executed on VM exit after _cache is freed.
2249 char* p = NEW_C_HEAP_ARRAY(char, strings_size+1, mtCode);
2250 memcpy(p, addr(strings_offset), strings_size);
2251 _C_strings_buf = p;
2252 for (uint i = 0; i < strings_count; i++) {
2253 _C_strings[i] = p;
2254 uint len = string_lengths[i];
2255 _C_strings_s[i] = i;
2256 _C_strings_id[i] = i;
2257 log_trace(aot, codecache, stringtable)("load_strings: _C_strings[%d] " INTPTR_FORMAT " '%s'", i, p2i(p), p);
2258 p += len;
2259 }
2260 assert((uint)(p - _C_strings_buf) <= strings_size, "(" INTPTR_FORMAT " - " INTPTR_FORMAT ") = %d > %d ", p2i(p), p2i(_C_strings_buf), (uint)(p - _C_strings_buf), strings_size);
2261 _C_strings_count = strings_count;
2262 _C_strings_used = strings_count;
2263 log_debug(aot, codecache, init)(" Loaded %d C strings of total length %d at offset %d from AOT Code Cache", _C_strings_count, strings_size, strings_offset);
2264 }
2265
2266 int AOTCodeCache::store_strings() {
2267 if (_C_strings_used > 0) {
2268 MutexLocker ml(AOTCodeCStrings_lock, Mutex::_no_safepoint_check_flag);
2269 uint offset = _write_position;
2270 uint length = 0;
2271 uint* lengths = (uint *)reserve_bytes(sizeof(uint) * _C_strings_used);
2272 if (lengths == nullptr) {
2273 return -1;
2274 }
2275 for (int i = 0; i < _C_strings_used; i++) {
2276 const char* str = _C_strings[_C_strings_s[i]];
2277 log_trace(aot, codecache, stringtable)("store_strings: _C_strings[%d] " INTPTR_FORMAT " '%s'", i, p2i(str), str);
2278 uint len = (uint)strlen(str) + 1;
2279 length += len;
2280 assert(len < 1000, "big string: %s", str);
2281 lengths[i] = len;
2282 uint n = write_bytes(str, len);
2283 if (n != len) {
2284 return -1;
2285 }
2286 }
2287 log_debug(aot, codecache, exit)(" Wrote %d C strings of total length %d at offset %d to AOT Code Cache",
2288 _C_strings_used, length, offset);
2289 }
2290 return _C_strings_used;
2291 }
2292
2293 const char* AOTCodeCache::add_C_string(const char* str) {
2294 if (is_on_for_dump() && str != nullptr) {
2295 MutexLocker ml(AOTCodeCStrings_lock, Mutex::_no_safepoint_check_flag);
2296 AOTCodeAddressTable* table = addr_table();
2297 if (table != nullptr) {
2298 return table->add_C_string(str);
2299 }
2300 }
2301 return str;
2302 }
2303
2304 const char* AOTCodeAddressTable::add_C_string(const char* str) {
2305 if (_extrs_complete || initializing_extrs) {
2306 // Check previous strings address
2307 for (int i = 0; i < _C_strings_count; i++) {
2308 if (_C_strings_in[i] == str) {
2309 return _C_strings[i]; // Found previous one - return our duplicate
2310 } else if (strcmp(_C_strings[i], str) == 0) {
2311 return _C_strings[i];
2312 }
2313 }
2314 // Add new one
2315 if (_C_strings_count < MAX_STR_COUNT) {
2316 // Passed in string can be freed and used space become inaccessible.
2317 // Keep original address but duplicate string for future compare.
2318 _C_strings_id[_C_strings_count] = -1; // Init
2319 _C_strings_in[_C_strings_count] = str;
2320 const char* dup = os::strdup(str);
2321 _C_strings[_C_strings_count++] = dup;
2322 log_trace(aot, codecache, stringtable)("add_C_string: [%d] " INTPTR_FORMAT " '%s'", _C_strings_count, p2i(dup), dup);
2323 return dup;
2324 } else {
2325 assert(false, "Number of C strings >= MAX_STR_COUNT");
2326 }
2327 }
2328 return str;
2329 }
2330
2331 int AOTCodeAddressTable::id_for_C_string(address str) {
2332 if (str == nullptr) {
2333 return BAD_ADDRESS_ID;
2334 }
2335 MutexLocker ml(AOTCodeCStrings_lock, Mutex::_no_safepoint_check_flag);
2336 for (int i = 0; i < _C_strings_count; i++) {
2337 if (_C_strings[i] == (const char*)str) { // found
2338 int id = _C_strings_id[i];
2339 if (id >= 0) {
2340 assert(id < _C_strings_used, "%d >= %d", id , _C_strings_used);
2341 return id; // Found recorded
2342 }
2343 log_trace(aot, codecache, stringtable)("id_for_C_string: _C_strings[%d ==> %d] " INTPTR_FORMAT " '%s'", i, _C_strings_used, p2i(str), str);
2344 // Not found in recorded, add new
2345 id = _C_strings_used++;
2346 _C_strings_s[id] = i;
2347 _C_strings_id[i] = id;
2348 return id;
2349 }
2350 }
2351 return BAD_ADDRESS_ID;
2352 }
2353
2354 address AOTCodeAddressTable::address_for_C_string(int idx) {
2355 assert(idx < _C_strings_count, "sanity");
2356 return (address)_C_strings[idx];
2357 }
2358
2359 static int search_address(address addr, address* table, uint length) {
2360 for (int i = 0; i < (int)length; i++) {
2361 if (table[i] == addr) {
2362 return i;
2363 }
2364 }
2365 return BAD_ADDRESS_ID;
2366 }
2367
2368 address AOTCodeAddressTable::address_for_id(int idx) {
2369 assert(_extrs_complete || initializing_extrs, "AOT Code Cache VM runtime addresses table is not complete");
2370 if (idx == -1) {
2371 return (address)-1;
2372 }
2373 uint id = (uint)idx;
2374 // special case for symbols based relative to os::init
2375 if (id > (_c_str_base + _c_str_max)) {
2376 return (address)os::init + idx;
2377 }
2378 if (idx < 0) {
2379 fatal("Incorrect id %d for AOT Code Cache addresses table", id);
2380 return nullptr;
2381 }
2382 // no need to compare unsigned id against 0
2383 if (/* id >= _extrs_base && */ id < _extrs_length) {
2384 return _extrs_addr[id - _extrs_base];
2385 }
2386 if (id >= _stubs_base && id < _c_str_base) {
2387 return _stubs_addr[id - _stubs_base];
2388 }
2389 if (id >= _c_str_base && id < (_c_str_base + (uint)_C_strings_count)) {
2390 return address_for_C_string(id - _c_str_base);
2391 }
2392 fatal("Incorrect id %d for AOT Code Cache addresses table", id);
2393 return nullptr;
2394 }
2395
2396 int AOTCodeAddressTable::id_for_address(address addr, RelocIterator reloc, CodeBlob* code_blob) {
2397 assert(_extrs_complete || initializing_extrs, "AOT Code Cache VM runtime addresses table is not complete");
2398 int id = -1;
2399 if (addr == (address)-1) { // Static call stub has jump to itself
2400 return id;
2401 }
2402 // fast path for stubs and external addresses
2403 if (_hash_table != nullptr) {
2404 int *result = _hash_table->get(addr);
2405 if (result != nullptr) {
2406 id = *result;
2407 log_trace(aot, codecache)("Address " INTPTR_FORMAT " retrieved from AOT Code Cache address hash table with index '%d'",
2408 p2i(addr), id);
2409 return id;
2410 }
2411 }
2412 // Seach for C string
2413 id = id_for_C_string(addr);
2414 if (id != BAD_ADDRESS_ID) {
2415 return id + _c_str_base;
2416 }
2417 if (StubRoutines::contains(addr) || CodeCache::find_blob(addr) != nullptr) {
2418 // Search for a matching stub entry
2419 id = search_address(addr, _stubs_addr, _stubs_max);
2420 if (id == BAD_ADDRESS_ID) {
2421 StubCodeDesc* desc = StubCodeDesc::desc_for(addr);
2422 if (desc == nullptr) {
2423 desc = StubCodeDesc::desc_for(addr + frame::pc_return_offset);
2424 }
2425 const char* sub_name = (desc != nullptr) ? desc->name() : "<unknown>";
2426 assert(false, "Address " INTPTR_FORMAT " for Stub:%s is missing in AOT Code Cache addresses table", p2i(addr), sub_name);
2427 } else {
2428 return id + _stubs_base;
2429 }
2430 } else {
2431 // Search in runtime functions
2432 id = search_address(addr, _extrs_addr, _extrs_length);
2433 if (id == BAD_ADDRESS_ID) {
2434 ResourceMark rm;
2435 const int buflen = 1024;
2436 char* func_name = NEW_RESOURCE_ARRAY(char, buflen);
2437 int offset = 0;
2438 if (os::dll_address_to_function_name(addr, func_name, buflen, &offset)) {
2439 if (offset > 0) {
2440 // Could be address of C string
2441 uint dist = (uint)pointer_delta(addr, (address)os::init, 1);
2442 log_debug(aot, codecache)("Address " INTPTR_FORMAT " (offset %d) for runtime target '%s' is missing in AOT Code Cache addresses table",
2443 p2i(addr), dist, (const char*)addr);
2444 assert(dist > (uint)(_all_max + MAX_STR_COUNT), "change encoding of distance");
2445 return dist;
2446 }
2447 #ifdef ASSERT
2448 reloc.print_current_on(tty);
2449 code_blob->print_on(tty);
2450 code_blob->print_code_on(tty);
2451 assert(false, "Address " INTPTR_FORMAT " for runtime target '%s+%d' is missing in AOT Code Cache addresses table", p2i(addr), func_name, offset);
2452 #endif
2453 } else {
2454 #ifdef ASSERT
2455 reloc.print_current_on(tty);
2456 code_blob->print_on(tty);
2457 code_blob->print_code_on(tty);
2458 os::find(addr, tty);
2459 assert(false, "Address " INTPTR_FORMAT " for <unknown>/('%s') is missing in AOT Code Cache addresses table", p2i(addr), (const char*)addr);
2460 #endif
2461 }
2462 } else {
2463 return _extrs_base + id;
2464 }
2465 }
2466 return id;
2467 }
2468
2469 AOTRuntimeConstants AOTRuntimeConstants::_aot_runtime_constants;
2470
2471 void AOTRuntimeConstants::initialize_from_runtime() {
2472 BarrierSet* bs = BarrierSet::barrier_set();
2473 address card_table_base = nullptr;
2474 uint grain_shift = 0;
2475 address cset_base = nullptr;
2476 #if INCLUDE_G1GC
2477 if (bs->is_a(BarrierSet::G1BarrierSet)) {
2478 grain_shift = G1HeapRegion::LogOfHRGrainBytes;
2479 } else
2480 #endif
2481 #if INCLUDE_SHENANDOAHGC
2482 if (bs->is_a(BarrierSet::ShenandoahBarrierSet)) {
2483 grain_shift = ShenandoahHeapRegion::region_size_bytes_shift_jint();
2484 cset_base = ShenandoahHeap::in_cset_fast_test_addr();
2485 } else
2486 #endif
2487 if (bs->is_a(BarrierSet::CardTableBarrierSet)) {
2488 CardTable::CardValue* base = ci_card_table_address_const();
2489 assert(base != nullptr, "unexpected byte_map_base");
2490 card_table_base = base;
2491 CardTableBarrierSet* ctbs = barrier_set_cast<CardTableBarrierSet>(bs);
2492 grain_shift = ctbs->grain_shift();
2493 }
2494 _aot_runtime_constants._card_table_base = card_table_base;
2495 _aot_runtime_constants._grain_shift = grain_shift;
2496 _aot_runtime_constants._cset_base = cset_base;
2497 }
2498
2499 address AOTRuntimeConstants::_field_addresses_list[] = {
2500 ((address)&_aot_runtime_constants._card_table_base),
2501 ((address)&_aot_runtime_constants._grain_shift),
2502 ((address)&_aot_runtime_constants._cset_base),
2503 nullptr
2504 };
2505
2506 address AOTRuntimeConstants::card_table_base_address() {
2507 assert(UseSerialGC || UseParallelGC, "Only these GCs have constant card table base");
2508 return (address)&_aot_runtime_constants._card_table_base;
2509 }
2510
2511 // This is called after initialize() but before init2()
2512 // and _cache is not set yet.
2513 void AOTCodeCache::print_on(outputStream* st) {
2514 if (opened_cache != nullptr && opened_cache->for_use()) {
2515 st->print_cr("\nAOT Code Cache");
2516 uint count = opened_cache->_load_header->entries_count();
2517 uint* search_entries = (uint*)opened_cache->addr(opened_cache->_load_header->entries_offset()); // [id, index]
2518 AOTCodeEntry* load_entries = (AOTCodeEntry*)(search_entries + 2 * count);
2519
2520 for (uint i = 0; i < count; i++) {
2521 // Use search_entries[] to order ouput
2522 int index = search_entries[2*i + 1];
2523 AOTCodeEntry* entry = &(load_entries[index]);
2524
2525 uint entry_position = entry->offset();
2526 uint name_offset = entry->name_offset() + entry_position;
2527 const char* saved_name = opened_cache->addr(name_offset);
2528
2529 st->print_cr("%4u: %10s idx:%4u Id:%u size=%u '%s'",
2530 i, aot_code_entry_kind_name[entry->kind()], index, entry->id(), entry->size(), saved_name);
2531 }
2532 }
2533 }
2534
2535 // methods for managing entries in multi-stub blobs
2536
2537
2538 AOTStubData::AOTStubData(BlobId blob_id) :
2539 _blob_id(blob_id),
2540 _cached_blob(nullptr),
2541 _stub_cnt(0),
2542 _ranges(nullptr),
2543 _flags(0) {
2544 assert(StubInfo::is_stubgen(blob_id),
2545 "AOTStubData expects a multi-stub blob not %s",
2546 StubInfo::name(blob_id));
2547
2548 // we cannot save or restore preuniversestubs because the cache
2549 // cannot be accessed before initialising the universe
2550 if (blob_id == BlobId::stubgen_preuniverse_id) {
2551 // invalidate any attempt to use this
2552 _flags = INVALID;
2553 return;
2554 }
2555 if (AOTCodeCache::is_on()) {
2556 _flags = OPEN;
2557 // allow update of stub entry addresses
2558 if (AOTCodeCache::is_using_stub()) {
2559 // allow stub loading
2560 _flags |= USING;
2561 }
2562 if (AOTCodeCache::is_dumping_stub()) {
2563 // allow stub saving
2564 _flags |= DUMPING;
2565 }
2566 // we need to track all the blob's entries
2567 _stub_cnt = StubInfo::stub_count(_blob_id);
2568 _ranges = NEW_C_HEAP_ARRAY(StubAddrRange, _stub_cnt, mtCode);
2569 for (int i = 0; i < _stub_cnt; i++) {
2570 _ranges[i].default_init();
2571 }
2572 }
2573 }
2574
2575 bool AOTStubData::load_code_blob() {
2576 assert(is_using(), "should not call");
2577 assert(!is_invalid() && _cached_blob == nullptr, "repeated init");
2578 _cached_blob = AOTCodeCache::load_code_blob(AOTCodeEntry::StubGenBlob,
2579 _blob_id,
2580 this);
2581 if (_cached_blob == nullptr) {
2582 set_invalid();
2583 return false;
2584 } else {
2585 return true;
2586 }
2587 }
2588
2589 bool AOTStubData::store_code_blob(CodeBlob& new_blob, CodeBuffer *code_buffer) {
2590 assert(is_dumping(), "should not call");
2591 assert(_cached_blob == nullptr, "should not be loading and storing!");
2592 if (!AOTCodeCache::store_code_blob(new_blob,
2593 AOTCodeEntry::StubGenBlob,
2594 _blob_id, this, code_buffer)) {
2595 set_invalid();
2596 return false;
2597 } else {
2598 return true;
2599 }
2600 }
2601
2602 address AOTStubData::load_archive_data(StubId stub_id, address& end, GrowableArray<address>* entries, GrowableArray<address>* extras) {
2603 assert(StubInfo::blob(stub_id) == _blob_id, "sanity check");
2604 if (is_invalid()) {
2605 return nullptr;
2606 }
2607 int idx = StubInfo::stubgen_offset_in_blob(_blob_id, stub_id);
2608 assert(idx >= 0 && idx < _stub_cnt, "invalid index %d for stub count %d", idx, _stub_cnt);
2609 // ensure we have a valid associated range
2610 StubAddrRange &range = _ranges[idx];
2611 int base = range.start_index();
2612 if (base < 0) {
2613 return nullptr;
2614 }
2615 int count = range.count();
2616 assert(base >= 0, "sanity");
2617 assert(count >= 2, "sanity");
2618 // first two saved addresses are start and end
2619 address start = _address_array.at(base);
2620 end = _address_array.at(base + 1);
2621 assert(start != nullptr, "failed to load start address of stub %s", StubInfo::name(stub_id));
2622 assert(end != nullptr, "failed to load end address of stub %s", StubInfo::name(stub_id));
2623 assert(start < end, "start address %p should be less than end %p address for stub %s", start, end, StubInfo::name(stub_id));
2624
2625 int entry_count = StubInfo::entry_count(stub_id);
2626 // the address count must at least include the stub start, end
2627 // and secondary addresses
2628 assert(count >= entry_count + 1, "stub %s requires %d saved addresses but only has %d", StubInfo::name(stub_id), entry_count + 1, count);
2629
2630 // caller must retrieve secondary entries if and only if they exist
2631 assert((entry_count == 1) == (entries == nullptr), "trying to retrieve wrong number of entries for stub %s", StubInfo::name(stub_id));
2632 int index = 2;
2633 if (entries != nullptr) {
2634 assert(entries->length() == 0, "non-empty array when retrieving entries for stub %s!", StubInfo::name(stub_id));
2635 while (index < entry_count + 1) {
2636 address entry = _address_array.at(base + index++);
2637 assert(entry == nullptr || (start < entry && entry < end), "entry address %p not in range (%p, %p) for stub %s", entry, start, end, StubInfo::name(stub_id));
2638 entries->append(entry);
2639 }
2640 }
2641 // caller must retrieve extras if and only if they exist
2642 assert((index < count) == (extras != nullptr), "trying to retrieve wrong number of extras for stub %s", StubInfo::name(stub_id));
2643 if (extras != nullptr) {
2644 assert(extras->length() == 0, "non-empty array when retrieving extras for stub %s!", StubInfo::name(stub_id));
2645 while (index < count) {
2646 address extra = _address_array.at(base + index++);
2647 assert(extra == nullptr || (start <= extra && extra <= end), "extra address %p not in range (%p, %p) for stub %s", extra, start, end, StubInfo::name(stub_id));
2648 extras->append(extra);
2649 }
2650 }
2651
2652 return start;
2653 }
2654
2655 void AOTStubData::store_archive_data(StubId stub_id, address start, address end, GrowableArray<address>* entries, GrowableArray<address>* extras) {
2656 assert(StubInfo::blob(stub_id) == _blob_id, "sanity check");
2657 assert(start != nullptr, "start address cannot be null");
2658 assert(end != nullptr, "end address cannot be null");
2659 assert(start < end, "start address %p should be less than end %p address for stub %s", start, end, StubInfo::name(stub_id));
2660 int idx = StubInfo::stubgen_offset_in_blob(_blob_id, stub_id);
2661 StubAddrRange& range = _ranges[idx];
2662 assert(range.start_index() == -1, "sanity");
2663 int base = _address_array.length();
2664 assert(base >= 0, "sanity");
2665 // first two saved addresses are start and end
2666 _address_array.append(start);
2667 _address_array.append(end);
2668 // caller must save secondary entries if and only if they exist
2669 assert((StubInfo::entry_count(stub_id) == 1) == (entries == nullptr), "trying to save wrong number of entries for stub %s", StubInfo::name(stub_id));
2670 if (entries != nullptr) {
2671 assert(entries->length() == StubInfo::entry_count(stub_id) - 1, "incorrect entry count %d when saving entries for stub %s!", entries->length(), StubInfo::name(stub_id));
2672 for (int i = 0; i < entries->length(); i++) {
2673 address entry = entries->at(i);
2674 assert(entry == nullptr || (start < entry && entry < end), "entry address %p not in range (%p, %p) for stub %s", entry, start, end, StubInfo::name(stub_id));
2675 _address_array.append(entry);
2676 }
2677 }
2678 // caller may wish to save extra addresses
2679 if (extras != nullptr) {
2680 for (int i = 0; i < extras->length(); i++) {
2681 address extra = extras->at(i);
2682 // handler range end may be end -- it gets restored as nullptr
2683 assert(extra == nullptr || (start <= extra && extra <= end), "extra address %p not in range (%p, %p) for stub %s", extra, start, end, StubInfo::name(stub_id));
2684 _address_array.append(extra);
2685 }
2686 }
2687 range.init_entry(base, _address_array.length() - base);
2688 }
2689
2690 void AOTStubData::stub_epilog(StubId stub_id) {
2691 DEBUG_ONLY(check_stored(stub_id));
2692 }
2693
2694 #ifdef ASSERT
2695 void AOTStubData::check_stored(StubId stub_id) {
2696 // Only need to check if we are dumping
2697 //
2698 // This excludes cases where the cache got closed because of error
2699 // plus the pre-universe stubs we can never store because they are
2700 // generated prior to cache opening.
2701 if (is_dumping()) {
2702 int idx = StubInfo::stubgen_offset_in_blob(_blob_id, stub_id);
2703 assert(idx >= 0 && idx < _stub_cnt, "invalid index %d for stub count %d", idx, _stub_cnt);
2704 StubAddrRange& range = _ranges[idx];
2705 assert(range.start_index() != -1, "missing store_archive_data for generated stub %s", StubInfo::name(stub_id));
2706 }
2707 }
2708 #endif