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