1 /*
  2  * Copyright (c) 1997, 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 "memory/allocation.hpp"
 26 #include "memory/allocation.inline.hpp"
 27 #include "memory/arena.hpp"
 28 #include "memory/metaspace.hpp"
 29 #include "memory/resourceArea.hpp"
 30 #include "nmt/memTracker.hpp"
 31 #include "runtime/os.hpp"
 32 #include "runtime/task.hpp"
 33 #include "runtime/threadCritical.hpp"
 34 #include "utilities/ostream.hpp"
 35 
 36 // allocate using malloc; will fail if no memory available
 37 char* AllocateHeap(size_t size,
 38                    MemTag mem_tag,
 39                    const NativeCallStack& stack,
 40                    AllocFailType alloc_failmode /* = AllocFailStrategy::EXIT_OOM*/) {
 41   char* p = (char*) os::malloc(size, mem_tag, stack);
 42   if (p == nullptr && alloc_failmode == AllocFailStrategy::EXIT_OOM) {
 43     vm_exit_out_of_memory(size, OOM_MALLOC_ERROR, "AllocateHeap");
 44   }
 45   return p;
 46 }
 47 
 48 char* AllocateHeap(size_t size,
 49                    MemTag mem_tag,
 50                    AllocFailType alloc_failmode /* = AllocFailStrategy::EXIT_OOM*/) {
 51   return AllocateHeap(size, mem_tag, CALLER_PC, alloc_failmode);
 52 }
 53 
 54 char* ReallocateHeap(char *old,
 55                      size_t size,
 56                      MemTag mem_tag,
 57                      AllocFailType alloc_failmode) {
 58   char* p = (char*) os::realloc(old, size, mem_tag, CALLER_PC);
 59   if (p == nullptr && alloc_failmode == AllocFailStrategy::EXIT_OOM) {
 60     vm_exit_out_of_memory(size, OOM_MALLOC_ERROR, "ReallocateHeap");
 61   }
 62   return p;
 63 }
 64 
 65 // handles null pointers
 66 void FreeHeap(void* p) {
 67   os::free(p);
 68 }
 69 
 70 void* MetaspaceObj::_shared_metaspace_base = nullptr;
 71 void* MetaspaceObj::_shared_metaspace_top  = nullptr;
 72 
 73 void* MetaspaceObj::operator new(size_t size, ClassLoaderData* loader_data,
 74                                  size_t word_size,
 75                                  MetaspaceObj::Type type, TRAPS) throw() {
 76   // Klass has its own operator new
 77   assert(type != ClassType, "class has its own operator new");
 78   return Metaspace::allocate(loader_data, word_size, type, /*use_class_space*/ false, THREAD);
 79 }
 80 
 81 void* MetaspaceObj::operator new(size_t size, ClassLoaderData* loader_data,
 82                                  size_t word_size,
 83                                  MetaspaceObj::Type type) throw() {
 84   assert(!Thread::current()->is_Java_thread(), "only allowed by non-Java thread");
 85   assert(type != ClassType, "class has its own operator new");
 86   return Metaspace::allocate(loader_data, word_size, type, /*use_class_space*/ false);
 87 }
 88 
 89 
 90 // Work-around -- see JDK-8331086
 91 void* MetaspaceObj::operator new(size_t size, MemTag flags) throw() {
 92   void* p = AllocateHeap(size, flags, CALLER_PC);
 93   memset(p, 0, size);
 94   return p;
 95 }
 96 
 97 bool MetaspaceObj::is_valid(const MetaspaceObj* p) {
 98   // Weed out obvious bogus values first without traversing metaspace
 99   if ((size_t)p < os::min_page_size()) {
100     return false;
101   } else if (!is_aligned((address)p, sizeof(MetaWord))) {
102     return false;
103   }
104   return Metaspace::contains((void*)p);
105 }
106 
107 void MetaspaceObj::print_address_on(outputStream* st) const {
108   st->print(" {" PTR_FORMAT "}", p2i(this));
109 }
110 
111 //
112 // ArenaObj
113 //
114 
115 void* ArenaObj::operator new(size_t size, Arena *arena) throw() {
116   return arena->Amalloc(size);
117 }
118 
119 //
120 // AnyObj
121 //
122 
123 void* AnyObj::operator new(size_t size, Arena *arena) {
124   address res = (address)arena->Amalloc(size);
125   DEBUG_ONLY(set_allocation_type(res, ARENA);)
126   return res;
127 }
128 
129 void* AnyObj::operator new(size_t size, MemTag mem_tag) throw() {
130   address res = (address)AllocateHeap(size, mem_tag, CALLER_PC);
131   DEBUG_ONLY(set_allocation_type(res, C_HEAP);)
132   return res;
133 }
134 
135 void* AnyObj::operator new(size_t size, const std::nothrow_t&  nothrow_constant,
136     MemTag mem_tag) throw() {
137   // should only call this with std::nothrow, use other operator new() otherwise
138     address res = (address)AllocateHeap(size, mem_tag, CALLER_PC, AllocFailStrategy::RETURN_NULL);
139     DEBUG_ONLY(if (res!= nullptr) set_allocation_type(res, C_HEAP);)
140   return res;
141 }
142 
143 void AnyObj::operator delete(void* p) {
144   if (p == nullptr) {
145     return;
146   }
147   assert(((AnyObj *)p)->allocated_on_C_heap(),
148          "delete only allowed for C_HEAP objects");
149   DEBUG_ONLY(((AnyObj *)p)->_allocation_t[0] = (uintptr_t)badHeapOopVal;)
150   FreeHeap(p);
151 }
152 
153 #ifdef ASSERT
154 void AnyObj::set_allocation_type(address res, allocation_type type) {
155   // Set allocation type in the resource object
156   uintptr_t allocation = (uintptr_t)res;
157   assert((allocation & allocation_mask) == 0, "address should be aligned to 4 bytes at least: " PTR_FORMAT, p2i(res));
158   assert(type <= allocation_mask, "incorrect allocation type");
159   AnyObj* resobj = (AnyObj *)res;
160   resobj->_allocation_t[0] = ~(allocation + type);
161   if (type != STACK_OR_EMBEDDED) {
162     // Called from operator new(), set verification value.
163     resobj->_allocation_t[1] = (uintptr_t)&(resobj->_allocation_t[1]) + type;
164   }
165 }
166 
167 AnyObj::allocation_type AnyObj::get_allocation_type() const {
168   assert(~(_allocation_t[0] | allocation_mask) == (uintptr_t)this, "lost resource object");
169   return (allocation_type)((~_allocation_t[0]) & allocation_mask);
170 }
171 
172 bool AnyObj::is_type_set() const {
173   allocation_type type = (allocation_type)(_allocation_t[1] & allocation_mask);
174   return get_allocation_type()  == type &&
175          (_allocation_t[1] - type) == (uintptr_t)(&_allocation_t[1]);
176 }
177 
178 // This whole business of passing information from AnyObj::operator new
179 // to the AnyObj constructor via fields in the "object" is technically UB.
180 // But it seems to work within the limitations of HotSpot usage (such as no
181 // multiple inheritance) with the compilers and compiler options we're using.
182 // And it gives some possibly useful checking for misuse of AnyObj.
183 void AnyObj::initialize_allocation_info() {
184   if (~(_allocation_t[0] | allocation_mask) != (uintptr_t)this) {
185     // Operator new() is not called for allocations
186     // on stack and for embedded objects.
187     set_allocation_type((address)this, STACK_OR_EMBEDDED);
188   } else if (allocated_on_stack_or_embedded()) { // STACK_OR_EMBEDDED
189     // For some reason we got a value which resembles
190     // an embedded or stack object (operator new() does not
191     // set such type). Keep it since it is valid value
192     // (even if it was garbage).
193     // Ignore garbage in other fields.
194   } else if (is_type_set()) {
195     // Operator new() was called and type was set.
196     assert(!allocated_on_stack_or_embedded(),
197            "not embedded or stack, this(" PTR_FORMAT ") type %d a[0]=(" PTR_FORMAT ") a[1]=(" PTR_FORMAT ")",
198            p2i(this), get_allocation_type(), _allocation_t[0], _allocation_t[1]);
199   } else {
200     // Operator new() was not called.
201     // Assume that it is embedded or stack object.
202     set_allocation_type((address)this, STACK_OR_EMBEDDED);
203   }
204   _allocation_t[1] = 0; // Zap verification value
205 }
206 
207 AnyObj::AnyObj() {
208   initialize_allocation_info();
209 }
210 
211 AnyObj::AnyObj(const AnyObj&) {
212   // Initialize _allocation_t as a new object, ignoring object being copied.
213   initialize_allocation_info();
214 }
215 
216 AnyObj& AnyObj::operator=(const AnyObj& r) {
217   assert(allocated_on_stack_or_embedded(),
218          "copy only into local, this(" PTR_FORMAT ") type %d a[0]=(" PTR_FORMAT ") a[1]=(" PTR_FORMAT ")",
219          p2i(this), get_allocation_type(), _allocation_t[0], _allocation_t[1]);
220   // Keep current _allocation_t value;
221   return *this;
222 }
223 
224 AnyObj::~AnyObj() {
225   // allocated_on_C_heap() also checks that encoded (in _allocation) address == this.
226   if (!allocated_on_C_heap()) { // AnyObj::delete() will zap _allocation for C_heap.
227     _allocation_t[0] = (uintptr_t)badHeapOopVal; // zap type
228   }
229 }
230 #endif // ASSERT
231 
232 //--------------------------------------------------------------------------------------
233 // Non-product code
234 
235 #ifndef PRODUCT
236 void AnyObj::print() const       { print_on(tty); }
237 
238 void AnyObj::print_on(outputStream* st) const {
239   st->print_cr("AnyObj(" PTR_FORMAT ")", p2i(this));
240 }
241 
242 ReallocMark::ReallocMark() {
243 #ifdef ASSERT
244   Thread *thread = Thread::current();
245   _nesting = thread->resource_area()->nesting();
246 #endif
247 }
248 
249 void ReallocMark::check(Arena* arena) {
250 #ifdef ASSERT
251   if ((arena == nullptr || arena == Thread::current()->resource_area()) &&
252       _nesting != Thread::current()->resource_area()->nesting()) {
253     fatal("allocation bug: array could grow within nested ResourceMark");
254   }
255 #endif
256 }
257 
258 #endif // Non-product