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/refArrayKlass.inline.hpp"
 44 #include "oops/refArrayOop.inline.hpp"
 45 #include "oops/symbol.hpp"
 46 #include "runtime/handles.inline.hpp"
 47 #include "runtime/mutexLocker.hpp"
 48 #include "utilities/macros.hpp"
 49 
 50 RefArrayKlass *RefArrayKlass::allocate_klass(ClassLoaderData* loader_data, int n,
 51                                        Klass* k, Symbol *name, ArrayKlass::ArrayProperties props,
 52                                        TRAPS) {
 53   assert(RefArrayKlass::header_size() <= InstanceKlass::header_size(),
 54          "array klasses must be same size as InstanceKlass");
 55 
 56   int size = ArrayKlass::static_size(RefArrayKlass::header_size());
 57 
 58   return new (loader_data, size, THREAD) RefArrayKlass(n, k, name, props);
 59 }
 60 
 61 RefArrayKlass* RefArrayKlass::allocate_refArray_klass(ClassLoaderData* loader_data, int n,
 62                                        Klass* element_klass, ArrayKlass::ArrayProperties props,
 63                                        TRAPS) {
 64   assert(!ArrayKlass::is_null_restricted(props) || (n == 1 && element_klass->is_inline_klass()),
 65          "null-free unsupported");
 66 
 67   // Eagerly allocate the direct array supertype.
 68   Klass* super_klass = nullptr;
 69   if (!Universe::is_bootstrapping() || vmClasses::Object_klass_is_loaded()) {
 70     assert(MultiArray_lock->holds_lock(THREAD),
 71            "must hold lock after bootstrapping");
 72     Klass* element_super = element_klass->super();
 73     super_klass = element_klass->array_klass(CHECK_NULL);
 74   }
 75 
 76   // Create type name for klass.
 77   Symbol* name = ArrayKlass::create_element_klass_array_name(element_klass, CHECK_NULL);
 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 has 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                              ArrayKlass::ArrayProperties props)
102     : ObjArrayKlass(n, element_klass, name, Kind, props,
103                     ArrayKlass::is_null_restricted(props) ? markWord::null_free_array_prototype() : markWord::prototype()) {
104   set_dimension(n);
105   set_element_klass(element_klass);
106 
107   Klass* bk;
108   if (element_klass->is_objArray_klass()) {
109     bk = ObjArrayKlass::cast(element_klass)->bottom_klass();
110   } else {
111     bk = element_klass;
112   }
113   assert(bk != nullptr && (bk->is_instance_klass() || bk->is_typeArray_klass()),
114          "invalid bottom klass");
115   set_bottom_klass(bk);
116   set_class_loader_data(bk->class_loader_data());
117 
118   if (element_klass->is_array_klass()) {
119     set_lower_dimension(ArrayKlass::cast(element_klass));
120   }
121 
122   int lh = array_layout_helper(T_OBJECT);
123   if (ArrayKlass::is_null_restricted(props)) {
124     assert(n == 1, "Bytecode does not support null-free multi-dim");
125     lh = layout_helper_set_null_free(lh);
126 #ifdef _LP64
127     assert(prototype_header().is_null_free_array(), "sanity");
128 #endif
129   }
130   set_layout_helper(lh);
131   assert(is_array_klass(), "sanity");
132   assert(is_refArray_klass(), "sanity");
133 }
134 
135 size_t RefArrayKlass::oop_size(oop obj) const {
136   // In this assert, we cannot safely access the Klass* with compact headers,
137   // because size_given_klass() calls oop_size() on objects that might be
138   // concurrently forwarded, which would overwrite the Klass*.
139   assert(UseCompactObjectHeaders || obj->is_refArray(), "must be a reference array");
140   return refArrayOop(obj)->object_size();
141 }
142 
143 objArrayOop RefArrayKlass::allocate_instance(int length, ArrayProperties props, TRAPS) {
144   check_array_allocation_length(
145       length, arrayOopDesc::max_array_length(T_OBJECT), CHECK_NULL);
146   size_t size = refArrayOopDesc::object_size(length);
147   objArrayOop array = (objArrayOop)Universe::heap()->array_allocate(
148       this, size, length,
149       /* do_zero */ true, CHECK_NULL);
150   assert(array->is_refArray(), "Must be");
151   return array;
152 }
153 
154 static void throw_array_null_pointer_store_exception(arrayOop src, arrayOop dst, TRAPS) {
155   ResourceMark rm(THREAD);
156   Klass* bound = ObjArrayKlass::cast(dst->klass())->element_klass();
157   stringStream ss;
158   ss.print("arraycopy: can not copy null values into %s[]",
159            bound->external_name());
160   THROW_MSG(vmSymbols::java_lang_NullPointerException(), ss.as_string());
161 }
162 
163 static void throw_array_store_exception(arrayOop src, arrayOop dst, TRAPS) {
164   ResourceMark rm(THREAD);
165   Klass* bound = ObjArrayKlass::cast(dst->klass())->element_klass();
166   Klass* stype = ObjArrayKlass::cast(src->klass())->element_klass();
167   stringStream ss;
168   if (!bound->is_subtype_of(stype)) {
169     ss.print("arraycopy: type mismatch: can not copy %s[] into %s[]",
170              stype->external_name(), bound->external_name());
171   } else {
172     // oop_arraycopy should return the index in the source array that
173     // contains the problematic oop.
174     ss.print("arraycopy: element type mismatch: can not cast one of the elements"
175              " of %s[] to the type of the destination array, %s",
176              stype->external_name(), bound->external_name());
177   }
178   THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
179 }
180 
181 
182 // Either oop or narrowOop depending on UseCompressedOops.
183 void RefArrayKlass::do_copy(arrayOop s, size_t src_offset, arrayOop d,
184                             size_t dst_offset, int length, TRAPS) {
185   if (s == d) {
186     // since source and destination are equal we do not need conversion checks.
187     assert(length > 0, "sanity check");
188     OopCopyResult result = ArrayAccess<>::oop_arraycopy(s, src_offset, d, dst_offset, length);
189     assert(result == OopCopyResult::ok, "Should never fail");
190   } else {
191     // Perform null check if dst is null-free but src has no such guarantee
192     bool null_check = ((!s->klass()->is_null_free_array_klass()) &&
193                        d->klass()->is_null_free_array_klass());
194     // We have to make sure all elements conform to the destination array
195     Klass *bound = RefArrayKlass::cast(d->klass())->element_klass();
196     Klass *stype = RefArrayKlass::cast(s->klass())->element_klass();
197     bool type_check = stype != bound && !stype->is_subtype_of(bound);
198 
199     auto arraycopy = [&] {
200       if (type_check) {
201         if (null_check) {
202           return ArrayAccess<ARRAYCOPY_DISJOINT | ARRAYCOPY_CHECKCAST | ARRAYCOPY_NOTNULL>::
203               oop_arraycopy(s, src_offset, d, dst_offset, length);
204         } else {
205           return ArrayAccess<ARRAYCOPY_DISJOINT | ARRAYCOPY_CHECKCAST>::
206               oop_arraycopy(s, src_offset, d, dst_offset, length);
207         }
208       } else {
209         if (null_check) {
210           return ArrayAccess<ARRAYCOPY_DISJOINT | ARRAYCOPY_NOTNULL>::
211               oop_arraycopy(s, src_offset, d, dst_offset, length);
212         } else {
213           return ArrayAccess<ARRAYCOPY_DISJOINT>::
214               oop_arraycopy(s, src_offset, d, dst_offset, length);
215         }
216       }
217     };
218 
219     OopCopyResult result = arraycopy();
220 
221     switch (result) {
222     case OopCopyResult::ok:
223       // Done
224       break;
225     case OopCopyResult::failed_check_class_cast:
226       throw_array_store_exception(s, d, JavaThread::current());
227       break;
228     case OopCopyResult::failed_check_null:
229       throw_array_null_pointer_store_exception(s, d, JavaThread::current());
230       break;
231     default:
232       ShouldNotReachHere();
233     }
234   }
235 }
236 
237 void RefArrayKlass::copy_array(arrayOop s, int src_pos, arrayOop d, int dst_pos,
238                                int length, TRAPS) {
239   assert(s->is_refArray(), "must be a reference array");
240 
241   if (UseArrayFlattening) {
242     if (d->is_flatArray()) {
243       FlatArrayKlass::cast(d->klass())->copy_array(s, src_pos, d, dst_pos, length, THREAD);
244       return;
245     }
246     if (s->is_flatArray()) {
247       FlatArrayKlass::cast(s->klass())->copy_array(s, src_pos, d, dst_pos, length, THREAD);
248       return;
249     }
250   }
251 
252   if (!d->is_refArray()) {
253     ResourceMark rm(THREAD);
254     stringStream ss;
255     if (d->is_typeArray()) {
256       ss.print(
257           "arraycopy: type mismatch: can not copy object array[] into %s[]",
258           type2name_tab[ArrayKlass::cast(d->klass())->element_type()]);
259     } else {
260       ss.print("arraycopy: destination type %s is not an array",
261                d->klass()->external_name());
262     }
263     THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
264   }
265 
266   // Check is all offsets and lengths are non negative
267   if (src_pos < 0 || dst_pos < 0 || length < 0) {
268     // Pass specific exception reason.
269     ResourceMark rm(THREAD);
270     stringStream ss;
271     if (src_pos < 0) {
272       ss.print("arraycopy: source index %d out of bounds for object array[%d]",
273                src_pos, s->length());
274     } else if (dst_pos < 0) {
275       ss.print(
276           "arraycopy: destination index %d out of bounds for object array[%d]",
277           dst_pos, d->length());
278     } else {
279       ss.print("arraycopy: length %d is negative", length);
280     }
281     THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(),
282               ss.as_string());
283   }
284   // Check if the ranges are valid
285   if ((((unsigned int)length + (unsigned int)src_pos) >
286        (unsigned int)s->length()) ||
287       (((unsigned int)length + (unsigned int)dst_pos) >
288        (unsigned int)d->length())) {
289     // Pass specific exception reason.
290     ResourceMark rm(THREAD);
291     stringStream ss;
292     if (((unsigned int)length + (unsigned int)src_pos) >
293         (unsigned int)s->length()) {
294       ss.print(
295           "arraycopy: last source index %u out of bounds for object array[%d]",
296           (unsigned int)length + (unsigned int)src_pos, s->length());
297     } else {
298       ss.print("arraycopy: last destination index %u out of bounds for object "
299                "array[%d]",
300                (unsigned int)length + (unsigned int)dst_pos, d->length());
301     }
302     THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(),
303               ss.as_string());
304   }
305 
306   // Special case. Boundary cases must be checked first
307   // This allows the following call: copy_array(s, s.length(), d.length(), 0).
308   // This is correct, since the position is supposed to be an 'in between
309   // point', i.e., s.length(), points to the right of the last element.
310   if (length == 0) {
311     return;
312   }
313   if (UseCompressedOops) {
314     size_t src_offset =
315         (size_t)refArrayOopDesc::obj_at_offset<narrowOop>(src_pos);
316     size_t dst_offset =
317         (size_t)refArrayOopDesc::obj_at_offset<narrowOop>(dst_pos);
318     assert(arrayOopDesc::obj_offset_to_raw<narrowOop>(s, src_offset, nullptr) ==
319                refArrayOop(s)->obj_at_addr<narrowOop>(src_pos),
320            "sanity");
321     assert(arrayOopDesc::obj_offset_to_raw<narrowOop>(d, dst_offset, nullptr) ==
322                refArrayOop(d)->obj_at_addr<narrowOop>(dst_pos),
323            "sanity");
324     do_copy(s, src_offset, d, dst_offset, length, CHECK);
325   } else {
326     size_t src_offset = (size_t)refArrayOopDesc::obj_at_offset<oop>(src_pos);
327     size_t dst_offset = (size_t)refArrayOopDesc::obj_at_offset<oop>(dst_pos);
328     assert(arrayOopDesc::obj_offset_to_raw<oop>(s, src_offset, nullptr) ==
329                refArrayOop(s)->obj_at_addr<oop>(src_pos),
330            "sanity");
331     assert(arrayOopDesc::obj_offset_to_raw<oop>(d, dst_offset, nullptr) ==
332                refArrayOop(d)->obj_at_addr<oop>(dst_pos),
333            "sanity");
334     do_copy(s, src_offset, d, dst_offset, length, CHECK);
335   }
336 }
337 
338 void RefArrayKlass::initialize(TRAPS) {
339   bottom_klass()->initialize(THREAD); // dispatches to either InstanceKlass or TypeArrayKlass
340 }
341 
342 void RefArrayKlass::metaspace_pointers_do(MetaspaceClosure *it) {
343   ObjArrayKlass::metaspace_pointers_do(it);
344 }
345 
346 // Printing
347 
348 void RefArrayKlass::print_on(outputStream* st) const {
349 #ifndef PRODUCT
350   Klass::print_on(st);
351   st->print(" - element klass: ");
352   element_klass()->print_value_on(st);
353   st->cr();
354 #endif // PRODUCT
355 }
356 
357 void RefArrayKlass::print_value_on(outputStream* st) const {
358   assert(is_klass(), "must be klass");
359 
360   element_klass()->print_value_on(st);
361   st->print("[]");
362 }
363 
364 #ifndef PRODUCT
365 
366 void RefArrayKlass::oop_print_on(oop obj, outputStream* st) {
367   ArrayKlass::oop_print_on(obj, st);
368   assert(obj->is_refArray(), "must be refArray");
369   refArrayOop oa = refArrayOop(obj);
370   int print_len = MIN2(oa->length(), MaxElementPrintSize);
371   for (int index = 0; index < print_len; index++) {
372     st->print(" - %3d : ", index);
373     if (oa->obj_at(index) != nullptr) {
374       oa->obj_at(index)->print_value_on(st);
375       st->cr();
376     } else {
377       st->print_cr("null");
378     }
379   }
380   int remaining = oa->length() - print_len;
381   if (remaining > 0) {
382     st->print_cr(" - <%d more elements, increase MaxElementPrintSize to print>",
383                  remaining);
384   }
385 }
386 
387 #endif // PRODUCT
388 
389 void RefArrayKlass::oop_print_value_on(oop obj, outputStream* st) {
390   assert(obj->is_refArray(), "must be refArray");
391   st->print("a ");
392   element_klass()->print_value_on(st);
393   int len = refArrayOop(obj)->length();
394   st->print("[%d] ", len);
395   if (obj != nullptr) {
396     obj->print_address_on(st);
397   } else {
398     st->print_cr("null");
399   }
400 }
401 
402 // Verification
403 
404 void RefArrayKlass::verify_on(outputStream* st) {
405   ArrayKlass::verify_on(st);
406   guarantee(element_klass()->is_klass(), "should be klass");
407   guarantee(bottom_klass()->is_klass(), "should be klass");
408   Klass *bk = bottom_klass();
409   guarantee(bk->is_instance_klass() || bk->is_typeArray_klass() ||
410                 bk->is_flatArray_klass(),
411             "invalid bottom klass");
412 }
413 
414 void RefArrayKlass::oop_verify_on(oop obj, outputStream* st) {
415   ArrayKlass::oop_verify_on(obj, st);
416   guarantee(obj->is_refArray(), "must be refArray");
417   guarantee(obj->is_null_free_array() || (!is_null_free_array_klass()),
418             "null-free klass but not object");
419   refArrayOop oa = refArrayOop(obj);
420   for (int index = 0; index < oa->length(); index++) {
421     guarantee(oopDesc::is_oop_or_null(oa->obj_at(index)), "should be oop");
422   }
423 }