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