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