1 /*
   2  * Copyright (c) 1997, 2017, 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 "gc/shared/specialized_oop_closures.hpp"
  33 #include "memory/iterator.inline.hpp"
  34 #include "memory/metadataFactory.hpp"
  35 #include "memory/metaspaceClosure.hpp"
  36 #include "memory/oopFactory.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "memory/universe.inline.hpp"
  39 #include "oops/arrayKlass.inline.hpp"
  40 #include "oops/instanceKlass.hpp"
  41 #include "oops/klass.inline.hpp"
  42 #include "oops/objArrayKlass.inline.hpp"
  43 #include "oops/objArrayOop.inline.hpp"
  44 #include "oops/oop.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 ObjArrayKlass* ObjArrayKlass::allocate(ClassLoaderData* loader_data, int n, Klass* k, Symbol* name, TRAPS) {
  51   assert(ObjArrayKlass::header_size() <= InstanceKlass::header_size(),
  52       "array klasses must be same size as InstanceKlass");
  53 
  54   int size = ArrayKlass::static_size(ObjArrayKlass::header_size());
  55 
  56   return new (loader_data, size, THREAD) ObjArrayKlass(n, k, name);
  57 }
  58 
  59 Klass* ObjArrayKlass::allocate_objArray_klass(ClassLoaderData* loader_data,
  60                                                 int n, Klass* element_klass, TRAPS) {
  61 
  62   // Eagerly allocate the direct array supertype.
  63   Klass* super_klass = NULL;
  64   if (!Universe::is_bootstrapping() || SystemDictionary::Object_klass_loaded()) {
  65     Klass* element_super = element_klass->super();
  66     if (element_super != NULL) {
  67       // The element type has a direct super.  E.g., String[] has direct super of Object[].
  68       super_klass = element_super->array_klass_or_null();
  69       bool supers_exist = super_klass != NULL;
  70       // Also, see if the element has secondary supertypes.
  71       // We need an array type for each.
  72       Array<Klass*>* element_supers = element_klass->secondary_supers();
  73       for( int i = element_supers->length()-1; i >= 0; i-- ) {
  74         Klass* elem_super = element_supers->at(i);
  75         if (elem_super->array_klass_or_null() == NULL) {
  76           supers_exist = false;
  77           break;
  78         }
  79       }
  80       if (!supers_exist) {
  81         // Oops.  Not allocated yet.  Back out, allocate it, and retry.
  82         Klass* ek = NULL;
  83         {
  84           MutexUnlocker mu(MultiArray_lock);
  85           MutexUnlocker mc(Compile_lock);   // for vtables
  86           super_klass = element_super->array_klass(CHECK_0);
  87           for( int i = element_supers->length()-1; i >= 0; i-- ) {
  88             Klass* elem_super = element_supers->at(i);
  89             elem_super->array_klass(CHECK_0);
  90           }
  91           // Now retry from the beginning
  92           ek = element_klass->array_klass(n, CHECK_0);
  93         }  // re-lock
  94         return ek;
  95       }
  96     } else {
  97       // The element type is already Object.  Object[] has direct super of Object.
  98       super_klass = SystemDictionary::Object_klass();
  99     }
 100   }
 101 
 102   // Create type name for klass.
 103   Symbol* name = ArrayKlass::create_element_klass_array_name(element_klass, CHECK_NULL);
 104 
 105   // Initialize instance variables
 106   ObjArrayKlass* oak = ObjArrayKlass::allocate(loader_data, n, element_klass, name, CHECK_0);
 107 
 108   // Add all classes to our internal class loader list here,
 109   // including classes in the bootstrap (NULL) class loader.
 110   // GC walks these as strong roots.
 111   loader_data->add_class(oak);
 112 
 113   ModuleEntry* module = oak->module();
 114   assert(module != NULL, "No module entry for array");
 115 
 116   // Call complete_create_array_klass after all instance variables has been initialized.
 117   ArrayKlass::complete_create_array_klass(oak, super_klass, module, CHECK_0);
 118 
 119   return oak;
 120 }
 121 
 122 ObjArrayKlass::ObjArrayKlass(int n, Klass* element_klass, Symbol* name) : ArrayKlass(name) {
 123   this->set_dimension(n);
 124   this->set_element_klass(element_klass);
 125   // decrement refcount because object arrays are not explicitly freed.  The
 126   // InstanceKlass array_name() keeps the name counted while the klass is
 127   // loaded.
 128   name->decrement_refcount();
 129 
 130   Klass* bk;
 131   if (element_klass->is_objArray_klass()) {
 132     bk = ObjArrayKlass::cast(element_klass)->bottom_klass();
 133   } else {
 134     bk = element_klass;
 135   }
 136   assert(bk != NULL && (bk->is_instance_klass()
 137       || bk->is_typeArray_klass()
 138       || bk->is_valueArray_klass()), "invalid bottom klass");
 139   this->set_bottom_klass(bk);
 140   this->set_class_loader_data(bk->class_loader_data());
 141 
 142   this->set_layout_helper(array_layout_helper(T_OBJECT));
 143   assert(this->is_array_klass(), "sanity");
 144   assert(this->is_objArray_klass(), "sanity");
 145 }
 146 
 147 int ObjArrayKlass::oop_size(oop obj) const {
 148   assert(obj->is_objArray(), "must be object array");
 149   return objArrayOop(obj)->object_size();
 150 }
 151 
 152 objArrayOop ObjArrayKlass::allocate(int length, TRAPS) {
 153   if (length >= 0) {
 154     if (length <= arrayOopDesc::max_array_length(T_OBJECT)) {
 155       int size = objArrayOopDesc::object_size(length);
 156       return (objArrayOop)CollectedHeap::array_allocate(this, size, length, THREAD);
 157     } else {
 158       report_java_out_of_memory("Requested array size exceeds VM limit");
 159       JvmtiExport::post_array_size_exhausted();
 160       THROW_OOP_0(Universe::out_of_memory_error_array_size());
 161     }
 162   } else {
 163     THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
 164   }
 165 }
 166 
 167 static int multi_alloc_counter = 0;
 168 
 169 oop ObjArrayKlass::multi_allocate(int rank, jint* sizes, TRAPS) {
 170   int length = *sizes;
 171   if (rank == 1) { // last dim may be valueArray
 172     return oopFactory::new_array(element_klass(), length, CHECK_NULL);
 173   }
 174   guarantee(rank > 1, "Rank below 1");
 175   // Call to lower_dimension uses this pointer, so most be called before a
 176   // possible GC
 177   Klass* ld_klass = lower_dimension();
 178   // If length < 0 allocate will throw an exception.
 179   objArrayOop array = allocate(length, CHECK_NULL);
 180   objArrayHandle h_array (THREAD, array);
 181   if (length != 0) {
 182     for (int index = 0; index < length; index++) {
 183       ArrayKlass* ak = ArrayKlass::cast(ld_klass);
 184       oop sub_array = ak->multi_allocate(rank-1, &sizes[1], CHECK_NULL);
 185       h_array->obj_at_put(index, sub_array);
 186     }
 187   } else {
 188     // Since this array dimension has zero length, nothing will be
 189     // allocated, however the lower dimension values must be checked
 190     // for illegal values.
 191     for (int i = 0; i < rank - 1; ++i) {
 192       sizes += 1;
 193       if (*sizes < 0) {
 194         THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
 195       }
 196     }
 197   }
 198   return h_array();
 199 }
 200 
 201 // Either oop or narrowOop depending on UseCompressedOops.
 202 template <class T> void ObjArrayKlass::do_copy(arrayOop s, T* src,
 203                                arrayOop d, T* dst, int length, TRAPS) {
 204   if (s == d) {
 205     // since source and destination are equal we do not need conversion checks.
 206     assert(length > 0, "sanity check");
 207     HeapAccess<>::oop_arraycopy(s, d, src, dst, length);
 208   } else {
 209     // We have to make sure all elements conform to the destination array
 210     Klass* bound = ObjArrayKlass::cast(d->klass())->element_klass();
 211     Klass* stype = ObjArrayKlass::cast(s->klass())->element_klass();
 212     if (stype == bound || stype->is_subtype_of(bound)) {
 213       // elements are guaranteed to be subtypes, so no check necessary
 214       HeapAccess<ARRAYCOPY_DISJOINT>::oop_arraycopy(s, d, src, dst, length);
 215     } else {
 216       // slow case: need individual subtype checks
 217       // note: don't use obj_at_put below because it includes a redundant store check
 218       if (!HeapAccess<ARRAYCOPY_DISJOINT | ARRAYCOPY_CHECKCAST>::oop_arraycopy(s, d, src, dst, length)) {
 219         THROW(vmSymbols::java_lang_ArrayStoreException());
 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_valueArray()) {
 230     ValueArrayKlass::cast(d->klass())->copy_array(s, src_pos, d, dst_pos, length, THREAD);
 231     return;
 232   }
 233 
 234   if (!d->is_objArray()) {
 235     THROW(vmSymbols::java_lang_ArrayStoreException());
 236   }
 237 
 238   // Check is all offsets and lengths are non negative
 239   if (src_pos < 0 || dst_pos < 0 || length < 0) {
 240     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
 241   }
 242   // Check if the ranges are valid
 243   if  ( (((unsigned int) length + (unsigned int) src_pos) > (unsigned int) s->length())
 244      || (((unsigned int) length + (unsigned int) dst_pos) > (unsigned int) d->length()) ) {
 245     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
 246   }
 247 
 248   // Special case. Boundary cases must be checked first
 249   // This allows the following call: copy_array(s, s.length(), d.length(), 0).
 250   // This is correct, since the position is supposed to be an 'in between point', i.e., s.length(),
 251   // points to the right of the last element.
 252   if (length==0) {
 253     return;
 254   }
 255   if (UseCompressedOops) {
 256     narrowOop* const src = objArrayOop(s)->obj_at_addr<narrowOop>(src_pos);
 257     narrowOop* const dst = objArrayOop(d)->obj_at_addr<narrowOop>(dst_pos);
 258     do_copy<narrowOop>(s, src, d, dst, length, CHECK);
 259   } else {
 260     oop* const src = objArrayOop(s)->obj_at_addr<oop>(src_pos);
 261     oop* const dst = objArrayOop(d)->obj_at_addr<oop>(dst_pos);
 262     do_copy<oop> (s, src, d, dst, length, CHECK);
 263   }
 264 }
 265 
 266 
 267 Klass* ObjArrayKlass::array_klass_impl(bool or_null, int n, TRAPS) {
 268 
 269   assert(dimension() <= n, "check order of chain");
 270   int dim = dimension();
 271   if (dim == n) return this;
 272 
 273   // lock-free read needs acquire semantics
 274   if (higher_dimension_acquire() == NULL) {
 275     if (or_null)  return NULL;
 276 
 277     ResourceMark rm;
 278     JavaThread *jt = (JavaThread *)THREAD;
 279     {
 280       MutexLocker mc(Compile_lock, THREAD);   // for vtables
 281       // Ensure atomic creation of higher dimensions
 282       MutexLocker mu(MultiArray_lock, THREAD);
 283 
 284       // Check if another thread beat us
 285       if (higher_dimension() == NULL) {
 286 
 287         // Create multi-dim klass object and link them together
 288         Klass* k =
 289           ObjArrayKlass::allocate_objArray_klass(class_loader_data(), dim + 1, this, CHECK_NULL);
 290         ObjArrayKlass* ak = ObjArrayKlass::cast(k);
 291         ak->set_lower_dimension(this);
 292         // use 'release' to pair with lock-free load
 293         release_set_higher_dimension(ak);
 294         assert(ak->is_objArray_klass(), "incorrect initialization of ObjArrayKlass");
 295       }
 296     }
 297   } else {
 298     CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
 299   }
 300 
 301   ObjArrayKlass *ak = ObjArrayKlass::cast(higher_dimension());
 302   if (or_null) {
 303     return ak->array_klass_or_null(n);
 304   }
 305   return ak->array_klass(n, THREAD);
 306 }
 307 
 308 Klass* ObjArrayKlass::array_klass_impl(bool or_null, TRAPS) {
 309   return array_klass_impl(or_null, dimension() +  1, THREAD);
 310 }
 311 
 312 bool ObjArrayKlass::can_be_primary_super_slow() const {
 313   if (!bottom_klass()->can_be_primary_super())
 314     // array of interfaces
 315     return false;
 316   else
 317     return Klass::can_be_primary_super_slow();
 318 }
 319 
 320 GrowableArray<Klass*>* ObjArrayKlass::compute_secondary_supers(int num_extra_slots) {
 321   // interfaces = { cloneable_klass, serializable_klass, elemSuper[], ... };
 322   Array<Klass*>* elem_supers = element_klass()->secondary_supers();
 323   int num_elem_supers = elem_supers == NULL ? 0 : elem_supers->length();
 324   int num_secondaries = num_extra_slots + 2 + num_elem_supers;
 325   if (num_secondaries == 2) {
 326     // Must share this for correct bootstrapping!
 327     set_secondary_supers(Universe::the_array_interfaces_array());
 328     return NULL;
 329   } else {
 330     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(num_elem_supers+2);
 331     secondaries->push(SystemDictionary::Cloneable_klass());
 332     secondaries->push(SystemDictionary::Serializable_klass());
 333     for (int i = 0; i < num_elem_supers; i++) {
 334       Klass* elem_super = (Klass*) elem_supers->at(i);
 335       Klass* array_super = elem_super->array_klass_or_null();
 336       assert(array_super != NULL, "must already have been created");
 337       secondaries->push(array_super);
 338     }
 339     return secondaries;
 340   }
 341 }
 342 
 343 bool ObjArrayKlass::compute_is_subtype_of(Klass* k) {
 344   if (k->is_valueArray_klass() || k->is_objArray_klass()) {
 345     return element_klass()->is_subtype_of(ArrayKlass::cast(k)->element_klass());
 346   } else {
 347     return ArrayKlass::compute_is_subtype_of(k);
 348   }
 349 }
 350 
 351 void ObjArrayKlass::initialize(TRAPS) {
 352   bottom_klass()->initialize(THREAD);  // dispatches to either InstanceKlass or TypeArrayKlass
 353 }
 354 
 355 void ObjArrayKlass::metaspace_pointers_do(MetaspaceClosure* it) {
 356   ArrayKlass::metaspace_pointers_do(it);
 357   it->push(&_element_klass);
 358   it->push(&_bottom_klass);
 359 }
 360 
 361 // JVM support
 362 
 363 jint ObjArrayKlass::compute_modifier_flags(TRAPS) const {
 364   // The modifier for an objectArray is the same as its element
 365   if (element_klass() == NULL) {
 366     assert(Universe::is_bootstrapping(), "partial objArray only at startup");
 367     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
 368   }
 369   // Return the flags of the bottom element type.
 370   jint element_flags = bottom_klass()->compute_modifier_flags(CHECK_0);
 371 
 372   return (element_flags & (JVM_ACC_PUBLIC | JVM_ACC_PRIVATE | JVM_ACC_PROTECTED))
 373                         | (JVM_ACC_ABSTRACT | JVM_ACC_FINAL);
 374 }
 375 
 376 ModuleEntry* ObjArrayKlass::module() const {
 377   assert(bottom_klass() != NULL, "ObjArrayKlass returned unexpected NULL bottom_klass");
 378   // The array is defined in the module of its bottom class
 379   return bottom_klass()->module();
 380 }
 381 
 382 PackageEntry* ObjArrayKlass::package() const {
 383   assert(bottom_klass() != NULL, "ObjArrayKlass returned unexpected NULL bottom_klass");
 384   return bottom_klass()->package();
 385 }
 386 
 387 // Printing
 388 
 389 void ObjArrayKlass::print_on(outputStream* st) const {
 390 #ifndef PRODUCT
 391   Klass::print_on(st);
 392   st->print(" - element klass: ");
 393   element_klass()->print_value_on(st);
 394   st->cr();
 395 #endif //PRODUCT
 396 }
 397 
 398 void ObjArrayKlass::print_value_on(outputStream* st) const {
 399   assert(is_klass(), "must be klass");
 400 
 401   element_klass()->print_value_on(st);
 402   st->print("[]");
 403 }
 404 
 405 #ifndef PRODUCT
 406 
 407 void ObjArrayKlass::oop_print_on(oop obj, outputStream* st) {
 408   ArrayKlass::oop_print_on(obj, st);
 409   assert(obj->is_objArray(), "must be objArray");
 410   objArrayOop oa = objArrayOop(obj);
 411   int print_len = MIN2((intx) oa->length(), MaxElementPrintSize);
 412   for(int index = 0; index < print_len; index++) {
 413     st->print(" - %3d : ", index);
 414     oa->obj_at(index)->print_value_on(st);
 415     st->cr();
 416   }
 417   int remaining = oa->length() - print_len;
 418   if (remaining > 0) {
 419     st->print_cr(" - <%d more elements, increase MaxElementPrintSize to print>", remaining);
 420   }
 421 }
 422 
 423 #endif //PRODUCT
 424 
 425 void ObjArrayKlass::oop_print_value_on(oop obj, outputStream* st) {
 426   assert(obj->is_objArray(), "must be objArray");
 427   st->print("a ");
 428   element_klass()->print_value_on(st);
 429   int len = objArrayOop(obj)->length();
 430   st->print("[%d] ", len);
 431   obj->print_address_on(st);
 432 }
 433 
 434 const char* ObjArrayKlass::internal_name() const {
 435   return external_name();
 436 }
 437 
 438 
 439 // Verification
 440 
 441 void ObjArrayKlass::verify_on(outputStream* st) {
 442   ArrayKlass::verify_on(st);
 443   guarantee(element_klass()->is_klass(), "should be klass");
 444   guarantee(bottom_klass()->is_klass(), "should be klass");
 445   Klass* bk = bottom_klass();
 446   guarantee(bk->is_instance_klass() || bk->is_typeArray_klass() || bk->is_valueArray_klass(),
 447             "invalid bottom klass");
 448 }
 449 
 450 void ObjArrayKlass::oop_verify_on(oop obj, outputStream* st) {
 451   ArrayKlass::oop_verify_on(obj, st);
 452   guarantee(obj->is_objArray(), "must be objArray");
 453   objArrayOop oa = objArrayOop(obj);
 454   for(int index = 0; index < oa->length(); index++) {
 455     guarantee(oopDesc::is_oop_or_null(oa->obj_at(index)), "should be oop");
 456   }
 457 }