1 /*
   2  * Copyright (c) 1998, 2010, 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 "gc_implementation/shared/markSweep.inline.hpp"
  27 #include "interpreter/interpreter.hpp"
  28 #include "interpreter/rewriter.hpp"
  29 #include "memory/universe.inline.hpp"
  30 #include "oops/cpCacheOop.hpp"
  31 #include "oops/objArrayOop.hpp"
  32 #include "oops/oop.inline.hpp"
  33 #include "prims/jvmtiRedefineClassesTrace.hpp"
  34 #include "runtime/handles.inline.hpp"
  35 
  36 
  37 // Implememtation of ConstantPoolCacheEntry
  38 
  39 void ConstantPoolCacheEntry::initialize_entry(int index) {
  40   assert(0 < index && index < 0x10000, "sanity check");
  41   _indices = index;
  42   assert(constant_pool_index() == index, "");
  43 }
  44 
  45 void ConstantPoolCacheEntry::initialize_secondary_entry(int main_index) {
  46   assert(0 <= main_index && main_index < 0x10000, "sanity check");
  47   _indices = (main_index << 16);
  48   assert(main_entry_index() == main_index, "");
  49 }
  50 
  51 int ConstantPoolCacheEntry::as_flags(TosState state, bool is_final,
  52                     bool is_vfinal, bool is_volatile,
  53                     bool is_method_interface, bool is_method) {
  54   int f = state;
  55 
  56   assert( state < number_of_states, "Invalid state in as_flags");
  57 
  58   f <<= 1;
  59   if (is_final) f |= 1;
  60   f <<= 1;
  61   if (is_vfinal) f |= 1;
  62   f <<= 1;
  63   if (is_volatile) f |= 1;
  64   f <<= 1;
  65   if (is_method_interface) f |= 1;
  66   f <<= 1;
  67   if (is_method) f |= 1;
  68   f <<= ConstantPoolCacheEntry::hotSwapBit;
  69   // Preserve existing flag bit values
  70 #ifdef ASSERT
  71   int old_state = ((_flags >> tosBits) & 0x0F);
  72   assert(old_state == 0 || old_state == state,
  73          "inconsistent cpCache flags state");
  74 #endif
  75   return (_flags | f) ;
  76 }
  77 
  78 void ConstantPoolCacheEntry::set_bytecode_1(Bytecodes::Code code) {
  79 #ifdef ASSERT
  80   // Read once.
  81   volatile Bytecodes::Code c = bytecode_1();
  82   assert(c == 0 || c == code || code == 0, "update must be consistent");
  83 #endif
  84   // Need to flush pending stores here before bytecode is written.
  85   OrderAccess::release_store_ptr(&_indices, _indices | ((u_char)code << 16));
  86 }
  87 
  88 void ConstantPoolCacheEntry::set_bytecode_2(Bytecodes::Code code) {
  89 #ifdef ASSERT
  90   // Read once.
  91   volatile Bytecodes::Code c = bytecode_2();
  92   assert(c == 0 || c == code || code == 0, "update must be consistent");
  93 #endif
  94   // Need to flush pending stores here before bytecode is written.
  95   OrderAccess::release_store_ptr(&_indices, _indices | ((u_char)code << 24));
  96 }
  97 
  98 #ifdef ASSERT
  99 // It is possible to have two different dummy methodOops created
 100 // when the resolve code for invoke interface executes concurrently
 101 // Hence the assertion below is weakened a bit for the invokeinterface
 102 // case.
 103 bool ConstantPoolCacheEntry::same_methodOop(oop cur_f1, oop f1) {
 104   return (cur_f1 == f1 || ((methodOop)cur_f1)->name() ==
 105          ((methodOop)f1)->name() || ((methodOop)cur_f1)->signature() ==
 106          ((methodOop)f1)->signature());
 107 }
 108 #endif
 109 
 110 // Note that concurrent update of both bytecodes can leave one of them
 111 // reset to zero.  This is harmless; the interpreter will simply re-resolve
 112 // the damaged entry.  More seriously, the memory synchronization is needed
 113 // to flush other fields (f1, f2) completely to memory before the bytecodes
 114 // are updated, lest other processors see a non-zero bytecode but zero f1/f2.
 115 void ConstantPoolCacheEntry::set_field(Bytecodes::Code get_code,
 116                                        Bytecodes::Code put_code,
 117                                        KlassHandle field_holder,
 118                                        int orig_field_index,
 119                                        int field_offset,
 120                                        TosState field_type,
 121                                        bool is_final,
 122                                        bool is_volatile) {
 123   set_f1(field_holder());
 124   set_f2(field_offset);
 125   // The field index is used by jvm/ti and is the index into fields() array
 126   // in holder instanceKlass.  This is scaled by instanceKlass::next_offset.
 127   assert((orig_field_index % instanceKlass::next_offset) == 0, "wierd index");
 128   const int field_index = orig_field_index / instanceKlass::next_offset;
 129   assert(field_index <= field_index_mask,
 130          "field index does not fit in low flag bits");
 131   set_flags(as_flags(field_type, is_final, false, is_volatile, false, false) |
 132             (field_index & field_index_mask));
 133   set_bytecode_1(get_code);
 134   set_bytecode_2(put_code);
 135   NOT_PRODUCT(verify(tty));
 136 }
 137 
 138 int  ConstantPoolCacheEntry::field_index() const {
 139   return (_flags & field_index_mask) * instanceKlass::next_offset;
 140 }
 141 
 142 void ConstantPoolCacheEntry::set_method(Bytecodes::Code invoke_code,
 143                                         methodHandle method,
 144                                         int vtable_index) {
 145   assert(!is_secondary_entry(), "");
 146   assert(method->interpreter_entry() != NULL, "should have been set at this point");
 147   assert(!method->is_obsolete(),  "attempt to write obsolete method to cpCache");
 148   bool change_to_virtual = (invoke_code == Bytecodes::_invokeinterface);
 149 
 150   int byte_no = -1;
 151   bool needs_vfinal_flag = false;
 152   switch (invoke_code) {
 153     case Bytecodes::_invokevirtual:
 154     case Bytecodes::_invokeinterface: {
 155         if (method->can_be_statically_bound()) {
 156           set_f2((intptr_t)method());
 157           needs_vfinal_flag = true;
 158         } else {
 159           assert(vtable_index >= 0, "valid index");
 160           set_f2(vtable_index);
 161         }
 162         byte_no = 2;
 163         break;
 164     }
 165 
 166     case Bytecodes::_invokedynamic:  // similar to _invokevirtual
 167       if (TraceInvokeDynamic) {
 168         tty->print_cr("InvokeDynamic set_method%s method="PTR_FORMAT" index=%d",
 169                       (is_secondary_entry() ? " secondary" : ""),
 170                       (intptr_t)method(), vtable_index);
 171         method->print();
 172         this->print(tty, 0);
 173       }
 174       assert(method->can_be_statically_bound(), "must be a MH invoker method");
 175       assert(AllowTransitionalJSR292 || _f2 >= constantPoolOopDesc::CPCACHE_INDEX_TAG, "BSM index initialized");
 176       set_f1(method());
 177       needs_vfinal_flag = false;  // _f2 is not an oop
 178       assert(!is_vfinal(), "f2 not an oop");
 179       byte_no = 1;  // coordinate this with bytecode_number & is_resolved
 180       break;
 181 
 182     case Bytecodes::_invokespecial:
 183       // Preserve the value of the vfinal flag on invokevirtual bytecode
 184       // which may be shared with this constant pool cache entry.
 185       needs_vfinal_flag = is_resolved(Bytecodes::_invokevirtual) && is_vfinal();
 186       // fall through
 187     case Bytecodes::_invokestatic:
 188       set_f1(method());
 189       byte_no = 1;
 190       break;
 191     default:
 192       ShouldNotReachHere();
 193       break;
 194   }
 195 
 196   set_flags(as_flags(as_TosState(method->result_type()),
 197                      method->is_final_method(),
 198                      needs_vfinal_flag,
 199                      false,
 200                      change_to_virtual,
 201                      true)|
 202             method()->size_of_parameters());
 203 
 204   // Note:  byte_no also appears in TemplateTable::resolve.
 205   if (byte_no == 1) {
 206     set_bytecode_1(invoke_code);
 207   } else if (byte_no == 2)  {
 208     if (change_to_virtual) {
 209       // NOTE: THIS IS A HACK - BE VERY CAREFUL!!!
 210       //
 211       // Workaround for the case where we encounter an invokeinterface, but we
 212       // should really have an _invokevirtual since the resolved method is a
 213       // virtual method in java.lang.Object. This is a corner case in the spec
 214       // but is presumably legal. javac does not generate this code.
 215       //
 216       // We set bytecode_1() to _invokeinterface, because that is the
 217       // bytecode # used by the interpreter to see if it is resolved.
 218       // We set bytecode_2() to _invokevirtual.
 219       // See also interpreterRuntime.cpp. (8/25/2000)
 220       // Only set resolved for the invokeinterface case if method is public.
 221       // Otherwise, the method needs to be reresolved with caller for each
 222       // interface call.
 223       if (method->is_public()) set_bytecode_1(invoke_code);
 224       set_bytecode_2(Bytecodes::_invokevirtual);
 225     } else {
 226       set_bytecode_2(invoke_code);
 227     }
 228   } else {
 229     ShouldNotReachHere();
 230   }
 231   NOT_PRODUCT(verify(tty));
 232 }
 233 
 234 
 235 void ConstantPoolCacheEntry::set_interface_call(methodHandle method, int index) {
 236   assert(!is_secondary_entry(), "");
 237   klassOop interf = method->method_holder();
 238   assert(instanceKlass::cast(interf)->is_interface(), "must be an interface");
 239   set_f1(interf);
 240   set_f2(index);
 241   set_flags(as_flags(as_TosState(method->result_type()), method->is_final_method(), false, false, false, true) | method()->size_of_parameters());
 242   set_bytecode_1(Bytecodes::_invokeinterface);
 243 }
 244 
 245 
 246 void ConstantPoolCacheEntry::initialize_bootstrap_method_index_in_cache(int bsm_cache_index) {
 247   assert(!is_secondary_entry(), "only for JVM_CONSTANT_InvokeDynamic main entry");
 248   assert(_f2 == 0, "initialize once");
 249   assert(bsm_cache_index == (int)(u2)bsm_cache_index, "oob");
 250   set_f2(bsm_cache_index + constantPoolOopDesc::CPCACHE_INDEX_TAG);
 251 }
 252 
 253 int ConstantPoolCacheEntry::bootstrap_method_index_in_cache() {
 254   assert(!is_secondary_entry(), "only for JVM_CONSTANT_InvokeDynamic main entry");
 255   intptr_t bsm_cache_index = (intptr_t) _f2 - constantPoolOopDesc::CPCACHE_INDEX_TAG;
 256   assert(bsm_cache_index == (intptr_t)(u2)bsm_cache_index, "oob");
 257   return (int) bsm_cache_index;
 258 }
 259 
 260 void ConstantPoolCacheEntry::set_dynamic_call(Handle call_site,
 261                                               methodHandle signature_invoker) {
 262   assert(is_secondary_entry(), "");
 263   int param_size = signature_invoker->size_of_parameters();
 264   assert(param_size >= 1, "method argument size must include MH.this");
 265   param_size -= 1;              // do not count MH.this; it is not stacked for invokedynamic
 266   if (Atomic::cmpxchg_ptr(call_site(), &_f1, NULL) == NULL) {
 267     // racing threads might be trying to install their own favorites
 268     set_f1(call_site());
 269   }
 270   bool is_final = true;
 271   assert(signature_invoker->is_final_method(), "is_final");
 272   set_flags(as_flags(as_TosState(signature_invoker->result_type()), is_final, false, false, false, true) | param_size);
 273   // do not do set_bytecode on a secondary CP cache entry
 274   //set_bytecode_1(Bytecodes::_invokedynamic);
 275 }
 276 
 277 
 278 class LocalOopClosure: public OopClosure {
 279  private:
 280   void (*_f)(oop*);
 281 
 282  public:
 283   LocalOopClosure(void f(oop*))        { _f = f; }
 284   virtual void do_oop(oop* o)          { _f(o); }
 285   virtual void do_oop(narrowOop *o)    { ShouldNotReachHere(); }
 286 };
 287 
 288 
 289 void ConstantPoolCacheEntry::oops_do(void f(oop*)) {
 290   LocalOopClosure blk(f);
 291   oop_iterate(&blk);
 292 }
 293 
 294 
 295 void ConstantPoolCacheEntry::oop_iterate(OopClosure* blk) {
 296   assert(in_words(size()) == 4, "check code below - may need adjustment");
 297   // field[1] is always oop or NULL
 298   blk->do_oop((oop*)&_f1);
 299   if (is_vfinal()) {
 300     blk->do_oop((oop*)&_f2);
 301   }
 302 }
 303 
 304 
 305 void ConstantPoolCacheEntry::oop_iterate_m(OopClosure* blk, MemRegion mr) {
 306   assert(in_words(size()) == 4, "check code below - may need adjustment");
 307   // field[1] is always oop or NULL
 308   if (mr.contains((oop *)&_f1)) blk->do_oop((oop*)&_f1);
 309   if (is_vfinal()) {
 310     if (mr.contains((oop *)&_f2)) blk->do_oop((oop*)&_f2);
 311   }
 312 }
 313 
 314 
 315 void ConstantPoolCacheEntry::follow_contents() {
 316   assert(in_words(size()) == 4, "check code below - may need adjustment");
 317   // field[1] is always oop or NULL
 318   MarkSweep::mark_and_push((oop*)&_f1);
 319   if (is_vfinal()) {
 320     MarkSweep::mark_and_push((oop*)&_f2);
 321   }
 322 }
 323 
 324 #ifndef SERIALGC
 325 void ConstantPoolCacheEntry::follow_contents(ParCompactionManager* cm) {
 326   assert(in_words(size()) == 4, "check code below - may need adjustment");
 327   // field[1] is always oop or NULL
 328   PSParallelCompact::mark_and_push(cm, (oop*)&_f1);
 329   if (is_vfinal()) {
 330     PSParallelCompact::mark_and_push(cm, (oop*)&_f2);
 331   }
 332 }
 333 #endif // SERIALGC
 334 
 335 void ConstantPoolCacheEntry::adjust_pointers() {
 336   assert(in_words(size()) == 4, "check code below - may need adjustment");
 337   // field[1] is always oop or NULL
 338   MarkSweep::adjust_pointer((oop*)&_f1);
 339   if (is_vfinal()) {
 340     MarkSweep::adjust_pointer((oop*)&_f2);
 341   }
 342 }
 343 
 344 #ifndef SERIALGC
 345 void ConstantPoolCacheEntry::update_pointers() {
 346   assert(in_words(size()) == 4, "check code below - may need adjustment");
 347   // field[1] is always oop or NULL
 348   PSParallelCompact::adjust_pointer((oop*)&_f1);
 349   if (is_vfinal()) {
 350     PSParallelCompact::adjust_pointer((oop*)&_f2);
 351   }
 352 }
 353 
 354 void ConstantPoolCacheEntry::update_pointers(HeapWord* beg_addr,
 355                                              HeapWord* end_addr) {
 356   assert(in_words(size()) == 4, "check code below - may need adjustment");
 357   // field[1] is always oop or NULL
 358   PSParallelCompact::adjust_pointer((oop*)&_f1, beg_addr, end_addr);
 359   if (is_vfinal()) {
 360     PSParallelCompact::adjust_pointer((oop*)&_f2, beg_addr, end_addr);
 361   }
 362 }
 363 #endif // SERIALGC
 364 
 365 // RedefineClasses() API support:
 366 // If this constantPoolCacheEntry refers to old_method then update it
 367 // to refer to new_method.
 368 bool ConstantPoolCacheEntry::adjust_method_entry(methodOop old_method,
 369        methodOop new_method, bool * trace_name_printed) {
 370 
 371   if (is_vfinal()) {
 372     // virtual and final so f2() contains method ptr instead of vtable index
 373     if (f2() == (intptr_t)old_method) {
 374       // match old_method so need an update
 375       _f2 = (intptr_t)new_method;
 376       if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
 377         if (!(*trace_name_printed)) {
 378           // RC_TRACE_MESG macro has an embedded ResourceMark
 379           RC_TRACE_MESG(("adjust: name=%s",
 380             Klass::cast(old_method->method_holder())->external_name()));
 381           *trace_name_printed = true;
 382         }
 383         // RC_TRACE macro has an embedded ResourceMark
 384         RC_TRACE(0x00400000, ("cpc vf-entry update: %s(%s)",
 385           new_method->name()->as_C_string(),
 386           new_method->signature()->as_C_string()));
 387       }
 388 
 389       return true;
 390     }
 391 
 392     // f1() is not used with virtual entries so bail out
 393     return false;
 394   }
 395 
 396   if ((oop)_f1 == NULL) {
 397     // NULL f1() means this is a virtual entry so bail out
 398     // We are assuming that the vtable index does not need change.
 399     return false;
 400   }
 401 
 402   if ((oop)_f1 == old_method) {
 403     _f1 = new_method;
 404     if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
 405       if (!(*trace_name_printed)) {
 406         // RC_TRACE_MESG macro has an embedded ResourceMark
 407         RC_TRACE_MESG(("adjust: name=%s",
 408           Klass::cast(old_method->method_holder())->external_name()));
 409         *trace_name_printed = true;
 410       }
 411       // RC_TRACE macro has an embedded ResourceMark
 412       RC_TRACE(0x00400000, ("cpc entry update: %s(%s)",
 413         new_method->name()->as_C_string(),
 414         new_method->signature()->as_C_string()));
 415     }
 416 
 417     return true;
 418   }
 419 
 420   return false;
 421 }
 422 
 423 bool ConstantPoolCacheEntry::is_interesting_method_entry(klassOop k) {
 424   if (!is_method_entry()) {
 425     // not a method entry so not interesting by default
 426     return false;
 427   }
 428 
 429   methodOop m = NULL;
 430   if (is_vfinal()) {
 431     // virtual and final so _f2 contains method ptr instead of vtable index
 432     m = (methodOop)_f2;
 433   } else if ((oop)_f1 == NULL) {
 434     // NULL _f1 means this is a virtual entry so also not interesting
 435     return false;
 436   } else {
 437     if (!((oop)_f1)->is_method()) {
 438       // _f1 can also contain a klassOop for an interface
 439       return false;
 440     }
 441     m = (methodOop)_f1;
 442   }
 443 
 444   assert(m != NULL && m->is_method(), "sanity check");
 445   if (m == NULL || !m->is_method() || m->method_holder() != k) {
 446     // robustness for above sanity checks or method is not in
 447     // the interesting class
 448     return false;
 449   }
 450 
 451   // the method is in the interesting class so the entry is interesting
 452   return true;
 453 }
 454 
 455 void ConstantPoolCacheEntry::print(outputStream* st, int index) const {
 456   // print separator
 457   if (index == 0) tty->print_cr("                 -------------");
 458   // print entry
 459   tty->print("%3d  ("PTR_FORMAT")  ", index, (intptr_t)this);
 460   if (is_secondary_entry())
 461     tty->print_cr("[%5d|secondary]", main_entry_index());
 462   else
 463     tty->print_cr("[%02x|%02x|%5d]", bytecode_2(), bytecode_1(), constant_pool_index());
 464   tty->print_cr("                 [   "PTR_FORMAT"]", (intptr_t)(oop)_f1);
 465   tty->print_cr("                 [   "PTR_FORMAT"]", (intptr_t)_f2);
 466   tty->print_cr("                 [   "PTR_FORMAT"]", (intptr_t)_flags);
 467   tty->print_cr("                 -------------");
 468 }
 469 
 470 void ConstantPoolCacheEntry::verify(outputStream* st) const {
 471   // not implemented yet
 472 }
 473 
 474 // Implementation of ConstantPoolCache
 475 
 476 void constantPoolCacheOopDesc::initialize(intArray& inverse_index_map) {
 477   assert(inverse_index_map.length() == length(), "inverse index map must have same length as cache");
 478   for (int i = 0; i < length(); i++) {
 479     ConstantPoolCacheEntry* e = entry_at(i);
 480     int original_index = inverse_index_map[i];
 481     if ((original_index & Rewriter::_secondary_entry_tag) != 0) {
 482       int main_index = (original_index - Rewriter::_secondary_entry_tag);
 483       assert(!entry_at(main_index)->is_secondary_entry(), "valid main index");
 484       e->initialize_secondary_entry(main_index);
 485     } else {
 486       e->initialize_entry(original_index);
 487     }
 488     assert(entry_at(i) == e, "sanity");
 489   }
 490 }
 491 
 492 // RedefineClasses() API support:
 493 // If any entry of this constantPoolCache points to any of
 494 // old_methods, replace it with the corresponding new_method.
 495 void constantPoolCacheOopDesc::adjust_method_entries(methodOop* old_methods, methodOop* new_methods,
 496                                                      int methods_length, bool * trace_name_printed) {
 497 
 498   if (methods_length == 0) {
 499     // nothing to do if there are no methods
 500     return;
 501   }
 502 
 503   // get shorthand for the interesting class
 504   klassOop old_holder = old_methods[0]->method_holder();
 505 
 506   for (int i = 0; i < length(); i++) {
 507     if (!entry_at(i)->is_interesting_method_entry(old_holder)) {
 508       // skip uninteresting methods
 509       continue;
 510     }
 511 
 512     // The constantPoolCache contains entries for several different
 513     // things, but we only care about methods. In fact, we only care
 514     // about methods in the same class as the one that contains the
 515     // old_methods. At this point, we have an interesting entry.
 516 
 517     for (int j = 0; j < methods_length; j++) {
 518       methodOop old_method = old_methods[j];
 519       methodOop new_method = new_methods[j];
 520 
 521       if (entry_at(i)->adjust_method_entry(old_method, new_method,
 522           trace_name_printed)) {
 523         // current old_method matched this entry and we updated it so
 524         // break out and get to the next interesting entry if there one
 525         break;
 526       }
 527     }
 528   }
 529 }