1 /*
   2  * Copyright (c) 2015, 2019, 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 "code/compiledIC.hpp"
  27 #include "code/compiledMethod.inline.hpp"
  28 #include "code/exceptionHandlerTable.hpp"
  29 #include "code/scopeDesc.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/icBuffer.hpp"
  32 #include "gc/shared/barrierSet.hpp"
  33 #include "gc/shared/gcBehaviours.hpp"
  34 #include "interpreter/bytecode.inline.hpp"
  35 #include "logging/log.hpp"
  36 #include "logging/logTag.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/methodData.hpp"
  39 #include "oops/method.inline.hpp"
  40 #include "oops/weakHandle.inline.hpp"
  41 #include "prims/methodHandles.hpp"
  42 #include "runtime/deoptimization.hpp"
  43 #include "runtime/jniHandles.inline.hpp"
  44 #include "runtime/handles.inline.hpp"
  45 #include "runtime/mutexLocker.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 
  48 CompiledMethod::CompiledMethod(Method* method, const char* name, CompilerType type, const CodeBlobLayout& layout,
  49                                int frame_complete_offset, int frame_size, ImmutableOopMapSet* oop_maps,
  50                                bool caller_must_gc_arguments, bool compiled)
  51   : CodeBlob(name, type, layout, frame_complete_offset, frame_size, oop_maps, caller_must_gc_arguments, compiled),
  52     _mark_for_deoptimization_status(not_marked),
  53     _method(method),
  54     _gc_data(NULL),
  55     _keepalive(NULL)
  56 {
  57   init_defaults();
  58 }
  59 
  60 CompiledMethod::CompiledMethod(Method* method, const char* name, CompilerType type, int size,
  61                                int header_size, CodeBuffer* cb, int frame_complete_offset, int frame_size,
  62                                OopMapSet* oop_maps, bool caller_must_gc_arguments, bool compiled)
  63   : CodeBlob(name, type, CodeBlobLayout((address) this, size, header_size, cb), cb,
  64              frame_complete_offset, frame_size, oop_maps, caller_must_gc_arguments, compiled),
  65     _mark_for_deoptimization_status(not_marked),
  66     _method(method),
  67     _gc_data(NULL),
  68     _keepalive(NULL)
  69 {
  70   init_defaults();
  71 }
  72 
  73 void CompiledMethod::init_defaults() {
  74   _has_unsafe_access          = 0;
  75   _has_method_handle_invokes  = 0;
  76   _lazy_critical_native       = 0;
  77   _has_wide_vectors           = 0;
  78   _has_monitors               = 0;
  79 }
  80 
  81 bool CompiledMethod::is_method_handle_return(address return_pc) {
  82   if (!has_method_handle_invokes())  return false;
  83   PcDesc* pd = pc_desc_at(return_pc);
  84   if (pd == NULL)
  85     return false;
  86   return pd->is_method_handle_invoke();
  87 }
  88 
  89 // Returns a string version of the method state.
  90 const char* CompiledMethod::state() const {
  91   int state = get_state();
  92   switch (state) {
  93   case not_installed:
  94     return "not installed";
  95   case in_use:
  96     return "in use";
  97   case not_used:
  98     return "not_used";
  99   case not_entrant:
 100     return "not_entrant";
 101   case zombie:
 102     return "zombie";
 103   case unloaded:
 104     return "unloaded";
 105   default:
 106     fatal("unexpected method state: %d", state);
 107     return NULL;
 108   }
 109 }
 110 
 111 //-----------------------------------------------------------------------------
 112 
 113 ExceptionCache* CompiledMethod::exception_cache_acquire() const {
 114   return OrderAccess::load_acquire(&_exception_cache);
 115 }
 116 
 117 void CompiledMethod::add_exception_cache_entry(ExceptionCache* new_entry) {
 118   assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
 119   assert(new_entry != NULL,"Must be non null");
 120   assert(new_entry->next() == NULL, "Must be null");
 121 
 122   for (;;) {
 123     ExceptionCache *ec = exception_cache();
 124     if (ec != NULL) {
 125       Klass* ex_klass = ec->exception_type();
 126       if (!ex_klass->is_loader_alive()) {
 127         // We must guarantee that entries are not inserted with new next pointer
 128         // edges to ExceptionCache entries with dead klasses, due to bad interactions
 129         // with concurrent ExceptionCache cleanup. Therefore, the inserts roll
 130         // the head pointer forward to the first live ExceptionCache, so that the new
 131         // next pointers always point at live ExceptionCaches, that are not removed due
 132         // to concurrent ExceptionCache cleanup.
 133         ExceptionCache* next = ec->next();
 134         if (Atomic::cmpxchg(next, &_exception_cache, ec) == ec) {
 135           CodeCache::release_exception_cache(ec);
 136         }
 137         continue;
 138       }
 139       ec = exception_cache();
 140       if (ec != NULL) {
 141         new_entry->set_next(ec);
 142       }
 143     }
 144     if (Atomic::cmpxchg(new_entry, &_exception_cache, ec) == ec) {
 145       return;
 146     }
 147   }
 148 }
 149 
 150 void CompiledMethod::clean_exception_cache() {
 151   // For each nmethod, only a single thread may call this cleanup function
 152   // at the same time, whether called in STW cleanup or concurrent cleanup.
 153   // Note that if the GC is processing exception cache cleaning in a concurrent phase,
 154   // then a single writer may contend with cleaning up the head pointer to the
 155   // first ExceptionCache node that has a Klass* that is alive. That is fine,
 156   // as long as there is no concurrent cleanup of next pointers from concurrent writers.
 157   // And the concurrent writers do not clean up next pointers, only the head.
 158   // Also note that concurent readers will walk through Klass* pointers that are not
 159   // alive. That does not cause ABA problems, because Klass* is deleted after
 160   // a handshake with all threads, after all stale ExceptionCaches have been
 161   // unlinked. That is also when the CodeCache::exception_cache_purge_list()
 162   // is deleted, with all ExceptionCache entries that were cleaned concurrently.
 163   // That similarly implies that CAS operations on ExceptionCache entries do not
 164   // suffer from ABA problems as unlinking and deletion is separated by a global
 165   // handshake operation.
 166   ExceptionCache* prev = NULL;
 167   ExceptionCache* curr = exception_cache_acquire();
 168 
 169   while (curr != NULL) {
 170     ExceptionCache* next = curr->next();
 171 
 172     if (!curr->exception_type()->is_loader_alive()) {
 173       if (prev == NULL) {
 174         // Try to clean head; this is contended by concurrent inserts, that
 175         // both lazily clean the head, and insert entries at the head. If
 176         // the CAS fails, the operation is restarted.
 177         if (Atomic::cmpxchg(next, &_exception_cache, curr) != curr) {
 178           prev = NULL;
 179           curr = exception_cache_acquire();
 180           continue;
 181         }
 182       } else {
 183         // It is impossible to during cleanup connect the next pointer to
 184         // an ExceptionCache that has not been published before a safepoint
 185         // prior to the cleanup. Therefore, release is not required.
 186         prev->set_next(next);
 187       }
 188       // prev stays the same.
 189 
 190       CodeCache::release_exception_cache(curr);
 191     } else {
 192       prev = curr;
 193     }
 194 
 195     curr = next;
 196   }
 197 }
 198 
 199 // public method for accessing the exception cache
 200 // These are the public access methods.
 201 address CompiledMethod::handler_for_exception_and_pc(Handle exception, address pc) {
 202   // We never grab a lock to read the exception cache, so we may
 203   // have false negatives. This is okay, as it can only happen during
 204   // the first few exception lookups for a given nmethod.
 205   ExceptionCache* ec = exception_cache_acquire();
 206   while (ec != NULL) {
 207     address ret_val;
 208     if ((ret_val = ec->match(exception,pc)) != NULL) {
 209       return ret_val;
 210     }
 211     ec = ec->next();
 212   }
 213   return NULL;
 214 }
 215 
 216 void CompiledMethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
 217   // There are potential race conditions during exception cache updates, so we
 218   // must own the ExceptionCache_lock before doing ANY modifications. Because
 219   // we don't lock during reads, it is possible to have several threads attempt
 220   // to update the cache with the same data. We need to check for already inserted
 221   // copies of the current data before adding it.
 222 
 223   MutexLocker ml(ExceptionCache_lock);
 224   ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
 225 
 226   if (target_entry == NULL || !target_entry->add_address_and_handler(pc,handler)) {
 227     target_entry = new ExceptionCache(exception,pc,handler);
 228     add_exception_cache_entry(target_entry);
 229   }
 230 }
 231 
 232 // private method for handling exception cache
 233 // These methods are private, and used to manipulate the exception cache
 234 // directly.
 235 ExceptionCache* CompiledMethod::exception_cache_entry_for_exception(Handle exception) {
 236   ExceptionCache* ec = exception_cache_acquire();
 237   while (ec != NULL) {
 238     if (ec->match_exception_with_space(exception)) {
 239       return ec;
 240     }
 241     ec = ec->next();
 242   }
 243   return NULL;
 244 }
 245 
 246 //-------------end of code for ExceptionCache--------------
 247 
 248 bool CompiledMethod::is_at_poll_return(address pc) {
 249   RelocIterator iter(this, pc, pc+1);
 250   while (iter.next()) {
 251     if (iter.type() == relocInfo::poll_return_type)
 252       return true;
 253   }
 254   return false;
 255 }
 256 
 257 
 258 bool CompiledMethod::is_at_poll_or_poll_return(address pc) {
 259   RelocIterator iter(this, pc, pc+1);
 260   while (iter.next()) {
 261     relocInfo::relocType t = iter.type();
 262     if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
 263       return true;
 264   }
 265   return false;
 266 }
 267 
 268 void CompiledMethod::verify_oop_relocations() {
 269   // Ensure sure that the code matches the current oop values
 270   RelocIterator iter(this, NULL, NULL);
 271   while (iter.next()) {
 272     if (iter.type() == relocInfo::oop_type) {
 273       oop_Relocation* reloc = iter.oop_reloc();
 274       if (!reloc->oop_is_immediate()) {
 275         reloc->verify_oop_relocation();
 276       }
 277     }
 278   }
 279 }
 280 
 281 
 282 ScopeDesc* CompiledMethod::scope_desc_at(address pc) {
 283   PcDesc* pd = pc_desc_at(pc);
 284   guarantee(pd != NULL, "scope must be present");
 285   return new ScopeDesc(this, pd->scope_decode_offset(),
 286                        pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
 287                        pd->return_oop());
 288 }
 289 
 290 ScopeDesc* CompiledMethod::scope_desc_near(address pc) {
 291   PcDesc* pd = pc_desc_near(pc);
 292   guarantee(pd != NULL, "scope must be present");
 293   return new ScopeDesc(this, pd->scope_decode_offset(),
 294                        pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
 295                        pd->return_oop());
 296 }
 297 
 298 address CompiledMethod::oops_reloc_begin() const {
 299   // If the method is not entrant or zombie then a JMP is plastered over the
 300   // first few bytes.  If an oop in the old code was there, that oop
 301   // should not get GC'd.  Skip the first few bytes of oops on
 302   // not-entrant methods.
 303   if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
 304       code_begin() + frame_complete_offset() >
 305       verified_entry_point() + NativeJump::instruction_size)
 306   {
 307     // If we have a frame_complete_offset after the native jump, then there
 308     // is no point trying to look for oops before that. This is a requirement
 309     // for being allowed to scan oops concurrently.
 310     return code_begin() + frame_complete_offset();
 311   }
 312 
 313   // It is not safe to read oops concurrently using entry barriers, if their
 314   // location depend on whether the nmethod is entrant or not.
 315   assert(BarrierSet::barrier_set()->barrier_set_nmethod() == NULL, "Not safe oop scan");
 316 
 317   address low_boundary = verified_entry_point();
 318   if (!is_in_use() && is_nmethod()) {
 319     low_boundary += NativeJump::instruction_size;
 320     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
 321     // This means that the low_boundary is going to be a little too high.
 322     // This shouldn't matter, since oops of non-entrant methods are never used.
 323     // In fact, why are we bothering to look at oops in a non-entrant method??
 324   }
 325   return low_boundary;
 326 }
 327 
 328 int CompiledMethod::verify_icholder_relocations() {
 329   ResourceMark rm;
 330   int count = 0;
 331 
 332   RelocIterator iter(this);
 333   while(iter.next()) {
 334     if (iter.type() == relocInfo::virtual_call_type) {
 335       if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc(), this)) {
 336         CompiledIC *ic = CompiledIC_at(&iter);
 337         if (TraceCompiledIC) {
 338           tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder()));
 339           ic->print();
 340         }
 341         assert(ic->cached_icholder() != NULL, "must be non-NULL");
 342         count++;
 343       }
 344     }
 345   }
 346 
 347   return count;
 348 }
 349 
 350 // Method that knows how to preserve outgoing arguments at call. This method must be
 351 // called with a frame corresponding to a Java invoke
 352 void CompiledMethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
 353   if (method() != NULL && !method()->is_native()) {
 354     address pc = fr.pc();
 355     SimpleScopeDesc ssd(this, pc);
 356     Bytecode_invoke call(ssd.method(), ssd.bci());
 357     bool has_receiver = call.has_receiver();
 358     bool has_appendix = call.has_appendix();
 359     Symbol* signature = call.signature();
 360 
 361     // The method attached by JIT-compilers should be used, if present.
 362     // Bytecode can be inaccurate in such case.
 363     Method* callee = attached_method_before_pc(pc);
 364     if (callee != NULL) {
 365       has_receiver = !(callee->access_flags().is_static());
 366       has_appendix = false;
 367       signature = callee->signature();
 368     }
 369 
 370     fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
 371   }
 372 }
 373 
 374 Method* CompiledMethod::attached_method(address call_instr) {
 375   assert(code_contains(call_instr), "not part of the nmethod");
 376   RelocIterator iter(this, call_instr, call_instr + 1);
 377   while (iter.next()) {
 378     if (iter.addr() == call_instr) {
 379       switch(iter.type()) {
 380         case relocInfo::static_call_type:      return iter.static_call_reloc()->method_value();
 381         case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value();
 382         case relocInfo::virtual_call_type:     return iter.virtual_call_reloc()->method_value();
 383         default:                               break;
 384       }
 385     }
 386   }
 387   return NULL; // not found
 388 }
 389 
 390 Method* CompiledMethod::attached_method_before_pc(address pc) {
 391   if (NativeCall::is_call_before(pc)) {
 392     NativeCall* ncall = nativeCall_before(pc);
 393     return attached_method(ncall->instruction_address());
 394   }
 395   return NULL; // not a call
 396 }
 397 
 398 void CompiledMethod::clear_inline_caches() {
 399   assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint");
 400   if (is_zombie()) {
 401     return;
 402   }
 403 
 404   RelocIterator iter(this);
 405   while (iter.next()) {
 406     iter.reloc()->clear_inline_cache();
 407   }
 408 }
 409 
 410 // Clear IC callsites, releasing ICStubs of all compiled ICs
 411 // as well as any associated CompiledICHolders.
 412 void CompiledMethod::clear_ic_callsites() {
 413   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
 414   ResourceMark rm;
 415   RelocIterator iter(this);
 416   while(iter.next()) {
 417     if (iter.type() == relocInfo::virtual_call_type) {
 418       CompiledIC* ic = CompiledIC_at(&iter);
 419       ic->set_to_clean(false);
 420     }
 421   }
 422 }
 423 
 424 #ifdef ASSERT
 425 // Check class_loader is alive for this bit of metadata.
 426 class CheckClass : public MetadataClosure {
 427   void do_metadata(Metadata* md) {
 428     Klass* klass = NULL;
 429     if (md->is_klass()) {
 430       klass = ((Klass*)md);
 431     } else if (md->is_method()) {
 432       klass = ((Method*)md)->method_holder();
 433     } else if (md->is_methodData()) {
 434       klass = ((MethodData*)md)->method()->method_holder();
 435     } else {
 436       md->print();
 437       ShouldNotReachHere();
 438     }
 439     assert(klass->is_loader_alive(), "must be alive");
 440   }
 441 };
 442 #endif // ASSERT
 443 
 444 
 445 bool CompiledMethod::clean_ic_if_metadata_is_dead(CompiledIC *ic) {
 446   if (ic->is_clean()) {
 447     return true;
 448   }
 449   if (ic->is_icholder_call()) {
 450     // The only exception is compiledICHolder metdata which may
 451     // yet be marked below. (We check this further below).
 452     CompiledICHolder* cichk_metdata = ic->cached_icholder();
 453 
 454     if (cichk_metdata->is_loader_alive()) {
 455       return true;
 456     }
 457   } else {
 458     Metadata* ic_metdata = ic->cached_metadata();
 459     if (ic_metdata != NULL) {
 460       if (ic_metdata->is_klass()) {
 461         if (((Klass*)ic_metdata)->is_loader_alive()) {
 462           return true;
 463         }
 464       } else if (ic_metdata->is_method()) {
 465         Method* method = (Method*)ic_metdata;
 466         assert(!method->is_old(), "old method should have been cleaned");
 467         if (method->method_holder()->is_loader_alive()) {
 468           return true;
 469         }
 470       } else {
 471         ShouldNotReachHere();
 472       }
 473     }
 474   }
 475 
 476   return ic->set_to_clean();
 477 }
 478 
 479 // Clean references to unloaded nmethods at addr from this one, which is not unloaded.
 480 template <class CompiledICorStaticCall>
 481 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, CompiledMethod* from,
 482                                          bool clean_all) {
 483   // Ok, to lookup references to zombies here
 484   CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
 485   CompiledMethod* nm = (cb != NULL) ? cb->as_compiled_method_or_null() : NULL;
 486   if (nm != NULL) {
 487     // Clean inline caches pointing to both zombie and not_entrant methods
 488     if (clean_all || !nm->is_in_use() || nm->is_unloading() || (nm->method()->code() != nm)) {
 489       if (!ic->set_to_clean(from->is_alive())) {
 490         return false;
 491       }
 492       assert(ic->is_clean(), "nmethod " PTR_FORMAT "not clean %s", p2i(from), from->method()->name_and_sig_as_C_string());
 493     }
 494   }
 495   return true;
 496 }
 497 
 498 static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, CompiledMethod* from,
 499                                          bool clean_all) {
 500   return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), from, clean_all);
 501 }
 502 
 503 static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, CompiledMethod* from,
 504                                          bool clean_all) {
 505   return clean_if_nmethod_is_unloaded(csc, csc->destination(), from, clean_all);
 506 }
 507 
 508 // Cleans caches in nmethods that point to either classes that are unloaded
 509 // or nmethods that are unloaded.
 510 //
 511 // Can be called either in parallel by G1 currently or after all
 512 // nmethods are unloaded.  Return postponed=true in the parallel case for
 513 // inline caches found that point to nmethods that are not yet visited during
 514 // the do_unloading walk.
 515 bool CompiledMethod::unload_nmethod_caches(bool unloading_occurred) {
 516   ResourceMark rm;
 517 
 518   // Exception cache only needs to be called if unloading occurred
 519   if (unloading_occurred) {
 520     clean_exception_cache();
 521   }
 522 
 523   if (!cleanup_inline_caches_impl(unloading_occurred, false)) {
 524     return false;
 525   }
 526 
 527 #ifdef ASSERT
 528   // Check that the metadata embedded in the nmethod is alive
 529   CheckClass check_class;
 530   metadata_do(&check_class);
 531 #endif
 532   return true;
 533 }
 534 
 535 void CompiledMethod::cleanup_inline_caches(bool clean_all) {
 536   for (;;) {
 537     ICRefillVerifier ic_refill_verifier;
 538     { CompiledICLocker ic_locker(this);
 539       if (cleanup_inline_caches_impl(false, clean_all)) {
 540         return;
 541       }
 542     }
 543     InlineCacheBuffer::refill_ic_stubs();
 544   }
 545 }
 546 
 547 // Called to clean up after class unloading for live nmethods and from the sweeper
 548 // for all methods.
 549 bool CompiledMethod::cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all) {
 550   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
 551   ResourceMark rm;
 552 
 553   // Find all calls in an nmethod and clear the ones that point to non-entrant,
 554   // zombie and unloaded nmethods.
 555   RelocIterator iter(this, oops_reloc_begin());
 556   bool is_in_static_stub = false;
 557   while(iter.next()) {
 558 
 559     switch (iter.type()) {
 560 
 561     case relocInfo::virtual_call_type:
 562       if (unloading_occurred) {
 563         // If class unloading occurred we first clear ICs where the cached metadata
 564         // is referring to an unloaded klass or method.
 565         if (!clean_ic_if_metadata_is_dead(CompiledIC_at(&iter))) {
 566           return false;
 567         }
 568       }
 569 
 570       if (!clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), this, clean_all)) {
 571         return false;
 572       }
 573       break;
 574 
 575     case relocInfo::opt_virtual_call_type:
 576       if (!clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), this, clean_all)) {
 577         return false;
 578       }
 579       break;
 580 
 581     case relocInfo::static_call_type:
 582       if (!clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), this, clean_all)) {
 583         return false;
 584       }
 585       break;
 586 
 587     case relocInfo::static_stub_type: {
 588       is_in_static_stub = true;
 589       break;
 590     }
 591 
 592     case relocInfo::metadata_type: {
 593       // Only the metadata relocations contained in static/opt virtual call stubs
 594       // contains the Method* passed to c2i adapters. It is the only metadata
 595       // relocation that needs to be walked, as it is the one metadata relocation
 596       // that violates the invariant that all metadata relocations have an oop
 597       // in the compiled method (due to deferred resolution and code patching).
 598 
 599       // This causes dead metadata to remain in compiled methods that are not
 600       // unloading. Unless these slippery metadata relocations of the static
 601       // stubs are at least cleared, subsequent class redefinition operations
 602       // will access potentially free memory, and JavaThread execution
 603       // concurrent to class unloading may call c2i adapters with dead methods.
 604       if (!is_in_static_stub) {
 605         // The first metadata relocation after a static stub relocation is the
 606         // metadata relocation of the static stub used to pass the Method* to
 607         // c2i adapters.
 608         continue;
 609       }
 610       is_in_static_stub = false;
 611       metadata_Relocation* r = iter.metadata_reloc();
 612       Metadata* md = r->metadata_value();
 613       if (md != NULL && md->is_method()) {
 614         Method* method = static_cast<Method*>(md);
 615         if (!method->method_holder()->is_loader_alive()) {
 616           Atomic::store((Method*)NULL, r->metadata_addr());
 617 
 618           if (!r->metadata_is_immediate()) {
 619             r->fix_metadata_relocation();
 620           }
 621         }
 622       }
 623       break;
 624     }
 625 
 626     default:
 627       break;
 628     }
 629   }
 630 
 631   return true;
 632 }
 633 
 634 // Iterating over all nmethods, e.g. with the help of CodeCache::nmethods_do(fun) was found
 635 // to not be inherently safe. There is a chance that fields are seen which are not properly
 636 // initialized. This happens despite the fact that nmethods_do() asserts the CodeCache_lock
 637 // to be held.
 638 // To bundle knowledge about necessary checks in one place, this function was introduced.
 639 // It is not claimed that these checks are sufficient, but they were found to be necessary.
 640 bool CompiledMethod::nmethod_access_is_safe(nmethod* nm) {
 641   Method* method = (nm == NULL) ? NULL : nm->method();  // nm->method() may be uninitialized, i.e. != NULL, but invalid
 642   return (nm != NULL) && (method != NULL) && (method->signature() != NULL) &&
 643          !nm->is_zombie() && !nm->is_not_installed() &&
 644          os::is_readable_pointer(method) &&
 645          os::is_readable_pointer(method->constants()) &&
 646          os::is_readable_pointer(method->signature());
 647 }
 648 
 649 address CompiledMethod::continuation_for_implicit_exception(address pc, bool for_div0_check) {
 650   // Exception happened outside inline-cache check code => we are inside
 651   // an active nmethod => use cpc to determine a return address
 652   int exception_offset = pc - code_begin();
 653   int cont_offset = ImplicitExceptionTable(this).continuation_offset( exception_offset );
 654 #ifdef ASSERT
 655   if (cont_offset == 0) {
 656     Thread* thread = Thread::current();
 657     ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
 658     HandleMark hm(thread);
 659     ResourceMark rm(thread);
 660     CodeBlob* cb = CodeCache::find_blob(pc);
 661     assert(cb != NULL && cb == this, "");
 662     ttyLocker ttyl;
 663     tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
 664     print();
 665     method()->print_codes();
 666     print_code();
 667     print_pcs();
 668   }
 669 #endif
 670   if (cont_offset == 0) {
 671     // Let the normal error handling report the exception
 672     return NULL;
 673   }
 674   if (cont_offset == exception_offset) {
 675 #if INCLUDE_JVMCI
 676     Deoptimization::DeoptReason deopt_reason = for_div0_check ? Deoptimization::Reason_div0_check : Deoptimization::Reason_null_check;
 677     JavaThread *thread = JavaThread::current();
 678     thread->set_jvmci_implicit_exception_pc(pc);
 679     thread->set_pending_deoptimization(Deoptimization::make_trap_request(deopt_reason,
 680                                                                          Deoptimization::Action_reinterpret));
 681     return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap());
 682 #else
 683     ShouldNotReachHere();
 684 #endif
 685   }
 686   return code_begin() + cont_offset;
 687 }
 688 
 689 class HasEvolDependency : public MetadataClosure {
 690   bool _has_evol_dependency;
 691  public:
 692   HasEvolDependency() : _has_evol_dependency(false) {}
 693   void do_metadata(Metadata* md) {
 694     if (md->is_method()) {
 695       Method* method = (Method*)md;
 696       if (method->is_old()) {
 697         _has_evol_dependency = true;
 698       }
 699     }
 700   }
 701   bool has_evol_dependency() const { return _has_evol_dependency; }
 702 };
 703 
 704 bool CompiledMethod::has_evol_metadata() {
 705   // Check the metadata in relocIter and CompiledIC and also deoptimize
 706   // any nmethod that has reference to old methods.
 707   HasEvolDependency check_evol;
 708   metadata_do(&check_evol);
 709   if (check_evol.has_evol_dependency() && log_is_enabled(Debug, redefine, class, nmethod)) {
 710     ResourceMark rm;
 711     log_debug(redefine, class, nmethod)
 712             ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on in nmethod metadata",
 713              _method->method_holder()->external_name(),
 714              _method->name()->as_C_string(),
 715              _method->signature()->as_C_string(),
 716              compile_id());
 717   }
 718   return check_evol.has_evol_dependency();
 719 }
 720 
 721 bool CompiledMethod::is_on_continuation_stack() {
 722   if (_keepalive != NULL) {
 723     WeakHandle<vm_nmethod_keepalive_data> wh = WeakHandle<vm_nmethod_keepalive_data>::from_raw(_keepalive);
 724     return wh.resolve() != NULL;
 725   }
 726   return false;
 727 }