1 /*
   2  * Copyright (c) 2016, 2018, 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 #include "precompiled.hpp"
  25 
  26 #include "aot/aotCodeHeap.hpp"
  27 #include "aot/aotLoader.hpp"
  28 #include "ci/ciUtilities.hpp"
  29 #include "classfile/javaAssertions.hpp"
  30 #include "gc/shared/cardTable.hpp"
  31 #include "gc/shared/cardTableModRefBS.hpp"
  32 #include "gc/g1/heapRegion.hpp"
  33 #include "gc/shared/gcLocker.hpp"
  34 #include "interpreter/abstractInterpreter.hpp"
  35 #include "jvmci/compilerRuntime.hpp"
  36 #include "jvmci/jvmciRuntime.hpp"
  37 #include "memory/allocation.inline.hpp"
  38 #include "oops/method.inline.hpp"
  39 #include "runtime/os.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 #include "runtime/vm_operations.hpp"
  42 
  43 bool AOTLib::_narrow_oop_shift_initialized = false;
  44 int  AOTLib::_narrow_oop_shift = 0;
  45 int  AOTLib::_narrow_klass_shift = 0;
  46 
  47 address AOTLib::load_symbol(const char *name) {
  48   address symbol = (address) os::dll_lookup(_dl_handle, name);
  49   if (symbol == NULL) {
  50     tty->print_cr("Shared file %s error: missing %s", _name, name);
  51     vm_exit(1);
  52   }
  53   return symbol;
  54 }
  55 
  56 Klass* AOTCodeHeap::get_klass_from_got(const char* klass_name, int klass_len, const Method* method) {
  57   AOTKlassData* klass_data = (AOTKlassData*)_lib->load_symbol(klass_name);
  58   Klass* k = (Klass*)_klasses_got[klass_data->_got_index];
  59   if (k == NULL) {
  60     Thread* thread = Thread::current();
  61     k = lookup_klass(klass_name, klass_len, method, thread);
  62     // Note, exceptions are cleared.
  63     if (k == NULL) {
  64       fatal("Shared file %s error: klass %s should be resolved already", _lib->name(), klass_name);
  65       vm_exit(1);
  66     }
  67     // Patch now to avoid extra runtime lookup
  68     _klasses_got[klass_data->_got_index] = k;
  69     if (k->is_instance_klass()) {
  70       InstanceKlass* ik = InstanceKlass::cast(k);
  71       if (ik->is_initialized()) {
  72         _klasses_got[klass_data->_got_index - 1] = ik;
  73       }
  74     }
  75   }
  76   return k;
  77 }
  78 
  79 Klass* AOTCodeHeap::lookup_klass(const char* name, int len, const Method* method, Thread* thread) {
  80   ResourceMark rm(thread);
  81   assert(method != NULL, "incorrect call parameter");
  82   methodHandle caller(thread, (Method*)method);
  83 
  84   // Use class loader of aot method.
  85   Handle loader(thread, caller->method_holder()->class_loader());
  86   Handle protection_domain(thread, caller->method_holder()->protection_domain());
  87 
  88   // Ignore wrapping L and ;
  89   if (name[0] == 'L') {
  90     assert(len > 2, "small name %s", name);
  91     name++;
  92     len -= 2;
  93   }
  94   TempNewSymbol sym = SymbolTable::probe(name, len);
  95   if (sym == NULL) {
  96     log_debug(aot, class, resolve)("Probe failed for AOT class %s", name);
  97     return NULL;
  98   }
  99   Klass* k = SystemDictionary::find_instance_or_array_klass(sym, loader, protection_domain, thread);
 100   assert(!thread->has_pending_exception(), "should not throw");
 101 
 102   if (k != NULL) {
 103     log_info(aot, class, resolve)("%s %s (lookup)", caller->method_holder()->external_name(), k->external_name());
 104   }
 105   return k;
 106 }
 107 
 108 void AOTLib::handle_config_error(const char* format, ...) {
 109   if (PrintAOT) {
 110     va_list ap;
 111     va_start(ap, format);
 112     tty->vprint_cr(format, ap);
 113     va_end(ap);
 114   }
 115   if (UseAOTStrictLoading) {
 116     vm_exit(1);
 117   }
 118   _valid = false;
 119 }
 120 
 121 void AOTLib::verify_flag(bool aot_flag, bool flag, const char* name) {
 122   if (_valid && aot_flag != flag) {
 123     handle_config_error("Shared file %s error: %s has different value '%s' from current '%s'", _name, name , (aot_flag ? "true" : "false"), (flag ? "true" : "false"));
 124   }
 125 }
 126 
 127 void AOTLib::verify_flag(int aot_flag, int flag, const char* name) {
 128   if (_valid && aot_flag != flag) {
 129     handle_config_error("Shared file %s error: %s has different value '%d' from current '%d'", _name, name , aot_flag, flag);
 130   }
 131 }
 132 
 133 void AOTLib::verify_config() {
 134   GrowableArray<AOTLib*>* libraries = AOTLoader::libraries();
 135   for (GrowableArrayIterator<AOTLib*> lib = libraries->begin(); lib != libraries->end(); ++lib) {
 136     if ((*lib)->_config == _config) {
 137       handle_config_error("AOT library %s already loaded.", (*lib)->_name);
 138       return;
 139     }
 140   }
 141 
 142   if (_header->_version != AOTHeader::AOT_SHARED_VERSION) {
 143     handle_config_error("Invalid version of the shared file %s. Expected %d but was %d", _name, _header->_version, AOTHeader::AOT_SHARED_VERSION);
 144     return;
 145   }
 146 
 147   const char* aot_jvm_version = (const char*)_header + _header->_jvm_version_offset + 2;
 148   if (strcmp(aot_jvm_version, VM_Version::jre_release_version()) != 0) {
 149     handle_config_error("JVM version '%s' recorded in the shared file %s does not match current version '%s'", aot_jvm_version, _name, VM_Version::jre_release_version());
 150     return;
 151   }
 152 
 153   // Debug VM has different layout of runtime and metadata structures
 154 #ifdef ASSERT
 155   verify_flag(_config->_debug_VM, true, "Debug VM version");
 156 #else
 157   verify_flag(!(_config->_debug_VM), true, "Product VM version");
 158 #endif
 159   // Check configuration size
 160   verify_flag(_config->_config_size, AOTConfiguration::CONFIG_SIZE, "AOT configuration size");
 161 
 162   // Check flags
 163   verify_flag(_config->_useCompressedOops, UseCompressedOops, "UseCompressedOops");
 164   verify_flag(_config->_useCompressedClassPointers, UseCompressedClassPointers, "UseCompressedClassPointers");
 165   verify_flag(_config->_useG1GC, UseG1GC, "UseG1GC");
 166   verify_flag(_config->_useTLAB, UseTLAB, "UseTLAB");
 167   verify_flag(_config->_useBiasedLocking, UseBiasedLocking, "UseBiasedLocking");
 168   verify_flag(_config->_objectAlignment, ObjectAlignmentInBytes, "ObjectAlignmentInBytes");
 169   verify_flag(_config->_contendedPaddingWidth, ContendedPaddingWidth, "ContendedPaddingWidth");
 170   verify_flag(_config->_fieldsAllocationStyle, FieldsAllocationStyle, "FieldsAllocationStyle");
 171   verify_flag(_config->_compactFields, CompactFields, "CompactFields");
 172   verify_flag(_config->_enableContended, EnableContended, "EnableContended");
 173   verify_flag(_config->_restrictContended, RestrictContended, "RestrictContended");
 174   verify_flag(_config->_threadLocalHandshakes, ThreadLocalHandshakes, "ThreadLocalHandshakes");
 175 
 176   if (!TieredCompilation && _config->_tieredAOT) {
 177     handle_config_error("Shared file %s error: Expected to run with tiered compilation on", _name);
 178   }
 179 
 180   // Shifts are static values which initialized by 0 until java heap initialization.
 181   // AOT libs are loaded before heap initialized so shift values are not set.
 182   // It is okay since ObjectAlignmentInBytes flag which defines shifts value is set before AOT libs are loaded.
 183   // Set shifts value based on first AOT library config.
 184   if (UseCompressedOops && _valid) {
 185     if (!_narrow_oop_shift_initialized) {
 186       _narrow_oop_shift = _config->_narrowOopShift;
 187       if (UseCompressedClassPointers) { // It is set only if UseCompressedOops is set
 188         _narrow_klass_shift = _config->_narrowKlassShift;
 189       }
 190       _narrow_oop_shift_initialized = true;
 191     } else {
 192       verify_flag(_config->_narrowOopShift, _narrow_oop_shift, "aot_config->_narrowOopShift");
 193       if (UseCompressedClassPointers) { // It is set only if UseCompressedOops is set
 194         verify_flag(_config->_narrowKlassShift, _narrow_klass_shift, "aot_config->_narrowKlassShift");
 195       }
 196     }
 197   }
 198 }
 199 
 200 AOTLib::~AOTLib() {
 201   os::free((void*) _name);
 202 }
 203 
 204 AOTCodeHeap::~AOTCodeHeap() {
 205   if (_classes != NULL) {
 206     FREE_C_HEAP_ARRAY(AOTClass, _classes);
 207   }
 208   if (_code_to_aot != NULL) {
 209     FREE_C_HEAP_ARRAY(CodeToAMethod, _code_to_aot);
 210   }
 211 }
 212 
 213 AOTLib::AOTLib(void* handle, const char* name, int dso_id) : _valid(true), _dl_handle(handle), _dso_id(dso_id) {
 214   _name = (const char*) os::strdup(name);
 215 
 216   // Verify that VM runs with the same parameters as AOT tool.
 217   _config = (AOTConfiguration*) load_symbol("A.config");
 218   _header = (AOTHeader*) load_symbol("A.header");
 219 
 220   verify_config();
 221 
 222   if (!_valid && PrintAOT) {
 223       tty->print("%7d ", (int) tty->time_stamp().milliseconds());
 224       tty->print_cr("%4d     skipped %s  aot library", _dso_id, _name);
 225   }
 226 }
 227 
 228 AOTCodeHeap::AOTCodeHeap(AOTLib* lib) :
 229     CodeHeap("CodeHeap 'AOT'", CodeBlobType::AOT), _lib(lib), _classes(NULL), _code_to_aot(NULL) {
 230   assert(_lib->is_valid(), "invalid library");
 231 
 232   _lib_symbols_initialized = false;
 233   _aot_id = 0;
 234 
 235   _class_count = _lib->header()->_class_count;
 236   _method_count = _lib->header()->_method_count;
 237 
 238   // Collect metaspace info: names -> address in .got section
 239   _metaspace_names = (const char*) _lib->load_symbol("A.meta.names");
 240   _method_metadata =     (address) _lib->load_symbol("A.meth.metadata");
 241   _methods_offsets =     (address) _lib->load_symbol("A.meth.offsets");
 242   _klasses_offsets =     (address) _lib->load_symbol("A.kls.offsets");
 243   _dependencies    =     (address) _lib->load_symbol("A.kls.dependencies");
 244   _code_space      =     (address) _lib->load_symbol("A.text");
 245 
 246   // First cell is number of elements.
 247   _klasses_got      = (Metadata**) _lib->load_symbol("A.kls.got");
 248   _klasses_got_size = _lib->header()->_klasses_got_size;
 249 
 250   _metadata_got      = (Metadata**) _lib->load_symbol("A.meta.got");
 251   _metadata_got_size = _lib->header()->_metadata_got_size;
 252 
 253   _oop_got      = (oop*) _lib->load_symbol("A.oop.got");
 254   _oop_got_size = _lib->header()->_oop_got_size;
 255 
 256   // Collect stubs info
 257   _stubs_offsets = (int*) _lib->load_symbol("A.stubs.offsets");
 258 
 259   // code segments table
 260   _code_segments = (address) _lib->load_symbol("A.code.segments");
 261 
 262   // method state
 263   _method_state = (jlong*) _lib->load_symbol("A.meth.state");
 264 
 265   // Create a table for mapping classes
 266   _classes = NEW_C_HEAP_ARRAY(AOTClass, _class_count, mtCode);
 267   memset(_classes, 0, _class_count * sizeof(AOTClass));
 268 
 269   // Create table for searching AOTCompiledMethod based on pc.
 270   _code_to_aot = NEW_C_HEAP_ARRAY(CodeToAMethod, _method_count, mtCode);
 271   memset(_code_to_aot, 0, _method_count * sizeof(CodeToAMethod));
 272 
 273   _memory.set_low_boundary((char *)_code_space);
 274   _memory.set_high_boundary((char *)_code_space);
 275   _memory.set_low((char *)_code_space);
 276   _memory.set_high((char *)_code_space);
 277 
 278   _segmap.set_low_boundary((char *)_code_segments);
 279   _segmap.set_low((char *)_code_segments);
 280 
 281   _log2_segment_size = exact_log2(_lib->config()->_codeSegmentSize);
 282 
 283   // Register aot stubs
 284   register_stubs();
 285 
 286   if (PrintAOT || (PrintCompilation && PrintAOT)) {
 287     tty->print("%7d ", (int) tty->time_stamp().milliseconds());
 288     tty->print_cr("%4d     loaded    %s  aot library", _lib->id(), _lib->name());
 289   }
 290 }
 291 
 292 void AOTCodeHeap::publish_aot(const methodHandle& mh, AOTMethodData* method_data, int code_id) {
 293   // The method may be explicitly excluded by the user.
 294   // Or Interpreter uses an intrinsic for this method.
 295   if (CompilerOracle::should_exclude(mh) || !AbstractInterpreter::can_be_compiled(mh)) {
 296     return;
 297   }
 298 
 299   address code = method_data->_code;
 300   const char* name = method_data->_name;
 301   aot_metadata* meta = method_data->_meta;
 302 
 303   if (meta->scopes_pcs_begin() == meta->scopes_pcs_end()) {
 304     // When the AOT compiler compiles something big we fail to generate metadata
 305     // in CodeInstaller::gather_metadata. In that case the scopes_pcs_begin == scopes_pcs_end.
 306     // In all successful cases we always have 2 entries of scope pcs.
 307     log_info(aot, class, resolve)("Failed to load %s (no metadata available)", mh->name_and_sig_as_C_string());
 308     _code_to_aot[code_id]._state = invalid;
 309     return;
 310   }
 311 
 312   jlong* state_adr = &_method_state[code_id];
 313   address metadata_table = method_data->_metadata_table;
 314   int metadata_size = method_data->_metadata_size;
 315   assert(code_id < _method_count, "sanity");
 316   _aot_id++;
 317 
 318 #ifdef ASSERT
 319   if (_aot_id > CIStop || _aot_id < CIStart) {
 320     // Skip compilation
 321     return;
 322   }
 323 #endif
 324   // Check one more time.
 325   if (_code_to_aot[code_id]._state == invalid) {
 326     return;
 327   }
 328   AOTCompiledMethod *aot = new AOTCompiledMethod(code, mh(), meta, metadata_table, metadata_size, state_adr, this, name, code_id, _aot_id);
 329   assert(_code_to_aot[code_id]._aot == NULL, "should be not initialized");
 330   _code_to_aot[code_id]._aot = aot; // Should set this first
 331   if (Atomic::cmpxchg(in_use, &_code_to_aot[code_id]._state, not_set) != not_set) {
 332     _code_to_aot[code_id]._aot = NULL; // Clean
 333   } else { // success
 334     // Publish method
 335 #ifdef TIERED
 336     mh->set_aot_code(aot);
 337 #endif
 338     Method::set_code(mh, aot);
 339     if (PrintAOT || (PrintCompilation && PrintAOT)) {
 340       aot->print_on(tty, NULL);
 341     }
 342     // Publish oop only after we are visible to CompiledMethodIterator
 343     aot->set_oop(mh()->method_holder()->klass_holder());
 344   }
 345 }
 346 
 347 void AOTCodeHeap::link_primitive_array_klasses() {
 348   ResourceMark rm;
 349   for (int i = T_BOOLEAN; i <= T_CONFLICT; i++) {
 350     BasicType t = (BasicType)i;
 351     if (is_java_primitive(t)) {
 352       const Klass* arr_klass = Universe::typeArrayKlassObj(t);
 353       AOTKlassData* klass_data = (AOTKlassData*) os::dll_lookup(_lib->dl_handle(), arr_klass->signature_name());
 354       if (klass_data != NULL) {
 355         // Set both GOT cells, resolved and initialized klass pointers.
 356         // _got_index points to second cell - resolved klass pointer.
 357         _klasses_got[klass_data->_got_index-1] = (Metadata*)arr_klass; // Initialized
 358         _klasses_got[klass_data->_got_index  ] = (Metadata*)arr_klass; // Resolved
 359         if (PrintAOT) {
 360           tty->print_cr("[Found  %s  in  %s]", arr_klass->internal_name(), _lib->name());
 361         }
 362       }
 363     }
 364   }
 365 }
 366 
 367 void AOTCodeHeap::register_stubs() {
 368   int stubs_count = _stubs_offsets[0]; // contains number
 369   _stubs_offsets++;
 370   AOTMethodOffsets* stub_offsets = (AOTMethodOffsets*)_stubs_offsets;
 371   for (int i = 0; i < stubs_count; ++i) {
 372     const char* stub_name = _metaspace_names + stub_offsets[i]._name_offset;
 373     address entry = _code_space  + stub_offsets[i]._code_offset;
 374     aot_metadata* meta = (aot_metadata *) (_method_metadata + stub_offsets[i]._meta_offset);
 375     address metadata_table = (address)_metadata_got + stub_offsets[i]._metadata_got_offset;
 376     int metadata_size = stub_offsets[i]._metadata_got_size;
 377     int code_id = stub_offsets[i]._code_id;
 378     assert(code_id < _method_count, "sanity");
 379     jlong* state_adr = &_method_state[code_id];
 380     int len = build_u2_from((address)stub_name);
 381     stub_name += 2;
 382     char* full_name = NEW_C_HEAP_ARRAY(char, len+5, mtCode);
 383     if (full_name == NULL) { // No memory?
 384       break;
 385     }
 386     memcpy(full_name, "AOT ", 4);
 387     memcpy(full_name+4, stub_name, len);
 388     full_name[len+4] = 0;
 389     guarantee(_code_to_aot[code_id]._state != invalid, "stub %s can't be invalidated", full_name);
 390     AOTCompiledMethod* aot = new AOTCompiledMethod(entry, NULL, meta, metadata_table, metadata_size, state_adr, this, full_name, code_id, i);
 391     assert(_code_to_aot[code_id]._aot  == NULL, "should be not initialized");
 392     _code_to_aot[code_id]._aot  = aot;
 393     if (Atomic::cmpxchg(in_use, &_code_to_aot[code_id]._state, not_set) != not_set) {
 394       fatal("stab '%s' code state is %d", full_name, _code_to_aot[code_id]._state);
 395     }
 396     // Adjust code buffer boundaries only for stubs because they are last in the buffer.
 397     adjust_boundaries(aot);
 398     if (PrintAOT && Verbose) {
 399       aot->print_on(tty, NULL);
 400     }
 401   }
 402 }
 403 
 404 #define SET_AOT_GLOBAL_SYMBOL_VALUE(AOTSYMNAME, AOTSYMTYPE, VMSYMVAL) \
 405   {                                                                   \
 406     AOTSYMTYPE * adr = (AOTSYMTYPE *) os::dll_lookup(_lib->dl_handle(), AOTSYMNAME);  \
 407     /* Check for a lookup error */                                    \
 408     guarantee(adr != NULL, "AOT Symbol not found %s", AOTSYMNAME);    \
 409     *adr = (AOTSYMTYPE) VMSYMVAL;                                     \
 410   }
 411 
 412 void AOTCodeHeap::link_graal_runtime_symbols()  {
 413     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_monitorenter", address, JVMCIRuntime::monitorenter);
 414     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_monitorexit", address, JVMCIRuntime::monitorexit);
 415     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_log_object", address, JVMCIRuntime::log_object);
 416     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_log_printf", address, JVMCIRuntime::log_printf);
 417     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_log_primitive", address, JVMCIRuntime::log_primitive);
 418     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_instance", address, JVMCIRuntime::new_instance);
 419     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_array", address, JVMCIRuntime::new_array);
 420     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_multi_array", address, JVMCIRuntime::new_multi_array);
 421     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_dynamic_new_array", address, JVMCIRuntime::dynamic_new_array);
 422     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_validate_object", address, JVMCIRuntime::validate_object);
 423     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_write_barrier_pre", address, JVMCIRuntime::write_barrier_pre);
 424     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_identity_hash_code", address, JVMCIRuntime::identity_hash_code);
 425     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_write_barrier_post", address, JVMCIRuntime::write_barrier_post);
 426     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_dynamic_new_instance", address, JVMCIRuntime::dynamic_new_instance);
 427     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_thread_is_interrupted", address, JVMCIRuntime::thread_is_interrupted);
 428     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_exception_handler_for_pc", address, JVMCIRuntime::exception_handler_for_pc);
 429     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_test_deoptimize_call_int", address, JVMCIRuntime::test_deoptimize_call_int);
 430     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_throw_and_post_jvmti_exception", address, JVMCIRuntime::throw_and_post_jvmti_exception);
 431     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_throw_klass_external_name_exception", address, JVMCIRuntime::throw_klass_external_name_exception);
 432     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_throw_class_cast_exception", address, JVMCIRuntime::throw_class_cast_exception);
 433     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_vm_message", address, JVMCIRuntime::vm_message);
 434     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_vm_error", address, JVMCIRuntime::vm_error);
 435 }
 436 
 437 void AOTCodeHeap::link_shared_runtime_symbols() {
 438     SET_AOT_GLOBAL_SYMBOL_VALUE("_resolve_static_entry", address, SharedRuntime::get_resolve_static_call_stub());
 439     SET_AOT_GLOBAL_SYMBOL_VALUE("_resolve_virtual_entry", address, SharedRuntime::get_resolve_virtual_call_stub());
 440     SET_AOT_GLOBAL_SYMBOL_VALUE("_resolve_opt_virtual_entry", address, SharedRuntime::get_resolve_opt_virtual_call_stub());
 441     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_deopt_blob_unpack", address, SharedRuntime::deopt_blob()->unpack());
 442     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_deopt_blob_uncommon_trap", address, SharedRuntime::deopt_blob()->uncommon_trap());
 443     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_ic_miss_stub", address, SharedRuntime::get_ic_miss_stub());
 444     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_handle_wrong_method_stub", address, SharedRuntime::get_handle_wrong_method_stub());
 445     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_exception_handler_for_return_address", address, SharedRuntime::exception_handler_for_return_address);
 446     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_register_finalizer", address, SharedRuntime::register_finalizer);
 447     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_OSR_migration_end", address, SharedRuntime::OSR_migration_end);
 448     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_resolve_dynamic_invoke", address, CompilerRuntime::resolve_dynamic_invoke);
 449     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_resolve_string_by_symbol", address, CompilerRuntime::resolve_string_by_symbol);
 450     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_resolve_klass_by_symbol", address, CompilerRuntime::resolve_klass_by_symbol);
 451     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_resolve_method_by_symbol_and_load_counters", address, CompilerRuntime::resolve_method_by_symbol_and_load_counters);
 452     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_initialize_klass_by_symbol", address, CompilerRuntime::initialize_klass_by_symbol);
 453     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_invocation_event", address, CompilerRuntime::invocation_event);
 454     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_backedge_event", address, CompilerRuntime::backedge_event);
 455 
 456     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dpow", address, SharedRuntime::dpow);
 457     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dexp", address, SharedRuntime::dexp);
 458     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dcos", address, SharedRuntime::dcos);
 459     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dsin", address, SharedRuntime::dsin);
 460     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dtan", address, SharedRuntime::dtan);
 461     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dlog", address, SharedRuntime::dlog);
 462     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dlog10", address, SharedRuntime::dlog10);
 463 }
 464 
 465 void AOTCodeHeap::link_stub_routines_symbols() {
 466     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jbyte_arraycopy", address, StubRoutines::_jbyte_arraycopy);
 467     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jshort_arraycopy", address, StubRoutines::_jshort_arraycopy);
 468     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jint_arraycopy", address, StubRoutines::_jint_arraycopy);
 469     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jlong_arraycopy", address, StubRoutines::_jlong_arraycopy);
 470     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_arraycopy", address, StubRoutines::_oop_arraycopy);
 471     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_arraycopy_uninit", address, StubRoutines::_oop_arraycopy_uninit);
 472 
 473     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jbyte_disjoint_arraycopy", address, StubRoutines::_jbyte_disjoint_arraycopy);
 474     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jshort_disjoint_arraycopy", address, StubRoutines::_jshort_disjoint_arraycopy);
 475     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jint_disjoint_arraycopy", address, StubRoutines::_jint_disjoint_arraycopy);
 476     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jlong_disjoint_arraycopy", address, StubRoutines::_jlong_disjoint_arraycopy);
 477     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_disjoint_arraycopy", address, StubRoutines::_oop_disjoint_arraycopy);
 478     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_disjoint_arraycopy_uninit", address, StubRoutines::_oop_disjoint_arraycopy_uninit);
 479 
 480     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jbyte_arraycopy", address, StubRoutines::_arrayof_jbyte_arraycopy);
 481     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jshort_arraycopy", address, StubRoutines::_arrayof_jshort_arraycopy);
 482     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jint_arraycopy", address, StubRoutines::_arrayof_jint_arraycopy);
 483     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jlong_arraycopy", address, StubRoutines::_arrayof_jlong_arraycopy);
 484     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_arraycopy", address, StubRoutines::_arrayof_oop_arraycopy);
 485     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_arraycopy_uninit", address, StubRoutines::_arrayof_oop_arraycopy_uninit);
 486 
 487     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jbyte_disjoint_arraycopy", address, StubRoutines::_arrayof_jbyte_disjoint_arraycopy);
 488     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jshort_disjoint_arraycopy", address, StubRoutines::_arrayof_jshort_disjoint_arraycopy);
 489     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jint_disjoint_arraycopy", address, StubRoutines::_arrayof_jint_disjoint_arraycopy);
 490     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jlong_disjoint_arraycopy", address, StubRoutines::_arrayof_jlong_disjoint_arraycopy);
 491     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_disjoint_arraycopy", address, StubRoutines::_arrayof_oop_disjoint_arraycopy);
 492     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_disjoint_arraycopy_uninit", address, StubRoutines::_arrayof_oop_disjoint_arraycopy_uninit);
 493 
 494     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_unsafe_arraycopy", address, StubRoutines::_unsafe_arraycopy);
 495 
 496     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_checkcast_arraycopy", address, StubRoutines::_checkcast_arraycopy);
 497 
 498     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_generic_arraycopy", address, StubRoutines::_generic_arraycopy);
 499 
 500     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_aescrypt_encryptBlock", address, StubRoutines::_aescrypt_encryptBlock);
 501     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_aescrypt_decryptBlock", address, StubRoutines::_aescrypt_decryptBlock);
 502     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_cipherBlockChaining_encryptAESCrypt", address, StubRoutines::_cipherBlockChaining_encryptAESCrypt);
 503     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_cipherBlockChaining_decryptAESCrypt", address, StubRoutines::_cipherBlockChaining_decryptAESCrypt);
 504     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_update_bytes_crc32", address, StubRoutines::_updateBytesCRC32);
 505     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_crc_table_adr", address, StubRoutines::_crc_table_adr);
 506 
 507 
 508     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha1_implCompress", address, StubRoutines::_sha1_implCompress);
 509     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha1_implCompressMB", address, StubRoutines::_sha1_implCompressMB);
 510     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha256_implCompress", address, StubRoutines::_sha256_implCompress);
 511     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha256_implCompressMB", address, StubRoutines::_sha256_implCompressMB);
 512     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha512_implCompress", address, StubRoutines::_sha512_implCompress);
 513     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha512_implCompressMB", address, StubRoutines::_sha512_implCompressMB);
 514     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_multiplyToLen", address, StubRoutines::_multiplyToLen);
 515 
 516     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_counterMode_AESCrypt", address, StubRoutines::_counterMode_AESCrypt);
 517     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_ghash_processBlocks", address, StubRoutines::_ghash_processBlocks);
 518     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_crc32c_table_addr", address, StubRoutines::_crc32c_table_addr);
 519     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_updateBytesCRC32C", address, StubRoutines::_updateBytesCRC32C);
 520     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_updateBytesAdler32", address, StubRoutines::_updateBytesAdler32);
 521     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_squareToLen", address, StubRoutines::_squareToLen);
 522     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_mulAdd", address, StubRoutines::_mulAdd);
 523     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_montgomeryMultiply",  address, StubRoutines::_montgomeryMultiply);
 524     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_montgomerySquare", address, StubRoutines::_montgomerySquare);
 525     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_vectorizedMismatch", address, StubRoutines::_vectorizedMismatch);
 526 
 527     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_throw_delayed_StackOverflowError_entry", address, StubRoutines::_throw_delayed_StackOverflowError_entry);
 528 
 529 }
 530 
 531 void AOTCodeHeap::link_os_symbols() {
 532     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_os_javaTimeMillis", address, os::javaTimeMillis);
 533     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_os_javaTimeNanos", address, os::javaTimeNanos);
 534 }
 535 
 536 /*
 537  * Link any global symbols in precompiled DSO with dlopen() _dl_handle
 538  * dso_handle.
 539  */
 540 
 541 void AOTCodeHeap::link_global_lib_symbols() {
 542   if (!_lib_symbols_initialized) {
 543     _lib_symbols_initialized = true;
 544 
 545     CollectedHeap* heap = Universe::heap();
 546     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_card_table_address", address, ci_card_table_address());
 547     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_heap_top_address", address, (heap->supports_inline_contig_alloc() ? heap->top_addr() : NULL));
 548     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_heap_end_address", address, (heap->supports_inline_contig_alloc() ? heap->end_addr() : NULL));
 549     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_polling_page", address, os::get_polling_page());
 550     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_narrow_klass_base_address", address, Universe::narrow_klass_base());
 551     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_narrow_oop_base_address", address, Universe::narrow_oop_base());
 552     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_log_of_heap_region_grain_bytes", int, HeapRegion::LogOfHRGrainBytes);
 553     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_inline_contiguous_allocation_supported", bool, heap->supports_inline_contig_alloc());
 554     link_shared_runtime_symbols();
 555     link_stub_routines_symbols();
 556     link_os_symbols();
 557     link_graal_runtime_symbols();
 558 
 559     // Link primitive array klasses.
 560     link_primitive_array_klasses();
 561   }
 562 }
 563 
 564 #ifndef PRODUCT
 565 int AOTCodeHeap::klasses_seen = 0;
 566 int AOTCodeHeap::aot_klasses_found = 0;
 567 int AOTCodeHeap::aot_klasses_fp_miss = 0;
 568 int AOTCodeHeap::aot_klasses_cl_miss = 0;
 569 int AOTCodeHeap::aot_methods_found = 0;
 570 
 571 void AOTCodeHeap::print_statistics() {
 572   tty->print_cr("Classes seen: %d  AOT classes found: %d  AOT methods found: %d", klasses_seen, aot_klasses_found, aot_methods_found);
 573   tty->print_cr("AOT fingerprint mismatches: %d  AOT class loader mismatches: %d", aot_klasses_fp_miss, aot_klasses_cl_miss);
 574 }
 575 #endif
 576 
 577 Method* AOTCodeHeap::find_method(Klass* klass, Thread* thread, const char* method_name) {
 578   int method_name_len = build_u2_from((address)method_name);
 579   method_name += 2;
 580   const char* signature_name = method_name + method_name_len;
 581   int signature_name_len = build_u2_from((address)signature_name);
 582   signature_name += 2;
 583   // The class should have been loaded so the method and signature should already be
 584   // in the symbol table.  If they're not there, the method doesn't exist.
 585   TempNewSymbol name = SymbolTable::probe(method_name, method_name_len);
 586   TempNewSymbol signature = SymbolTable::probe(signature_name, signature_name_len);
 587 
 588   Method* m;
 589   if (name == NULL || signature == NULL) {
 590     m = NULL;
 591   } else if (name == vmSymbols::object_initializer_name() ||
 592              name == vmSymbols::class_initializer_name()) {
 593     // Never search superclasses for constructors
 594     if (klass->is_instance_klass()) {
 595       m = InstanceKlass::cast(klass)->find_method(name, signature);
 596     } else {
 597       m = NULL;
 598     }
 599   } else {
 600     m = klass->lookup_method(name, signature);
 601     if (m == NULL && klass->is_instance_klass()) {
 602       m = InstanceKlass::cast(klass)->lookup_method_in_ordered_interfaces(name, signature);
 603     }
 604   }
 605   if (m == NULL) {
 606     // Fatal error because we assume classes and methods should not be changed since aot compilation.
 607     const char* klass_name = klass->external_name();
 608     int klass_len = (int)strlen(klass_name);
 609     char* meta_name = NEW_RESOURCE_ARRAY(char, klass_len + 1 + method_name_len + signature_name_len + 1);
 610     memcpy(meta_name, klass_name, klass_len);
 611     meta_name[klass_len] = '.';
 612     memcpy(&meta_name[klass_len + 1], method_name, method_name_len);
 613     memcpy(&meta_name[klass_len + 1 + method_name_len], signature_name, signature_name_len);
 614     meta_name[klass_len + 1 + method_name_len + signature_name_len] = '\0';
 615     Handle exception = Exceptions::new_exception(thread, vmSymbols::java_lang_NoSuchMethodError(), meta_name);
 616     java_lang_Throwable::print(exception(), tty);
 617     tty->cr();
 618     java_lang_Throwable::print_stack_trace(exception, tty);
 619     tty->cr();
 620     fatal("Failed to find method '%s'", meta_name);
 621   }
 622   NOT_PRODUCT( aot_methods_found++; )
 623   return m;
 624 }
 625 
 626 AOTKlassData* AOTCodeHeap::find_klass(const char *name) {
 627   return (AOTKlassData*) os::dll_lookup(_lib->dl_handle(), name);
 628 }
 629 
 630 AOTKlassData* AOTCodeHeap::find_klass(InstanceKlass* ik) {
 631   ResourceMark rm;
 632   AOTKlassData* klass_data = find_klass(ik->signature_name());
 633   return klass_data;
 634 }
 635 
 636 bool AOTCodeHeap::is_dependent_method(Klass* dependee, AOTCompiledMethod* aot) {
 637   InstanceKlass *dependee_ik = InstanceKlass::cast(dependee);
 638   AOTKlassData* klass_data = find_klass(dependee_ik);
 639   if (klass_data == NULL) {
 640     return false; // no AOT records for this class - no dependencies
 641   }
 642   if (!dependee_ik->has_passed_fingerprint_check()) {
 643     return false; // different class
 644   }
 645 
 646   int methods_offset = klass_data->_dependent_methods_offset;
 647   if (methods_offset >= 0) {
 648     address methods_cnt_adr = _dependencies + methods_offset;
 649     int methods_cnt = *(int*)methods_cnt_adr;
 650     int* indexes = (int*)(methods_cnt_adr + 4);
 651     for (int i = 0; i < methods_cnt; ++i) {
 652       int code_id = indexes[i];
 653       if (_code_to_aot[code_id]._aot == aot) {
 654         return true; // found dependent method
 655       }
 656     }
 657   }
 658   return false;
 659 }
 660 
 661 void AOTCodeHeap::sweep_dependent_methods(int* indexes, int methods_cnt) {
 662   int marked = 0;
 663   for (int i = 0; i < methods_cnt; ++i) {
 664     int code_id = indexes[i];
 665     // Invalidate aot code.
 666     if (Atomic::cmpxchg(invalid, &_code_to_aot[code_id]._state, not_set) != not_set) {
 667       if (_code_to_aot[code_id]._state == in_use) {
 668         AOTCompiledMethod* aot = _code_to_aot[code_id]._aot;
 669         assert(aot != NULL, "aot should be set");
 670         if (!aot->is_runtime_stub()) { // Something is wrong - should not invalidate stubs.
 671           aot->mark_for_deoptimization(false);
 672           marked++;
 673         }
 674       }
 675     }
 676   }
 677   if (marked > 0) {
 678     VM_Deoptimize op;
 679     VMThread::execute(&op);
 680   }
 681 }
 682 
 683 void AOTCodeHeap::sweep_dependent_methods(AOTKlassData* klass_data) {
 684   // Make dependent methods non_entrant forever.
 685   int methods_offset = klass_data->_dependent_methods_offset;
 686   if (methods_offset >= 0) {
 687     address methods_cnt_adr = _dependencies + methods_offset;
 688     int methods_cnt = *(int*)methods_cnt_adr;
 689     int* indexes = (int*)(methods_cnt_adr + 4);
 690     sweep_dependent_methods(indexes, methods_cnt);
 691   }
 692 }
 693 
 694 void AOTCodeHeap::sweep_dependent_methods(InstanceKlass* ik) {
 695   AOTKlassData* klass_data = find_klass(ik);
 696   vmassert(klass_data != NULL, "dependency data missing");
 697   sweep_dependent_methods(klass_data);
 698 }
 699 
 700 void AOTCodeHeap::sweep_method(AOTCompiledMethod *aot) {
 701   int indexes[] = {aot->method_index()};
 702   sweep_dependent_methods(indexes, 1);
 703   vmassert(aot->method()->code() != aot && aot->method()->aot_code() == NULL, "method still active");
 704 }
 705 
 706 
 707 bool AOTCodeHeap::load_klass_data(InstanceKlass* ik, Thread* thread) {
 708   ResourceMark rm;
 709 
 710   NOT_PRODUCT( klasses_seen++; )
 711 
 712   AOTKlassData* klass_data = find_klass(ik);
 713   if (klass_data == NULL) {
 714     return false;
 715   }
 716 
 717   if (!ik->has_passed_fingerprint_check()) {
 718     NOT_PRODUCT( aot_klasses_fp_miss++; )
 719     log_trace(aot, class, fingerprint)("class  %s%s  has bad fingerprint in  %s tid=" INTPTR_FORMAT,
 720                                        ik->internal_name(), ik->is_shared() ? " (shared)" : "",
 721                                        _lib->name(), p2i(thread));
 722     sweep_dependent_methods(klass_data);
 723     return false;
 724   }
 725 
 726   if (ik->has_been_redefined()) {
 727     log_trace(aot, class, load)("class  %s%s in %s  has been redefined tid=" INTPTR_FORMAT,
 728                                 ik->internal_name(), ik->is_shared() ? " (shared)" : "",
 729                                 _lib->name(), p2i(thread));
 730     sweep_dependent_methods(klass_data);
 731     return false;
 732   }
 733 
 734   assert(klass_data->_class_id < _class_count, "invalid class id");
 735   AOTClass* aot_class = &_classes[klass_data->_class_id];
 736   if (aot_class->_classloader != NULL && aot_class->_classloader != ik->class_loader_data()) {
 737     log_trace(aot, class, load)("class  %s  in  %s already loaded for classloader %p vs %p tid=" INTPTR_FORMAT,
 738                                 ik->internal_name(), _lib->name(), aot_class->_classloader, ik->class_loader_data(), p2i(thread));
 739     NOT_PRODUCT( aot_klasses_cl_miss++; )
 740     return false;
 741   }
 742 
 743   if (_lib->config()->_omitAssertions && JavaAssertions::enabled(ik->name()->as_C_string(), ik->class_loader() == NULL)) {
 744     log_trace(aot, class, load)("class  %s  in  %s does not have java assertions in compiled code, but assertions are enabled for this execution.", ik->internal_name(), _lib->name());
 745     sweep_dependent_methods(klass_data);
 746     return false;
 747   }
 748 
 749   NOT_PRODUCT( aot_klasses_found++; )
 750 
 751   log_trace(aot, class, load)("found  %s  in  %s for classloader %p tid=" INTPTR_FORMAT, ik->internal_name(), _lib->name(), ik->class_loader_data(), p2i(thread));
 752 
 753   aot_class->_classloader = ik->class_loader_data();
 754   // Set klass's Resolve (second) got cell.
 755   _klasses_got[klass_data->_got_index] = ik;
 756   if (ik->is_initialized()) {
 757     _klasses_got[klass_data->_got_index - 1] = ik;
 758   }
 759 
 760   // Initialize global symbols of the DSO to the corresponding VM symbol values.
 761   link_global_lib_symbols();
 762 
 763   int methods_offset = klass_data->_compiled_methods_offset;
 764   if (methods_offset >= 0) {
 765     address methods_cnt_adr = _methods_offsets + methods_offset;
 766     int methods_cnt = *(int*)methods_cnt_adr;
 767     // Collect data about compiled methods
 768     AOTMethodData* methods_data = NEW_RESOURCE_ARRAY(AOTMethodData, methods_cnt);
 769     AOTMethodOffsets* methods_offsets = (AOTMethodOffsets*)(methods_cnt_adr + 4);
 770     for (int i = 0; i < methods_cnt; ++i) {
 771       AOTMethodOffsets* method_offsets = &methods_offsets[i];
 772       int code_id = method_offsets->_code_id;
 773       if (_code_to_aot[code_id]._state == invalid) {
 774         continue; // skip AOT methods slots which have been invalidated
 775       }
 776       AOTMethodData* method_data = &methods_data[i];
 777       const char* aot_name = _metaspace_names + method_offsets->_name_offset;
 778       method_data->_name = aot_name;
 779       method_data->_code = _code_space  + method_offsets->_code_offset;
 780       method_data->_meta = (aot_metadata*)(_method_metadata + method_offsets->_meta_offset);
 781       method_data->_metadata_table = (address)_metadata_got + method_offsets->_metadata_got_offset;
 782       method_data->_metadata_size  = method_offsets->_metadata_got_size;
 783       // aot_name format: "<u2_size>Ljava/lang/ThreadGroup;<u2_size>addUnstarted<u2_size>()V"
 784       int klass_len = build_u2_from((address)aot_name);
 785       const char* method_name = aot_name + 2 + klass_len;
 786       Method* m = AOTCodeHeap::find_method(ik, thread, method_name);
 787       methodHandle mh(thread, m);
 788       if (mh->code() != NULL) { // Does it have already compiled code?
 789         continue; // Don't overwrite
 790       }
 791       publish_aot(mh, method_data, code_id);
 792     }
 793   }
 794   return true;
 795 }
 796 
 797 AOTCompiledMethod* AOTCodeHeap::next_in_use_at(int start) const {
 798   for (int index = start; index < _method_count; index++) {
 799     if (_code_to_aot[index]._state != in_use) {
 800       continue; // Skip uninitialized entries.
 801     }
 802     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 803     return aot;
 804   }
 805   return NULL;
 806 }
 807 
 808 void* AOTCodeHeap::first() const {
 809   return next_in_use_at(0);
 810 }
 811 
 812 void* AOTCodeHeap::next(void* p) const {
 813   AOTCompiledMethod *aot = (AOTCompiledMethod *)p;
 814   int next_index = aot->method_index() + 1;
 815   assert(next_index <= _method_count, "");
 816   if (next_index == _method_count) {
 817     return NULL;
 818   }
 819   return next_in_use_at(next_index);
 820 }
 821 
 822 void* AOTCodeHeap::find_start(void* p) const {
 823   if (!contains(p)) {
 824     return NULL;
 825   }
 826   size_t offset = pointer_delta(p, low_boundary(), 1);
 827   // Use segments table
 828   size_t seg_idx = offset / _lib->config()->_codeSegmentSize;
 829   if ((int)(_code_segments[seg_idx]) == 0xff) {
 830     return NULL;
 831   }
 832   while (_code_segments[seg_idx] > 0) {
 833     seg_idx -= (int)_code_segments[seg_idx];
 834   }
 835   int code_offset = (int)seg_idx * _lib->config()->_codeSegmentSize;
 836   int aot_index = *(int*)(_code_space + code_offset);
 837   AOTCompiledMethod* aot = _code_to_aot[aot_index]._aot;
 838   assert(aot != NULL, "should find registered aot method");
 839   return aot;
 840 }
 841 
 842 AOTCompiledMethod* AOTCodeHeap::find_aot(address p) const {
 843   assert(contains(p), "should be here");
 844   return (AOTCompiledMethod *)find_start(p);
 845 }
 846 
 847 CodeBlob* AOTCodeHeap::find_blob_unsafe(void* start) const {
 848   return (CodeBlob*)AOTCodeHeap::find_start(start);
 849 }
 850 
 851 void AOTCodeHeap::oops_do(OopClosure* f) {
 852   for (int i = 0; i < _oop_got_size; i++) {
 853     oop* p = &_oop_got[i];
 854     if (*p == NULL)  continue;  // skip non-oops
 855     f->do_oop(p);
 856   }
 857   for (int index = 0; index < _method_count; index++) {
 858     if (_code_to_aot[index]._state != in_use) {
 859       continue; // Skip uninitialized entries.
 860     }
 861     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 862     aot->do_oops(f);
 863   }
 864 }
 865 
 866 // Scan only klasses_got cells which should have only Klass*,
 867 // metadata_got cells are scanned only for alive AOT methods
 868 // by AOTCompiledMethod::metadata_do().
 869 void AOTCodeHeap::got_metadata_do(void f(Metadata*)) {
 870   for (int i = 1; i < _klasses_got_size; i++) {
 871     Metadata** p = &_klasses_got[i];
 872     Metadata* md = *p;
 873     if (md == NULL)  continue;  // skip non-oops
 874     if (Metaspace::contains(md)) {
 875       f(md);
 876     } else {
 877       intptr_t meta = (intptr_t)md;
 878       fatal("Invalid value in _klasses_got[%d] = " INTPTR_FORMAT, i, meta);
 879     }
 880   }
 881 }
 882 
 883 void AOTCodeHeap::cleanup_inline_caches() {
 884   for (int index = 0; index < _method_count; index++) {
 885     if (_code_to_aot[index]._state != in_use) {
 886       continue; // Skip uninitialized entries.
 887     }
 888     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 889     aot->cleanup_inline_caches();
 890   }
 891 }
 892 
 893 #ifdef ASSERT
 894 int AOTCodeHeap::verify_icholder_relocations() {
 895   int count = 0;
 896   for (int index = 0; index < _method_count; index++) {
 897     if (_code_to_aot[index]._state != in_use) {
 898       continue; // Skip uninitialized entries.
 899     }
 900     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 901     count += aot->verify_icholder_relocations();
 902   }
 903   return count;
 904 }
 905 #endif
 906 
 907 void AOTCodeHeap::flush_evol_dependents_on(InstanceKlass* dependee) {
 908   for (int index = 0; index < _method_count; index++) {
 909     if (_code_to_aot[index]._state != in_use) {
 910       continue; // Skip uninitialized entries.
 911     }
 912     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 913     aot->flush_evol_dependents_on(dependee);
 914   }
 915 }
 916 
 917 void AOTCodeHeap::metadata_do(void f(Metadata*)) {
 918   for (int index = 0; index < _method_count; index++) {
 919     if (_code_to_aot[index]._state != in_use) {
 920       continue; // Skip uninitialized entries.
 921     }
 922     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 923     if (aot->_is_alive()) {
 924       aot->metadata_do(f);
 925     }
 926   }
 927   // Scan klasses_got cells.
 928   got_metadata_do(f);
 929 }
 930 
 931 bool AOTCodeHeap::reconcile_dynamic_klass(AOTCompiledMethod *caller, InstanceKlass* holder, int index, Klass *dyno_klass, const char *descriptor1, const char *descriptor2) {
 932   const char * const descriptors[2] = {descriptor1, descriptor2};
 933   JavaThread *thread = JavaThread::current();
 934   ResourceMark rm(thread);
 935 
 936   AOTKlassData* holder_data = find_klass(holder);
 937   vmassert(holder_data != NULL, "klass %s not found", holder->signature_name());
 938   vmassert(is_dependent_method(holder, caller), "sanity");
 939 
 940   AOTKlassData* dyno_data = NULL;
 941   bool adapter_failed = false;
 942   char buf[64];
 943   int descriptor_index = 0;
 944   // descriptors[0] specific name ("adapter:<method_id>") for matching
 945   // descriptors[1] fall-back name ("adapter") for depdencies
 946   while (descriptor_index < 2) {
 947     const char *descriptor = descriptors[descriptor_index];
 948     if (descriptor == NULL) {
 949       break;
 950     }
 951     jio_snprintf(buf, sizeof buf, "%s<%d:%d>", descriptor, holder_data->_class_id, index);
 952     dyno_data = find_klass(buf);
 953     if (dyno_data != NULL) {
 954       break;
 955     }
 956     // If match failed then try fall-back for dependencies
 957     ++descriptor_index;
 958     adapter_failed = true;
 959   }
 960 
 961   if (dyno_data == NULL && dyno_klass == NULL) {
 962     // all is well, no (appendix) at compile-time, and still none
 963     return true;
 964   }
 965 
 966   if (dyno_data == NULL) {
 967     // no (appendix) at build-time, but now there is
 968     sweep_dependent_methods(holder_data);
 969     return false;
 970   }
 971 
 972   if (adapter_failed) {
 973     // adapter method mismatch
 974     sweep_dependent_methods(holder_data);
 975     sweep_dependent_methods(dyno_data);
 976     return false;
 977   }
 978 
 979   if (dyno_klass == NULL) {
 980     // (appendix) at build-time, none now
 981     sweep_dependent_methods(holder_data);
 982     sweep_dependent_methods(dyno_data);
 983     return false;
 984   }
 985 
 986   // TODO: support array appendix object
 987   if (!dyno_klass->is_instance_klass()) {
 988     sweep_dependent_methods(holder_data);
 989     sweep_dependent_methods(dyno_data);
 990     return false;
 991   }
 992 
 993   InstanceKlass* dyno = InstanceKlass::cast(dyno_klass);
 994 
 995   if (!dyno->is_anonymous()) {
 996     if (_klasses_got[dyno_data->_got_index] != dyno) {
 997       // compile-time class different from runtime class, fail and deoptimize
 998       sweep_dependent_methods(holder_data);
 999       sweep_dependent_methods(dyno_data);
1000       return false;
1001     }
1002 
1003     if (dyno->is_initialized()) {
1004       _klasses_got[dyno_data->_got_index - 1] = dyno;
1005     }
1006     return true;
1007   }
1008 
1009   // TODO: support anonymous supers
1010   if (!dyno->supers_have_passed_fingerprint_checks() || dyno->get_stored_fingerprint() != dyno_data->_fingerprint) {
1011       NOT_PRODUCT( aot_klasses_fp_miss++; )
1012       log_trace(aot, class, fingerprint)("class  %s%s  has bad fingerprint in  %s tid=" INTPTR_FORMAT,
1013           dyno->internal_name(), dyno->is_shared() ? " (shared)" : "",
1014           _lib->name(), p2i(thread));
1015     sweep_dependent_methods(holder_data);
1016     sweep_dependent_methods(dyno_data);
1017     return false;
1018   }
1019 
1020   _klasses_got[dyno_data->_got_index] = dyno;
1021   if (dyno->is_initialized()) {
1022     _klasses_got[dyno_data->_got_index - 1] = dyno;
1023   }
1024 
1025   // TODO: hook up any AOT code
1026   // load_klass_data(dyno_data, thread);
1027   return true;
1028 }
1029 
1030 bool AOTCodeHeap::reconcile_dynamic_method(AOTCompiledMethod *caller, InstanceKlass* holder, int index, Method *adapter_method) {
1031     InstanceKlass *adapter_klass = adapter_method->method_holder();
1032     char buf[64];
1033     jio_snprintf(buf, sizeof buf, "adapter:%d", adapter_method->method_idnum());
1034     if (!reconcile_dynamic_klass(caller, holder, index, adapter_klass, buf, "adapter")) {
1035       return false;
1036     }
1037     return true;
1038 }
1039 
1040 bool AOTCodeHeap::reconcile_dynamic_invoke(AOTCompiledMethod* caller, InstanceKlass* holder, int index, Method* adapter_method, Klass *appendix_klass) {
1041     if (!reconcile_dynamic_klass(caller, holder, index, appendix_klass, "appendix")) {
1042       return false;
1043     }
1044 
1045     if (!reconcile_dynamic_method(caller, holder, index, adapter_method)) {
1046       return false;
1047     }
1048 
1049     return true;
1050 }