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