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 "aot/compiledIC_aot.hpp"
  29 #include "code/codeCache.hpp"
  30 #include "code/compiledIC.hpp"
  31 #include "code/nativeInst.hpp"
  32 #include "compiler/compilerOracle.hpp"
  33 #include "gc/shared/cardTableBarrierSet.hpp"
  34 #include "gc/shared/collectedHeap.hpp"
  35 #include "jvmci/compilerRuntime.hpp"
  36 #include "jvmci/jvmciRuntime.hpp"
  37 #include "oops/method.inline.hpp"
  38 #include "runtime/frame.inline.hpp"
  39 #include "runtime/handles.inline.hpp"
  40 #include "runtime/java.hpp"
  41 #include "runtime/os.hpp"
  42 #include "runtime/safepointVerifiers.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 #include "utilities/xmlstream.hpp"
  45 
  46 #include <stdio.h>
  47 
  48 #if 0
  49 static void metadata_oops_do(Metadata** metadata_begin, Metadata **metadata_end, OopClosure* f) {
  50   // Visit the metadata/oops section
  51   for (Metadata** p = metadata_begin; p < metadata_end; p++) {
  52     Metadata* m = *p;
  53 
  54     intptr_t meta = (intptr_t)m;
  55     if ((meta & 1) == 1) {
  56       // already resolved
  57       m = (Metadata*)(meta & ~1);
  58     } else {
  59       continue;
  60     }
  61     assert(Metaspace::contains(m), "");
  62     if (m->is_method()) {
  63       m = ((Method*)m)->method_holder();
  64     }
  65     assert(m->is_klass(), "must be");
  66     oop o = ((Klass*)m)->klass_holder();
  67     if (o != NULL) {
  68       f->do_oop(&o);
  69     }
  70   }
  71 }
  72 #endif
  73 
  74 address* AOTCompiledMethod::orig_pc_addr(const frame* fr) {
  75   return (address*) ((address)fr->unextended_sp() + _meta->orig_pc_offset());
  76 }
  77 
  78 bool AOTCompiledMethod::do_unloading_oops(address low_boundary, BoolObjectClosure* is_alive) {
  79   return false;
  80 }
  81 
  82 oop AOTCompiledMethod::oop_at(int index) const {
  83   if (index == 0) { // 0 is reserved
  84     return NULL;
  85   }
  86   Metadata** entry = _metadata_got + (index - 1);
  87   intptr_t meta = (intptr_t)*entry;
  88   if ((meta & 1) == 1) {
  89     // already resolved
  90     Klass* k = (Klass*)(meta & ~1);
  91     return k->java_mirror();
  92   }
  93   // The entry is string which we need to resolve.
  94   const char* meta_name = _heap->get_name_at((int)meta);
  95   int klass_len = build_u2_from((address)meta_name);
  96   const char* klass_name = meta_name + 2;
  97   // Quick check the current method's holder.
  98   Klass* k = _method->method_holder();
  99 
 100   ResourceMark rm; // for signature_name()
 101   if (strncmp(k->signature_name(), klass_name, klass_len) != 0) { // Does not match?
 102     // Search klass in got cells in DSO which have this compiled method.
 103     k = _heap->get_klass_from_got(klass_name, klass_len, _method);
 104   }
 105   int method_name_len = build_u2_from((address)klass_name + klass_len);
 106   guarantee(method_name_len == 0, "only klass is expected here");
 107   meta = ((intptr_t)k) | 1;
 108   *entry = (Metadata*)meta; // Should be atomic on x64
 109   return k->java_mirror();
 110 }
 111 
 112 Metadata* AOTCompiledMethod::metadata_at(int index) const {
 113   if (index == 0) { // 0 is reserved
 114     return NULL;
 115   }
 116   assert(index - 1 < _metadata_size, "");
 117   {
 118     Metadata** entry = _metadata_got + (index - 1);
 119     intptr_t meta = (intptr_t)*entry;
 120     if ((meta & 1) == 1) {
 121       // already resolved
 122       Metadata *m = (Metadata*)(meta & ~1);
 123       return m;
 124     }
 125     // The entry is string which we need to resolve.
 126     const char* meta_name = _heap->get_name_at((int)meta);
 127     int klass_len = build_u2_from((address)meta_name);
 128     const char* klass_name = meta_name + 2;
 129     // Quick check the current method's holder.
 130     Klass* k = _method->method_holder();
 131     bool klass_matched = true;
 132 
 133     ResourceMark rm; // for signature_name() and find_method()
 134     if (strncmp(k->signature_name(), klass_name, klass_len) != 0) { // Does not match?
 135       // Search klass in got cells in DSO which have this compiled method.
 136       k = _heap->get_klass_from_got(klass_name, klass_len, _method);
 137       klass_matched = false;
 138     }
 139     int method_name_len = build_u2_from((address)klass_name + klass_len);
 140     if (method_name_len == 0) { // Array or Klass name only?
 141       meta = ((intptr_t)k) | 1;
 142       *entry = (Metadata*)meta; // Should be atomic on x64
 143       return (Metadata*)k;
 144     } else { // Method
 145       // Quick check the current method's name.
 146       Method* m = _method;
 147       int signature_len = build_u2_from((address)klass_name + klass_len + 2 + method_name_len);
 148       int full_len = 2 + klass_len + 2 + method_name_len + 2 + signature_len;
 149       if (!klass_matched || memcmp(_name, meta_name, full_len) != 0) { // Does not match?
 150         Thread* thread = Thread::current();
 151         const char* method_name = klass_name + klass_len;
 152         m = AOTCodeHeap::find_method(k, thread, method_name);
 153       }
 154       meta = ((intptr_t)m) | 1;
 155       *entry = (Metadata*)meta; // Should be atomic on x64
 156       return (Metadata*)m;
 157     }
 158   }
 159   ShouldNotReachHere(); return NULL;
 160 }
 161 
 162 bool AOTCompiledMethod::make_not_entrant_helper(int new_state) {
 163   // Make sure the method is not flushed in case of a safepoint in code below.
 164   methodHandle the_method(method());
 165   NoSafepointVerifier nsv;
 166 
 167   {
 168     // Enter critical section.  Does not block for safepoint.
 169     MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
 170 
 171     if (*_state_adr == new_state) {
 172       // another thread already performed this transition so nothing
 173       // to do, but return false to indicate this.
 174       return false;
 175     }
 176 
 177     // Change state
 178     OrderAccess::storestore();
 179     *_state_adr = new_state;
 180 
 181     // Log the transition once
 182     log_state_change();
 183 
 184 #ifdef TIERED
 185     // Remain non-entrant forever
 186     if (new_state == not_entrant && method() != NULL) {
 187         method()->set_aot_code(NULL);
 188     }
 189 #endif
 190 
 191     // Remove AOTCompiledMethod from method.
 192     if (method() != NULL && (method()->code() == this ||
 193                              method()->from_compiled_entry() == verified_entry_point())) {
 194       HandleMark hm;
 195       method()->clear_code(false /* already owns Patching_lock */);
 196     }
 197   } // leave critical region under Patching_lock
 198 
 199 
 200   if (TraceCreateZombies) {
 201     ResourceMark m;
 202     const char *new_state_str = (new_state == not_entrant) ? "not entrant" : "not used";
 203     tty->print_cr("aot method <" INTPTR_FORMAT "> %s code made %s", p2i(this), this->method() ? this->method()->name_and_sig_as_C_string() : "null", new_state_str);
 204   }
 205 
 206   return true;
 207 }
 208 
 209 bool AOTCompiledMethod::make_entrant() {
 210   assert(!method()->is_old(), "reviving evolved method!");
 211   assert(*_state_adr != not_entrant, "%s", method()->has_aot_code() ? "has_aot_code() not cleared" : "caller didn't check has_aot_code()");
 212 
 213   // Make sure the method is not flushed in case of a safepoint in code below.
 214   methodHandle the_method(method());
 215   NoSafepointVerifier nsv;
 216 
 217   {
 218     // Enter critical section.  Does not block for safepoint.
 219     MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
 220 
 221     if (*_state_adr == in_use) {
 222       // another thread already performed this transition so nothing
 223       // to do, but return false to indicate this.
 224       return false;
 225     }
 226 
 227     // Change state
 228     OrderAccess::storestore();
 229     *_state_adr = in_use;
 230 
 231     // Log the transition once
 232     log_state_change();
 233   } // leave critical region under Patching_lock
 234 
 235 
 236   if (TraceCreateZombies) {
 237     ResourceMark m;
 238     tty->print_cr("aot method <" INTPTR_FORMAT "> %s code made entrant", p2i(this), this->method() ? this->method()->name_and_sig_as_C_string() : "null");
 239   }
 240 
 241   return true;
 242 }
 243 
 244 // We don't have full dependencies for AOT methods, so flushing is
 245 // more conservative than for nmethods.
 246 void AOTCompiledMethod::flush_evol_dependents_on(InstanceKlass* dependee) {
 247   if (is_java_method()) {
 248     clear_inline_caches();
 249     mark_for_deoptimization();
 250     make_not_entrant();
 251   }
 252 }
 253 
 254 // Iterate over metadata calling this function.   Used by RedefineClasses
 255 // Copied from nmethod::metadata_do
 256 void AOTCompiledMethod::metadata_do(void f(Metadata*)) {
 257   address low_boundary = verified_entry_point();
 258   {
 259     // Visit all immediate references that are embedded in the instruction stream.
 260     RelocIterator iter(this, low_boundary);
 261     while (iter.next()) {
 262       if (iter.type() == relocInfo::metadata_type ) {
 263         metadata_Relocation* r = iter.metadata_reloc();
 264         // In this metadata, we must only follow those metadatas directly embedded in
 265         // the code.  Other metadatas (oop_index>0) are seen as part of
 266         // the metadata section below.
 267         assert(1 == (r->metadata_is_immediate()) +
 268                (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
 269                "metadata must be found in exactly one place");
 270         if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
 271           Metadata* md = r->metadata_value();
 272           if (md != _method) f(md);
 273         }
 274       } else if (iter.type() == relocInfo::virtual_call_type) {
 275         ResourceMark rm;
 276         // Check compiledIC holders associated with this nmethod
 277         CompiledIC *ic = CompiledIC_at(&iter);
 278         if (ic->is_icholder_call()) {
 279           CompiledICHolder* cichk = ic->cached_icholder();
 280           f(cichk->holder_metadata());
 281           f(cichk->holder_klass());
 282         } else {
 283           // Get Klass* or NULL (if value is -1) from GOT cell of virtual call PLT stub.
 284           Metadata* ic_oop = ic->cached_metadata();
 285           if (ic_oop != NULL) {
 286             f(ic_oop);
 287           }
 288         }
 289       } else if (iter.type() == relocInfo::static_call_type ||
 290                  iter.type() == relocInfo::opt_virtual_call_type){
 291         // Check Method* in AOT c2i stub for other calls.
 292         Metadata* meta = (Metadata*)nativeLoadGot_at(nativePltCall_at(iter.addr())->plt_c2i_stub())->data();
 293         if (meta != NULL) {
 294           f(meta);
 295         }
 296       }
 297     }
 298   }
 299 
 300   // Visit the metadata section
 301   for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
 302     Metadata* m = *p;
 303 
 304     intptr_t meta = (intptr_t)m;
 305     if ((meta & 1) == 1) {
 306       // already resolved
 307       m = (Metadata*)(meta & ~1);
 308     } else {
 309       continue;
 310     }
 311     assert(Metaspace::contains(m), "");
 312     f(m);
 313   }
 314 
 315   // Visit metadata not embedded in the other places.
 316   if (_method != NULL) f(_method);
 317 }
 318 
 319 void AOTCompiledMethod::print() const {
 320   print_on(tty, "AOTCompiledMethod");
 321 }
 322 
 323 void AOTCompiledMethod::print_on(outputStream* st) const {
 324   print_on(st, "AOTCompiledMethod");
 325 }
 326 
 327 // Print out more verbose output usually for a newly created aot method.
 328 void AOTCompiledMethod::print_on(outputStream* st, const char* msg) const {
 329   if (st != NULL) {
 330     ttyLocker ttyl;
 331     st->print("%7d ", (int) st->time_stamp().milliseconds());
 332     st->print("%4d ", _aot_id);    // print compilation number
 333     st->print("    aot[%2d]", _heap->dso_id());
 334     // Stubs have _method == NULL
 335     if (_method == NULL) {
 336       st->print("   %s", _name);
 337     } else {
 338       ResourceMark m;
 339       st->print("   %s", _method->name_and_sig_as_C_string());
 340     }
 341     if (Verbose) {
 342       st->print(" entry at " INTPTR_FORMAT, p2i(_code));
 343     }
 344     if (msg != NULL) {
 345       st->print("   %s", msg);
 346     }
 347     st->cr();
 348   }
 349 }
 350 
 351 void AOTCompiledMethod::print_value_on(outputStream* st) const {
 352   st->print("AOTCompiledMethod ");
 353   print_on(st, NULL);
 354 }
 355 
 356 // Print a short set of xml attributes to identify this aot method.  The
 357 // output should be embedded in some other element.
 358 void AOTCompiledMethod::log_identity(xmlStream* log) const {
 359   log->print(" aot_id='%d'", _aot_id);
 360   log->print(" aot='%2d'", _heap->dso_id());
 361 }
 362 
 363 void AOTCompiledMethod::log_state_change() const {
 364   if (LogCompilation) {
 365     ResourceMark m;
 366     if (xtty != NULL) {
 367       ttyLocker ttyl;  // keep the following output all in one block
 368       if (*_state_adr == not_entrant) {
 369         xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'",
 370                          os::current_thread_id());
 371       } else if (*_state_adr == not_used) {
 372         xtty->begin_elem("make_not_used thread='" UINTX_FORMAT "'",
 373                          os::current_thread_id());
 374       } else if (*_state_adr == in_use) {
 375         xtty->begin_elem("make_entrant thread='" UINTX_FORMAT "'",
 376                          os::current_thread_id());
 377       }
 378       log_identity(xtty);
 379       xtty->stamp();
 380       xtty->end_elem();
 381     }
 382   }
 383   if (PrintCompilation) {
 384     ResourceMark m;
 385     if (*_state_adr == not_entrant) {
 386       print_on(tty, "made not entrant");
 387     } else if (*_state_adr == not_used) {
 388       print_on(tty, "made not used");
 389     } else if (*_state_adr == in_use) {
 390       print_on(tty, "made entrant");
 391     }
 392   }
 393 }
 394 
 395 
 396 NativeInstruction* PltNativeCallWrapper::get_load_instruction(virtual_call_Relocation* r) const {
 397   return nativeLoadGot_at(_call->plt_load_got());
 398 }
 399 
 400 void PltNativeCallWrapper::verify_resolve_call(address dest) const {
 401   CodeBlob* db = CodeCache::find_blob_unsafe(dest);
 402   if (db == NULL) {
 403     assert(dest == _call->plt_resolve_call(), "sanity");
 404   }
 405 }
 406 
 407 void PltNativeCallWrapper::set_to_interpreted(const methodHandle& method, CompiledICInfo& info) {
 408   assert(!info.to_aot(), "only for nmethod");
 409   CompiledPltStaticCall* csc = CompiledPltStaticCall::at(instruction_address());
 410   csc->set_to_interpreted(method, info.entry());
 411 }
 412 
 413 NativeCallWrapper* AOTCompiledMethod::call_wrapper_at(address call) const {
 414   return new PltNativeCallWrapper((NativePltCall*) call);
 415 }
 416 
 417 NativeCallWrapper* AOTCompiledMethod::call_wrapper_before(address return_pc) const {
 418   return new PltNativeCallWrapper(nativePltCall_before(return_pc));
 419 }
 420 
 421 CompiledStaticCall* AOTCompiledMethod::compiledStaticCall_at(Relocation* call_site) const {
 422   return CompiledPltStaticCall::at(call_site);
 423 }
 424 
 425 CompiledStaticCall* AOTCompiledMethod::compiledStaticCall_at(address call_site) const {
 426   return CompiledPltStaticCall::at(call_site);
 427 }
 428 
 429 CompiledStaticCall* AOTCompiledMethod::compiledStaticCall_before(address return_addr) const {
 430   return CompiledPltStaticCall::before(return_addr);
 431 }
 432 
 433 address AOTCompiledMethod::call_instruction_address(address pc) const {
 434   NativePltCall* pltcall = nativePltCall_before(pc);
 435   return pltcall->instruction_address();
 436 }
 437 
 438 bool AOTCompiledMethod::is_evol_dependent_on(Klass* dependee) {
 439   return !is_aot_runtime_stub() && _heap->is_dependent_method(dependee, this);
 440 }
 441 
 442 void AOTCompiledMethod::clear_inline_caches() {
 443   assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint");
 444   if (is_zombie()) {
 445     return;
 446   }
 447 
 448   ResourceMark rm;
 449   RelocIterator iter(this);
 450   while (iter.next()) {
 451     iter.reloc()->clear_inline_cache();
 452     if (iter.type() == relocInfo::opt_virtual_call_type) {
 453       CompiledIC* cic = CompiledIC_at(&iter);
 454       assert(cic->is_clean(), "!");
 455       nativePltCall_at(iter.addr())->set_stub_to_clean();
 456     }
 457   }
 458 }