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   cb->copy_code_and_locs_to(this);
 332 
 333   // Flush generated code
 334   ICache::invalidate_range(code_begin(), code_size());
 335 }
 336 
 337 void RuntimeBlob::free(RuntimeBlob* blob) {
 338   assert(blob != nullptr, "caller must check for nullptr");
 339   MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
 340   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 341   blob->purge();
 342   {
 343     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 344     CodeCache::free(blob);
 345   }
 346   // Track memory usage statistic after releasing CodeCache_lock
 347   MemoryService::track_code_cache_memory_usage();
 348 }
 349 
 350 void RuntimeBlob::trace_new_stub(RuntimeBlob* stub, const char* name1, const char* name2) {
 351   // Do not hold the CodeCache lock during name formatting.
 352   assert(!CodeCache_lock->owned_by_self(), "release CodeCache before registering the stub");
 353 
 354   if (stub != nullptr && (PrintStubCode ||
 355                        Forte::is_enabled() ||
 356                        JvmtiExport::should_post_dynamic_code_generated())) {
 357     char stub_id[256];
 358     assert(strlen(name1) + strlen(name2) < sizeof(stub_id), "");
 359     jio_snprintf(stub_id, sizeof(stub_id), "%s%s", name1, name2);
 360     if (PrintStubCode) {
 361       ttyLocker ttyl;
 362       tty->print_cr("- - - [BEGIN] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
 363       tty->print_cr("Decoding %s " PTR_FORMAT " [" PTR_FORMAT ", " PTR_FORMAT "] (%d bytes)",
 364                     stub_id, p2i(stub), p2i(stub->code_begin()), p2i(stub->code_end()), stub->code_size());
 365       Disassembler::decode(stub->code_begin(), stub->code_end(), tty
 366                            NOT_PRODUCT(COMMA &stub->asm_remarks()));
 367       if ((stub->oop_maps() != nullptr) && AbstractDisassembler::show_structs()) {
 368         tty->print_cr("- - - [OOP MAPS]- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
 369         stub->oop_maps()->print();
 370       }
 371       tty->print_cr("- - - [END] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
 372       tty->cr();
 373     }
 374     if (Forte::is_enabled()) {
 375       Forte::register_stub(stub_id, stub->code_begin(), stub->code_end());
 376     }
 377 
 378     if (JvmtiExport::should_post_dynamic_code_generated()) {
 379       const char* stub_name = name2;
 380       if (name2[0] == '\0')  stub_name = name1;
 381       JvmtiExport::post_dynamic_code_generated(stub_name, stub->code_begin(), stub->code_end());
 382     }
 383   }
 384 
 385   // Track memory usage statistic after releasing CodeCache_lock
 386   MemoryService::track_code_cache_memory_usage();
 387 }
 388 
 389 //----------------------------------------------------------------------------------------------------
 390 // Implementation of BufferBlob
 391 
 392 BufferBlob::BufferBlob(const char* name, CodeBlobKind kind, int size, uint16_t header_size)
 393   : RuntimeBlob(name, kind, size, header_size)
 394 {}
 395 
 396 BufferBlob* BufferBlob::create(const char* name, uint buffer_size) {
 397   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 398 
 399   BufferBlob* blob = nullptr;
 400   unsigned int size = sizeof(BufferBlob);
 401   // align the size to CodeEntryAlignment
 402   size = CodeBlob::align_code_offset(size);
 403   size += align_up(buffer_size, oopSize);
 404   assert(name != nullptr, "must provide a name");
 405   {
 406     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 407     blob = new (size) BufferBlob(name, CodeBlobKind::Buffer, size);
 408   }
 409   // Track memory usage statistic after releasing CodeCache_lock
 410   MemoryService::track_code_cache_memory_usage();
 411 
 412   return blob;
 413 }
 414 
 415 
 416 BufferBlob::BufferBlob(const char* name, CodeBlobKind kind, CodeBuffer* cb, int size, uint16_t header_size)
 417   : RuntimeBlob(name, kind, cb, size, header_size, CodeOffsets::frame_never_safe, 0, nullptr)
 418 {}
 419 
 420 // Used by gtest
 421 BufferBlob* BufferBlob::create(const char* name, CodeBuffer* cb) {
 422   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 423 
 424   BufferBlob* blob = nullptr;
 425   unsigned int size = CodeBlob::allocation_size(cb, sizeof(BufferBlob));
 426   assert(name != nullptr, "must provide a name");
 427   {
 428     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 429     blob = new (size) BufferBlob(name, CodeBlobKind::Buffer, cb, size, sizeof(BufferBlob));
 430   }
 431   // Track memory usage statistic after releasing CodeCache_lock
 432   MemoryService::track_code_cache_memory_usage();
 433 
 434   return blob;
 435 }
 436 
 437 void* BufferBlob::operator new(size_t s, unsigned size) throw() {
 438   return CodeCache::allocate(size, CodeBlobType::NonNMethod);
 439 }
 440 
 441 void BufferBlob::free(BufferBlob *blob) {
 442   RuntimeBlob::free(blob);
 443 }
 444 
 445 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)
 446   : RuntimeBlob(name, kind, cb, size, header_size, frame_complete, frame_size, oop_maps, caller_must_gc_arguments)
 447 {}
 448 
 449 
 450 //----------------------------------------------------------------------------------------------------
 451 // Implementation of AdapterBlob
 452 
 453 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) :
 454   BufferBlob("I2C/C2I adapters", CodeBlobKind::Adapter, cb, size, sizeof(AdapterBlob), frame_complete, frame_size, oop_maps, caller_must_gc_arguments) {
 455 #ifdef ASSERT
 456   assert(entry_offset[I2C] == 0, "sanity check");
 457   for (int i = 1; i < AdapterBlob::ENTRY_COUNT; i++) {
 458     // The entry is within the adapter blob or unset.
 459     int offset = entry_offset[i];
 460     assert((offset > 0 && offset < cb->insts()->size()) ||
 461            (i >= C2I_No_Clinit_Check && offset == -1),
 462            "invalid entry offset[%d] = 0x%x", i, offset);
 463   }
 464 #endif // ASSERT
 465   _c2i_offset = entry_offset[C2I];
 466   _c2i_inline_offset = entry_offset[C2I_Inline];
 467   _c2i_inline_ro_offset = entry_offset[C2I_Inline_RO];
 468   _c2i_unverified_offset = entry_offset[C2I_Unverified];
 469   _c2i_unverified_inline_offset = entry_offset[C2I_Unverified_Inline];
 470   _c2i_no_clinit_check_offset = entry_offset[C2I_No_Clinit_Check];
 471   CodeCache::commit(this);
 472 }
 473 
 474 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) {
 475   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 476 
 477   CodeCache::gc_on_allocation();
 478 
 479   AdapterBlob* blob = nullptr;
 480   unsigned int size = CodeBlob::allocation_size(cb, sizeof(AdapterBlob));
 481   {
 482     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 483     blob = new (size) AdapterBlob(size, cb, entry_offset, frame_complete, frame_size, oop_maps, caller_must_gc_arguments);
 484   }
 485   // Track memory usage statistic after releasing CodeCache_lock
 486   MemoryService::track_code_cache_memory_usage();
 487 
 488   return blob;
 489 }
 490 
 491 //----------------------------------------------------------------------------------------------------
 492 // Implementation of VtableBlob
 493 
 494 void* VtableBlob::operator new(size_t s, unsigned size) throw() {
 495   // Handling of allocation failure stops compilation and prints a bunch of
 496   // stuff, which requires unlocking the CodeCache_lock, so that the Compile_lock
 497   // can be locked, and then re-locking the CodeCache_lock. That is not safe in
 498   // this context as we hold the CompiledICLocker. So we just don't handle code
 499   // cache exhaustion here; we leave that for a later allocation that does not
 500   // hold the CompiledICLocker.
 501   return CodeCache::allocate(size, CodeBlobType::NonNMethod, false /* handle_alloc_failure */);
 502 }
 503 
 504 VtableBlob::VtableBlob(const char* name, int size) :
 505   BufferBlob(name, CodeBlobKind::Vtable, size) {
 506 }
 507 
 508 VtableBlob* VtableBlob::create(const char* name, int buffer_size) {
 509   assert(JavaThread::current()->thread_state() == _thread_in_vm, "called with the wrong state");
 510 
 511   VtableBlob* blob = nullptr;
 512   unsigned int size = sizeof(VtableBlob);
 513   // align the size to CodeEntryAlignment
 514   size = align_code_offset(size);
 515   size += align_up(buffer_size, oopSize);
 516   assert(name != nullptr, "must provide a name");
 517   {
 518     if (!CodeCache_lock->try_lock()) {
 519       // If we can't take the CodeCache_lock, then this is a bad time to perform the ongoing
 520       // IC transition to megamorphic, for which this stub will be needed. It is better to
 521       // bail out the transition, and wait for a more opportune moment. Not only is it not
 522       // worth waiting for the lock blockingly for the megamorphic transition, it might
 523       // also result in a deadlock to blockingly wait, when concurrent class unloading is
 524       // performed. At this point in time, the CompiledICLocker is taken, so we are not
 525       // allowed to blockingly wait for the CodeCache_lock, as these two locks are otherwise
 526       // consistently taken in the opposite order. Bailing out results in an IC transition to
 527       // the clean state instead, which will cause subsequent calls to retry the transitioning
 528       // eventually.
 529       return nullptr;
 530     }
 531 
 532     MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
 533     blob = new (size) VtableBlob(name, size);
 534     CodeCache_lock->unlock();
 535   }
 536   // Track memory usage statistic after releasing CodeCache_lock
 537   MemoryService::track_code_cache_memory_usage();
 538 
 539   return blob;
 540 }
 541 
 542 //----------------------------------------------------------------------------------------------------
 543 // Implementation of MethodHandlesAdapterBlob
 544 
 545 MethodHandlesAdapterBlob* MethodHandlesAdapterBlob::create(int buffer_size) {
 546   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 547 
 548   MethodHandlesAdapterBlob* blob = nullptr;
 549   unsigned int size = sizeof(MethodHandlesAdapterBlob);
 550   // align the size to CodeEntryAlignment
 551   size = CodeBlob::align_code_offset(size);
 552   size += align_up(buffer_size, oopSize);
 553   {
 554     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 555     blob = new (size) MethodHandlesAdapterBlob(size);
 556     if (blob == nullptr) {
 557       vm_exit_out_of_memory(size, OOM_MALLOC_ERROR, "CodeCache: no room for method handle adapter blob");
 558     }
 559   }
 560   // Track memory usage statistic after releasing CodeCache_lock
 561   MemoryService::track_code_cache_memory_usage();
 562 
 563   return blob;
 564 }
 565 
 566 //----------------------------------------------------------------------------------------------------
 567 // Implementation of BufferedInlineTypeBlob
 568 BufferedInlineTypeBlob::BufferedInlineTypeBlob(int size, CodeBuffer* cb, int pack_fields_off, int pack_fields_jobject_off, int unpack_fields_off) :
 569   BufferBlob("buffered inline type", CodeBlobKind::BufferedInlineType, cb, size, sizeof(BufferedInlineTypeBlob)),
 570   _pack_fields_off(pack_fields_off),
 571   _pack_fields_jobject_off(pack_fields_jobject_off),
 572   _unpack_fields_off(unpack_fields_off) {
 573   CodeCache::commit(this);
 574 }
 575 
 576 BufferedInlineTypeBlob* BufferedInlineTypeBlob::create(CodeBuffer* cb, int pack_fields_off, int pack_fields_jobject_off, int unpack_fields_off) {
 577   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 578 
 579   BufferedInlineTypeBlob* blob = nullptr;
 580   unsigned int size = CodeBlob::allocation_size(cb, sizeof(BufferedInlineTypeBlob));
 581   {
 582     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 583     blob = new (size) BufferedInlineTypeBlob(size, cb, pack_fields_off, pack_fields_jobject_off, unpack_fields_off);
 584   }
 585   // Track memory usage statistic after releasing CodeCache_lock
 586   MemoryService::track_code_cache_memory_usage();
 587 
 588   return blob;
 589 }
 590 
 591 //----------------------------------------------------------------------------------------------------
 592 // Implementation of RuntimeStub
 593 
 594 RuntimeStub::RuntimeStub(
 595   const char* name,
 596   CodeBuffer* cb,
 597   int         size,
 598   int16_t     frame_complete,
 599   int         frame_size,
 600   OopMapSet*  oop_maps,
 601   bool        caller_must_gc_arguments
 602 )
 603 : RuntimeBlob(name, CodeBlobKind::RuntimeStub, cb, size, sizeof(RuntimeStub),
 604               frame_complete, frame_size, oop_maps, caller_must_gc_arguments)
 605 {
 606 }
 607 
 608 RuntimeStub* RuntimeStub::new_runtime_stub(const char* stub_name,
 609                                            CodeBuffer* cb,
 610                                            int16_t frame_complete,
 611                                            int frame_size,
 612                                            OopMapSet* oop_maps,
 613                                            bool caller_must_gc_arguments,
 614                                            bool alloc_fail_is_fatal)
 615 {
 616   RuntimeStub* stub = nullptr;
 617   unsigned int size = CodeBlob::allocation_size(cb, sizeof(RuntimeStub));
 618   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 619   {
 620     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 621     stub = new (size) RuntimeStub(stub_name, cb, size, frame_complete, frame_size, oop_maps, caller_must_gc_arguments);
 622     if (stub == nullptr) {
 623       if (!alloc_fail_is_fatal) {
 624         return nullptr;
 625       }
 626       fatal("Initial size of CodeCache is too small");
 627     }
 628   }
 629 
 630   trace_new_stub(stub, "RuntimeStub - ", stub_name);
 631 
 632   return stub;
 633 }
 634 
 635 
 636 void* RuntimeStub::operator new(size_t s, unsigned size) throw() {
 637   return CodeCache::allocate(size, CodeBlobType::NonNMethod);
 638 }
 639 
 640 // operator new shared by all singletons:
 641 void* SingletonBlob::operator new(size_t s, unsigned size, bool alloc_fail_is_fatal) throw() {
 642   void* p = CodeCache::allocate(size, CodeBlobType::NonNMethod);
 643   if (alloc_fail_is_fatal && !p) fatal("Initial size of CodeCache is too small");
 644   return p;
 645 }
 646 
 647 
 648 //----------------------------------------------------------------------------------------------------
 649 // Implementation of DeoptimizationBlob
 650 
 651 DeoptimizationBlob::DeoptimizationBlob(
 652   CodeBuffer* cb,
 653   int         size,
 654   OopMapSet*  oop_maps,
 655   int         unpack_offset,
 656   int         unpack_with_exception_offset,
 657   int         unpack_with_reexecution_offset,
 658   int         frame_size
 659 )
 660   : SingletonBlob("DeoptimizationBlob", CodeBlobKind::Deoptimization, cb,
 661                   size, sizeof(DeoptimizationBlob), frame_size, oop_maps)
 662 {
 663   _unpack_offset           = unpack_offset;
 664   _unpack_with_exception   = unpack_with_exception_offset;
 665   _unpack_with_reexecution = unpack_with_reexecution_offset;
 666 #ifdef COMPILER1
 667   _unpack_with_exception_in_tls   = -1;
 668 #endif
 669 }
 670 
 671 
 672 DeoptimizationBlob* DeoptimizationBlob::create(
 673   CodeBuffer* cb,
 674   OopMapSet*  oop_maps,
 675   int        unpack_offset,
 676   int        unpack_with_exception_offset,
 677   int        unpack_with_reexecution_offset,
 678   int        frame_size)
 679 {
 680   DeoptimizationBlob* blob = nullptr;
 681   unsigned int size = CodeBlob::allocation_size(cb, sizeof(DeoptimizationBlob));
 682   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 683   {
 684     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 685     blob = new (size) DeoptimizationBlob(cb,
 686                                          size,
 687                                          oop_maps,
 688                                          unpack_offset,
 689                                          unpack_with_exception_offset,
 690                                          unpack_with_reexecution_offset,
 691                                          frame_size);
 692   }
 693 
 694   trace_new_stub(blob, "DeoptimizationBlob");
 695 
 696   return blob;
 697 }
 698 
 699 #ifdef COMPILER2
 700 
 701 //----------------------------------------------------------------------------------------------------
 702 // Implementation of UncommonTrapBlob
 703 
 704 UncommonTrapBlob::UncommonTrapBlob(
 705   CodeBuffer* cb,
 706   int         size,
 707   OopMapSet*  oop_maps,
 708   int         frame_size
 709 )
 710   : SingletonBlob("UncommonTrapBlob", CodeBlobKind::UncommonTrap, cb,
 711                   size, sizeof(UncommonTrapBlob), frame_size, oop_maps)
 712 {}
 713 
 714 
 715 UncommonTrapBlob* UncommonTrapBlob::create(
 716   CodeBuffer* cb,
 717   OopMapSet*  oop_maps,
 718   int        frame_size)
 719 {
 720   UncommonTrapBlob* blob = nullptr;
 721   unsigned int size = CodeBlob::allocation_size(cb, sizeof(UncommonTrapBlob));
 722   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 723   {
 724     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 725     blob = new (size, false) UncommonTrapBlob(cb, size, oop_maps, frame_size);
 726   }
 727 
 728   trace_new_stub(blob, "UncommonTrapBlob");
 729 
 730   return blob;
 731 }
 732 
 733 //----------------------------------------------------------------------------------------------------
 734 // Implementation of ExceptionBlob
 735 
 736 ExceptionBlob::ExceptionBlob(
 737   CodeBuffer* cb,
 738   int         size,
 739   OopMapSet*  oop_maps,
 740   int         frame_size
 741 )
 742   : SingletonBlob("ExceptionBlob", CodeBlobKind::Exception, cb,
 743                   size, sizeof(ExceptionBlob), frame_size, oop_maps)
 744 {}
 745 
 746 
 747 ExceptionBlob* ExceptionBlob::create(
 748   CodeBuffer* cb,
 749   OopMapSet*  oop_maps,
 750   int         frame_size)
 751 {
 752   ExceptionBlob* blob = nullptr;
 753   unsigned int size = CodeBlob::allocation_size(cb, sizeof(ExceptionBlob));
 754   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 755   {
 756     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 757     blob = new (size, false) ExceptionBlob(cb, size, oop_maps, frame_size);
 758   }
 759 
 760   trace_new_stub(blob, "ExceptionBlob");
 761 
 762   return blob;
 763 }
 764 
 765 #endif // COMPILER2
 766 
 767 //----------------------------------------------------------------------------------------------------
 768 // Implementation of SafepointBlob
 769 
 770 SafepointBlob::SafepointBlob(
 771   CodeBuffer* cb,
 772   int         size,
 773   OopMapSet*  oop_maps,
 774   int         frame_size
 775 )
 776   : SingletonBlob(cb->name(), CodeBlobKind::Safepoint, cb,
 777                   size, sizeof(SafepointBlob), frame_size, oop_maps)
 778 {}
 779 
 780 
 781 SafepointBlob* SafepointBlob::create(
 782   CodeBuffer* cb,
 783   OopMapSet*  oop_maps,
 784   int         frame_size)
 785 {
 786   SafepointBlob* blob = nullptr;
 787   unsigned int size = CodeBlob::allocation_size(cb, sizeof(SafepointBlob));
 788   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 789   {
 790     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 791     blob = new (size) SafepointBlob(cb, size, oop_maps, frame_size);
 792   }
 793 
 794   trace_new_stub(blob, "SafepointBlob - ", blob->name());
 795 
 796   return blob;
 797 }
 798 
 799 //----------------------------------------------------------------------------------------------------
 800 // Implementation of UpcallStub
 801 
 802 UpcallStub::UpcallStub(const char* name, CodeBuffer* cb, int size, jobject receiver, ByteSize frame_data_offset) :
 803   RuntimeBlob(name, CodeBlobKind::Upcall, cb, size, sizeof(UpcallStub),
 804               CodeOffsets::frame_never_safe, 0 /* no frame size */,
 805               /* oop maps = */ nullptr, /* caller must gc arguments = */ false),
 806   _receiver(receiver),
 807   _frame_data_offset(frame_data_offset)
 808 {
 809   CodeCache::commit(this);
 810 }
 811 
 812 void* UpcallStub::operator new(size_t s, unsigned size) throw() {
 813   return CodeCache::allocate(size, CodeBlobType::NonNMethod);
 814 }
 815 
 816 UpcallStub* UpcallStub::create(const char* name, CodeBuffer* cb, jobject receiver, ByteSize frame_data_offset) {
 817   ThreadInVMfromUnknown __tiv;  // get to VM state in case we block on CodeCache_lock
 818 
 819   UpcallStub* blob = nullptr;
 820   unsigned int size = CodeBlob::allocation_size(cb, sizeof(UpcallStub));
 821   {
 822     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 823     blob = new (size) UpcallStub(name, cb, size, receiver, frame_data_offset);
 824   }
 825   if (blob == nullptr) {
 826     return nullptr; // caller must handle this
 827   }
 828 
 829   // Track memory usage statistic after releasing CodeCache_lock
 830   MemoryService::track_code_cache_memory_usage();
 831 
 832   trace_new_stub(blob, "UpcallStub - ", name);
 833 
 834   return blob;
 835 }
 836 
 837 void UpcallStub::oops_do(OopClosure* f, const frame& frame) {
 838   frame_data_for_frame(frame)->old_handles->oops_do(f);
 839 }
 840 
 841 JavaFrameAnchor* UpcallStub::jfa_for_frame(const frame& frame) const {
 842   return &frame_data_for_frame(frame)->jfa;
 843 }
 844 
 845 void UpcallStub::free(UpcallStub* blob) {
 846   assert(blob != nullptr, "caller must check for nullptr");
 847   JNIHandles::destroy_global(blob->receiver());
 848   RuntimeBlob::free(blob);
 849 }
 850 
 851 //----------------------------------------------------------------------------------------------------
 852 // Verification and printing
 853 
 854 void CodeBlob::verify() {
 855   if (is_nmethod()) {
 856     as_nmethod()->verify();
 857   }
 858 }
 859 
 860 void CodeBlob::print_on(outputStream* st) const {
 861   vptr()->print_on(this, st);
 862 }
 863 
 864 void CodeBlob::print() const { print_on(tty); }
 865 
 866 void CodeBlob::print_value_on(outputStream* st) const {
 867   vptr()->print_value_on(this, st);
 868 }
 869 
 870 void CodeBlob::print_on_impl(outputStream* st) const {
 871   st->print_cr("[CodeBlob kind:%d (" INTPTR_FORMAT ")]", (int)_kind, p2i(this));
 872   st->print_cr("Framesize: %d", _frame_size);
 873 }
 874 
 875 void CodeBlob::print_value_on_impl(outputStream* st) const {
 876   st->print_cr("[CodeBlob]");
 877 }
 878 
 879 void CodeBlob::print_block_comment(outputStream* stream, address block_begin) const {
 880 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 881   if (is_nmethod()) {
 882     as_nmethod()->print_nmethod_labels(stream, block_begin);
 883   }
 884 #endif
 885 
 886 #ifndef PRODUCT
 887   ptrdiff_t offset = block_begin - code_begin();
 888   assert(offset >= 0, "Expecting non-negative offset!");
 889   _asm_remarks.print(uint(offset), stream);
 890 #endif
 891   }
 892 
 893 void CodeBlob::dump_for_addr(address addr, outputStream* st, bool verbose) const {
 894   if (is_buffer_blob() || is_adapter_blob() || is_vtable_blob() || is_method_handles_adapter_blob()) {
 895     // the interpreter is generated into a buffer blob
 896     InterpreterCodelet* i = Interpreter::codelet_containing(addr);
 897     if (i != nullptr) {
 898       st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an Interpreter codelet", p2i(addr), (int)(addr - i->code_begin()));
 899       i->print_on(st);
 900       return;
 901     }
 902     if (Interpreter::contains(addr)) {
 903       st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
 904                    " (not bytecode specific)", p2i(addr));
 905       return;
 906     }
 907     //
 908     if (is_adapter_blob()) {
 909       st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an AdapterHandler", p2i(addr), (int)(addr - code_begin()));
 910       AdapterHandlerLibrary::print_handler_on(st, this);
 911       return;
 912     }
 913     // the stubroutines are generated into a buffer blob
 914     StubCodeDesc* d = StubCodeDesc::desc_for(addr);
 915     if (d != nullptr) {
 916       st->print_cr(INTPTR_FORMAT " is at begin+%d in a stub", p2i(addr), (int)(addr - d->begin()));
 917       d->print_on(st);
 918       st->cr();
 919       return;
 920     }
 921     if (StubRoutines::contains(addr)) {
 922       st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) stub routine", p2i(addr));
 923       return;
 924     }
 925     VtableStub* v = VtableStubs::stub_containing(addr);
 926     if (v != nullptr) {
 927       st->print_cr(INTPTR_FORMAT " is at entry_point+%d in a vtable stub", p2i(addr), (int)(addr - v->entry_point()));
 928       v->print_on(st);
 929       st->cr();
 930       return;
 931     }
 932   }
 933   if (is_nmethod()) {
 934     nmethod* nm = as_nmethod();
 935     ResourceMark rm;
 936     st->print(INTPTR_FORMAT " is at entry_point+%d in (nmethod*)" INTPTR_FORMAT,
 937               p2i(addr), (int)(addr - nm->entry_point()), p2i(nm));
 938     if (verbose) {
 939       st->print(" for ");
 940       nm->method()->print_value_on(st);
 941     }
 942     st->cr();
 943     if (verbose && st == tty) {
 944       // verbose is only ever true when called from findpc in debug.cpp
 945       nm->print_nmethod(true);
 946     } else {
 947       nm->print_on(st);
 948       nm->print_code_snippet(st, addr);
 949     }
 950     return;
 951   }
 952   st->print_cr(INTPTR_FORMAT " is at code_begin+%d in ", p2i(addr), (int)(addr - code_begin()));
 953   print_on(st);
 954 }
 955 
 956 void BufferBlob::print_on_impl(outputStream* st) const {
 957   RuntimeBlob::print_on_impl(st);
 958   print_value_on_impl(st);
 959 }
 960 
 961 void BufferBlob::print_value_on_impl(outputStream* st) const {
 962   st->print_cr("BufferBlob (" INTPTR_FORMAT  ") used for %s", p2i(this), name());
 963 }
 964 
 965 void RuntimeStub::print_on_impl(outputStream* st) const {
 966   ttyLocker ttyl;
 967   RuntimeBlob::print_on_impl(st);
 968   st->print("Runtime Stub (" INTPTR_FORMAT "): ", p2i(this));
 969   st->print_cr("%s", name());
 970   Disassembler::decode((CodeBlob*)this, st);
 971 }
 972 
 973 void RuntimeStub::print_value_on_impl(outputStream* st) const {
 974   st->print("RuntimeStub (" INTPTR_FORMAT "): ", p2i(this)); st->print("%s", name());
 975 }
 976 
 977 void SingletonBlob::print_on_impl(outputStream* st) const {
 978   ttyLocker ttyl;
 979   RuntimeBlob::print_on_impl(st);
 980   st->print_cr("%s", name());
 981   Disassembler::decode((CodeBlob*)this, st);
 982 }
 983 
 984 void SingletonBlob::print_value_on_impl(outputStream* st) const {
 985   st->print_cr("%s", name());
 986 }
 987 
 988 void DeoptimizationBlob::print_value_on_impl(outputStream* st) const {
 989   st->print_cr("Deoptimization (frame not available)");
 990 }
 991 
 992 void UpcallStub::print_on_impl(outputStream* st) const {
 993   RuntimeBlob::print_on_impl(st);
 994   print_value_on_impl(st);
 995   st->print_cr("Frame data offset: %d", (int) _frame_data_offset);
 996   oop recv = JNIHandles::resolve(_receiver);
 997   st->print("Receiver MH=");
 998   recv->print_on(st);
 999   Disassembler::decode((CodeBlob*)this, st);
1000 }
1001 
1002 void UpcallStub::print_value_on_impl(outputStream* st) const {
1003   st->print_cr("UpcallStub (" INTPTR_FORMAT  ") used for %s", p2i(this), name());
1004 }