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, ID) {
 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 
 95   InlineKlass* element_klass = InlineKlass::cast(eklass);
 96   assert(element_klass->is_naturally_atomic() || (!InlineArrayAtomicAccess), "Atomic by-default");
 97 
 98   /*
 99    *  MVT->LWorld, now need to allocate secondaries array types, just like objArrayKlass...
100    *  ...so now we are trying out covariant array types, just copy objArrayKlass
101    *  TODO refactor any remaining commonality
102    *
103    */
104   // Eagerly allocate the direct array supertype.
105   Klass* super_klass = NULL;
106   Klass* element_super = element_klass->super();
107   if (element_super != NULL) {
108     // The element type has a direct super.  E.g., String[] has direct super of Object[].
109     super_klass = element_klass->array_klass_or_null();
110     bool supers_exist = super_klass != 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       if (elem_super->array_klass_or_null() == NULL) {
117         supers_exist = false;
118         break;
119       }
120     }
121     if (!supers_exist) {
122       // Oops.  Not allocated yet.  Back out, allocate it, and retry.
123       Klass* ek = NULL;
124       {
125         MutexUnlocker mu(MultiArray_lock);
126         super_klass = element_klass->array_klass(CHECK_NULL);
127         for( int i = element_supers->length()-1; i >= 0; i-- ) {
128           Klass* elem_super = element_supers->at(i);
129           elem_super->array_klass(CHECK_NULL);
130         }
131         // Now retry from the beginning
132         ek = element_klass->null_free_inline_array_klass(CHECK_NULL);
133       }  // re-lock
134       return FlatArrayKlass::cast(ek);
135     }
136   }
137 
138   Symbol* name = ArrayKlass::create_element_klass_array_name(element_klass, true, CHECK_NULL);
139   ClassLoaderData* loader_data = element_klass->class_loader_data();
140   int size = ArrayKlass::static_size(FlatArrayKlass::header_size());
141   FlatArrayKlass* vak = new (loader_data, size, THREAD) FlatArrayKlass(element_klass, name);
142 
143   ModuleEntry* module = vak->module();
144   assert(module != NULL, "No module entry for array");
145   complete_create_array_klass(vak, super_klass, module, CHECK_NULL);
146 
147   loader_data->add_class(vak);
148 
149   return vak;
150 }
151 
152 void FlatArrayKlass::initialize(TRAPS) {
153   element_klass()->initialize(THREAD);
154 }
155 
156 void FlatArrayKlass::metaspace_pointers_do(MetaspaceClosure* it) {
157   ArrayKlass::metaspace_pointers_do(it);
158   it->push(&_element_klass);
159 }
160 
161 // Oops allocation...
162 flatArrayOop FlatArrayKlass::allocate(int length, TRAPS) {
163   check_array_allocation_length(length, max_elements(), CHECK_NULL);
164   int size = flatArrayOopDesc::object_size(layout_helper(), length);
165   return (flatArrayOop) Universe::heap()->array_allocate(this, size, length, true, THREAD);
166 }
167 
168 
169 oop FlatArrayKlass::multi_allocate(int rank, jint* last_size, TRAPS) {
170   // For flatArrays this is only called for the last dimension
171   assert(rank == 1, "just checking");
172   int length = *last_size;
173   return allocate(length, THREAD);
174 }
175 
176 jint FlatArrayKlass::array_layout_helper(InlineKlass* vk) {
177   BasicType etype = T_INLINE_TYPE;
178   int esize = log2i_exact(round_up_power_of_2(vk->get_exact_size_in_bytes()));
179   int hsize = arrayOopDesc::base_offset_in_bytes(etype);
180 
181   int lh = Klass::array_layout_helper(_lh_array_tag_vt_value, true, hsize, etype, esize);
182 
183   assert(lh < (int)_lh_neutral_value, "must look like an array layout");
184   assert(layout_helper_is_array(lh), "correct kind");
185   assert(layout_helper_is_flatArray(lh), "correct kind");
186   assert(!layout_helper_is_typeArray(lh), "correct kind");
187   assert(!layout_helper_is_objArray(lh), "correct kind");
188   assert(layout_helper_is_null_free(lh), "correct kind");
189   assert(layout_helper_header_size(lh) == hsize, "correct decode");
190   assert(layout_helper_element_type(lh) == etype, "correct decode");
191   assert(layout_helper_log2_element_size(lh) == esize, "correct decode");
192   assert((1 << esize) < BytesPerLong || is_aligned(hsize, HeapWordsPerLong), "unaligned base");
193 
194   return lh;
195 }
196 
197 int FlatArrayKlass::oop_size(oop obj) const {
198   assert(obj->klass()->is_flatArray_klass(),"must be an flat array");
199   flatArrayOop array = flatArrayOop(obj);
200   return array->object_size();
201 }
202 
203 // For now return the maximum number of array elements that will not exceed:
204 // nof bytes = "max_jint * HeapWord" since the "oopDesc::oop_iterate_size"
205 // returns "int" HeapWords, need fix for JDK-4718400 and JDK-8233189
206 jint FlatArrayKlass::max_elements() const {
207   // Check the max number of heap words limit first (because of int32_t in oopDesc_oop_size() etc)
208   size_t max_size = max_jint;
209   max_size -= arrayOopDesc::header_size(T_INLINE_TYPE);
210   max_size = align_down(max_size, MinObjAlignment);
211   max_size <<= LogHeapWordSize;                                  // convert to max payload size in bytes
212   max_size >>= layout_helper_log2_element_size(_layout_helper);  // divide by element size (in bytes) = max elements
213   // Within int32_t heap words, still can't exceed Java array element limit
214   if (max_size > max_jint) {
215     max_size = max_jint;
216   }
217   assert((max_size >> LogHeapWordSize) <= max_jint, "Overflow");
218   return (jint) max_size;
219 }
220 
221 oop FlatArrayKlass::protection_domain() const {
222   return element_klass()->protection_domain();
223 }
224 
225 // Temp hack having this here: need to move towards Access API
226 static bool needs_backwards_copy(arrayOop s, int src_pos,
227                                  arrayOop d, int dst_pos, int length) {
228   return (s == d) && (dst_pos > src_pos) && (dst_pos - src_pos) < length;
229 }
230 
231 void FlatArrayKlass::copy_array(arrayOop s, int src_pos,
232                                 arrayOop d, int dst_pos, int length, TRAPS) {
233 
234   assert(s->is_objArray() || s->is_flatArray(), "must be obj or flat array");
235 
236    // Check destination
237    if ((!d->is_flatArray()) && (!d->is_objArray())) {
238      THROW(vmSymbols::java_lang_ArrayStoreException());
239    }
240 
241    // Check if all offsets and lengths are non negative
242    if (src_pos < 0 || dst_pos < 0 || length < 0) {
243      THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
244    }
245    // Check if the ranges are valid
246    if  ( (((unsigned int) length + (unsigned int) src_pos) > (unsigned int) s->length())
247       || (((unsigned int) length + (unsigned int) dst_pos) > (unsigned int) d->length()) ) {
248      THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
249    }
250    // Check zero copy
251    if (length == 0)
252      return;
253 
254    ArrayKlass* sk = ArrayKlass::cast(s->klass());
255    ArrayKlass* dk = ArrayKlass::cast(d->klass());
256    Klass* d_elem_klass = dk->element_klass();
257    Klass* s_elem_klass = sk->element_klass();
258    /**** CMH: compare and contrast impl, re-factor once we find edge cases... ****/
259 
260    if (sk->is_flatArray_klass()) {
261      assert(sk == this, "Unexpected call to copy_array");
262      // Check subtype, all src homogeneous, so just once
263      if (!s_elem_klass->is_subtype_of(d_elem_klass)) {
264        THROW(vmSymbols::java_lang_ArrayStoreException());
265      }
266 
267      flatArrayOop sa = flatArrayOop(s);
268      InlineKlass* s_elem_vklass = element_klass();
269 
270      // flatArray-to-flatArray
271      if (dk->is_flatArray_klass()) {
272        // element types MUST be exact, subtype check would be dangerous
273        if (dk != this) {
274          THROW(vmSymbols::java_lang_ArrayStoreException());
275        }
276 
277        flatArrayOop da = flatArrayOop(d);
278        address dst = (address) da->value_at_addr(dst_pos, layout_helper());
279        address src = (address) sa->value_at_addr(src_pos, layout_helper());
280        if (contains_oops()) {
281          int elem_incr = 1 << log2_element_size();
282          address src_end = src + (length << log2_element_size());
283          if (needs_backwards_copy(s, src_pos, d, dst_pos, length)) {
284            swap(src, src_end);
285            dst = dst + (length << log2_element_size());
286            do {
287              src -= elem_incr;
288              dst -= elem_incr;
289              HeapAccess<>::value_copy(src, dst, s_elem_vklass);
290            } while (src > src_end);
291          } else {
292            address src_end = src + (length << log2_element_size());
293            while (src < src_end) {
294              HeapAccess<>::value_copy(src, dst, s_elem_vklass);
295              src += elem_incr;
296              dst += elem_incr;
297            }
298          }
299        } else {
300          // we are basically a type array...don't bother limiting element copy
301          // it would have to be a lot wasted space to be worth value_store() calls, need a setting here ?
302          Copy::conjoint_memory_atomic(src, dst, (size_t)length << log2_element_size());
303        }
304      }
305      else { // flatArray-to-objArray
306        assert(dk->is_objArray_klass(), "Expected objArray here");
307        // Need to allocate each new src elem payload -> dst oop
308        objArrayHandle dh(THREAD, (objArrayOop)d);
309        flatArrayHandle sh(THREAD, sa);
310        int dst_end = dst_pos + length;
311        while (dst_pos < dst_end) {
312          oop o = flatArrayOopDesc::value_alloc_copy_from_index(sh, src_pos, CHECK);
313          dh->obj_at_put(dst_pos, o);
314          dst_pos++;
315          src_pos++;
316        }
317      }
318    } else {
319      assert(s->is_objArray(), "Expected objArray");
320      objArrayOop sa = objArrayOop(s);
321      assert(d->is_flatArray(), "Excepted flatArray");  // objArray-to-flatArray
322      InlineKlass* d_elem_vklass = InlineKlass::cast(d_elem_klass);
323      flatArrayOop da = flatArrayOop(d);
324 
325      int src_end = src_pos + length;
326      int delem_incr = 1 << dk->log2_element_size();
327      address dst = (address) da->value_at_addr(dst_pos, layout_helper());
328      while (src_pos < src_end) {
329        oop se = sa->obj_at(src_pos);
330        if (se == NULL) {
331          THROW(vmSymbols::java_lang_NullPointerException());
332        }
333        // Check exact type per element
334        if (se->klass() != d_elem_klass) {
335          THROW(vmSymbols::java_lang_ArrayStoreException());
336        }
337        d_elem_vklass->inline_copy_oop_to_payload(se, dst);
338        dst += delem_incr;
339        src_pos++;
340      }
341    }
342 }
343 
344 
345 Klass* FlatArrayKlass::array_klass(int n, TRAPS) {
346   assert(dimension() <= n, "check order of chain");
347   int dim = dimension();
348   if (dim == n) return this;
349 
350   // lock-free read needs acquire semantics
351   if (higher_dimension_acquire() == NULL) {
352 
353     ResourceMark rm(THREAD);
354     {
355       // Ensure atomic creation of higher dimensions
356       MutexLocker mu(THREAD, MultiArray_lock);
357 
358       // Check if another thread beat us
359       if (higher_dimension() == NULL) {
360 
361         // Create multi-dim klass object and link them together
362         Klass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), dim + 1, this, false, true, CHECK_NULL);
363         ObjArrayKlass* ak = ObjArrayKlass::cast(k);
364         ak->set_lower_dimension(this);
365         // use 'release' to pair with lock-free load
366         release_set_higher_dimension(ak);
367         assert(ak->is_objArray_klass(), "incorrect initialization of ObjArrayKlass");
368       }
369     }
370   }
371 
372   ObjArrayKlass *ak = ObjArrayKlass::cast(higher_dimension());
373   JavaThread::cast(THREAD)->check_possible_safepoint();
374   return ak->array_klass(n, THREAD);
375 }
376 
377 Klass* FlatArrayKlass::array_klass_or_null(int n) {
378 
379   assert(dimension() <= n, "check order of chain");
380   int dim = dimension();
381   if (dim == n) return this;
382 
383   // lock-free read needs acquire semantics
384   if (higher_dimension_acquire() == NULL) {
385     return NULL;
386   }
387 
388   ObjArrayKlass *ak = ObjArrayKlass::cast(higher_dimension());
389   return ak->array_klass_or_null(n);
390 }
391 
392 Klass* FlatArrayKlass::array_klass(TRAPS) {
393   return array_klass(dimension() +  1, THREAD);
394 }
395 
396 Klass* FlatArrayKlass::array_klass_or_null() {
397   return array_klass_or_null(dimension() +  1);
398 }
399 
400 
401 ModuleEntry* FlatArrayKlass::module() const {
402   assert(element_klass() != NULL, "FlatArrayKlass returned unexpected NULL bottom_klass");
403   // The array is defined in the module of its bottom class
404   return element_klass()->module();
405 }
406 
407 PackageEntry* FlatArrayKlass::package() const {
408   assert(element_klass() != NULL, "FlatArrayKlass returned unexpected NULL bottom_klass");
409   return element_klass()->package();
410 }
411 
412 bool FlatArrayKlass::can_be_primary_super_slow() const {
413     return true;
414 }
415 
416 GrowableArray<Klass*>* FlatArrayKlass::compute_secondary_supers(int num_extra_slots,
417                                                                 Array<InstanceKlass*>* transitive_interfaces) {
418   assert(transitive_interfaces == NULL, "sanity");
419   // interfaces = { cloneable_klass, serializable_klass, elemSuper[], ... };
420   Array<Klass*>* elem_supers = element_klass()->secondary_supers();
421   assert(elem_supers->length() > 0, "Must at least include the PrimitiveObject interface");
422   int num_elem_supers = elem_supers == NULL ? 0 : elem_supers->length();
423   int num_secondaries = num_extra_slots + 2 + num_elem_supers;
424   GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(num_elem_supers+4);
425 
426   secondaries->push(vmClasses::Cloneable_klass());
427   secondaries->push(vmClasses::Serializable_klass());
428   secondaries->push(vmClasses::IdentityObject_klass());
429   for (int i = 0; i < num_elem_supers; i++) {
430     Klass* elem_super = (Klass*) elem_supers->at(i);
431     Klass* array_super = elem_super->array_klass_or_null();
432     assert(array_super != NULL, "must already have been created");
433     secondaries->push(array_super);
434   }
435   return secondaries;
436 }
437 
438 jint FlatArrayKlass::compute_modifier_flags() const {
439   // The modifier for an flatArray is the same as its element
440   jint element_flags = element_klass()->compute_modifier_flags();
441 
442   return (element_flags & (JVM_ACC_PUBLIC | JVM_ACC_PRIVATE | JVM_ACC_PROTECTED))
443                         | (JVM_ACC_ABSTRACT | JVM_ACC_FINAL);
444 }
445 
446 void FlatArrayKlass::print_on(outputStream* st) const {
447 #ifndef PRODUCT
448   assert(!is_objArray_klass(), "Unimplemented");
449 
450   st->print("Flat Type Array: ");
451   Klass::print_on(st);
452 
453   st->print(" - element klass: ");
454   element_klass()->print_value_on(st);
455   st->cr();
456 
457   int elem_size = element_byte_size();
458   st->print(" - element size %i ", elem_size);
459   st->print("aligned layout size %i", 1 << layout_helper_log2_element_size(layout_helper()));
460   st->cr();
461 #endif //PRODUCT
462 }
463 
464 void FlatArrayKlass::print_value_on(outputStream* st) const {
465   assert(is_klass(), "must be klass");
466 
467   element_klass()->print_value_on(st);
468   st->print("[]");
469 }
470 
471 
472 #ifndef PRODUCT
473 void FlatArrayKlass::oop_print_on(oop obj, outputStream* st) {
474   ArrayKlass::oop_print_on(obj, st);
475   flatArrayOop va = flatArrayOop(obj);
476   InlineKlass* vk = element_klass();
477   int print_len = MIN2((intx) va->length(), MaxElementPrintSize);
478   for(int index = 0; index < print_len; index++) {
479     int off = (address) va->value_at_addr(index, layout_helper()) - cast_from_oop<address>(obj);
480     st->print_cr(" - Index %3d offset %3d: ", index, off);
481     oop obj = cast_to_oop((address)va->value_at_addr(index, layout_helper()) - vk->first_field_offset());
482     FieldPrinter print_field(st, obj);
483     vk->do_nonstatic_fields(&print_field);
484     st->cr();
485   }
486   int remaining = va->length() - print_len;
487   if (remaining > 0) {
488     st->print_cr(" - <%d more elements, increase MaxElementPrintSize to print>", remaining);
489   }
490 }
491 #endif //PRODUCT
492 
493 void FlatArrayKlass::oop_print_value_on(oop obj, outputStream* st) {
494   assert(obj->is_flatArray(), "must be flatArray");
495   st->print("a ");
496   element_klass()->print_value_on(st);
497   int len = flatArrayOop(obj)->length();
498   st->print("[%d] ", len);
499   obj->print_address_on(st);
500   if (PrintMiscellaneous && (WizardMode || Verbose)) {
501     int lh = layout_helper();
502     st->print("{");
503     for (int i = 0; i < len; i++) {
504       if (i > 4) {
505         st->print("..."); break;
506       }
507       st->print(" " INTPTR_FORMAT, (intptr_t)(void*)flatArrayOop(obj)->value_at_addr(i , lh));
508     }
509     st->print(" }");
510   }
511 }
512 
513 // Verification
514 class VerifyElementClosure: public BasicOopIterateClosure {
515  public:
516   virtual void do_oop(oop* p)       { VerifyOopClosure::verify_oop.do_oop(p); }
517   virtual void do_oop(narrowOop* p) { VerifyOopClosure::verify_oop.do_oop(p); }
518 };
519 
520 void FlatArrayKlass::oop_verify_on(oop obj, outputStream* st) {
521   ArrayKlass::oop_verify_on(obj, st);
522   guarantee(obj->is_flatArray(), "must be flatArray");
523 
524   if (contains_oops()) {
525     flatArrayOop va = flatArrayOop(obj);
526     VerifyElementClosure ec;
527     va->oop_iterate(&ec);
528   }
529 }
530 
531 void FlatArrayKlass::verify_on(outputStream* st) {
532   ArrayKlass::verify_on(st);
533   guarantee(element_klass()->is_inline_klass(), "should be inline type klass");
534 }