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 "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/resourceArea.hpp"
 35 #include "memory/universe.hpp"
 36 #include "oops/arrayKlass.hpp"
 37 #include "oops/instanceKlass.hpp"
 38 #include "oops/klass.inline.hpp"
 39 #include "oops/objArrayKlass.inline.hpp"
 40 #include "oops/objArrayOop.inline.hpp"
 41 #include "oops/oop.inline.hpp"
 42 #include "oops/symbol.hpp"
 43 #include "runtime/handles.inline.hpp"
 44 #include "runtime/mutexLocker.hpp"
 45 #include "utilities/macros.hpp"
 46 
 47 ObjArrayKlass* ObjArrayKlass::allocate(ClassLoaderData* loader_data, int n, Klass* k, Symbol* name, TRAPS) {
 48   assert(ObjArrayKlass::header_size() <= InstanceKlass::header_size(),
 49       "array klasses must be same size as InstanceKlass");
 50 
 51   int size = ArrayKlass::static_size(ObjArrayKlass::header_size());
 52 
 53   return new (loader_data, size, THREAD) ObjArrayKlass(n, k, name);
 54 }
 55 
 56 ObjArrayKlass* ObjArrayKlass::allocate_objArray_klass(ClassLoaderData* loader_data,
 57                                                       int n, Klass* element_klass, TRAPS) {
 58 
 59   // Eagerly allocate the direct array supertype.
 60   Klass* super_klass = nullptr;
 61   if (!Universe::is_bootstrapping() || vmClasses::Object_klass_loaded()) {
 62     assert(MultiArray_lock->holds_lock(THREAD), "must hold lock after bootstrapping");
 63     Klass* element_super = element_klass->super();
 64     if (element_super != nullptr) {
 65       // The element type has a direct super.  E.g., String[] has direct super of Object[].
 66       // Also, see if the element has secondary supertypes.
 67       // We need an array type for each before creating this array type.
 68       super_klass = element_super->array_klass(CHECK_NULL);
 69       const Array<Klass*>* element_supers = element_klass->secondary_supers();
 70       for (int i = element_supers->length() - 1; i >= 0; i--) {
 71         Klass* elem_super = element_supers->at(i);
 72         elem_super->array_klass(CHECK_NULL);
 73       }
 74       // Fall through because inheritance is acyclic and we hold the global recursive lock to allocate all the arrays.
 75     } else {
 76       // The element type is already Object.  Object[] has direct super of Object.
 77       super_klass = vmClasses::Object_klass();
 78     }
 79   }
 80 
 81   // Create type name for klass.
 82   Symbol* name = nullptr;
 83   {
 84     ResourceMark rm(THREAD);
 85     char *name_str = element_klass->name()->as_C_string();
 86     int len = element_klass->name()->utf8_length();
 87     char *new_str = NEW_RESOURCE_ARRAY(char, len + 4);
 88     int idx = 0;
 89     new_str[idx++] = JVM_SIGNATURE_ARRAY;
 90     if (element_klass->is_instance_klass()) { // it could be an array or simple type
 91       new_str[idx++] = JVM_SIGNATURE_CLASS;
 92     }
 93     memcpy(&new_str[idx], name_str, len * sizeof(char));
 94     idx += len;
 95     if (element_klass->is_instance_klass()) {
 96       new_str[idx++] = JVM_SIGNATURE_ENDCLASS;
 97     }
 98     new_str[idx++] = '\0';
 99     name = SymbolTable::new_symbol(new_str);
100   }
101 
102   // Initialize instance variables
103   ObjArrayKlass* oak = ObjArrayKlass::allocate(loader_data, n, element_klass, name, CHECK_NULL);
104 
105   ModuleEntry* module = oak->module();
106   assert(module != nullptr, "No module entry for array");
107 
108   // Call complete_create_array_klass after all instance variables has been initialized.
109   ArrayKlass::complete_create_array_klass(oak, super_klass, module, CHECK_NULL);
110 
111   // Add all classes to our internal class loader list here,
112   // including classes in the bootstrap (null) class loader.
113   // Do this step after creating the mirror so that if the
114   // mirror creation fails, loaded_classes_do() doesn't find
115   // an array class without a mirror.
116   loader_data->add_class(oak);
117 
118   return oak;
119 }
120 
121 ObjArrayKlass::ObjArrayKlass(int n, Klass* element_klass, Symbol* name) : ArrayKlass(name, Kind) {
122   set_dimension(n);
123   set_element_klass(element_klass);
124 
125   Klass* bk;
126   if (element_klass->is_objArray_klass()) {
127     bk = ObjArrayKlass::cast(element_klass)->bottom_klass();
128   } else {
129     bk = element_klass;
130   }
131   assert(bk != nullptr && (bk->is_instance_klass() || bk->is_typeArray_klass()), "invalid bottom klass");
132   set_bottom_klass(bk);
133   set_class_loader_data(bk->class_loader_data());
134 
135   if (element_klass->is_array_klass()) {
136     set_lower_dimension(ArrayKlass::cast(element_klass));
137   }
138 
139   set_layout_helper(array_layout_helper(T_OBJECT));
140   assert(is_array_klass(), "sanity");
141   assert(is_objArray_klass(), "sanity");
142 
143   // Compute modifier flags after bottom_klass and element_klass are initialized.
144   set_modifier_flags(compute_modifier_flags());
145 }
146 
147 size_t ObjArrayKlass::oop_size(oop obj) const {
148   // In this assert, we cannot safely access the Klass* with compact headers,
149   // because size_given_klass() calls oop_size() on objects that might be
150   // concurrently forwarded, which would overwrite the Klass*.
151   assert(UseCompactObjectHeaders || obj->is_objArray(), "must be object array");
152   return objArrayOop(obj)->object_size();
153 }
154 
155 objArrayOop ObjArrayKlass::allocate(int length, TRAPS) {
156   check_array_allocation_length(length, arrayOopDesc::max_array_length(T_OBJECT), CHECK_NULL);
157   size_t size = objArrayOopDesc::object_size(length);
158   return (objArrayOop)Universe::heap()->array_allocate(this, size, length,
159                                                        /* do_zero */ true, THREAD);
160 }
161 
162 oop ObjArrayKlass::multi_allocate(int rank, jint* sizes, TRAPS) {
163   int length = *sizes;
164   ArrayKlass* ld_klass = lower_dimension();
165   // If length < 0 allocate will throw an exception.
166   objArrayOop array = allocate(length, CHECK_NULL);
167   objArrayHandle h_array (THREAD, array);
168   if (rank > 1) {
169     if (length != 0) {
170       for (int index = 0; index < length; index++) {
171         oop sub_array = ld_klass->multi_allocate(rank - 1, &sizes[1], CHECK_NULL);
172         h_array->obj_at_put(index, sub_array);
173       }
174     } else {
175       // Since this array dimension has zero length, nothing will be
176       // allocated, however the lower dimension values must be checked
177       // for illegal values.
178       for (int i = 0; i < rank - 1; ++i) {
179         sizes += 1;
180         if (*sizes < 0) {
181           THROW_MSG_NULL(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", *sizes));
182         }
183       }
184     }
185   }
186   return h_array();
187 }
188 
189 // Either oop or narrowOop depending on UseCompressedOops.
190 void ObjArrayKlass::do_copy(arrayOop s, size_t src_offset,
191                             arrayOop d, size_t dst_offset, int length, TRAPS) {
192   if (s == d) {
193     // since source and destination are equal we do not need conversion checks.
194     assert(length > 0, "sanity check");
195     ArrayAccess<>::oop_arraycopy(s, src_offset, d, dst_offset, length);
196   } else {
197     // We have to make sure all elements conform to the destination array
198     Klass* bound = ObjArrayKlass::cast(d->klass())->element_klass();
199     Klass* stype = ObjArrayKlass::cast(s->klass())->element_klass();
200     if (stype == bound || stype->is_subtype_of(bound)) {
201       // elements are guaranteed to be subtypes, so no check necessary
202       ArrayAccess<ARRAYCOPY_DISJOINT>::oop_arraycopy(s, src_offset, d, dst_offset, length);
203     } else {
204       // slow case: need individual subtype checks
205       // note: don't use obj_at_put below because it includes a redundant store check
206       if (!ArrayAccess<ARRAYCOPY_DISJOINT | ARRAYCOPY_CHECKCAST>::oop_arraycopy(s, src_offset, d, dst_offset, length)) {
207         ResourceMark rm(THREAD);
208         stringStream ss;
209         if (!bound->is_subtype_of(stype)) {
210           ss.print("arraycopy: type mismatch: can not copy %s[] into %s[]",
211                    stype->external_name(), bound->external_name());
212         } else {
213           // oop_arraycopy should return the index in the source array that
214           // contains the problematic oop.
215           ss.print("arraycopy: element type mismatch: can not cast one of the elements"
216                    " of %s[] to the type of the destination array, %s",
217                    stype->external_name(), bound->external_name());
218         }
219         THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
220       }
221     }
222   }
223 }
224 
225 void ObjArrayKlass::copy_array(arrayOop s, int src_pos, arrayOop d,
226                                int dst_pos, int length, TRAPS) {
227   assert(s->is_objArray(), "must be obj array");
228 
229   if (!d->is_objArray()) {
230     ResourceMark rm(THREAD);
231     stringStream ss;
232     if (d->is_typeArray()) {
233       ss.print("arraycopy: type mismatch: can not copy object array[] into %s[]",
234                type2name_tab[ArrayKlass::cast(d->klass())->element_type()]);
235     } else {
236       ss.print("arraycopy: destination type %s is not an array", d->klass()->external_name());
237     }
238     THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
239   }
240 
241   // Check is all offsets and lengths are non negative
242   if (src_pos < 0 || dst_pos < 0 || length < 0) {
243     // Pass specific exception reason.
244     ResourceMark rm(THREAD);
245     stringStream ss;
246     if (src_pos < 0) {
247       ss.print("arraycopy: source index %d out of bounds for object array[%d]",
248                src_pos, s->length());
249     } else if (dst_pos < 0) {
250       ss.print("arraycopy: destination index %d out of bounds for object array[%d]",
251                dst_pos, d->length());
252     } else {
253       ss.print("arraycopy: length %d is negative", length);
254     }
255     THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string());
256   }
257   // Check if the ranges are valid
258   if ((((unsigned int) length + (unsigned int) src_pos) > (unsigned int) s->length()) ||
259       (((unsigned int) length + (unsigned int) dst_pos) > (unsigned int) d->length())) {
260     // Pass specific exception reason.
261     ResourceMark rm(THREAD);
262     stringStream ss;
263     if (((unsigned int) length + (unsigned int) src_pos) > (unsigned int) s->length()) {
264       ss.print("arraycopy: last source index %u out of bounds for object array[%d]",
265                (unsigned int) length + (unsigned int) src_pos, s->length());
266     } else {
267       ss.print("arraycopy: last destination index %u out of bounds for object array[%d]",
268                (unsigned int) length + (unsigned int) dst_pos, d->length());
269     }
270     THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string());
271   }
272 
273   // Special case. Boundary cases must be checked first
274   // This allows the following call: copy_array(s, s.length(), d.length(), 0).
275   // This is correct, since the position is supposed to be an 'in between point', i.e., s.length(),
276   // points to the right of the last element.
277   if (length==0) {
278     return;
279   }
280   if (UseCompressedOops) {
281     size_t src_offset = (size_t) objArrayOopDesc::obj_at_offset<narrowOop>(src_pos);
282     size_t dst_offset = (size_t) objArrayOopDesc::obj_at_offset<narrowOop>(dst_pos);
283     assert(arrayOopDesc::obj_offset_to_raw<narrowOop>(s, src_offset, nullptr) ==
284            objArrayOop(s)->obj_at_addr<narrowOop>(src_pos), "sanity");
285     assert(arrayOopDesc::obj_offset_to_raw<narrowOop>(d, dst_offset, nullptr) ==
286            objArrayOop(d)->obj_at_addr<narrowOop>(dst_pos), "sanity");
287     do_copy(s, src_offset, d, dst_offset, length, CHECK);
288   } else {
289     size_t src_offset = (size_t) objArrayOopDesc::obj_at_offset<oop>(src_pos);
290     size_t dst_offset = (size_t) objArrayOopDesc::obj_at_offset<oop>(dst_pos);
291     assert(arrayOopDesc::obj_offset_to_raw<oop>(s, src_offset, nullptr) ==
292            objArrayOop(s)->obj_at_addr<oop>(src_pos), "sanity");
293     assert(arrayOopDesc::obj_offset_to_raw<oop>(d, dst_offset, nullptr) ==
294            objArrayOop(d)->obj_at_addr<oop>(dst_pos), "sanity");
295     do_copy(s, src_offset, d, dst_offset, length, CHECK);
296   }
297 }
298 
299 bool ObjArrayKlass::can_be_primary_super_slow() const {
300   if (!bottom_klass()->can_be_primary_super())
301     // array of interfaces
302     return false;
303   else
304     return Klass::can_be_primary_super_slow();
305 }
306 
307 GrowableArray<Klass*>* ObjArrayKlass::compute_secondary_supers(int num_extra_slots,
308                                                                Array<InstanceKlass*>* transitive_interfaces) {
309   assert(transitive_interfaces == nullptr, "sanity");
310   // interfaces = { cloneable_klass, serializable_klass, elemSuper[], ... };
311   const Array<Klass*>* elem_supers = element_klass()->secondary_supers();
312   int num_elem_supers = elem_supers == nullptr ? 0 : elem_supers->length();
313   int num_secondaries = num_extra_slots + 2 + num_elem_supers;
314   if (num_secondaries == 2) {
315     // Must share this for correct bootstrapping!
316     set_secondary_supers(Universe::the_array_interfaces_array(),
317                          Universe::the_array_interfaces_bitmap());
318     return nullptr;
319   } else {
320     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(num_elem_supers+2);
321     secondaries->push(vmClasses::Cloneable_klass());
322     secondaries->push(vmClasses::Serializable_klass());
323     for (int i = 0; i < num_elem_supers; i++) {
324       Klass* elem_super = elem_supers->at(i);
325       Klass* array_super = elem_super->array_klass_or_null();
326       assert(array_super != nullptr, "must already have been created");
327       secondaries->push(array_super);
328     }
329     return secondaries;
330   }
331 }
332 
333 void ObjArrayKlass::initialize(TRAPS) {
334   bottom_klass()->initialize(THREAD);  // dispatches to either InstanceKlass or TypeArrayKlass
335 }
336 
337 void ObjArrayKlass::metaspace_pointers_do(MetaspaceClosure* it) {
338   ArrayKlass::metaspace_pointers_do(it);
339   it->push(&_element_klass);
340   it->push(&_bottom_klass);
341 }
342 
343 u2 ObjArrayKlass::compute_modifier_flags() const {
344   // The modifier for an objectArray is the same as its element
345   assert (element_klass() != nullptr, "should be initialized");
346 
347   // Return the flags of the bottom element type.
348   u2 element_flags = bottom_klass()->compute_modifier_flags();
349 
350   return (element_flags & (JVM_ACC_PUBLIC | JVM_ACC_PRIVATE | JVM_ACC_PROTECTED))
351                         | (JVM_ACC_ABSTRACT | JVM_ACC_FINAL);
352 }
353 
354 ModuleEntry* ObjArrayKlass::module() const {
355   assert(bottom_klass() != nullptr, "ObjArrayKlass returned unexpected null bottom_klass");
356   // The array is defined in the module of its bottom class
357   return bottom_klass()->module();
358 }
359 
360 PackageEntry* ObjArrayKlass::package() const {
361   assert(bottom_klass() != nullptr, "ObjArrayKlass returned unexpected null bottom_klass");
362   return bottom_klass()->package();
363 }
364 
365 // Printing
366 
367 void ObjArrayKlass::print_on(outputStream* st) const {
368 #ifndef PRODUCT
369   Klass::print_on(st);
370   st->print(" - instance klass: ");
371   element_klass()->print_value_on(st);
372   st->cr();
373 #endif //PRODUCT
374 }
375 
376 void ObjArrayKlass::print_value_on(outputStream* st) const {
377   assert(is_klass(), "must be klass");
378 
379   element_klass()->print_value_on(st);
380   st->print("[]");
381 }
382 
383 #ifndef PRODUCT
384 
385 void ObjArrayKlass::oop_print_on(oop obj, outputStream* st) {
386   ArrayKlass::oop_print_on(obj, st);
387   assert(obj->is_objArray(), "must be objArray");
388   objArrayOop oa = objArrayOop(obj);
389   int print_len = MIN2(oa->length(), MaxElementPrintSize);
390   for(int index = 0; index < print_len; index++) {
391     st->print(" - %3d : ", index);
392     if (oa->obj_at(index) != nullptr) {
393       oa->obj_at(index)->print_value_on(st);
394       st->cr();
395     } else {
396       st->print_cr("null");
397     }
398   }
399   int remaining = oa->length() - print_len;
400   if (remaining > 0) {
401     st->print_cr(" - <%d more elements, increase MaxElementPrintSize to print>", remaining);
402   }
403 }
404 
405 #endif //PRODUCT
406 
407 void ObjArrayKlass::oop_print_value_on(oop obj, outputStream* st) {
408   assert(obj->is_objArray(), "must be objArray");
409   st->print("a ");
410   element_klass()->print_value_on(st);
411   int len = objArrayOop(obj)->length();
412   st->print("[%d] ", len);
413   if (obj != nullptr) {
414     obj->print_address_on(st);
415   } else {
416     st->print_cr("null");
417   }
418 }
419 
420 const char* ObjArrayKlass::internal_name() const {
421   return external_name();
422 }
423 
424 
425 // Verification
426 
427 void ObjArrayKlass::verify_on(outputStream* st) {
428   ArrayKlass::verify_on(st);
429   guarantee(element_klass()->is_klass(), "should be klass");
430   guarantee(bottom_klass()->is_klass(), "should be klass");
431   Klass* bk = bottom_klass();
432   guarantee(bk->is_instance_klass() || bk->is_typeArray_klass(),  "invalid bottom klass");
433 }
434 
435 void ObjArrayKlass::oop_verify_on(oop obj, outputStream* st) {
436   ArrayKlass::oop_verify_on(obj, st);
437   guarantee(obj->is_objArray(), "must be objArray");
438   objArrayOop oa = objArrayOop(obj);
439   for(int index = 0; index < oa->length(); index++) {
440     guarantee(oopDesc::is_oop_or_null(oa->obj_at(index)), "should be oop");
441   }
442 }