1 /*
   2  * Copyright (c) 1997, 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 "code/compiledIC.hpp"
  27 #include "code/nmethod.hpp"
  28 #include "code/relocInfo.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "runtime/stubCodeGenerator.hpp"
  31 #include "utilities/copy.hpp"
  32 #ifdef TARGET_ARCH_x86
  33 # include "assembler_x86.inline.hpp"
  34 # include "nativeInst_x86.hpp"
  35 #endif
  36 #ifdef TARGET_ARCH_sparc
  37 # include "assembler_sparc.inline.hpp"
  38 # include "nativeInst_sparc.hpp"
  39 #endif
  40 #ifdef TARGET_ARCH_zero
  41 # include "assembler_zero.inline.hpp"
  42 # include "nativeInst_zero.hpp"
  43 #endif
  44 #ifdef TARGET_ARCH_arm
  45 # include "assembler_arm.inline.hpp"
  46 # include "nativeInst_arm.hpp"
  47 #endif
  48 #ifdef TARGET_ARCH_ppc
  49 # include "assembler_ppc.inline.hpp"
  50 # include "nativeInst_ppc.hpp"
  51 #endif
  52 
  53 
  54 const RelocationHolder RelocationHolder::none; // its type is relocInfo::none
  55 
  56 
  57 // Implementation of relocInfo
  58 
  59 #ifdef ASSERT
  60 relocInfo::relocInfo(relocType t, int off, int f) {
  61   assert(t != data_prefix_tag, "cannot build a prefix this way");
  62   assert((t & type_mask) == t, "wrong type");
  63   assert((f & format_mask) == f, "wrong format");
  64   assert(off >= 0 && off < offset_limit(), "offset out off bounds");
  65   assert((off & (offset_unit-1)) == 0, "misaligned offset");
  66   (*this) = relocInfo(t, RAW_BITS, off, f);
  67 }
  68 #endif
  69 
  70 void relocInfo::initialize(CodeSection* dest, Relocation* reloc) {
  71   relocInfo* data = this+1;  // here's where the data might go
  72   dest->set_locs_end(data);  // sync end: the next call may read dest.locs_end
  73   reloc->pack_data_to(dest); // maybe write data into locs, advancing locs_end
  74   relocInfo* data_limit = dest->locs_end();
  75   if (data_limit > data) {
  76     relocInfo suffix = (*this);
  77     data_limit = this->finish_prefix((short*) data_limit);
  78     // Finish up with the suffix.  (Hack note: pack_data_to might edit this.)
  79     *data_limit = suffix;
  80     dest->set_locs_end(data_limit+1);
  81   }
  82 }
  83 
  84 relocInfo* relocInfo::finish_prefix(short* prefix_limit) {
  85   assert(sizeof(relocInfo) == sizeof(short), "change this code");
  86   short* p = (short*)(this+1);
  87   assert(prefix_limit >= p, "must be a valid span of data");
  88   int plen = prefix_limit - p;
  89   if (plen == 0) {
  90     debug_only(_value = 0xFFFF);
  91     return this;                         // no data: remove self completely
  92   }
  93   if (plen == 1 && fits_into_immediate(p[0])) {
  94     (*this) = immediate_relocInfo(p[0]); // move data inside self
  95     return this+1;
  96   }
  97   // cannot compact, so just update the count and return the limit pointer
  98   (*this) = prefix_relocInfo(plen);   // write new datalen
  99   assert(data() + datalen() == prefix_limit, "pointers must line up");
 100   return (relocInfo*)prefix_limit;
 101 }
 102 
 103 
 104 void relocInfo::set_type(relocType t) {
 105   int old_offset = addr_offset();
 106   int old_format = format();
 107   (*this) = relocInfo(t, old_offset, old_format);
 108   assert(type()==(int)t, "sanity check");
 109   assert(addr_offset()==old_offset, "sanity check");
 110   assert(format()==old_format, "sanity check");
 111 }
 112 
 113 
 114 void relocInfo::set_format(int f) {
 115   int old_offset = addr_offset();
 116   assert((f & format_mask) == f, "wrong format");
 117   _value = (_value & ~(format_mask << offset_width)) | (f << offset_width);
 118   assert(addr_offset()==old_offset, "sanity check");
 119 }
 120 
 121 
 122 void relocInfo::change_reloc_info_for_address(RelocIterator *itr, address pc, relocType old_type, relocType new_type) {
 123   bool found = false;
 124   while (itr->next() && !found) {
 125     if (itr->addr() == pc) {
 126       assert(itr->type()==old_type, "wrong relocInfo type found");
 127       itr->current()->set_type(new_type);
 128       found=true;
 129     }
 130   }
 131   assert(found, "no relocInfo found for pc");
 132 }
 133 
 134 
 135 void relocInfo::remove_reloc_info_for_address(RelocIterator *itr, address pc, relocType old_type) {
 136   change_reloc_info_for_address(itr, pc, old_type, none);
 137 }
 138 
 139 
 140 // ----------------------------------------------------------------------------------------------------
 141 // Implementation of RelocIterator
 142 
 143 void RelocIterator::initialize(nmethod* nm, address begin, address limit) {
 144   initialize_misc();
 145 
 146   if (nm == NULL && begin != NULL) {
 147     // allow nmethod to be deduced from beginning address
 148     CodeBlob* cb = CodeCache::find_blob(begin);
 149     nm = cb->as_nmethod_or_null();
 150   }
 151   assert(nm != NULL, "must be able to deduce nmethod from other arguments");
 152 
 153   _code    = nm;
 154   _current = nm->relocation_begin() - 1;
 155   _end     = nm->relocation_end();
 156   _addr    = nm->content_begin();
 157 
 158   // Initialize code sections.
 159   _section_start[CodeBuffer::SECT_CONSTS] = nm->consts_begin();
 160   _section_start[CodeBuffer::SECT_INSTS ] = nm->insts_begin() ;
 161   _section_start[CodeBuffer::SECT_STUBS ] = nm->stub_begin()  ;
 162 
 163   _section_end  [CodeBuffer::SECT_CONSTS] = nm->consts_end()  ;
 164   _section_end  [CodeBuffer::SECT_INSTS ] = nm->insts_end()   ;
 165   _section_end  [CodeBuffer::SECT_STUBS ] = nm->stub_end()    ;
 166 
 167   assert(!has_current(), "just checking");
 168   assert(begin == NULL || begin >= nm->code_begin(), "in bounds");
 169   assert(limit == NULL || limit <= nm->code_end(),   "in bounds");
 170   set_limits(begin, limit);
 171 }
 172 
 173 
 174 RelocIterator::RelocIterator(CodeSection* cs, address begin, address limit) {
 175   initialize_misc();
 176 
 177   _current = cs->locs_start()-1;
 178   _end     = cs->locs_end();
 179   _addr    = cs->start();
 180   _code    = NULL; // Not cb->blob();
 181 
 182   CodeBuffer* cb = cs->outer();
 183   assert((int) SECT_LIMIT == CodeBuffer::SECT_LIMIT, "my copy must be equal");
 184   for (int n = (int) CodeBuffer::SECT_FIRST; n < (int) CodeBuffer::SECT_LIMIT; n++) {
 185     CodeSection* cs = cb->code_section(n);
 186     _section_start[n] = cs->start();
 187     _section_end  [n] = cs->end();
 188   }
 189 
 190   assert(!has_current(), "just checking");
 191 
 192   assert(begin == NULL || begin >= cs->start(), "in bounds");
 193   assert(limit == NULL || limit <= cs->end(),   "in bounds");
 194   set_limits(begin, limit);
 195 }
 196 
 197 
 198 enum { indexCardSize = 128 };
 199 struct RelocIndexEntry {
 200   jint addr_offset;          // offset from header_end of an addr()
 201   jint reloc_offset;         // offset from header_end of a relocInfo (prefix)
 202 };
 203 
 204 
 205 bool RelocIterator::addr_in_const() const {
 206   const int n = CodeBuffer::SECT_CONSTS;
 207   return section_start(n) <= addr() && addr() < section_end(n);
 208 }
 209 
 210 
 211 static inline int num_cards(int code_size) {
 212   return (code_size-1) / indexCardSize;
 213 }
 214 
 215 
 216 int RelocIterator::locs_and_index_size(int code_size, int locs_size) {
 217   if (!UseRelocIndex)  return locs_size;   // no index
 218   code_size = round_to(code_size, oopSize);
 219   locs_size = round_to(locs_size, oopSize);
 220   int index_size = num_cards(code_size) * sizeof(RelocIndexEntry);
 221   // format of indexed relocs:
 222   //   relocation_begin:   relocInfo ...
 223   //   index:              (addr,reloc#) ...
 224   //                       indexSize           :relocation_end
 225   return locs_size + index_size + BytesPerInt;
 226 }
 227 
 228 
 229 void RelocIterator::create_index(relocInfo* dest_begin, int dest_count, relocInfo* dest_end) {
 230   address relocation_begin = (address)dest_begin;
 231   address relocation_end   = (address)dest_end;
 232   int     total_size       = relocation_end - relocation_begin;
 233   int     locs_size        = dest_count * sizeof(relocInfo);
 234   if (!UseRelocIndex) {
 235     Copy::fill_to_bytes(relocation_begin + locs_size, total_size-locs_size, 0);
 236     return;
 237   }
 238   int     index_size       = total_size - locs_size - BytesPerInt;      // find out how much space is left
 239   int     ncards           = index_size / sizeof(RelocIndexEntry);
 240   assert(total_size == locs_size + index_size + BytesPerInt, "checkin'");
 241   assert(index_size >= 0 && index_size % sizeof(RelocIndexEntry) == 0, "checkin'");
 242   jint*   index_size_addr  = (jint*)relocation_end - 1;
 243 
 244   assert(sizeof(jint) == BytesPerInt, "change this code");
 245 
 246   *index_size_addr = index_size;
 247   if (index_size != 0) {
 248     assert(index_size > 0, "checkin'");
 249 
 250     RelocIndexEntry* index = (RelocIndexEntry *)(relocation_begin + locs_size);
 251     assert(index == (RelocIndexEntry*)index_size_addr - ncards, "checkin'");
 252 
 253     // walk over the relocations, and fill in index entries as we go
 254     RelocIterator iter;
 255     const address    initial_addr    = NULL;
 256     relocInfo* const initial_current = dest_begin - 1;  // biased by -1 like elsewhere
 257 
 258     iter._code    = NULL;
 259     iter._addr    = initial_addr;
 260     iter._limit   = (address)(intptr_t)(ncards * indexCardSize);
 261     iter._current = initial_current;
 262     iter._end     = dest_begin + dest_count;
 263 
 264     int i = 0;
 265     address next_card_addr = (address)indexCardSize;
 266     int addr_offset = 0;
 267     int reloc_offset = 0;
 268     while (true) {
 269       // Checkpoint the iterator before advancing it.
 270       addr_offset  = iter._addr    - initial_addr;
 271       reloc_offset = iter._current - initial_current;
 272       if (!iter.next())  break;
 273       while (iter.addr() >= next_card_addr) {
 274         index[i].addr_offset  = addr_offset;
 275         index[i].reloc_offset = reloc_offset;
 276         i++;
 277         next_card_addr += indexCardSize;
 278       }
 279     }
 280     while (i < ncards) {
 281       index[i].addr_offset  = addr_offset;
 282       index[i].reloc_offset = reloc_offset;
 283       i++;
 284     }
 285   }
 286 }
 287 
 288 
 289 void RelocIterator::set_limits(address begin, address limit) {
 290   int index_size = 0;
 291   if (UseRelocIndex && _code != NULL) {
 292     index_size = ((jint*)_end)[-1];
 293     _end = (relocInfo*)( (address)_end - index_size - BytesPerInt );
 294   }
 295 
 296   _limit = limit;
 297 
 298   // the limit affects this next stuff:
 299   if (begin != NULL) {
 300 #ifdef ASSERT
 301     // In ASSERT mode we do not actually use the index, but simply
 302     // check that its contents would have led us to the right answer.
 303     address addrCheck = _addr;
 304     relocInfo* infoCheck = _current;
 305 #endif // ASSERT
 306     if (index_size > 0) {
 307       // skip ahead
 308       RelocIndexEntry* index       = (RelocIndexEntry*)_end;
 309       RelocIndexEntry* index_limit = (RelocIndexEntry*)((address)index + index_size);
 310       assert(_addr == _code->code_begin(), "_addr must be unadjusted");
 311       int card = (begin - _addr) / indexCardSize;
 312       if (card > 0) {
 313         if (index+card-1 < index_limit)  index += card-1;
 314         else                             index = index_limit - 1;
 315 #ifdef ASSERT
 316         addrCheck = _addr    + index->addr_offset;
 317         infoCheck = _current + index->reloc_offset;
 318 #else
 319         // Advance the iterator immediately to the last valid state
 320         // for the previous card.  Calling "next" will then advance
 321         // it to the first item on the required card.
 322         _addr    += index->addr_offset;
 323         _current += index->reloc_offset;
 324 #endif // ASSERT
 325       }
 326     }
 327 
 328     relocInfo* backup;
 329     address    backup_addr;
 330     while (true) {
 331       backup      = _current;
 332       backup_addr = _addr;
 333 #ifdef ASSERT
 334       if (backup == infoCheck) {
 335         assert(backup_addr == addrCheck, "must match"); addrCheck = NULL; infoCheck = NULL;
 336       } else {
 337         assert(addrCheck == NULL || backup_addr <= addrCheck, "must not pass addrCheck");
 338       }
 339 #endif // ASSERT
 340       if (!next() || addr() >= begin) break;
 341     }
 342     assert(addrCheck == NULL || addrCheck == backup_addr, "must have matched addrCheck");
 343     assert(infoCheck == NULL || infoCheck == backup,      "must have matched infoCheck");
 344     // At this point, either we are at the first matching record,
 345     // or else there is no such record, and !has_current().
 346     // In either case, revert to the immediatly preceding state.
 347     _current = backup;
 348     _addr    = backup_addr;
 349     set_has_current(false);
 350   }
 351 }
 352 
 353 
 354 void RelocIterator::set_limit(address limit) {
 355   address code_end = (address)code() + code()->size();
 356   assert(limit == NULL || limit <= code_end, "in bounds");
 357   _limit = limit;
 358 }
 359 
 360 
 361 void PatchingRelocIterator:: prepass() {
 362   // turn breakpoints off during patching
 363   _init_state = (*this);        // save cursor
 364   while (next()) {
 365     if (type() == relocInfo::breakpoint_type) {
 366       breakpoint_reloc()->set_active(false);
 367     }
 368   }
 369   (RelocIterator&)(*this) = _init_state;        // reset cursor for client
 370 }
 371 
 372 
 373 void PatchingRelocIterator:: postpass() {
 374   // turn breakpoints back on after patching
 375   (RelocIterator&)(*this) = _init_state;        // reset cursor again
 376   while (next()) {
 377     if (type() == relocInfo::breakpoint_type) {
 378       breakpoint_Relocation* bpt = breakpoint_reloc();
 379       bpt->set_active(bpt->enabled());
 380     }
 381   }
 382 }
 383 
 384 
 385 // All the strange bit-encodings are in here.
 386 // The idea is to encode relocation data which are small integers
 387 // very efficiently (a single extra halfword).  Larger chunks of
 388 // relocation data need a halfword header to hold their size.
 389 void RelocIterator::advance_over_prefix() {
 390   if (_current->is_datalen()) {
 391     _data    = (short*) _current->data();
 392     _datalen =          _current->datalen();
 393     _current += _datalen + 1;   // skip the embedded data & header
 394   } else {
 395     _databuf = _current->immediate();
 396     _data = &_databuf;
 397     _datalen = 1;
 398     _current++;                 // skip the header
 399   }
 400   // The client will see the following relocInfo, whatever that is.
 401   // It is the reloc to which the preceding data applies.
 402 }
 403 
 404 
 405 void RelocIterator::initialize_misc() {
 406   set_has_current(false);
 407   for (int i = (int) CodeBuffer::SECT_FIRST; i < (int) CodeBuffer::SECT_LIMIT; i++) {
 408     _section_start[i] = NULL;  // these will be lazily computed, if needed
 409     _section_end  [i] = NULL;
 410   }
 411 }
 412 
 413 
 414 Relocation* RelocIterator::reloc() {
 415   // (take the "switch" out-of-line)
 416   relocInfo::relocType t = type();
 417   if (false) {}
 418   #define EACH_TYPE(name)                             \
 419   else if (t == relocInfo::name##_type) {             \
 420     return name##_reloc();                            \
 421   }
 422   APPLY_TO_RELOCATIONS(EACH_TYPE);
 423   #undef EACH_TYPE
 424   assert(t == relocInfo::none, "must be padding");
 425   return new(_rh) Relocation();
 426 }
 427 
 428 
 429 //////// Methods for flyweight Relocation types
 430 
 431 
 432 RelocationHolder RelocationHolder::plus(int offset) const {
 433   if (offset != 0) {
 434     switch (type()) {
 435     case relocInfo::none:
 436       break;
 437     case relocInfo::oop_type:
 438       {
 439         oop_Relocation* r = (oop_Relocation*)reloc();
 440         return oop_Relocation::spec(r->oop_index(), r->offset() + offset);
 441       }
 442     default:
 443       ShouldNotReachHere();
 444     }
 445   }
 446   return (*this);
 447 }
 448 
 449 
 450 void Relocation::guarantee_size() {
 451   guarantee(false, "Make _relocbuf bigger!");
 452 }
 453 
 454     // some relocations can compute their own values
 455 address Relocation::value() {
 456   ShouldNotReachHere();
 457   return NULL;
 458 }
 459 
 460 
 461 void Relocation::set_value(address x) {
 462   ShouldNotReachHere();
 463 }
 464 
 465 
 466 RelocationHolder Relocation::spec_simple(relocInfo::relocType rtype) {
 467   if (rtype == relocInfo::none)  return RelocationHolder::none;
 468   relocInfo ri = relocInfo(rtype, 0);
 469   RelocIterator itr;
 470   itr.set_current(ri);
 471   itr.reloc();
 472   return itr._rh;
 473 }
 474 
 475 
 476 static inline bool is_index(intptr_t index) {
 477   return 0 < index && index < os::vm_page_size();
 478 }
 479 
 480 
 481 int32_t Relocation::runtime_address_to_index(address runtime_address) {
 482   assert(!is_index((intptr_t)runtime_address), "must not look like an index");
 483 
 484   if (runtime_address == NULL)  return 0;
 485 
 486   StubCodeDesc* p = StubCodeDesc::desc_for(runtime_address);
 487   if (p != NULL && p->begin() == runtime_address) {
 488     assert(is_index(p->index()), "there must not be too many stubs");
 489     return (int32_t)p->index();
 490   } else {
 491     // Known "miscellaneous" non-stub pointers:
 492     // os::get_polling_page(), SafepointSynchronize::address_of_state()
 493     if (PrintRelocations) {
 494       tty->print_cr("random unregistered address in relocInfo: " INTPTR_FORMAT, runtime_address);
 495     }
 496 #ifndef _LP64
 497     return (int32_t) (intptr_t)runtime_address;
 498 #else
 499     // didn't fit return non-index
 500     return -1;
 501 #endif /* _LP64 */
 502   }
 503 }
 504 
 505 
 506 address Relocation::index_to_runtime_address(int32_t index) {
 507   if (index == 0)  return NULL;
 508 
 509   if (is_index(index)) {
 510     StubCodeDesc* p = StubCodeDesc::desc_for_index(index);
 511     assert(p != NULL, "there must be a stub for this index");
 512     return p->begin();
 513   } else {
 514 #ifndef _LP64
 515     // this only works on 32bit machines
 516     return (address) ((intptr_t) index);
 517 #else
 518     fatal("Relocation::index_to_runtime_address, int32_t not pointer sized");
 519     return NULL;
 520 #endif /* _LP64 */
 521   }
 522 }
 523 
 524 address Relocation::old_addr_for(address newa,
 525                                  const CodeBuffer* src, CodeBuffer* dest) {
 526   int sect = dest->section_index_of(newa);
 527   guarantee(sect != CodeBuffer::SECT_NONE, "lost track of this address");
 528   address ostart = src->code_section(sect)->start();
 529   address nstart = dest->code_section(sect)->start();
 530   return ostart + (newa - nstart);
 531 }
 532 
 533 address Relocation::new_addr_for(address olda,
 534                                  const CodeBuffer* src, CodeBuffer* dest) {
 535   debug_only(const CodeBuffer* src0 = src);
 536   int sect = CodeBuffer::SECT_NONE;
 537   // Look for olda in the source buffer, and all previous incarnations
 538   // if the source buffer has been expanded.
 539   for (; src != NULL; src = src->before_expand()) {
 540     sect = src->section_index_of(olda);
 541     if (sect != CodeBuffer::SECT_NONE)  break;
 542   }
 543   guarantee(sect != CodeBuffer::SECT_NONE, "lost track of this address");
 544   address ostart = src->code_section(sect)->start();
 545   address nstart = dest->code_section(sect)->start();
 546   return nstart + (olda - ostart);
 547 }
 548 
 549 void Relocation::normalize_address(address& addr, const CodeSection* dest, bool allow_other_sections) {
 550   address addr0 = addr;
 551   if (addr0 == NULL || dest->allocates2(addr0))  return;
 552   CodeBuffer* cb = dest->outer();
 553   addr = new_addr_for(addr0, cb, cb);
 554   assert(allow_other_sections || dest->contains2(addr),
 555          "addr must be in required section");
 556 }
 557 
 558 
 559 void CallRelocation::set_destination(address x) {
 560   pd_set_call_destination(x);
 561 }
 562 
 563 void CallRelocation::fix_relocation_after_move(const CodeBuffer* src, CodeBuffer* dest) {
 564   // Usually a self-relative reference to an external routine.
 565   // On some platforms, the reference is absolute (not self-relative).
 566   // The enhanced use of pd_call_destination sorts this all out.
 567   address orig_addr = old_addr_for(addr(), src, dest);
 568   address callee    = pd_call_destination(orig_addr);
 569   // Reassert the callee address, this time in the new copy of the code.
 570   pd_set_call_destination(callee);
 571 }
 572 
 573 
 574 //// pack/unpack methods
 575 
 576 void oop_Relocation::pack_data_to(CodeSection* dest) {
 577   short* p = (short*) dest->locs_end();
 578   p = pack_2_ints_to(p, _oop_index, _offset);
 579   dest->set_locs_end((relocInfo*) p);
 580 }
 581 
 582 
 583 void oop_Relocation::unpack_data() {
 584   unpack_2_ints(_oop_index, _offset);
 585 }
 586 
 587 
 588 void virtual_call_Relocation::pack_data_to(CodeSection* dest) {
 589   short*  p     = (short*) dest->locs_end();
 590   address point =          dest->locs_point();
 591 
 592   // Try to make a pointer NULL first.
 593   if (_oop_limit >= point &&
 594       _oop_limit <= point + NativeCall::instruction_size) {
 595     _oop_limit = NULL;
 596   }
 597   // If the _oop_limit is NULL, it "defaults" to the end of the call.
 598   // See ic_call_Relocation::oop_limit() below.
 599 
 600   normalize_address(_first_oop, dest);
 601   normalize_address(_oop_limit, dest);
 602   jint x0 = scaled_offset_null_special(_first_oop, point);
 603   jint x1 = scaled_offset_null_special(_oop_limit, point);
 604   p = pack_2_ints_to(p, x0, x1);
 605   dest->set_locs_end((relocInfo*) p);
 606 }
 607 
 608 
 609 void virtual_call_Relocation::unpack_data() {
 610   jint x0, x1; unpack_2_ints(x0, x1);
 611   address point = addr();
 612   _first_oop = x0==0? NULL: address_from_scaled_offset(x0, point);
 613   _oop_limit = x1==0? NULL: address_from_scaled_offset(x1, point);
 614 }
 615 
 616 
 617 void static_stub_Relocation::pack_data_to(CodeSection* dest) {
 618   short* p = (short*) dest->locs_end();
 619   CodeSection* insts = dest->outer()->insts();
 620   normalize_address(_static_call, insts);
 621   p = pack_1_int_to(p, scaled_offset(_static_call, insts->start()));
 622   dest->set_locs_end((relocInfo*) p);
 623 }
 624 
 625 void static_stub_Relocation::unpack_data() {
 626   address base = binding()->section_start(CodeBuffer::SECT_INSTS);
 627   _static_call = address_from_scaled_offset(unpack_1_int(), base);
 628 }
 629 
 630 
 631 void external_word_Relocation::pack_data_to(CodeSection* dest) {
 632   short* p = (short*) dest->locs_end();
 633   int32_t index = runtime_address_to_index(_target);
 634 #ifndef _LP64
 635   p = pack_1_int_to(p, index);
 636 #else
 637   if (is_index(index)) {
 638     p = pack_2_ints_to(p, index, 0);
 639   } else {
 640     jlong t = (jlong) _target;
 641     int32_t lo = low(t);
 642     int32_t hi = high(t);
 643     p = pack_2_ints_to(p, lo, hi);
 644     DEBUG_ONLY(jlong t1 = jlong_from(hi, lo));
 645     assert(!is_index(t1) && (address) t1 == _target, "not symmetric");
 646   }
 647 #endif /* _LP64 */
 648   dest->set_locs_end((relocInfo*) p);
 649 }
 650 
 651 
 652 void external_word_Relocation::unpack_data() {
 653 #ifndef _LP64
 654   _target = index_to_runtime_address(unpack_1_int());
 655 #else
 656   int32_t lo, hi;
 657   unpack_2_ints(lo, hi);
 658   jlong t = jlong_from(hi, lo);;
 659   if (is_index(t)) {
 660     _target = index_to_runtime_address(t);
 661   } else {
 662     _target = (address) t;
 663   }
 664 #endif /* _LP64 */
 665 }
 666 
 667 
 668 void internal_word_Relocation::pack_data_to(CodeSection* dest) {
 669   short* p = (short*) dest->locs_end();
 670   normalize_address(_target, dest, true);
 671 
 672   // Check whether my target address is valid within this section.
 673   // If not, strengthen the relocation type to point to another section.
 674   int sindex = _section;
 675   if (sindex == CodeBuffer::SECT_NONE && _target != NULL
 676       && (!dest->allocates(_target) || _target == dest->locs_point())) {
 677     sindex = dest->outer()->section_index_of(_target);
 678     guarantee(sindex != CodeBuffer::SECT_NONE, "must belong somewhere");
 679     relocInfo* base = dest->locs_end() - 1;
 680     assert(base->type() == this->type(), "sanity");
 681     // Change the written type, to be section_word_type instead.
 682     base->set_type(relocInfo::section_word_type);
 683   }
 684 
 685   // Note: An internal_word relocation cannot refer to its own instruction,
 686   // because we reserve "0" to mean that the pointer itself is embedded
 687   // in the code stream.  We use a section_word relocation for such cases.
 688 
 689   if (sindex == CodeBuffer::SECT_NONE) {
 690     assert(type() == relocInfo::internal_word_type, "must be base class");
 691     guarantee(_target == NULL || dest->allocates2(_target), "must be within the given code section");
 692     jint x0 = scaled_offset_null_special(_target, dest->locs_point());
 693     assert(!(x0 == 0 && _target != NULL), "correct encoding of null target");
 694     p = pack_1_int_to(p, x0);
 695   } else {
 696     assert(_target != NULL, "sanity");
 697     CodeSection* sect = dest->outer()->code_section(sindex);
 698     guarantee(sect->allocates2(_target), "must be in correct section");
 699     address base = sect->start();
 700     jint offset = scaled_offset(_target, base);
 701     assert((uint)sindex < (uint)CodeBuffer::SECT_LIMIT, "sanity");
 702     assert(CodeBuffer::SECT_LIMIT <= (1 << section_width), "section_width++");
 703     p = pack_1_int_to(p, (offset << section_width) | sindex);
 704   }
 705 
 706   dest->set_locs_end((relocInfo*) p);
 707 }
 708 
 709 
 710 void internal_word_Relocation::unpack_data() {
 711   jint x0 = unpack_1_int();
 712   _target = x0==0? NULL: address_from_scaled_offset(x0, addr());
 713   _section = CodeBuffer::SECT_NONE;
 714 }
 715 
 716 
 717 void section_word_Relocation::unpack_data() {
 718   jint    x      = unpack_1_int();
 719   jint    offset = (x >> section_width);
 720   int     sindex = (x & ((1<<section_width)-1));
 721   address base   = binding()->section_start(sindex);
 722 
 723   _section = sindex;
 724   _target  = address_from_scaled_offset(offset, base);
 725 }
 726 
 727 
 728 void breakpoint_Relocation::pack_data_to(CodeSection* dest) {
 729   short* p = (short*) dest->locs_end();
 730   address point = dest->locs_point();
 731 
 732   *p++ = _bits;
 733 
 734   assert(_target != NULL, "sanity");
 735 
 736   if (internal())  normalize_address(_target, dest);
 737 
 738   jint target_bits =
 739     (jint)( internal() ? scaled_offset           (_target, point)
 740                        : runtime_address_to_index(_target) );
 741   if (settable()) {
 742     // save space for set_target later
 743     p = add_jint(p, target_bits);
 744   } else {
 745     p = add_var_int(p, target_bits);
 746   }
 747 
 748   for (int i = 0; i < instrlen(); i++) {
 749     // put placeholder words until bytes can be saved
 750     p = add_short(p, (short)0x7777);
 751   }
 752 
 753   dest->set_locs_end((relocInfo*) p);
 754 }
 755 
 756 
 757 void breakpoint_Relocation::unpack_data() {
 758   _bits = live_bits();
 759 
 760   int targetlen = datalen() - 1 - instrlen();
 761   jint target_bits = 0;
 762   if (targetlen == 0)       target_bits = 0;
 763   else if (targetlen == 1)  target_bits = *(data()+1);
 764   else if (targetlen == 2)  target_bits = relocInfo::jint_from_data(data()+1);
 765   else                      { ShouldNotReachHere(); }
 766 
 767   _target = internal() ? address_from_scaled_offset(target_bits, addr())
 768                        : index_to_runtime_address  (target_bits);
 769 }
 770 
 771 
 772 //// miscellaneous methods
 773 oop* oop_Relocation::oop_addr() {
 774   int n = _oop_index;
 775   if (n == 0) {
 776     // oop is stored in the code stream
 777     return (oop*) pd_address_in_code();
 778   } else {
 779     // oop is stored in table at nmethod::oops_begin
 780     return code()->oop_addr_at(n);
 781   }
 782 }
 783 
 784 
 785 oop oop_Relocation::oop_value() {
 786   oop v = *oop_addr();
 787   // clean inline caches store a special pseudo-null
 788   if (v == (oop)Universe::non_oop_word())  v = NULL;
 789   return v;
 790 }
 791 
 792 
 793 void oop_Relocation::fix_oop_relocation() {
 794   if (!oop_is_immediate()) {
 795     // get the oop from the pool, and re-insert it into the instruction:
 796     set_value(value());
 797   }
 798 }
 799 
 800 
 801 RelocIterator virtual_call_Relocation::parse_ic(nmethod* &nm, address &ic_call, address &first_oop,
 802                                                 oop* &oop_addr, bool *is_optimized) {
 803   assert(ic_call != NULL, "ic_call address must be set");
 804   assert(ic_call != NULL || first_oop != NULL, "must supply a non-null input");
 805   if (nm == NULL) {
 806     CodeBlob* code;
 807     if (ic_call != NULL) {
 808       code = CodeCache::find_blob(ic_call);
 809     } else if (first_oop != NULL) {
 810       code = CodeCache::find_blob(first_oop);
 811     }
 812     nm = code->as_nmethod_or_null();
 813     assert(nm != NULL, "address to parse must be in nmethod");
 814   }
 815   assert(ic_call   == NULL || nm->contains(ic_call),   "must be in nmethod");
 816   assert(first_oop == NULL || nm->contains(first_oop), "must be in nmethod");
 817 
 818   address oop_limit = NULL;
 819 
 820   if (ic_call != NULL) {
 821     // search for the ic_call at the given address
 822     RelocIterator iter(nm, ic_call, ic_call+1);
 823     bool ret = iter.next();
 824     assert(ret == true, "relocInfo must exist at this address");
 825     assert(iter.addr() == ic_call, "must find ic_call");
 826     if (iter.type() == relocInfo::virtual_call_type) {
 827       virtual_call_Relocation* r = iter.virtual_call_reloc();
 828       first_oop = r->first_oop();
 829       oop_limit = r->oop_limit();
 830       *is_optimized = false;
 831     } else {
 832       assert(iter.type() == relocInfo::opt_virtual_call_type, "must be a virtual call");
 833       *is_optimized = true;
 834       oop_addr = NULL;
 835       first_oop = NULL;
 836       return iter;
 837     }
 838   }
 839 
 840   // search for the first_oop, to get its oop_addr
 841   RelocIterator all_oops(nm, first_oop);
 842   RelocIterator iter = all_oops;
 843   iter.set_limit(first_oop+1);
 844   bool found_oop = false;
 845   while (iter.next()) {
 846     if (iter.type() == relocInfo::oop_type) {
 847       assert(iter.addr() == first_oop, "must find first_oop");
 848       oop_addr = iter.oop_reloc()->oop_addr();
 849       found_oop = true;
 850       break;
 851     }
 852   }
 853   assert(found_oop, "must find first_oop");
 854 
 855   bool did_reset = false;
 856   while (ic_call == NULL) {
 857     // search forward for the ic_call matching the given first_oop
 858     while (iter.next()) {
 859       if (iter.type() == relocInfo::virtual_call_type) {
 860         virtual_call_Relocation* r = iter.virtual_call_reloc();
 861         if (r->first_oop() == first_oop) {
 862           ic_call   = r->addr();
 863           oop_limit = r->oop_limit();
 864           break;
 865         }
 866       }
 867     }
 868     guarantee(!did_reset, "cannot find ic_call");
 869     iter = RelocIterator(nm); // search the whole nmethod
 870     did_reset = true;
 871   }
 872 
 873   assert(oop_limit != NULL && first_oop != NULL && ic_call != NULL, "");
 874   all_oops.set_limit(oop_limit);
 875   return all_oops;
 876 }
 877 
 878 
 879 address virtual_call_Relocation::first_oop() {
 880   assert(_first_oop != NULL && _first_oop < addr(), "must precede ic_call");
 881   return _first_oop;
 882 }
 883 
 884 
 885 address virtual_call_Relocation::oop_limit() {
 886   if (_oop_limit == NULL)
 887     return addr() + NativeCall::instruction_size;
 888   else
 889     return _oop_limit;
 890 }
 891 
 892 
 893 
 894 void virtual_call_Relocation::clear_inline_cache() {
 895   // No stubs for ICs
 896   // Clean IC
 897   ResourceMark rm;
 898   CompiledIC* icache = CompiledIC_at(this);
 899   icache->set_to_clean();
 900 }
 901 
 902 
 903 void opt_virtual_call_Relocation::clear_inline_cache() {
 904   // No stubs for ICs
 905   // Clean IC
 906   ResourceMark rm;
 907   CompiledIC* icache = CompiledIC_at(this);
 908   icache->set_to_clean();
 909 }
 910 
 911 
 912 address opt_virtual_call_Relocation::static_stub() {
 913   // search for the static stub who points back to this static call
 914   address static_call_addr = addr();
 915   RelocIterator iter(code());
 916   while (iter.next()) {
 917     if (iter.type() == relocInfo::static_stub_type) {
 918       if (iter.static_stub_reloc()->static_call() == static_call_addr) {
 919         return iter.addr();
 920       }
 921     }
 922   }
 923   return NULL;
 924 }
 925 
 926 
 927 void static_call_Relocation::clear_inline_cache() {
 928   // Safe call site info
 929   CompiledStaticCall* handler = compiledStaticCall_at(this);
 930   handler->set_to_clean();
 931 }
 932 
 933 
 934 address static_call_Relocation::static_stub() {
 935   // search for the static stub who points back to this static call
 936   address static_call_addr = addr();
 937   RelocIterator iter(code());
 938   while (iter.next()) {
 939     if (iter.type() == relocInfo::static_stub_type) {
 940       if (iter.static_stub_reloc()->static_call() == static_call_addr) {
 941         return iter.addr();
 942       }
 943     }
 944   }
 945   return NULL;
 946 }
 947 
 948 
 949 void static_stub_Relocation::clear_inline_cache() {
 950   // Call stub is only used when calling the interpreted code.
 951   // It does not really need to be cleared, except that we want to clean out the methodoop.
 952   CompiledStaticCall::set_stub_to_clean(this);
 953 }
 954 
 955 
 956 void external_word_Relocation::fix_relocation_after_move(const CodeBuffer* src, CodeBuffer* dest) {
 957   address target = _target;
 958   if (target == NULL) {
 959     // An absolute embedded reference to an external location,
 960     // which means there is nothing to fix here.
 961     return;
 962   }
 963   // Probably this reference is absolute, not relative, so the
 964   // following is probably a no-op.
 965   assert(src->section_index_of(target) == CodeBuffer::SECT_NONE, "sanity");
 966   set_value(target);
 967 }
 968 
 969 
 970 address external_word_Relocation::target() {
 971   address target = _target;
 972   if (target == NULL) {
 973     target = pd_get_address_from_code();
 974   }
 975   return target;
 976 }
 977 
 978 
 979 void internal_word_Relocation::fix_relocation_after_move(const CodeBuffer* src, CodeBuffer* dest) {
 980   address target = _target;
 981   if (target == NULL) {
 982     if (addr_in_const()) {
 983       target = new_addr_for(*(address*)addr(), src, dest);
 984     } else {
 985       target = new_addr_for(pd_get_address_from_code(), src, dest);
 986     }
 987   }
 988   set_value(target);
 989 }
 990 
 991 
 992 address internal_word_Relocation::target() {
 993   address target = _target;
 994   if (target == NULL) {
 995     target = pd_get_address_from_code();
 996   }
 997   return target;
 998 }
 999 
1000 
1001 breakpoint_Relocation::breakpoint_Relocation(int kind, address target, bool internal) {
1002   bool active    = false;
1003   bool enabled   = (kind == initialization);
1004   bool removable = (kind != safepoint);
1005   bool settable  = (target == NULL);
1006 
1007   int bits = kind;
1008   if (enabled)    bits |= enabled_state;
1009   if (internal)   bits |= internal_attr;
1010   if (removable)  bits |= removable_attr;
1011   if (settable)   bits |= settable_attr;
1012 
1013   _bits = bits | high_bit;
1014   _target = target;
1015 
1016   assert(this->kind()      == kind,      "kind encoded");
1017   assert(this->enabled()   == enabled,   "enabled encoded");
1018   assert(this->active()    == active,    "active encoded");
1019   assert(this->internal()  == internal,  "internal encoded");
1020   assert(this->removable() == removable, "removable encoded");
1021   assert(this->settable()  == settable,  "settable encoded");
1022 }
1023 
1024 
1025 address breakpoint_Relocation::target() const {
1026   return _target;
1027 }
1028 
1029 
1030 void breakpoint_Relocation::set_target(address x) {
1031   assert(settable(), "must be settable");
1032   jint target_bits =
1033     (jint)(internal() ? scaled_offset           (x, addr())
1034                       : runtime_address_to_index(x));
1035   short* p = &live_bits() + 1;
1036   p = add_jint(p, target_bits);
1037   assert(p == instrs(), "new target must fit");
1038   _target = x;
1039 }
1040 
1041 
1042 void breakpoint_Relocation::set_enabled(bool b) {
1043   if (enabled() == b) return;
1044 
1045   if (b) {
1046     set_bits(bits() | enabled_state);
1047   } else {
1048     set_active(false);          // remove the actual breakpoint insn, if any
1049     set_bits(bits() & ~enabled_state);
1050   }
1051 }
1052 
1053 
1054 void breakpoint_Relocation::set_active(bool b) {
1055   assert(!b || enabled(), "cannot activate a disabled breakpoint");
1056 
1057   if (active() == b) return;
1058 
1059   // %%% should probably seize a lock here (might not be the right lock)
1060   //MutexLockerEx ml_patch(Patching_lock, true);
1061   //if (active() == b)  return;         // recheck state after locking
1062 
1063   if (b) {
1064     set_bits(bits() | active_state);
1065     if (instrlen() == 0)
1066       fatal("breakpoints in original code must be undoable");
1067     pd_swap_in_breakpoint (addr(), instrs(), instrlen());
1068   } else {
1069     set_bits(bits() & ~active_state);
1070     pd_swap_out_breakpoint(addr(), instrs(), instrlen());
1071   }
1072 }
1073 
1074 
1075 //---------------------------------------------------------------------------------
1076 // Non-product code
1077 
1078 #ifndef PRODUCT
1079 
1080 static const char* reloc_type_string(relocInfo::relocType t) {
1081   switch (t) {
1082   #define EACH_CASE(name) \
1083   case relocInfo::name##_type: \
1084     return #name;
1085 
1086   APPLY_TO_RELOCATIONS(EACH_CASE);
1087   #undef EACH_CASE
1088 
1089   case relocInfo::none:
1090     return "none";
1091   case relocInfo::data_prefix_tag:
1092     return "prefix";
1093   default:
1094     return "UNKNOWN RELOC TYPE";
1095   }
1096 }
1097 
1098 
1099 void RelocIterator::print_current() {
1100   if (!has_current()) {
1101     tty->print_cr("(no relocs)");
1102     return;
1103   }
1104   tty->print("relocInfo@" INTPTR_FORMAT " [type=%d(%s) addr=" INTPTR_FORMAT " offset=%d",
1105              _current, type(), reloc_type_string((relocInfo::relocType) type()), _addr, _current->addr_offset());
1106   if (current()->format() != 0)
1107     tty->print(" format=%d", current()->format());
1108   if (datalen() == 1) {
1109     tty->print(" data=%d", data()[0]);
1110   } else if (datalen() > 0) {
1111     tty->print(" data={");
1112     for (int i = 0; i < datalen(); i++) {
1113       tty->print("%04x", data()[i] & 0xFFFF);
1114     }
1115     tty->print("}");
1116   }
1117   tty->print("]");
1118   switch (type()) {
1119   case relocInfo::oop_type:
1120     {
1121       oop_Relocation* r = oop_reloc();
1122       oop* oop_addr  = NULL;
1123       oop  raw_oop   = NULL;
1124       oop  oop_value = NULL;
1125       if (code() != NULL || r->oop_is_immediate()) {
1126         oop_addr  = r->oop_addr();
1127         raw_oop   = *oop_addr;
1128         oop_value = r->oop_value();
1129       }
1130       tty->print(" | [oop_addr=" INTPTR_FORMAT " *=" INTPTR_FORMAT " offset=%d]",
1131                  oop_addr, (address)raw_oop, r->offset());
1132       // Do not print the oop by default--we want this routine to
1133       // work even during GC or other inconvenient times.
1134       if (WizardMode && oop_value != NULL) {
1135         tty->print("oop_value=" INTPTR_FORMAT ": ", (address)oop_value);
1136         oop_value->print_value_on(tty);
1137       }
1138       break;
1139     }
1140   case relocInfo::external_word_type:
1141   case relocInfo::internal_word_type:
1142   case relocInfo::section_word_type:
1143     {
1144       DataRelocation* r = (DataRelocation*) reloc();
1145       tty->print(" | [target=" INTPTR_FORMAT "]", r->value()); //value==target
1146       break;
1147     }
1148   case relocInfo::static_call_type:
1149   case relocInfo::runtime_call_type:
1150     {
1151       CallRelocation* r = (CallRelocation*) reloc();
1152       tty->print(" | [destination=" INTPTR_FORMAT "]", r->destination());
1153       break;
1154     }
1155   case relocInfo::virtual_call_type:
1156     {
1157       virtual_call_Relocation* r = (virtual_call_Relocation*) reloc();
1158       tty->print(" | [destination=" INTPTR_FORMAT " first_oop=" INTPTR_FORMAT " oop_limit=" INTPTR_FORMAT "]",
1159                  r->destination(), r->first_oop(), r->oop_limit());
1160       break;
1161     }
1162   case relocInfo::static_stub_type:
1163     {
1164       static_stub_Relocation* r = (static_stub_Relocation*) reloc();
1165       tty->print(" | [static_call=" INTPTR_FORMAT "]", r->static_call());
1166       break;
1167     }
1168   }
1169   tty->cr();
1170 }
1171 
1172 
1173 void RelocIterator::print() {
1174   RelocIterator save_this = (*this);
1175   relocInfo* scan = _current;
1176   if (!has_current())  scan += 1;  // nothing to scan here!
1177 
1178   bool skip_next = has_current();
1179   bool got_next;
1180   while (true) {
1181     got_next = (skip_next || next());
1182     skip_next = false;
1183 
1184     tty->print("         @" INTPTR_FORMAT ": ", scan);
1185     relocInfo* newscan = _current+1;
1186     if (!has_current())  newscan -= 1;  // nothing to scan here!
1187     while (scan < newscan) {
1188       tty->print("%04x", *(short*)scan & 0xFFFF);
1189       scan++;
1190     }
1191     tty->cr();
1192 
1193     if (!got_next)  break;
1194     print_current();
1195   }
1196 
1197   (*this) = save_this;
1198 }
1199 
1200 // For the debugger:
1201 extern "C"
1202 void print_blob_locs(nmethod* nm) {
1203   nm->print();
1204   RelocIterator iter(nm);
1205   iter.print();
1206 }
1207 extern "C"
1208 void print_buf_locs(CodeBuffer* cb) {
1209   FlagSetting fs(PrintRelocations, true);
1210   cb->print();
1211 }
1212 #endif // !PRODUCT