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/vmSymbols.hpp"
 27 #include "code/codeCache.hpp"
 28 #include "gc/shared/barrierSet.hpp"
 29 #include "gc/shared/collectedHeap.inline.hpp"
 30 #include "gc/shared/gcLocker.inline.hpp"
 31 #include "interpreter/interpreter.hpp"
 32 #include "logging/log.hpp"
 33 #include "memory/metaspaceClosure.hpp"
 34 #include "memory/metadataFactory.hpp"
 35 #include "oops/access.hpp"
 36 #include "oops/compressedOops.inline.hpp"
 37 #include "oops/fieldStreams.inline.hpp"
 38 #include "oops/flatArrayKlass.hpp"
 39 #include "oops/inlineKlass.inline.hpp"
 40 #include "oops/instanceKlass.inline.hpp"
 41 #include "oops/method.hpp"
 42 #include "oops/oop.inline.hpp"
 43 #include "oops/objArrayKlass.hpp"
 44 #include "runtime/fieldDescriptor.inline.hpp"
 45 #include "runtime/handles.inline.hpp"
 46 #include "runtime/safepointVerifiers.hpp"
 47 #include "runtime/sharedRuntime.hpp"
 48 #include "runtime/signature.hpp"
 49 #include "runtime/thread.inline.hpp"
 50 #include "utilities/copy.hpp"
 51 
 52   // Constructor
 53 InlineKlass::InlineKlass(const ClassFileParser& parser)
 54     : InstanceKlass(parser, InlineKlass::Kind) {
 55   set_prototype_header(markWord::inline_type_prototype());
 56   assert(is_inline_klass(), "sanity");
 57   assert(prototype_header().is_inline_type(), "sanity");
 58 }
 59 
 60 void InlineKlass::init_fixed_block() {
 61   _adr_inlineklass_fixed_block = inlineklass_static_block();
 62   // Addresses used for inline type calling convention
 63   *((Array<SigEntry>**)adr_extended_sig()) = nullptr;
 64   *((Array<VMRegPair>**)adr_return_regs()) = nullptr;
 65   *((address*)adr_pack_handler()) = nullptr;
 66   *((address*)adr_pack_handler_jobject()) = nullptr;
 67   *((address*)adr_unpack_handler()) = nullptr;
 68   assert(pack_handler() == nullptr, "pack handler not null");
 69   *((int*)adr_default_value_offset()) = 0;
 70   *((address*)adr_value_array_klasses()) = nullptr;
 71 }
 72 
 73 oop InlineKlass::default_value() {
 74   assert(is_initialized() || is_being_initialized() || is_in_error_state(), "default value is set at the beginning of initialization");
 75   oop val = java_mirror()->obj_field_acquire(default_value_offset());
 76   assert(val != nullptr, "Sanity check");
 77   assert(oopDesc::is_oop(val), "Sanity check");
 78   assert(val->is_inline_type(), "Sanity check");
 79   assert(val->klass() == this, "sanity check");
 80   return val;
 81 }
 82 
 83 int InlineKlass::first_field_offset_old() {
 84 #ifdef ASSERT
 85   int first_offset = INT_MAX;
 86   for (AllFieldStream fs(this); !fs.done(); fs.next()) {
 87     if (fs.offset() < first_offset) first_offset= fs.offset();
 88   }
 89 #endif
 90   int base_offset = instanceOopDesc::base_offset_in_bytes();
 91   // The first field of line types is aligned on a long boundary
 92   base_offset = align_up(base_offset, BytesPerLong);
 93   assert(base_offset == first_offset, "inconsistent offsets");
 94   return base_offset;
 95 }
 96 
 97 instanceOop InlineKlass::allocate_instance(TRAPS) {
 98   int size = size_helper();  // Query before forming handle.
 99 
100   instanceOop oop = (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
101   assert(oop->mark().is_inline_type(), "Expected inline type");
102   return oop;
103 }
104 
105 instanceOop InlineKlass::allocate_instance_buffer(TRAPS) {
106   int size = size_helper();  // Query before forming handle.
107 
108   instanceOop oop = (instanceOop)Universe::heap()->obj_buffer_allocate(this, size, CHECK_NULL);
109   assert(oop->mark().is_inline_type(), "Expected inline type");
110   return oop;
111 }
112 
113 int InlineKlass::nonstatic_oop_count() {
114   int oops = 0;
115   int map_count = nonstatic_oop_map_count();
116   OopMapBlock* block = start_of_nonstatic_oop_maps();
117   OopMapBlock* end = block + map_count;
118   while (block != end) {
119     oops += block->count();
120     block++;
121   }
122   return oops;
123 }
124 
125 oop InlineKlass::read_flat_field(oop obj, int offset, TRAPS) {
126   oop res = nullptr;
127   assert(is_initialized() || is_being_initialized()|| is_in_error_state(),
128         "Must be initialized, initializing or in a corner case of an escaped instance of a class that failed its initialization");
129   if (is_empty_inline_type()) {
130     res = (instanceOop)default_value();
131   } else {
132     Handle obj_h(THREAD, obj);
133     res = allocate_instance_buffer(CHECK_NULL);
134     inline_copy_payload_to_new_oop(((char*)(oopDesc*)obj_h()) + offset, res);
135   }
136   assert(res != nullptr, "Must be set in one of two paths above");
137   return res;
138 }
139 
140 void InlineKlass::write_flat_field(oop obj, int offset, oop value, TRAPS) {
141   if (value == nullptr) {
142     THROW(vmSymbols::java_lang_NullPointerException());
143   }
144   if (!is_empty_inline_type()) {
145     inline_copy_oop_to_payload(value, ((char*)(oopDesc*)obj) + offset);
146   }
147 }
148 
149 // Arrays of...
150 
151 bool InlineKlass::flat_array() {
152   if (!UseFlatArray) {
153     return false;
154   }
155   // Too big
156   int elem_bytes = get_exact_size_in_bytes();
157   if ((FlatArrayElementMaxSize >= 0) && (elem_bytes > FlatArrayElementMaxSize)) {
158     return false;
159   }
160   // Too many embedded oops
161   if ((FlatArrayElementMaxOops >= 0) && (nonstatic_oop_count() > FlatArrayElementMaxOops)) {
162     return false;
163   }
164   // Declared atomic but not naturally atomic.
165   if (is_declared_atomic() && !is_naturally_atomic()) {
166     return false;
167   }
168   // VM enforcing InlineArrayAtomicAccess only...
169   if (InlineArrayAtomicAccess && (!is_naturally_atomic())) {
170     return false;
171   }
172   return true;
173 }
174 
175 Klass* InlineKlass::value_array_klass(int n, TRAPS) {
176   if (Atomic::load_acquire(adr_value_array_klasses()) == nullptr) {
177     ResourceMark rm(THREAD);
178     JavaThread *jt = JavaThread::cast(THREAD);
179     {
180       // Atomic creation of array_klasses
181       MutexLocker ma(THREAD, MultiArray_lock);
182 
183       // Check if update has already taken place
184       if (value_array_klasses() == nullptr) {
185         ArrayKlass* k;
186         if (flat_array()) {
187           k = FlatArrayKlass::allocate_klass(this, CHECK_NULL);
188         } else {
189           k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, true, true, CHECK_NULL);
190 
191         }
192         // use 'release' to pair with lock-free load
193         Atomic::release_store(adr_value_array_klasses(), k);
194       }
195     }
196   }
197   ArrayKlass* ak = value_array_klasses();
198   return ak->array_klass(n, THREAD);
199 }
200 
201 Klass* InlineKlass::value_array_klass_or_null(int n) {
202   // Need load-acquire for lock-free read
203   ArrayKlass* ak = Atomic::load_acquire(adr_value_array_klasses());
204   if (ak == nullptr) {
205     return nullptr;
206   } else {
207     return ak->array_klass_or_null(n);
208   }
209 }
210 
211 Klass* InlineKlass::value_array_klass(TRAPS) {
212   return value_array_klass(1, THREAD);
213 }
214 
215 Klass* InlineKlass::value_array_klass_or_null() {
216   return value_array_klass_or_null(1);
217 }
218 
219 // Inline type arguments are not passed by reference, instead each
220 // field of the inline type is passed as an argument. This helper
221 // function collects the flat field (recursively)
222 // in a list. Included with the field's type is
223 // the offset of each field in the inline type: i2c and c2i adapters
224 // need that to load or store fields. Finally, the list of fields is
225 // sorted in order of increasing offsets: the adapters and the
226 // compiled code need to agree upon the order of fields.
227 //
228 // The list of basic types that is returned starts with a T_METADATA
229 // and ends with an extra T_VOID. T_METADATA/T_VOID pairs are used as
230 // delimiters. Every entry between the two is a field of the inline
231 // type. If there's an embedded inline type in the list, it also starts
232 // with a T_METADATA and ends with a T_VOID. This is so we can
233 // generate a unique fingerprint for the method's adapters and we can
234 // generate the list of basic types from the interpreter point of view
235 // (inline types passed as reference: iterate on the list until a
236 // T_METADATA, drop everything until and including the closing
237 // T_VOID) or the compiler point of view (each field of the inline
238 // types is an argument: drop all T_METADATA/T_VOID from the list).
239 int InlineKlass::collect_fields(GrowableArray<SigEntry>* sig, int base_off) {
240   int count = 0;
241   SigEntry::add_entry(sig, T_METADATA, name(), base_off);
242   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
243     if (fs.access_flags().is_static()) continue;
244     int offset = base_off + fs.offset() - (base_off > 0 ? first_field_offset() : 0);
245     if (fs.is_flat()) {
246       // Resolve klass of flat field and recursively collect fields
247       Klass* vk = get_inline_type_field_klass(fs.index());
248       count += InlineKlass::cast(vk)->collect_fields(sig, offset);
249     } else {
250       BasicType bt = Signature::basic_type(fs.signature());
251       if (bt == T_PRIMITIVE_OBJECT) {
252         bt = T_OBJECT;
253       }
254       SigEntry::add_entry(sig, bt, fs.signature(), offset);
255       count += type2size[bt];
256     }
257   }
258   int offset = base_off + size_helper()*HeapWordSize - (base_off > 0 ? first_field_offset() : 0);
259   SigEntry::add_entry(sig, T_VOID, name(), offset);
260   if (base_off == 0) {
261     sig->sort(SigEntry::compare);
262   }
263   assert(sig->at(0)._bt == T_METADATA && sig->at(sig->length()-1)._bt == T_VOID, "broken structure");
264   return count;
265 }
266 
267 void InlineKlass::initialize_calling_convention(TRAPS) {
268   // Because the pack and unpack handler addresses need to be loadable from generated code,
269   // they are stored at a fixed offset in the klass metadata. Since inline type klasses do
270   // not have a vtable, the vtable offset is used to store these addresses.
271   if (InlineTypeReturnedAsFields || InlineTypePassFieldsAsArgs) {
272     ResourceMark rm;
273     GrowableArray<SigEntry> sig_vk;
274     int nb_fields = collect_fields(&sig_vk);
275     Array<SigEntry>* extended_sig = MetadataFactory::new_array<SigEntry>(class_loader_data(), sig_vk.length(), CHECK);
276     *((Array<SigEntry>**)adr_extended_sig()) = extended_sig;
277     for (int i = 0; i < sig_vk.length(); i++) {
278       extended_sig->at_put(i, sig_vk.at(i));
279     }
280     if (can_be_returned_as_fields(/* init= */ true)) {
281       nb_fields++;
282       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, nb_fields);
283       sig_bt[0] = T_METADATA;
284       SigEntry::fill_sig_bt(&sig_vk, sig_bt+1);
285       VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, nb_fields);
286       int total = SharedRuntime::java_return_convention(sig_bt, regs, nb_fields);
287 
288       if (total > 0) {
289         Array<VMRegPair>* return_regs = MetadataFactory::new_array<VMRegPair>(class_loader_data(), nb_fields, CHECK);
290         *((Array<VMRegPair>**)adr_return_regs()) = return_regs;
291         for (int i = 0; i < nb_fields; i++) {
292           return_regs->at_put(i, regs[i]);
293         }
294 
295         BufferedInlineTypeBlob* buffered_blob = SharedRuntime::generate_buffered_inline_type_adapter(this);
296         *((address*)adr_pack_handler()) = buffered_blob->pack_fields();
297         *((address*)adr_pack_handler_jobject()) = buffered_blob->pack_fields_jobject();
298         *((address*)adr_unpack_handler()) = buffered_blob->unpack_fields();
299         assert(CodeCache::find_blob(pack_handler()) == buffered_blob, "lost track of blob");
300         assert(can_be_returned_as_fields(), "sanity");
301       }
302     }
303     if (!can_be_returned_as_fields() && !can_be_passed_as_fields()) {
304       MetadataFactory::free_array<SigEntry>(class_loader_data(), extended_sig);
305       assert(return_regs() == nullptr, "sanity");
306     }
307   }
308 }
309 
310 void InlineKlass::deallocate_contents(ClassLoaderData* loader_data) {
311   if (extended_sig() != nullptr) {
312     MetadataFactory::free_array<SigEntry>(loader_data, extended_sig());
313   }
314   if (return_regs() != nullptr) {
315     MetadataFactory::free_array<VMRegPair>(loader_data, return_regs());
316   }
317   cleanup_blobs();
318   InstanceKlass::deallocate_contents(loader_data);
319 }
320 
321 void InlineKlass::cleanup(InlineKlass* ik) {
322   ik->cleanup_blobs();
323 }
324 
325 void InlineKlass::cleanup_blobs() {
326   if (pack_handler() != nullptr) {
327     CodeBlob* buffered_blob = CodeCache::find_blob(pack_handler());
328     assert(buffered_blob->is_buffered_inline_type_blob(), "bad blob type");
329     BufferBlob::free((BufferBlob*)buffered_blob);
330     *((address*)adr_pack_handler()) = nullptr;
331     *((address*)adr_pack_handler_jobject()) = nullptr;
332     *((address*)adr_unpack_handler()) = nullptr;
333   }
334 }
335 
336 // Can this inline type be passed as multiple values?
337 bool InlineKlass::can_be_passed_as_fields() const {
338   return InlineTypePassFieldsAsArgs;
339 }
340 
341 // Can this inline type be returned as multiple values?
342 bool InlineKlass::can_be_returned_as_fields(bool init) const {
343   return InlineTypeReturnedAsFields && (init || return_regs() != nullptr);
344 }
345 
346 // Create handles for all oop fields returned in registers that are going to be live across a safepoint
347 void InlineKlass::save_oop_fields(const RegisterMap& reg_map, GrowableArray<Handle>& handles) const {
348   Thread* thread = Thread::current();
349   const Array<SigEntry>* sig_vk = extended_sig();
350   const Array<VMRegPair>* regs = return_regs();
351   int j = 1;
352 
353   for (int i = 0; i < sig_vk->length(); i++) {
354     BasicType bt = sig_vk->at(i)._bt;
355     if (bt == T_OBJECT || bt == T_ARRAY) {
356       VMRegPair pair = regs->at(j);
357       address loc = reg_map.location(pair.first(), nullptr);
358       oop v = *(oop*)loc;
359       assert(v == nullptr || oopDesc::is_oop(v), "not an oop?");
360       assert(Universe::heap()->is_in_or_null(v), "must be heap pointer");
361       handles.push(Handle(thread, v));
362     }
363     if (bt == T_METADATA) {
364       continue;
365     }
366     if (bt == T_VOID &&
367         sig_vk->at(i-1)._bt != T_LONG &&
368         sig_vk->at(i-1)._bt != T_DOUBLE) {
369       continue;
370     }
371     j++;
372   }
373   assert(j == regs->length(), "missed a field?");
374 }
375 
376 // Update oop fields in registers from handles after a safepoint
377 void InlineKlass::restore_oop_results(RegisterMap& reg_map, GrowableArray<Handle>& handles) const {
378   assert(InlineTypeReturnedAsFields, "Inline types should never be returned as fields");
379   const Array<SigEntry>* sig_vk = extended_sig();
380   const Array<VMRegPair>* regs = return_regs();
381   assert(regs != nullptr, "inconsistent");
382 
383   int j = 1;
384   for (int i = 0, k = 0; i < sig_vk->length(); i++) {
385     BasicType bt = sig_vk->at(i)._bt;
386     if (bt == T_OBJECT || bt == T_ARRAY) {
387       VMRegPair pair = regs->at(j);
388       address loc = reg_map.location(pair.first(), nullptr);
389       *(oop*)loc = handles.at(k++)();
390     }
391     if (bt == T_METADATA) {
392       continue;
393     }
394     if (bt == T_VOID &&
395         sig_vk->at(i-1)._bt != T_LONG &&
396         sig_vk->at(i-1)._bt != T_DOUBLE) {
397       continue;
398     }
399     j++;
400   }
401   assert(j == regs->length(), "missed a field?");
402 }
403 
404 // Fields are in registers. Create an instance of the inline type and
405 // initialize it with the values of the fields.
406 oop InlineKlass::realloc_result(const RegisterMap& reg_map, const GrowableArray<Handle>& handles, TRAPS) {
407   oop new_vt = allocate_instance(CHECK_NULL);
408   const Array<SigEntry>* sig_vk = extended_sig();
409   const Array<VMRegPair>* regs = return_regs();
410 
411   int j = 1;
412   int k = 0;
413   for (int i = 0; i < sig_vk->length(); i++) {
414     BasicType bt = sig_vk->at(i)._bt;
415     if (bt == T_METADATA) {
416       continue;
417     }
418     if (bt == T_VOID) {
419       if (sig_vk->at(i-1)._bt == T_LONG ||
420           sig_vk->at(i-1)._bt == T_DOUBLE) {
421         j++;
422       }
423       continue;
424     }
425     int off = sig_vk->at(i)._offset;
426     assert(off > 0, "offset in object should be positive");
427     VMRegPair pair = regs->at(j);
428     address loc = reg_map.location(pair.first(), nullptr);
429     switch(bt) {
430     case T_BOOLEAN: {
431       new_vt->bool_field_put(off, *(jboolean*)loc);
432       break;
433     }
434     case T_CHAR: {
435       new_vt->char_field_put(off, *(jchar*)loc);
436       break;
437     }
438     case T_BYTE: {
439       new_vt->byte_field_put(off, *(jbyte*)loc);
440       break;
441     }
442     case T_SHORT: {
443       new_vt->short_field_put(off, *(jshort*)loc);
444       break;
445     }
446     case T_INT: {
447       new_vt->int_field_put(off, *(jint*)loc);
448       break;
449     }
450     case T_LONG: {
451 #ifdef _LP64
452       new_vt->double_field_put(off,  *(jdouble*)loc);
453 #else
454       Unimplemented();
455 #endif
456       break;
457     }
458     case T_OBJECT:
459     case T_ARRAY: {
460       Handle handle = handles.at(k++);
461       new_vt->obj_field_put(off, handle());
462       break;
463     }
464     case T_FLOAT: {
465       new_vt->float_field_put(off,  *(jfloat*)loc);
466       break;
467     }
468     case T_DOUBLE: {
469       new_vt->double_field_put(off, *(jdouble*)loc);
470       break;
471     }
472     default:
473       ShouldNotReachHere();
474     }
475     *(intptr_t*)loc = 0xDEAD;
476     j++;
477   }
478   assert(j == regs->length(), "missed a field?");
479   assert(k == handles.length(), "missed an oop?");
480   return new_vt;
481 }
482 
483 // Check the return register for an InlineKlass oop
484 InlineKlass* InlineKlass::returned_inline_klass(const RegisterMap& map) {
485   BasicType bt = T_METADATA;
486   VMRegPair pair;
487   int nb = SharedRuntime::java_return_convention(&bt, &pair, 1);
488   assert(nb == 1, "broken");
489 
490   address loc = map.location(pair.first(), nullptr);
491   intptr_t ptr = *(intptr_t*)loc;
492   if (is_set_nth_bit(ptr, 0)) {
493     // Return value is tagged, must be an InlineKlass pointer
494     clear_nth_bit(ptr, 0);
495     assert(Metaspace::contains((void*)ptr), "should be klass");
496     InlineKlass* vk = (InlineKlass*)ptr;
497     assert(vk->can_be_returned_as_fields(), "must be able to return as fields");
498     return vk;
499   }
500   // Return value is not tagged, must be a valid oop
501   assert(oopDesc::is_oop_or_null(cast_to_oop(ptr), true),
502          "Bad oop return: " PTR_FORMAT, ptr);
503   return nullptr;
504 }
505 
506 // CDS support
507 
508 void InlineKlass::metaspace_pointers_do(MetaspaceClosure* it) {
509   InstanceKlass::metaspace_pointers_do(it);
510 
511   InlineKlass* this_ptr = this;
512   it->push((Klass**)adr_value_array_klasses());
513 }
514 
515 void InlineKlass::remove_unshareable_info() {
516   InstanceKlass::remove_unshareable_info();
517 
518   *((Array<SigEntry>**)adr_extended_sig()) = nullptr;
519   *((Array<VMRegPair>**)adr_return_regs()) = nullptr;
520   *((address*)adr_pack_handler()) = nullptr;
521   *((address*)adr_pack_handler_jobject()) = nullptr;
522   *((address*)adr_unpack_handler()) = nullptr;
523   assert(pack_handler() == nullptr, "pack handler not null");
524   if (value_array_klasses() != nullptr) {
525     value_array_klasses()->remove_unshareable_info();
526   }
527 }
528 
529 void InlineKlass::remove_java_mirror() {
530   InstanceKlass::remove_java_mirror();
531   if (value_array_klasses() != nullptr) {
532     value_array_klasses()->remove_java_mirror();
533   }
534 }
535 
536 void InlineKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, PackageEntry* pkg_entry, TRAPS) {
537   // We are no longer bookkeeping pointer to fixed block during serialization, hence reinitializing
538   // fixed block address since its size was already accounted by InstanceKlass::size() and it will
539   // anyways be part of shared archive.
540   _adr_inlineklass_fixed_block = inlineklass_static_block();
541   InstanceKlass::restore_unshareable_info(loader_data, protection_domain, pkg_entry, CHECK);
542   if (value_array_klasses() != nullptr) {
543     value_array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
544   }
545 }
546 
547 // oop verify
548 
549 void InlineKlass::verify_on(outputStream* st) {
550   InstanceKlass::verify_on(st);
551   guarantee(prototype_header().is_inline_type(), "Prototype header is not inline type");
552 }
553 
554 void InlineKlass::oop_verify_on(oop obj, outputStream* st) {
555   InstanceKlass::oop_verify_on(obj, st);
556   guarantee(obj->mark().is_inline_type(), "Header is not inline type");
557 }