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