1 /*
  2  * Copyright (c) 1997, 2024, 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 "cds/cdsConfig.hpp"
 27 #include "cds/metaspaceShared.hpp"
 28 #include "classfile/javaClasses.hpp"
 29 #include "classfile/moduleEntry.hpp"
 30 #include "classfile/symbolTable.hpp"
 31 #include "classfile/vmClasses.hpp"
 32 #include "classfile/vmSymbols.hpp"
 33 #include "gc/shared/collectedHeap.inline.hpp"
 34 #include "jvmtifiles/jvmti.h"
 35 #include "memory/metaspaceClosure.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/instanceKlass.hpp"
 41 #include "oops/klass.inline.hpp"
 42 #include "oops/objArrayKlass.hpp"
 43 #include "oops/objArrayOop.hpp"
 44 #include "oops/oop.inline.hpp"
 45 #include "runtime/handles.inline.hpp"
 46 
 47 ArrayKlass::ArrayKlass() {
 48   assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
 49 }
 50 
 51 int ArrayKlass::static_size(int header_size) {
 52   // size of an array klass object
 53   assert(header_size <= InstanceKlass::header_size(), "bad header size");
 54   // If this assert fails, see comments in base_create_array_klass.
 55   header_size = InstanceKlass::header_size();
 56   int vtable_len = Universe::base_vtable_size();
 57   int size = header_size + vtable_len;
 58   return align_metadata_size(size);
 59 }
 60 
 61 
 62 InstanceKlass* ArrayKlass::java_super() const {
 63   if (super() == nullptr)  return nullptr;  // bootstrap case
 64   // Array klasses have primary supertypes which are not reported to Java.
 65   // Example super chain:  String[][] -> Object[][] -> Object[] -> Object
 66   return vmClasses::Object_klass();
 67 }
 68 
 69 
 70 oop ArrayKlass::multi_allocate(int rank, jint* sizes, TRAPS) {
 71   ShouldNotReachHere();
 72   return nullptr;
 73 }
 74 
 75 // find field according to JVM spec 5.4.3.2, returns the klass in which the field is defined
 76 Klass* ArrayKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
 77   // There are no fields in an array klass but look to the super class (Object)
 78   assert(super(), "super klass must be present");
 79   return super()->find_field(name, sig, fd);
 80 }
 81 
 82 Method* ArrayKlass::uncached_lookup_method(const Symbol* name,
 83                                            const Symbol* signature,
 84                                            OverpassLookupMode overpass_mode,
 85                                            PrivateLookupMode private_mode) const {
 86   // There are no methods in an array klass but the super class (Object) has some
 87   assert(super(), "super klass must be present");
 88   // Always ignore overpass methods in superclasses, although technically the
 89   // super klass of an array, (j.l.Object) should not have
 90   // any overpass methods present.
 91   return super()->uncached_lookup_method(name, signature, OverpassLookupMode::skip, private_mode);
 92 }
 93 
 94 ArrayKlass::ArrayKlass(Symbol* name, KlassKind kind) :
 95   Klass(kind),
 96   _dimension(1),
 97   _higher_dimension(nullptr),
 98   _lower_dimension(nullptr) {
 99   // Arrays don't add any new methods, so their vtable is the same size as
100   // the vtable of klass Object.
101   set_vtable_length(Universe::base_vtable_size());
102   set_name(name);
103   set_super(Universe::is_bootstrapping() ? nullptr : vmClasses::Object_klass());
104   set_layout_helper(Klass::_lh_neutral_value);
105   set_is_cloneable(); // All arrays are considered to be cloneable (See JLS 20.1.5)
106   JFR_ONLY(INIT_ID(this);)
107   log_array_class_load(this);
108 }
109 
110 Symbol* ArrayKlass::create_element_klass_array_name(Klass* element_klass, TRAPS) {
111   ResourceMark rm(THREAD);
112   Symbol* name = nullptr;
113   char *name_str = element_klass->name()->as_C_string();
114   int len = element_klass->name()->utf8_length();
115   char *new_str = NEW_RESOURCE_ARRAY(char, len + 4);
116   int idx = 0;
117   new_str[idx++] = JVM_SIGNATURE_ARRAY;
118   if (element_klass->is_instance_klass()) { // it could be an array or simple type
119     new_str[idx++] = JVM_SIGNATURE_CLASS;
120   }
121   memcpy(&new_str[idx], name_str, len * sizeof(char));
122   idx += len;
123   if (element_klass->is_instance_klass()) {
124     new_str[idx++] = JVM_SIGNATURE_ENDCLASS;
125   }
126   new_str[idx++] = '\0';
127   return SymbolTable::new_symbol(new_str);
128 }
129 
130 // Initialization of vtables and mirror object is done separately from base_create_array_klass,
131 // since a GC can happen. At this point all instance variables of the ArrayKlass must be setup.
132 void ArrayKlass::complete_create_array_klass(ArrayKlass* k, Klass* super_klass, ModuleEntry* module_entry, TRAPS) {
133   k->initialize_supers(super_klass, nullptr, CHECK);
134   k->vtable().initialize_vtable();
135 
136   // During bootstrapping, before java.base is defined, the module_entry may not be present yet.
137   // These classes will be put on a fixup list and their module fields will be patched once
138   // java.base is defined.
139   assert((module_entry != nullptr) || ((module_entry == nullptr) && !ModuleEntryTable::javabase_defined()),
140          "module entry not available post " JAVA_BASE_NAME " definition");
141   oop module = (module_entry != nullptr) ? module_entry->module() : (oop)nullptr;
142   java_lang_Class::create_mirror(k, Handle(THREAD, k->class_loader()), Handle(THREAD, module), Handle(), Handle(), CHECK);
143 }
144 
145 ArrayKlass* ArrayKlass::array_klass(int n, TRAPS) {
146 
147   assert(dimension() <= n, "check order of chain");
148   int dim = dimension();
149   if (dim == n) return this;
150 
151   // lock-free read needs acquire semantics
152   if (higher_dimension_acquire() == nullptr) {
153 
154     // Ensure atomic creation of higher dimensions
155     RecursiveLocker rl(MultiArray_lock, THREAD);
156 
157     if (higher_dimension() == nullptr) {
158       // Create multi-dim klass object and link them together
159       ObjArrayKlass* ak =
160       ObjArrayKlass::allocate_objArray_klass(class_loader_data(), dim + 1, this, false, CHECK_NULL);
161       // use 'release' to pair with lock-free load
162       release_set_higher_dimension(ak);
163       assert(ak->lower_dimension() == this, "lower dimension mismatch");
164     }
165   }
166 
167   ObjArrayKlass* ak = higher_dimension();
168   assert(ak != nullptr, "should be set");
169   THREAD->check_possible_safepoint();
170   return ak->array_klass(n, THREAD);
171 }
172 
173 ArrayKlass* ArrayKlass::array_klass_or_null(int n) {
174 
175   assert(dimension() <= n, "check order of chain");
176   int dim = dimension();
177   if (dim == n) return this;
178 
179   // lock-free read needs acquire semantics
180   if (higher_dimension_acquire() == nullptr) {
181     return nullptr;
182   }
183 
184   ObjArrayKlass *ak = higher_dimension();
185   return ak->array_klass_or_null(n);
186 }
187 
188 ArrayKlass* ArrayKlass::array_klass(TRAPS) {
189   return array_klass(dimension() +  1, THREAD);
190 }
191 
192 ArrayKlass* ArrayKlass::array_klass_or_null() {
193   return array_klass_or_null(dimension() +  1);
194 }
195 
196 
197 GrowableArray<Klass*>* ArrayKlass::compute_secondary_supers(int num_extra_slots,
198                                                             Array<InstanceKlass*>* transitive_interfaces) {
199   // interfaces = { cloneable_klass, serializable_klass };
200   assert(num_extra_slots == 0, "sanity of primitive array type");
201   assert(transitive_interfaces == nullptr, "sanity");
202   // Must share this for correct bootstrapping!
203   set_secondary_supers(Universe::the_array_interfaces_array(),
204                        Universe::the_array_interfaces_bitmap());
205   return nullptr;
206 }
207 
208 objArrayOop ArrayKlass::allocate_arrayArray(int n, int length, TRAPS) {
209   check_array_allocation_length(length, arrayOopDesc::max_array_length(T_ARRAY), CHECK_NULL);
210   size_t size = objArrayOopDesc::object_size(length);
211   ArrayKlass* ak = array_klass(n + dimension(), CHECK_NULL);
212   objArrayOop o = (objArrayOop)Universe::heap()->array_allocate(ak, size, length,
213                                                                 /* do_zero */ true, CHECK_NULL);
214   // initialization to null not necessary, area already cleared
215   return o;
216 }
217 
218 oop ArrayKlass::component_mirror() const {
219   return java_lang_Class::component_mirror(java_mirror());
220 }
221 
222 jint ArrayKlass::compute_modifier_flags() const {
223   int identity_flag = (Arguments::enable_preview()) ? JVM_ACC_IDENTITY : 0;
224 
225   return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC
226                     | identity_flag;
227 }
228 
229 // JVMTI support
230 
231 jint ArrayKlass::jvmti_class_status() const {
232   return JVMTI_CLASS_STATUS_ARRAY;
233 }
234 
235 void ArrayKlass::metaspace_pointers_do(MetaspaceClosure* it) {
236   Klass::metaspace_pointers_do(it);
237 
238   ResourceMark rm;
239   log_trace(cds)("Iter(ArrayKlass): %p (%s)", this, external_name());
240 
241   // need to cast away volatile
242   it->push((Klass**)&_higher_dimension);
243   it->push((Klass**)&_lower_dimension);
244 }
245 
246 #if INCLUDE_CDS
247 void ArrayKlass::remove_unshareable_info() {
248   Klass::remove_unshareable_info();
249   if (_higher_dimension != nullptr) {
250     ArrayKlass *ak = higher_dimension();
251     ak->remove_unshareable_info();
252   }
253 }
254 
255 void ArrayKlass::remove_java_mirror() {
256   Klass::remove_java_mirror();
257   if (_higher_dimension != nullptr) {
258     ArrayKlass *ak = higher_dimension();
259     ak->remove_java_mirror();
260   }
261 }
262 
263 void ArrayKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
264   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
265   // Klass recreates the component mirror also
266 
267   if (_higher_dimension != nullptr) {
268     ArrayKlass *ak = higher_dimension();
269     log_array_class_load(ak);
270     ak->restore_unshareable_info(loader_data, protection_domain, CHECK);
271   }
272 }
273 
274 void ArrayKlass::cds_print_value_on(outputStream* st) const {
275   assert(is_klass(), "must be klass");
276   st->print("      - array: %s", internal_name());
277   if (_higher_dimension != nullptr) {
278     ArrayKlass* ak = higher_dimension();
279     st->cr();
280     ak->cds_print_value_on(st);
281   }
282 }
283 #endif // INCLUDE_CDS
284 
285 void ArrayKlass::log_array_class_load(Klass* k) {
286   LogTarget(Debug, class, load, array) lt;
287   if (lt.is_enabled()) {
288     LogStream ls(lt);
289     ResourceMark rm;
290     ls.print("%s", k->name()->as_klass_external_name());
291     if (MetaspaceShared::is_shared_dynamic((void*)k)) {
292       ls.print(" source: shared objects file (top)");
293     } else if (MetaspaceShared::is_shared_static((void*)k)) {
294       ls.print(" source: shared objects file");
295     }
296     ls.cr();
297   }
298 }
299 
300 // Printing
301 
302 void ArrayKlass::print_on(outputStream* st) const {
303   assert(is_klass(), "must be klass");
304   Klass::print_on(st);
305 }
306 
307 void ArrayKlass::print_value_on(outputStream* st) const {
308   assert(is_klass(), "must be klass");
309   for(int index = 0; index < dimension(); index++) {
310     st->print("[]");
311   }
312 }
313 
314 void ArrayKlass::oop_print_on(oop obj, outputStream* st) {
315   assert(obj->is_array(), "must be array");
316   Klass::oop_print_on(obj, st);
317   st->print_cr(" - length: %d", arrayOop(obj)->length());
318 }
319 
320 
321 // Verification
322 
323 void ArrayKlass::verify_on(outputStream* st) {
324   Klass::verify_on(st);
325 }
326 
327 void ArrayKlass::oop_verify_on(oop obj, outputStream* st) {
328   guarantee(obj->is_array(), "must be array");
329   arrayOop a = arrayOop(obj);
330   guarantee(a->length() >= 0, "array with negative length?");
331 }