1 /*
   2  * Copyright (c) 1997, 2025, 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 "code/codeCache.hpp"
  26 #include "code/compiledIC.hpp"
  27 #include "code/nmethod.hpp"
  28 #include "code/relocInfo.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "memory/universe.hpp"
  31 #include "oops/compressedOops.inline.hpp"
  32 #include "oops/oop.inline.hpp"
  33 #include "runtime/flags/flagSetting.hpp"
  34 #include "runtime/stubCodeGenerator.hpp"
  35 #include "utilities/align.hpp"
  36 #include "utilities/checkedCast.hpp"
  37 #include "utilities/copy.hpp"
  38 
  39 #include <new>
  40 #include <type_traits>
  41 
  42 const RelocationHolder RelocationHolder::none; // its type is relocInfo::none
  43 
  44 
  45 // Implementation of relocInfo
  46 
  47 #ifdef ASSERT
  48 relocInfo::relocType relocInfo::check_relocType(relocType type) {
  49   assert(type != data_prefix_tag, "cannot build a prefix this way");
  50   assert((type & type_mask) == type, "wrong type");
  51   return type;
  52 }
  53 
  54 void relocInfo::check_offset_and_format(int offset, int format) {
  55   assert(offset >= 0 && offset < offset_limit(), "offset out off bounds");
  56   assert(is_aligned(offset, offset_unit), "misaligned offset");
  57   assert((format & format_mask) == format, "wrong format");
  58 }
  59 #endif // ASSERT
  60 
  61 void relocInfo::initialize(CodeSection* dest, Relocation* reloc) {
  62   relocInfo* data = this+1;  // here's where the data might go
  63   dest->set_locs_end(data);  // sync end: the next call may read dest.locs_end
  64   reloc->pack_data_to(dest); // maybe write data into locs, advancing locs_end
  65   relocInfo* data_limit = dest->locs_end();
  66   if (data_limit > data) {
  67     relocInfo suffix = (*this);
  68     data_limit = this->finish_prefix((short*) data_limit);
  69     // Finish up with the suffix.  (Hack note: pack_data_to might edit this.)
  70     *data_limit = suffix;
  71     dest->set_locs_end(data_limit+1);
  72   }
  73 }
  74 
  75 relocInfo* relocInfo::finish_prefix(short* prefix_limit) {
  76   assert(sizeof(relocInfo) == sizeof(short), "change this code");
  77   short* p = (short*)(this+1);
  78   assert(prefix_limit >= p, "must be a valid span of data");
  79   int plen = checked_cast<int>(prefix_limit - p);
  80   if (plen == 0) {
  81     debug_only(_value = 0xFFFF);
  82     return this;                         // no data: remove self completely
  83   }
  84   if (plen == 1 && fits_into_immediate(p[0])) {
  85     (*this) = immediate_relocInfo(p[0]); // move data inside self
  86     return this+1;
  87   }
  88   // cannot compact, so just update the count and return the limit pointer
  89   (*this) = prefix_info(plen);       // write new datalen
  90   assert(data() + datalen() == prefix_limit, "pointers must line up");
  91   return (relocInfo*)prefix_limit;
  92 }
  93 
  94 void relocInfo::set_type(relocType t) {
  95   int old_offset = addr_offset();
  96   int old_format = format();
  97   (*this) = relocInfo(t, old_offset, old_format);
  98   assert(type()==(int)t, "sanity check");
  99   assert(addr_offset()==old_offset, "sanity check");
 100   assert(format()==old_format, "sanity check");
 101 }
 102 
 103 void relocInfo::change_reloc_info_for_address(RelocIterator *itr, address pc, relocType old_type, relocType new_type) {
 104   bool found = false;
 105   while (itr->next() && !found) {
 106     if (itr->addr() == pc) {
 107       assert(itr->type()==old_type, "wrong relocInfo type found");
 108       itr->current()->set_type(new_type);
 109       found=true;
 110     }
 111   }
 112   assert(found, "no relocInfo found for pc");
 113 }
 114 
 115 
 116 // ----------------------------------------------------------------------------------------------------
 117 // Implementation of RelocIterator
 118 
 119 // A static dummy to serve as a safe pointer when there is no relocation info.
 120 static relocInfo dummy_relocInfo = relocInfo(relocInfo::none, 0);
 121 
 122 void RelocIterator::initialize(nmethod* nm, address begin, address limit) {
 123   initialize_misc();
 124 
 125   if (nm == nullptr && begin != nullptr) {
 126     // allow nmethod to be deduced from beginning address
 127     CodeBlob* cb = CodeCache::find_blob(begin);
 128     nm = (cb != nullptr) ? cb->as_nmethod_or_null() : nullptr;
 129   }
 130   guarantee(nm != nullptr, "must be able to deduce nmethod from other arguments");
 131 
 132   _code    = nm;
 133   if (nm->relocation_size() == 0) {
 134     _current = &dummy_relocInfo - 1;
 135     _end = &dummy_relocInfo;
 136   } else {
 137     assert(((nm->relocation_begin() != nullptr) && (nm->relocation_end() != nullptr)), "valid start and end pointer");
 138     _current = nm->relocation_begin() - 1;
 139     _end     = nm->relocation_end();
 140   }
 141   _addr    = nm->content_begin();
 142 
 143   // Initialize code sections.
 144   _section_start[CodeBuffer::SECT_CONSTS] = nm->consts_begin();
 145   _section_start[CodeBuffer::SECT_INSTS ] = nm->insts_begin() ;
 146   _section_start[CodeBuffer::SECT_STUBS ] = nm->stub_begin()  ;
 147 
 148   _section_end  [CodeBuffer::SECT_CONSTS] = nm->consts_end()  ;
 149   _section_end  [CodeBuffer::SECT_INSTS ] = nm->insts_end()   ;
 150   _section_end  [CodeBuffer::SECT_STUBS ] = nm->stub_end()    ;
 151 
 152   assert(!has_current(), "just checking");
 153   assert(begin == nullptr || begin >= nm->code_begin(), "in bounds");
 154   assert(limit == nullptr || limit <= nm->code_end(),   "in bounds");
 155   set_limits(begin, limit);
 156 }
 157 
 158 
 159 RelocIterator::RelocIterator(CodeSection* cs, address begin, address limit) {
 160   initialize_misc();
 161   assert(((cs->locs_start() != nullptr) && (cs->locs_end() != nullptr)), "valid start and end pointer");
 162   _current = cs->locs_start() - 1;
 163   _end     = cs->locs_end();
 164   _addr    = cs->start();
 165   _code    = nullptr; // Not cb->blob();
 166 
 167   CodeBuffer* cb = cs->outer();
 168   assert((int) SECT_LIMIT == CodeBuffer::SECT_LIMIT, "my copy must be equal");
 169   for (int n = (int) CodeBuffer::SECT_FIRST; n < (int) CodeBuffer::SECT_LIMIT; n++) {
 170     CodeSection* cs = cb->code_section(n);
 171     _section_start[n] = cs->start();
 172     _section_end  [n] = cs->end();
 173   }
 174 
 175   assert(!has_current(), "just checking");
 176 
 177   assert(begin == nullptr || begin >= cs->start(), "in bounds");
 178   assert(limit == nullptr || limit <= cs->end(),   "in bounds");
 179   set_limits(begin, limit);
 180 }
 181 
 182 bool RelocIterator::addr_in_const() const {
 183   const int n = CodeBuffer::SECT_CONSTS;
 184   return section_start(n) <= addr() && addr() < section_end(n);
 185 }
 186 
 187 
 188 void RelocIterator::set_limits(address begin, address limit) {
 189   _limit = limit;
 190 
 191   // the limit affects this next stuff:
 192   if (begin != nullptr) {
 193     relocInfo* backup;
 194     address    backup_addr;
 195     while (true) {
 196       backup      = _current;
 197       backup_addr = _addr;
 198       if (!next() || addr() >= begin) break;
 199     }
 200     // At this point, either we are at the first matching record,
 201     // or else there is no such record, and !has_current().
 202     // In either case, revert to the immediately preceding state.
 203     _current = backup;
 204     _addr    = backup_addr;
 205     set_has_current(false);
 206   }
 207 }
 208 
 209 
 210 // All the strange bit-encodings are in here.
 211 // The idea is to encode relocation data which are small integers
 212 // very efficiently (a single extra halfword).  Larger chunks of
 213 // relocation data need a halfword header to hold their size.
 214 void RelocIterator::advance_over_prefix() {
 215   if (_current->is_datalen()) {
 216     _data    = (short*) _current->data();
 217     _datalen =          _current->datalen();
 218     _current += _datalen + 1;   // skip the embedded data & header
 219   } else {
 220     _databuf = _current->immediate();
 221     _data = &_databuf;
 222     _datalen = 1;
 223     _current++;                 // skip the header
 224   }
 225   // The client will see the following relocInfo, whatever that is.
 226   // It is the reloc to which the preceding data applies.
 227 }
 228 
 229 
 230 void RelocIterator::initialize_misc() {
 231   set_has_current(false);
 232   for (int i = (int) CodeBuffer::SECT_FIRST; i < (int) CodeBuffer::SECT_LIMIT; i++) {
 233     _section_start[i] = nullptr;  // these will be lazily computed, if needed
 234     _section_end  [i] = nullptr;
 235   }
 236 }
 237 
 238 
 239 Relocation* RelocIterator::reloc() {
 240   // (take the "switch" out-of-line)
 241   relocInfo::relocType t = type();
 242   if (false) {}
 243   #define EACH_TYPE(name)                             \
 244   else if (t == relocInfo::name##_type) {             \
 245     return name##_reloc();                            \
 246   }
 247   APPLY_TO_RELOCATIONS(EACH_TYPE);
 248   #undef EACH_TYPE
 249   assert(t == relocInfo::none, "must be padding");
 250   _rh = RelocationHolder::none;
 251   return _rh.reloc();
 252 }
 253 
 254 // Verify all the destructors are trivial, so we don't need to worry about
 255 // destroying old contents of a RelocationHolder being assigned or destroyed.
 256 #define VERIFY_TRIVIALLY_DESTRUCTIBLE_AUX(Reloc) \
 257   static_assert(std::is_trivially_destructible<Reloc>::value, "must be");
 258 
 259 #define VERIFY_TRIVIALLY_DESTRUCTIBLE(name) \
 260   VERIFY_TRIVIALLY_DESTRUCTIBLE_AUX(PASTE_TOKENS(name, _Relocation));
 261 
 262 APPLY_TO_RELOCATIONS(VERIFY_TRIVIALLY_DESTRUCTIBLE)
 263 VERIFY_TRIVIALLY_DESTRUCTIBLE_AUX(Relocation)
 264 
 265 #undef VERIFY_TRIVIALLY_DESTRUCTIBLE_AUX
 266 #undef VERIFY_TRIVIALLY_DESTRUCTIBLE
 267 
 268 // Define all the copy_into functions.  These rely on all Relocation types
 269 // being trivially destructible (verified above).  So it doesn't matter
 270 // whether the target holder has been previously initialized or not.  There's
 271 // no need to consider that distinction and destruct the relocation in an
 272 // already initialized holder.
 273 #define DEFINE_COPY_INTO_AUX(Reloc)                             \
 274   void Reloc::copy_into(RelocationHolder& holder) const {       \
 275     copy_into_helper(*this, holder);                            \
 276   }
 277 
 278 #define DEFINE_COPY_INTO(name) \
 279   DEFINE_COPY_INTO_AUX(PASTE_TOKENS(name, _Relocation))
 280 
 281 APPLY_TO_RELOCATIONS(DEFINE_COPY_INTO)
 282 DEFINE_COPY_INTO_AUX(Relocation)
 283 
 284 #undef DEFINE_COPY_INTO_AUX
 285 #undef DEFINE_COPY_INTO
 286 
 287 //////// Methods for flyweight Relocation types
 288 
 289 // some relocations can compute their own values
 290 address Relocation::value() {
 291   ShouldNotReachHere();
 292   return nullptr;
 293 }
 294 
 295 
 296 void Relocation::set_value(address x) {
 297   ShouldNotReachHere();
 298 }
 299 
 300 void Relocation::const_set_data_value(address x) {
 301 #ifdef _LP64
 302   if (format() == relocInfo::narrow_oop_in_const) {
 303     *(narrowOop*)addr() = CompressedOops::encode(cast_to_oop(x));
 304   } else {
 305 #endif
 306     *(address*)addr() = x;
 307 #ifdef _LP64
 308   }
 309 #endif
 310 }
 311 
 312 void Relocation::const_verify_data_value(address x) {
 313 #ifdef _LP64
 314   if (format() == relocInfo::narrow_oop_in_const) {
 315     guarantee(*(narrowOop*)addr() == CompressedOops::encode(cast_to_oop(x)), "must agree");
 316   } else {
 317 #endif
 318     guarantee(*(address*)addr() == x, "must agree");
 319 #ifdef _LP64
 320   }
 321 #endif
 322 }
 323 
 324 
 325 RelocationHolder Relocation::spec_simple(relocInfo::relocType rtype) {
 326   if (rtype == relocInfo::none)  return RelocationHolder::none;
 327   relocInfo ri = relocInfo(rtype, 0);
 328   RelocIterator itr;
 329   itr.set_current(ri);
 330   itr.reloc();
 331   return itr._rh;
 332 }
 333 
 334 address Relocation::old_addr_for(address newa,
 335                                  const CodeBuffer* src, CodeBuffer* dest) {
 336   int sect = dest->section_index_of(newa);
 337   guarantee(sect != CodeBuffer::SECT_NONE, "lost track of this address");
 338   address ostart = src->code_section(sect)->start();
 339   address nstart = dest->code_section(sect)->start();
 340   return ostart + (newa - nstart);
 341 }
 342 
 343 address Relocation::new_addr_for(address olda,
 344                                  const CodeBuffer* src, CodeBuffer* dest) {
 345   debug_only(const CodeBuffer* src0 = src);
 346   int sect = CodeBuffer::SECT_NONE;
 347   // Look for olda in the source buffer, and all previous incarnations
 348   // if the source buffer has been expanded.
 349   for (; src != nullptr; src = src->before_expand()) {
 350     sect = src->section_index_of(olda);
 351     if (sect != CodeBuffer::SECT_NONE)  break;
 352   }
 353   guarantee(sect != CodeBuffer::SECT_NONE, "lost track of this address");
 354   address ostart = src->code_section(sect)->start();
 355   address nstart = dest->code_section(sect)->start();
 356   return nstart + (olda - ostart);
 357 }
 358 
 359 void Relocation::normalize_address(address& addr, const CodeSection* dest, bool allow_other_sections) {
 360   address addr0 = addr;
 361   if (addr0 == nullptr || dest->allocates2(addr0))  return;
 362   CodeBuffer* cb = dest->outer();
 363   addr = new_addr_for(addr0, cb, cb);
 364   assert(allow_other_sections || dest->contains2(addr),
 365          "addr must be in required section");
 366 }
 367 
 368 
 369 void CallRelocation::set_destination(address x) {
 370   pd_set_call_destination(x);
 371 }
 372 
 373 void CallRelocation::fix_relocation_after_move(const CodeBuffer* src, CodeBuffer* dest) {
 374   // Usually a self-relative reference to an external routine.
 375   // On some platforms, the reference is absolute (not self-relative).
 376   // The enhanced use of pd_call_destination sorts this all out.
 377   address orig_addr = old_addr_for(addr(), src, dest);
 378   address callee    = pd_call_destination(orig_addr);
 379   // Reassert the callee address, this time in the new copy of the code.
 380   pd_set_call_destination(callee);
 381 }
 382 
 383 
 384 #ifdef USE_TRAMPOLINE_STUB_FIX_OWNER
 385 void trampoline_stub_Relocation::fix_relocation_after_move(const CodeBuffer* src, CodeBuffer* dest) {
 386   // Finalize owner destination only for nmethods
 387   if (dest->blob() != nullptr) return;
 388   pd_fix_owner_after_move();
 389 }
 390 #endif
 391 
 392 //// pack/unpack methods
 393 
 394 void oop_Relocation::pack_data_to(CodeSection* dest) {
 395   short* p = (short*) dest->locs_end();
 396   p = pack_1_int_to(p, _oop_index);
 397   dest->set_locs_end((relocInfo*) p);
 398 }
 399 
 400 
 401 void oop_Relocation::unpack_data() {
 402   _oop_index = unpack_1_int();
 403 }
 404 
 405 void metadata_Relocation::pack_data_to(CodeSection* dest) {
 406   short* p = (short*) dest->locs_end();
 407   p = pack_1_int_to(p, _metadata_index);
 408   dest->set_locs_end((relocInfo*) p);
 409 }
 410 
 411 
 412 void metadata_Relocation::unpack_data() {
 413   _metadata_index = unpack_1_int();
 414 }
 415 
 416 
 417 void virtual_call_Relocation::pack_data_to(CodeSection* dest) {
 418   short*  p     = (short*) dest->locs_end();
 419   address point =          dest->locs_point();
 420 
 421   normalize_address(_cached_value, dest);
 422   jint x0 = scaled_offset_null_special(_cached_value, point);
 423   p = pack_2_ints_to(p, x0, _method_index);
 424   dest->set_locs_end((relocInfo*) p);
 425 }
 426 
 427 
 428 void virtual_call_Relocation::unpack_data() {
 429   jint x0 = 0;
 430   unpack_2_ints(x0, _method_index);
 431   address point = addr();
 432   _cached_value = x0==0? nullptr: address_from_scaled_offset(x0, point);
 433 }
 434 
 435 void runtime_call_w_cp_Relocation::pack_data_to(CodeSection * dest) {
 436   short* p = pack_1_int_to((short *)dest->locs_end(), (jint)(_offset >> 2));
 437   dest->set_locs_end((relocInfo*) p);
 438 }
 439 
 440 void runtime_call_w_cp_Relocation::unpack_data() {
 441   _offset = unpack_1_int() << 2;
 442 }
 443 
 444 void static_stub_Relocation::pack_data_to(CodeSection* dest) {
 445   short* p = (short*) dest->locs_end();
 446   CodeSection* insts = dest->outer()->insts();
 447   normalize_address(_static_call, insts);
 448   p = pack_1_int_to(p, scaled_offset(_static_call, insts->start()));
 449   dest->set_locs_end((relocInfo*) p);
 450 }
 451 
 452 void static_stub_Relocation::unpack_data() {
 453   address base = binding()->section_start(CodeBuffer::SECT_INSTS);
 454   jint offset = unpack_1_int();
 455   _static_call = address_from_scaled_offset(offset, base);
 456 }
 457 
 458 void trampoline_stub_Relocation::pack_data_to(CodeSection* dest ) {
 459   short* p = (short*) dest->locs_end();
 460   CodeSection* insts = dest->outer()->insts();
 461   normalize_address(_owner, insts);
 462   p = pack_1_int_to(p, scaled_offset(_owner, insts->start()));
 463   dest->set_locs_end((relocInfo*) p);
 464 }
 465 
 466 void trampoline_stub_Relocation::unpack_data() {
 467   address base = binding()->section_start(CodeBuffer::SECT_INSTS);
 468   _owner = address_from_scaled_offset(unpack_1_int(), base);
 469 }
 470 
 471 void external_word_Relocation::pack_data_to(CodeSection* dest) {
 472   short* p = (short*) dest->locs_end();
 473   int index = ExternalsRecorder::find_index(_target);
 474   p = pack_1_int_to(p, index);
 475   dest->set_locs_end((relocInfo*) p);
 476 }
 477 
 478 
 479 void external_word_Relocation::unpack_data() {
 480   int index = unpack_1_int();
 481   _target = ExternalsRecorder::at(index);
 482 }
 483 
 484 
 485 void internal_word_Relocation::pack_data_to(CodeSection* dest) {
 486   short* p = (short*) dest->locs_end();
 487   normalize_address(_target, dest, true);
 488 
 489   // Check whether my target address is valid within this section.
 490   // If not, strengthen the relocation type to point to another section.
 491   int sindex = _section;
 492   if (sindex == CodeBuffer::SECT_NONE && _target != nullptr
 493       && (!dest->allocates(_target) || _target == dest->locs_point())) {
 494     sindex = dest->outer()->section_index_of(_target);
 495     guarantee(sindex != CodeBuffer::SECT_NONE, "must belong somewhere");
 496     relocInfo* base = dest->locs_end() - 1;
 497     assert(base->type() == this->type(), "sanity");
 498     // Change the written type, to be section_word_type instead.
 499     base->set_type(relocInfo::section_word_type);
 500   }
 501 
 502   // Note: An internal_word relocation cannot refer to its own instruction,
 503   // because we reserve "0" to mean that the pointer itself is embedded
 504   // in the code stream.  We use a section_word relocation for such cases.
 505 
 506   if (sindex == CodeBuffer::SECT_NONE) {
 507     assert(type() == relocInfo::internal_word_type, "must be base class");
 508     guarantee(_target == nullptr || dest->allocates2(_target), "must be within the given code section");
 509     jint x0 = scaled_offset_null_special(_target, dest->locs_point());
 510     assert(!(x0 == 0 && _target != nullptr), "correct encoding of null target");
 511     p = pack_1_int_to(p, x0);
 512   } else {
 513     assert(_target != nullptr, "sanity");
 514     CodeSection* sect = dest->outer()->code_section(sindex);
 515     guarantee(sect->allocates2(_target), "must be in correct section");
 516     address base = sect->start();
 517     jint offset = scaled_offset(_target, base);
 518     assert((uint)sindex < (uint)CodeBuffer::SECT_LIMIT, "sanity");
 519     assert(CodeBuffer::SECT_LIMIT <= (1 << section_width), "section_width++");
 520     p = pack_1_int_to(p, (offset << section_width) | sindex);
 521   }
 522 
 523   dest->set_locs_end((relocInfo*) p);
 524 }
 525 
 526 
 527 void internal_word_Relocation::unpack_data() {
 528   jint x0 = unpack_1_int();
 529   _target = x0==0? nullptr: address_from_scaled_offset(x0, addr());
 530   _section = CodeBuffer::SECT_NONE;
 531 }
 532 
 533 
 534 void section_word_Relocation::unpack_data() {
 535   jint    x      = unpack_1_int();
 536   jint    offset = (x >> section_width);
 537   int     sindex = (x & ((1<<section_width)-1));
 538   address base   = binding()->section_start(sindex);
 539 
 540   _section = sindex;
 541   _target  = address_from_scaled_offset(offset, base);
 542 }
 543 
 544 //// miscellaneous methods
 545 oop* oop_Relocation::oop_addr() {
 546   int n = _oop_index;
 547   if (n == 0) {
 548     // oop is stored in the code stream
 549     return (oop*) pd_address_in_code();
 550   } else {
 551     // oop is stored in table at nmethod::oops_begin
 552     return code()->oop_addr_at(n);
 553   }
 554 }
 555 
 556 
 557 oop oop_Relocation::oop_value() {
 558   // clean inline caches store a special pseudo-null
 559   if (Universe::contains_non_oop_word(oop_addr())) {
 560     return nullptr;
 561   }
 562   return *oop_addr();
 563 }
 564 
 565 
 566 void oop_Relocation::fix_oop_relocation() {
 567   if (!oop_is_immediate()) {
 568     // get the oop from the pool, and re-insert it into the instruction:
 569     set_value(value());
 570   }
 571 }
 572 
 573 
 574 void oop_Relocation::verify_oop_relocation() {
 575   if (!oop_is_immediate()) {
 576     // get the oop from the pool, and re-insert it into the instruction:
 577     verify_value(value());
 578   }
 579 }
 580 
 581 // meta data versions
 582 Metadata** metadata_Relocation::metadata_addr() {
 583   int n = _metadata_index;
 584   if (n == 0) {
 585     // metadata is stored in the code stream
 586     return (Metadata**) pd_address_in_code();
 587     } else {
 588     // metadata is stored in table at nmethod::metadatas_begin
 589     return code()->metadata_addr_at(n);
 590     }
 591   }
 592 
 593 
 594 Metadata* metadata_Relocation::metadata_value() {
 595   Metadata* v = *metadata_addr();
 596   // clean inline caches store a special pseudo-null
 597   if (v == (Metadata*)Universe::non_oop_word())  v = nullptr;
 598   return v;
 599   }
 600 
 601 
 602 void metadata_Relocation::fix_metadata_relocation() {
 603   if (!metadata_is_immediate()) {
 604     // get the metadata from the pool, and re-insert it into the instruction:
 605     pd_fix_value(value());
 606   }
 607 }
 608 
 609 address virtual_call_Relocation::cached_value() {
 610   assert(_cached_value != nullptr && _cached_value < addr(), "must precede ic_call");
 611   return _cached_value;
 612 }
 613 
 614 Method* virtual_call_Relocation::method_value() {
 615   nmethod* nm = code();
 616   if (nm == nullptr) return (Method*)nullptr;
 617   Metadata* m = nm->metadata_at(_method_index);
 618   assert(m != nullptr || _method_index == 0, "should be non-null for non-zero index");
 619   assert(m == nullptr || m->is_method(), "not a method");
 620   return (Method*)m;
 621 }
 622 
 623 void virtual_call_Relocation::clear_inline_cache() {
 624   ResourceMark rm;
 625   CompiledIC* icache = CompiledIC_at(this);
 626   icache->set_to_clean();
 627 }
 628 
 629 
 630 void opt_virtual_call_Relocation::pack_data_to(CodeSection* dest) {
 631   short* p = (short*) dest->locs_end();
 632   p = pack_1_int_to(p, _method_index);
 633   dest->set_locs_end((relocInfo*) p);
 634 }
 635 
 636 void opt_virtual_call_Relocation::unpack_data() {
 637   _method_index = unpack_1_int();
 638 }
 639 
 640 Method* opt_virtual_call_Relocation::method_value() {
 641   nmethod* nm = code();
 642   if (nm == nullptr) return (Method*)nullptr;
 643   Metadata* m = nm->metadata_at(_method_index);
 644   assert(m != nullptr || _method_index == 0, "should be non-null for non-zero index");
 645   assert(m == nullptr || m->is_method(), "not a method");
 646   return (Method*)m;
 647 }
 648 
 649 void opt_virtual_call_Relocation::clear_inline_cache() {
 650   ResourceMark rm;
 651   CompiledDirectCall* callsite = CompiledDirectCall::at(this);
 652   callsite->set_to_clean();
 653 }
 654 
 655 address opt_virtual_call_Relocation::static_stub() {
 656   // search for the static stub who points back to this static call
 657   address static_call_addr = addr();
 658   RelocIterator iter(code());
 659   while (iter.next()) {
 660     if (iter.type() == relocInfo::static_stub_type) {
 661       static_stub_Relocation* stub_reloc = iter.static_stub_reloc();
 662       if (stub_reloc->static_call() == static_call_addr) {
 663         return iter.addr();
 664       }
 665     }
 666   }
 667   return nullptr;
 668 }
 669 
 670 Method* static_call_Relocation::method_value() {
 671   nmethod* nm = code();
 672   if (nm == nullptr) return (Method*)nullptr;
 673   Metadata* m = nm->metadata_at(_method_index);
 674   assert(m != nullptr || _method_index == 0, "should be non-null for non-zero index");
 675   assert(m == nullptr || m->is_method(), "not a method");
 676   return (Method*)m;
 677 }
 678 
 679 void static_call_Relocation::pack_data_to(CodeSection* dest) {
 680   short* p = (short*) dest->locs_end();
 681   p = pack_1_int_to(p, _method_index);
 682   dest->set_locs_end((relocInfo*) p);
 683 }
 684 
 685 void static_call_Relocation::unpack_data() {
 686   _method_index = unpack_1_int();
 687 }
 688 
 689 void static_call_Relocation::clear_inline_cache() {
 690   ResourceMark rm;
 691   CompiledDirectCall* callsite = CompiledDirectCall::at(this);
 692   callsite->set_to_clean();
 693 }
 694 
 695 
 696 address static_call_Relocation::static_stub() {
 697   // search for the static stub who points back to this static call
 698   address static_call_addr = addr();
 699   RelocIterator iter(code());
 700   while (iter.next()) {
 701     if (iter.type() == relocInfo::static_stub_type) {
 702       static_stub_Relocation* stub_reloc = iter.static_stub_reloc();
 703       if (stub_reloc->static_call() == static_call_addr) {
 704         return iter.addr();
 705       }
 706     }
 707   }
 708   return nullptr;
 709 }
 710 
 711 // Finds the trampoline address for a call. If no trampoline stub is
 712 // found nullptr is returned which can be handled by the caller.
 713 address trampoline_stub_Relocation::get_trampoline_for(address call, nmethod* code) {
 714   // There are no relocations available when the code gets relocated
 715   // because of CodeBuffer expansion.
 716   if (code->relocation_size() == 0)
 717     return nullptr;
 718 
 719   RelocIterator iter(code, call);
 720   while (iter.next()) {
 721     if (iter.type() == relocInfo::trampoline_stub_type) {
 722       if (iter.trampoline_stub_reloc()->owner() == call) {
 723         return iter.addr();
 724       }
 725     }
 726   }
 727 
 728   return nullptr;
 729 }
 730 
 731 void static_stub_Relocation::clear_inline_cache() {
 732   // Call stub is only used when calling the interpreted code.
 733   // It does not really need to be cleared, except that we want to clean out the methodoop.
 734   CompiledDirectCall::set_stub_to_clean(this);
 735 }
 736 
 737 
 738 void external_word_Relocation::fix_relocation_after_move(const CodeBuffer* src, CodeBuffer* dest) {
 739   if (_target != nullptr) {
 740     // Probably this reference is absolute,  not relative, so the following is
 741     // probably a no-op.
 742     set_value(_target);
 743   }
 744   // If target is nullptr, this is  an absolute embedded reference to an external
 745   // location, which means  there is nothing to fix here.  In either case, the
 746   // resulting target should be an "external" address.
 747   postcond(src->section_index_of(target()) == CodeBuffer::SECT_NONE);
 748   postcond(dest->section_index_of(target()) == CodeBuffer::SECT_NONE);
 749 }
 750 
 751 
 752 address external_word_Relocation::target() {
 753   address target = _target;
 754   if (target == nullptr) {
 755     target = pd_get_address_from_code();
 756   }
 757   return target;
 758 }
 759 
 760 
 761 void internal_word_Relocation::fix_relocation_after_move(const CodeBuffer* src, CodeBuffer* dest) {
 762   address target = _target;
 763   if (target == nullptr) {
 764     target = new_addr_for(this->target(), src, dest);
 765   }
 766   set_value(target);
 767 }
 768 
 769 
 770 address internal_word_Relocation::target() {
 771   address target = _target;
 772   if (target == nullptr) {
 773     if (addr_in_const()) {
 774       target = *(address*)addr();
 775     } else {
 776       target = pd_get_address_from_code();
 777     }
 778   }
 779   return target;
 780 }
 781 
 782 //---------------------------------------------------------------------------------
 783 // Non-product code
 784 
 785 #ifndef PRODUCT
 786 
 787 static const char* reloc_type_string(relocInfo::relocType t) {
 788   switch (t) {
 789   #define EACH_CASE(name) \
 790   case relocInfo::name##_type: \
 791     return #name;
 792 
 793   APPLY_TO_RELOCATIONS(EACH_CASE);
 794   #undef EACH_CASE
 795 
 796   case relocInfo::none:
 797     return "none";
 798   case relocInfo::data_prefix_tag:
 799     return "prefix";
 800   default:
 801     return "UNKNOWN RELOC TYPE";
 802   }
 803 }
 804 
 805 
 806 void RelocIterator::print_current() {
 807   if (!has_current()) {
 808     tty->print_cr("(no relocs)");
 809     return;
 810   }
 811   tty->print("relocInfo@" INTPTR_FORMAT " [type=%d(%s) addr=" INTPTR_FORMAT " offset=%d",
 812              p2i(_current), type(), reloc_type_string((relocInfo::relocType) type()), p2i(_addr), _current->addr_offset());
 813   if (current()->format() != 0)
 814     tty->print(" format=%d", current()->format());
 815   if (datalen() == 1) {
 816     tty->print(" data=%d", data()[0]);
 817   } else if (datalen() > 0) {
 818     tty->print(" data={");
 819     for (int i = 0; i < datalen(); i++) {
 820       tty->print("%04x", data()[i] & 0xFFFF);
 821     }
 822     tty->print("}");
 823   }
 824   tty->print("]");
 825   switch (type()) {
 826   case relocInfo::oop_type:
 827     {
 828       oop_Relocation* r = oop_reloc();
 829       oop* oop_addr  = nullptr;
 830       oop  raw_oop   = nullptr;
 831       oop  oop_value = nullptr;
 832       if (code() != nullptr || r->oop_is_immediate()) {
 833         oop_addr  = r->oop_addr();
 834         raw_oop   = *oop_addr;
 835         oop_value = r->oop_value();
 836       }
 837       tty->print(" | [oop_addr=" INTPTR_FORMAT " *=" INTPTR_FORMAT "]",
 838                  p2i(oop_addr), p2i(raw_oop));
 839       // Do not print the oop by default--we want this routine to
 840       // work even during GC or other inconvenient times.
 841       if (WizardMode && oop_value != nullptr) {
 842         tty->print("oop_value=" INTPTR_FORMAT ": ", p2i(oop_value));
 843         if (oopDesc::is_oop(oop_value)) {
 844           oop_value->print_value_on(tty);
 845         }
 846       }
 847       break;
 848     }
 849   case relocInfo::metadata_type:
 850     {
 851       metadata_Relocation* r = metadata_reloc();
 852       Metadata** metadata_addr  = nullptr;
 853       Metadata*    raw_metadata   = nullptr;
 854       Metadata*    metadata_value = nullptr;
 855       if (code() != nullptr || r->metadata_is_immediate()) {
 856         metadata_addr  = r->metadata_addr();
 857         raw_metadata   = *metadata_addr;
 858         metadata_value = r->metadata_value();
 859       }
 860       tty->print(" | [metadata_addr=" INTPTR_FORMAT " *=" INTPTR_FORMAT "]",
 861                  p2i(metadata_addr), p2i(raw_metadata));
 862       if (metadata_value != nullptr) {
 863         tty->print("metadata_value=" INTPTR_FORMAT ": ", p2i(metadata_value));
 864         metadata_value->print_value_on(tty);
 865       }
 866       break;
 867     }
 868   case relocInfo::external_word_type:
 869   case relocInfo::internal_word_type:
 870   case relocInfo::section_word_type:
 871     {
 872       DataRelocation* r = (DataRelocation*) reloc();
 873       tty->print(" | [target=" INTPTR_FORMAT "]", p2i(r->value())); //value==target
 874       break;
 875     }
 876   case relocInfo::static_call_type:
 877     {
 878       static_call_Relocation* r = (static_call_Relocation*) reloc();
 879       tty->print(" | [destination=" INTPTR_FORMAT " metadata=" INTPTR_FORMAT "]",
 880                  p2i(r->destination()), p2i(r->method_value()));
 881       CodeBlob* cb = CodeCache::find_blob(r->destination());
 882       if (cb != nullptr) {
 883         tty->print(" Blob::%s", cb->name());
 884       }
 885       break;
 886     }
 887   case relocInfo::runtime_call_type:
 888   case relocInfo::runtime_call_w_cp_type:
 889     {
 890       CallRelocation* r = (CallRelocation*) reloc();
 891       address dest = r->destination();
 892       tty->print(" | [destination=" INTPTR_FORMAT "]", p2i(dest));
 893       if (StubRoutines::contains(dest)) {
 894         StubCodeDesc* desc = StubCodeDesc::desc_for(dest);
 895         if (desc == nullptr) {
 896           desc = StubCodeDesc::desc_for(dest + frame::pc_return_offset);
 897         }
 898         if (desc != nullptr) {
 899           tty->print(" Stub::%s", desc->name());
 900         }
 901       } else {
 902         CodeBlob* cb = CodeCache::find_blob(dest);
 903         if (cb != nullptr) {
 904           tty->print(" %s", cb->name());
 905         } else {
 906           ResourceMark rm;
 907           const int buflen = 1024;
 908           char* buf = NEW_RESOURCE_ARRAY(char, buflen);
 909           int offset;
 910           if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {
 911             tty->print(" %s", buf);
 912             if (offset != 0) {
 913               tty->print("+%d", offset);
 914             }
 915           }
 916         }
 917       }
 918       break;
 919     }
 920   case relocInfo::virtual_call_type:
 921     {
 922       virtual_call_Relocation* r = (virtual_call_Relocation*) reloc();
 923       tty->print(" | [destination=" INTPTR_FORMAT " cached_value=" INTPTR_FORMAT " metadata=" INTPTR_FORMAT "]",
 924                  p2i(r->destination()), p2i(r->cached_value()), p2i(r->method_value()));
 925       CodeBlob* cb = CodeCache::find_blob(r->destination());
 926       if (cb != nullptr) {
 927         tty->print(" Blob::%s", cb->name());
 928       }
 929       break;
 930     }
 931   case relocInfo::static_stub_type:
 932     {
 933       static_stub_Relocation* r = (static_stub_Relocation*) reloc();
 934       tty->print(" | [static_call=" INTPTR_FORMAT "]", p2i(r->static_call()));
 935       break;
 936     }
 937   case relocInfo::trampoline_stub_type:
 938     {
 939       trampoline_stub_Relocation* r = (trampoline_stub_Relocation*) reloc();
 940       tty->print(" | [trampoline owner=" INTPTR_FORMAT "]", p2i(r->owner()));
 941       break;
 942     }
 943   case relocInfo::opt_virtual_call_type:
 944     {
 945       opt_virtual_call_Relocation* r = (opt_virtual_call_Relocation*) reloc();
 946       tty->print(" | [destination=" INTPTR_FORMAT " metadata=" INTPTR_FORMAT "]",
 947                  p2i(r->destination()), p2i(r->method_value()));
 948       CodeBlob* cb = CodeCache::find_blob(r->destination());
 949       if (cb != nullptr) {
 950         tty->print(" Blob::%s", cb->name());
 951       }
 952       break;
 953     }
 954   default:
 955     break;
 956   }
 957   tty->cr();
 958 }
 959 
 960 
 961 void RelocIterator::print() {
 962   RelocIterator save_this = (*this);
 963   relocInfo* scan = _current;
 964   if (!has_current())  scan += 1;  // nothing to scan here!
 965 
 966   bool skip_next = has_current();
 967   bool got_next;
 968   while (true) {
 969     got_next = (skip_next || next());
 970     skip_next = false;
 971 
 972     tty->print("         @" INTPTR_FORMAT ": ", p2i(scan));
 973     relocInfo* newscan = _current+1;
 974     if (!has_current())  newscan -= 1;  // nothing to scan here!
 975     while (scan < newscan) {
 976       tty->print("%04x", *(short*)scan & 0xFFFF);
 977       scan++;
 978     }
 979     tty->cr();
 980 
 981     if (!got_next)  break;
 982     print_current();
 983   }
 984 
 985   (*this) = save_this;
 986 }
 987 
 988 // For the debugger:
 989 extern "C"
 990 void print_blob_locs(nmethod* nm) {
 991   nm->print();
 992   RelocIterator iter(nm);
 993   iter.print();
 994 }
 995 extern "C"
 996 void print_buf_locs(CodeBuffer* cb) {
 997   FlagSetting fs(PrintRelocations, true);
 998   cb->print();
 999 }
1000 #endif // !PRODUCT