1 /*
  2  * Copyright (c) 2018, 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 "classfile/javaClasses.hpp"
 26 #include "classfile/vmClasses.hpp"
 27 #include "gc/shared/allocTracer.hpp"
 28 #include "gc/shared/collectedHeap.hpp"
 29 #include "gc/shared/memAllocator.hpp"
 30 #include "gc/shared/threadLocalAllocBuffer.inline.hpp"
 31 #include "gc/shared/tlab_globals.hpp"
 32 #include "memory/universe.hpp"
 33 #include "oops/arrayOop.hpp"
 34 #include "oops/oop.inline.hpp"
 35 #include "prims/jvmtiExport.hpp"
 36 #include "runtime/continuationJavaClasses.inline.hpp"
 37 #include "runtime/handles.inline.hpp"
 38 #include "runtime/sharedRuntime.hpp"
 39 #include "runtime/javaThread.hpp"
 40 #include "services/lowMemoryDetector.hpp"
 41 #include "utilities/align.hpp"
 42 #include "utilities/copy.hpp"
 43 #include "utilities/globalDefinitions.hpp"
 44 
 45 class MemAllocator::Allocation: StackObj {
 46   friend class MemAllocator;
 47 
 48   const MemAllocator& _allocator;
 49   JavaThread*         _thread;
 50   oop*                _obj_ptr;
 51   bool                _overhead_limit_exceeded;
 52   bool                _allocated_outside_tlab;
 53   size_t              _allocated_tlab_size;
 54   bool                _tlab_end_reset_for_sample;
 55 
 56   bool check_out_of_memory();
 57   void verify_before();
 58   void verify_after();
 59   void notify_allocation();
 60   void notify_allocation_jvmti_sampler();
 61   void notify_allocation_low_memory_detector();
 62   void notify_allocation_jfr_sampler();
 63   void notify_allocation_dtrace_sampler();
 64 #ifdef ASSERT
 65   void check_for_valid_allocation_state() const;
 66 #endif
 67 
 68   class PreserveObj;
 69 
 70 public:
 71   Allocation(const MemAllocator& allocator, oop* obj_ptr)
 72     : _allocator(allocator),
 73       _thread(JavaThread::cast(allocator._thread)), // Do not use Allocation in non-JavaThreads.
 74       _obj_ptr(obj_ptr),
 75       _overhead_limit_exceeded(false),
 76       _allocated_outside_tlab(false),
 77       _allocated_tlab_size(0),
 78       _tlab_end_reset_for_sample(false)
 79   {
 80     assert(Thread::current() == allocator._thread, "do not pass MemAllocator across threads");
 81     verify_before();
 82   }
 83 
 84   ~Allocation() {
 85     if (!check_out_of_memory()) {
 86       notify_allocation();
 87     }
 88   }
 89 
 90   oop obj() const { return *_obj_ptr; }
 91 };
 92 
 93 class MemAllocator::Allocation::PreserveObj: StackObj {
 94   HandleMark _handle_mark;
 95   Handle     _handle;
 96   oop* const _obj_ptr;
 97 
 98 public:
 99   PreserveObj(JavaThread* thread, oop* obj_ptr)
100     : _handle_mark(thread),
101       _handle(thread, *obj_ptr),
102       _obj_ptr(obj_ptr)
103   {
104     *obj_ptr = nullptr;
105   }
106 
107   ~PreserveObj() {
108     *_obj_ptr = _handle();
109   }
110 
111   oop operator()() const {
112     return _handle();
113   }
114 };
115 
116 bool MemAllocator::Allocation::check_out_of_memory() {
117   JavaThread* THREAD = _thread; // For exception macros.
118   assert(!HAS_PENDING_EXCEPTION, "Unexpected exception, will result in uninitialized storage");
119 
120   if (obj() != nullptr) {
121     return false;
122   }
123 
124   const char* message = _overhead_limit_exceeded ? "GC overhead limit exceeded" : "Java heap space";
125   if (!_thread->is_in_internal_oome_mark()) {
126     // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
127     report_java_out_of_memory(message);
128     if (JvmtiExport::should_post_resource_exhausted()) {
129       JvmtiExport::post_resource_exhausted(
130         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_JAVA_HEAP,
131         message);
132     }
133 
134     oop exception = _overhead_limit_exceeded ?
135         Universe::out_of_memory_error_gc_overhead_limit() :
136         Universe::out_of_memory_error_java_heap();
137     THROW_OOP_(exception, true);
138   } else {
139     THROW_OOP_(Universe::out_of_memory_error_java_heap_without_backtrace(), true);
140   }
141 }
142 
143 void MemAllocator::Allocation::verify_before() {
144   // Clear unhandled oops for memory allocation.  Memory allocation might
145   // not take out a lock if from tlab, so clear here.
146   JavaThread* THREAD = _thread; // For exception macros.
147   assert(!HAS_PENDING_EXCEPTION, "Should not allocate with exception pending");
148   debug_only(check_for_valid_allocation_state());
149   assert(!Universe::heap()->is_stw_gc_active(), "Allocation during GC pause not allowed");
150 }
151 
152 #ifdef ASSERT
153 void MemAllocator::Allocation::check_for_valid_allocation_state() const {
154   // How to choose between a pending exception and a potential
155   // OutOfMemoryError?  Don't allow pending exceptions.
156   // This is a VM policy failure, so how do we exhaustively test it?
157   assert(!_thread->has_pending_exception(),
158          "shouldn't be allocating with pending exception");
159   // Allocation of an oop can always invoke a safepoint.
160   _thread->check_for_valid_safepoint_state();
161 }
162 #endif
163 
164 void MemAllocator::Allocation::notify_allocation_jvmti_sampler() {
165   // support for JVMTI VMObjectAlloc event (no-op if not enabled)
166   JvmtiExport::vm_object_alloc_event_collector(obj());
167 
168   if (!JvmtiExport::should_post_sampled_object_alloc()) {
169     // Sampling disabled
170     return;
171   }
172 
173   if (!_allocated_outside_tlab && _allocated_tlab_size == 0 && !_tlab_end_reset_for_sample) {
174     // Sample if it's a non-TLAB allocation, or a TLAB allocation that either refills the TLAB
175     // or expands it due to taking a sampler induced slow path.
176     return;
177   }
178 
179   // If we want to be sampling, protect the allocated object with a Handle
180   // before doing the callback. The callback is done in the destructor of
181   // the JvmtiSampledObjectAllocEventCollector.
182   size_t bytes_since_last = 0;
183 
184   {
185     PreserveObj obj_h(_thread, _obj_ptr);
186     JvmtiSampledObjectAllocEventCollector collector;
187     size_t size_in_bytes = _allocator._word_size * HeapWordSize;
188     ThreadLocalAllocBuffer& tlab = _thread->tlab();
189 
190     if (!_allocated_outside_tlab) {
191       bytes_since_last = tlab.bytes_since_last_sample_point();
192     }
193 
194     _thread->heap_sampler().check_for_sampling(obj_h(), size_in_bytes, bytes_since_last);
195   }
196 
197   if (_tlab_end_reset_for_sample || _allocated_tlab_size != 0) {
198     // Tell tlab to forget bytes_since_last if we passed it to the heap sampler.
199     _thread->tlab().set_sample_end(bytes_since_last != 0);
200   }
201 }
202 
203 void MemAllocator::Allocation::notify_allocation_low_memory_detector() {
204   // support low memory notifications (no-op if not enabled)
205   LowMemoryDetector::detect_low_memory_for_collected_pools();
206 }
207 
208 void MemAllocator::Allocation::notify_allocation_jfr_sampler() {
209   HeapWord* mem = cast_from_oop<HeapWord*>(obj());
210   size_t size_in_bytes = _allocator._word_size * HeapWordSize;
211 
212   if (_allocated_outside_tlab) {
213     AllocTracer::send_allocation_outside_tlab(obj()->klass(), mem, size_in_bytes, _thread);
214   } else if (_allocated_tlab_size != 0) {
215     // TLAB was refilled
216     AllocTracer::send_allocation_in_new_tlab(obj()->klass(), mem, _allocated_tlab_size * HeapWordSize,
217                                              size_in_bytes, _thread);
218   }
219 }
220 
221 void MemAllocator::Allocation::notify_allocation_dtrace_sampler() {
222   if (DTraceAllocProbes) {
223     // support for Dtrace object alloc event (no-op most of the time)
224     Klass* klass = obj()->klass();
225     size_t word_size = _allocator._word_size;
226     if (klass != nullptr && klass->name() != nullptr) {
227       SharedRuntime::dtrace_object_alloc(_thread, obj(), word_size);
228     }
229   }
230 }
231 
232 void MemAllocator::Allocation::notify_allocation() {
233   notify_allocation_low_memory_detector();
234   notify_allocation_jfr_sampler();
235   notify_allocation_dtrace_sampler();
236   notify_allocation_jvmti_sampler();
237 }
238 
239 HeapWord* MemAllocator::mem_allocate_outside_tlab(Allocation& allocation) const {
240   allocation._allocated_outside_tlab = true;
241   HeapWord* mem = Universe::heap()->mem_allocate(_word_size, &allocation._overhead_limit_exceeded);
242   if (mem == nullptr) {
243     return mem;
244   }
245 
246   size_t size_in_bytes = _word_size * HeapWordSize;
247   _thread->incr_allocated_bytes(size_in_bytes);
248 
249   return mem;
250 }
251 
252 HeapWord* MemAllocator::mem_allocate_inside_tlab_fast() const {
253   return _thread->tlab().allocate(_word_size);
254 }
255 
256 HeapWord* MemAllocator::mem_allocate_inside_tlab_slow(Allocation& allocation) const {
257   HeapWord* mem = nullptr;
258   ThreadLocalAllocBuffer& tlab = _thread->tlab();
259 
260   if (JvmtiExport::should_post_sampled_object_alloc()) {
261     tlab.set_back_allocation_end();
262     mem = tlab.allocate(_word_size);
263 
264     // We set back the allocation sample point to try to allocate this, reset it
265     // when done.
266     allocation._tlab_end_reset_for_sample = true;
267 
268     if (mem != nullptr) {
269       return mem;
270     }
271   }
272 
273   // Retain tlab and allocate object in shared space if
274   // the amount free in the tlab is too large to discard.
275   if (tlab.free() > tlab.refill_waste_limit()) {
276     tlab.record_slow_allocation(_word_size);
277     return nullptr;
278   }
279 
280   // Discard tlab and allocate a new one.
281   // To minimize fragmentation, the last TLAB may be smaller than the rest.
282   size_t new_tlab_size = tlab.compute_size(_word_size);
283 
284   tlab.retire_before_allocation();
285 
286   if (new_tlab_size == 0) {
287     return nullptr;
288   }
289 
290   // Allocate a new TLAB requesting new_tlab_size. Any size
291   // between minimal and new_tlab_size is accepted.
292   size_t min_tlab_size = ThreadLocalAllocBuffer::compute_min_size(_word_size);
293   mem = Universe::heap()->allocate_new_tlab(min_tlab_size, new_tlab_size, &allocation._allocated_tlab_size);
294   if (mem == nullptr) {
295     assert(allocation._allocated_tlab_size == 0,
296            "Allocation failed, but actual size was updated. min: %zu"
297            ", desired: %zu, actual: %zu",
298            min_tlab_size, new_tlab_size, allocation._allocated_tlab_size);
299     return nullptr;
300   }
301   assert(allocation._allocated_tlab_size != 0, "Allocation succeeded but actual size not updated. mem at: "
302          PTR_FORMAT " min: %zu, desired: %zu",
303          p2i(mem), min_tlab_size, new_tlab_size);
304 
305   // ...and clear or zap just allocated TLAB, if needed.
306   if (ZeroTLAB) {
307     Copy::zero_to_words(mem, allocation._allocated_tlab_size);
308   } else if (ZapTLAB) {
309     // Skip mangling the space corresponding to the object header to
310     // ensure that the returned space is not considered parsable by
311     // any concurrent GC thread.
312     size_t hdr_size = oopDesc::header_size();
313     Copy::fill_to_words(mem + hdr_size, allocation._allocated_tlab_size - hdr_size, badHeapWordVal);
314   }
315 
316   tlab.fill(mem, mem + _word_size, allocation._allocated_tlab_size);
317   return mem;
318 }
319 
320 HeapWord* MemAllocator::mem_allocate(Allocation& allocation) const {
321   if (UseTLAB) {
322     // Try allocating from an existing TLAB.
323     HeapWord* mem = mem_allocate_inside_tlab_fast();
324     if (mem != nullptr) {
325       return mem;
326     }
327   }
328 
329   // Allocation of an oop can always invoke a safepoint.
330   debug_only(allocation._thread->check_for_valid_safepoint_state());
331 
332   if (UseTLAB) {
333     // Try refilling the TLAB and allocating the object in it.
334     HeapWord* mem = mem_allocate_inside_tlab_slow(allocation);
335     if (mem != nullptr) {
336       return mem;
337     }
338   }
339 
340   return mem_allocate_outside_tlab(allocation);
341 }
342 
343 oop MemAllocator::allocate() const {
344   oop obj = nullptr;
345   {
346     Allocation allocation(*this, &obj);
347     HeapWord* mem = mem_allocate(allocation);
348     if (mem != nullptr) {
349       obj = initialize(mem);
350     } else {
351       // The unhandled oop detector will poison local variable obj,
352       // so reset it to null if mem is null.
353       obj = nullptr;
354     }
355   }
356   return obj;
357 }
358 
359 void MemAllocator::mem_clear(HeapWord* mem) const {
360   assert(mem != nullptr, "cannot initialize null object");
361   const size_t hs = oopDesc::header_size();
362   assert(_word_size >= hs, "unexpected object size");
363   if (oopDesc::has_klass_gap()) {
364     oopDesc::set_klass_gap(mem, 0);
365   }
366   Copy::fill_to_aligned_words(mem + hs, _word_size - hs);
367 }
368 
369 oop MemAllocator::finish(HeapWord* mem) const {
370   assert(mem != nullptr, "null object pointer");
371   // Need a release store to ensure array/class length, mark word, and
372   // object zeroing are visible before setting the klass non-null, for
373   // concurrent collectors.
374   if (UseCompactObjectHeaders) {
375     oopDesc::release_set_mark(mem, _klass->prototype_header());
376   } else {
377     oopDesc::set_mark(mem, markWord::prototype());
378     oopDesc::release_set_klass(mem, _klass);
379   }
380   return cast_to_oop(mem);
381 }
382 
383 oop ObjAllocator::initialize(HeapWord* mem) const {
384   mem_clear(mem);
385   return finish(mem);
386 }
387 
388 oop ObjArrayAllocator::initialize(HeapWord* mem) const {
389   // Set array length before setting the _klass field because a
390   // non-null klass field indicates that the object is parsable by
391   // concurrent GC.
392   assert(_length >= 0, "length should be non-negative");
393   if (_do_zero) {
394     mem_clear(mem);
395     mem_zap_start_padding(mem);
396     mem_zap_end_padding(mem);
397   }
398   arrayOopDesc::set_length(mem, _length);
399   return finish(mem);
400 }
401 
402 #ifndef PRODUCT
403 void ObjArrayAllocator::mem_zap_start_padding(HeapWord* mem) const {
404   const BasicType element_type = ArrayKlass::cast(_klass)->element_type();
405   const size_t base_offset_in_bytes = arrayOopDesc::base_offset_in_bytes(element_type);
406   const size_t header_size_in_bytes = arrayOopDesc::header_size_in_bytes();
407 
408   const address base = reinterpret_cast<address>(mem) + base_offset_in_bytes;
409   const address header_end = reinterpret_cast<address>(mem) + header_size_in_bytes;
410 
411   if (header_end < base) {
412     const size_t padding_in_bytes = base - header_end;
413     Copy::fill_to_bytes(header_end, padding_in_bytes, heapPaddingByteVal);
414   }
415 }
416 
417 void ObjArrayAllocator::mem_zap_end_padding(HeapWord* mem) const {
418   const size_t length_in_bytes = static_cast<size_t>(_length) << ArrayKlass::cast(_klass)->log2_element_size();
419   const BasicType element_type = ArrayKlass::cast(_klass)->element_type();
420   const size_t base_offset_in_bytes = arrayOopDesc::base_offset_in_bytes(element_type);
421   const size_t size_in_bytes = _word_size * BytesPerWord;
422 
423   const address obj_end = reinterpret_cast<address>(mem) + size_in_bytes;
424   const address base = reinterpret_cast<address>(mem) + base_offset_in_bytes;
425   const address elements_end = base + length_in_bytes;
426   assert(elements_end <= obj_end, "payload must fit in object");
427   if (elements_end < obj_end) {
428     const size_t padding_in_bytes = obj_end - elements_end;
429     Copy::fill_to_bytes(elements_end, padding_in_bytes, heapPaddingByteVal);
430   }
431 }
432 #endif
433 
434 oop ClassAllocator::initialize(HeapWord* mem) const {
435   // Set oop_size field before setting the _klass field because a
436   // non-null _klass field indicates that the object is parsable by
437   // concurrent GC.
438   assert(_base_size > 0, "oop_size must be positive.");
439   mem_clear(mem);
440   java_lang_Class::set_oop_size(mem, _base_size);
441   return finish(mem);
442 }