1 /*
  2  * Copyright (c) 2017, 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 "precompiled.hpp"
 26 #include "classfile/moduleEntry.hpp"
 27 #include "classfile/packageEntry.hpp"
 28 #include "classfile/symbolTable.hpp"
 29 #include "classfile/systemDictionary.hpp"
 30 #include "classfile/vmSymbols.hpp"
 31 #include "gc/shared/collectedHeap.inline.hpp"
 32 #include "memory/iterator.inline.hpp"
 33 #include "memory/metadataFactory.hpp"
 34 #include "memory/metaspaceClosure.hpp"
 35 #include "memory/oopFactory.hpp"
 36 #include "memory/resourceArea.hpp"
 37 #include "memory/universe.hpp"
 38 #include "oops/arrayKlass.inline.hpp"
 39 #include "oops/arrayOop.hpp"
 40 #include "oops/flatArrayOop.hpp"
 41 #include "oops/flatArrayOop.inline.hpp"
 42 #include "oops/inlineKlass.hpp"
 43 #include "oops/instanceKlass.hpp"
 44 #include "oops/klass.inline.hpp"
 45 #include "oops/objArrayKlass.hpp"
 46 #include "oops/objArrayOop.inline.hpp"
 47 #include "oops/oop.inline.hpp"
 48 #include "oops/verifyOopClosure.hpp"
 49 #include "runtime/handles.inline.hpp"
 50 #include "runtime/mutexLocker.hpp"
 51 #include "utilities/copy.hpp"
 52 #include "utilities/macros.hpp"
 53 
 54 #include "oops/flatArrayKlass.hpp"
 55 
 56 // Allocation...
 57 
 58 FlatArrayKlass::FlatArrayKlass(Klass* element_klass, Symbol* name, LayoutKind lk) : ArrayKlass(name, Kind) {
 59   assert(element_klass->is_inline_klass(), "Expected Inline");
 60   assert(lk == NON_ATOMIC_FLAT || lk == ATOMIC_FLAT || lk == NULLABLE_ATOMIC_FLAT, "Must be a flat layout");
 61 
 62   set_element_klass(InlineKlass::cast(element_klass));
 63   set_class_loader_data(element_klass->class_loader_data());
 64   set_layout_kind(lk);
 65 
 66   set_layout_helper(array_layout_helper(InlineKlass::cast(element_klass), lk));
 67   assert(is_array_klass(), "sanity");
 68   assert(is_flatArray_klass(), "sanity");
 69   assert(is_null_free_array_klass(), "sanity");
 70 
 71 #ifdef _LP64
 72   set_prototype_header(markWord::flat_array_prototype(lk));
 73   assert(prototype_header().is_flat_array(), "sanity");
 74 #else
 75   fatal("Not supported yet");
 76   set_prototype_header(markWord::inline_type_prototype());
 77 #endif
 78 
 79 #ifdef ASSERT
 80   switch(lk) {
 81     case NON_ATOMIC_FLAT:
 82       assert(layout_helper_is_null_free(layout_helper()), "Must be");
 83       assert(layout_helper_is_array(layout_helper()), "Must be");
 84       assert(layout_helper_is_flatArray(layout_helper()), "Must be");
 85       assert(layout_helper_element_type(layout_helper()) == T_FLAT_ELEMENT, "Must be");
 86       assert(prototype_header().is_null_free_array(), "Must be");
 87       assert(prototype_header().is_flat_array(), "Must be");
 88     break;
 89     default:
 90     break;
 91   }
 92 #endif // ASSERT
 93 
 94 #ifndef PRODUCT
 95   if (PrintFlatArrayLayout) {
 96     print();
 97   }
 98 #endif
 99 }
100 
101 FlatArrayKlass* FlatArrayKlass::allocate_klass(Klass* eklass, LayoutKind lk, TRAPS) {
102   guarantee((!Universe::is_bootstrapping() || vmClasses::Object_klass_loaded()), "Really ?!");
103   assert(UseFlatArray, "Flatten array required");
104   assert(MultiArray_lock->holds_lock(THREAD), "must hold lock after bootstrapping");
105 
106   InlineKlass* element_klass = InlineKlass::cast(eklass);
107   assert(element_klass->must_be_atomic() || (!InlineArrayAtomicAccess), "Atomic by-default");
108 
109   // Eagerly allocate the direct array supertype.
110   Klass* super_klass = nullptr;
111   Klass* element_super = element_klass->super();
112   if (element_super != nullptr) {
113     // The element type has a direct super.  E.g., String[] has direct super of Object[].
114     super_klass = element_klass->array_klass(CHECK_NULL);
115     // Also, see if the element has secondary supertypes.
116     // We need an array type for each.
117     const Array<Klass*>* element_supers = element_klass->secondary_supers();
118     for( int i = element_supers->length()-1; i >= 0; i-- ) {
119       Klass* elem_super = element_supers->at(i);
120       elem_super->array_klass(CHECK_NULL);
121     }
122    // Fall through because inheritance is acyclic and we hold the global recursive lock to allocate all the arrays.
123   }
124 
125   Symbol* name = ArrayKlass::create_element_klass_array_name(element_klass, CHECK_NULL);
126   ClassLoaderData* loader_data = element_klass->class_loader_data();
127   int size = ArrayKlass::static_size(FlatArrayKlass::header_size());
128   FlatArrayKlass* vak = new (loader_data, size, THREAD) FlatArrayKlass(element_klass, name, lk);
129 
130   ModuleEntry* module = vak->module();
131   assert(module != nullptr, "No module entry for array");
132   complete_create_array_klass(vak, super_klass, module, CHECK_NULL);
133 
134   loader_data->add_class(vak);
135 
136   return vak;
137 }
138 
139 void FlatArrayKlass::initialize(TRAPS) {
140   element_klass()->initialize(THREAD);
141 }
142 
143 void FlatArrayKlass::metaspace_pointers_do(MetaspaceClosure* it) {
144   ArrayKlass::metaspace_pointers_do(it);
145   it->push(&_element_klass);
146 }
147 
148 // Oops allocation...
149 flatArrayOop FlatArrayKlass::allocate(int length, LayoutKind lk, TRAPS) {
150   check_array_allocation_length(length, max_elements(), CHECK_NULL);
151   int size = flatArrayOopDesc::object_size(layout_helper(), length);
152   flatArrayOop array = (flatArrayOop) Universe::heap()->array_allocate(this, size, length, true, CHECK_NULL);
153   return array;
154 }
155 
156 oop FlatArrayKlass::multi_allocate(int rank, jint* last_size, TRAPS) {
157   // FlatArrays only have one dimension
158   ShouldNotReachHere();
159 }
160 
161 jint FlatArrayKlass::array_layout_helper(InlineKlass* vk, LayoutKind lk) {
162   BasicType etype = T_FLAT_ELEMENT;
163   int esize = log2i_exact(round_up_power_of_2(vk->layout_size_in_bytes(lk)));
164   int hsize = arrayOopDesc::base_offset_in_bytes(etype);
165 
166   int lh = Klass::array_layout_helper(_lh_array_tag_vt_value, true, hsize, etype, esize);
167 
168   assert(lh < (int)_lh_neutral_value, "must look like an array layout");
169   assert(layout_helper_is_array(lh), "correct kind");
170   assert(layout_helper_is_flatArray(lh), "correct kind");
171   assert(!layout_helper_is_typeArray(lh), "correct kind");
172   assert(!layout_helper_is_objArray(lh), "correct kind");
173   assert(layout_helper_is_null_free(lh), "correct kind");
174   assert(layout_helper_header_size(lh) == hsize, "correct decode");
175   assert(layout_helper_element_type(lh) == etype, "correct decode");
176   assert(layout_helper_log2_element_size(lh) == esize, "correct decode");
177   assert((1 << esize) < BytesPerLong || is_aligned(hsize, HeapWordsPerLong), "unaligned base");
178 
179   return lh;
180 }
181 
182 size_t FlatArrayKlass::oop_size(oop obj) const {
183   assert(obj->klass()->is_flatArray_klass(),"must be an flat array");
184   flatArrayOop array = flatArrayOop(obj);
185   return array->object_size();
186 }
187 
188 // For now return the maximum number of array elements that will not exceed:
189 // nof bytes = "max_jint * HeapWord" since the "oopDesc::oop_iterate_size"
190 // returns "int" HeapWords, need fix for JDK-4718400 and JDK-8233189
191 jint FlatArrayKlass::max_elements() const {
192   // Check the max number of heap words limit first (because of int32_t in oopDesc_oop_size() etc)
193   size_t max_size = max_jint;
194   max_size -= (arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT) >> LogHeapWordSize);
195   max_size = align_down(max_size, MinObjAlignment);
196   max_size <<= LogHeapWordSize;                                  // convert to max payload size in bytes
197   max_size >>= layout_helper_log2_element_size(_layout_helper);  // divide by element size (in bytes) = max elements
198   // Within int32_t heap words, still can't exceed Java array element limit
199   if (max_size > max_jint) {
200     max_size = max_jint;
201   }
202   assert((max_size >> LogHeapWordSize) <= max_jint, "Overflow");
203   return (jint) max_size;
204 }
205 
206 oop FlatArrayKlass::protection_domain() const {
207   return element_klass()->protection_domain();
208 }
209 
210 // Temp hack having this here: need to move towards Access API
211 static bool needs_backwards_copy(arrayOop s, int src_pos,
212                                  arrayOop d, int dst_pos, int length) {
213   return (s == d) && (dst_pos > src_pos) && (dst_pos - src_pos) < length;
214 }
215 
216 void FlatArrayKlass::copy_array(arrayOop s, int src_pos,
217                                 arrayOop d, int dst_pos, int length, TRAPS) {
218 
219   assert(s->is_objArray() || s->is_flatArray(), "must be obj or flat array");
220 
221   // Check destination
222   if ((!d->is_flatArray()) && (!d->is_objArray())) {
223     THROW(vmSymbols::java_lang_ArrayStoreException());
224   }
225 
226   // Check if all offsets and lengths are non negative
227   if (src_pos < 0 || dst_pos < 0 || length < 0) {
228     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
229   }
230   // Check if the ranges are valid
231   if  ( (((unsigned int) length + (unsigned int) src_pos) > (unsigned int) s->length())
232       || (((unsigned int) length + (unsigned int) dst_pos) > (unsigned int) d->length()) ) {
233     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
234   }
235   // Check zero copy
236   if (length == 0)
237     return;
238 
239   ArrayKlass* sk = ArrayKlass::cast(s->klass());
240   ArrayKlass* dk = ArrayKlass::cast(d->klass());
241   Klass* d_elem_klass = dk->element_klass();
242   Klass* s_elem_klass = sk->element_klass();
243   /**** CMH: compare and contrast impl, re-factor once we find edge cases... ****/
244 
245   if (sk->is_flatArray_klass()) {
246     assert(sk == this, "Unexpected call to copy_array");
247     FlatArrayKlass* fsk = FlatArrayKlass::cast(sk);
248     // Check subtype, all src homogeneous, so just once
249     if (!s_elem_klass->is_subtype_of(d_elem_klass)) {
250       THROW(vmSymbols::java_lang_ArrayStoreException());
251     }
252 
253     flatArrayOop sa = flatArrayOop(s);
254     InlineKlass* s_elem_vklass = element_klass();
255 
256     // flatArray-to-flatArray
257     if (dk->is_flatArray_klass()) {
258       // element types MUST be exact, subtype check would be dangerous
259       if (d_elem_klass != this->element_klass()) {
260         THROW(vmSymbols::java_lang_ArrayStoreException());
261       }
262 
263       FlatArrayKlass* fdk = FlatArrayKlass::cast(dk);
264       InlineKlass* vk = InlineKlass::cast(s_elem_klass);
265       flatArrayOop da = flatArrayOop(d);
266       int src_incr = fsk->element_byte_size();
267       int dst_incr = fdk->element_byte_size();
268 
269       if (fsk->layout_kind() == fdk->layout_kind()) {
270         assert(src_incr == dst_incr, "Must be");
271         if (needs_backwards_copy(sa, src_pos, da, dst_pos, length)) {
272           address dst = (address) da->value_at_addr(dst_pos + length - 1, fdk->layout_helper());
273           address src = (address) sa->value_at_addr(src_pos + length - 1, fsk->layout_helper());
274           for (int i = 0; i < length; i++) {
275             // because source and destination have the same layout, bypassing the InlineKlass copy methods
276             // and call AccessAPI directly
277             HeapAccess<>::value_copy(src, dst, vk, fsk->layout_kind());
278             dst -= dst_incr;
279             src -= src_incr;
280           }
281         } else {
282           // source and destination share same layout, direct copy from array to array is possible
283           address dst = (address) da->value_at_addr(dst_pos, fdk->layout_helper());
284           address src = (address) sa->value_at_addr(src_pos, fsk->layout_helper());
285           for (int i = 0; i < length; i++) {
286             // because source and destination have the same layout, bypassing the InlineKlass copy methods
287             // and call AccessAPI directly
288             HeapAccess<>::value_copy(src, dst, vk, fsk->layout_kind());
289             dst += dst_incr;
290             src += src_incr;
291           }
292         }
293       } else {
294         flatArrayHandle hd(THREAD, da);
295         flatArrayHandle hs(THREAD, sa);
296         // source and destination layouts mismatch, simpler solution is to copy through an intermediate buffer (heap instance)
297         bool need_null_check = fsk->layout_kind() == NULLABLE_ATOMIC_FLAT && fdk->layout_kind() != NULLABLE_ATOMIC_FLAT;
298         oop buffer = vk->allocate_instance(CHECK);
299         address dst = (address) hd->value_at_addr(dst_pos, fdk->layout_helper());
300         address src = (address) hs->value_at_addr(src_pos, fsk->layout_helper());
301         for (int i = 0; i < length; i++) {
302           if (need_null_check) {
303             if (vk->is_payload_marked_as_null(src)) {
304               THROW(vmSymbols::java_lang_NullPointerException());
305             }
306           }
307           vk->copy_payload_to_addr(src, vk->data_for_oop(buffer), fsk->layout_kind(), true);
308           if (vk->has_nullable_atomic_layout()) {
309             // Setting null marker to not zero for non-nullable source layouts
310             vk->mark_payload_as_non_null(vk->data_for_oop(buffer));
311           }
312           vk->copy_payload_to_addr(vk->data_for_oop(buffer), dst, fdk->layout_kind(), true);
313           dst += dst_incr;
314           src += src_incr;
315         }
316       }
317     } else { // flatArray-to-objArray
318       assert(dk->is_objArray_klass(), "Expected objArray here");
319       // Need to allocate each new src elem payload -> dst oop
320       objArrayHandle dh(THREAD, (objArrayOop)d);
321       flatArrayHandle sh(THREAD, sa);
322       InlineKlass* vk = InlineKlass::cast(s_elem_klass);
323       for (int i = 0; i < length; i++) {
324         oop o = sh->read_value_from_flat_array(src_pos + i, CHECK);
325         dh->obj_at_put(dst_pos + i, o);
326       }
327     }
328   } else {
329     assert(s->is_objArray(), "Expected objArray");
330     objArrayOop sa = objArrayOop(s);
331     assert(d->is_flatArray(), "Expected flatArray");  // objArray-to-flatArray
332     InlineKlass* d_elem_vklass = InlineKlass::cast(d_elem_klass);
333     flatArrayOop da = flatArrayOop(d);
334     FlatArrayKlass* fdk = FlatArrayKlass::cast(da->klass());
335     InlineKlass* vk = InlineKlass::cast(d_elem_klass);
336 
337     for (int i = 0; i < length; i++) {
338       da->write_value_to_flat_array(sa->obj_at(src_pos + i), dst_pos + i, CHECK);
339     }
340   }
341 }
342 
343 ModuleEntry* FlatArrayKlass::module() const {
344   assert(element_klass() != nullptr, "FlatArrayKlass returned unexpected nullptr bottom_klass");
345   // The array is defined in the module of its bottom class
346   return element_klass()->module();
347 }
348 
349 PackageEntry* FlatArrayKlass::package() const {
350   assert(element_klass() != nullptr, "FlatArrayKlass returned unexpected nullptr bottom_klass");
351   return element_klass()->package();
352 }
353 
354 bool FlatArrayKlass::can_be_primary_super_slow() const {
355     return true;
356 }
357 
358 GrowableArray<Klass*>* FlatArrayKlass::compute_secondary_supers(int num_extra_slots,
359                                                                 Array<InstanceKlass*>* transitive_interfaces) {
360   assert(transitive_interfaces == nullptr, "sanity");
361   // interfaces = { cloneable_klass, serializable_klass, elemSuper[], ... };
362   Array<Klass*>* elem_supers = element_klass()->secondary_supers();
363   int num_elem_supers = elem_supers == nullptr ? 0 : elem_supers->length();
364   int num_secondaries = num_extra_slots + 2 + num_elem_supers;
365   GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(num_elem_supers+2);
366 
367   secondaries->push(vmClasses::Cloneable_klass());
368   secondaries->push(vmClasses::Serializable_klass());
369   for (int i = 0; i < num_elem_supers; i++) {
370     Klass* elem_super = (Klass*) elem_supers->at(i);
371     Klass* array_super = elem_super->array_klass_or_null();
372     assert(array_super != nullptr, "must already have been created");
373     secondaries->push(array_super);
374   }
375   return secondaries;
376 }
377 
378 jint FlatArrayKlass::compute_modifier_flags() const {
379   // The modifier for an flatArray is the same as its element
380   // With the addition of ACC_IDENTITY
381   jint element_flags = element_klass()->compute_modifier_flags();
382 
383   int identity_flag = (Arguments::enable_preview()) ? JVM_ACC_IDENTITY : 0;
384 
385   return (element_flags & (JVM_ACC_PUBLIC | JVM_ACC_PRIVATE | JVM_ACC_PROTECTED))
386                         | (identity_flag | JVM_ACC_ABSTRACT | JVM_ACC_FINAL);
387 }
388 
389 void FlatArrayKlass::print_on(outputStream* st) const {
390 #ifndef PRODUCT
391   assert(!is_objArray_klass(), "Unimplemented");
392 
393   st->print("Flat Type Array: ");
394   Klass::print_on(st);
395 
396   st->print(" - element klass: ");
397   element_klass()->print_value_on(st);
398   st->cr();
399 
400   int elem_size = element_byte_size();
401   st->print(" - element size %i ", elem_size);
402   st->print("aligned layout size %i", 1 << layout_helper_log2_element_size(layout_helper()));
403   st->cr();
404 #endif //PRODUCT
405 }
406 
407 void FlatArrayKlass::print_value_on(outputStream* st) const {
408   assert(is_klass(), "must be klass");
409 
410   element_klass()->print_value_on(st);
411   st->print("[]");
412 }
413 
414 
415 #ifndef PRODUCT
416 void FlatArrayKlass::oop_print_on(oop obj, outputStream* st) {
417   ArrayKlass::oop_print_on(obj, st);
418   flatArrayOop va = flatArrayOop(obj);
419   InlineKlass* vk = element_klass();
420   int print_len = MIN2(va->length(), MaxElementPrintSize);
421   for(int index = 0; index < print_len; index++) {
422     int off = (address) va->value_at_addr(index, layout_helper()) - cast_from_oop<address>(obj);
423     st->print_cr(" - Index %3d offset %3d: ", index, off);
424     oop obj = cast_to_oop((address)va->value_at_addr(index, layout_helper()) - vk->first_field_offset());
425     FieldPrinter print_field(st, obj);
426     vk->do_nonstatic_fields(&print_field);
427     st->cr();
428   }
429   int remaining = va->length() - print_len;
430   if (remaining > 0) {
431     st->print_cr(" - <%d more elements, increase MaxElementPrintSize to print>", remaining);
432   }
433 }
434 #endif //PRODUCT
435 
436 void FlatArrayKlass::oop_print_value_on(oop obj, outputStream* st) {
437   assert(obj->is_flatArray(), "must be flatArray");
438   st->print("a ");
439   element_klass()->print_value_on(st);
440   int len = flatArrayOop(obj)->length();
441   st->print("[%d] ", len);
442   obj->print_address_on(st);
443   if (PrintMiscellaneous && (WizardMode || Verbose)) {
444     int lh = layout_helper();
445     st->print("{");
446     for (int i = 0; i < len; i++) {
447       if (i > 4) {
448         st->print("..."); break;
449       }
450       st->print(" " INTPTR_FORMAT, (intptr_t)(void*)flatArrayOop(obj)->value_at_addr(i , lh));
451     }
452     st->print(" }");
453   }
454 }
455 
456 // Verification
457 class VerifyElementClosure: public BasicOopIterateClosure {
458  public:
459   virtual void do_oop(oop* p)       { VerifyOopClosure::verify_oop.do_oop(p); }
460   virtual void do_oop(narrowOop* p) { VerifyOopClosure::verify_oop.do_oop(p); }
461 };
462 
463 void FlatArrayKlass::oop_verify_on(oop obj, outputStream* st) {
464   ArrayKlass::oop_verify_on(obj, st);
465   guarantee(obj->is_flatArray(), "must be flatArray");
466 
467   if (contains_oops()) {
468     flatArrayOop va = flatArrayOop(obj);
469     VerifyElementClosure ec;
470     va->oop_iterate(&ec);
471   }
472 }
473 
474 void FlatArrayKlass::verify_on(outputStream* st) {
475   ArrayKlass::verify_on(st);
476   guarantee(element_klass()->is_inline_klass(), "should be inline type klass");
477 }