1 /*
   2  * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/macroAssembler.hpp"
  27 #include "cds/cdsAccess.hpp"
  28 #include "cds/cdsConfig.hpp"
  29 #include "cds/metaspaceShared.hpp"
  30 #include "ci/ciConstant.hpp"
  31 #include "ci/ciEnv.hpp"
  32 #include "ci/ciField.hpp"
  33 #include "ci/ciMethod.hpp"
  34 #include "ci/ciMethodData.hpp"
  35 #include "ci/ciObject.hpp"
  36 #include "ci/ciUtilities.inline.hpp"
  37 #include "classfile/javaAssertions.hpp"
  38 #include "classfile/stringTable.hpp"
  39 #include "classfile/symbolTable.hpp"
  40 #include "classfile/systemDictionary.hpp"
  41 #include "classfile/vmClasses.hpp"
  42 #include "classfile/vmIntrinsics.hpp"
  43 #include "code/codeBlob.hpp"
  44 #include "code/codeCache.hpp"
  45 #include "code/oopRecorder.inline.hpp"
  46 #include "code/SCCache.hpp"
  47 #include "compiler/abstractCompiler.hpp"
  48 #include "compiler/compileBroker.hpp"
  49 #include "compiler/compileTask.hpp"
  50 #include "gc/g1/g1BarrierSetRuntime.hpp"
  51 #include "gc/shared/gcConfig.hpp"
  52 #include "logging/log.hpp"
  53 #include "memory/universe.hpp"
  54 #include "oops/klass.inline.hpp"
  55 #include "oops/method.inline.hpp"
  56 #include "prims/jvmtiThreadState.hpp"
  57 #include "runtime/atomic.hpp"
  58 #include "runtime/flags/flagSetting.hpp"
  59 #include "runtime/globals_extension.hpp"
  60 #include "runtime/handles.inline.hpp"
  61 #include "runtime/jniHandles.inline.hpp"
  62 #include "runtime/os.inline.hpp"
  63 #include "runtime/sharedRuntime.hpp"
  64 #include "runtime/stubCodeGenerator.hpp"
  65 #include "runtime/stubRoutines.hpp"
  66 #include "runtime/timerTrace.hpp"
  67 #include "runtime/threadIdentifier.hpp"
  68 #include "utilities/ostream.hpp"
  69 #ifdef COMPILER1
  70 #include "c1/c1_Runtime1.hpp"
  71 #include "c1/c1_LIRAssembler.hpp"
  72 #include "gc/shared/c1/barrierSetC1.hpp"
  73 #include "gc/g1/c1/g1BarrierSetC1.hpp"
  74 #include "gc/z/c1/zBarrierSetC1.hpp"
  75 #endif
  76 #ifdef COMPILER2
  77 #include "opto/runtime.hpp"
  78 #endif
  79 #if INCLUDE_JVMCI
  80 #include "jvmci/jvmci.hpp"
  81 #endif
  82 
  83 #include <sys/stat.h>
  84 #include <errno.h>
  85 
  86 #ifndef O_BINARY       // if defined (Win32) use binary files.
  87 #define O_BINARY 0     // otherwise do nothing.
  88 #endif
  89 
  90 static elapsedTimer _t_totalLoad;
  91 static elapsedTimer _t_totalRegister;
  92 static elapsedTimer _t_totalFind;
  93 static elapsedTimer _t_totalStore;
  94 
  95 SCCache* SCCache::_cache = nullptr;
  96 
  97 static bool enable_timers() {
  98   return CITime || log_is_enabled(Info, init);
  99 }
 100 
 101 void SCCache::initialize() {
 102   if (LoadCachedCode && !UseSharedSpaces) {
 103     return;
 104   }
 105   if (StoreCachedCode || LoadCachedCode) {
 106     if (FLAG_IS_DEFAULT(ClassInitBarrierMode)) {
 107       FLAG_SET_DEFAULT(ClassInitBarrierMode, 1);
 108     }
 109   } else if (ClassInitBarrierMode > 0) {
 110     log_warning(scc, init)("Set ClassInitBarrierMode to 0 because StoreCachedCode and LoadCachedCode are false.");
 111     FLAG_SET_DEFAULT(ClassInitBarrierMode, 0);
 112   }
 113   if ((LoadCachedCode || StoreCachedCode) && CachedCodeFile != nullptr) {
 114     const int len = (int)strlen(CachedCodeFile);
 115     // cache file path
 116     char* path  = NEW_C_HEAP_ARRAY(char, len+1, mtCode);
 117     memcpy(path, CachedCodeFile, len);
 118     path[len] = '\0';
 119     if (!open_cache(path)) {
 120       return;
 121     }
 122     if (StoreCachedCode) {
 123       FLAG_SET_DEFAULT(FoldStableValues, false);
 124       FLAG_SET_DEFAULT(ForceUnreachable, true);
 125     }
 126     FLAG_SET_DEFAULT(DelayCompilerStubsGeneration, false);
 127   }
 128 }
 129 
 130 void SCCache::init2() {
 131   if (!is_on()) {
 132     return;
 133   }
 134   // After Universe initialized
 135   BarrierSet* bs = BarrierSet::barrier_set();
 136   if (bs->is_a(BarrierSet::CardTableBarrierSet)) {
 137     address byte_map_base = ci_card_table_address_as<address>();
 138     if (is_on_for_write() && !external_word_Relocation::can_be_relocated(byte_map_base)) {
 139       // Bail out since we can't encode card table base address with relocation
 140       log_warning(scc, init)("Can't create Startup Code Cache because card table base address is not relocatable: " INTPTR_FORMAT, p2i(byte_map_base));
 141       close();
 142     }
 143   }
 144   if (!verify_vm_config()) {
 145     close();
 146   }
 147 }
 148 
 149 void SCCache::print_timers_on(outputStream* st) {
 150   if (LoadCachedCode) {
 151     st->print_cr ("    SC Load Time:         %7.3f s", _t_totalLoad.seconds());
 152     st->print_cr ("      nmethod register:     %7.3f s", _t_totalRegister.seconds());
 153     st->print_cr ("      find cached code:     %7.3f s", _t_totalFind.seconds());
 154   }
 155   if (StoreCachedCode) {
 156     st->print_cr ("    SC Store Time:        %7.3f s", _t_totalStore.seconds());
 157   }
 158 }
 159 
 160 bool SCCache::is_C3_on() {
 161 #if INCLUDE_JVMCI
 162   if (UseJVMCICompiler) {
 163     return (StoreCachedCode || LoadCachedCode) && UseC2asC3;
 164   }
 165 #endif
 166   return false;
 167 }
 168 
 169 bool SCCache::is_code_load_thread_on() {
 170   return UseCodeLoadThread && LoadCachedCode;
 171 }
 172 
 173 bool SCCache::gen_preload_code(ciMethod* m, int entry_bci) {
 174   VM_ENTRY_MARK;
 175   return (entry_bci == InvocationEntryBci) && is_on() && _cache->gen_preload_code() &&
 176          CDSAccess::can_generate_cached_code(m->get_Method());
 177 }
 178 
 179 void SCCache::close() {
 180   if (is_on()) {
 181     if (SCCache::is_on_for_read()) {
 182       LogStreamHandle(Info, init) log;
 183       if (log.is_enabled()) {
 184         log.print_cr("Startup Code Cache statistics (when closed): ");
 185         SCCache::print_statistics_on(&log);
 186         log.cr();
 187         SCCache::print_timers_on(&log);
 188       }
 189     }
 190 
 191     delete _cache; // Free memory
 192     _cache = nullptr;
 193   }
 194 }
 195 
 196 void SCCache::invalidate(SCCEntry* entry) {
 197   // This could be concurent execution
 198   if (entry != nullptr && is_on()) { // Request could come after cache is closed.
 199     _cache->invalidate_entry(entry);
 200   }
 201 }
 202 
 203 bool SCCache::is_loaded(SCCEntry* entry) {
 204   if (is_on() && _cache->cache_buffer() != nullptr) {
 205     return (uint)((char*)entry - _cache->cache_buffer()) < _cache->load_size();
 206   }
 207   return false;
 208 }
 209 
 210 void SCCache::preload_code(JavaThread* thread) {
 211   if ((ClassInitBarrierMode == 0) || !is_on_for_read()) {
 212     return;
 213   }
 214   if ((DisableCachedCode & (1 << 3)) != 0) {
 215     return; // no preloaded code (level 5);
 216   }
 217   _cache->preload_startup_code(thread);
 218 }
 219 
 220 SCCEntry* SCCache::find_code_entry(const methodHandle& method, uint comp_level) {
 221   switch (comp_level) {
 222     case CompLevel_simple:
 223       if ((DisableCachedCode & (1 << 0)) != 0) {
 224         return nullptr;
 225       }
 226       break;
 227     case CompLevel_limited_profile:
 228       if ((DisableCachedCode & (1 << 1)) != 0) {
 229         return nullptr;
 230       }
 231       break;
 232     case CompLevel_full_optimization:
 233       if ((DisableCachedCode & (1 << 2)) != 0) {
 234         return nullptr;
 235       }
 236       break;
 237 
 238     default: return nullptr; // Level 1, 2, and 4 only
 239   }
 240   TraceTime t1("SC total find code time", &_t_totalFind, enable_timers(), false);
 241   if (is_on() && _cache->cache_buffer() != nullptr) {
 242     MethodData* md = method->method_data();
 243     uint decomp = (md == nullptr) ? 0 : md->decompile_count();
 244 
 245     ResourceMark rm;
 246     const char* target_name = method->name_and_sig_as_C_string();
 247     uint hash = java_lang_String::hash_code((const jbyte*)target_name, (int)strlen(target_name));
 248     SCCEntry* entry = _cache->find_entry(SCCEntry::Code, hash, comp_level, decomp);
 249     if (entry == nullptr) {
 250       log_info(scc, nmethod)("Missing entry for '%s' (comp_level %d, decomp: %d, hash: " UINT32_FORMAT_X_0 ")", target_name, (uint)comp_level, decomp, hash);
 251 #ifdef ASSERT
 252     } else {
 253       uint name_offset = entry->offset() + entry->name_offset();
 254       uint name_size   = entry->name_size(); // Includes '/0'
 255       const char* name = _cache->cache_buffer() + name_offset;
 256       if (strncmp(target_name, name, name_size) != 0) {
 257         assert(false, "SCA: saved nmethod's name '%s' is different from '%s', hash: " UINT32_FORMAT_X_0, name, target_name, hash);
 258       }
 259 #endif
 260     }
 261 
 262     DirectiveSet* directives = DirectivesStack::getMatchingDirective(method, nullptr);
 263     if (directives->IgnorePrecompiledOption) {
 264       LogStreamHandle(Info, scc, compilation) log;
 265       if (log.is_enabled()) {
 266         log.print("Ignore cached code entry on level %d for ", comp_level);
 267         method->print_value_on(&log);
 268       }
 269       return nullptr;
 270     }
 271 
 272     return entry;
 273   }
 274   return nullptr;
 275 }
 276 
 277 void SCCache::add_C_string(const char* str) {
 278   if (is_on_for_write()) {
 279     _cache->add_new_C_string(str);
 280   }
 281 }
 282 
 283 bool SCCache::allow_const_field(ciConstant& value) {
 284   return !is_on() || !StoreCachedCode // Restrict only when we generate cache
 285         // Can not trust primitive too   || !is_reference_type(value.basic_type())
 286         // May disable this too for now  || is_reference_type(value.basic_type()) && value.as_object()->should_be_constant()
 287         ;
 288 }
 289 
 290 bool SCCache::open_cache(const char* cache_path) {
 291   if (LoadCachedCode) {
 292     log_info(scc)("Trying to load Startup Code Cache '%s'", cache_path);
 293     struct stat st;
 294     if (os::stat(cache_path, &st) != 0) {
 295       log_warning(scc, init)("Specified Startup Code Cache file not found '%s'", cache_path);
 296       return false;
 297     } else if ((st.st_mode & S_IFMT) != S_IFREG) {
 298       log_warning(scc, init)("Specified Startup Code Cache is not file '%s'", cache_path);
 299       return false;
 300     }
 301     int fd = os::open(cache_path, O_RDONLY | O_BINARY, 0);
 302     if (fd < 0) {
 303       if (errno == ENOENT) {
 304         log_warning(scc, init)("Specified Startup Code Cache file not found '%s'", cache_path);
 305       } else {
 306         log_warning(scc, init)("Failed to open Startup Code Cache file '%s': (%s)", cache_path, os::strerror(errno));
 307       }
 308       return false;
 309     } else {
 310       log_info(scc, init)("Opened for read Startup Code Cache '%s'", cache_path);
 311     }
 312     SCCache* cache = new SCCache(cache_path, fd, (uint)st.st_size);
 313     bool failed = cache->failed();
 314     if (::close(fd) < 0) {
 315       log_warning(scc)("Failed to close for read Startup Code Cache file '%s'", cache_path);
 316       failed = true;
 317     }
 318     if (failed) {
 319       delete cache;
 320       _cache = nullptr;
 321       return false;
 322     }
 323     _cache = cache;
 324   }
 325   if (_cache == nullptr && StoreCachedCode) {
 326     SCCache* cache = new SCCache(cache_path, -1 /* fd */, 0 /* size */);
 327     if (cache->failed()) {
 328       delete cache;
 329       _cache = nullptr;
 330       return false;
 331     }
 332     _cache = cache;
 333   }
 334   return true;
 335 }
 336 
 337 class CachedCodeDirectory {
 338 public:
 339   int _some_number;
 340   InstanceKlass* _some_klass;
 341   size_t _my_data_length;
 342   void* _my_data;
 343 };
 344 
 345 // Skeleton code for including cached code in CDS:
 346 //
 347 // [1] Use CachedCodeDirectory to keep track of all of data related to cached code.
 348 //     E.g., you can build a hashtable to record what methods have been archived.
 349 //
 350 // [2] Memory for all data for cached code, including CachedCodeDirectory, should be
 351 //     allocated using CDSAccess::allocate_from_code_cache().
 352 //
 353 // [3] CachedCodeDirectory must be the very first allocation.
 354 //
 355 // [4] Two kinds of pointer can be stored:
 356 //     - A pointer p that points to metadata. CDSAccess::can_generate_cached_code(p) must return true.
 357 //     - A pointer to a buffer returned by CDSAccess::allocate_from_code_cache().
 358 //       (It's OK to point to an interior location within this buffer).
 359 //     Such pointers must be stored using CDSAccess::set_pointer()
 360 //
 361 // The buffers allocated by CDSAccess::allocate_from_code_cache() are in a contiguous region. At runtime, this
 362 // region is mapped to the beginning of the CodeCache (see _cds_code_space in codeCache.cpp). All the pointers
 363 // in this buffer are relocated as necessary (e.g., to account for the runtime location of the CodeCache).
 364 //
 365 // Example:
 366 //
 367 // # make sure hw.cds doesn't exist, so that it's regenerated (1.5 step training)
 368 // $ rm -f hw.cds; java -Xlog:cds,scc::uptime,tags,pid -XX:CacheDataStore=hw.cds -cp ~/tmp/HelloWorld.jar HelloWorld
 369 //
 370 // # After training is finish, hw.cds should contain a CachedCodeDirectory. You can see the effect of relocation
 371 // # from the [scc] log.
 372 // $ java -Xlog:cds,scc -XX:CacheDataStore=hw.cds -cp ~/tmp/HelloWorld.jar HelloWorld
 373 // [0.016s][info][scc] new workflow: cached code mapped at 0x7fef97ebc000
 374 // [0.016s][info][scc] _cached_code_directory->_some_klass     = 0x800009ca8 (java.lang.String)
 375 // [0.016s][info][scc] _cached_code_directory->_some_number    = 0
 376 // [0.016s][info][scc] _cached_code_directory->_my_data_length = 0
 377 // [0.016s][info][scc] _cached_code_directory->_my_data        = 0x7fef97ebc020 (32 bytes offset from base)
 378 //
 379 // The 1.5 step training may be hard to debug. If you want to run in a debugger, run the above training step
 380 // with an additional "-XX:+CDSManualFinalImage" command-line argument.
 381 
 382 // This is always at the very beginning of the mmaped CDS "cc" (cached code) region
 383 static CachedCodeDirectory* _cached_code_directory = nullptr;
 384 
 385 void SCCache::new_workflow_start_writing_cache() {
 386   CachedCodeDirectory* dir = (CachedCodeDirectory*)CDSAccess::allocate_from_code_cache(sizeof(CachedCodeDirectory));
 387   _cached_code_directory = dir;
 388 
 389   CDSAccess::set_pointer(&dir->_some_klass, vmClasses::String_klass()); 
 390 
 391   size_t n = 120;
 392   void* d = (void*)CDSAccess::allocate_from_code_cache(n);
 393   CDSAccess::set_pointer(&dir->_my_data, d);
 394 }
 395 
 396 void SCCache::new_workflow_end_writing_cache() {
 397 
 398 }
 399 
 400 void SCCache::new_workflow_load_cache() {
 401   void* ptr = CodeCache::map_cached_code();
 402   if (ptr != nullptr) {
 403     // At this point:
 404     // - CodeCache::initialize_heaps() has finished.
 405     // - CDS archive is fully mapped ("metadata", "heap" and "cached_code" regions are mapped)
 406     // - All pointers in the mapped CDS regions are relocated.
 407     // - CDSAccess::get_archived_object() works.
 408     ResourceMark rm;
 409     _cached_code_directory = (CachedCodeDirectory*)ptr;
 410     InstanceKlass* k = _cached_code_directory->_some_klass;
 411     log_info(scc)("new workflow: cached code mapped at %p", ptr);
 412     log_info(scc)("_cached_code_directory->_some_klass     = %p (%s)", k, k->external_name());
 413     log_info(scc)("_cached_code_directory->_some_number    = %d", _cached_code_directory->_some_number);
 414     log_info(scc)("_cached_code_directory->_my_data_length = %zu", _cached_code_directory->_my_data_length);
 415     log_info(scc)("_cached_code_directory->_my_data        = %p (%zu bytes offset from base)", _cached_code_directory->_my_data,
 416                   pointer_delta((address)_cached_code_directory->_my_data, (address)_cached_code_directory, 1));
 417   }
 418 }
 419 
 420 #define DATA_ALIGNMENT HeapWordSize
 421 
 422 SCCache::SCCache(const char* cache_path, int fd, uint load_size) {
 423   _load_header = nullptr;
 424   _cache_path = cache_path;
 425   _for_read  = LoadCachedCode;
 426   _for_write = StoreCachedCode;
 427   _load_size = load_size;
 428   _store_size = 0;
 429   _write_position = 0;
 430   _closing  = false;
 431   _failed = false;
 432   _lookup_failed = false;
 433   _table = nullptr;
 434   _load_entries = nullptr;
 435   _store_entries  = nullptr;
 436   _C_strings_buf  = nullptr;
 437   _load_buffer = nullptr;
 438   _store_buffer = nullptr;
 439   _C_load_buffer = nullptr;
 440   _C_store_buffer = nullptr;
 441   _store_entries_cnt = 0;
 442   _gen_preload_code = false;
 443   _for_preload = false;       // changed while storing entry data
 444   _has_clinit_barriers = false;
 445 
 446   _compile_id = 0;
 447   _comp_level = 0;
 448 
 449   _use_meta_ptrs = UseSharedSpaces ? UseMetadataPointers : false;
 450 
 451   // Read header at the begining of cache
 452   uint header_size = sizeof(SCCHeader);
 453   if (_for_read) {
 454     // Read cache
 455     _C_load_buffer = NEW_C_HEAP_ARRAY(char, load_size + DATA_ALIGNMENT, mtCode);
 456     _load_buffer = align_up(_C_load_buffer, DATA_ALIGNMENT);
 457     uint n = (uint)::read(fd, _load_buffer, load_size);
 458     if (n != load_size) {
 459       log_warning(scc, init)("Failed to read %d bytes at address " INTPTR_FORMAT " from Startup Code Cache file '%s'", load_size, p2i(_load_buffer), _cache_path);
 460       set_failed();
 461       return;
 462     }
 463     log_info(scc, init)("Read %d bytes at address " INTPTR_FORMAT " from Startup Code Cache '%s'", load_size, p2i(_load_buffer), _cache_path);
 464 
 465     _load_header = (SCCHeader*)addr(0);
 466     const char* scc_jvm_version = addr(_load_header->jvm_version_offset());
 467     if (strncmp(scc_jvm_version, VM_Version::internal_vm_info_string(), strlen(scc_jvm_version)) != 0) {
 468       log_warning(scc, init)("Disable Startup Code Cache: JVM version '%s' recorded in '%s' does not match current version '%s'", scc_jvm_version, _cache_path, VM_Version::internal_vm_info_string());
 469       set_failed();
 470       return;
 471     }
 472     if (!_load_header->verify_config(_cache_path, load_size)) {
 473       set_failed();
 474       return;
 475     }
 476     log_info(scc, init)("Read header from Startup Code Cache '%s'", cache_path);
 477     if (_load_header->has_meta_ptrs()) {
 478       assert(UseSharedSpaces, "should be verified already");
 479       _use_meta_ptrs = true; // Regardless UseMetadataPointers
 480       UseMetadataPointers = true;
 481     }
 482     // Read strings
 483     load_strings();
 484   }
 485   if (_for_write) {
 486     _gen_preload_code = _use_meta_ptrs && (ClassInitBarrierMode > 0);
 487 
 488     _C_store_buffer = NEW_C_HEAP_ARRAY(char, CachedCodeMaxSize + DATA_ALIGNMENT, mtCode);
 489     _store_buffer = align_up(_C_store_buffer, DATA_ALIGNMENT);
 490     // Entries allocated at the end of buffer in reverse (as on stack).
 491     _store_entries = (SCCEntry*)align_up(_C_store_buffer + CachedCodeMaxSize, DATA_ALIGNMENT);
 492     log_info(scc, init)("Allocated store buffer at address " INTPTR_FORMAT " of size %d", p2i(_store_buffer), CachedCodeMaxSize);
 493   }
 494   _table = new SCAddressTable();
 495 }
 496 
 497 void SCCache::init_table() {
 498   SCCache* cache = SCCache::cache();
 499   if (cache != nullptr && cache->_table != nullptr) {
 500     cache->_table->init();
 501   }
 502 }
 503 
 504 void SCCache::init_opto_table() {
 505   SCCache* cache = SCCache::cache();
 506   if (cache != nullptr && cache->_table != nullptr) {
 507     cache->_table->init_opto();
 508   }
 509 }
 510 
 511 void SCCache::init_c1_table() {
 512   SCCache* cache = SCCache::cache();
 513   if (cache != nullptr && cache->_table != nullptr) {
 514     cache->_table->init_c1();
 515   }
 516 }
 517 
 518 void SCConfig::record(bool use_meta_ptrs) {
 519   _flags = 0;
 520   if (use_meta_ptrs) {
 521     _flags |= metadataPointers;
 522   }
 523 #ifdef ASSERT
 524   _flags |= debugVM;
 525 #endif
 526   if (UseCompressedOops) {
 527     _flags |= compressedOops;
 528   }
 529   if (UseCompressedClassPointers) {
 530     _flags |= compressedClassPointers;
 531   }
 532   if (UseTLAB) {
 533     _flags |= useTLAB;
 534   }
 535   if (JavaAssertions::systemClassDefault()) {
 536     _flags |= systemClassAssertions;
 537   }
 538   if (JavaAssertions::userClassDefault()) {
 539     _flags |= userClassAssertions;
 540   }
 541   if (EnableContended) {
 542     _flags |= enableContendedPadding;
 543   }
 544   if (RestrictContended) {
 545     _flags |= restrictContendedPadding;
 546   }
 547   if (UseEmptySlotsInSupers) {
 548     _flags |= useEmptySlotsInSupers;
 549   }
 550   _compressedOopShift    = CompressedOops::shift();
 551   _compressedKlassShift  = CompressedKlassPointers::shift();
 552   _contendedPaddingWidth = ContendedPaddingWidth;
 553   _objectAlignment       = ObjectAlignmentInBytes;
 554   _gc                    = (uint)Universe::heap()->kind();
 555 }
 556 
 557 bool SCConfig::verify(const char* cache_path) const {
 558 #ifdef ASSERT
 559   if ((_flags & debugVM) == 0) {
 560     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created by product VM, it can't be used by debug VM", cache_path);
 561     return false;
 562   }
 563 #else
 564   if ((_flags & debugVM) != 0) {
 565     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created by debug VM, it can't be used by product VM", cache_path);
 566     return false;
 567   }
 568 #endif
 569 
 570   CollectedHeap::Name scc_gc = (CollectedHeap::Name)_gc;
 571   if (scc_gc != Universe::heap()->kind()) {
 572     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with %s vs current %s", cache_path, GCConfig::hs_err_name(scc_gc), GCConfig::hs_err_name());
 573     return false;
 574   }
 575 
 576   if (((_flags & compressedOops) != 0) != UseCompressedOops) {
 577     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with UseCompressedOops = %s", cache_path, UseCompressedOops ? "false" : "true");
 578     return false;
 579   }
 580   if (((_flags & compressedClassPointers) != 0) != UseCompressedClassPointers) {
 581     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with UseCompressedClassPointers = %s", cache_path, UseCompressedClassPointers ? "false" : "true");
 582     return false;
 583   }
 584 
 585   if (((_flags & systemClassAssertions) != 0) != JavaAssertions::systemClassDefault()) {
 586     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with JavaAssertions::systemClassDefault() = %s", cache_path, JavaAssertions::systemClassDefault() ? "disabled" : "enabled");
 587     return false;
 588   }
 589   if (((_flags & userClassAssertions) != 0) != JavaAssertions::userClassDefault()) {
 590     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with JavaAssertions::userClassDefault() = %s", cache_path, JavaAssertions::userClassDefault() ? "disabled" : "enabled");
 591     return false;
 592   }
 593 
 594   if (((_flags & enableContendedPadding) != 0) != EnableContended) {
 595     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with EnableContended = %s", cache_path, EnableContended ? "false" : "true");
 596     return false;
 597   }
 598   if (((_flags & restrictContendedPadding) != 0) != RestrictContended) { 
 599     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with RestrictContended = %s", cache_path, RestrictContended ? "false" : "true");
 600     return false;
 601   }
 602   if (((_flags & useEmptySlotsInSupers) != 0) != UseEmptySlotsInSupers) { 
 603     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with UseEmptySlotsInSupers = %s", cache_path, UseEmptySlotsInSupers ? "false" : "true");
 604     return false;
 605   }
 606 
 607   if (_compressedOopShift != (uint)CompressedOops::shift()) {
 608     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with CompressedOops::shift() = %d vs current %d", cache_path, _compressedOopShift, CompressedOops::shift());
 609     return false;
 610   }
 611   if (_compressedKlassShift != (uint)CompressedKlassPointers::shift()) {
 612     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with CompressedKlassPointers::shift() = %d vs current %d", cache_path, _compressedKlassShift, CompressedKlassPointers::shift());
 613     return false;
 614   }
 615   if (_contendedPaddingWidth != (uint)ContendedPaddingWidth) {
 616     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with ContendedPaddingWidth = %d vs current %d", cache_path, _contendedPaddingWidth, ContendedPaddingWidth);
 617     return false;
 618   }
 619   if (_objectAlignment != (uint)ObjectAlignmentInBytes) {
 620     log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with ObjectAlignmentInBytes = %d vs current %d", cache_path, _objectAlignment, ObjectAlignmentInBytes);
 621     return false;
 622   }
 623   return true;
 624 }
 625 
 626 bool SCCHeader::verify_config(const char* cache_path, uint load_size) const {
 627   if (_version != SCC_VERSION) {
 628     log_warning(scc, init)("Disable Startup Code Cache: different SCC version %d vs %d recorded in '%s'", SCC_VERSION, _version, cache_path);
 629     return false;
 630   }
 631   if (_cache_size != load_size) {
 632     log_warning(scc, init)("Disable Startup Code Cache: different cached code size %d vs %d recorded in '%s'", load_size, _cache_size, cache_path);
 633     return false;
 634   }
 635   if (has_meta_ptrs() && !UseSharedSpaces) {
 636     log_warning(scc, init)("Disable Startup Cached Code: '%s' contains metadata pointers but CDS is off", cache_path);
 637     return false;
 638   }
 639   return true;
 640 }
 641 
 642 static volatile int _reading_nmethod = 0;
 643 
 644 class ReadingMark {
 645 public:
 646   ReadingMark() {
 647     Atomic::inc(&_reading_nmethod);
 648   }
 649   ~ReadingMark() {
 650     Atomic::dec(&_reading_nmethod);
 651   }
 652 };
 653 
 654 SCCache::~SCCache() {
 655   if (_closing) {
 656     return; // Already closed
 657   }
 658   // Stop any further access to cache.
 659   // Checked on entry to load_nmethod() and store_nmethod().
 660   _closing = true;
 661   if (_for_read && _reading_nmethod > 0) {
 662     // Wait for all load_nmethod() finish.
 663     // TODO: may be have new separate locker for SCA.
 664     MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
 665     while (_reading_nmethod > 0) {
 666       locker.wait(10); // Wait 10 ms
 667     }
 668   }
 669   // Prevent writing code into cache while we are closing it.
 670   // This lock held by ciEnv::register_method() which calls store_nmethod().
 671   MutexLocker ml(Compile_lock);
 672   if (for_write()) { // Finalize cache
 673     finish_write();
 674   }
 675   FREE_C_HEAP_ARRAY(char, _cache_path);
 676   if (_C_load_buffer != nullptr) {
 677     FREE_C_HEAP_ARRAY(char, _C_load_buffer);
 678     _C_load_buffer = nullptr;
 679     _load_buffer = nullptr;
 680   }
 681   if (_C_store_buffer != nullptr) {
 682     FREE_C_HEAP_ARRAY(char, _C_store_buffer);
 683     _C_store_buffer = nullptr;
 684     _store_buffer = nullptr;
 685   }
 686   if (_table != nullptr) {
 687     delete _table;
 688     _table = nullptr;
 689   }
 690 }
 691 
 692 SCCache* SCCache::open_for_read() {
 693   if (SCCache::is_on_for_read()) {
 694     return SCCache::cache();
 695   }
 696   return nullptr;
 697 }
 698 
 699 SCCache* SCCache::open_for_write() {
 700   if (SCCache::is_on_for_write()) {
 701     SCCache* cache = SCCache::cache();
 702     cache->clear_lookup_failed(); // Reset bit
 703     return cache;
 704   }
 705   return nullptr;
 706 }
 707 
 708 void copy_bytes(const char* from, address to, uint size) {
 709   assert(size > 0, "sanity");
 710   bool by_words = true;
 711   if ((size > 2 * HeapWordSize) && (((intptr_t)from | (intptr_t)to) & (HeapWordSize - 1)) == 0) {
 712     // Use wordwise copies if possible:
 713     Copy::disjoint_words((HeapWord*)from,
 714                          (HeapWord*)to,
 715                          ((size_t)size + HeapWordSize-1) / HeapWordSize);
 716   } else {
 717     by_words = false;
 718     Copy::conjoint_jbytes(from, to, (size_t)size);
 719   }
 720   log_trace(scc)("Copied %d bytes as %s from " INTPTR_FORMAT " to " INTPTR_FORMAT, size, (by_words ? "HeapWord" : "bytes"), p2i(from), p2i(to));
 721 }
 722 
 723 void SCCReader::set_read_position(uint pos) {
 724   if (pos == _read_position) {
 725     return;
 726   }
 727   assert(pos < _cache->load_size(), "offset:%d >= file size:%d", pos, _cache->load_size());
 728   _read_position = pos;
 729 }
 730 
 731 bool SCCache::set_write_position(uint pos) {
 732   if (pos == _write_position) {
 733     return true;
 734   }
 735   if (_store_size < _write_position) {
 736     _store_size = _write_position; // Adjust during write
 737   }
 738   assert(pos < _store_size, "offset:%d >= file size:%d", pos, _store_size);
 739   _write_position = pos;
 740   return true;
 741 }
 742 
 743 static char align_buffer[256] = { 0 };
 744 
 745 bool SCCache::align_write() {
 746   // We are not executing code from cache - we copy it by bytes first.
 747   // No need for big alignment (or at all).
 748   uint padding = DATA_ALIGNMENT - (_write_position & (DATA_ALIGNMENT - 1));
 749   if (padding == DATA_ALIGNMENT) {
 750     return true;
 751   }
 752   uint n = write_bytes((const void*)&align_buffer, padding);
 753   if (n != padding) {
 754     return false;
 755   }
 756   log_trace(scc)("Adjust write alignment in Startup Code Cache '%s'", _cache_path);
 757   return true;
 758 }
 759 
 760 uint SCCache::write_bytes(const void* buffer, uint nbytes) {
 761   assert(for_write(), "Code Cache file is not created");
 762   if (nbytes == 0) {
 763     return 0;
 764   }
 765   uint new_position = _write_position + nbytes;
 766   if (new_position >= (uint)((char*)_store_entries - _store_buffer)) {
 767     log_warning(scc)("Failed to write %d bytes at offset %d to Startup Code Cache file '%s'. Increase CachedCodeMaxSize.",
 768                      nbytes, _write_position, _cache_path);
 769     set_failed();
 770     return 0;
 771   }
 772   copy_bytes((const char* )buffer, (address)(_store_buffer + _write_position), nbytes);
 773   log_trace(scc)("Wrote %d bytes at offset %d to Startup Code Cache '%s'", nbytes, _write_position, _cache_path);
 774   _write_position += nbytes;
 775   if (_store_size < _write_position) {
 776     _store_size = _write_position;
 777   }
 778   return nbytes;
 779 }
 780 
 781 void SCCEntry::update_method_for_writing() {
 782   if (_method != nullptr) {
 783     _method = CDSAccess::method_in_cached_code(_method);
 784   }
 785 }
 786 
 787 void SCCEntry::print(outputStream* st) const {
 788   st->print_cr(" SCA entry " INTPTR_FORMAT " [kind: %d, id: " UINT32_FORMAT_X_0 ", offset: %d, size: %d, comp_level: %d, comp_id: %d, decompiled: %d, %s%s%s%s]",
 789                p2i(this), (int)_kind, _id, _offset, _size, _comp_level, _comp_id, _decompile,
 790                (_not_entrant? "not_entrant" : "entrant"),
 791                (_loaded ? ", loaded" : ""),
 792                (_has_clinit_barriers ? ", has_clinit_barriers" : ""),
 793                (_for_preload ? ", for_preload" : ""));
 794 }
 795 
 796 void* SCCEntry::operator new(size_t x, SCCache* cache) {
 797   return (void*)(cache->add_entry());
 798 }
 799 
 800 bool skip_preload(methodHandle mh) {
 801   if (!mh->method_holder()->is_loaded()) {
 802     return true;
 803   }
 804   DirectiveSet* directives = DirectivesStack::getMatchingDirective(mh, nullptr);
 805   if (directives->DontPreloadOption) {
 806     LogStreamHandle(Info, scc, init) log;
 807     if (log.is_enabled()) {
 808       log.print("Exclude preloading code for ");
 809       mh->print_value_on(&log);
 810     }
 811     return true;
 812   }
 813   return false;
 814 }
 815 
 816 void SCCache::preload_startup_code(TRAPS) {
 817   assert(_for_read, "sanity");
 818   uint count = _load_header->entries_count();
 819   if (_load_entries == nullptr) {
 820     // Read it
 821     _search_entries = (uint*)addr(_load_header->entries_offset()); // [id, index]
 822     _load_entries = (SCCEntry*)(_search_entries + 2 * count);
 823     log_info(scc, init)("Read %d entries table at offset %d from Startup Code Cache '%s'", count, _load_header->entries_offset(), _cache_path);
 824   }
 825   uint preload_entries_count = _load_header->preload_entries_count();
 826   if (preload_entries_count > 0) {
 827     uint* entries_index = (uint*)addr(_load_header->preload_entries_offset());
 828     log_info(scc, init)("Load %d preload entries from Startup Code Cache '%s'", preload_entries_count, _cache_path);
 829     uint count = MIN2(preload_entries_count, SCLoadStop);
 830     for (uint i = SCLoadStart; i < count; i++) {
 831       uint index = entries_index[i];
 832       SCCEntry* entry = &(_load_entries[index]);
 833       if (entry->not_entrant()) {
 834         continue;
 835       }
 836       methodHandle mh(THREAD, entry->method());
 837       assert((mh.not_null() && MetaspaceShared::is_in_shared_metaspace((address)mh())), "sanity");
 838       if (skip_preload(mh)) {
 839         continue; // Exclude preloading for this method
 840       }
 841       assert(mh->method_holder()->is_loaded(), "");
 842       if (!mh->method_holder()->is_linked()) {
 843         assert(!HAS_PENDING_EXCEPTION, "");
 844         mh->method_holder()->link_class(THREAD);
 845         if (HAS_PENDING_EXCEPTION) {
 846           LogStreamHandle(Warning, scc) log;
 847           if (log.is_enabled()) {
 848             ResourceMark rm;
 849             log.print("Linkage failed for %s: ", mh->method_holder()->external_name());
 850             THREAD->pending_exception()->print_value_on(&log);
 851             if (log_is_enabled(Debug, scc)) {
 852               THREAD->pending_exception()->print_on(&log);
 853             }
 854           }
 855           CLEAR_PENDING_EXCEPTION;
 856         }
 857       }
 858       if (mh->scc_entry() != nullptr) {
 859         // Second C2 compilation of the same method could happen for
 860         // different reasons without marking first entry as not entrant.
 861         continue; // Keep old entry to avoid issues
 862       }
 863       mh->set_scc_entry(entry);
 864       CompileBroker::compile_method(mh, InvocationEntryBci, CompLevel_full_optimization, methodHandle(), 0, false, CompileTask::Reason_Preload, CHECK);
 865     }
 866   }
 867 }
 868 
 869 static bool check_entry(SCCEntry::Kind kind, uint id, uint comp_level, uint decomp, SCCEntry* entry) {
 870   if (entry->kind() == kind) {
 871     assert(entry->id() == id, "sanity");
 872     if (kind != SCCEntry::Code || (!entry->not_entrant() && !entry->has_clinit_barriers() &&
 873                                   entry->comp_level() == comp_level &&
 874                                   (comp_level == CompLevel_limited_profile || entry->decompile() == decomp))) {
 875       return true; // Found
 876     }
 877   }
 878   return false;
 879 }
 880 
 881 SCCEntry* SCCache::find_entry(SCCEntry::Kind kind, uint id, uint comp_level, uint decomp) {
 882   assert(_for_read, "sanity");
 883   uint count = _load_header->entries_count();
 884   if (_load_entries == nullptr) {
 885     // Read it
 886     _search_entries = (uint*)addr(_load_header->entries_offset()); // [id, index]
 887     _load_entries = (SCCEntry*)(_search_entries + 2 * count);
 888     log_info(scc, init)("Read %d entries table at offset %d from Startup Code Cache '%s'", count, _load_header->entries_offset(), _cache_path);
 889   }
 890   // Binary search
 891   int l = 0;
 892   int h = count - 1;
 893   while (l <= h) {
 894     int mid = (l + h) >> 1;
 895     int ix = mid * 2;
 896     uint is = _search_entries[ix];
 897     if (is == id) {
 898       int index = _search_entries[ix + 1];
 899       SCCEntry* entry = &(_load_entries[index]);
 900       if (check_entry(kind, id, comp_level, decomp, entry)) {
 901         return entry; // Found
 902       }
 903       // Leaner search around (could be the same nmethod with different decompile count)
 904       for (int i = mid - 1; i >= l; i--) { // search back
 905         ix = i * 2;
 906         is = _search_entries[ix];
 907         if (is != id) {
 908           break;
 909         }
 910         index = _search_entries[ix + 1];
 911         SCCEntry* entry = &(_load_entries[index]);
 912         if (check_entry(kind, id, comp_level, decomp, entry)) {
 913           return entry; // Found
 914         }
 915       }
 916       for (int i = mid + 1; i <= h; i++) { // search forward
 917         ix = i * 2;
 918         is = _search_entries[ix];
 919         if (is != id) {
 920           break;
 921         }
 922         index = _search_entries[ix + 1];
 923         SCCEntry* entry = &(_load_entries[index]);
 924         if (check_entry(kind, id, comp_level, decomp, entry)) {
 925           return entry; // Found
 926         }
 927       }
 928       break; // Not found match (different decompile count or not_entrant state).
 929     } else if (is < id) {
 930       l = mid + 1;
 931     } else {
 932       h = mid - 1;
 933     }
 934   }
 935   return nullptr;
 936 }
 937 
 938 void SCCache::invalidate_entry(SCCEntry* entry) {
 939   assert(entry!= nullptr, "all entries should be read already");
 940   if (entry->not_entrant()) {
 941     return; // Someone invalidated it already
 942   }
 943 #ifdef ASSERT
 944   bool found = false;
 945   if (_for_read) {
 946     uint count = _load_header->entries_count();
 947     uint i = 0;
 948     for(; i < count; i++) {
 949       if (entry == &(_load_entries[i])) {
 950         break;
 951       }
 952     }
 953     found = (i < count);
 954   }
 955   if (!found && _for_write) {
 956     uint count = _store_entries_cnt;
 957     uint i = 0;
 958     for(; i < count; i++) {
 959       if (entry == &(_store_entries[i])) {
 960         break;
 961       }
 962     }
 963     found = (i < count);
 964   }
 965   assert(found, "entry should exist");
 966 #endif
 967   entry->set_not_entrant();
 968   {
 969     uint name_offset = entry->offset() + entry->name_offset();
 970     const char* name;
 971     if (SCCache::is_loaded(entry)) {
 972       name = _load_buffer + name_offset;
 973     } else {
 974       name = _store_buffer + name_offset;
 975     }
 976     uint level   = entry->comp_level();
 977     uint comp_id = entry->comp_id();
 978     uint decomp  = entry->decompile();
 979     bool clinit_brs = entry->has_clinit_barriers();
 980     log_info(scc, nmethod)("Invalidated entry for '%s' (comp_id %d, comp_level %d, decomp: %d, hash: " UINT32_FORMAT_X_0 "%s)",
 981                            name, comp_id, level, decomp, entry->id(), (clinit_brs ? ", has clinit barriers" : ""));
 982   }
 983   if (entry->next() != nullptr) {
 984     entry = entry->next();
 985     assert(entry->has_clinit_barriers(), "expecting only such entries here");
 986     invalidate_entry(entry);
 987   }
 988 }
 989 
 990 extern "C" {
 991   static int uint_cmp(const void *i, const void *j) {
 992     uint a = *(uint *)i;
 993     uint b = *(uint *)j;
 994     return a > b ? 1 : a < b ? -1 : 0;
 995   }
 996 }
 997 
 998 bool SCCache::finish_write() {
 999   if (!align_write()) {
1000     return false;
1001   }
1002   uint strings_offset = _write_position;
1003   int strings_count = store_strings();
1004   if (strings_count < 0) {
1005     return false;
1006   }
1007   if (!align_write()) {
1008     return false;
1009   }
1010   uint strings_size = _write_position - strings_offset;
1011 
1012   uint entries_count = 0; // Number of entrant (useful) code entries
1013   uint entries_offset = _write_position;
1014 
1015   uint store_count = _store_entries_cnt;
1016   if (store_count > 0) {
1017     uint header_size = (uint)align_up(sizeof(SCCHeader),  DATA_ALIGNMENT);
1018     const char* vm_version = VM_Version::internal_vm_info_string();
1019     uint vm_version_size = (uint)align_up(strlen(vm_version) + 1, DATA_ALIGNMENT);
1020     uint load_count = (_load_header != nullptr) ? _load_header->entries_count() : 0;
1021     uint code_count = store_count + load_count;
1022     uint search_count = code_count * 2;
1023     uint search_size = search_count * sizeof(uint);
1024     uint entries_size = (uint)align_up(code_count * sizeof(SCCEntry), DATA_ALIGNMENT); // In bytes
1025     uint preload_entries_cnt = 0;
1026     uint* preload_entries = NEW_C_HEAP_ARRAY(uint, code_count, mtCode);
1027     uint preload_entries_size = code_count * sizeof(uint);
1028     // _write_position should include code and strings
1029     uint code_alignment = code_count * DATA_ALIGNMENT; // We align_up code size when storing it.
1030     uint total_size = _write_position + _load_size + header_size + vm_version_size +
1031                      code_alignment + search_size + preload_entries_size + entries_size;
1032 
1033     // Create ordered search table for entries [id, index];
1034     uint* search = NEW_C_HEAP_ARRAY(uint, search_count, mtCode);
1035     char* buffer = NEW_C_HEAP_ARRAY(char, total_size + DATA_ALIGNMENT, mtCode);
1036     char* start = align_up(buffer, DATA_ALIGNMENT);
1037     char* current = start + header_size; // Skip header
1038     uint jvm_version_offset = current - start;
1039     copy_bytes(vm_version, (address)current, (uint)strlen(vm_version) + 1);
1040     current += vm_version_size;
1041 
1042     SCCEntry* entries_address = _store_entries; // Pointer to latest entry
1043     uint not_entrant_nb = 0;
1044     uint max_size = 0;
1045     // Add old entries first
1046     if (_for_read && (_load_header != nullptr)) {
1047       for(uint i = 0; i < load_count; i++) {
1048         if (_load_entries[i].load_fail()) {
1049           continue;
1050         }
1051         if (_load_entries[i].not_entrant()) {
1052           log_info(scc, exit)("Not entrant load entry id: %d, decomp: %d, hash: " UINT32_FORMAT_X_0, i, _load_entries[i].decompile(), _load_entries[i].id());
1053           not_entrant_nb++;
1054           if (_load_entries[i].for_preload()) {
1055             // Skip not entrant preload code:
1056             // we can't pre-load code which may have failing dependencies.
1057             continue;
1058           }
1059           _load_entries[i].set_entrant(); // Reset
1060         } else if (_load_entries[i].for_preload() && _load_entries[i].method() != nullptr) {
1061           // record entrant first version code for pre-loading
1062           preload_entries[preload_entries_cnt++] = entries_count;
1063         }
1064         {
1065           uint size = align_up(_load_entries[i].size(), DATA_ALIGNMENT);
1066           if (size > max_size) {
1067             max_size = size;
1068           }
1069           copy_bytes((_load_buffer + _load_entries[i].offset()), (address)current, size);
1070           _load_entries[i].set_offset(current - start); // New offset
1071           current += size;
1072           uint n = write_bytes(&(_load_entries[i]), sizeof(SCCEntry));
1073           if (n != sizeof(SCCEntry)) {
1074             FREE_C_HEAP_ARRAY(char, buffer);
1075             FREE_C_HEAP_ARRAY(uint, search);
1076             return false;
1077           }
1078           search[entries_count*2 + 0] = _load_entries[i].id();
1079           search[entries_count*2 + 1] = entries_count;
1080           entries_count++;
1081         }
1082       }
1083     }
1084     // SCCEntry entries were allocated in reverse in store buffer.
1085     // Process them in reverse order to cache first code first.
1086     for (int i = store_count - 1; i >= 0; i--) {
1087       if (entries_address[i].load_fail()) {
1088         continue;
1089       }
1090       if (entries_address[i].not_entrant()) {
1091         log_info(scc, exit)("Not entrant new entry comp_id: %d, comp_level: %d, decomp: %d, hash: " UINT32_FORMAT_X_0 "%s", entries_address[i].comp_id(), entries_address[i].comp_level(), entries_address[i].decompile(), entries_address[i].id(), (entries_address[i].has_clinit_barriers() ? ", has clinit barriers" : ""));
1092         not_entrant_nb++;
1093         if (entries_address[i].for_preload()) {
1094           // Skip not entrant preload code:
1095           // we can't pre-load code which may have failing dependencies.
1096           continue;
1097         }
1098         entries_address[i].set_entrant(); // Reset
1099       } else if (entries_address[i].for_preload() && entries_address[i].method() != nullptr) {
1100         // record entrant first version code for pre-loading
1101         preload_entries[preload_entries_cnt++] = entries_count;
1102       }
1103       {
1104         entries_address[i].set_next(nullptr); // clear pointers before storing data
1105         uint size = align_up(entries_address[i].size(), DATA_ALIGNMENT);
1106         if (size > max_size) {
1107           max_size = size;
1108         }
1109         copy_bytes((_store_buffer + entries_address[i].offset()), (address)current, size);
1110         entries_address[i].set_offset(current - start); // New offset
1111         entries_address[i].update_method_for_writing();
1112         current += size;
1113         uint n = write_bytes(&(entries_address[i]), sizeof(SCCEntry));
1114         if (n != sizeof(SCCEntry)) {
1115           FREE_C_HEAP_ARRAY(char, buffer);
1116           FREE_C_HEAP_ARRAY(uint, search);
1117           return false;
1118         }
1119         search[entries_count*2 + 0] = entries_address[i].id();
1120         search[entries_count*2 + 1] = entries_count;
1121         entries_count++;
1122       }
1123     }
1124     if (entries_count == 0) {
1125       log_info(scc, exit)("No new entires, cache files %s was not %s", _cache_path, (_for_read ? "updated" : "created"));
1126       FREE_C_HEAP_ARRAY(char, buffer);
1127       FREE_C_HEAP_ARRAY(uint, search);
1128       return true; // Nothing to write
1129     }
1130     assert(entries_count <= (store_count + load_count), "%d > (%d + %d)", entries_count, store_count, load_count);
1131     // Write strings
1132     if (strings_count > 0) {
1133       copy_bytes((_store_buffer + strings_offset), (address)current, strings_size);
1134       strings_offset = (current - start); // New offset
1135       current += strings_size;
1136     }
1137     uint preload_entries_offset = (current - start);
1138     preload_entries_size = preload_entries_cnt * sizeof(uint);
1139     if (preload_entries_size > 0) {
1140       copy_bytes((const char*)preload_entries, (address)current, preload_entries_size);
1141       current += preload_entries_size;
1142       log_info(scc, exit)("Wrote %d preload entries to Startup Code Cache '%s'", preload_entries_cnt, _cache_path);
1143     }
1144     if (preload_entries != nullptr) {
1145       FREE_C_HEAP_ARRAY(uint, preload_entries);
1146     }
1147 
1148     uint new_entries_offset = (current - start); // New offset
1149     // Sort and store search table
1150     qsort(search, entries_count, 2*sizeof(uint), uint_cmp);
1151     search_size = 2 * entries_count * sizeof(uint);
1152     copy_bytes((const char*)search, (address)current, search_size);
1153     FREE_C_HEAP_ARRAY(uint, search);
1154     current += search_size;
1155 
1156     // Write entries
1157     entries_size = entries_count * sizeof(SCCEntry); // New size
1158     copy_bytes((_store_buffer + entries_offset), (address)current, entries_size);
1159     current += entries_size;
1160     log_info(scc, exit)("Wrote %d SCCEntry entries (%d were not entrant, %d max size) to Startup Code Cache '%s'", entries_count, not_entrant_nb, max_size, _cache_path);
1161 
1162     uint size = (current - start);
1163     assert(size <= total_size, "%d > %d", size , total_size);
1164 
1165     // Finalize header
1166     SCCHeader* header = (SCCHeader*)start;
1167     header->init(jvm_version_offset, size,
1168                  (uint)strings_count, strings_offset,
1169                  entries_count, new_entries_offset,
1170                  preload_entries_cnt, preload_entries_offset,
1171                  _use_meta_ptrs);
1172     log_info(scc, init)("Wrote header to Startup Code Cache '%s'", _cache_path);
1173 
1174     // Now store to file
1175 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
1176     chmod(_cache_path, _S_IREAD | _S_IWRITE);
1177 #endif
1178     // Use remove() to delete the existing file because, on Unix, this will
1179     // allow processes that have it open continued access to the file.
1180     remove(_cache_path);
1181     int fd = os::open(_cache_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
1182     if (fd < 0) {
1183       log_warning(scc, exit)("Unable to create Startup Code Cache file '%s': (%s)", _cache_path, os::strerror(errno));
1184       FREE_C_HEAP_ARRAY(char, buffer);
1185       return false;
1186     } else {
1187       log_info(scc, exit)("Opened for write Startup Code Cache '%s'", _cache_path);
1188     }
1189     bool success = os::write(fd, start, (size_t)size);
1190     if (!success) {
1191       log_warning(scc, exit)("Failed to write %d bytes to Startup Code Cache file '%s': (%s)", size, _cache_path, os::strerror(errno));
1192       FREE_C_HEAP_ARRAY(char, buffer);
1193       return false;
1194     }
1195     log_info(scc, exit)("Wrote %d bytes to Startup Code Cache '%s'", size, _cache_path);
1196     if (::close(fd) < 0) {
1197       log_warning(scc, exit)("Failed to close for write Startup Code Cache file '%s'", _cache_path);
1198     } else {
1199       log_info(scc, exit)("Closed for write Startup Code Cache '%s'", _cache_path);
1200     }
1201     FREE_C_HEAP_ARRAY(char, buffer);
1202   }
1203   return true;
1204 }
1205 
1206 bool SCCache::load_stub(StubCodeGenerator* cgen, vmIntrinsicID id, const char* name, address start) {
1207   assert(start == cgen->assembler()->pc(), "wrong buffer");
1208   SCCache* cache = open_for_read();
1209   if (cache == nullptr) {
1210     return false;
1211   }
1212   SCCEntry* entry = cache->find_entry(SCCEntry::Stub, (uint)id);
1213   if (entry == nullptr) {
1214     return false;
1215   }
1216   uint entry_position = entry->offset();
1217   // Read name
1218   uint name_offset = entry->name_offset() + entry_position;
1219   uint name_size   = entry->name_size(); // Includes '/0'
1220   const char* saved_name = cache->addr(name_offset);
1221   if (strncmp(name, saved_name, (name_size - 1)) != 0) {
1222     log_warning(scc)("Saved stub's name '%s' is different from '%s' for id:%d", saved_name, name, (int)id);
1223     cache->set_failed();
1224     return false;
1225   }
1226   log_info(scc,stubs)("Reading stub '%s' id:%d from Startup Code Cache '%s'", name, (int)id, cache->_cache_path);
1227   // Read code
1228   uint code_offset = entry->code_offset() + entry_position;
1229   uint code_size   = entry->code_size();
1230   copy_bytes(cache->addr(code_offset), start, code_size);
1231   cgen->assembler()->code_section()->set_end(start + code_size);
1232   log_info(scc,stubs)("Read stub '%s' id:%d from Startup Code Cache '%s'", name, (int)id, cache->_cache_path);
1233   return true;
1234 }
1235 
1236 bool SCCache::store_stub(StubCodeGenerator* cgen, vmIntrinsicID id, const char* name, address start) {
1237   SCCache* cache = open_for_write();
1238   if (cache == nullptr) {
1239     return false;
1240   }
1241   log_info(scc, stubs)("Writing stub '%s' id:%d to Startup Code Cache '%s'", name, (int)id, cache->_cache_path);
1242   if (!cache->align_write()) {
1243     return false;
1244   }
1245 #ifdef ASSERT
1246   CodeSection* cs = cgen->assembler()->code_section();
1247   if (cs->has_locs()) {
1248     uint reloc_count = cs->locs_count();
1249     tty->print_cr("======== write stubs code section relocations [%d]:", reloc_count);
1250     // Collect additional data
1251     RelocIterator iter(cs);
1252     while (iter.next()) {
1253       switch (iter.type()) {
1254         case relocInfo::none:
1255           break;
1256         default: {
1257           iter.print_current();
1258           fatal("stub's relocation %d unimplemented", (int)iter.type());
1259           break;
1260         }
1261       }
1262     }
1263   }
1264 #endif
1265   uint entry_position = cache->_write_position;
1266 
1267   // Write code
1268   uint code_offset = 0;
1269   uint code_size = cgen->assembler()->pc() - start;
1270   uint n = cache->write_bytes(start, code_size);
1271   if (n != code_size) {
1272     return false;
1273   }
1274   // Write name
1275   uint name_offset = cache->_write_position - entry_position;
1276   uint name_size = (uint)strlen(name) + 1; // Includes '/0'
1277   n = cache->write_bytes(name, name_size);
1278   if (n != name_size) {
1279     return false;
1280   }
1281   uint entry_size = cache->_write_position - entry_position;
1282   SCCEntry* entry = new(cache) SCCEntry(entry_position, entry_size, name_offset, name_size,
1283                                           code_offset, code_size, 0, 0,
1284                                           SCCEntry::Stub, (uint32_t)id);
1285   log_info(scc, stubs)("Wrote stub '%s' id:%d to Startup Code Cache '%s'", name, (int)id, cache->_cache_path);
1286   return true;
1287 }
1288 
1289 Klass* SCCReader::read_klass(const methodHandle& comp_method, bool shared) {
1290   uint code_offset = read_position();
1291   int not_init = *(int*)addr(code_offset);
1292   code_offset += sizeof(int);
1293   if (_cache->use_meta_ptrs() && shared) {
1294     uint klass_offset = *(uint*)addr(code_offset);
1295     code_offset += sizeof(uint);
1296     set_read_position(code_offset);
1297     Klass* k = (Klass*)((address)SharedBaseAddress + klass_offset);
1298     if (!MetaspaceShared::is_in_shared_metaspace((address)k)) {
1299       // Something changed in CDS
1300       set_lookup_failed();
1301       log_warning(scc)("Lookup failed for shared klass: " INTPTR_FORMAT " is not in CDS ", p2i((address)k));
1302       return nullptr;
1303     }
1304     assert(k->is_klass(), "sanity");
1305     ResourceMark rm;
1306     const char* comp_name = comp_method->name_and_sig_as_C_string();
1307     if (k->is_instance_klass() && !InstanceKlass::cast(k)->is_loaded()) {
1308       set_lookup_failed();
1309       log_warning(scc)("%d '%s' (L%d): Lookup failed for klass %s: not loaded",
1310                        compile_id(), comp_name, comp_level(), k->external_name());
1311       return nullptr;
1312     } else
1313     // Allow not initialized klass which was uninitialized during code caching or for preload
1314     if (k->is_instance_klass() && !InstanceKlass::cast(k)->is_initialized() && (not_init != 1) && !_preload) {
1315       set_lookup_failed();
1316       log_warning(scc)("%d '%s' (L%d): Lookup failed for klass %s: not initialized",
1317                        compile_id(), comp_name, comp_level(), k->external_name());
1318       return nullptr;
1319     }
1320     log_info(scc)("%d (L%d): Shared klass lookup: %s",
1321                   compile_id(), comp_level(), k->external_name());
1322     return k;
1323   }
1324   int name_length = *(int*)addr(code_offset);
1325   code_offset += sizeof(int);
1326   const char* dest = addr(code_offset);
1327   code_offset += name_length + 1;
1328   set_read_position(code_offset);
1329   TempNewSymbol klass_sym = SymbolTable::probe(&(dest[0]), name_length);
1330   if (klass_sym == nullptr) {
1331     set_lookup_failed();
1332     log_warning(scc)("%d (L%d): Probe failed for class %s",
1333                      compile_id(), comp_level(), &(dest[0]));
1334     return nullptr;
1335   }
1336   // Use class loader of compiled method.
1337   Thread* thread = Thread::current();
1338   Handle loader(thread, comp_method->method_holder()->class_loader());
1339   Handle protection_domain(thread, comp_method->method_holder()->protection_domain());
1340   Klass* k = SystemDictionary::find_instance_or_array_klass(thread, klass_sym, loader, protection_domain);
1341   assert(!thread->has_pending_exception(), "should not throw");
1342   if (k == nullptr && !loader.is_null()) {
1343     // Try default loader and domain
1344     k = SystemDictionary::find_instance_or_array_klass(thread, klass_sym, Handle(), Handle());
1345     assert(!thread->has_pending_exception(), "should not throw");
1346   }
1347   if (k != nullptr) {
1348     // Allow not initialized klass which was uninitialized during code caching
1349     if (k->is_instance_klass() && !InstanceKlass::cast(k)->is_initialized() && (not_init != 1)) {
1350       set_lookup_failed();
1351       log_warning(scc)("%d (L%d): Lookup failed for klass %s: not initialized", compile_id(), comp_level(), &(dest[0]));
1352       return nullptr;
1353     }
1354     log_info(scc)("%d (L%d): Klass lookup %s", compile_id(), comp_level(), k->external_name());
1355   } else {
1356     set_lookup_failed();
1357     log_warning(scc)("%d (L%d): Lookup failed for class %s", compile_id(), comp_level(), &(dest[0]));
1358     return nullptr;
1359   }
1360   return k;
1361 }
1362 
1363 Method* SCCReader::read_method(const methodHandle& comp_method, bool shared) {
1364   uint code_offset = read_position();
1365   if (_cache->use_meta_ptrs() && shared) {
1366     uint method_offset = *(uint*)addr(code_offset);
1367     code_offset += sizeof(uint);
1368     set_read_position(code_offset);
1369     Method* m = (Method*)((address)SharedBaseAddress + method_offset);
1370     if (!MetaspaceShared::is_in_shared_metaspace((address)m)) {
1371       // Something changed in CDS
1372       set_lookup_failed();
1373       log_warning(scc)("Lookup failed for shared method: " INTPTR_FORMAT " is not in CDS ", p2i((address)m));
1374       return nullptr;
1375     }
1376     assert(m->is_method(), "sanity");
1377     ResourceMark rm;
1378     const char* comp_name = comp_method->name_and_sig_as_C_string();
1379     Klass* k = m->method_holder();
1380     if (!k->is_instance_klass()) {
1381       set_lookup_failed();
1382       log_warning(scc)("%d '%s' (L%d): Lookup failed for holder %s: not instance klass", compile_id(), comp_name, comp_level(), k->external_name());
1383       return nullptr;
1384     } else if (!MetaspaceShared::is_in_shared_metaspace((address)k)) {
1385       set_lookup_failed();
1386       log_warning(scc)("%d '%s' (L%d): Lookup failed for holder %s: not in CDS", compile_id(), comp_name, comp_level(), k->external_name());
1387       return nullptr;
1388     } else if (!InstanceKlass::cast(k)->is_loaded()) {
1389       set_lookup_failed();
1390       log_warning(scc)("%d '%s' (L%d): Lookup failed for holder %s: not loaded", compile_id(), comp_name, comp_level(), k->external_name());
1391       return nullptr;
1392     } else if (!InstanceKlass::cast(k)->is_linked()) {
1393       set_lookup_failed();
1394       log_warning(scc)("%d '%s' (L%d): Lookup failed for holder %s: not linked%s", compile_id(), comp_name, comp_level(), k->external_name(), (_preload ? " for code preload" : ""));
1395       return nullptr;
1396     }
1397     log_info(scc)("%d (L%d): Shared method lookup: %s", compile_id(), comp_level(), m->name_and_sig_as_C_string());
1398     return m;
1399   }
1400   int holder_length = *(int*)addr(code_offset);
1401   code_offset += sizeof(int);
1402   int name_length = *(int*)addr(code_offset);
1403   code_offset += sizeof(int);
1404   int signat_length = *(int*)addr(code_offset);
1405   code_offset += sizeof(int);
1406 
1407   const char* dest = addr(code_offset);
1408   code_offset += holder_length + 1 + name_length + 1 + signat_length + 1;
1409   set_read_position(code_offset);
1410   TempNewSymbol klass_sym = SymbolTable::probe(&(dest[0]), holder_length);
1411   if (klass_sym == nullptr) {
1412     set_lookup_failed();
1413     log_warning(scc)("%d (L%d): Probe failed for class %s", compile_id(), comp_level(), &(dest[0]));
1414     return nullptr;
1415   }
1416   // Use class loader of compiled method.
1417   Thread* thread = Thread::current();
1418   Handle loader(thread, comp_method->method_holder()->class_loader());
1419   Handle protection_domain(thread, comp_method->method_holder()->protection_domain());
1420   Klass* k = SystemDictionary::find_instance_or_array_klass(thread, klass_sym, loader, protection_domain);
1421   assert(!thread->has_pending_exception(), "should not throw");
1422   if (k == nullptr && !loader.is_null()) {
1423     // Try default loader and domain
1424     k = SystemDictionary::find_instance_or_array_klass(thread, klass_sym, Handle(), Handle());
1425     assert(!thread->has_pending_exception(), "should not throw");
1426   }
1427   if (k != nullptr) {
1428     if (!k->is_instance_klass()) {
1429       set_lookup_failed();
1430       log_warning(scc)("%d (L%d): Lookup failed for holder %s: not instance klass",
1431                        compile_id(), comp_level(), &(dest[0]));
1432       return nullptr;
1433     } else if (!InstanceKlass::cast(k)->is_linked()) {
1434       set_lookup_failed();
1435       log_warning(scc)("%d (L%d): Lookup failed for holder %s: not linked",
1436                        compile_id(), comp_level(), &(dest[0]));
1437       return nullptr;
1438     }
1439     log_info(scc)("%d (L%d): Holder lookup: %s", compile_id(), comp_level(), k->external_name());
1440   } else {
1441     set_lookup_failed();
1442     log_warning(scc)("%d (L%d): Lookup failed for holder %s",
1443                   compile_id(), comp_level(), &(dest[0]));
1444     return nullptr;
1445   }
1446   TempNewSymbol name_sym = SymbolTable::probe(&(dest[holder_length + 1]), name_length);
1447   int pos = holder_length + 1 + name_length + 1;
1448   TempNewSymbol sign_sym = SymbolTable::probe(&(dest[pos]), signat_length);
1449   if (name_sym == nullptr) {
1450     set_lookup_failed();
1451     log_warning(scc)("%d (L%d): Probe failed for method name %s",
1452                      compile_id(), comp_level(), &(dest[holder_length + 1]));
1453     return nullptr;
1454   }
1455   if (sign_sym == nullptr) {
1456     set_lookup_failed();
1457     log_warning(scc)("%d (L%d): Probe failed for method signature %s",
1458                      compile_id(), comp_level(), &(dest[pos]));
1459     return nullptr;
1460   }
1461   Method* m = InstanceKlass::cast(k)->find_method(name_sym, sign_sym);
1462   if (m != nullptr) {
1463     ResourceMark rm;
1464     log_info(scc)("%d (L%d): Method lookup: %s", compile_id(), comp_level(), m->name_and_sig_as_C_string());
1465   } else {
1466     set_lookup_failed();
1467     log_warning(scc)("%d (L%d): Lookup failed for method %s::%s%s",
1468                      compile_id(), comp_level(), &(dest[0]), &(dest[holder_length + 1]), &(dest[pos]));
1469     return nullptr;
1470   }
1471   return m;
1472 }
1473 
1474 bool SCCache::write_klass(Klass* klass) {
1475   if (klass->is_hidden()) { // Skip such nmethod
1476     set_lookup_failed();
1477     return false;
1478   }
1479   bool can_use_meta_ptrs = _use_meta_ptrs;
1480   int not_init = 0;
1481   if (klass->is_instance_klass()) {
1482     InstanceKlass* ik = InstanceKlass::cast(klass);
1483     ClassLoaderData* cld = ik->class_loader_data();
1484     if (!cld->is_builtin_class_loader_data()) {
1485       set_lookup_failed();
1486       return false;
1487     }
1488     if (_for_preload && !CDSAccess::can_generate_cached_code(ik)) {
1489       _for_preload = false;
1490       // Bailout if code has clinit barriers:
1491       // method will be recompiled without them in any case
1492       if (_has_clinit_barriers) {
1493         set_lookup_failed();
1494         return false;    
1495       }
1496       can_use_meta_ptrs = false;
1497     }
1498     not_init = !ik->is_initialized() ? 1 : 0;
1499   }
1500   ResourceMark rm;
1501   if (can_use_meta_ptrs && CDSAccess::can_generate_cached_code(klass)) {
1502     DataKind kind = DataKind::Klass_Shared;
1503     uint n = write_bytes(&kind, sizeof(int));
1504     if (n != sizeof(int)) {
1505       return false;
1506     }
1507     // Record state of instance klass initialization.
1508     n = write_bytes(&not_init, sizeof(int));
1509     if (n != sizeof(int)) {
1510       return false;
1511     }
1512     uint klass_offset = CDSAccess::delta_from_shared_address_base((address)klass);
1513     n = write_bytes(&klass_offset, sizeof(uint));
1514     if (n != sizeof(uint)) {
1515       return false;
1516     }
1517     log_info(scc)("%d (L%d): Wrote shared klass: %s%s @ 0x%08x", compile_id(), comp_level(), klass->external_name(),
1518                   (!klass->is_instance_klass() ? "" : ((not_init == 0) ? " (initialized)" : " (not-initialized)")), klass_offset);
1519     return true;
1520   }
1521   // Bailout if code has clinit barriers:
1522   // method will be recompiled without them in any case
1523   if (_for_preload && _has_clinit_barriers) {
1524     set_lookup_failed();
1525     return false;
1526   }
1527   _for_preload = false;
1528   log_info(scc,cds)("%d (L%d): Not shared klass: %s", compile_id(), comp_level(), klass->external_name());
1529   DataKind kind = DataKind::Klass;
1530   uint n = write_bytes(&kind, sizeof(int));
1531   if (n != sizeof(int)) {
1532     return false;
1533   }
1534   // Record state of instance klass initialization.
1535   n = write_bytes(&not_init, sizeof(int));
1536   if (n != sizeof(int)) {
1537     return false;
1538   }
1539   Symbol* name = klass->name();
1540   int name_length = name->utf8_length();
1541   int total_length = name_length + 1;
1542   char* dest = NEW_RESOURCE_ARRAY(char, total_length);
1543   name->as_C_string(dest, total_length);
1544   dest[total_length - 1] = '\0';
1545   LogTarget(Info, scc, loader) log;
1546   if (log.is_enabled()) {
1547     LogStream ls(log);
1548     oop loader = klass->class_loader();
1549     oop domain = klass->protection_domain();
1550     ls.print("Class %s loader: ", dest);
1551     if (loader == nullptr) {
1552       ls.print("nullptr");
1553     } else {
1554       loader->print_value_on(&ls);
1555     }
1556     ls.print(" domain: ");
1557     if (domain == nullptr) {
1558       ls.print("nullptr");
1559     } else {
1560       domain->print_value_on(&ls);
1561     }
1562     ls.cr();
1563   }
1564   n = write_bytes(&name_length, sizeof(int));
1565   if (n != sizeof(int)) {
1566     return false;
1567   }
1568   n = write_bytes(dest, total_length);
1569   if (n != (uint)total_length) {
1570     return false;
1571   }
1572   log_info(scc)("%d (L%d): Wrote klass: %s%s",
1573                 compile_id(), comp_level(),
1574                 dest, (!klass->is_instance_klass() ? "" : ((not_init == 0) ? " (initialized)" : " (not-initialized)")));
1575   return true;
1576 }
1577 
1578 bool SCCache::write_method(Method* method) {
1579   if (method->is_hidden()) { // Skip such nmethod
1580     set_lookup_failed();
1581     return false;
1582   }
1583   bool can_use_meta_ptrs = _use_meta_ptrs;
1584   Klass* klass = method->method_holder();
1585   if (klass->is_instance_klass()) {
1586     InstanceKlass* ik = InstanceKlass::cast(klass);
1587     ClassLoaderData* cld = ik->class_loader_data();
1588     if (!cld->is_builtin_class_loader_data()) {
1589       set_lookup_failed();
1590       return false;
1591     }
1592     if (_for_preload && !CDSAccess::can_generate_cached_code(ik)) {
1593       _for_preload = false;
1594       // Bailout if code has clinit barriers:
1595       // method will be recompiled without them in any case
1596       if (_has_clinit_barriers) {
1597         set_lookup_failed();
1598         return false;
1599       }
1600       can_use_meta_ptrs = false;
1601     }
1602   }
1603   ResourceMark rm;
1604   if (can_use_meta_ptrs && CDSAccess::can_generate_cached_code(method)) {
1605     DataKind kind = DataKind::Method_Shared;
1606     uint n = write_bytes(&kind, sizeof(int));
1607     if (n != sizeof(int)) {
1608       return false;
1609     }
1610     uint method_offset = CDSAccess::delta_from_shared_address_base((address)method);
1611     n = write_bytes(&method_offset, sizeof(uint));
1612     if (n != sizeof(uint)) {
1613       return false;
1614     }
1615     log_info(scc)("%d (L%d): Wrote shared method: %s @ 0x%08x", compile_id(), comp_level(), method->name_and_sig_as_C_string(), method_offset);
1616     return true;
1617   }
1618   // Bailout if code has clinit barriers:
1619   // method will be recompiled without them in any case
1620   if (_for_preload && _has_clinit_barriers) {
1621     set_lookup_failed();
1622     return false;
1623   }
1624   _for_preload = false;
1625   log_info(scc,cds)("%d (L%d): Not shared method: %s", compile_id(), comp_level(), method->name_and_sig_as_C_string());
1626   DataKind kind = DataKind::Method;
1627   uint n = write_bytes(&kind, sizeof(int));
1628   if (n != sizeof(int)) {
1629     return false;
1630   }
1631   Symbol* name   = method->name();
1632   Symbol* holder = method->klass_name();
1633   Symbol* signat = method->signature();
1634   int name_length   = name->utf8_length();
1635   int holder_length = holder->utf8_length();
1636   int signat_length = signat->utf8_length();
1637 
1638   // Write sizes and strings
1639   int total_length = holder_length + 1 + name_length + 1 + signat_length + 1;
1640   char* dest = NEW_RESOURCE_ARRAY(char, total_length);
1641   holder->as_C_string(dest, total_length);
1642   dest[holder_length] = '\0';
1643   int pos = holder_length + 1;
1644   name->as_C_string(&(dest[pos]), (total_length - pos));
1645   pos += name_length;
1646   dest[pos++] = '\0';
1647   signat->as_C_string(&(dest[pos]), (total_length - pos));
1648   dest[total_length - 1] = '\0';
1649 
1650   LogTarget(Info, scc, loader) log;
1651   if (log.is_enabled()) {
1652     LogStream ls(log);
1653     oop loader = klass->class_loader();
1654     oop domain = klass->protection_domain();
1655     ls.print("Holder %s loader: ", dest);
1656     if (loader == nullptr) {
1657       ls.print("nullptr");
1658     } else {
1659       loader->print_value_on(&ls);
1660     }
1661     ls.print(" domain: ");
1662     if (domain == nullptr) {
1663       ls.print("nullptr");
1664     } else {
1665       domain->print_value_on(&ls);
1666     }
1667     ls.cr();
1668   }
1669 
1670   n = write_bytes(&holder_length, sizeof(int));
1671   if (n != sizeof(int)) {
1672     return false;
1673   }
1674   n = write_bytes(&name_length, sizeof(int));
1675   if (n != sizeof(int)) {
1676     return false;
1677   }
1678   n = write_bytes(&signat_length, sizeof(int));
1679   if (n != sizeof(int)) {
1680     return false;
1681   }
1682   n = write_bytes(dest, total_length);
1683   if (n != (uint)total_length) {
1684     return false;
1685   }
1686   dest[holder_length] = ' ';
1687   dest[holder_length + 1 + name_length] = ' ';
1688   log_info(scc)("%d (L%d): Wrote method: %s", compile_id(), comp_level(), dest);
1689   return true;
1690 }
1691 
1692 // Repair the pc relative information in the code after load
1693 bool SCCReader::read_relocations(CodeBuffer* buffer, CodeBuffer* orig_buffer,
1694                                  OopRecorder* oop_recorder, ciMethod* target) {
1695   bool success = true;
1696   for (int i = 0; i < (int)CodeBuffer::SECT_LIMIT; i++) {
1697     uint code_offset = read_position();
1698     int reloc_count = *(int*)addr(code_offset);
1699     code_offset += sizeof(int);
1700     if (reloc_count == 0) {
1701       set_read_position(code_offset);
1702       continue;
1703     }
1704     // Read _locs_point (as offset from start)
1705     int locs_point_off = *(int*)addr(code_offset);
1706     code_offset += sizeof(int);
1707     uint reloc_size = reloc_count * sizeof(relocInfo);
1708     CodeSection* cs  = buffer->code_section(i);
1709     if (cs->locs_capacity() < reloc_count) {
1710       cs->expand_locs(reloc_count);
1711     }
1712     relocInfo* reloc_start = cs->locs_start();
1713     copy_bytes(addr(code_offset), (address)reloc_start, reloc_size);
1714     code_offset += reloc_size;
1715     cs->set_locs_end(reloc_start + reloc_count);
1716     cs->set_locs_point(cs->start() + locs_point_off);
1717 
1718     // Read additional relocation data: uint per relocation
1719     uint  data_size  = reloc_count * sizeof(uint);
1720     uint* reloc_data = (uint*)addr(code_offset);
1721     code_offset += data_size;
1722     set_read_position(code_offset);
1723     LogTarget(Info, scc, reloc) log;
1724     if (log.is_enabled()) {
1725       LogStream ls(log);
1726       ls.print_cr("======== read code section %d relocations [%d]:", i, reloc_count);
1727     }
1728     RelocIterator iter(cs);
1729     int j = 0;
1730     while (iter.next()) {
1731       switch (iter.type()) {
1732         case relocInfo::none:
1733           break;
1734         case relocInfo::oop_type: {
1735           VM_ENTRY_MARK;
1736           oop_Relocation* r = (oop_Relocation*)iter.reloc();
1737           if (r->oop_is_immediate()) {
1738             assert(reloc_data[j] == (uint)j, "should be");
1739             methodHandle comp_method(THREAD, target->get_Method());
1740             jobject jo = read_oop(THREAD, comp_method);
1741             if (lookup_failed()) {
1742               success = false;
1743               break;
1744             }
1745             r->set_value((address)jo);
1746           } else if (false) {
1747             // Get already updated value from OopRecorder.
1748             assert(oop_recorder != nullptr, "sanity");
1749             int index = r->oop_index();
1750             jobject jo = oop_recorder->oop_at(index);
1751             oop obj = JNIHandles::resolve(jo);
1752             r->set_value(*reinterpret_cast<address*>(&obj));
1753           }
1754           break;
1755         }
1756         case relocInfo::metadata_type: {
1757           VM_ENTRY_MARK;
1758           metadata_Relocation* r = (metadata_Relocation*)iter.reloc();
1759           Metadata* m;
1760           if (r->metadata_is_immediate()) {
1761             assert(reloc_data[j] == (uint)j, "should be");
1762             methodHandle comp_method(THREAD, target->get_Method());
1763             m = read_metadata(comp_method);
1764             if (lookup_failed()) {
1765               success = false;
1766               break;
1767             }
1768           } else {
1769             // Get already updated value from OopRecorder.
1770             assert(oop_recorder != nullptr, "sanity");
1771             int index = r->metadata_index();
1772             m = oop_recorder->metadata_at(index);
1773           }
1774           r->set_value((address)m);
1775           break;
1776         }
1777         case relocInfo::virtual_call_type:   // Fall through. They all call resolve_*_call blobs.
1778         case relocInfo::opt_virtual_call_type:
1779         case relocInfo::static_call_type: {
1780           address dest = _cache->address_for_id(reloc_data[j]);
1781           if (dest != (address)-1) {
1782             ((CallRelocation*)iter.reloc())->set_destination(dest);
1783           }
1784           break;
1785         }
1786         case relocInfo::trampoline_stub_type: {
1787           address dest = _cache->address_for_id(reloc_data[j]);
1788           if (dest != (address)-1) {
1789             ((trampoline_stub_Relocation*)iter.reloc())->set_destination(dest);
1790           }
1791           break;
1792         }
1793         case relocInfo::static_stub_type:
1794           break;
1795         case relocInfo::runtime_call_type: {
1796           address dest = _cache->address_for_id(reloc_data[j]);
1797           if (dest != (address)-1) {
1798             ((CallRelocation*)iter.reloc())->set_destination(dest);
1799           }
1800           break;
1801         }
1802         case relocInfo::runtime_call_w_cp_type:
1803           fatal("runtime_call_w_cp_type unimplemented");
1804           //address destination = iter.reloc()->value();
1805           break;
1806         case relocInfo::external_word_type: {
1807           address target = _cache->address_for_id(reloc_data[j]);
1808           int data_len = iter.datalen();
1809           if (data_len > 0) {
1810             // Overwrite RelocInfo embedded address
1811             RelocationHolder rh = external_word_Relocation::spec(target);
1812             external_word_Relocation* new_reloc = (external_word_Relocation*)rh.reloc();
1813             short buf[4] = {0}; // 8 bytes
1814             short* p = new_reloc->pack_data_to(buf);
1815             if ((p - buf) != data_len) {
1816               return false; // New address does not fit into old relocInfo
1817             }
1818             short* data = iter.data();
1819             for (int i = 0; i < data_len; i++) {
1820               data[i] = buf[i];
1821             }
1822           }
1823           external_word_Relocation* reloc = (external_word_Relocation*)iter.reloc();
1824           reloc->set_value(target); // Patch address in the code
1825           iter.reloc()->fix_relocation_after_move(orig_buffer, buffer);
1826           break;
1827         }
1828         case relocInfo::internal_word_type:
1829           iter.reloc()->fix_relocation_after_move(orig_buffer, buffer);
1830           break;
1831         case relocInfo::section_word_type:
1832           iter.reloc()->fix_relocation_after_move(orig_buffer, buffer);
1833           break;
1834         case relocInfo::poll_type:
1835           break;
1836         case relocInfo::poll_return_type:
1837           break;
1838         case relocInfo::post_call_nop_type:
1839           break;
1840         case relocInfo::entry_guard_type:
1841           break;
1842         default:
1843           fatal("relocation %d unimplemented", (int)iter.type());
1844           break;
1845       }
1846 #ifdef ASSERT
1847       if (success && log.is_enabled()) {
1848         iter.print_current();
1849       }
1850 #endif
1851       j++;
1852     }
1853     assert(j <= (int)reloc_count, "sanity");
1854   }
1855   return success;
1856 }
1857 
1858 bool SCCReader::read_code(CodeBuffer* buffer, CodeBuffer* orig_buffer, uint code_offset) {
1859   assert(code_offset == align_up(code_offset, DATA_ALIGNMENT), "%d not aligned to %d", code_offset, DATA_ALIGNMENT);
1860   assert(buffer->blob() != nullptr, "sanity");
1861   SCCodeSection* scc_cs = (SCCodeSection*)addr(code_offset);
1862   for (int i = 0; i < (int)CodeBuffer::SECT_LIMIT; i++) {
1863     CodeSection* cs = buffer->code_section(i);
1864     // Read original section size and address.
1865     uint orig_size = scc_cs[i]._size;
1866     log_debug(scc)("======== read code section %d [%d]:", i, orig_size);
1867     uint orig_size_align = align_up(orig_size, DATA_ALIGNMENT);
1868     if (i != (int)CodeBuffer::SECT_INSTS) {
1869       buffer->initialize_section_size(cs, orig_size_align);
1870     }
1871     if (orig_size_align > (uint)cs->capacity()) { // Will not fit
1872       log_warning(scc)("%d (L%d): original code section %d size %d > current capacity %d",
1873                        compile_id(), comp_level(), i, orig_size, cs->capacity());
1874       return false;
1875     }
1876     if (orig_size == 0) {
1877       assert(cs->size() == 0, "should match");
1878       continue;  // skip trivial section
1879     }
1880     address orig_start = scc_cs[i]._origin_address;
1881 
1882     // Populate fake original buffer (no code allocation in CodeCache).
1883     // It is used for relocations to calculate sections addesses delta.
1884     CodeSection* orig_cs = orig_buffer->code_section(i);
1885     assert(!orig_cs->is_allocated(), "This %d section should not be set", i);
1886     orig_cs->initialize(orig_start, orig_size);
1887 
1888     // Load code to new buffer.
1889     address code_start = cs->start();
1890     copy_bytes(addr(scc_cs[i]._offset + code_offset), code_start, orig_size_align);
1891     cs->set_end(code_start + orig_size);
1892   }
1893 
1894   return true;
1895 }
1896 
1897 bool SCCache::load_exception_blob(CodeBuffer* buffer, int* pc_offset) {
1898 #ifdef ASSERT
1899   LogTarget(Debug, scc, nmethod) log;
1900   if (log.is_enabled()) {
1901     FlagSetting fs(PrintRelocations, true);
1902     buffer->print();
1903   }
1904 #endif
1905   SCCache* cache = open_for_read();
1906   if (cache == nullptr) {
1907     return false;
1908   }
1909   SCCEntry* entry = cache->find_entry(SCCEntry::Blob, 999);
1910   if (entry == nullptr) {
1911     return false;
1912   }
1913   SCCReader reader(cache, entry, nullptr);
1914   return reader.compile_blob(buffer, pc_offset);
1915 }
1916 
1917 bool SCCReader::compile_blob(CodeBuffer* buffer, int* pc_offset) {
1918   uint entry_position = _entry->offset();
1919 
1920   // Read pc_offset
1921   *pc_offset = *(int*)addr(entry_position);
1922 
1923   // Read name
1924   uint name_offset = entry_position + _entry->name_offset();
1925   uint name_size = _entry->name_size(); // Includes '/0'
1926   const char* name = addr(name_offset);
1927 
1928   log_info(scc, stubs)("%d (L%d): Reading blob '%s' with pc_offset %d from Startup Code Cache '%s'",
1929                        compile_id(), comp_level(), name, *pc_offset, _cache->cache_path());
1930 
1931   if (strncmp(buffer->name(), name, (name_size - 1)) != 0) {
1932     log_warning(scc)("%d (L%d): Saved blob's name '%s' is different from '%s'",
1933                      compile_id(), comp_level(), name, buffer->name());
1934     ((SCCache*)_cache)->set_failed();
1935     return false;
1936   }
1937 
1938   // Create fake original CodeBuffer
1939   CodeBuffer orig_buffer(name);
1940 
1941   // Read code
1942   uint code_offset = entry_position + _entry->code_offset();
1943   if (!read_code(buffer, &orig_buffer, code_offset)) {
1944     return false;
1945   }
1946 
1947   // Read relocations
1948   uint reloc_offset = entry_position + _entry->reloc_offset();
1949   set_read_position(reloc_offset);
1950   if (!read_relocations(buffer, &orig_buffer, nullptr, nullptr)) {
1951     return false;
1952   }
1953 
1954   log_info(scc, stubs)("%d (L%d): Read blob '%s' from Startup Code Cache '%s'",
1955                        compile_id(), comp_level(), name, _cache->cache_path());
1956 #ifdef ASSERT
1957   LogTarget(Debug, scc, nmethod) log;
1958   if (log.is_enabled()) {
1959     FlagSetting fs(PrintRelocations, true);
1960     buffer->print();
1961     buffer->decode();
1962   }
1963 #endif
1964   return true;
1965 }
1966 
1967 bool SCCache::write_relocations(CodeBuffer* buffer, uint& all_reloc_size) {
1968   uint all_reloc_count = 0;
1969   for (int i = 0; i < (int)CodeBuffer::SECT_LIMIT; i++) {
1970     CodeSection* cs = buffer->code_section(i);
1971     uint reloc_count = cs->has_locs() ? cs->locs_count() : 0;
1972     all_reloc_count += reloc_count;
1973   }
1974   all_reloc_size = all_reloc_count * sizeof(relocInfo);
1975   bool success = true;
1976   uint* reloc_data = NEW_C_HEAP_ARRAY(uint, all_reloc_count, mtCode);
1977   for (int i = 0; i < (int)CodeBuffer::SECT_LIMIT; i++) {
1978     CodeSection* cs = buffer->code_section(i);
1979     int reloc_count = cs->has_locs() ? cs->locs_count() : 0;
1980     uint n = write_bytes(&reloc_count, sizeof(int));
1981     if (n != sizeof(int)) {
1982       success = false;
1983       break;
1984     }
1985     if (reloc_count == 0) {
1986       continue;
1987     }
1988     // Write _locs_point (as offset from start)
1989     int locs_point_off = cs->locs_point_off();
1990     n = write_bytes(&locs_point_off, sizeof(int));
1991     if (n != sizeof(int)) {
1992       success = false;
1993       break;
1994     }
1995     relocInfo* reloc_start = cs->locs_start();
1996     uint reloc_size      = reloc_count * sizeof(relocInfo);
1997     n = write_bytes(reloc_start, reloc_size);
1998     if (n != reloc_size) {
1999       success = false;
2000       break;
2001     }
2002     LogTarget(Info, scc, reloc) log;
2003     if (log.is_enabled()) {
2004       LogStream ls(log);
2005       ls.print_cr("======== write code section %d relocations [%d]:", i, reloc_count);
2006     }
2007     // Collect additional data
2008     RelocIterator iter(cs);
2009     bool has_immediate = false;
2010     int j = 0;
2011     while (iter.next()) {
2012       reloc_data[j] = 0; // initialize
2013       switch (iter.type()) {
2014         case relocInfo::none:
2015           break;
2016         case relocInfo::oop_type: {
2017           oop_Relocation* r = (oop_Relocation*)iter.reloc();
2018           if (r->oop_is_immediate()) {
2019             reloc_data[j] = (uint)j; // Indication that we need to restore immediate
2020             has_immediate = true;
2021           }
2022           break;
2023         }
2024         case relocInfo::metadata_type: {
2025           metadata_Relocation* r = (metadata_Relocation*)iter.reloc();
2026           if (r->metadata_is_immediate()) {
2027             reloc_data[j] = (uint)j; // Indication that we need to restore immediate
2028             has_immediate = true;
2029           }
2030           break;
2031         }
2032         case relocInfo::virtual_call_type:  // Fall through. They all call resolve_*_call blobs.
2033         case relocInfo::opt_virtual_call_type:
2034         case relocInfo::static_call_type: {
2035           CallRelocation* r = (CallRelocation*)iter.reloc();
2036           address dest = r->destination();
2037           if (dest == r->addr()) { // possible call via trampoline on Aarch64
2038             dest = (address)-1;    // do nothing in this case when loading this relocation
2039           }
2040           reloc_data[j] = _table->id_for_address(dest, iter, buffer);
2041           break;
2042         }
2043         case relocInfo::trampoline_stub_type: {
2044           address dest = ((trampoline_stub_Relocation*)iter.reloc())->destination();
2045           reloc_data[j] = _table->id_for_address(dest, iter, buffer);
2046           break;
2047         }
2048         case relocInfo::static_stub_type:
2049           break;
2050         case relocInfo::runtime_call_type: {
2051           // Record offset of runtime destination
2052           CallRelocation* r = (CallRelocation*)iter.reloc();
2053           address dest = r->destination();
2054           if (dest == r->addr()) { // possible call via trampoline on Aarch64
2055             dest = (address)-1;    // do nothing in this case when loading this relocation
2056           }
2057           reloc_data[j] = _table->id_for_address(dest, iter, buffer);
2058           break;
2059         }
2060         case relocInfo::runtime_call_w_cp_type:
2061           fatal("runtime_call_w_cp_type unimplemented");
2062           break;
2063         case relocInfo::external_word_type: {
2064           // Record offset of runtime target
2065           address target = ((external_word_Relocation*)iter.reloc())->target();
2066           reloc_data[j] = _table->id_for_address(target, iter, buffer);
2067           break;
2068         }
2069         case relocInfo::internal_word_type:
2070           break;
2071         case relocInfo::section_word_type:
2072           break;
2073         case relocInfo::poll_type:
2074           break;
2075         case relocInfo::poll_return_type:
2076           break;
2077         case relocInfo::post_call_nop_type:
2078           break;
2079         case relocInfo::entry_guard_type:
2080           break;
2081         default:
2082           fatal("relocation %d unimplemented", (int)iter.type());
2083           break;
2084       }
2085 #ifdef ASSERT
2086       if (log.is_enabled()) {
2087         iter.print_current();
2088       }
2089 #endif
2090       j++;
2091     }
2092     assert(j <= (int)reloc_count, "sanity");
2093     // Write additional relocation data: uint per relocation
2094     uint data_size = reloc_count * sizeof(uint);
2095     n = write_bytes(reloc_data, data_size);
2096     if (n != data_size) {
2097       success = false;
2098       break;
2099     }
2100     if (has_immediate) {
2101       // Save information about immediates in this Code Section
2102       RelocIterator iter_imm(cs);
2103       int j = 0;
2104       while (iter_imm.next()) {
2105         switch (iter_imm.type()) {
2106           case relocInfo::oop_type: {
2107             oop_Relocation* r = (oop_Relocation*)iter_imm.reloc();
2108             if (r->oop_is_immediate()) {
2109               assert(reloc_data[j] == (uint)j, "should be");
2110               jobject jo = *(jobject*)(r->oop_addr()); // Handle currently
2111               if (!write_oop(jo)) {
2112                 success = false;
2113               }
2114             }
2115             break;
2116           }
2117           case relocInfo::metadata_type: {
2118             metadata_Relocation* r = (metadata_Relocation*)iter_imm.reloc();
2119             if (r->metadata_is_immediate()) {
2120               assert(reloc_data[j] == (uint)j, "should be");
2121               Metadata* m = r->metadata_value();
2122               if (!write_metadata(m)) {
2123                 success = false;
2124               }
2125             }
2126             break;
2127           }
2128           default:
2129             break;
2130         }
2131         if (!success) {
2132           break;
2133         }
2134         j++;
2135       } // while (iter_imm.next())
2136     } // if (has_immediate)
2137   } // for(i < SECT_LIMIT)
2138   FREE_C_HEAP_ARRAY(uint, reloc_data);
2139   return success;
2140 }
2141 
2142 bool SCCache::write_code(CodeBuffer* buffer, uint& code_size) {
2143   assert(_write_position == align_up(_write_position, DATA_ALIGNMENT), "%d not aligned to %d", _write_position, DATA_ALIGNMENT);
2144   //assert(buffer->blob() != nullptr, "sanity");
2145   uint code_offset = _write_position;
2146   uint cb_total_size = (uint)buffer->total_content_size();
2147   // Write information about Code sections first.
2148   SCCodeSection scc_cs[CodeBuffer::SECT_LIMIT];
2149   uint scc_cs_size = (uint)(sizeof(SCCodeSection) * CodeBuffer::SECT_LIMIT);
2150   uint offset = align_up(scc_cs_size, DATA_ALIGNMENT);
2151   uint total_size = 0;
2152   for (int i = 0; i < (int)CodeBuffer::SECT_LIMIT; i++) {
2153     const CodeSection* cs = buffer->code_section(i);
2154     assert(cs->mark() == nullptr, "CodeSection::_mark is not implemented");
2155     uint cs_size = (uint)cs->size();
2156     scc_cs[i]._size = cs_size;
2157     scc_cs[i]._origin_address = (cs_size == 0) ? nullptr : cs->start();
2158     scc_cs[i]._offset = (cs_size == 0) ? 0 : (offset + total_size);
2159     assert(cs->mark() == nullptr, "CodeSection::_mark is not implemented");
2160     total_size += align_up(cs_size, DATA_ALIGNMENT);
2161   }
2162   uint n = write_bytes(scc_cs, scc_cs_size);
2163   if (n != scc_cs_size) {
2164     return false;
2165   }
2166   if (!align_write()) {
2167     return false;
2168   }
2169   assert(_write_position == (code_offset + offset), "%d  != (%d + %d)", _write_position, code_offset, offset);
2170   for (int i = 0; i < (int)CodeBuffer::SECT_LIMIT; i++) {
2171     const CodeSection* cs = buffer->code_section(i);
2172     uint cs_size = (uint)cs->size();
2173     if (cs_size == 0) {
2174       continue;  // skip trivial section
2175     }
2176     assert((_write_position - code_offset) == scc_cs[i]._offset, "%d != %d", _write_position, scc_cs[i]._offset);
2177     // Write code
2178     n = write_bytes(cs->start(), cs_size);
2179     if (n != cs_size) {
2180       return false;
2181     }
2182     if (!align_write()) {
2183       return false;
2184     }
2185   }
2186   assert((_write_position - code_offset) == (offset + total_size), "(%d - %d) != (%d + %d)", _write_position, code_offset, offset, total_size);
2187   code_size = total_size;
2188   return true;
2189 }
2190 
2191 bool SCCache::store_exception_blob(CodeBuffer* buffer, int pc_offset) {
2192   SCCache* cache = open_for_write();
2193   if (cache == nullptr) {
2194     return false;
2195   }
2196   log_info(scc, stubs)("Writing blob '%s' to Startup Code Cache '%s'", buffer->name(), cache->_cache_path);
2197 
2198 #ifdef ASSERT
2199   LogTarget(Debug, scc, nmethod) log;
2200   if (log.is_enabled()) {
2201     FlagSetting fs(PrintRelocations, true);
2202     buffer->print();
2203     buffer->decode();
2204   }
2205 #endif
2206   if (!cache->align_write()) {
2207     return false;
2208   }
2209   uint entry_position = cache->_write_position;
2210 
2211   // Write pc_offset
2212   uint n = cache->write_bytes(&pc_offset, sizeof(int));
2213   if (n != sizeof(int)) {
2214     return false;
2215   }
2216 
2217   // Write name
2218   const char* name = buffer->name();
2219   uint name_offset = cache->_write_position - entry_position;
2220   uint name_size = (uint)strlen(name) + 1; // Includes '/0'
2221   n = cache->write_bytes(name, name_size);
2222   if (n != name_size) {
2223     return false;
2224   }
2225 
2226   // Write code section
2227   if (!cache->align_write()) {
2228     return false;
2229   }
2230   uint code_offset = cache->_write_position - entry_position;
2231   uint code_size = 0;
2232   if (!cache->write_code(buffer, code_size)) {
2233     return false;
2234   }
2235   // Write relocInfo array
2236   uint reloc_offset = cache->_write_position - entry_position;
2237   uint reloc_size = 0;
2238   if (!cache->write_relocations(buffer, reloc_size)) {
2239     return false;
2240   }
2241 
2242   uint entry_size = cache->_write_position - entry_position;
2243   SCCEntry* entry = new(cache) SCCEntry(entry_position, entry_size, name_offset, name_size,
2244                                           code_offset, code_size, reloc_offset, reloc_size,
2245                                           SCCEntry::Blob, (uint32_t)999);
2246   log_info(scc, stubs)("Wrote stub '%s' to Startup Code Cache '%s'", name, cache->_cache_path);
2247   return true;
2248 }
2249 
2250 DebugInformationRecorder* SCCReader::read_debug_info(OopRecorder* oop_recorder) {
2251   uint code_offset = align_up(read_position(), DATA_ALIGNMENT);
2252   int data_size  = *(int*)addr(code_offset);
2253   code_offset   += sizeof(int);
2254   int pcs_length = *(int*)addr(code_offset);
2255   code_offset   += sizeof(int);
2256 
2257   log_debug(scc)("======== read DebugInfo [%d, %d]:", data_size, pcs_length);
2258 
2259   // Aligned initial sizes
2260   int data_size_align  = align_up(data_size, DATA_ALIGNMENT);
2261   int pcs_length_align = pcs_length + 1;
2262   assert(sizeof(PcDesc) > DATA_ALIGNMENT, "sanity");
2263   DebugInformationRecorder* recorder = new DebugInformationRecorder(oop_recorder, data_size_align, pcs_length);
2264 
2265   copy_bytes(addr(code_offset), recorder->stream()->buffer(), data_size_align);
2266   recorder->stream()->set_position(data_size);
2267   code_offset += data_size;
2268 
2269   uint pcs_size = pcs_length * sizeof(PcDesc);
2270   copy_bytes(addr(code_offset), (address)recorder->pcs(), pcs_size);
2271   code_offset += pcs_size;
2272   set_read_position(code_offset);
2273   return recorder;
2274 }
2275 
2276 bool SCCache::write_debug_info(DebugInformationRecorder* recorder) {
2277   if (!align_write()) {
2278     return false;
2279   }
2280   // Don't call data_size() and pcs_size(). They will freeze OopRecorder.
2281   int data_size = recorder->stream()->position(); // In bytes
2282   uint n = write_bytes(&data_size, sizeof(int));
2283   if (n != sizeof(int)) {
2284     return false;
2285   }
2286   int pcs_length = recorder->pcs_length(); // In bytes
2287   n = write_bytes(&pcs_length, sizeof(int));
2288   if (n != sizeof(int)) {
2289     return false;
2290   }
2291   n = write_bytes(recorder->stream()->buffer(), data_size);
2292   if (n != (uint)data_size) {
2293     return false;
2294   }
2295   uint pcs_size = pcs_length * sizeof(PcDesc);
2296   n = write_bytes(recorder->pcs(), pcs_size);
2297   if (n != pcs_size) {
2298     return false;
2299   }
2300   return true;
2301 }
2302 
2303 OopMapSet* SCCReader::read_oop_maps() {
2304   uint code_offset = read_position();
2305   int om_count = *(int*)addr(code_offset);
2306   code_offset += sizeof(int);
2307 
2308   log_debug(scc)("======== read oop maps [%d]:", om_count);
2309 
2310   OopMapSet* oop_maps = new OopMapSet(om_count);
2311   for (int i = 0; i < (int)om_count; i++) {
2312     int data_size = *(int*)addr(code_offset);
2313     code_offset += sizeof(int);
2314 
2315     OopMap* oop_map = new OopMap(data_size);
2316     // Preserve allocated stream
2317     CompressedWriteStream* stream = oop_map->write_stream();
2318 
2319     // Read data which overwrites default data
2320     copy_bytes(addr(code_offset), (address)oop_map, sizeof(OopMap));
2321     code_offset += sizeof(OopMap);
2322     stream->set_position(data_size);
2323     oop_map->set_write_stream(stream);
2324     if (data_size > 0) {
2325       copy_bytes(addr(code_offset), (address)(oop_map->data()), (uint)data_size);
2326       code_offset += data_size;
2327     }
2328 #ifdef ASSERT
2329     oop_map->_locs_length = 0;
2330     oop_map->_locs_used   = nullptr;
2331 #endif
2332     oop_maps->add(oop_map);
2333   }
2334   set_read_position(code_offset);
2335   return oop_maps;
2336 }
2337 
2338 bool SCCache::write_oop_maps(OopMapSet* oop_maps) {
2339   uint om_count = oop_maps->size();
2340   uint n = write_bytes(&om_count, sizeof(int));
2341   if (n != sizeof(int)) {
2342     return false;
2343   }
2344   for (int i = 0; i < (int)om_count; i++) {
2345     OopMap* om = oop_maps->at(i);
2346     int data_size = om->data_size();
2347     n = write_bytes(&data_size, sizeof(int));
2348     if (n != sizeof(int)) {
2349       return false;
2350     }
2351     n = write_bytes(om, sizeof(OopMap));
2352     if (n != sizeof(OopMap)) {
2353       return false;
2354     }
2355     n = write_bytes(om->data(), (uint)data_size);
2356     if (n != (uint)data_size) {
2357       return false;
2358     }
2359   }
2360   return true;
2361 }
2362 
2363 jobject SCCReader::read_oop(JavaThread* thread, const methodHandle& comp_method) {
2364   uint code_offset = read_position();
2365   oop obj = nullptr;
2366   DataKind kind = *(DataKind*)addr(code_offset);
2367   code_offset += sizeof(DataKind);
2368   set_read_position(code_offset);
2369   if (kind == DataKind::Null) {
2370     return nullptr;
2371   } else if (kind == DataKind::No_Data) {
2372     return (jobject)Universe::non_oop_word();
2373   } else if (kind == DataKind::Klass || kind == DataKind::Klass_Shared) {
2374     Klass* k = read_klass(comp_method, (kind == DataKind::Klass_Shared));
2375     if (k == nullptr) {
2376       return nullptr;
2377     }
2378     obj = k->java_mirror();
2379     if (obj == nullptr) {
2380       set_lookup_failed();
2381       log_warning(scc)("Lookup failed for java_mirror of klass %s", k->external_name());
2382       return nullptr;
2383     }
2384   } else if (kind == DataKind::Primitive) {
2385     code_offset = read_position();
2386     int t = *(int*)addr(code_offset);
2387     code_offset += sizeof(int);
2388     set_read_position(code_offset);
2389     BasicType bt = (BasicType)t;
2390     obj = java_lang_Class::primitive_mirror(bt);
2391     log_info(scc)("%d (L%d): Read primitive type klass: %s", compile_id(), comp_level(), type2name(bt));
2392   } else if (kind == DataKind::String_Shared) {
2393     code_offset = read_position();
2394     int k = *(int*)addr(code_offset);
2395     code_offset += sizeof(int);
2396     set_read_position(code_offset);
2397     obj = CDSAccess::get_archived_object(k);
2398     assert(k == CDSAccess::get_archived_object_permanent_index(obj), "sanity");
2399   } else if (kind == DataKind::String) {
2400     code_offset = read_position();
2401     int length = *(int*)addr(code_offset);
2402     code_offset += sizeof(int);
2403     set_read_position(code_offset);
2404     const char* dest = addr(code_offset);
2405     set_read_position(code_offset + length);
2406     obj = StringTable::intern(&(dest[0]), thread);
2407     if (obj == nullptr) {
2408       set_lookup_failed();
2409       log_warning(scc)("%d (L%d): Lookup failed for String %s",
2410                        compile_id(), comp_level(), &(dest[0]));
2411       return nullptr;
2412     }
2413     assert(java_lang_String::is_instance(obj), "must be string");
2414     log_info(scc)("%d (L%d): Read String: %s", compile_id(), comp_level(), dest);
2415   } else if (kind == DataKind::SysLoader) {
2416     obj = SystemDictionary::java_system_loader();
2417     log_info(scc)("%d (L%d): Read java_system_loader", compile_id(), comp_level());
2418   } else if (kind == DataKind::PlaLoader) {
2419     obj = SystemDictionary::java_platform_loader();
2420     log_info(scc)("%d (L%d): Read java_platform_loader", compile_id(), comp_level());
2421   } else if (kind == DataKind::MH_Oop_Shared) {
2422     code_offset = read_position();
2423     int k = *(int*)addr(code_offset);
2424     code_offset += sizeof(int);
2425     set_read_position(code_offset);
2426     obj = CDSAccess::get_archived_object(k);
2427     assert(k == CDSAccess::get_archived_object_permanent_index(obj), "sanity");
2428   } else {
2429     set_lookup_failed();
2430     log_warning(scc)("%d (L%d): Unknown oop's kind: %d",
2431                      compile_id(), comp_level(), (int)kind);
2432     return nullptr;
2433   }
2434   return JNIHandles::make_local(thread, obj);
2435 }
2436 
2437 bool SCCReader::read_oops(OopRecorder* oop_recorder, ciMethod* target) {
2438   uint code_offset = read_position();
2439   int oop_count = *(int*)addr(code_offset);
2440   code_offset += sizeof(int);
2441   set_read_position(code_offset);
2442   log_debug(scc)("======== read oops [%d]:", oop_count);
2443   if (oop_count == 0) {
2444     return true;
2445   }
2446   {
2447     VM_ENTRY_MARK;
2448     methodHandle comp_method(THREAD, target->get_Method());
2449     for (int i = 1; i < oop_count; i++) {
2450       jobject jo = read_oop(THREAD, comp_method);
2451       if (lookup_failed()) {
2452         return false;
2453       }
2454       if (oop_recorder->is_real(jo)) {
2455         oop_recorder->find_index(jo);
2456       } else {
2457         oop_recorder->allocate_oop_index(jo);
2458       }
2459       LogTarget(Debug, scc, oops) log;
2460       if (log.is_enabled()) {
2461         LogStream ls(log);
2462         ls.print("%d: " INTPTR_FORMAT " ", i, p2i(jo));
2463         if (jo == (jobject)Universe::non_oop_word()) {
2464           ls.print("non-oop word");
2465         } else if (jo == nullptr) {
2466           ls.print("nullptr-oop");
2467         } else {
2468           JNIHandles::resolve(jo)->print_value_on(&ls);
2469         }
2470         ls.cr();
2471       }
2472     }
2473   }
2474   return true;
2475 }
2476 
2477 Metadata* SCCReader::read_metadata(const methodHandle& comp_method) {
2478   uint code_offset = read_position();
2479   Metadata* m = nullptr;
2480   DataKind kind = *(DataKind*)addr(code_offset);
2481   code_offset += sizeof(DataKind);
2482   set_read_position(code_offset);
2483   if (kind == DataKind::Null) {
2484     m = (Metadata*)nullptr;
2485   } else if (kind == DataKind::No_Data) {
2486     m = (Metadata*)Universe::non_oop_word();
2487   } else if (kind == DataKind::Klass || kind == DataKind::Klass_Shared) {
2488     m = (Metadata*)read_klass(comp_method, (kind == DataKind::Klass_Shared));
2489   } else if (kind == DataKind::Method || kind == DataKind::Method_Shared) {
2490     m = (Metadata*)read_method(comp_method, (kind == DataKind::Method_Shared));
2491   } else if (kind == DataKind::MethodCnts) {
2492     kind = *(DataKind*)addr(code_offset);
2493     bool shared = (kind == DataKind::Method_Shared);
2494     assert(kind == DataKind::Method || shared, "Sanity");
2495     code_offset += sizeof(DataKind);
2496     set_read_position(code_offset);
2497     m = (Metadata*)read_method(comp_method, shared);
2498     if (m != nullptr) {
2499       Method* method = (Method*)m;
2500       m = method->get_method_counters(Thread::current());
2501       if (m == nullptr) {
2502         set_lookup_failed();
2503         log_warning(scc)("%d (L%d): Failed to get MethodCounters", compile_id(), comp_level());
2504       } else {
2505         log_info(scc)("%d (L%d): Read MethodCounters : " INTPTR_FORMAT, compile_id(), comp_level(), p2i(m));
2506       }
2507     }
2508   } else {
2509     set_lookup_failed();
2510     log_warning(scc)("%d (L%d): Unknown metadata's kind: %d", compile_id(), comp_level(), (int)kind);
2511   }
2512   return m;
2513 }
2514 
2515 bool SCCReader::read_metadata(OopRecorder* oop_recorder, ciMethod* target) {
2516   uint code_offset = read_position();
2517   int metadata_count = *(int*)addr(code_offset);
2518   code_offset += sizeof(int);
2519   set_read_position(code_offset);
2520 
2521   log_debug(scc)("======== read metadata [%d]:", metadata_count);
2522 
2523   if (metadata_count == 0) {
2524     return true;
2525   }
2526   {
2527     VM_ENTRY_MARK;
2528     methodHandle comp_method(THREAD, target->get_Method());
2529 
2530     for (int i = 1; i < metadata_count; i++) {
2531       Metadata* m = read_metadata(comp_method);
2532       if (lookup_failed()) {
2533         return false;
2534       }
2535       if (oop_recorder->is_real(m)) {
2536         oop_recorder->find_index(m);
2537       } else {
2538         oop_recorder->allocate_metadata_index(m);
2539       }
2540       LogTarget(Debug, scc, metadata) log;
2541       if (log.is_enabled()) {
2542         LogStream ls(log);
2543         ls.print("%d: " INTPTR_FORMAT " ", i, p2i(m));
2544         if (m == (Metadata*)Universe::non_oop_word()) {
2545           ls.print("non-metadata word");
2546         } else if (m == nullptr) {
2547           ls.print("nullptr-oop");
2548         } else {
2549           Metadata::print_value_on_maybe_null(&ls, m);
2550         }
2551         ls.cr();
2552       }
2553     }
2554   }
2555   return true;
2556 }
2557 
2558 bool SCCache::write_oop(jobject& jo) {
2559   DataKind kind;
2560   uint n = 0;
2561   oop obj = JNIHandles::resolve(jo);
2562   if (jo == nullptr) {
2563     kind = DataKind::Null;
2564     n = write_bytes(&kind, sizeof(int));
2565     if (n != sizeof(int)) {
2566       return false;
2567     }
2568   } else if (jo == (jobject)Universe::non_oop_word()) {
2569     kind = DataKind::No_Data;
2570     n = write_bytes(&kind, sizeof(int));
2571     if (n != sizeof(int)) {
2572       return false;
2573     }
2574   } else if (java_lang_Class::is_instance(obj)) {
2575     if (java_lang_Class::is_primitive(obj)) {
2576       int bt = (int)java_lang_Class::primitive_type(obj);
2577       kind = DataKind::Primitive;
2578       n = write_bytes(&kind, sizeof(int));
2579       if (n != sizeof(int)) {
2580         return false;
2581       }
2582       n = write_bytes(&bt, sizeof(int));
2583       if (n != sizeof(int)) {
2584         return false;
2585       }
2586       log_info(scc)("%d (L%d): Write primitive type klass: %s", compile_id(), comp_level(), type2name((BasicType)bt));
2587     } else {
2588       Klass* klass = java_lang_Class::as_Klass(obj);
2589       if (!write_klass(klass)) {
2590         return false;
2591       }
2592     }
2593   } else if (java_lang_String::is_instance(obj)) { // herere
2594     int k = CDSAccess::get_archived_object_permanent_index(obj);  // k >= 1 means obj is a "permanent heap object"
2595     if (k > 0) {
2596       kind = DataKind::String_Shared;
2597       n = write_bytes(&kind, sizeof(int));
2598       if (n != sizeof(int)) {
2599         return false;
2600       }
2601       n = write_bytes(&k, sizeof(int));
2602       if (n != sizeof(int)) {
2603         return false;
2604       }
2605       return true;
2606     }
2607     kind = DataKind::String;
2608     n = write_bytes(&kind, sizeof(int));
2609     if (n != sizeof(int)) {
2610       return false;
2611     }
2612     ResourceMark rm;
2613     int length = 0;
2614     const char* string = java_lang_String::as_utf8_string(obj, length);
2615     length++; // write tailing '/0'
2616     n = write_bytes(&length, sizeof(int));
2617     if (n != sizeof(int)) {
2618       return false;
2619     }
2620     n = write_bytes(string, (uint)length);
2621     if (n != (uint)length) {
2622       return false;
2623     }
2624     log_info(scc)("%d (L%d): Write String: %s", compile_id(), comp_level(), string);
2625   } else if (java_lang_Module::is_instance(obj)) {
2626     fatal("Module object unimplemented");
2627   } else if (java_lang_ClassLoader::is_instance(obj)) {
2628     if (obj == SystemDictionary::java_system_loader()) {
2629       kind = DataKind::SysLoader;
2630       log_info(scc)("%d (L%d): Write ClassLoader: java_system_loader", compile_id(), comp_level());
2631     } else if (obj == SystemDictionary::java_platform_loader()) {
2632       kind = DataKind::PlaLoader;
2633       log_info(scc)("%d (L%d): Write ClassLoader: java_platform_loader", compile_id(), comp_level());
2634     } else {
2635       fatal("ClassLoader object unimplemented");
2636       return false;
2637     }
2638     n = write_bytes(&kind, sizeof(int));
2639     if (n != sizeof(int)) {
2640       return false;
2641     }
2642   } else { // herere
2643     int k = CDSAccess::get_archived_object_permanent_index(obj);  // k >= 1 means obj is a "permanent heap object"
2644     if (k > 0) {
2645       kind = DataKind::MH_Oop_Shared;
2646       n = write_bytes(&kind, sizeof(int));
2647       if (n != sizeof(int)) {
2648         return false;
2649       }
2650       n = write_bytes(&k, sizeof(int));
2651       if (n != sizeof(int)) {
2652         return false;
2653       }
2654       return true;
2655     }
2656     // Unhandled oop - bailout
2657     set_lookup_failed();
2658     log_warning(scc, nmethod)("%d (L%d): Unhandled obj: " PTR_FORMAT " : %s",
2659                               compile_id(), comp_level(), p2i(obj), obj->klass()->external_name());
2660     return false;
2661   }
2662   return true;
2663 }
2664 
2665 bool SCCache::write_oops(OopRecorder* oop_recorder) {
2666   int oop_count = oop_recorder->oop_count();
2667   uint n = write_bytes(&oop_count, sizeof(int));
2668   if (n != sizeof(int)) {
2669     return false;
2670   }
2671   log_debug(scc)("======== write oops [%d]:", oop_count);
2672 
2673   for (int i = 1; i < oop_count; i++) { // skip first virtual nullptr
2674     jobject jo = oop_recorder->oop_at(i);
2675     LogTarget(Info, scc, oops) log;
2676     if (log.is_enabled()) {
2677       LogStream ls(log);
2678       ls.print("%d: " INTPTR_FORMAT " ", i, p2i(jo));
2679       if (jo == (jobject)Universe::non_oop_word()) {
2680         ls.print("non-oop word");
2681       } else if (jo == nullptr) {
2682         ls.print("nullptr-oop");
2683       } else {
2684         JNIHandles::resolve(jo)->print_value_on(&ls);
2685       }
2686       ls.cr();
2687     }
2688     if (!write_oop(jo)) {
2689       return false;
2690     }
2691   }
2692   return true;
2693 }
2694 
2695 bool SCCache::write_metadata(Metadata* m) {
2696   uint n = 0;
2697   if (m == nullptr) {
2698     DataKind kind = DataKind::Null;
2699     n = write_bytes(&kind, sizeof(int));
2700     if (n != sizeof(int)) {
2701       return false;
2702     }
2703   } else if (m == (Metadata*)Universe::non_oop_word()) {
2704     DataKind kind = DataKind::No_Data;
2705     n = write_bytes(&kind, sizeof(int));
2706     if (n != sizeof(int)) {
2707       return false;
2708     }
2709   } else if (m->is_klass()) {
2710     if (!write_klass((Klass*)m)) {
2711       return false;
2712     }
2713   } else if (m->is_method()) {
2714     if (!write_method((Method*)m)) {
2715       return false;
2716     }
2717   } else if (m->is_methodCounters()) {
2718     DataKind kind = DataKind::MethodCnts;
2719     n = write_bytes(&kind, sizeof(int));
2720     if (n != sizeof(int)) {
2721       return false;
2722     }
2723     if (!write_method(((MethodCounters*)m)->method())) {
2724       return false;
2725     }
2726     log_info(scc)("%d (L%d): Write MethodCounters : " INTPTR_FORMAT, compile_id(), comp_level(), p2i(m));
2727   } else { // Not supported
2728     fatal("metadata : " INTPTR_FORMAT " unimplemented", p2i(m));
2729     return false;
2730   }
2731   return true;
2732 }
2733 
2734 bool SCCache::write_metadata(OopRecorder* oop_recorder) {
2735   int metadata_count = oop_recorder->metadata_count();
2736   uint n = write_bytes(&metadata_count, sizeof(int));
2737   if (n != sizeof(int)) {
2738     return false;
2739   }
2740 
2741   log_debug(scc)("======== write metadata [%d]:", metadata_count);
2742 
2743   for (int i = 1; i < metadata_count; i++) { // skip first virtual nullptr
2744     Metadata* m = oop_recorder->metadata_at(i);
2745     LogTarget(Debug, scc, metadata) log;
2746     if (log.is_enabled()) {
2747       LogStream ls(log);
2748       ls.print("%d: " INTPTR_FORMAT " ", i, p2i(m));
2749       if (m == (Metadata*)Universe::non_oop_word()) {
2750         ls.print("non-metadata word");
2751       } else if (m == nullptr) {
2752         ls.print("nillptr-oop");
2753       } else {
2754         Metadata::print_value_on_maybe_null(&ls, m);
2755       }
2756       ls.cr();
2757     }
2758     if (!write_metadata(m)) {
2759       return false;
2760     }
2761   }
2762   return true;
2763 }
2764 
2765 bool SCCReader::read_dependencies(Dependencies* dependencies) {
2766   uint code_offset = read_position();
2767   int dependencies_size = *(int*)addr(code_offset);
2768 
2769   log_debug(scc)("======== read dependencies [%d]:", dependencies_size);
2770 
2771   code_offset += sizeof(int);
2772   code_offset = align_up(code_offset, DATA_ALIGNMENT);
2773   if (dependencies_size > 0) {
2774     dependencies->set_content((u_char*)addr(code_offset), dependencies_size);
2775   }
2776   code_offset += dependencies_size;
2777   set_read_position(code_offset);
2778   return true;
2779 }
2780 
2781 bool SCCache::load_nmethod(ciEnv* env, ciMethod* target, int entry_bci, AbstractCompiler* compiler, CompLevel comp_level) {
2782   TraceTime t1("SC total load time", &_t_totalLoad, enable_timers(), false);
2783   CompileTask* task = env->task();
2784   SCCEntry* entry = task->scc_entry();
2785   bool preload = task->preload();
2786   assert(entry != nullptr, "sanity");
2787   SCCache* cache = open_for_read();
2788   if (cache == nullptr) {
2789     return false;
2790   }
2791   if (log_is_enabled(Info, scc, nmethod)) {
2792     uint decomp = (target->method_data() == nullptr) ? 0 : target->method_data()->decompile_count();
2793     VM_ENTRY_MARK;
2794     ResourceMark rm;
2795     methodHandle method(THREAD, target->get_Method());
2796     const char* target_name = method->name_and_sig_as_C_string();
2797     uint hash = java_lang_String::hash_code((const jbyte*)target_name, (int)strlen(target_name));
2798     bool clinit_brs = entry->has_clinit_barriers();
2799     log_info(scc, nmethod)("%d (L%d): %s nmethod '%s' (decomp: %d, hash: " UINT32_FORMAT_X_0 "%s)",
2800                            task->compile_id(), task->comp_level(), (preload ? "Preloading" : "Reading"),
2801                            target_name, decomp, hash, (clinit_brs ? ", has clinit barriers" : ""));
2802   }
2803   ReadingMark rdmk;
2804   SCCReader reader(cache, entry, task);
2805   bool success = reader.compile(env, target, entry_bci, compiler);
2806   if (success) {
2807     task->set_num_inlined_bytecodes(entry->num_inlined_bytecodes());
2808   } else {
2809     entry->set_load_fail();
2810   }
2811   return success;
2812 }
2813 
2814 SCCReader::SCCReader(SCCache* cache, SCCEntry* entry, CompileTask* task) {
2815   _cache = cache;
2816   _entry   = entry;
2817   _load_buffer = cache->cache_buffer();
2818   _read_position = 0;
2819   if (task != nullptr) {
2820     _compile_id = task->compile_id();
2821     _comp_level = task->comp_level();
2822     _preload    = task->preload();
2823   } else {
2824     _compile_id = 0;
2825     _comp_level = 0;
2826     _preload    = false;
2827   }
2828   _lookup_failed = false;
2829 }
2830 
2831 bool SCCReader::compile(ciEnv* env, ciMethod* target, int entry_bci, AbstractCompiler* compiler) {
2832   uint entry_position = _entry->offset();
2833   uint code_offset = entry_position + _entry->code_offset();
2834   set_read_position(code_offset);
2835 
2836   // Read flags
2837   int flags = *(int*)addr(code_offset);
2838   code_offset += sizeof(int);
2839   bool has_monitors      = (flags & 0xFF) > 0;
2840   bool has_wide_vectors  = ((flags >>  8) & 0xFF) > 0;
2841   bool has_unsafe_access = ((flags >> 16) & 0xFF) > 0;
2842 
2843   int orig_pc_offset = *(int*)addr(code_offset);
2844   code_offset += sizeof(int);
2845   int frame_size = *(int*)addr(code_offset);
2846   code_offset += sizeof(int);
2847 
2848   // Read offsets
2849   CodeOffsets* offsets = (CodeOffsets*)addr(code_offset);
2850   code_offset += sizeof(CodeOffsets);
2851 
2852   // Create Debug Information Recorder to record scopes, oopmaps, etc.
2853   OopRecorder* oop_recorder = new OopRecorder(env->arena());
2854   env->set_oop_recorder(oop_recorder);
2855 
2856   set_read_position(code_offset);
2857 
2858   // Write OopRecorder data
2859   if (!read_oops(oop_recorder, target)) {
2860     return false;
2861   }
2862   if (!read_metadata(oop_recorder, target)) {
2863     return false;
2864   }
2865 
2866   // Read Debug info
2867   DebugInformationRecorder* recorder = read_debug_info(oop_recorder);
2868   if (recorder == nullptr) {
2869     return false;
2870   }
2871   env->set_debug_info(recorder);
2872 
2873   // Read Dependencies (compressed already)
2874   Dependencies* dependencies = new Dependencies(env);
2875   if (!read_dependencies(dependencies)) {
2876     return false;
2877   }
2878   env->set_dependencies(dependencies);
2879 
2880   // Read oop maps
2881   OopMapSet* oop_maps = read_oop_maps();
2882   if (oop_maps == nullptr) {
2883     return false;
2884   }
2885 
2886   // Read exception handles
2887   code_offset = read_position();
2888   int exc_table_length = *(int*)addr(code_offset);
2889   code_offset += sizeof(int);
2890   ExceptionHandlerTable handler_table(MAX2(exc_table_length, 4));
2891   if (exc_table_length > 0) {
2892     handler_table.set_length(exc_table_length);
2893     uint exc_table_size = handler_table.size_in_bytes();
2894     copy_bytes(addr(code_offset), (address)handler_table.table(), exc_table_size);
2895     code_offset += exc_table_size;
2896   }
2897 
2898   // Read null check table
2899   int nul_chk_length = *(int*)addr(code_offset);
2900   code_offset += sizeof(int);
2901   ImplicitExceptionTable nul_chk_table;
2902   if (nul_chk_length > 0) {
2903     nul_chk_table.set_size(nul_chk_length);
2904     nul_chk_table.set_len(nul_chk_length);
2905     uint nul_chk_size = nul_chk_table.size_in_bytes();
2906     copy_bytes(addr(code_offset), (address)nul_chk_table.data(), nul_chk_size - sizeof(implicit_null_entry));
2907     code_offset += nul_chk_size;
2908   }
2909 
2910   uint reloc_size = _entry->reloc_size();
2911   CodeBuffer buffer("Compile::Fill_buffer", _entry->code_size(), reloc_size);
2912   buffer.initialize_oop_recorder(oop_recorder);
2913 
2914   const char* name = addr(entry_position + _entry->name_offset());
2915 
2916   // Create fake original CodeBuffer
2917   CodeBuffer orig_buffer(name);
2918 
2919   // Read code
2920   if (!read_code(&buffer, &orig_buffer, align_up(code_offset, DATA_ALIGNMENT))) {
2921     return false;
2922   }
2923 
2924   // Read relocations
2925   uint reloc_offset = entry_position + _entry->reloc_offset();
2926   set_read_position(reloc_offset);
2927   if (!read_relocations(&buffer, &orig_buffer, oop_recorder, target)) {
2928     return false;
2929   }
2930 
2931   log_info(scc, nmethod)("%d (L%d): Read nmethod '%s' from Startup Code Cache '%s'", compile_id(), comp_level(), name, _cache->cache_path());
2932 #ifdef ASSERT
2933   LogTarget(Debug, scc, nmethod) log;
2934   if (log.is_enabled()) {
2935     FlagSetting fs(PrintRelocations, true);
2936     buffer.print();
2937     buffer.decode();
2938   }
2939 #endif
2940 
2941   if (VerifyCachedCode) {
2942     return false;
2943   }
2944 
2945   // Register nmethod
2946   TraceTime t1("SC total nmethod register time", &_t_totalRegister, enable_timers(), false);
2947   env->register_method(target, entry_bci,
2948                        offsets, orig_pc_offset,
2949                        &buffer, frame_size,
2950                        oop_maps, &handler_table,
2951                        &nul_chk_table, compiler,
2952                        _entry->has_clinit_barriers(),
2953                        false,
2954                        has_unsafe_access,
2955                        has_wide_vectors,
2956                        has_monitors,
2957                        0, true /* install_code */, NoRTM,
2958                        (SCCEntry *)_entry);
2959   CompileTask* task = env->task();
2960   bool success = task->is_success();
2961   if (success) {
2962     ((SCCEntry *)_entry)->set_loaded();
2963   }
2964   return success;
2965 }
2966 
2967 // No concurency for writing to cache file because this method is called from
2968 // ciEnv::register_method() under MethodCompileQueue_lock and Compile_lock locks.
2969 SCCEntry* SCCache::store_nmethod(const methodHandle& method,
2970                      int comp_id,
2971                      int entry_bci,
2972                      CodeOffsets* offsets,
2973                      int orig_pc_offset,
2974                      DebugInformationRecorder* recorder,
2975                      Dependencies* dependencies,
2976                      CodeBuffer* buffer,
2977                      int frame_size,
2978                      OopMapSet* oop_maps,
2979                      ExceptionHandlerTable* handler_table,
2980                      ImplicitExceptionTable* nul_chk_table,
2981                      AbstractCompiler* compiler,
2982                      CompLevel comp_level,
2983                      bool has_clinit_barriers,
2984                      bool for_preload,
2985                      bool has_unsafe_access,
2986                      bool has_wide_vectors,
2987                      bool has_monitors) {
2988   CompileTask* task = ciEnv::current()->task();
2989 
2990   if (!CDSConfig::is_dumping_cached_code()) {
2991     return nullptr; // The metadata and heap in the CDS image haven't been finalized yet.
2992   }
2993   if (entry_bci != InvocationEntryBci) {
2994     return nullptr; // No OSR
2995   }
2996   if (compiler->is_c1() && (comp_level == CompLevel_simple || comp_level == CompLevel_limited_profile)) {
2997     // Cache tier1 compilations
2998   } else if (!compiler->is_c2()) {
2999     return nullptr; // Only C2 now
3000   }
3001   TraceTime t1("SC total store time", &_t_totalStore, enable_timers(), false);
3002   SCCache* cache = open_for_write();
3003   if (cache == nullptr) {
3004     return nullptr; // Cache file is closed
3005   }
3006   if (method->is_hidden()) {
3007     ResourceMark rm;
3008     log_info(scc, nmethod)("%d (L%d): Skip hidden method '%s'", task->compile_id(), task->comp_level(), method->name_and_sig_as_C_string());
3009     return nullptr;
3010   }
3011   if (buffer->before_expand() != nullptr) {
3012     ResourceMark rm;
3013     log_info(scc, nmethod)("%d (L%d): Skip nmethod with expanded buffer '%s'", task->compile_id(), task->comp_level(), method->name_and_sig_as_C_string());
3014     return nullptr;
3015   }
3016 #ifdef ASSERT
3017   LogTarget(Debug, scc, nmethod) log;
3018   if (log.is_enabled()) {
3019     tty->print_cr(" == store_nmethod");
3020     FlagSetting fs(PrintRelocations, true);
3021     buffer->print();
3022     buffer->decode();
3023   }
3024 #endif
3025   assert(!has_clinit_barriers || cache->_gen_preload_code, "sanity");
3026   Method* m = method();
3027   bool method_in_cds = MetaspaceShared::is_in_shared_metaspace((address)m); // herere
3028   InstanceKlass* holder = m->method_holder();
3029   bool klass_in_cds = holder->is_shared() && !holder->is_shared_unregistered_class();
3030   bool builtin_loader = holder->class_loader_data()->is_builtin_class_loader_data();
3031   if (!builtin_loader) {
3032     ResourceMark rm;
3033     log_info(scc, nmethod)("%d (L%d): Skip method '%s' loaded by custom class loader %s", task->compile_id(), task->comp_level(), method->name_and_sig_as_C_string(), holder->class_loader_data()->loader_name());
3034     return nullptr;
3035   }
3036   if (for_preload && !(method_in_cds && klass_in_cds)) {
3037     ResourceMark rm;
3038     log_info(scc, nmethod)("%d (L%d): Skip method '%s' for preload: not in CDS", task->compile_id(), task->comp_level(), method->name_and_sig_as_C_string());
3039     return nullptr;
3040   }
3041   assert(!for_preload || method_in_cds, "sanity");
3042   cache->_for_preload = for_preload;
3043   cache->_has_clinit_barriers = has_clinit_barriers;
3044 
3045   if (!cache->align_write()) {
3046     return nullptr;
3047   }
3048   cache->_compile_id = task->compile_id();
3049   cache->_comp_level = task->comp_level();
3050 
3051   uint entry_position = cache->_write_position;
3052 
3053   uint decomp = (method->method_data() == nullptr) ? 0 : method->method_data()->decompile_count();
3054   // Write name
3055   uint name_offset = 0;
3056   uint name_size   = 0;
3057   uint hash = 0;
3058   uint n;
3059   {
3060     ResourceMark rm;
3061     const char* name   = method->name_and_sig_as_C_string();
3062     log_info(scc, nmethod)("%d (L%d): Writing nmethod '%s' (comp level: %d, decomp: %d%s) to Startup Code Cache '%s'",
3063                            task->compile_id(), task->comp_level(), name, comp_level, decomp,
3064                            (has_clinit_barriers ? ", has clinit barriers" : ""), cache->_cache_path);
3065 
3066     LogTarget(Info, scc, loader) log;
3067     if (log.is_enabled()) {
3068       LogStream ls(log);
3069       oop loader = holder->class_loader();
3070       oop domain = holder->protection_domain();
3071       ls.print("Holder: ");
3072       holder->print_value_on(&ls);
3073       ls.print(" loader: ");
3074       if (loader == nullptr) {
3075         ls.print("nullptr");
3076       } else {
3077         loader->print_value_on(&ls);
3078       }
3079       ls.print(" domain: ");
3080       if (domain == nullptr) {
3081         ls.print("nullptr");
3082       } else {
3083         domain->print_value_on(&ls);
3084       }
3085       ls.cr();
3086     }
3087     name_offset = cache->_write_position  - entry_position;
3088     name_size   = (uint)strlen(name) + 1; // Includes '/0'
3089     n = cache->write_bytes(name, name_size);
3090     if (n != name_size) {
3091       return nullptr;
3092     }
3093     hash = java_lang_String::hash_code((const jbyte*)name, (int)strlen(name));
3094   }
3095 
3096   if (!cache->align_write()) {
3097     return nullptr;
3098   }
3099 
3100   uint code_offset = cache->_write_position - entry_position;
3101 
3102   int flags = ((has_unsafe_access ? 1 : 0) << 16) | ((has_wide_vectors ? 1 : 0) << 8) | (has_monitors ? 1 : 0);
3103   n = cache->write_bytes(&flags, sizeof(int));
3104   if (n != sizeof(int)) {
3105     return nullptr;
3106   }
3107 
3108   n = cache->write_bytes(&orig_pc_offset, sizeof(int));
3109   if (n != sizeof(int)) {
3110     return nullptr;
3111   }
3112 
3113   n = cache->write_bytes(&frame_size, sizeof(int));
3114   if (n != sizeof(int)) {
3115     return nullptr;
3116   }
3117 
3118   // Write offsets
3119   n = cache->write_bytes(offsets, sizeof(CodeOffsets));
3120   if (n != sizeof(CodeOffsets)) {
3121     return nullptr;
3122   }
3123 
3124   // Write OopRecorder data
3125   if (!cache->write_oops(buffer->oop_recorder())) {
3126     if (cache->lookup_failed() && !cache->failed()) {
3127       // Skip this method and reposition file
3128       cache->set_write_position(entry_position);
3129     }
3130     return nullptr;
3131   }
3132   if (!cache->write_metadata(buffer->oop_recorder())) {
3133     if (cache->lookup_failed() && !cache->failed()) {
3134       // Skip this method and reposition file
3135       cache->set_write_position(entry_position);
3136     }
3137     return nullptr;
3138   }
3139 
3140   // Write Debug info
3141   if (!cache->write_debug_info(recorder)) {
3142     return nullptr;
3143   }
3144   // Write Dependencies
3145   int dependencies_size = (int)dependencies->size_in_bytes();
3146   n = cache->write_bytes(&dependencies_size, sizeof(int));
3147   if (n != sizeof(int)) {
3148     return nullptr;
3149   }
3150   if (!cache->align_write()) {
3151     return nullptr;
3152   }
3153   n = cache->write_bytes(dependencies->content_bytes(), dependencies_size);
3154   if (n != (uint)dependencies_size) {
3155     return nullptr;
3156   }
3157 
3158   // Write oop maps
3159   if (!cache->write_oop_maps(oop_maps)) {
3160     return nullptr;
3161   }
3162 
3163   // Write exception handles
3164   int exc_table_length = handler_table->length();
3165   n = cache->write_bytes(&exc_table_length, sizeof(int));
3166   if (n != sizeof(int)) {
3167     return nullptr;
3168   }
3169   uint exc_table_size = handler_table->size_in_bytes();
3170   n = cache->write_bytes(handler_table->table(), exc_table_size);
3171   if (n != exc_table_size) {
3172     return nullptr;
3173   }
3174 
3175   // Write null check table
3176   int nul_chk_length = nul_chk_table->len();
3177   n = cache->write_bytes(&nul_chk_length, sizeof(int));
3178   if (n != sizeof(int)) {
3179     return nullptr;
3180   }
3181   uint nul_chk_size = nul_chk_table->size_in_bytes();
3182   n = cache->write_bytes(nul_chk_table->data(), nul_chk_size);
3183   if (n != nul_chk_size) {
3184     return nullptr;
3185   }
3186 
3187   // Write code section
3188   if (!cache->align_write()) {
3189     return nullptr;
3190   }
3191   uint code_size = 0;
3192   if (!cache->write_code(buffer, code_size)) {
3193     return nullptr;
3194   }
3195   // Write relocInfo array
3196   uint reloc_offset = cache->_write_position - entry_position;
3197   uint reloc_size = 0;
3198   if (!cache->write_relocations(buffer, reloc_size)) {
3199     if (cache->lookup_failed() && !cache->failed()) {
3200       // Skip this method and reposition file
3201       cache->set_write_position(entry_position);
3202     }
3203     return nullptr;
3204   }
3205   uint entry_size = cache->_write_position - entry_position;
3206 
3207   SCCEntry* entry = new(cache) SCCEntry(entry_position, entry_size, name_offset, name_size,
3208                                  code_offset, code_size, reloc_offset, reloc_size,
3209                                  SCCEntry::Code, hash, (uint)comp_level, (uint)comp_id, decomp,
3210                                  has_clinit_barriers, cache->_for_preload);
3211   if (method_in_cds) {
3212     entry->set_method(m);
3213   }
3214 #ifdef ASSERT
3215   if (has_clinit_barriers || cache->_for_preload) {
3216     assert(for_preload, "sanity");
3217     assert(entry->method() != nullptr, "sanity");
3218   }
3219 #endif
3220   {
3221     ResourceMark rm;
3222     const char* name   = method->name_and_sig_as_C_string();
3223     log_info(scc, nmethod)("%d (L%d): Wrote nmethod '%s'%s to Startup Code Cache '%s'",
3224                            task->compile_id(), task->comp_level(), name, (cache->_for_preload ? " (for preload)" : ""), cache->_cache_path);
3225   }
3226   if (VerifyCachedCode) {
3227     return nullptr;
3228   }
3229   return entry;
3230 }
3231 
3232 static void print_helper1(outputStream* st, const char* name, int count) {
3233   if (count > 0) {
3234     st->print(" %s=%d", name, count);
3235   }
3236 }
3237 static void print_helper(outputStream* st, const char* name, int stats[6+3][6], int idx) {
3238   int total = stats[idx][0];
3239   if (total > 0) {
3240     st->print("  %s:", name);
3241     print_helper1(st, "total",               stats[idx][0]);
3242     //print_helper1(st, "for_preload",         stats[idx][2]); // implied by Tier5
3243     print_helper1(st, "loaded",              stats[idx][3]);
3244     print_helper1(st, "invalidated",         stats[idx][4]);
3245     print_helper1(st, "failed",              stats[idx][5]);
3246     print_helper1(st, "has_clinit_barriers", stats[idx][1]);
3247     st->cr();
3248   }
3249 }
3250 
3251 void SCCache::print_statistics_on(outputStream* st) {
3252   SCCache* cache = open_for_read();
3253   if (cache != nullptr) {
3254     ReadingMark rdmk;
3255 
3256     uint count = cache->_load_header->entries_count();
3257     uint* search_entries = (uint*)cache->addr(cache->_load_header->entries_offset()); // [id, index]
3258     SCCEntry* load_entries = (SCCEntry*)(search_entries + 2 * count);
3259 
3260     int stats[6 + 3][6] = {0};
3261     for (uint i = 0; i < count; i++) {
3262       int index = search_entries[2*i + 1];
3263       SCCEntry* entry = &(load_entries[index]);
3264 
3265       int lvl = entry->kind();
3266       if (entry->kind() == SCCEntry::Code) {
3267         lvl += entry->comp_level() + (entry->for_preload() ? 1 : 0);
3268       }
3269       ++stats[lvl][0]; // total
3270       if (entry->has_clinit_barriers()) {
3271         ++stats[lvl][1];
3272       }
3273       if (entry->for_preload()) {
3274         ++stats[lvl][2];
3275       }
3276       if (entry->is_loaded()) {
3277         ++stats[lvl][3];
3278       }
3279       if (entry->not_entrant()) {
3280         ++stats[lvl][4];
3281       }
3282       if (entry->load_fail()) {
3283         ++stats[lvl][5];
3284       }
3285     }
3286 
3287     print_helper(st, "None", stats, SCCEntry::None);
3288     print_helper(st, "Stub", stats, SCCEntry::Stub);
3289     print_helper(st, "Blob", stats, SCCEntry::Blob);
3290     for (int lvl = 0; lvl <= CompLevel_full_optimization + 1; lvl++) {
3291       ResourceMark rm;
3292       stringStream ss;
3293       ss.print("SC T%d", lvl);
3294       print_helper(st, ss.freeze(), stats, SCCEntry::Code + lvl);
3295     }
3296 
3297   } else {
3298     st->print_cr("failed to open SCA at %s", CachedCodeFile);
3299   }
3300 }
3301 
3302 void SCCache::print_on(outputStream* st) {
3303   SCCache* cache = open_for_read();
3304   if (cache != nullptr) {
3305     ReadingMark rdmk;
3306 
3307     uint count = cache->_load_header->entries_count();
3308     uint* search_entries = (uint*)cache->addr(cache->_load_header->entries_offset()); // [id, index]
3309     SCCEntry* load_entries = (SCCEntry*)(search_entries + 2 * count);
3310 
3311     for (uint i = 0; i < count; i++) {
3312       int index = search_entries[2*i + 1];
3313       SCCEntry* entry = &(load_entries[index]);
3314 
3315       st->print_cr("%4u: %4u: K%u L%u offset=%u decompile=%u size=%u code_size=%u%s%s%s%s",
3316                 i, index, entry->kind(), entry->comp_level(), entry->offset(),
3317                 entry->decompile(), entry->size(), entry->code_size(),
3318                 entry->has_clinit_barriers() ? " has_clinit_barriers" : "",
3319                 entry->for_preload()         ? " for_preload"         : "",
3320                 entry->is_loaded()           ? " loaded"              : "",
3321                 entry->not_entrant()         ? " not_entrant"         : "");
3322       st->print_raw("         ");
3323       SCCReader reader(cache, entry, nullptr);
3324       reader.print_on(st);
3325     }
3326   } else {
3327     st->print_cr("failed to open SCA at %s", CachedCodeFile);
3328   }
3329 }
3330 
3331 void SCCReader::print_on(outputStream* st) {
3332   uint entry_position = _entry->offset();
3333   set_read_position(entry_position);
3334 
3335   // Read name
3336   uint name_offset = entry_position + _entry->name_offset();
3337   uint name_size = _entry->name_size(); // Includes '/0'
3338   const char* name = addr(name_offset);
3339 
3340   st->print_cr("  name: %s", name);
3341 }
3342 
3343 #define _extrs_max 80
3344 #define _stubs_max 120
3345 #define _blobs_max 80
3346 #define _shared_blobs_max 16
3347 #define _C2_blobs_max 21
3348 #define _C1_blobs_max (_blobs_max - _shared_blobs_max - _C2_blobs_max)
3349 #define _all_max 280
3350 
3351 #define SET_ADDRESS(type, addr)                           \
3352   {                                                       \
3353     type##_addr[type##_length++] = (address) (addr);      \
3354     assert(type##_length <= type##_max, "increase size"); \
3355   }
3356 
3357 static bool initializing = false;
3358 void SCAddressTable::init() {
3359   if (_complete || initializing) return; // Done already
3360   initializing = true;
3361   _extrs_addr = NEW_C_HEAP_ARRAY(address, _extrs_max, mtCode);
3362   _stubs_addr = NEW_C_HEAP_ARRAY(address, _stubs_max, mtCode);
3363   _blobs_addr = NEW_C_HEAP_ARRAY(address, _blobs_max, mtCode);
3364 
3365   // Divide _blobs_addr array to chunks because they could be initialized in parrallel
3366   _C2_blobs_addr = _blobs_addr + _shared_blobs_max;// C2 blobs addresses stored after shared blobs
3367   _C1_blobs_addr = _C2_blobs_addr + _C2_blobs_max; // C1 blobs addresses stored after C2 blobs
3368 
3369   _extrs_length = 0;
3370   _stubs_length = 0;
3371   _blobs_length = 0;       // for shared blobs
3372   _C1_blobs_length = 0;
3373   _C2_blobs_length = 0;
3374   _final_blobs_length = 0; // Depends on numnber of C1 blobs
3375 
3376   // Runtime methods
3377 #ifdef COMPILER2
3378   SET_ADDRESS(_extrs, OptoRuntime::handle_exception_C);
3379 #endif
3380 #ifdef COMPILER1
3381   SET_ADDRESS(_extrs, Runtime1::is_instance_of);
3382   SET_ADDRESS(_extrs, Runtime1::trace_block_entry);
3383 #endif
3384 
3385   SET_ADDRESS(_extrs, CompressedOops::ptrs_base_addr());
3386   SET_ADDRESS(_extrs, G1BarrierSetRuntime::write_ref_field_post_entry);
3387   SET_ADDRESS(_extrs, G1BarrierSetRuntime::write_ref_field_pre_entry);
3388 
3389   SET_ADDRESS(_extrs, SharedRuntime::complete_monitor_unlocking_C);
3390   SET_ADDRESS(_extrs, SharedRuntime::enable_stack_reserved_zone);
3391 #ifdef AMD64
3392   SET_ADDRESS(_extrs, SharedRuntime::montgomery_multiply);
3393   SET_ADDRESS(_extrs, SharedRuntime::montgomery_square);
3394 #endif // AMD64
3395   SET_ADDRESS(_extrs, SharedRuntime::d2f);
3396   SET_ADDRESS(_extrs, SharedRuntime::d2i);
3397   SET_ADDRESS(_extrs, SharedRuntime::d2l);
3398   SET_ADDRESS(_extrs, SharedRuntime::dcos);
3399   SET_ADDRESS(_extrs, SharedRuntime::dexp);
3400   SET_ADDRESS(_extrs, SharedRuntime::dlog);
3401   SET_ADDRESS(_extrs, SharedRuntime::dlog10);
3402   SET_ADDRESS(_extrs, SharedRuntime::dpow);
3403   SET_ADDRESS(_extrs, SharedRuntime::drem);
3404   SET_ADDRESS(_extrs, SharedRuntime::dsin);
3405   SET_ADDRESS(_extrs, SharedRuntime::dtan);
3406   SET_ADDRESS(_extrs, SharedRuntime::f2i);
3407   SET_ADDRESS(_extrs, SharedRuntime::f2l);
3408   SET_ADDRESS(_extrs, SharedRuntime::frem);
3409   SET_ADDRESS(_extrs, SharedRuntime::l2d);
3410   SET_ADDRESS(_extrs, SharedRuntime::l2f);
3411   SET_ADDRESS(_extrs, SharedRuntime::ldiv);
3412   SET_ADDRESS(_extrs, SharedRuntime::lmul);
3413   SET_ADDRESS(_extrs, SharedRuntime::lrem);
3414   SET_ADDRESS(_extrs, &JvmtiExport::_should_notify_object_alloc);
3415 
3416   BarrierSet* bs = BarrierSet::barrier_set(); 
3417   if (bs->is_a(BarrierSet::CardTableBarrierSet)) {
3418     SET_ADDRESS(_extrs, ci_card_table_address_as<address>());
3419   }
3420   SET_ADDRESS(_extrs, ThreadIdentifier::unsafe_offset());
3421   SET_ADDRESS(_extrs, Thread::current);
3422 
3423   SET_ADDRESS(_extrs, os::javaTimeMillis);
3424   SET_ADDRESS(_extrs, os::javaTimeNanos);
3425 
3426   SET_ADDRESS(_extrs, &JvmtiVTMSTransitionDisabler::_VTMS_notify_jvmti_events);
3427   SET_ADDRESS(_extrs, StubRoutines::crc_table_addr());
3428 #ifndef PRODUCT
3429   SET_ADDRESS(_extrs, &SharedRuntime::_partial_subtype_ctr);
3430   SET_ADDRESS(_extrs, JavaThread::verify_cross_modify_fence_failure);
3431 #endif
3432 
3433 #if defined(AMD64) || defined(AARCH64) || defined(RISCV64)
3434   SET_ADDRESS(_extrs, MacroAssembler::debug64);
3435 #endif
3436 #if defined(AMD64)
3437   SET_ADDRESS(_extrs, StubRoutines::x86::arrays_hashcode_powers_of_31());
3438 #endif
3439 
3440 #ifdef X86
3441   SET_ADDRESS(_extrs, LIR_Assembler::float_signmask_pool);
3442   SET_ADDRESS(_extrs, LIR_Assembler::double_signmask_pool);
3443   SET_ADDRESS(_extrs, LIR_Assembler::float_signflip_pool);
3444   SET_ADDRESS(_extrs, LIR_Assembler::double_signflip_pool);
3445 #endif
3446 
3447   // Stubs
3448   SET_ADDRESS(_stubs, StubRoutines::method_entry_barrier());
3449   SET_ADDRESS(_stubs, StubRoutines::forward_exception_entry());
3450 /*
3451   SET_ADDRESS(_stubs, StubRoutines::throw_AbstractMethodError_entry());
3452   SET_ADDRESS(_stubs, StubRoutines::throw_IncompatibleClassChangeError_entry());
3453   SET_ADDRESS(_stubs, StubRoutines::throw_NullPointerException_at_call_entry());
3454   SET_ADDRESS(_stubs, StubRoutines::throw_StackOverflowError_entry());
3455   SET_ADDRESS(_stubs, StubRoutines::throw_delayed_StackOverflowError_entry());
3456 */
3457   SET_ADDRESS(_stubs, StubRoutines::atomic_xchg_entry());
3458   SET_ADDRESS(_stubs, StubRoutines::atomic_cmpxchg_entry());
3459   SET_ADDRESS(_stubs, StubRoutines::atomic_cmpxchg_long_entry());
3460   SET_ADDRESS(_stubs, StubRoutines::atomic_add_entry());
3461   SET_ADDRESS(_stubs, StubRoutines::fence_entry());
3462 
3463   SET_ADDRESS(_stubs, StubRoutines::cont_thaw());
3464   SET_ADDRESS(_stubs, StubRoutines::cont_returnBarrier());
3465   SET_ADDRESS(_stubs, StubRoutines::cont_returnBarrierExc());
3466 
3467   JFR_ONLY(SET_ADDRESS(_stubs, StubRoutines::jfr_write_checkpoint());)
3468 
3469 
3470   SET_ADDRESS(_stubs, StubRoutines::jbyte_arraycopy());
3471   SET_ADDRESS(_stubs, StubRoutines::jshort_arraycopy());
3472   SET_ADDRESS(_stubs, StubRoutines::jint_arraycopy());
3473   SET_ADDRESS(_stubs, StubRoutines::jlong_arraycopy());
3474   SET_ADDRESS(_stubs, StubRoutines::_oop_arraycopy);
3475   SET_ADDRESS(_stubs, StubRoutines::_oop_arraycopy_uninit);
3476 
3477   SET_ADDRESS(_stubs, StubRoutines::jbyte_disjoint_arraycopy());
3478   SET_ADDRESS(_stubs, StubRoutines::jshort_disjoint_arraycopy());
3479   SET_ADDRESS(_stubs, StubRoutines::jint_disjoint_arraycopy());
3480   SET_ADDRESS(_stubs, StubRoutines::jlong_disjoint_arraycopy());
3481   SET_ADDRESS(_stubs, StubRoutines::_oop_disjoint_arraycopy);
3482   SET_ADDRESS(_stubs, StubRoutines::_oop_disjoint_arraycopy_uninit);
3483 
3484   SET_ADDRESS(_stubs, StubRoutines::arrayof_jbyte_arraycopy());
3485   SET_ADDRESS(_stubs, StubRoutines::arrayof_jshort_arraycopy());
3486   SET_ADDRESS(_stubs, StubRoutines::arrayof_jint_arraycopy());
3487   SET_ADDRESS(_stubs, StubRoutines::arrayof_jlong_arraycopy());
3488   SET_ADDRESS(_stubs, StubRoutines::_arrayof_oop_arraycopy);
3489   SET_ADDRESS(_stubs, StubRoutines::_arrayof_oop_arraycopy_uninit);
3490 
3491   SET_ADDRESS(_stubs, StubRoutines::arrayof_jbyte_disjoint_arraycopy());
3492   SET_ADDRESS(_stubs, StubRoutines::arrayof_jshort_disjoint_arraycopy());
3493   SET_ADDRESS(_stubs, StubRoutines::arrayof_jint_disjoint_arraycopy());
3494   SET_ADDRESS(_stubs, StubRoutines::arrayof_jlong_disjoint_arraycopy());
3495   SET_ADDRESS(_stubs, StubRoutines::_arrayof_oop_disjoint_arraycopy);
3496   SET_ADDRESS(_stubs, StubRoutines::_arrayof_oop_disjoint_arraycopy_uninit);
3497 
3498   SET_ADDRESS(_stubs, StubRoutines::_checkcast_arraycopy);
3499   SET_ADDRESS(_stubs, StubRoutines::_checkcast_arraycopy_uninit);
3500 
3501   SET_ADDRESS(_stubs, StubRoutines::unsafe_arraycopy());
3502   SET_ADDRESS(_stubs, StubRoutines::generic_arraycopy());
3503 
3504   SET_ADDRESS(_stubs, StubRoutines::jbyte_fill());
3505   SET_ADDRESS(_stubs, StubRoutines::jshort_fill());
3506   SET_ADDRESS(_stubs, StubRoutines::jint_fill());
3507   SET_ADDRESS(_stubs, StubRoutines::arrayof_jbyte_fill());
3508   SET_ADDRESS(_stubs, StubRoutines::arrayof_jshort_fill());
3509   SET_ADDRESS(_stubs, StubRoutines::arrayof_jint_fill());
3510 
3511   SET_ADDRESS(_stubs, StubRoutines::data_cache_writeback());
3512   SET_ADDRESS(_stubs, StubRoutines::data_cache_writeback_sync());
3513 
3514   SET_ADDRESS(_stubs, StubRoutines::aescrypt_encryptBlock());
3515   SET_ADDRESS(_stubs, StubRoutines::aescrypt_decryptBlock());
3516   SET_ADDRESS(_stubs, StubRoutines::cipherBlockChaining_encryptAESCrypt());
3517   SET_ADDRESS(_stubs, StubRoutines::cipherBlockChaining_decryptAESCrypt());
3518   SET_ADDRESS(_stubs, StubRoutines::electronicCodeBook_encryptAESCrypt());
3519   SET_ADDRESS(_stubs, StubRoutines::electronicCodeBook_decryptAESCrypt());
3520   SET_ADDRESS(_stubs, StubRoutines::poly1305_processBlocks());
3521   SET_ADDRESS(_stubs, StubRoutines::counterMode_AESCrypt());
3522   SET_ADDRESS(_stubs, StubRoutines::ghash_processBlocks());
3523   SET_ADDRESS(_stubs, StubRoutines::chacha20Block());
3524   SET_ADDRESS(_stubs, StubRoutines::base64_encodeBlock());
3525   SET_ADDRESS(_stubs, StubRoutines::base64_decodeBlock());
3526   SET_ADDRESS(_stubs, StubRoutines::md5_implCompress());
3527   SET_ADDRESS(_stubs, StubRoutines::md5_implCompressMB());
3528   SET_ADDRESS(_stubs, StubRoutines::sha1_implCompress());
3529   SET_ADDRESS(_stubs, StubRoutines::sha1_implCompressMB());
3530   SET_ADDRESS(_stubs, StubRoutines::sha256_implCompress());
3531   SET_ADDRESS(_stubs, StubRoutines::sha256_implCompressMB());
3532   SET_ADDRESS(_stubs, StubRoutines::sha512_implCompress());
3533   SET_ADDRESS(_stubs, StubRoutines::sha512_implCompressMB());
3534   SET_ADDRESS(_stubs, StubRoutines::sha3_implCompress());
3535   SET_ADDRESS(_stubs, StubRoutines::sha3_implCompressMB());
3536 
3537   SET_ADDRESS(_stubs, StubRoutines::updateBytesCRC32());
3538 
3539   SET_ADDRESS(_stubs, StubRoutines::crc32c_table_addr());
3540   SET_ADDRESS(_stubs, StubRoutines::updateBytesCRC32C());
3541   SET_ADDRESS(_stubs, StubRoutines::updateBytesAdler32());
3542 
3543   SET_ADDRESS(_stubs, StubRoutines::multiplyToLen());
3544   SET_ADDRESS(_stubs, StubRoutines::squareToLen());
3545   SET_ADDRESS(_stubs, StubRoutines::mulAdd());
3546   SET_ADDRESS(_stubs, StubRoutines::montgomeryMultiply());
3547   SET_ADDRESS(_stubs, StubRoutines::montgomerySquare());
3548   SET_ADDRESS(_stubs, StubRoutines::bigIntegerRightShift());
3549   SET_ADDRESS(_stubs, StubRoutines::bigIntegerLeftShift());
3550   SET_ADDRESS(_stubs, StubRoutines::galoisCounterMode_AESCrypt());
3551 
3552   SET_ADDRESS(_stubs, StubRoutines::vectorizedMismatch());
3553 
3554   SET_ADDRESS(_stubs, StubRoutines::dexp());
3555   SET_ADDRESS(_stubs, StubRoutines::dlog());
3556   SET_ADDRESS(_stubs, StubRoutines::dlog10());
3557   SET_ADDRESS(_stubs, StubRoutines::dpow());
3558   SET_ADDRESS(_stubs, StubRoutines::dsin());
3559   SET_ADDRESS(_stubs, StubRoutines::dcos());
3560   SET_ADDRESS(_stubs, StubRoutines::dlibm_reduce_pi04l());
3561   SET_ADDRESS(_stubs, StubRoutines::dlibm_sin_cos_huge());
3562   SET_ADDRESS(_stubs, StubRoutines::dlibm_tan_cot_huge());
3563   SET_ADDRESS(_stubs, StubRoutines::dtan());
3564 
3565   SET_ADDRESS(_stubs, StubRoutines::f2hf_adr());
3566   SET_ADDRESS(_stubs, StubRoutines::hf2f_adr());
3567 
3568 #if defined(AMD64)
3569   SET_ADDRESS(_stubs, StubRoutines::x86::d2i_fixup());
3570   SET_ADDRESS(_stubs, StubRoutines::x86::f2i_fixup());
3571   SET_ADDRESS(_stubs, StubRoutines::x86::d2l_fixup());
3572   SET_ADDRESS(_stubs, StubRoutines::x86::f2l_fixup());
3573   SET_ADDRESS(_stubs, StubRoutines::x86::float_sign_mask());
3574   SET_ADDRESS(_stubs, StubRoutines::x86::float_sign_flip());
3575   SET_ADDRESS(_stubs, StubRoutines::x86::double_sign_mask());
3576   SET_ADDRESS(_stubs, StubRoutines::x86::double_sign_flip());
3577   SET_ADDRESS(_stubs, StubRoutines::x86::vector_popcount_lut());
3578   SET_ADDRESS(_stubs, StubRoutines::x86::vector_float_sign_mask());
3579   SET_ADDRESS(_stubs, StubRoutines::x86::vector_float_sign_flip());
3580   SET_ADDRESS(_stubs, StubRoutines::x86::vector_double_sign_mask());
3581   SET_ADDRESS(_stubs, StubRoutines::x86::vector_double_sign_flip());
3582   // The iota indices are ordered by type B/S/I/L/F/D, and the offset between two types is 64.
3583   // See C2_MacroAssembler::load_iota_indices().
3584   for (int i = 0; i < 6; i++) {
3585     SET_ADDRESS(_stubs, StubRoutines::x86::vector_iota_indices() + i * 64);
3586   }
3587 #endif
3588 #if defined(AARCH64)
3589   SET_ADDRESS(_stubs, StubRoutines::aarch64::d2i_fixup());
3590   SET_ADDRESS(_stubs, StubRoutines::aarch64::f2i_fixup());
3591   SET_ADDRESS(_stubs, StubRoutines::aarch64::d2l_fixup());
3592   SET_ADDRESS(_stubs, StubRoutines::aarch64::f2l_fixup());
3593   SET_ADDRESS(_stubs, StubRoutines::aarch64::float_sign_mask());
3594   SET_ADDRESS(_stubs, StubRoutines::aarch64::float_sign_flip());
3595   SET_ADDRESS(_stubs, StubRoutines::aarch64::double_sign_mask());
3596   SET_ADDRESS(_stubs, StubRoutines::aarch64::double_sign_flip());
3597   SET_ADDRESS(_stubs, StubRoutines::aarch64::zero_blocks());
3598   SET_ADDRESS(_stubs, StubRoutines::aarch64::count_positives());
3599   SET_ADDRESS(_stubs, StubRoutines::aarch64::count_positives_long());
3600   SET_ADDRESS(_stubs, StubRoutines::aarch64::large_array_equals());
3601   SET_ADDRESS(_stubs, StubRoutines::aarch64::compare_long_string_LL());
3602   SET_ADDRESS(_stubs, StubRoutines::aarch64::compare_long_string_UU());
3603   SET_ADDRESS(_stubs, StubRoutines::aarch64::compare_long_string_LU());
3604   SET_ADDRESS(_stubs, StubRoutines::aarch64::compare_long_string_UL());
3605   SET_ADDRESS(_stubs, StubRoutines::aarch64::string_indexof_linear_ul());
3606   SET_ADDRESS(_stubs, StubRoutines::aarch64::string_indexof_linear_ll());
3607   SET_ADDRESS(_stubs, StubRoutines::aarch64::string_indexof_linear_uu());
3608   SET_ADDRESS(_stubs, StubRoutines::aarch64::large_byte_array_inflate());
3609   SET_ADDRESS(_stubs, StubRoutines::aarch64::spin_wait());
3610 #endif
3611 
3612   // Blobs
3613   SET_ADDRESS(_blobs, SharedRuntime::get_handle_wrong_method_stub());
3614   SET_ADDRESS(_blobs, SharedRuntime::get_ic_miss_stub());
3615   SET_ADDRESS(_blobs, SharedRuntime::get_resolve_opt_virtual_call_stub());
3616   SET_ADDRESS(_blobs, SharedRuntime::get_resolve_virtual_call_stub());
3617   SET_ADDRESS(_blobs, SharedRuntime::get_resolve_static_call_stub());
3618   SET_ADDRESS(_blobs, SharedRuntime::deopt_blob()->entry_point());
3619   SET_ADDRESS(_blobs, SharedRuntime::polling_page_safepoint_handler_blob()->entry_point());
3620   SET_ADDRESS(_blobs, SharedRuntime::polling_page_return_handler_blob()->entry_point());
3621 #ifdef COMPILER2
3622   SET_ADDRESS(_blobs, SharedRuntime::polling_page_vectors_safepoint_handler_blob()->entry_point());
3623   SET_ADDRESS(_blobs, SharedRuntime::uncommon_trap_blob()->entry_point());
3624 #endif
3625   SET_ADDRESS(_blobs, StubRoutines::throw_AbstractMethodError_entry());
3626   SET_ADDRESS(_blobs, StubRoutines::throw_IncompatibleClassChangeError_entry());
3627   SET_ADDRESS(_blobs, StubRoutines::throw_NullPointerException_at_call_entry());
3628   SET_ADDRESS(_blobs, StubRoutines::throw_StackOverflowError_entry());
3629   SET_ADDRESS(_blobs, StubRoutines::throw_delayed_StackOverflowError_entry());
3630 
3631   assert(_blobs_length <= _shared_blobs_max, "increase _shared_blobs_max to %d", _blobs_length);
3632   _final_blobs_length = _blobs_length;
3633   _complete = true;
3634   log_info(scc,init)("External addresses and stubs recorded");
3635 }
3636 
3637 void SCAddressTable::init_opto() {
3638 #ifdef COMPILER2
3639   // OptoRuntime Blobs
3640   SET_ADDRESS(_C2_blobs, OptoRuntime::exception_blob()->entry_point());
3641   SET_ADDRESS(_C2_blobs, OptoRuntime::new_instance_Java());
3642   SET_ADDRESS(_C2_blobs, OptoRuntime::new_array_Java());
3643   SET_ADDRESS(_C2_blobs, OptoRuntime::new_array_nozero_Java());
3644   SET_ADDRESS(_C2_blobs, OptoRuntime::multianewarray2_Java());
3645   SET_ADDRESS(_C2_blobs, OptoRuntime::multianewarray3_Java());
3646   SET_ADDRESS(_C2_blobs, OptoRuntime::multianewarray4_Java());
3647   SET_ADDRESS(_C2_blobs, OptoRuntime::multianewarray5_Java());
3648   SET_ADDRESS(_C2_blobs, OptoRuntime::multianewarrayN_Java());
3649   SET_ADDRESS(_C2_blobs, OptoRuntime::vtable_must_compile_stub());
3650   SET_ADDRESS(_C2_blobs, OptoRuntime::complete_monitor_locking_Java());
3651   SET_ADDRESS(_C2_blobs, OptoRuntime::monitor_notify_Java());
3652   SET_ADDRESS(_C2_blobs, OptoRuntime::monitor_notifyAll_Java());
3653   SET_ADDRESS(_C2_blobs, OptoRuntime::rethrow_stub());
3654   SET_ADDRESS(_C2_blobs, OptoRuntime::slow_arraycopy_Java());
3655   SET_ADDRESS(_C2_blobs, OptoRuntime::register_finalizer_Java());
3656   SET_ADDRESS(_C2_blobs, OptoRuntime::class_init_barrier_Java());
3657   SET_ADDRESS(_C2_blobs, OptoRuntime::notify_jvmti_vthread_start());
3658   SET_ADDRESS(_C2_blobs, OptoRuntime::notify_jvmti_vthread_end());
3659   SET_ADDRESS(_C2_blobs, OptoRuntime::notify_jvmti_vthread_mount());
3660   SET_ADDRESS(_C2_blobs, OptoRuntime::notify_jvmti_vthread_unmount());
3661 #endif
3662 
3663   assert(_C2_blobs_length <= _C2_blobs_max, "increase _C2_blobs_max to %d", _C2_blobs_length);
3664   _final_blobs_length = MAX2(_final_blobs_length, (_shared_blobs_max + _C2_blobs_length));
3665   _opto_complete = true;
3666   log_info(scc,init)("OptoRuntime Blobs recorded");
3667 }
3668 
3669 void SCAddressTable::init_c1() {
3670 #ifdef COMPILER1
3671   // Runtime1 Blobs
3672   for (int i = 0; i < Runtime1::number_of_ids; i++) {
3673     Runtime1::StubID id = (Runtime1::StubID)i;
3674     if (Runtime1::blob_for(id) == nullptr) {
3675       log_info(scc, init)("C1 blob %s is missing", Runtime1::name_for(id));
3676       continue;
3677     }
3678     if (Runtime1::entry_for(id) == nullptr) {
3679       log_info(scc, init)("C1 blob %s is missing entry", Runtime1::name_for(id));
3680       continue;
3681     }
3682     address entry = Runtime1::entry_for(id);
3683     SET_ADDRESS(_C1_blobs, entry);
3684   }
3685 #if INCLUDE_G1GC
3686   if (UseG1GC) {
3687     G1BarrierSetC1* bs = (G1BarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
3688     address entry = bs->pre_barrier_c1_runtime_code_blob()->code_begin();
3689     SET_ADDRESS(_C1_blobs, entry);
3690     entry = bs->post_barrier_c1_runtime_code_blob()->code_begin();
3691     SET_ADDRESS(_C1_blobs, entry);
3692   }
3693 #endif // INCLUDE_G1GC
3694 #if INCLUDE_ZGC
3695   if (UseZGC) {
3696     ZBarrierSetC1* bs = (ZBarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
3697     SET_ADDRESS(_C1_blobs, bs->_load_barrier_on_oop_field_preloaded_runtime_stub);
3698     SET_ADDRESS(_C1_blobs, bs->_load_barrier_on_weak_oop_field_preloaded_runtime_stub);
3699     SET_ADDRESS(_C1_blobs, bs->_store_barrier_on_oop_field_with_healing);
3700     SET_ADDRESS(_C1_blobs, bs->_store_barrier_on_oop_field_without_healing);
3701   }
3702 #endif // INCLUDE_ZGC
3703 #endif // COMPILER1
3704 
3705   assert(_C1_blobs_length <= _C1_blobs_max, "increase _C1_blobs_max to %d", _C1_blobs_length);
3706   _final_blobs_length = MAX2(_final_blobs_length, (_shared_blobs_max + _C2_blobs_max + _C1_blobs_length));
3707   _c1_complete = true;
3708   log_info(scc,init)("Runtime1 Blobs recorded");
3709 }
3710 
3711 #undef SET_ADDRESS
3712 #undef _extrs_max
3713 #undef _stubs_max
3714 #undef _blobs_max
3715 #undef _shared_blobs_max
3716 #undef _C1_blobs_max
3717 #undef _C2_blobs_max
3718 
3719 SCAddressTable::~SCAddressTable() {
3720   if (_extrs_addr != nullptr) {
3721     FREE_C_HEAP_ARRAY(address, _extrs_addr);
3722   }
3723   if (_stubs_addr != nullptr) {
3724     FREE_C_HEAP_ARRAY(address, _stubs_addr);
3725   }
3726   if (_blobs_addr != nullptr) {
3727     FREE_C_HEAP_ARRAY(address, _blobs_addr);
3728   }
3729 }
3730 
3731 #define MAX_STR_COUNT 200
3732 static const char* _C_strings[MAX_STR_COUNT] = {nullptr};
3733 static int _C_strings_count = 0;
3734 static int _C_strings_s[MAX_STR_COUNT] = {0};
3735 static int _C_strings_id[MAX_STR_COUNT] = {0};
3736 static int _C_strings_len[MAX_STR_COUNT] = {0};
3737 static int _C_strings_hash[MAX_STR_COUNT] = {0};
3738 static int _C_strings_used = 0;
3739 
3740 void SCCache::load_strings() {
3741   uint strings_count  = _load_header->strings_count();
3742   if (strings_count == 0) {
3743     return;
3744   }
3745   uint strings_offset = _load_header->strings_offset();
3746   uint strings_size   = _load_header->entries_offset() - strings_offset;
3747   uint data_size = (uint)(strings_count * sizeof(uint));
3748   uint* sizes = (uint*)addr(strings_offset);
3749   uint* hashs = (uint*)addr(strings_offset + data_size);
3750   strings_size -= 2 * data_size;
3751   _C_strings_buf = addr(strings_offset + 2 * data_size);
3752   const char* p = _C_strings_buf;
3753   assert(strings_count <= MAX_STR_COUNT, "sanity");
3754   for (uint i = 0; i < strings_count; i++) {
3755     _C_strings[i] = p;
3756     uint len = sizes[i];
3757     _C_strings_s[i] = i;
3758     _C_strings_id[i] = i;
3759     _C_strings_len[i] = len;
3760     _C_strings_hash[i] = hashs[i];
3761     p += len;
3762   }
3763   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);
3764   _C_strings_count = strings_count;
3765   _C_strings_used  = strings_count;
3766   log_info(scc, init)("Load %d C strings at offset %d from Startup Code Cache '%s'", _C_strings_count, strings_offset, _cache_path);
3767 }
3768 
3769 int SCCache::store_strings() {
3770   uint offset = _write_position;
3771   uint length = 0;
3772   if (_C_strings_used > 0) {
3773     // Write sizes first
3774     for (int i = 0; i < _C_strings_used; i++) {
3775       uint len = _C_strings_len[i] + 1; // Include 0
3776       length += len;
3777       assert(len < 1000, "big string: %s", _C_strings[i]);
3778       uint n = write_bytes(&len, sizeof(uint));
3779       if (n != sizeof(uint)) {
3780         return -1;
3781       }
3782     }
3783     // Write hashs
3784     for (int i = 0; i < _C_strings_used; i++) {
3785       uint n = write_bytes(&(_C_strings_hash[i]), sizeof(uint));
3786       if (n != sizeof(uint)) {
3787         return -1;
3788       }
3789     }
3790     for (int i = 0; i < _C_strings_used; i++) {
3791       uint len = _C_strings_len[i] + 1; // Include 0
3792       uint n = write_bytes(_C_strings[_C_strings_s[i]], len);
3793       if (n != len) {
3794         return -1;
3795       }
3796     }
3797     log_info(scc, exit)("Wrote %d C strings of total length %d at offset %d to Startup Code Cache '%s'",
3798                         _C_strings_used, length, offset, _cache_path);
3799   }
3800   return _C_strings_used;
3801 }
3802 
3803 void SCCache::add_new_C_string(const char* str) {
3804   assert(for_write(), "only when storing code");
3805   _table->add_C_string(str);
3806 }
3807 
3808 void SCAddressTable::add_C_string(const char* str) {
3809   if (str != nullptr && _complete && (_opto_complete || _c1_complete)) {
3810     // Check previous strings address
3811     for (int i = 0; i < _C_strings_count; i++) {
3812       if (_C_strings[i] == str) {
3813         return; // Found existing one
3814       }
3815     }
3816     // Add new one
3817     if (_C_strings_count < MAX_STR_COUNT) {
3818       log_trace(scc)("add_C_string: [%d] " INTPTR_FORMAT " %s", _C_strings_count, p2i(str), str);
3819       _C_strings_id[_C_strings_count] = -1; // Init
3820       _C_strings[_C_strings_count++] = str;
3821     } else {
3822       CompileTask* task = ciEnv::current()->task();
3823       log_warning(scc)("%d (L%d): Number of C strings > max %d %s",
3824                        task->compile_id(), task->comp_level(), MAX_STR_COUNT, str);
3825     }
3826   }
3827 }
3828 
3829 int SCAddressTable::id_for_C_string(address str) {
3830   for (int i = 0; i < _C_strings_count; i++) {
3831     if (_C_strings[i] == (const char*)str) { // found
3832       int id = _C_strings_id[i];
3833       if (id >= 0) {
3834         assert(id < _C_strings_used, "%d >= %d", id , _C_strings_used);
3835         return id; // Found recorded
3836       }
3837       // Search for the same string content
3838       int len = (int)strlen((const char*)str);
3839       int hash = java_lang_String::hash_code((const jbyte*)str, len);
3840       for (int j = 0; j < _C_strings_used; j++) {
3841         if ((_C_strings_len[j] == len) && (_C_strings_hash[j] == hash)) {
3842           _C_strings_id[i] = j; // Found match
3843           return j;
3844         }
3845       }
3846       // Not found in recorded, add new
3847       id = _C_strings_used++;
3848       _C_strings_s[id] = i;
3849       _C_strings_id[i] = id;
3850       _C_strings_len[id] = len;
3851       _C_strings_hash[id] = hash;
3852       return id;
3853     }
3854   }
3855   return -1;
3856 }
3857 
3858 address SCAddressTable::address_for_C_string(int idx) {
3859   assert(idx < _C_strings_count, "sanity");
3860   return (address)_C_strings[idx];
3861 }
3862 
3863 int search_address(address addr, address* table, uint length) {
3864   for (int i = 0; i < (int)length; i++) {
3865     if (table[i] == addr) {
3866       return i;
3867     }
3868   }
3869   return -1;
3870 }
3871 
3872 address SCAddressTable::address_for_id(int idx) {
3873   if (!_complete) {
3874     fatal("SCA table is not complete");
3875   }
3876   if (idx == -1) {
3877     return (address)-1;
3878   }
3879   uint id = (uint)idx;
3880   if (id >= _all_max && idx < (_all_max + _C_strings_count)) {
3881     return address_for_C_string(idx - _all_max);
3882   }
3883   if (idx < 0 || id == (_extrs_length + _stubs_length + _final_blobs_length)) {
3884     fatal("Incorrect id %d for SCA table", id);
3885   }
3886   if (idx > (_all_max + _C_strings_count)) {
3887     return (address)os::init + idx;
3888   }
3889   if (id < _extrs_length) {
3890     return _extrs_addr[id];
3891   }
3892   id -= _extrs_length;
3893   if (id < _stubs_length) {
3894     return _stubs_addr[id];
3895   }
3896   id -= _stubs_length;
3897   if (id < _final_blobs_length) {
3898     return _blobs_addr[id];
3899   }
3900   return nullptr;
3901 }
3902 
3903 int SCAddressTable::id_for_address(address addr, RelocIterator reloc, CodeBuffer* buffer) {
3904   int id = -1;
3905   if (addr == (address)-1) { // Static call stub has jump to itself
3906     return id;
3907   }
3908   if (!_complete) {
3909     fatal("SCA table is not complete");
3910   }
3911   // Seach for C string
3912   id = id_for_C_string(addr);
3913   if (id >=0) {
3914     return id + _all_max;
3915   }
3916   if (StubRoutines::contains(addr)) {
3917     // Search in stubs
3918     id = search_address(addr, _stubs_addr, _stubs_length);
3919     if (id < 0) {
3920       StubCodeDesc* desc = StubCodeDesc::desc_for(addr);
3921       if (desc == nullptr) {
3922         desc = StubCodeDesc::desc_for(addr + frame::pc_return_offset);
3923       }
3924       const char* sub_name = (desc != nullptr) ? desc->name() : "<unknown>";
3925       fatal("Address " INTPTR_FORMAT " for Stub:%s is missing in SCA table", p2i(addr), sub_name);
3926     } else {
3927       id += _extrs_length;
3928     }
3929   } else {
3930     CodeBlob* cb = CodeCache::find_blob(addr);
3931     if (cb != nullptr) {
3932       // Search in code blobs
3933       id = search_address(addr, _blobs_addr, _final_blobs_length);
3934       if (id < 0) {
3935         fatal("Address " INTPTR_FORMAT " for Blob:%s is missing in SCA table", p2i(addr), cb->name());
3936       } else {
3937         id += _extrs_length + _stubs_length;
3938       }
3939     } else {
3940       // Search in runtime functions
3941       id = search_address(addr, _extrs_addr, _extrs_length);
3942       if (id < 0) {
3943         ResourceMark rm;
3944         const int buflen = 1024;
3945         char* func_name = NEW_RESOURCE_ARRAY(char, buflen);
3946         int offset = 0;
3947         if (os::dll_address_to_function_name(addr, func_name, buflen, &offset)) {
3948           if (offset > 0) {
3949             // Could be address of C string
3950             uint dist = (uint)pointer_delta(addr, (address)os::init, 1);
3951             CompileTask* task = ciEnv::current()->task();
3952             uint compile_id = 0;
3953             uint comp_level =0;
3954             if (task != nullptr) { // this could be called from compiler runtime initialization (compiler blobs)
3955               compile_id = task->compile_id();
3956               comp_level = task->comp_level();
3957             }
3958             log_info(scc)("%d (L%d): Address " INTPTR_FORMAT " (offset %d) for runtime target '%s' is missing in SCA table",
3959                           compile_id, comp_level, p2i(addr), dist, (const char*)addr);
3960             assert(dist > (uint)(_all_max + MAX_STR_COUNT), "change encoding of distance");
3961             return dist;
3962           }
3963           fatal("Address " INTPTR_FORMAT " for runtime target '%s+%d' is missing in SCA table", p2i(addr), func_name, offset);
3964         } else {
3965           os::print_location(tty, p2i(addr), true);
3966 #ifndef PRODUCT
3967           reloc.print_current();
3968           buffer->print();
3969           buffer->decode();
3970 #endif // !PRODUCT
3971           fatal("Address " INTPTR_FORMAT " for <unknown> is missing in SCA table", p2i(addr));
3972         }
3973       }
3974     }
3975   }
3976   return id;
3977 }