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