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)) ||
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 flyweight Relocation types
281 
282 // some relocations can compute their own values
283 address Relocation::value() {
284   ShouldNotReachHere();
285   return nullptr;
286 }
287 
288 
289 void Relocation::set_value(address x) {
290   ShouldNotReachHere();
291 }
292 
293 void Relocation::const_set_data_value(address x) {
294 #ifdef _LP64
295   if (format() == relocInfo::narrow_oop_in_const) {
296     *(narrowOop*)addr() = CompressedOops::encode(cast_to_oop(x));
297   } else {
298 #endif
299     *(address*)addr() = x;
300 #ifdef _LP64
301   }
302 #endif
303 }
304 
305 void Relocation::const_verify_data_value(address x) {
306 #ifdef _LP64
307   if (format() == relocInfo::narrow_oop_in_const) {
308     guarantee(*(narrowOop*)addr() == CompressedOops::encode(cast_to_oop(x)), "must agree");
309   } else {
310 #endif
311     guarantee(*(address*)addr() == x, "must agree");
312 #ifdef _LP64
313   }
314 #endif
315 }
316 
317 
318 RelocationHolder Relocation::spec_simple(relocInfo::relocType rtype) {
319   if (rtype == relocInfo::none)  return RelocationHolder::none;
320   relocInfo ri = relocInfo(rtype, 0);
321   RelocIterator itr;
322   itr.set_current(ri);
323   itr.reloc();
324   return itr._rh;
325 }
326 
327 address Relocation::old_addr_for(address newa,
328                                  const CodeBuffer* src, CodeBuffer* dest) {
329   int sect = dest->section_index_of(newa);
330   guarantee(sect != CodeBuffer::SECT_NONE, "lost track of this address");
331   address ostart = src->code_section(sect)->start();
332   address nstart = dest->code_section(sect)->start();
333   return ostart + (newa - nstart);
334 }
335 
336 address Relocation::new_addr_for(address olda,
337                                  const CodeBuffer* src, CodeBuffer* dest) {
338   debug_only(const CodeBuffer* src0 = src);
339   int sect = CodeBuffer::SECT_NONE;
340   // Look for olda in the source buffer, and all previous incarnations
341   // if the source buffer has been expanded.
342   for (; src != nullptr; src = src->before_expand()) {
343     sect = src->section_index_of(olda);
344     if (sect != CodeBuffer::SECT_NONE)  break;
345   }
346   guarantee(sect != CodeBuffer::SECT_NONE, "lost track of this address");
347   address ostart = src->code_section(sect)->start();
348   address nstart = dest->code_section(sect)->start();
349   return nstart + (olda - ostart);
350 }
351 
352 void Relocation::normalize_address(address& addr, const CodeSection* dest, bool allow_other_sections) {
353   address addr0 = addr;
354   if (addr0 == nullptr || dest->allocates2(addr0))  return;
355   CodeBuffer* cb = dest->outer();
356   addr = new_addr_for(addr0, cb, cb);
357   assert(allow_other_sections || dest->contains2(addr),
358          "addr must be in required section");
359 }
360 
361 
362 void CallRelocation::set_destination(address x) {
363   pd_set_call_destination(x);
364 }
365 
366 void CallRelocation::fix_relocation_after_move(const CodeBuffer* src, CodeBuffer* dest) {
367   // Usually a self-relative reference to an external routine.
368   // On some platforms, the reference is absolute (not self-relative).
369   // The enhanced use of pd_call_destination sorts this all out.
370   address orig_addr = old_addr_for(addr(), src, dest);
371   address callee    = pd_call_destination(orig_addr);
372   // Reassert the callee address, this time in the new copy of the code.
373   pd_set_call_destination(callee);
374 }
375 
376 
377 //// pack/unpack methods
378 
379 void oop_Relocation::pack_data_to(CodeSection* dest) {
380   short* p = (short*) dest->locs_end();
381   p = pack_1_int_to(p, _oop_index);
382   dest->set_locs_end((relocInfo*) p);
383 }
384 
385 
386 void oop_Relocation::unpack_data() {
387   _oop_index = unpack_1_int();
388 }
389 
390 void metadata_Relocation::pack_data_to(CodeSection* dest) {
391   short* p = (short*) dest->locs_end();
392   p = pack_1_int_to(p, _metadata_index);
393   dest->set_locs_end((relocInfo*) p);
394 }
395 
396 
397 void metadata_Relocation::unpack_data() {
398   _metadata_index = unpack_1_int();
399 }
400 
401 
402 void virtual_call_Relocation::pack_data_to(CodeSection* dest) {
403   short*  p     = (short*) dest->locs_end();
404   address point =          dest->locs_point();
405 
406   normalize_address(_cached_value, dest);
407   jint x0 = scaled_offset_null_special(_cached_value, point);
408   p = pack_2_ints_to(p, x0, _method_index);
409   dest->set_locs_end((relocInfo*) p);
410 }
411 
412 
413 void virtual_call_Relocation::unpack_data() {
414   jint x0 = 0;
415   unpack_2_ints(x0, _method_index);
416   address point = addr();
417   _cached_value = x0==0? nullptr: address_from_scaled_offset(x0, point);
418 }
419 
420 void runtime_call_w_cp_Relocation::pack_data_to(CodeSection * dest) {
421   short* p = pack_1_int_to((short *)dest->locs_end(), (jint)(_offset >> 2));
422   dest->set_locs_end((relocInfo*) p);
423 }
424 
425 void runtime_call_w_cp_Relocation::unpack_data() {
426   _offset = unpack_1_int() << 2;
427 }
428 
429 void static_stub_Relocation::pack_data_to(CodeSection* dest) {
430   short* p = (short*) dest->locs_end();
431   CodeSection* insts = dest->outer()->insts();
432   normalize_address(_static_call, insts);
433   p = pack_1_int_to(p, scaled_offset(_static_call, insts->start()));
434   dest->set_locs_end((relocInfo*) p);
435 }
436 
437 void static_stub_Relocation::unpack_data() {
438   address base = binding()->section_start(CodeBuffer::SECT_INSTS);
439   jint offset = unpack_1_int();
440   _static_call = address_from_scaled_offset(offset, base);
441 }
442 
443 void trampoline_stub_Relocation::pack_data_to(CodeSection* dest ) {
444   short* p = (short*) dest->locs_end();
445   CodeSection* insts = dest->outer()->insts();
446   normalize_address(_owner, insts);
447   p = pack_1_int_to(p, scaled_offset(_owner, insts->start()));
448   dest->set_locs_end((relocInfo*) p);
449 }
450 
451 void trampoline_stub_Relocation::unpack_data() {
452   address base = binding()->section_start(CodeBuffer::SECT_INSTS);
453   _owner = address_from_scaled_offset(unpack_1_int(), base);
454 }
455 
456 void external_word_Relocation::pack_data_to(CodeSection* dest) {
457   short* p = (short*) dest->locs_end();
458 #ifndef _LP64
459   p = pack_1_int_to(p, (int32_t) (intptr_t)_target);
460 #else
461   jlong t = (jlong) _target;
462   int32_t lo = low(t);
463   int32_t hi = high(t);
464   p = pack_2_ints_to(p, lo, hi);
465 #endif /* _LP64 */
466   dest->set_locs_end((relocInfo*) p);
467 }
468 
469 
470 void external_word_Relocation::unpack_data() {
471 #ifndef _LP64
472   _target = (address) (intptr_t)unpack_1_int();
473 #else
474   jint lo, hi;
475   unpack_2_ints(lo, hi);
476   jlong t = jlong_from(hi, lo);;
477   _target = (address) t;
478 #endif /* _LP64 */
479 }
480 
481 
482 void internal_word_Relocation::pack_data_to(CodeSection* dest) {
483   short* p = (short*) dest->locs_end();
484   normalize_address(_target, dest, true);
485 
486   // Check whether my target address is valid within this section.
487   // If not, strengthen the relocation type to point to another section.
488   int sindex = _section;
489   if (sindex == CodeBuffer::SECT_NONE && _target != nullptr
490       && (!dest->allocates(_target) || _target == dest->locs_point())) {
491     sindex = dest->outer()->section_index_of(_target);
492     guarantee(sindex != CodeBuffer::SECT_NONE, "must belong somewhere");
493     relocInfo* base = dest->locs_end() - 1;
494     assert(base->type() == this->type(), "sanity");
495     // Change the written type, to be section_word_type instead.
496     base->set_type(relocInfo::section_word_type);
497   }
498 
499   // Note: An internal_word relocation cannot refer to its own instruction,
500   // because we reserve "0" to mean that the pointer itself is embedded
501   // in the code stream.  We use a section_word relocation for such cases.
502 
503   if (sindex == CodeBuffer::SECT_NONE) {
504     assert(type() == relocInfo::internal_word_type, "must be base class");
505     guarantee(_target == nullptr || dest->allocates2(_target), "must be within the given code section");
506     jint x0 = scaled_offset_null_special(_target, dest->locs_point());
507     assert(!(x0 == 0 && _target != nullptr), "correct encoding of null target");
508     p = pack_1_int_to(p, x0);
509   } else {
510     assert(_target != nullptr, "sanity");
511     CodeSection* sect = dest->outer()->code_section(sindex);
512     guarantee(sect->allocates2(_target), "must be in correct section");
513     address base = sect->start();
514     jint offset = scaled_offset(_target, base);
515     assert((uint)sindex < (uint)CodeBuffer::SECT_LIMIT, "sanity");
516     assert(CodeBuffer::SECT_LIMIT <= (1 << section_width), "section_width++");
517     p = pack_1_int_to(p, (offset << section_width) | sindex);
518   }
519 
520   dest->set_locs_end((relocInfo*) p);
521 }
522 
523 
524 void internal_word_Relocation::unpack_data() {
525   jint x0 = unpack_1_int();
526   _target = x0==0? nullptr: address_from_scaled_offset(x0, addr());
527   _section = CodeBuffer::SECT_NONE;
528 }
529 
530 
531 void section_word_Relocation::unpack_data() {
532   jint    x      = unpack_1_int();
533   jint    offset = (x >> section_width);
534   int     sindex = (x & ((1<<section_width)-1));
535   address base   = binding()->section_start(sindex);
536 
537   _section = sindex;
538   _target  = address_from_scaled_offset(offset, base);
539 }
540 
541 //// miscellaneous methods
542 oop* oop_Relocation::oop_addr() {
543   int n = _oop_index;
544   if (n == 0) {
545     // oop is stored in the code stream
546     return (oop*) pd_address_in_code();
547   } else {
548     // oop is stored in table at nmethod::oops_begin
549     return code()->oop_addr_at(n);
550   }
551 }
552 
553 
554 oop oop_Relocation::oop_value() {
555   // clean inline caches store a special pseudo-null
556   if (Universe::contains_non_oop_word(oop_addr())) {
557     return nullptr;
558   }
559   return *oop_addr();
560 }
561 
562 
563 void oop_Relocation::fix_oop_relocation() {
564   if (!oop_is_immediate()) {
565     // get the oop from the pool, and re-insert it into the instruction:
566     set_value(value());
567   }
568 }
569 
570 
571 void oop_Relocation::verify_oop_relocation() {
572   if (!oop_is_immediate()) {
573     // get the oop from the pool, and re-insert it into the instruction:
574     verify_value(value());
575   }
576 }
577 
578 // meta data versions
579 Metadata** metadata_Relocation::metadata_addr() {
580   int n = _metadata_index;
581   if (n == 0) {
582     // metadata is stored in the code stream
583     return (Metadata**) pd_address_in_code();
584     } else {
585     // metadata is stored in table at nmethod::metadatas_begin
586     return code()->metadata_addr_at(n);
587     }
588   }
589 
590 
591 Metadata* metadata_Relocation::metadata_value() {
592   Metadata* v = *metadata_addr();
593   // clean inline caches store a special pseudo-null
594   if (v == (Metadata*)Universe::non_oop_word())  v = nullptr;
595   return v;
596   }
597 
598 
599 void metadata_Relocation::fix_metadata_relocation() {
600   if (!metadata_is_immediate()) {
601     // get the metadata from the pool, and re-insert it into the instruction:
602     pd_fix_value(value());
603   }
604 }
605 
606 address virtual_call_Relocation::cached_value() {
607   assert(_cached_value != nullptr && _cached_value < addr(), "must precede ic_call");
608   return _cached_value;
609 }
610 
611 Method* virtual_call_Relocation::method_value() {
612   nmethod* nm = code();
613   if (nm == nullptr) return (Method*)nullptr;
614   Metadata* m = nm->metadata_at(_method_index);
615   assert(m != nullptr || _method_index == 0, "should be non-null for non-zero index");
616   assert(m == nullptr || m->is_method(), "not a method");
617   return (Method*)m;
618 }
619 
620 void virtual_call_Relocation::clear_inline_cache() {
621   ResourceMark rm;
622   CompiledIC* icache = CompiledIC_at(this);
623   icache->set_to_clean();
624 }
625 
626 
627 void opt_virtual_call_Relocation::pack_data_to(CodeSection* dest) {
628   short* p = (short*) dest->locs_end();
629   p = pack_1_int_to(p, _method_index);
630   dest->set_locs_end((relocInfo*) p);
631 }
632 
633 void opt_virtual_call_Relocation::unpack_data() {
634   _method_index = unpack_1_int();
635 }
636 
637 Method* opt_virtual_call_Relocation::method_value() {
638   nmethod* nm = code();
639   if (nm == nullptr) return (Method*)nullptr;
640   Metadata* m = nm->metadata_at(_method_index);
641   assert(m != nullptr || _method_index == 0, "should be non-null for non-zero index");
642   assert(m == nullptr || m->is_method(), "not a method");
643   return (Method*)m;
644 }
645 
646 void opt_virtual_call_Relocation::clear_inline_cache() {
647   ResourceMark rm;
648   CompiledDirectCall* callsite = CompiledDirectCall::at(this);
649   callsite->set_to_clean();
650 }
651 
652 address opt_virtual_call_Relocation::static_stub() {
653   // search for the static stub who points back to this static call
654   address static_call_addr = addr();
655   RelocIterator iter(code());
656   while (iter.next()) {
657     if (iter.type() == relocInfo::static_stub_type) {
658       static_stub_Relocation* stub_reloc = iter.static_stub_reloc();
659       if (stub_reloc->static_call() == static_call_addr) {
660         return iter.addr();
661       }
662     }
663   }
664   return nullptr;
665 }
666 
667 Method* static_call_Relocation::method_value() {
668   nmethod* nm = code();
669   if (nm == nullptr) return (Method*)nullptr;
670   Metadata* m = nm->metadata_at(_method_index);
671   assert(m != nullptr || _method_index == 0, "should be non-null for non-zero index");
672   assert(m == nullptr || m->is_method(), "not a method");
673   return (Method*)m;
674 }
675 
676 void static_call_Relocation::pack_data_to(CodeSection* dest) {
677   short* p = (short*) dest->locs_end();
678   p = pack_1_int_to(p, _method_index);
679   dest->set_locs_end((relocInfo*) p);
680 }
681 
682 void static_call_Relocation::unpack_data() {
683   _method_index = unpack_1_int();
684 }
685 
686 void static_call_Relocation::clear_inline_cache() {
687   ResourceMark rm;
688   CompiledDirectCall* callsite = CompiledDirectCall::at(this);
689   callsite->set_to_clean();
690 }
691 
692 
693 address static_call_Relocation::static_stub() {
694   // search for the static stub who points back to this static call
695   address static_call_addr = addr();
696   RelocIterator iter(code());
697   while (iter.next()) {
698     if (iter.type() == relocInfo::static_stub_type) {
699       static_stub_Relocation* stub_reloc = iter.static_stub_reloc();
700       if (stub_reloc->static_call() == static_call_addr) {
701         return iter.addr();
702       }
703     }
704   }
705   return nullptr;
706 }
707 
708 // Finds the trampoline address for a call. If no trampoline stub is
709 // found nullptr is returned which can be handled by the caller.
710 address trampoline_stub_Relocation::get_trampoline_for(address call, nmethod* code) {
711   // There are no relocations available when the code gets relocated
712   // because of CodeBuffer expansion.
713   if (code->relocation_size() == 0)
714     return nullptr;
715 
716   RelocIterator iter(code, call);
717   while (iter.next()) {
718     if (iter.type() == relocInfo::trampoline_stub_type) {
719       if (iter.trampoline_stub_reloc()->owner() == call) {
720         return iter.addr();
721       }
722     }
723   }
724 
725   return nullptr;
726 }
727 
728 void static_stub_Relocation::clear_inline_cache() {
729   // Call stub is only used when calling the interpreted code.
730   // It does not really need to be cleared, except that we want to clean out the methodoop.
731   CompiledDirectCall::set_stub_to_clean(this);
732 }
733 
734 
735 void external_word_Relocation::fix_relocation_after_move(const CodeBuffer* src, CodeBuffer* dest) {
736   if (_target != nullptr) {
737     // Probably this reference is absolute,  not relative, so the following is
738     // probably a no-op.
739     set_value(_target);
740   }
741   // If target is nullptr, this is  an absolute embedded reference to an external
742   // location, which means  there is nothing to fix here.  In either case, the
743   // resulting target should be an "external" address.
744   postcond(src->section_index_of(target()) == CodeBuffer::SECT_NONE);
745   postcond(dest->section_index_of(target()) == CodeBuffer::SECT_NONE);
746 }
747 
748 
749 address external_word_Relocation::target() {
750   address target = _target;
751   if (target == nullptr) {
752     target = pd_get_address_from_code();
753   }
754   return target;
755 }
756 
757 
758 void internal_word_Relocation::fix_relocation_after_move(const CodeBuffer* src, CodeBuffer* dest) {
759   address target = _target;
760   if (target == nullptr) {
761     target = new_addr_for(this->target(), src, dest);
762   }
763   set_value(target);
764 }
765 
766 
767 address internal_word_Relocation::target() {
768   address target = _target;
769   if (target == nullptr) {
770     if (addr_in_const()) {
771       target = *(address*)addr();
772     } else {
773       target = pd_get_address_from_code();
774     }
775   }
776   return target;
777 }
778 
779 //---------------------------------------------------------------------------------
780 // Non-product code
781 
782 #ifndef PRODUCT
783 
784 static const char* reloc_type_string(relocInfo::relocType t) {
785   switch (t) {
786   #define EACH_CASE(name) \
787   case relocInfo::name##_type: \
788     return #name;
789 
790   APPLY_TO_RELOCATIONS(EACH_CASE);
791   #undef EACH_CASE
792 
793   case relocInfo::none:
794     return "none";
795   case relocInfo::data_prefix_tag:
796     return "prefix";
797   default:
798     return "UNKNOWN RELOC TYPE";
799   }
800 }
801 
802 
803 void RelocIterator::print_current() {
804   if (!has_current()) {
805     tty->print_cr("(no relocs)");
806     return;
807   }
808   tty->print("relocInfo@" INTPTR_FORMAT " [type=%d(%s) addr=" INTPTR_FORMAT " offset=%d",
809              p2i(_current), type(), reloc_type_string((relocInfo::relocType) type()), p2i(_addr), _current->addr_offset());
810   if (current()->format() != 0)
811     tty->print(" format=%d", current()->format());
812   if (datalen() == 1) {
813     tty->print(" data=%d", data()[0]);
814   } else if (datalen() > 0) {
815     tty->print(" data={");
816     for (int i = 0; i < datalen(); i++) {
817       tty->print("%04x", data()[i] & 0xFFFF);
818     }
819     tty->print("}");
820   }
821   tty->print("]");
822   switch (type()) {
823   case relocInfo::oop_type:
824     {
825       oop_Relocation* r = oop_reloc();
826       oop* oop_addr  = nullptr;
827       oop  raw_oop   = nullptr;
828       oop  oop_value = nullptr;
829       if (code() != nullptr || r->oop_is_immediate()) {
830         oop_addr  = r->oop_addr();
831         raw_oop   = *oop_addr;
832         oop_value = r->oop_value();
833       }
834       tty->print(" | [oop_addr=" INTPTR_FORMAT " *=" INTPTR_FORMAT "]",
835                  p2i(oop_addr), p2i(raw_oop));
836       // Do not print the oop by default--we want this routine to
837       // work even during GC or other inconvenient times.
838       if (WizardMode && oop_value != nullptr) {
839         tty->print("oop_value=" INTPTR_FORMAT ": ", p2i(oop_value));
840         if (oopDesc::is_oop(oop_value)) {
841           oop_value->print_value_on(tty);
842         }
843       }
844       break;
845     }
846   case relocInfo::metadata_type:
847     {
848       metadata_Relocation* r = metadata_reloc();
849       Metadata** metadata_addr  = nullptr;
850       Metadata*    raw_metadata   = nullptr;
851       Metadata*    metadata_value = nullptr;
852       if (code() != nullptr || r->metadata_is_immediate()) {
853         metadata_addr  = r->metadata_addr();
854         raw_metadata   = *metadata_addr;
855         metadata_value = r->metadata_value();
856       }
857       tty->print(" | [metadata_addr=" INTPTR_FORMAT " *=" INTPTR_FORMAT "]",
858                  p2i(metadata_addr), p2i(raw_metadata));
859       if (metadata_value != nullptr) {
860         tty->print("metadata_value=" INTPTR_FORMAT ": ", p2i(metadata_value));
861         metadata_value->print_value_on(tty);
862       }
863       break;
864     }
865   case relocInfo::external_word_type:
866   case relocInfo::internal_word_type:
867   case relocInfo::section_word_type:
868     {
869       DataRelocation* r = (DataRelocation*) reloc();
870       tty->print(" | [target=" INTPTR_FORMAT "]", p2i(r->value())); //value==target
871       break;
872     }
873   case relocInfo::static_call_type:
874     {
875       static_call_Relocation* r = (static_call_Relocation*) reloc();
876       tty->print(" | [destination=" INTPTR_FORMAT " metadata=" INTPTR_FORMAT "]",
877                  p2i(r->destination()), p2i(r->method_value()));
878       break;
879     }
880   case relocInfo::runtime_call_type:
881   case relocInfo::runtime_call_w_cp_type:
882     {
883       CallRelocation* r = (CallRelocation*) reloc();
884       tty->print(" | [destination=" INTPTR_FORMAT "]", p2i(r->destination()));
885       break;
886     }
887   case relocInfo::virtual_call_type:
888     {
889       virtual_call_Relocation* r = (virtual_call_Relocation*) reloc();
890       tty->print(" | [destination=" INTPTR_FORMAT " cached_value=" INTPTR_FORMAT " metadata=" INTPTR_FORMAT "]",
891                  p2i(r->destination()), p2i(r->cached_value()), p2i(r->method_value()));
892       break;
893     }
894   case relocInfo::static_stub_type:
895     {
896       static_stub_Relocation* r = (static_stub_Relocation*) reloc();
897       tty->print(" | [static_call=" INTPTR_FORMAT "]", p2i(r->static_call()));
898       break;
899     }
900   case relocInfo::trampoline_stub_type:
901     {
902       trampoline_stub_Relocation* r = (trampoline_stub_Relocation*) reloc();
903       tty->print(" | [trampoline owner=" INTPTR_FORMAT "]", p2i(r->owner()));
904       break;
905     }
906   case relocInfo::opt_virtual_call_type:
907     {
908       opt_virtual_call_Relocation* r = (opt_virtual_call_Relocation*) reloc();
909       tty->print(" | [destination=" INTPTR_FORMAT " metadata=" INTPTR_FORMAT "]",
910                  p2i(r->destination()), p2i(r->method_value()));
911       break;
912     }
913   default:
914     break;
915   }
916   tty->cr();
917 }
918 
919 
920 void RelocIterator::print() {
921   RelocIterator save_this = (*this);
922   relocInfo* scan = _current;
923   if (!has_current())  scan += 1;  // nothing to scan here!
924 
925   bool skip_next = has_current();
926   bool got_next;
927   while (true) {
928     got_next = (skip_next || next());
929     skip_next = false;
930 
931     tty->print("         @" INTPTR_FORMAT ": ", p2i(scan));
932     relocInfo* newscan = _current+1;
933     if (!has_current())  newscan -= 1;  // nothing to scan here!
934     while (scan < newscan) {
935       tty->print("%04x", *(short*)scan & 0xFFFF);
936       scan++;
937     }
938     tty->cr();
939 
940     if (!got_next)  break;
941     print_current();
942   }
943 
944   (*this) = save_this;
945 }
946 
947 // For the debugger:
948 extern "C"
949 void print_blob_locs(nmethod* nm) {
950   nm->print();
951   RelocIterator iter(nm);
952   iter.print();
953 }
954 extern "C"
955 void print_buf_locs(CodeBuffer* cb) {
956   FlagSetting fs(PrintRelocations, true);
957   cb->print();
958 }
959 #endif // !PRODUCT