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