1 /*
  2  * Copyright (c) 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/moduleEntry.hpp"
 26 #include "classfile/packageEntry.hpp"
 27 #include "classfile/symbolTable.hpp"
 28 #include "classfile/vmClasses.hpp"
 29 #include "classfile/vmSymbols.hpp"
 30 #include "gc/shared/collectedHeap.inline.hpp"
 31 #include "memory/iterator.inline.hpp"
 32 #include "memory/metadataFactory.hpp"
 33 #include "memory/metaspaceClosure.hpp"
 34 #include "memory/oopFactory.hpp"
 35 #include "memory/resourceArea.hpp"
 36 #include "memory/universe.hpp"
 37 #include "oops/arrayKlass.hpp"
 38 #include "oops/instanceKlass.hpp"
 39 #include "oops/klass.inline.hpp"
 40 #include "oops/markWord.hpp"
 41 #include "oops/objArrayKlass.inline.hpp"
 42 #include "oops/oop.inline.hpp"
 43 #include "oops/oopCast.inline.hpp"
 44 #include "oops/refArrayKlass.inline.hpp"
 45 #include "oops/refArrayOop.inline.hpp"
 46 #include "oops/symbol.hpp"
 47 #include "runtime/handles.inline.hpp"
 48 #include "runtime/mutexLocker.hpp"
 49 #include "utilities/macros.hpp"
 50 
 51 RefArrayKlass *RefArrayKlass::allocate_klass(ClassLoaderData* loader_data, int n,
 52                                              Klass* k, Symbol *name, ArrayProperties props,
 53                                              TRAPS) {
 54   assert(RefArrayKlass::header_size() <= InstanceKlass::header_size(),
 55          "array klasses must be same size as InstanceKlass");
 56 
 57   int size = ArrayKlass::static_size(RefArrayKlass::header_size());
 58 
 59   return new (loader_data, size, THREAD) RefArrayKlass(n, k, name, props);
 60 }
 61 
 62 RefArrayKlass* RefArrayKlass::allocate_refArray_klass(ClassLoaderData* loader_data, int n,
 63                                                       Klass* element_klass, ArrayProperties props,
 64                                                       TRAPS) {
 65   assert(!props.is_null_restricted() || (n == 1 && element_klass->is_inline_klass()),
 66          "null-free unsupported");
 67 
 68   // Eagerly allocate the direct array supertype.
 69   Klass* super_klass = nullptr;
 70   if (!Universe::is_bootstrapping() || vmClasses::Object_klass_is_loaded()) {
 71     assert(MultiArray_lock->holds_lock(THREAD),
 72            "must hold lock after bootstrapping");
 73     super_klass = element_klass->array_klass(CHECK_NULL);
 74   }
 75 
 76   // Create type name for klass.
 77   Symbol* name = create_element_klass_array_name(THREAD, element_klass);
 78 
 79   // Initialize instance variables
 80   RefArrayKlass* oak = RefArrayKlass::allocate_klass(loader_data, n, element_klass,
 81                                                      name, props, CHECK_NULL);
 82 
 83   ModuleEntry* module = oak->module();
 84   assert(module != nullptr, "No module entry for array");
 85 
 86   // Call complete_create_array_klass after all instance variables have been
 87   // initialized.
 88   ArrayKlass::complete_create_array_klass(oak, super_klass, module, CHECK_NULL);
 89 
 90   // Add all classes to our internal class loader list here,
 91   // including classes in the bootstrap (null) class loader.
 92   // Do this step after creating the mirror so that if the
 93   // mirror creation fails, loaded_classes_do() doesn't find
 94   // an array class without a mirror.
 95   loader_data->add_class(oak);
 96 
 97   return oak;
 98 }
 99 
100 RefArrayKlass::RefArrayKlass(int n, Klass* element_klass, Symbol* name,
101                              ArrayProperties props)
102     : ObjArrayKlass(n, element_klass, name, Kind, props) {
103   assert(is_refArray_klass(), "sanity");
104 }
105 
106 size_t RefArrayKlass::oop_size(oop obj) const {
107   // In this assert, we cannot safely access the Klass* with compact headers,
108   // because size_given_klass() calls oop_size() on objects that might be
109   // concurrently forwarded, which would overwrite the Klass*.
110   assert(UseCompactObjectHeaders || obj->is_refArray(), "must be a reference array");
111   return refArrayOop(obj)->object_size();
112 }
113 
114 refArrayOop RefArrayKlass::allocate_instance(int length, TRAPS) {
115   check_array_allocation_length(length, arrayOopDesc::max_array_length(T_OBJECT), CHECK_NULL);
116   size_t size = refArrayOopDesc::object_size(length);
117   oop array = Universe::heap()->array_allocate(
118       this, size, length, /* do_zero */ true, CHECK_NULL);
119   return oop_cast<refArrayOop>(array);
120 }
121 
122 static void throw_array_null_pointer_store_exception(arrayOop src, arrayOop dst, TRAPS) {
123   ResourceMark rm(THREAD);
124   Klass* bound = ObjArrayKlass::cast(dst->klass())->element_klass();
125   stringStream ss;
126   ss.print("arraycopy: can not copy null values into %s[]",
127            bound->external_name());
128   THROW_MSG(vmSymbols::java_lang_NullPointerException(), ss.as_string());
129 }
130 
131 static void throw_array_store_exception(arrayOop src, arrayOop dst, TRAPS) {
132   ResourceMark rm(THREAD);
133   Klass* bound = ObjArrayKlass::cast(dst->klass())->element_klass();
134   Klass* stype = ObjArrayKlass::cast(src->klass())->element_klass();
135   stringStream ss;
136   if (!bound->is_subtype_of(stype)) {
137     ss.print("arraycopy: type mismatch: can not copy %s[] into %s[]",
138              stype->external_name(), bound->external_name());
139   } else {
140     // oop_arraycopy should return the index in the source array that
141     // contains the problematic oop.
142     ss.print("arraycopy: element type mismatch: can not cast one of the elements"
143              " of %s[] to the type of the destination array, %s",
144              stype->external_name(), bound->external_name());
145   }
146   THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
147 }
148 
149 // Either oop or narrowOop depending on UseCompressedOops.
150 void RefArrayKlass::do_copy(arrayOop s, size_t src_offset, arrayOop d,
151                             size_t dst_offset, int length, TRAPS) {
152   if (s == d) {
153     // since source and destination are equal we do not need conversion checks.
154     assert(length > 0, "sanity check");
155     OopCopyResult result = ArrayAccess<>::oop_arraycopy(s, src_offset, d, dst_offset, length);
156     assert(result == OopCopyResult::ok, "Should never fail");
157   } else {
158     // Perform null check if dst is null-free but src has no such guarantee
159     bool null_check = ((!s->klass()->is_null_free_array_klass()) &&
160                        d->klass()->is_null_free_array_klass());
161     // We have to make sure all elements conform to the destination array
162     Klass *bound = RefArrayKlass::cast(d->klass())->element_klass();
163     Klass *stype = RefArrayKlass::cast(s->klass())->element_klass();
164     bool type_check = stype != bound && !stype->is_subtype_of(bound);
165 
166     auto arraycopy = [&] {
167       if (type_check) {
168         if (null_check) {
169           return ArrayAccess<ARRAYCOPY_DISJOINT | ARRAYCOPY_CHECKCAST | ARRAYCOPY_NOTNULL>::
170               oop_arraycopy(s, src_offset, d, dst_offset, length);
171         } else {
172           return ArrayAccess<ARRAYCOPY_DISJOINT | ARRAYCOPY_CHECKCAST>::
173               oop_arraycopy(s, src_offset, d, dst_offset, length);
174         }
175       } else {
176         if (null_check) {
177           return ArrayAccess<ARRAYCOPY_DISJOINT | ARRAYCOPY_NOTNULL>::
178               oop_arraycopy(s, src_offset, d, dst_offset, length);
179         } else {
180           return ArrayAccess<ARRAYCOPY_DISJOINT>::
181               oop_arraycopy(s, src_offset, d, dst_offset, length);
182         }
183       }
184     };
185 
186     OopCopyResult result = arraycopy();
187 
188     switch (result) {
189     case OopCopyResult::ok:
190       // Done
191       break;
192     case OopCopyResult::failed_check_class_cast:
193       throw_array_store_exception(s, d, JavaThread::current());
194       break;
195     case OopCopyResult::failed_check_null:
196       throw_array_null_pointer_store_exception(s, d, JavaThread::current());
197       break;
198     default:
199       ShouldNotReachHere();
200     }
201   }
202 }
203 
204 void RefArrayKlass::copy_array(arrayOop s, int src_pos, arrayOop d, int dst_pos,
205                                int length, TRAPS) {
206   assert(s->is_refArray(), "must be a reference array");
207 
208   if (UseArrayFlattening && d->is_flatArray()) {
209     FlatArrayKlass::cast(d->klass())->copy_array(s, src_pos, d, dst_pos, length, THREAD);
210     return;
211   }
212 
213   if (!d->is_refArray()) {
214     ResourceMark rm(THREAD);
215     stringStream ss;
216     if (d->is_typeArray()) {
217       ss.print(
218           "arraycopy: type mismatch: can not copy object array[] into %s[]",
219           type2name_tab[ArrayKlass::cast(d->klass())->element_type()]);
220     } else {
221       ss.print("arraycopy: destination type %s is not an array",
222                d->klass()->external_name());
223     }
224     THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
225   }
226 
227   // Check if all offsets and lengths are non negative
228   if (src_pos < 0 || dst_pos < 0 || length < 0) {
229     // Pass specific exception reason.
230     ResourceMark rm(THREAD);
231     stringStream ss;
232     if (src_pos < 0) {
233       ss.print("arraycopy: source index %d out of bounds for object array[%d]",
234                src_pos, s->length());
235     } else if (dst_pos < 0) {
236       ss.print(
237           "arraycopy: destination index %d out of bounds for object array[%d]",
238           dst_pos, d->length());
239     } else {
240       ss.print("arraycopy: length %d is negative", length);
241     }
242     THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(),
243               ss.as_string());
244   }
245 
246   // Check if the ranges are valid
247   if ((((unsigned int)length + (unsigned int)src_pos) >
248        (unsigned int)s->length()) ||
249       (((unsigned int)length + (unsigned int)dst_pos) >
250        (unsigned int)d->length())) {
251     // Pass specific exception reason.
252     ResourceMark rm(THREAD);
253     stringStream ss;
254     if (((unsigned int)length + (unsigned int)src_pos) >
255         (unsigned int)s->length()) {
256       ss.print(
257           "arraycopy: last source index %u out of bounds for object array[%d]",
258           (unsigned int)length + (unsigned int)src_pos, s->length());
259     } else {
260       ss.print("arraycopy: last destination index %u out of bounds for object "
261                "array[%d]",
262                (unsigned int)length + (unsigned int)dst_pos, d->length());
263     }
264     THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(),
265               ss.as_string());
266   }
267 
268   // Special case. Boundary cases must be checked first
269   // This allows the following call: copy_array(s, s.length(), d.length(), 0).
270   // This is correct, since the position is supposed to be an 'in between
271   // point', i.e., s.length(), points to the right of the last element.
272   if (length == 0) {
273     return;
274   }
275   if (UseCompressedOops) {
276     size_t src_offset =
277         (size_t)refArrayOopDesc::obj_at_offset<narrowOop>(src_pos);
278     size_t dst_offset =
279         (size_t)refArrayOopDesc::obj_at_offset<narrowOop>(dst_pos);
280     assert(arrayOopDesc::obj_offset_to_raw<narrowOop>(s, src_offset, nullptr) ==
281                refArrayOop(s)->obj_at_addr<narrowOop>(src_pos),
282            "sanity");
283     assert(arrayOopDesc::obj_offset_to_raw<narrowOop>(d, dst_offset, nullptr) ==
284                refArrayOop(d)->obj_at_addr<narrowOop>(dst_pos),
285            "sanity");
286     do_copy(s, src_offset, d, dst_offset, length, CHECK);
287   } else {
288     size_t src_offset = (size_t)refArrayOopDesc::obj_at_offset<oop>(src_pos);
289     size_t dst_offset = (size_t)refArrayOopDesc::obj_at_offset<oop>(dst_pos);
290     assert(arrayOopDesc::obj_offset_to_raw<oop>(s, src_offset, nullptr) ==
291                refArrayOop(s)->obj_at_addr<oop>(src_pos),
292            "sanity");
293     assert(arrayOopDesc::obj_offset_to_raw<oop>(d, dst_offset, nullptr) ==
294                refArrayOop(d)->obj_at_addr<oop>(dst_pos),
295            "sanity");
296     do_copy(s, src_offset, d, dst_offset, length, CHECK);
297   }
298 }
299 
300 void RefArrayKlass::initialize(TRAPS) {
301   bottom_klass()->initialize(THREAD); // dispatches to either InstanceKlass or TypeArrayKlass
302 }
303 
304 void RefArrayKlass::metaspace_pointers_do(MetaspaceClosure *it) {
305   ObjArrayKlass::metaspace_pointers_do(it);
306 }
307 
308 // Printing
309 
310 void RefArrayKlass::print_on(outputStream* st) const {
311 #ifndef PRODUCT
312   Klass::print_on(st);
313   st->print(" - element klass: ");
314   element_klass()->print_value_on(st);
315   st->cr();
316 #endif // PRODUCT
317 }
318 
319 void RefArrayKlass::print_value_on(outputStream* st) const {
320   assert(is_klass(), "must be klass");
321 
322   element_klass()->print_value_on(st);
323   st->print("[]");
324 }
325 
326 #ifndef PRODUCT
327 
328 void RefArrayKlass::oop_print_on(oop obj, outputStream* st) {
329   ArrayKlass::oop_print_on(obj, st);
330   assert(obj->is_refArray(), "must be refArray");
331   refArrayOop oa = refArrayOop(obj);
332   int print_len = MIN2(oa->length(), MaxElementPrintSize);
333   for (int index = 0; index < print_len; index++) {
334     st->print(" - %3d : ", index);
335     if (oa->obj_at(index) != nullptr) {
336       oa->obj_at(index)->print_value_on(st);
337       st->cr();
338     } else {
339       st->print_cr("null");
340     }
341   }
342   int remaining = oa->length() - print_len;
343   if (remaining > 0) {
344     st->print_cr(" - <%d more elements, increase MaxElementPrintSize to print>",
345                  remaining);
346   }
347 }
348 
349 #endif // PRODUCT
350 
351 void RefArrayKlass::oop_print_value_on(oop obj, outputStream* st) {
352   assert(obj->is_refArray(), "must be refArray");
353   st->print("a ");
354   element_klass()->print_value_on(st);
355   int len = refArrayOop(obj)->length();
356   st->print("[%d] ", len);
357   if (obj != nullptr) {
358     obj->print_address_on(st);
359   } else {
360     st->print_cr("null");
361   }
362 }
363 
364 // Verification
365 
366 void RefArrayKlass::verify_on(outputStream* st) {
367   ArrayKlass::verify_on(st);
368   guarantee(element_klass()->is_klass(), "should be klass");
369   guarantee(bottom_klass()->is_klass(), "should be klass");
370   Klass *bk = bottom_klass();
371   guarantee(bk->is_instance_klass() || bk->is_typeArray_klass(),
372             "invalid bottom klass");
373 }
374 
375 void RefArrayKlass::oop_verify_on(oop obj, outputStream* st) {
376   ObjArrayKlass::oop_verify_on(obj, st);
377   guarantee(obj->is_refArray(), "must be refArray");
378 
379   refArrayOop oa = refArrayOop(obj);
380   for (int index = 0; index < oa->length(); index++) {
381     guarantee(oopDesc::is_oop_or_null(oa->obj_at(index)), "should be oop");
382   }
383 }