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