1 /*
   2  * Copyright (c) 1998, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "code/aotCodeCache.hpp"
  26 #include "code/codeBlob.hpp"
  27 #include "code/codeCache.hpp"
  28 #include "code/relocInfo.hpp"
  29 #include "code/vtableStubs.hpp"
  30 #include "compiler/disassembler.hpp"
  31 #include "compiler/oopMap.hpp"
  32 #include "cppstdlib/type_traits.hpp"
  33 #include "interpreter/bytecode.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "jvm.h"
  36 #include "memory/allocation.inline.hpp"
  37 #include "memory/heap.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "oops/oop.inline.hpp"
  40 #include "prims/forte.hpp"
  41 #include "prims/jvmtiExport.hpp"
  42 #include "runtime/handles.inline.hpp"
  43 #include "runtime/icache.hpp"
  44 #include "runtime/interfaceSupport.inline.hpp"
  45 #include "runtime/javaFrameAnchor.hpp"
  46 #include "runtime/jniHandles.inline.hpp"
  47 #include "runtime/mutexLocker.hpp"
  48 #include "runtime/safepoint.hpp"
  49 #include "runtime/sharedRuntime.hpp"
  50 #include "runtime/stubCodeGenerator.hpp"
  51 #include "runtime/stubRoutines.hpp"
  52 #include "runtime/vframe.hpp"
  53 #include "services/memoryService.hpp"
  54 #include "utilities/align.hpp"
  55 #ifdef COMPILER1
  56 #include "c1/c1_Runtime1.hpp"
  57 #endif
  58 
  59 // Virtual methods are not allowed in code blobs to simplify caching compiled code.
  60 // Check all "leaf" subclasses of CodeBlob class.
  61 
  62 static_assert(!std::is_polymorphic<nmethod>::value,            "no virtual methods are allowed in nmethod");
  63 static_assert(!std::is_polymorphic<AdapterBlob>::value,        "no virtual methods are allowed in code blobs");
  64 static_assert(!std::is_polymorphic<VtableBlob>::value,         "no virtual methods are allowed in code blobs");
  65 static_assert(!std::is_polymorphic<MethodHandlesAdapterBlob>::value, "no virtual methods are allowed in code blobs");
  66 static_assert(!std::is_polymorphic<RuntimeStub>::value,        "no virtual methods are allowed in code blobs");
  67 static_assert(!std::is_polymorphic<BufferedInlineTypeBlob>::value,   "no virtual methods are allowed in code blobs");
  68 static_assert(!std::is_polymorphic<DeoptimizationBlob>::value, "no virtual methods are allowed in code blobs");
  69 static_assert(!std::is_polymorphic<SafepointBlob>::value,      "no virtual methods are allowed in code blobs");
  70 static_assert(!std::is_polymorphic<UpcallStub>::value,         "no virtual methods are allowed in code blobs");
  71 #ifdef COMPILER2
  72 static_assert(!std::is_polymorphic<ExceptionBlob>::value,      "no virtual methods are allowed in code blobs");
  73 static_assert(!std::is_polymorphic<UncommonTrapBlob>::value,   "no virtual methods are allowed in code blobs");
  74 #endif
  75 
  76 // Add proxy vtables.
  77 // We need only few for now - they are used only from prints.
  78 const nmethod::Vptr                  nmethod::_vpntr;
  79 const BufferBlob::Vptr               BufferBlob::_vpntr;
  80 const RuntimeStub::Vptr              RuntimeStub::_vpntr;
  81 const SingletonBlob::Vptr            SingletonBlob::_vpntr;
  82 const DeoptimizationBlob::Vptr       DeoptimizationBlob::_vpntr;
  83 const SafepointBlob::Vptr            SafepointBlob::_vpntr;
  84 #ifdef COMPILER2
  85 const ExceptionBlob::Vptr            ExceptionBlob::_vpntr;
  86 const UncommonTrapBlob::Vptr         UncommonTrapBlob::_vpntr;
  87 #endif // COMPILER2
  88 const UpcallStub::Vptr               UpcallStub::_vpntr;
  89 
  90 const CodeBlob::Vptr* CodeBlob::vptr(CodeBlobKind kind) {
  91   constexpr const CodeBlob::Vptr* array[(size_t)CodeBlobKind::Number_Of_Kinds] = {
  92       nullptr/* None */,
  93       &nmethod::_vpntr,
  94       &BufferBlob::_vpntr,
  95       &AdapterBlob::_vpntr,
  96       &VtableBlob::_vpntr,
  97       &MethodHandlesAdapterBlob::_vpntr,
  98       &BufferedInlineTypeBlob::_vpntr,
  99       &RuntimeStub::_vpntr,
 100       &DeoptimizationBlob::_vpntr,
 101       &SafepointBlob::_vpntr,
 102 #ifdef COMPILER2
 103       &ExceptionBlob::_vpntr,
 104       &UncommonTrapBlob::_vpntr,
 105 #endif
 106       &UpcallStub::_vpntr
 107   };
 108 
 109   return array[(size_t)kind];
 110 }
 111 
 112 const CodeBlob::Vptr* CodeBlob::vptr() const {
 113   return vptr(_kind);
 114 }
 115 
 116 unsigned int CodeBlob::align_code_offset(int offset) {
 117   // align the size to CodeEntryAlignment
 118   int header_size = (int)CodeHeap::header_size();
 119   return align_up(offset + header_size, CodeEntryAlignment) - header_size;
 120 }
 121 
 122 // This must be consistent with the CodeBlob constructor's layout actions.
 123 unsigned int CodeBlob::allocation_size(CodeBuffer* cb, int header_size) {
 124   // align the size to CodeEntryAlignment
 125   unsigned int size = align_code_offset(header_size);
 126   size += align_up(cb->total_content_size(), oopSize);
 127   size += align_up(cb->total_oop_size(), oopSize);
 128   return size;
 129 }
 130 
 131 CodeBlob::CodeBlob(const char* name, CodeBlobKind kind, CodeBuffer* cb, int size, uint16_t header_size,
 132                    int16_t frame_complete_offset, int frame_size, OopMapSet* oop_maps, bool caller_must_gc_arguments,
 133                    int mutable_data_size) :
 134   _oop_maps(nullptr), // will be set by set_oop_maps() call
 135   _name(name),
 136   _mutable_data(header_begin() + size), // default value is blob_end()
 137   _size(size),
 138   _relocation_size(align_up(cb->total_relocation_size(), oopSize)),
 139   _content_offset(CodeBlob::align_code_offset(header_size)),
 140   _code_offset(_content_offset + cb->total_offset_of(cb->insts())),
 141   _data_offset(_content_offset + align_up(cb->total_content_size(), oopSize)),
 142   _frame_size(frame_size),
 143   _mutable_data_size(mutable_data_size),
 144   S390_ONLY(_ctable_offset(0) COMMA)
 145   _header_size(header_size),
 146   _frame_complete_offset(frame_complete_offset),
 147   _kind(kind),
 148   _caller_must_gc_arguments(caller_must_gc_arguments)
 149 {
 150   assert(is_aligned(_size,            oopSize), "unaligned size");
 151   assert(is_aligned(header_size,      oopSize), "unaligned size");
 152   assert(is_aligned(_relocation_size, oopSize), "unaligned size");
 153   assert(_data_offset <= _size, "codeBlob is too small: %d > %d", _data_offset, _size);
 154   assert(is_nmethod() || (cb->total_oop_size() + cb->total_metadata_size() == 0), "must be nmethod");
 155   assert(code_end() == content_end(), "must be the same - see code_end()");
 156 #ifdef COMPILER1
 157   // probably wrong for tiered
 158   assert(_frame_size >= -1, "must use frame size or -1 for runtime stubs");
 159 #endif // COMPILER1
 160 
 161   if (_mutable_data_size > 0) {
 162     _mutable_data = (address)os::malloc(_mutable_data_size, mtCode);
 163     if (_mutable_data == nullptr) {
 164       vm_exit_out_of_memory(_mutable_data_size, OOM_MALLOC_ERROR, "codebuffer: no space for mutable data");
 165     }
 166   } else {
 167     // We need unique and valid not null address
 168     assert(_mutable_data == blob_end(), "sanity");
 169   }
 170 
 171   set_oop_maps(oop_maps);
 172 }
 173 
 174 // Simple CodeBlob used for simple BufferBlob.
 175 CodeBlob::CodeBlob(const char* name, CodeBlobKind kind, int size, uint16_t header_size) :
 176   _oop_maps(nullptr),
 177   _name(name),
 178   _mutable_data(header_begin() + size), // default value is blob_end()
 179   _size(size),
 180   _relocation_size(0),
 181   _content_offset(CodeBlob::align_code_offset(header_size)),
 182   _code_offset(_content_offset),
 183   _data_offset(size),
 184   _frame_size(0),
 185   _mutable_data_size(0),
 186   S390_ONLY(_ctable_offset(0) COMMA)
 187   _header_size(header_size),
 188   _frame_complete_offset(CodeOffsets::frame_never_safe),
 189   _kind(kind),
 190   _caller_must_gc_arguments(false)
 191 {
 192   assert(is_aligned(size,            oopSize), "unaligned size");
 193   assert(is_aligned(header_size,     oopSize), "unaligned size");
 194   assert(_mutable_data == blob_end(), "sanity");
 195 }
 196 
 197 void CodeBlob::purge() {
 198   assert(_mutable_data != nullptr, "should never be null");
 199   if (_mutable_data != blob_end()) {
 200     os::free(_mutable_data);
 201     _mutable_data = blob_end(); // Valid not null address
 202     _mutable_data_size = 0;
 203     _relocation_size = 0;
 204   }
 205   if (_oop_maps != nullptr) {
 206     delete _oop_maps;
 207     _oop_maps = nullptr;
 208   }
 209   NOT_PRODUCT(_asm_remarks.clear());
 210   NOT_PRODUCT(_dbg_strings.clear());
 211 }
 212 
 213 void CodeBlob::set_oop_maps(OopMapSet* p) {
 214   // Danger Will Robinson! This method allocates a big
 215   // chunk of memory, its your job to free it.
 216   if (p != nullptr) {
 217     _oop_maps = ImmutableOopMapSet::build_from(p);
 218   } else {
 219     _oop_maps = nullptr;
 220   }
 221 }
 222 
 223 const ImmutableOopMap* CodeBlob::oop_map_for_return_address(address return_address) const {
 224   assert(_oop_maps != nullptr, "nope");
 225   return _oop_maps->find_map_at_offset((intptr_t) return_address - (intptr_t) code_begin());
 226 }
 227 
 228 void CodeBlob::print_code_on(outputStream* st) {
 229   ResourceMark m;
 230   Disassembler::decode(this, st);
 231 }
 232 
 233 #if INCLUDE_CDS
 234 void CodeBlob::restore_mutable_data(address reloc_data) {
 235   // Relocation data is now stored as part of the mutable data area; allocate it before copy relocations
 236   if (_mutable_data_size > 0) {
 237     _mutable_data = (address)os::malloc(_mutable_data_size, mtCode);
 238     if (_mutable_data == nullptr) {
 239       vm_exit_out_of_memory(_mutable_data_size, OOM_MALLOC_ERROR, "codebuffer: no space for mutable data");
 240     }
 241   } else {
 242     _mutable_data = blob_end(); // default value
 243   }
 244   if (_relocation_size > 0) {
 245     assert(_mutable_data_size > 0, "relocation is part of mutable data section");
 246     memcpy((address)relocation_begin(), reloc_data, relocation_size());
 247   }
 248 }
 249 
 250 void CodeBlob::prepare_for_archiving_impl() {
 251   set_name(nullptr);
 252   _oop_maps = nullptr;
 253   _mutable_data = nullptr;
 254 #ifndef PRODUCT
 255   asm_remarks().clear();
 256   dbg_strings().clear();
 257 #endif /* PRODUCT */
 258 }
 259 
 260 void CodeBlob::prepare_for_archiving() {
 261   vptr(_kind)->prepare_for_archiving(this);
 262 }
 263 
 264 void CodeBlob::archive_blob(CodeBlob* blob, address archive_buffer) {
 265   blob->copy_to(archive_buffer);
 266   CodeBlob* archived_blob = (CodeBlob*)archive_buffer;
 267   archived_blob->prepare_for_archiving();
 268 }
 269 
 270 void CodeBlob::post_restore_impl() {
 271   // Track memory usage statistic after releasing CodeCache_lock
 272   MemoryService::track_code_cache_memory_usage();
 273 }
 274 
 275 void CodeBlob::post_restore() {
 276   vptr(_kind)->post_restore(this);
 277 }
 278 
 279 CodeBlob* CodeBlob::restore(address code_cache_buffer, AOTCodeReader* reader)
 280 {
 281   copy_to(code_cache_buffer);
 282   CodeBlob* code_blob = (CodeBlob*)code_cache_buffer;
 283   reader->restore(code_blob);
 284   return code_blob;
 285 }
 286 
 287 CodeBlob* CodeBlob::create(CodeBlob* archived_blob, AOTCodeReader* reader)
 288 {
 289   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 290 
 291   CodeCache::gc_on_allocation();
 292 
 293   CodeBlob* blob = nullptr;
 294   unsigned int size = archived_blob->size();
 295   {
 296     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 297     address code_cache_buffer = (address)CodeCache::allocate(size, CodeBlobType::NonNMethod);
 298     if (code_cache_buffer != nullptr) {
 299       blob = archived_blob->restore(code_cache_buffer, reader);
 300       assert(blob != nullptr, "sanity check");
 301 
 302       // Flush the code block
 303       ICache::invalidate_range(blob->code_begin(), blob->code_size());
 304       CodeCache::commit(blob); // Count adapters
 305     }
 306   }
 307   if (blob != nullptr) {
 308     blob->post_restore();
 309   }
 310   return blob;
 311 }
 312 
 313 #endif // INCLUDE_CDS
 314 
 315 //-----------------------------------------------------------------------------------------
 316 // Creates a RuntimeBlob from a CodeBuffer and copy code and relocation info.
 317 
 318 RuntimeBlob::RuntimeBlob(
 319   const char* name,
 320   CodeBlobKind kind,
 321   CodeBuffer* cb,
 322   int         size,
 323   uint16_t    header_size,
 324   int16_t     frame_complete,
 325   int         frame_size,
 326   OopMapSet*  oop_maps,
 327   bool        caller_must_gc_arguments)
 328   : CodeBlob(name, kind, cb, size, header_size, frame_complete, frame_size, oop_maps, caller_must_gc_arguments,
 329              align_up(cb->total_relocation_size(), oopSize))
 330 {
 331   if (code_size() == 0) {
 332     // Nothing to copy
 333     return;
 334   }
 335 
 336   cb->copy_code_and_locs_to(this);
 337 
 338   // Flush generated code
 339   ICache::invalidate_range(code_begin(), code_size());
 340 }
 341 
 342 void RuntimeBlob::free(RuntimeBlob* blob) {
 343   assert(blob != nullptr, "caller must check for nullptr");
 344   MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
 345   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 346   blob->purge();
 347   {
 348     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 349     CodeCache::free(blob);
 350   }
 351   // Track memory usage statistic after releasing CodeCache_lock
 352   MemoryService::track_code_cache_memory_usage();
 353 }
 354 
 355 void RuntimeBlob::trace_new_stub(RuntimeBlob* stub, const char* name1, const char* name2) {
 356   // Do not hold the CodeCache lock during name formatting.
 357   assert(!CodeCache_lock->owned_by_self(), "release CodeCache before registering the stub");
 358 
 359   if (stub != nullptr && (PrintStubCode ||
 360                        Forte::is_enabled() ||
 361                        JvmtiExport::should_post_dynamic_code_generated())) {
 362     char stub_id[256];
 363     assert(strlen(name1) + strlen(name2) < sizeof(stub_id), "");
 364     jio_snprintf(stub_id, sizeof(stub_id), "%s%s", name1, name2);
 365     if (PrintStubCode) {
 366       ttyLocker ttyl;
 367       tty->print_cr("- - - [BEGIN] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
 368       tty->print_cr("Decoding %s " PTR_FORMAT " [" PTR_FORMAT ", " PTR_FORMAT "] (%d bytes)",
 369                     stub_id, p2i(stub), p2i(stub->code_begin()), p2i(stub->code_end()), stub->code_size());
 370       Disassembler::decode(stub->code_begin(), stub->code_end(), tty
 371                            NOT_PRODUCT(COMMA &stub->asm_remarks()));
 372       if ((stub->oop_maps() != nullptr) && AbstractDisassembler::show_structs()) {
 373         tty->print_cr("- - - [OOP MAPS]- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
 374         stub->oop_maps()->print();
 375       }
 376       tty->print_cr("- - - [END] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
 377       tty->cr();
 378     }
 379     if (Forte::is_enabled()) {
 380       Forte::register_stub(stub_id, stub->code_begin(), stub->code_end());
 381     }
 382 
 383     if (JvmtiExport::should_post_dynamic_code_generated()) {
 384       const char* stub_name = name2;
 385       if (name2[0] == '\0')  stub_name = name1;
 386       JvmtiExport::post_dynamic_code_generated(stub_name, stub->code_begin(), stub->code_end());
 387     }
 388   }
 389 
 390   // Track memory usage statistic after releasing CodeCache_lock
 391   MemoryService::track_code_cache_memory_usage();
 392 }
 393 
 394 //----------------------------------------------------------------------------------------------------
 395 // Implementation of BufferBlob
 396 
 397 BufferBlob::BufferBlob(const char* name, CodeBlobKind kind, int size, uint16_t header_size)
 398   : RuntimeBlob(name, kind, size, header_size)
 399 {}
 400 
 401 BufferBlob* BufferBlob::create(const char* name, uint buffer_size) {
 402   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 403 
 404   BufferBlob* blob = nullptr;
 405   unsigned int size = sizeof(BufferBlob);
 406   // align the size to CodeEntryAlignment
 407   size = CodeBlob::align_code_offset(size);
 408   size += align_up(buffer_size, oopSize);
 409   assert(name != nullptr, "must provide a name");
 410   {
 411     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 412     blob = new (size) BufferBlob(name, CodeBlobKind::Buffer, size);
 413   }
 414   // Track memory usage statistic after releasing CodeCache_lock
 415   MemoryService::track_code_cache_memory_usage();
 416 
 417   return blob;
 418 }
 419 
 420 
 421 BufferBlob::BufferBlob(const char* name, CodeBlobKind kind, CodeBuffer* cb, int size, uint16_t header_size)
 422   : RuntimeBlob(name, kind, cb, size, header_size, CodeOffsets::frame_never_safe, 0, nullptr)
 423 {}
 424 
 425 // Used by gtest
 426 BufferBlob* BufferBlob::create(const char* name, CodeBuffer* cb) {
 427   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 428 
 429   BufferBlob* blob = nullptr;
 430   unsigned int size = CodeBlob::allocation_size(cb, sizeof(BufferBlob));
 431   assert(name != nullptr, "must provide a name");
 432   {
 433     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 434     blob = new (size) BufferBlob(name, CodeBlobKind::Buffer, cb, size, sizeof(BufferBlob));
 435   }
 436   // Track memory usage statistic after releasing CodeCache_lock
 437   MemoryService::track_code_cache_memory_usage();
 438 
 439   return blob;
 440 }
 441 
 442 void* BufferBlob::operator new(size_t s, unsigned size) throw() {
 443   return CodeCache::allocate(size, CodeBlobType::NonNMethod);
 444 }
 445 
 446 void BufferBlob::free(BufferBlob *blob) {
 447   RuntimeBlob::free(blob);
 448 }
 449 
 450 BufferBlob::BufferBlob(const char* name, CodeBlobKind kind, CodeBuffer* cb, int size, uint16_t header_size, int frame_complete, int frame_size, OopMapSet* oop_maps, bool caller_must_gc_arguments)
 451   : RuntimeBlob(name, kind, cb, size, header_size, frame_complete, frame_size, oop_maps, caller_must_gc_arguments)
 452 {}
 453 
 454 
 455 //----------------------------------------------------------------------------------------------------
 456 // Implementation of AdapterBlob
 457 
 458 AdapterBlob::AdapterBlob(int size, CodeBuffer* cb, int entry_offset[AdapterBlob::ENTRY_COUNT], int frame_complete, int frame_size, OopMapSet* oop_maps, bool caller_must_gc_arguments) :
 459   BufferBlob("I2C/C2I adapters", CodeBlobKind::Adapter, cb, size, sizeof(AdapterBlob), frame_complete, frame_size, oop_maps, caller_must_gc_arguments) {
 460 #ifdef ASSERT
 461   assert(entry_offset[I2C] == 0, "sanity check");
 462   for (int i = 1; i < AdapterBlob::ENTRY_COUNT; i++) {
 463     // The entry is within the adapter blob or unset.
 464     int offset = entry_offset[i];
 465     assert((offset > 0 && offset < cb->insts()->size()) ||
 466            (i >= C2I_No_Clinit_Check && offset == -1),
 467            "invalid entry offset[%d] = 0x%x", i, offset);
 468   }
 469 #endif // ASSERT
 470   _c2i_offset = entry_offset[C2I];
 471   _c2i_inline_offset = entry_offset[C2I_Inline];
 472   _c2i_inline_ro_offset = entry_offset[C2I_Inline_RO];
 473   _c2i_unverified_offset = entry_offset[C2I_Unverified];
 474   _c2i_unverified_inline_offset = entry_offset[C2I_Unverified_Inline];
 475   _c2i_no_clinit_check_offset = entry_offset[C2I_No_Clinit_Check];
 476   CodeCache::commit(this);
 477 }
 478 
 479 AdapterBlob* AdapterBlob::create(CodeBuffer* cb, int entry_offset[AdapterBlob::ENTRY_COUNT], int frame_complete, int frame_size, OopMapSet* oop_maps, bool caller_must_gc_arguments) {
 480   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 481 
 482   CodeCache::gc_on_allocation();
 483 
 484   AdapterBlob* blob = nullptr;
 485   unsigned int size = CodeBlob::allocation_size(cb, sizeof(AdapterBlob));
 486   {
 487     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 488     blob = new (size) AdapterBlob(size, cb, entry_offset, frame_complete, frame_size, oop_maps, caller_must_gc_arguments);
 489   }
 490   // Track memory usage statistic after releasing CodeCache_lock
 491   MemoryService::track_code_cache_memory_usage();
 492 
 493   return blob;
 494 }
 495 
 496 //----------------------------------------------------------------------------------------------------
 497 // Implementation of VtableBlob
 498 
 499 void* VtableBlob::operator new(size_t s, unsigned size) throw() {
 500   // Handling of allocation failure stops compilation and prints a bunch of
 501   // stuff, which requires unlocking the CodeCache_lock, so that the Compile_lock
 502   // can be locked, and then re-locking the CodeCache_lock. That is not safe in
 503   // this context as we hold the CompiledICLocker. So we just don't handle code
 504   // cache exhaustion here; we leave that for a later allocation that does not
 505   // hold the CompiledICLocker.
 506   return CodeCache::allocate(size, CodeBlobType::NonNMethod, false /* handle_alloc_failure */);
 507 }
 508 
 509 VtableBlob::VtableBlob(const char* name, int size) :
 510   BufferBlob(name, CodeBlobKind::Vtable, size) {
 511 }
 512 
 513 VtableBlob* VtableBlob::create(const char* name, int buffer_size) {
 514   assert(JavaThread::current()->thread_state() == _thread_in_vm, "called with the wrong state");
 515 
 516   VtableBlob* blob = nullptr;
 517   unsigned int size = sizeof(VtableBlob);
 518   // align the size to CodeEntryAlignment
 519   size = align_code_offset(size);
 520   size += align_up(buffer_size, oopSize);
 521   assert(name != nullptr, "must provide a name");
 522   {
 523     if (!CodeCache_lock->try_lock()) {
 524       // If we can't take the CodeCache_lock, then this is a bad time to perform the ongoing
 525       // IC transition to megamorphic, for which this stub will be needed. It is better to
 526       // bail out the transition, and wait for a more opportune moment. Not only is it not
 527       // worth waiting for the lock blockingly for the megamorphic transition, it might
 528       // also result in a deadlock to blockingly wait, when concurrent class unloading is
 529       // performed. At this point in time, the CompiledICLocker is taken, so we are not
 530       // allowed to blockingly wait for the CodeCache_lock, as these two locks are otherwise
 531       // consistently taken in the opposite order. Bailing out results in an IC transition to
 532       // the clean state instead, which will cause subsequent calls to retry the transitioning
 533       // eventually.
 534       return nullptr;
 535     }
 536 
 537     MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
 538     blob = new (size) VtableBlob(name, size);
 539     CodeCache_lock->unlock();
 540   }
 541   // Track memory usage statistic after releasing CodeCache_lock
 542   MemoryService::track_code_cache_memory_usage();
 543 
 544   return blob;
 545 }
 546 
 547 //----------------------------------------------------------------------------------------------------
 548 // Implementation of MethodHandlesAdapterBlob
 549 
 550 MethodHandlesAdapterBlob* MethodHandlesAdapterBlob::create(int buffer_size) {
 551   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 552 
 553   MethodHandlesAdapterBlob* blob = nullptr;
 554   unsigned int size = sizeof(MethodHandlesAdapterBlob);
 555   // align the size to CodeEntryAlignment
 556   size = CodeBlob::align_code_offset(size);
 557   size += align_up(buffer_size, oopSize);
 558   {
 559     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 560     blob = new (size) MethodHandlesAdapterBlob(size);
 561     if (blob == nullptr) {
 562       vm_exit_out_of_memory(size, OOM_MALLOC_ERROR, "CodeCache: no room for method handle adapter blob");
 563     }
 564   }
 565   // Track memory usage statistic after releasing CodeCache_lock
 566   MemoryService::track_code_cache_memory_usage();
 567 
 568   return blob;
 569 }
 570 
 571 //----------------------------------------------------------------------------------------------------
 572 // Implementation of BufferedInlineTypeBlob
 573 BufferedInlineTypeBlob::BufferedInlineTypeBlob(int size, CodeBuffer* cb, int pack_fields_off, int pack_fields_jobject_off, int unpack_fields_off) :
 574   BufferBlob("buffered inline type", CodeBlobKind::BufferedInlineType, cb, size, sizeof(BufferedInlineTypeBlob)),
 575   _pack_fields_off(pack_fields_off),
 576   _pack_fields_jobject_off(pack_fields_jobject_off),
 577   _unpack_fields_off(unpack_fields_off) {
 578   CodeCache::commit(this);
 579 }
 580 
 581 BufferedInlineTypeBlob* BufferedInlineTypeBlob::create(CodeBuffer* cb, int pack_fields_off, int pack_fields_jobject_off, int unpack_fields_off) {
 582   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 583 
 584   BufferedInlineTypeBlob* blob = nullptr;
 585   unsigned int size = CodeBlob::allocation_size(cb, sizeof(BufferedInlineTypeBlob));
 586   {
 587     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 588     blob = new (size) BufferedInlineTypeBlob(size, cb, pack_fields_off, pack_fields_jobject_off, unpack_fields_off);
 589   }
 590   // Track memory usage statistic after releasing CodeCache_lock
 591   MemoryService::track_code_cache_memory_usage();
 592 
 593   return blob;
 594 }
 595 
 596 //----------------------------------------------------------------------------------------------------
 597 // Implementation of RuntimeStub
 598 
 599 RuntimeStub::RuntimeStub(
 600   const char* name,
 601   CodeBuffer* cb,
 602   int         size,
 603   int16_t     frame_complete,
 604   int         frame_size,
 605   OopMapSet*  oop_maps,
 606   bool        caller_must_gc_arguments
 607 )
 608 : RuntimeBlob(name, CodeBlobKind::RuntimeStub, cb, size, sizeof(RuntimeStub),
 609               frame_complete, frame_size, oop_maps, caller_must_gc_arguments)
 610 {
 611 }
 612 
 613 RuntimeStub* RuntimeStub::new_runtime_stub(const char* stub_name,
 614                                            CodeBuffer* cb,
 615                                            int16_t frame_complete,
 616                                            int frame_size,
 617                                            OopMapSet* oop_maps,
 618                                            bool caller_must_gc_arguments,
 619                                            bool alloc_fail_is_fatal)
 620 {
 621   RuntimeStub* stub = nullptr;
 622   unsigned int size = CodeBlob::allocation_size(cb, sizeof(RuntimeStub));
 623   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 624   {
 625     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 626     stub = new (size) RuntimeStub(stub_name, cb, size, frame_complete, frame_size, oop_maps, caller_must_gc_arguments);
 627     if (stub == nullptr) {
 628       if (!alloc_fail_is_fatal) {
 629         return nullptr;
 630       }
 631       fatal("Initial size of CodeCache is too small");
 632     }
 633   }
 634 
 635   trace_new_stub(stub, "RuntimeStub - ", stub_name);
 636 
 637   return stub;
 638 }
 639 
 640 
 641 void* RuntimeStub::operator new(size_t s, unsigned size) throw() {
 642   return CodeCache::allocate(size, CodeBlobType::NonNMethod);
 643 }
 644 
 645 // operator new shared by all singletons:
 646 void* SingletonBlob::operator new(size_t s, unsigned size, bool alloc_fail_is_fatal) throw() {
 647   void* p = CodeCache::allocate(size, CodeBlobType::NonNMethod);
 648   if (alloc_fail_is_fatal && !p) fatal("Initial size of CodeCache is too small");
 649   return p;
 650 }
 651 
 652 
 653 //----------------------------------------------------------------------------------------------------
 654 // Implementation of DeoptimizationBlob
 655 
 656 DeoptimizationBlob::DeoptimizationBlob(
 657   CodeBuffer* cb,
 658   int         size,
 659   OopMapSet*  oop_maps,
 660   int         unpack_offset,
 661   int         unpack_with_exception_offset,
 662   int         unpack_with_reexecution_offset,
 663   int         frame_size
 664 )
 665   : SingletonBlob("DeoptimizationBlob", CodeBlobKind::Deoptimization, cb,
 666                   size, sizeof(DeoptimizationBlob), frame_size, oop_maps)
 667 {
 668   _unpack_offset           = unpack_offset;
 669   _unpack_with_exception   = unpack_with_exception_offset;
 670   _unpack_with_reexecution = unpack_with_reexecution_offset;
 671 #ifdef COMPILER1
 672   _unpack_with_exception_in_tls   = -1;
 673 #endif
 674 }
 675 
 676 
 677 DeoptimizationBlob* DeoptimizationBlob::create(
 678   CodeBuffer* cb,
 679   OopMapSet*  oop_maps,
 680   int        unpack_offset,
 681   int        unpack_with_exception_offset,
 682   int        unpack_with_reexecution_offset,
 683   int        frame_size)
 684 {
 685   DeoptimizationBlob* blob = nullptr;
 686   unsigned int size = CodeBlob::allocation_size(cb, sizeof(DeoptimizationBlob));
 687   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 688   {
 689     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 690     blob = new (size) DeoptimizationBlob(cb,
 691                                          size,
 692                                          oop_maps,
 693                                          unpack_offset,
 694                                          unpack_with_exception_offset,
 695                                          unpack_with_reexecution_offset,
 696                                          frame_size);
 697   }
 698 
 699   trace_new_stub(blob, "DeoptimizationBlob");
 700 
 701   return blob;
 702 }
 703 
 704 #ifdef COMPILER2
 705 
 706 //----------------------------------------------------------------------------------------------------
 707 // Implementation of UncommonTrapBlob
 708 
 709 UncommonTrapBlob::UncommonTrapBlob(
 710   CodeBuffer* cb,
 711   int         size,
 712   OopMapSet*  oop_maps,
 713   int         frame_size
 714 )
 715   : SingletonBlob("UncommonTrapBlob", CodeBlobKind::UncommonTrap, cb,
 716                   size, sizeof(UncommonTrapBlob), frame_size, oop_maps)
 717 {}
 718 
 719 
 720 UncommonTrapBlob* UncommonTrapBlob::create(
 721   CodeBuffer* cb,
 722   OopMapSet*  oop_maps,
 723   int        frame_size)
 724 {
 725   UncommonTrapBlob* blob = nullptr;
 726   unsigned int size = CodeBlob::allocation_size(cb, sizeof(UncommonTrapBlob));
 727   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 728   {
 729     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 730     blob = new (size, false) UncommonTrapBlob(cb, size, oop_maps, frame_size);
 731   }
 732 
 733   trace_new_stub(blob, "UncommonTrapBlob");
 734 
 735   return blob;
 736 }
 737 
 738 //----------------------------------------------------------------------------------------------------
 739 // Implementation of ExceptionBlob
 740 
 741 ExceptionBlob::ExceptionBlob(
 742   CodeBuffer* cb,
 743   int         size,
 744   OopMapSet*  oop_maps,
 745   int         frame_size
 746 )
 747   : SingletonBlob("ExceptionBlob", CodeBlobKind::Exception, cb,
 748                   size, sizeof(ExceptionBlob), frame_size, oop_maps)
 749 {}
 750 
 751 
 752 ExceptionBlob* ExceptionBlob::create(
 753   CodeBuffer* cb,
 754   OopMapSet*  oop_maps,
 755   int         frame_size)
 756 {
 757   ExceptionBlob* blob = nullptr;
 758   unsigned int size = CodeBlob::allocation_size(cb, sizeof(ExceptionBlob));
 759   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 760   {
 761     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 762     blob = new (size, false) ExceptionBlob(cb, size, oop_maps, frame_size);
 763   }
 764 
 765   trace_new_stub(blob, "ExceptionBlob");
 766 
 767   return blob;
 768 }
 769 
 770 #endif // COMPILER2
 771 
 772 //----------------------------------------------------------------------------------------------------
 773 // Implementation of SafepointBlob
 774 
 775 SafepointBlob::SafepointBlob(
 776   CodeBuffer* cb,
 777   int         size,
 778   OopMapSet*  oop_maps,
 779   int         frame_size
 780 )
 781   : SingletonBlob(cb->name(), CodeBlobKind::Safepoint, cb,
 782                   size, sizeof(SafepointBlob), frame_size, oop_maps)
 783 {}
 784 
 785 
 786 SafepointBlob* SafepointBlob::create(
 787   CodeBuffer* cb,
 788   OopMapSet*  oop_maps,
 789   int         frame_size)
 790 {
 791   SafepointBlob* blob = nullptr;
 792   unsigned int size = CodeBlob::allocation_size(cb, sizeof(SafepointBlob));
 793   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 794   {
 795     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 796     blob = new (size) SafepointBlob(cb, size, oop_maps, frame_size);
 797   }
 798 
 799   trace_new_stub(blob, "SafepointBlob - ", blob->name());
 800 
 801   return blob;
 802 }
 803 
 804 //----------------------------------------------------------------------------------------------------
 805 // Implementation of UpcallStub
 806 
 807 UpcallStub::UpcallStub(const char* name, CodeBuffer* cb, int size, jobject receiver, ByteSize frame_data_offset) :
 808   RuntimeBlob(name, CodeBlobKind::Upcall, cb, size, sizeof(UpcallStub),
 809               CodeOffsets::frame_never_safe, 0 /* no frame size */,
 810               /* oop maps = */ nullptr, /* caller must gc arguments = */ false),
 811   _receiver(receiver),
 812   _frame_data_offset(frame_data_offset)
 813 {
 814   CodeCache::commit(this);
 815 }
 816 
 817 void* UpcallStub::operator new(size_t s, unsigned size) throw() {
 818   return CodeCache::allocate(size, CodeBlobType::NonNMethod);
 819 }
 820 
 821 UpcallStub* UpcallStub::create(const char* name, CodeBuffer* cb, jobject receiver, ByteSize frame_data_offset) {
 822   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 823 
 824   UpcallStub* blob = nullptr;
 825   unsigned int size = CodeBlob::allocation_size(cb, sizeof(UpcallStub));
 826   {
 827     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 828     blob = new (size) UpcallStub(name, cb, size, receiver, frame_data_offset);
 829   }
 830   if (blob == nullptr) {
 831     return nullptr; // caller must handle this
 832   }
 833 
 834   // Track memory usage statistic after releasing CodeCache_lock
 835   MemoryService::track_code_cache_memory_usage();
 836 
 837   trace_new_stub(blob, "UpcallStub - ", name);
 838 
 839   return blob;
 840 }
 841 
 842 void UpcallStub::oops_do(OopClosure* f, const frame& frame) {
 843   frame_data_for_frame(frame)->old_handles->oops_do(f);
 844 }
 845 
 846 JavaFrameAnchor* UpcallStub::jfa_for_frame(const frame& frame) const {
 847   return &frame_data_for_frame(frame)->jfa;
 848 }
 849 
 850 void UpcallStub::free(UpcallStub* blob) {
 851   assert(blob != nullptr, "caller must check for nullptr");
 852   JNIHandles::destroy_global(blob->receiver());
 853   RuntimeBlob::free(blob);
 854 }
 855 
 856 //----------------------------------------------------------------------------------------------------
 857 // Verification and printing
 858 
 859 void CodeBlob::verify() {
 860   if (is_nmethod()) {
 861     as_nmethod()->verify();
 862   }
 863 }
 864 
 865 void CodeBlob::print_on(outputStream* st) const {
 866   vptr()->print_on(this, st);
 867 }
 868 
 869 void CodeBlob::print() const { print_on(tty); }
 870 
 871 void CodeBlob::print_value_on(outputStream* st) const {
 872   vptr()->print_value_on(this, st);
 873 }
 874 
 875 void CodeBlob::print_on_impl(outputStream* st) const {
 876   st->print_cr("[CodeBlob kind:%d (" INTPTR_FORMAT ")]", (int)_kind, p2i(this));
 877   st->print_cr("Framesize: %d", _frame_size);
 878 }
 879 
 880 void CodeBlob::print_value_on_impl(outputStream* st) const {
 881   st->print_cr("[CodeBlob]");
 882 }
 883 
 884 void CodeBlob::print_block_comment(outputStream* stream, address block_begin) const {
 885 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 886   if (is_nmethod()) {
 887     as_nmethod()->print_nmethod_labels(stream, block_begin);
 888   }
 889 #endif
 890 
 891 #ifndef PRODUCT
 892   ptrdiff_t offset = block_begin - code_begin();
 893   assert(offset >= 0, "Expecting non-negative offset!");
 894   _asm_remarks.print(uint(offset), stream);
 895 #endif
 896   }
 897 
 898 void CodeBlob::dump_for_addr(address addr, outputStream* st, bool verbose) const {
 899   if (is_buffer_blob() || is_adapter_blob() || is_vtable_blob() || is_method_handles_adapter_blob()) {
 900     // the interpreter is generated into a buffer blob
 901     InterpreterCodelet* i = Interpreter::codelet_containing(addr);
 902     if (i != nullptr) {
 903       st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an Interpreter codelet", p2i(addr), (int)(addr - i->code_begin()));
 904       i->print_on(st);
 905       return;
 906     }
 907     if (Interpreter::contains(addr)) {
 908       st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
 909                    " (not bytecode specific)", p2i(addr));
 910       return;
 911     }
 912     //
 913     if (is_adapter_blob()) {
 914       st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an AdapterHandler", p2i(addr), (int)(addr - code_begin()));
 915       AdapterHandlerLibrary::print_handler_on(st, this);
 916       return;
 917     }
 918     // the stubroutines are generated into a buffer blob
 919     StubCodeDesc* d = StubCodeDesc::desc_for(addr);
 920     if (d != nullptr) {
 921       st->print_cr(INTPTR_FORMAT " is at begin+%d in a stub", p2i(addr), (int)(addr - d->begin()));
 922       d->print_on(st);
 923       st->cr();
 924       return;
 925     }
 926     if (StubRoutines::contains(addr)) {
 927       st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) stub routine", p2i(addr));
 928       return;
 929     }
 930     VtableStub* v = VtableStubs::stub_containing(addr);
 931     if (v != nullptr) {
 932       st->print_cr(INTPTR_FORMAT " is at entry_point+%d in a vtable stub", p2i(addr), (int)(addr - v->entry_point()));
 933       v->print_on(st);
 934       st->cr();
 935       return;
 936     }
 937   }
 938   if (is_nmethod()) {
 939     nmethod* nm = as_nmethod();
 940     ResourceMark rm;
 941     st->print(INTPTR_FORMAT " is at entry_point+%d in (nmethod*)" INTPTR_FORMAT,
 942               p2i(addr), (int)(addr - nm->entry_point()), p2i(nm));
 943     if (verbose) {
 944       st->print(" for ");
 945       nm->method()->print_value_on(st);
 946     }
 947     st->cr();
 948     if (verbose && st == tty) {
 949       // verbose is only ever true when called from findpc in debug.cpp
 950       nm->print_nmethod(true);
 951     } else {
 952       nm->print_on(st);
 953       nm->print_code_snippet(st, addr);
 954     }
 955     return;
 956   }
 957   st->print_cr(INTPTR_FORMAT " is at code_begin+%d in ", p2i(addr), (int)(addr - code_begin()));
 958   print_on(st);
 959 }
 960 
 961 void BufferBlob::print_on_impl(outputStream* st) const {
 962   RuntimeBlob::print_on_impl(st);
 963   print_value_on_impl(st);
 964 }
 965 
 966 void BufferBlob::print_value_on_impl(outputStream* st) const {
 967   st->print_cr("BufferBlob (" INTPTR_FORMAT  ") used for %s", p2i(this), name());
 968 }
 969 
 970 void RuntimeStub::print_on_impl(outputStream* st) const {
 971   ttyLocker ttyl;
 972   RuntimeBlob::print_on_impl(st);
 973   st->print("Runtime Stub (" INTPTR_FORMAT "): ", p2i(this));
 974   st->print_cr("%s", name());
 975   Disassembler::decode((CodeBlob*)this, st);
 976 }
 977 
 978 void RuntimeStub::print_value_on_impl(outputStream* st) const {
 979   st->print("RuntimeStub (" INTPTR_FORMAT "): ", p2i(this)); st->print("%s", name());
 980 }
 981 
 982 void SingletonBlob::print_on_impl(outputStream* st) const {
 983   ttyLocker ttyl;
 984   RuntimeBlob::print_on_impl(st);
 985   st->print_cr("%s", name());
 986   Disassembler::decode((CodeBlob*)this, st);
 987 }
 988 
 989 void SingletonBlob::print_value_on_impl(outputStream* st) const {
 990   st->print_cr("%s", name());
 991 }
 992 
 993 void DeoptimizationBlob::print_value_on_impl(outputStream* st) const {
 994   st->print_cr("Deoptimization (frame not available)");
 995 }
 996 
 997 void UpcallStub::print_on_impl(outputStream* st) const {
 998   RuntimeBlob::print_on_impl(st);
 999   print_value_on_impl(st);
1000   st->print_cr("Frame data offset: %d", (int) _frame_data_offset);
1001   oop recv = JNIHandles::resolve(_receiver);
1002   st->print("Receiver MH=");
1003   recv->print_on(st);
1004   Disassembler::decode((CodeBlob*)this, st);
1005 }
1006 
1007 void UpcallStub::print_value_on_impl(outputStream* st) const {
1008   st->print_cr("UpcallStub (" INTPTR_FORMAT  ") used for %s", p2i(this), name());
1009 }