1 /*
  2  * Copyright (c) 1997, 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 "cds/aotMetaspace.hpp"
 26 #include "cds/cdsConfig.hpp"
 27 #include "classfile/javaClasses.hpp"
 28 #include "classfile/moduleEntry.hpp"
 29 #include "classfile/symbolTable.hpp"
 30 #include "classfile/vmClasses.hpp"
 31 #include "classfile/vmSymbols.hpp"
 32 #include "gc/shared/collectedHeap.inline.hpp"
 33 #include "jvmtifiles/jvmti.h"
 34 #include "memory/metaspaceClosure.hpp"
 35 #include "memory/resourceArea.hpp"
 36 #include "memory/universe.hpp"
 37 #include "oops/arrayKlass.inline.hpp"
 38 #include "oops/arrayOop.hpp"
 39 #include "oops/instanceKlass.hpp"
 40 #include "oops/klass.inline.hpp"
 41 #include "oops/objArrayKlass.hpp"
 42 #include "oops/objArrayOop.hpp"
 43 #include "oops/oop.inline.hpp"
 44 #include "oops/refArrayKlass.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, ArrayProperties props, markWord prototype_header) :
 95 Klass(kind, prototype_header),
 96   _dimension(1),
 97   _properties(props),
 98   _higher_dimension(nullptr),
 99   _lower_dimension(nullptr) {
100   // Arrays don't add any new methods, so their vtable is the same size as
101   // the vtable of klass Object.
102   set_vtable_length(Universe::base_vtable_size());
103   set_name(name);
104   set_super(Universe::is_bootstrapping() ? nullptr : vmClasses::Object_klass());
105   set_layout_helper(Klass::_lh_neutral_value);
106   // All arrays are considered to be cloneable (See JLS 20.1.5)
107   set_is_cloneable_fast();
108   JFR_ONLY(INIT_ID(this);)
109   log_array_class_load(this);
110 }
111 
112 Symbol* ArrayKlass::create_element_klass_array_name(Klass* element_klass, TRAPS) {
113   ResourceMark rm(THREAD);
114   Symbol* name = nullptr;
115   char *name_str = element_klass->name()->as_C_string();
116   int len = element_klass->name()->utf8_length();
117   char *new_str = NEW_RESOURCE_ARRAY(char, len + 4);
118   int idx = 0;
119   new_str[idx++] = JVM_SIGNATURE_ARRAY;
120   if (element_klass->is_instance_klass()) { // it could be an array or simple type
121     new_str[idx++] = JVM_SIGNATURE_CLASS;
122   }
123   memcpy(&new_str[idx], name_str, len * sizeof(char));
124   idx += len;
125   if (element_klass->is_instance_klass()) {
126     new_str[idx++] = JVM_SIGNATURE_ENDCLASS;
127   }
128   new_str[idx++] = '\0';
129   return SymbolTable::new_symbol(new_str);
130 }
131 
132 // Initialization of vtables and mirror object is done separately from base_create_array_klass,
133 // since a GC can happen. At this point all instance variables of the ArrayKlass must be setup.
134 void ArrayKlass::complete_create_array_klass(ArrayKlass* k, Klass* super_klass, ModuleEntry* module_entry, TRAPS) {
135   k->initialize_supers(super_klass, nullptr, CHECK);
136   k->vtable().initialize_vtable();
137 
138   // During bootstrapping, before java.base is defined, the module_entry may not be present yet.
139   // These classes will be put on a fixup list and their module fields will be patched once
140   // java.base is defined.
141   assert((module_entry != nullptr) || ((module_entry == nullptr) && !ModuleEntryTable::javabase_defined()),
142          "module entry not available post " JAVA_BASE_NAME " definition");
143   oop module_oop = (module_entry != nullptr) ? module_entry->module_oop() : (oop)nullptr;
144 
145   if (k->is_refArray_klass() || k->is_flatArray_klass()) {
146     assert(super_klass != nullptr, "Must be");
147     assert(k->super() != nullptr, "Must be");
148     assert(k->super() == super_klass, "Must be");
149     Handle mirror(THREAD, super_klass->java_mirror());
150     k->set_java_mirror(mirror);
151   } else {
152     java_lang_Class::create_mirror(k, Handle(THREAD, k->class_loader()), Handle(THREAD, module_oop), Handle(), Handle(), CHECK);
153   }
154 }
155 
156 ArrayKlass* ArrayKlass::array_klass(int n, TRAPS) {
157 
158   assert(dimension() <= n, "check order of chain");
159   int dim = dimension();
160   if (dim == n) return this;
161 
162   // lock-free read needs acquire semantics
163   if (higher_dimension_acquire() == nullptr) {
164 
165     // Ensure atomic creation of higher dimensions
166     RecursiveLocker rl(MultiArray_lock, THREAD);
167 
168     if (higher_dimension() == nullptr) {
169       // Create multi-dim klass object and link them together
170       ObjArrayKlass* ak = RefArrayKlass::allocate_objArray_klass(class_loader_data(), dim + 1, this, CHECK_NULL);
171       // use 'release' to pair with lock-free load
172       release_set_higher_dimension(ak);
173       assert(ak->lower_dimension() == this, "lower dimension mismatch");
174     }
175   }
176 
177   ObjArrayKlass* ak = higher_dimension();
178   assert(ak != nullptr, "should be set");
179   THREAD->check_possible_safepoint();
180   return ak->array_klass(n, THREAD);
181 }
182 
183 ArrayKlass* ArrayKlass::array_klass_or_null(int n) {
184 
185   assert(dimension() <= n, "check order of chain");
186   int dim = dimension();
187   if (dim == n) return this;
188 
189   // lock-free read needs acquire semantics
190   if (higher_dimension_acquire() == nullptr) {
191     return nullptr;
192   }
193 
194   ObjArrayKlass *ak = higher_dimension();
195   return ak->array_klass_or_null(n);
196 }
197 
198 ArrayKlass* ArrayKlass::array_klass(TRAPS) {
199   return array_klass(dimension() +  1, THREAD);
200 }
201 
202 ArrayKlass* ArrayKlass::array_klass_or_null() {
203   return array_klass_or_null(dimension() +  1);
204 }
205 
206 
207 GrowableArray<Klass*>* ArrayKlass::compute_secondary_supers(int num_extra_slots,
208                                                             Array<InstanceKlass*>* transitive_interfaces) {
209   // interfaces = { cloneable_klass, serializable_klass };
210   assert(num_extra_slots == 0, "sanity of primitive array type");
211   assert(transitive_interfaces == nullptr, "sanity");
212   // Must share this for correct bootstrapping!
213   set_secondary_supers(Universe::the_array_interfaces_array(),
214                        Universe::the_array_interfaces_bitmap());
215   return nullptr;
216 }
217 
218 oop ArrayKlass::component_mirror() const {
219   return java_lang_Class::component_mirror(java_mirror());
220 }
221 
222 ArrayKlass::ArrayProperties ArrayKlass::array_properties_from_layout(LayoutKind lk) {
223   ArrayKlass::ArrayProperties props = ArrayKlass::ArrayProperties::DEFAULT;
224   switch(lk) {
225     case LayoutKind::NULL_FREE_ATOMIC_FLAT:
226       props = ArrayKlass::ArrayProperties::NULL_RESTRICTED;
227       break;
228     case LayoutKind::NULL_FREE_NON_ATOMIC_FLAT:
229       props = (ArrayKlass::ArrayProperties)(ArrayKlass::ArrayProperties::NULL_RESTRICTED | ArrayKlass::ArrayProperties::NON_ATOMIC);
230       break;
231     case LayoutKind::NULLABLE_ATOMIC_FLAT:
232       props = ArrayKlass::ArrayProperties::DEFAULT;
233       break;
234     default:
235       ShouldNotReachHere();
236   }
237   return props;
238 }
239 
240   const char* ArrayKlass::array_properties_as_string(ArrayProperties props) {
241     // Caller must have set a ResourceMark
242     stringStream ss;
243     if (props == DEFAULT) {
244       ss.print("DEFAULT (NULLABLE ATOMIC)");
245     } else {
246       ss.print("%s", ((props & NULL_RESTRICTED) != 0) ? "NULL_RESTRICTED " : "NULLABLE ");
247       ss.print("%s", ((props & NON_ATOMIC) != 0) ? "NON_ATOMIC " : "ATOMIC ");
248     }
249     return ss.as_string();
250   }
251 
252 
253 // JVMTI support
254 
255 jint ArrayKlass::jvmti_class_status() const {
256   return JVMTI_CLASS_STATUS_ARRAY;
257 }
258 
259 void ArrayKlass::metaspace_pointers_do(MetaspaceClosure* it) {
260   Klass::metaspace_pointers_do(it);
261 
262   ResourceMark rm;
263   log_trace(aot)("Iter(ArrayKlass): %p (%s)", this, external_name());
264 
265   // need to cast away volatile
266   it->push((Klass**)&_higher_dimension);
267   it->push((Klass**)&_lower_dimension);
268 }
269 
270 #if INCLUDE_CDS
271 void ArrayKlass::remove_unshareable_info() {
272   Klass::remove_unshareable_info();
273   if (_higher_dimension != nullptr) {
274     ArrayKlass *ak = higher_dimension();
275     ak->remove_unshareable_info();
276   }
277 }
278 
279 void ArrayKlass::remove_java_mirror() {
280   Klass::remove_java_mirror();
281   if (_higher_dimension != nullptr) {
282     ArrayKlass *ak = higher_dimension();
283     ak->remove_java_mirror();
284   }
285 }
286 
287 void ArrayKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
288   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
289   // Klass recreates the component mirror also
290 
291   if (_higher_dimension != nullptr) {
292     ObjArrayKlass *ak = higher_dimension();
293     log_array_class_load(ak);
294     ak->restore_unshareable_info(loader_data, protection_domain, CHECK);
295   }
296 }
297 
298 void ArrayKlass::cds_print_value_on(outputStream* st) const {
299   assert(is_klass(), "must be klass");
300   st->print("      - array: %s", internal_name());
301   if (_higher_dimension != nullptr) {
302     ArrayKlass* ak = higher_dimension();
303     st->cr();
304     ak->cds_print_value_on(st);
305   }
306 }
307 #endif // INCLUDE_CDS
308 
309 void ArrayKlass::log_array_class_load(Klass* k) {
310   LogTarget(Debug, class, load, array) lt;
311   if (lt.is_enabled()) {
312     LogStream ls(lt);
313     ResourceMark rm;
314     ls.print("%s", k->name()->as_klass_external_name());
315     if (AOTMetaspace::in_aot_cache_dynamic_region((void*)k)) {
316       ls.print(" source: shared objects file (top)");
317     } else if (AOTMetaspace::in_aot_cache_static_region((void*)k)) {
318       ls.print(" source: shared objects file");
319     }
320     ls.cr();
321   }
322 }
323 
324 // Printing
325 
326 void ArrayKlass::print_on(outputStream* st) const {
327   assert(is_klass(), "must be klass");
328   Klass::print_on(st);
329 }
330 
331 void ArrayKlass::print_value_on(outputStream* st) const {
332   assert(is_klass(), "must be klass");
333   for(int index = 0; index < dimension(); index++) {
334     st->print("[]");
335   }
336 }
337 
338 void ArrayKlass::oop_print_on(oop obj, outputStream* st) {
339   assert(obj->is_array(), "must be array");
340   Klass::oop_print_on(obj, st);
341   st->print_cr(" - length: %d", arrayOop(obj)->length());
342 }
343 
344 
345 // Verification
346 
347 void ArrayKlass::verify_on(outputStream* st) {
348   Klass::verify_on(st);
349 }
350 
351 void ArrayKlass::oop_verify_on(oop obj, outputStream* st) {
352   guarantee(obj->is_array(), "must be array");
353   arrayOop a = arrayOop(obj);
354   guarantee(a->length() >= 0, "array with negative length?");
355 }