1 /*
  2  * Copyright (c) 1999, 2021, 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 "ci/ciField.hpp"
 27 #include "ci/ciInstance.hpp"
 28 #include "ci/ciInstanceKlass.hpp"
 29 #include "ci/ciUtilities.inline.hpp"
 30 #include "classfile/javaClasses.hpp"
 31 #include "classfile/systemDictionary.hpp"
 32 #include "classfile/vmClasses.hpp"
 33 #include "memory/allocation.hpp"
 34 #include "memory/allocation.inline.hpp"
 35 #include "memory/resourceArea.hpp"
 36 #include "oops/instanceKlass.inline.hpp"
 37 #include "oops/klass.inline.hpp"
 38 #include "oops/oop.inline.hpp"
 39 #include "oops/fieldStreams.inline.hpp"
 40 #include "runtime/fieldDescriptor.inline.hpp"
 41 #include "runtime/handles.inline.hpp"
 42 #include "runtime/jniHandles.inline.hpp"
 43 
 44 // ciInstanceKlass
 45 //
 46 // This class represents a Klass* in the HotSpot virtual machine
 47 // whose Klass part in an InstanceKlass.
 48 
 49 
 50 // ------------------------------------------------------------------
 51 // ciInstanceKlass::ciInstanceKlass
 52 //
 53 // Loaded instance klass.
 54 ciInstanceKlass::ciInstanceKlass(Klass* k) :
 55   ciKlass(k)
 56 {
 57   assert(get_Klass()->is_instance_klass(), "wrong type");
 58   assert(get_instanceKlass()->is_loaded(), "must be at least loaded");
 59   InstanceKlass* ik = get_instanceKlass();
 60 
 61   AccessFlags access_flags = ik->access_flags();
 62   _flags = ciFlags(access_flags);
 63   _has_finalizer = access_flags.has_finalizer();
 64   _has_subklass = flags().is_final() ? subklass_false : subklass_unknown;
 65   _init_state = ik->init_state();
 66   _has_nonstatic_fields = ik->has_nonstatic_fields();
 67   _has_nonstatic_concrete_methods = ik->has_nonstatic_concrete_methods();
 68   _is_hidden = ik->is_hidden();
 69   _is_record = ik->is_record();
 70   _nonstatic_fields = NULL; // initialized lazily by compute_nonstatic_fields:
 71   _has_injected_fields = -1;
 72   _implementor = NULL; // we will fill these lazily
 73 
 74   // Ensure that the metadata wrapped by the ciMetadata is kept alive by GC.
 75   // This is primarily useful for metadata which is considered as weak roots
 76   // by the GC but need to be strong roots if reachable from a current compilation.
 77   // InstanceKlass are created for both weak and strong metadata.  Ensuring this metadata
 78   // alive covers the cases where there are weak roots without performance cost.
 79   oop holder = ik->klass_holder();
 80   if (ik->class_loader_data()->has_class_mirror_holder()) {
 81     // Though ciInstanceKlass records class loader oop, it's not enough to keep
 82     // non-strong hidden classes alive (loader == NULL). Klass holder should
 83     // be used instead. It is enough to record a ciObject, since cached elements are never removed
 84     // during ciObjectFactory lifetime. ciObjectFactory itself is created for
 85     // every compilation and lives for the whole duration of the compilation.
 86     assert(holder != NULL, "holder of hidden class is the mirror which is never null");
 87     (void)CURRENT_ENV->get_object(holder);
 88   }
 89 
 90   JavaThread *thread = JavaThread::current();
 91   if (ciObjectFactory::is_initialized()) {
 92     _loader = JNIHandles::make_local(thread, ik->class_loader());
 93     _protection_domain = JNIHandles::make_local(thread,
 94                                                 ik->protection_domain());
 95     _is_shared = false;
 96   } else {
 97     Handle h_loader(thread, ik->class_loader());
 98     Handle h_protection_domain(thread, ik->protection_domain());
 99     _loader = JNIHandles::make_global(h_loader);
100     _protection_domain = JNIHandles::make_global(h_protection_domain);
101     _is_shared = true;
102   }
103 
104   // Lazy fields get filled in only upon request.
105   _super  = NULL;
106   _java_mirror = NULL;
107 
108   if (is_shared()) {
109     if (k != vmClasses::Object_klass()) {
110       super();
111     }
112     //compute_nonstatic_fields();  // done outside of constructor
113   }
114 
115   _field_cache = NULL;
116 }
117 
118 // Version for unloaded classes:
119 ciInstanceKlass::ciInstanceKlass(ciSymbol* name,
120                                  jobject loader, jobject protection_domain)
121   : ciKlass(name, T_OBJECT)
122 {
123   assert(name->char_at(0) != JVM_SIGNATURE_ARRAY, "not an instance klass");
124   _init_state = (InstanceKlass::ClassState)0;
125   _has_nonstatic_fields = false;
126   _nonstatic_fields = NULL;
127   _has_injected_fields = -1;
128   _is_hidden = false;
129   _is_record = false;
130   _loader = loader;
131   _protection_domain = protection_domain;
132   _is_shared = false;
133   _super = NULL;
134   _java_mirror = NULL;
135   _field_cache = NULL;
136 }
137 
138 
139 
140 // ------------------------------------------------------------------
141 // ciInstanceKlass::compute_shared_is_initialized
142 void ciInstanceKlass::compute_shared_init_state() {
143   GUARDED_VM_ENTRY(
144     InstanceKlass* ik = get_instanceKlass();
145     _init_state = ik->init_state();
146   )
147 }
148 
149 // ------------------------------------------------------------------
150 // ciInstanceKlass::compute_shared_has_subklass
151 bool ciInstanceKlass::compute_shared_has_subklass() {
152   GUARDED_VM_ENTRY(
153     InstanceKlass* ik = get_instanceKlass();
154     _has_subklass = ik->subklass() != NULL ? subklass_true : subklass_false;
155     return _has_subklass == subklass_true;
156   )
157 }
158 
159 // ------------------------------------------------------------------
160 // ciInstanceKlass::loader
161 oop ciInstanceKlass::loader() {
162   ASSERT_IN_VM;
163   return JNIHandles::resolve(_loader);
164 }
165 
166 // ------------------------------------------------------------------
167 // ciInstanceKlass::loader_handle
168 jobject ciInstanceKlass::loader_handle() {
169   return _loader;
170 }
171 
172 // ------------------------------------------------------------------
173 // ciInstanceKlass::protection_domain
174 oop ciInstanceKlass::protection_domain() {
175   ASSERT_IN_VM;
176   return JNIHandles::resolve(_protection_domain);
177 }
178 
179 // ------------------------------------------------------------------
180 // ciInstanceKlass::protection_domain_handle
181 jobject ciInstanceKlass::protection_domain_handle() {
182   return _protection_domain;
183 }
184 
185 // ------------------------------------------------------------------
186 // ciInstanceKlass::field_cache
187 //
188 // Get the field cache associated with this klass.
189 ciConstantPoolCache* ciInstanceKlass::field_cache() {
190   if (is_shared()) {
191     return NULL;
192   }
193   if (_field_cache == NULL) {
194     assert(!is_java_lang_Object(), "Object has no fields");
195     Arena* arena = CURRENT_ENV->arena();
196     _field_cache = new (arena) ciConstantPoolCache(arena, 5);
197   }
198   return _field_cache;
199 }
200 
201 // ------------------------------------------------------------------
202 // ciInstanceKlass::get_canonical_holder
203 //
204 ciInstanceKlass* ciInstanceKlass::get_canonical_holder(int offset) {
205   #ifdef ASSERT
206   if (!(offset >= 0 && offset < layout_helper_size_in_bytes())) {
207     tty->print("*** get_canonical_holder(%d) on ", offset);
208     this->print();
209     tty->print_cr(" ***");
210   };
211   assert(offset >= 0 && offset < layout_helper_size_in_bytes(), "offset must be tame");
212   #endif
213 
214   if (offset < instanceOopDesc::base_offset_in_bytes()) {
215     // All header offsets belong properly to java/lang/Object.
216     return CURRENT_ENV->Object_klass();
217   }
218 
219   ciInstanceKlass* self = this;
220   assert(self->is_loaded(), "must be loaded to access field info");
221   ciField* field = self->get_field_by_offset(offset, false);
222   if (field != NULL) {
223     return field->holder();
224   } else {
225     for (;;) {
226       assert(self->is_loaded(), "must be loaded to have size");
227       ciInstanceKlass* super = self->super();
228       if (super == NULL ||
229           super->nof_nonstatic_fields() == 0 ||
230           super->layout_helper_size_in_bytes() <= offset) {
231         return self;
232       } else {
233         self = super;  // return super->get_canonical_holder(offset)
234       }
235     }
236   }
237 }
238 
239 // ------------------------------------------------------------------
240 // ciInstanceKlass::is_java_lang_Object
241 //
242 // Is this klass java.lang.Object?
243 bool ciInstanceKlass::is_java_lang_Object() const {
244   return equals(CURRENT_ENV->Object_klass());
245 }
246 
247 // ------------------------------------------------------------------
248 // ciInstanceKlass::uses_default_loader
249 bool ciInstanceKlass::uses_default_loader() const {
250   // Note:  We do not need to resolve the handle or enter the VM
251   // in order to test null-ness.
252   return _loader == NULL;
253 }
254 
255 // ------------------------------------------------------------------
256 
257 /**
258  * Return basic type of boxed value for box klass or T_OBJECT if not.
259  */
260 BasicType ciInstanceKlass::box_klass_type() const {
261   if (uses_default_loader() && is_loaded()) {
262     return vmClasses::box_klass_type(get_Klass());
263   } else {
264     return T_OBJECT;
265   }
266 }
267 
268 /**
269  * Is this boxing klass?
270  */
271 bool ciInstanceKlass::is_box_klass() const {
272   return is_java_primitive(box_klass_type());
273 }
274 
275 /**
276  *  Is this boxed value offset?
277  */
278 bool ciInstanceKlass::is_boxed_value_offset(int offset) const {
279   BasicType bt = box_klass_type();
280   return is_java_primitive(bt) &&
281          (offset == java_lang_boxing_object::value_offset(bt));
282 }
283 
284 static bool is_klass_initialized(Symbol* klass_name) {
285   VM_ENTRY_MARK;
286   InstanceKlass* ik = SystemDictionary::find_instance_klass(klass_name, Handle(), Handle());
287   return ik != nullptr && ik->is_initialized();
288 }
289 
290 bool ciInstanceKlass::is_box_cache_valid() const {
291   BasicType box_type = box_klass_type();
292 
293   if (box_type != T_OBJECT) {
294     switch(box_type) {
295       case T_INT:     return is_klass_initialized(java_lang_Integer_IntegerCache::symbol());
296       case T_CHAR:    return is_klass_initialized(java_lang_Character_CharacterCache::symbol());
297       case T_SHORT:   return is_klass_initialized(java_lang_Short_ShortCache::symbol());
298       case T_BYTE:    return is_klass_initialized(java_lang_Byte_ByteCache::symbol());
299       case T_LONG:    return is_klass_initialized(java_lang_Long_LongCache::symbol());
300       case T_BOOLEAN:
301       case T_FLOAT:
302       case T_DOUBLE:  return true;
303       default:;
304     }
305   }
306   return false;
307 }
308 
309 // ------------------------------------------------------------------
310 // ciInstanceKlass::is_in_package
311 //
312 // Is this klass in the given package?
313 bool ciInstanceKlass::is_in_package(const char* packagename, int len) {
314   // To avoid class loader mischief, this test always rejects application classes.
315   if (!uses_default_loader())
316     return false;
317   GUARDED_VM_ENTRY(
318     return is_in_package_impl(packagename, len);
319   )
320 }
321 
322 bool ciInstanceKlass::is_in_package_impl(const char* packagename, int len) {
323   ASSERT_IN_VM;
324 
325   // If packagename contains trailing '/' exclude it from the
326   // prefix-test since we test for it explicitly.
327   if (packagename[len - 1] == '/')
328     len--;
329 
330   if (!name()->starts_with(packagename, len))
331     return false;
332 
333   // Test if the class name is something like "java/lang".
334   if ((len + 1) > name()->utf8_length())
335     return false;
336 
337   // Test for trailing '/'
338   if (name()->char_at(len) != '/')
339     return false;
340 
341   // Make sure it's not actually in a subpackage:
342   if (name()->index_of_at(len+1, "/", 1) >= 0)
343     return false;
344 
345   return true;
346 }
347 
348 // ------------------------------------------------------------------
349 // ciInstanceKlass::print_impl
350 //
351 // Implementation of the print method.
352 void ciInstanceKlass::print_impl(outputStream* st) {
353   ciKlass::print_impl(st);
354   GUARDED_VM_ENTRY(st->print(" loader=" INTPTR_FORMAT, p2i(loader()));)
355   if (is_loaded()) {
356     st->print(" loaded=true initialized=%s finalized=%s subklass=%s size=%d flags=",
357               bool_to_str(is_initialized()),
358               bool_to_str(has_finalizer()),
359               bool_to_str(has_subklass()),
360               layout_helper());
361 
362     _flags.print_klass_flags();
363 
364     if (_super) {
365       st->print(" super=");
366       _super->print_name();
367     }
368     if (_java_mirror) {
369       st->print(" mirror=PRESENT");
370     }
371   } else {
372     st->print(" loaded=false");
373   }
374 }
375 
376 // ------------------------------------------------------------------
377 // ciInstanceKlass::super
378 //
379 // Get the superklass of this klass.
380 ciInstanceKlass* ciInstanceKlass::super() {
381   assert(is_loaded(), "must be loaded");
382   if (_super == NULL && !is_java_lang_Object()) {
383     GUARDED_VM_ENTRY(
384       Klass* super_klass = get_instanceKlass()->super();
385       _super = CURRENT_ENV->get_instance_klass(super_klass);
386     )
387   }
388   return _super;
389 }
390 
391 // ------------------------------------------------------------------
392 // ciInstanceKlass::java_mirror
393 //
394 // Get the instance of java.lang.Class corresponding to this klass.
395 // Cache it on this->_java_mirror.
396 ciInstance* ciInstanceKlass::java_mirror() {
397   if (is_shared()) {
398     return ciKlass::java_mirror();
399   }
400   if (_java_mirror == NULL) {
401     _java_mirror = ciKlass::java_mirror();
402   }
403   return _java_mirror;
404 }
405 
406 // ------------------------------------------------------------------
407 // ciInstanceKlass::unique_concrete_subklass
408 ciInstanceKlass* ciInstanceKlass::unique_concrete_subklass() {
409   if (!is_loaded())     return NULL; // No change if class is not loaded
410   if (!is_abstract())   return NULL; // Only applies to abstract classes.
411   if (!has_subklass())  return NULL; // Must have at least one subklass.
412   VM_ENTRY_MARK;
413   InstanceKlass* ik = get_instanceKlass();
414   Klass* up = ik->up_cast_abstract();
415   assert(up->is_instance_klass(), "must be InstanceKlass");
416   if (ik == up) {
417     return NULL;
418   }
419   return CURRENT_THREAD_ENV->get_instance_klass(up);
420 }
421 
422 // ------------------------------------------------------------------
423 // ciInstanceKlass::has_finalizable_subclass
424 bool ciInstanceKlass::has_finalizable_subclass() {
425   if (!is_loaded())     return true;
426   VM_ENTRY_MARK;
427   return Dependencies::find_finalizable_subclass(get_instanceKlass()) != NULL;
428 }
429 
430 // ------------------------------------------------------------------
431 // ciInstanceKlass::contains_field_offset
432 bool ciInstanceKlass::contains_field_offset(int offset) {
433   VM_ENTRY_MARK;
434   return get_instanceKlass()->contains_field_offset(offset);
435 }
436 
437 // ------------------------------------------------------------------
438 // ciInstanceKlass::get_field_by_offset
439 ciField* ciInstanceKlass::get_field_by_offset(int field_offset, bool is_static) {
440   if (!is_static) {
441     for (int i = 0, len = nof_nonstatic_fields(); i < len; i++) {
442       ciField* field = _nonstatic_fields->at(i);
443       int  field_off = field->offset_in_bytes();
444       if (field_off == field_offset)
445         return field;
446       if (field_off > field_offset)
447         break;
448       // could do binary search or check bins, but probably not worth it
449     }
450     return NULL;
451   }
452   VM_ENTRY_MARK;
453   InstanceKlass* k = get_instanceKlass();
454   fieldDescriptor fd;
455   if (!k->find_field_from_offset(field_offset, is_static, &fd)) {
456     return NULL;
457   }
458   ciField* field = new (CURRENT_THREAD_ENV->arena()) ciField(&fd);
459   return field;
460 }
461 
462 // ------------------------------------------------------------------
463 // ciInstanceKlass::get_field_by_name
464 ciField* ciInstanceKlass::get_field_by_name(ciSymbol* name, ciSymbol* signature, bool is_static) {
465   VM_ENTRY_MARK;
466   InstanceKlass* k = get_instanceKlass();
467   fieldDescriptor fd;
468   Klass* def = k->find_field(name->get_symbol(), signature->get_symbol(), is_static, &fd);
469   if (def == NULL) {
470     return NULL;
471   }
472   ciField* field = new (CURRENT_THREAD_ENV->arena()) ciField(&fd);
473   return field;
474 }
475 
476 
477 static int sort_field_by_offset(ciField** a, ciField** b) {
478   return (*a)->offset_in_bytes() - (*b)->offset_in_bytes();
479   // (no worries about 32-bit overflow...)
480 }
481 
482 // ------------------------------------------------------------------
483 // ciInstanceKlass::compute_nonstatic_fields
484 int ciInstanceKlass::compute_nonstatic_fields() {
485   assert(is_loaded(), "must be loaded");
486 
487   if (_nonstatic_fields != NULL)
488     return _nonstatic_fields->length();
489 
490   if (!has_nonstatic_fields()) {
491     Arena* arena = CURRENT_ENV->arena();
492     _nonstatic_fields = new (arena) GrowableArray<ciField*>(arena, 0, 0, NULL);
493     return 0;
494   }
495   assert(!is_java_lang_Object(), "bootstrap OK");
496 
497   ciInstanceKlass* super = this->super();
498   GrowableArray<ciField*>* super_fields = NULL;
499   if (super != NULL && super->has_nonstatic_fields()) {
500     int super_flen   = super->nof_nonstatic_fields();
501     super_fields = super->_nonstatic_fields;
502     assert(super_flen == 0 || super_fields != NULL, "first get nof_fields");
503   }
504 
505   GrowableArray<ciField*>* fields = NULL;
506   GUARDED_VM_ENTRY({
507       fields = compute_nonstatic_fields_impl(super_fields);
508     });
509 
510   if (fields == NULL) {
511     // This can happen if this class (java.lang.Class) has invisible fields.
512     if (super_fields != NULL) {
513       _nonstatic_fields = super_fields;
514       return super_fields->length();
515     } else {
516       return 0;
517     }
518   }
519 
520   int flen = fields->length();
521 
522   // Now sort them by offset, ascending.
523   // (In principle, they could mix with superclass fields.)
524   fields->sort(sort_field_by_offset);
525   _nonstatic_fields = fields;
526   return flen;
527 }
528 
529 GrowableArray<ciField*>*
530 ciInstanceKlass::compute_nonstatic_fields_impl(GrowableArray<ciField*>*
531                                                super_fields) {
532   ASSERT_IN_VM;
533   Arena* arena = CURRENT_ENV->arena();
534   int flen = 0;
535   GrowableArray<ciField*>* fields = NULL;
536   InstanceKlass* k = get_instanceKlass();
537   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
538     if (fs.access_flags().is_static())  continue;
539     flen += 1;
540   }
541 
542   // allocate the array:
543   if (flen == 0) {
544     return NULL;  // return nothing if none are locally declared
545   }
546   if (super_fields != NULL) {
547     flen += super_fields->length();
548   }
549   fields = new (arena) GrowableArray<ciField*>(arena, flen, 0, NULL);
550   if (super_fields != NULL) {
551     fields->appendAll(super_fields);
552   }
553 
554   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
555     if (fs.access_flags().is_static())  continue;
556     fieldDescriptor& fd = fs.field_descriptor();
557     ciField* field = new (arena) ciField(&fd);
558     fields->append(field);
559   }
560   assert(fields->length() == flen, "sanity");
561   return fields;
562 }
563 
564 bool ciInstanceKlass::compute_injected_fields_helper() {
565   ASSERT_IN_VM;
566   InstanceKlass* k = get_instanceKlass();
567 
568   for (InternalFieldStream fs(k); !fs.done(); fs.next()) {
569     if (fs.access_flags().is_static())  continue;
570     return true;
571   }
572   return false;
573 }
574 
575 void ciInstanceKlass::compute_injected_fields() {
576   assert(is_loaded(), "must be loaded");
577 
578   int has_injected_fields = 0;
579   if (super() != NULL && super()->has_injected_fields()) {
580     has_injected_fields = 1;
581   } else {
582     GUARDED_VM_ENTRY({
583         has_injected_fields = compute_injected_fields_helper() ? 1 : 0;
584       });
585   }
586   // may be concurrently initialized for shared ciInstanceKlass objects
587   assert(_has_injected_fields == -1 || _has_injected_fields == has_injected_fields, "broken concurrent initialization");
588   _has_injected_fields = has_injected_fields;
589 }
590 
591 bool ciInstanceKlass::has_object_fields() const {
592   GUARDED_VM_ENTRY(
593       return get_instanceKlass()->nonstatic_oop_map_size() > 0;
594     );
595 }
596 
597 // ------------------------------------------------------------------
598 // ciInstanceKlass::find_method
599 //
600 // Find a method in this klass.
601 ciMethod* ciInstanceKlass::find_method(ciSymbol* name, ciSymbol* signature) {
602   VM_ENTRY_MARK;
603   InstanceKlass* k = get_instanceKlass();
604   Symbol* name_sym = name->get_symbol();
605   Symbol* sig_sym= signature->get_symbol();
606 
607   Method* m = k->find_method(name_sym, sig_sym);
608   if (m == NULL)  return NULL;
609 
610   return CURRENT_THREAD_ENV->get_method(m);
611 }
612 
613 // ------------------------------------------------------------------
614 // ciInstanceKlass::is_leaf_type
615 bool ciInstanceKlass::is_leaf_type() {
616   assert(is_loaded(), "must be loaded");
617   if (is_shared()) {
618     return is_final();  // approximately correct
619   } else {
620     return !has_subklass() && (nof_implementors() == 0);
621   }
622 }
623 
624 // ------------------------------------------------------------------
625 // ciInstanceKlass::implementor
626 //
627 // Report an implementor of this interface.
628 // Note that there are various races here, since my copy
629 // of _nof_implementors might be out of date with respect
630 // to results returned by InstanceKlass::implementor.
631 // This is OK, since any dependencies we decide to assert
632 // will be checked later under the Compile_lock.
633 ciInstanceKlass* ciInstanceKlass::implementor() {
634   ciInstanceKlass* impl = _implementor;
635   if (impl == NULL) {
636     // Go into the VM to fetch the implementor.
637     {
638       VM_ENTRY_MARK;
639       MutexLocker ml(Compile_lock);
640       Klass* k = get_instanceKlass()->implementor();
641       if (k != NULL) {
642         if (k == get_instanceKlass()) {
643           // More than one implementors. Use 'this' in this case.
644           impl = this;
645         } else {
646           impl = CURRENT_THREAD_ENV->get_instance_klass(k);
647         }
648       }
649     }
650     // Memoize this result.
651     if (!is_shared()) {
652       _implementor = impl;
653     }
654   }
655   return impl;
656 }
657 
658 // Utility class for printing of the contents of the static fields for
659 // use by compilation replay.  It only prints out the information that
660 // could be consumed by the compiler, so for primitive types it prints
661 // out the actual value.  For Strings it's the actual string value.
662 // For array types it it's first level array size since that's the
663 // only value which statically unchangeable.  For all other reference
664 // types it simply prints out the dynamic type.
665 
666 class StaticFinalFieldPrinter : public FieldClosure {
667   outputStream* _out;
668   const char*   _holder;
669  public:
670   StaticFinalFieldPrinter(outputStream* out, const char* holder) :
671     _out(out),
672     _holder(holder) {
673   }
674   void do_field(fieldDescriptor* fd) {
675     if (fd->is_final() && !fd->has_initial_value()) {
676       ResourceMark rm;
677       oop mirror = fd->field_holder()->java_mirror();
678       _out->print("staticfield %s %s %s ", _holder, fd->name()->as_quoted_ascii(), fd->signature()->as_quoted_ascii());
679       switch (fd->field_type()) {
680         case T_BYTE:    _out->print_cr("%d", mirror->byte_field(fd->offset()));   break;
681         case T_BOOLEAN: _out->print_cr("%d", mirror->bool_field(fd->offset()));   break;
682         case T_SHORT:   _out->print_cr("%d", mirror->short_field(fd->offset()));  break;
683         case T_CHAR:    _out->print_cr("%d", mirror->char_field(fd->offset()));   break;
684         case T_INT:     _out->print_cr("%d", mirror->int_field(fd->offset()));    break;
685         case T_LONG:    _out->print_cr(INT64_FORMAT, (int64_t)(mirror->long_field(fd->offset())));   break;
686         case T_FLOAT: {
687           float f = mirror->float_field(fd->offset());
688           _out->print_cr("%d", *(int*)&f);
689           break;
690         }
691         case T_DOUBLE: {
692           double d = mirror->double_field(fd->offset());
693           _out->print_cr(INT64_FORMAT, *(int64_t*)&d);
694           break;
695         }
696         case T_ARRAY:  // fall-through
697         case T_OBJECT: {
698           oop value =  mirror->obj_field_acquire(fd->offset());
699           if (value == NULL) {
700             _out->print_cr("null");
701           } else if (value->is_instance()) {
702             assert(fd->field_type() == T_OBJECT, "");
703             if (value->is_a(vmClasses::String_klass())) {
704               const char* ascii_value = java_lang_String::as_quoted_ascii(value);
705               _out->print_cr("\"%s\"", (ascii_value != NULL) ? ascii_value : "");
706             } else {
707               const char* klass_name  = value->klass()->name()->as_quoted_ascii();
708               _out->print_cr("%s", klass_name);
709             }
710           } else if (value->is_array()) {
711             typeArrayOop ta = (typeArrayOop)value;
712             _out->print("%d", ta->length());
713             if (value->is_objArray()) {
714               objArrayOop oa = (objArrayOop)value;
715               const char* klass_name  = value->klass()->name()->as_quoted_ascii();
716               _out->print(" %s", klass_name);
717             }
718             _out->cr();
719           } else {
720             ShouldNotReachHere();
721           }
722           break;
723         }
724         default:
725           ShouldNotReachHere();
726         }
727     }
728   }
729 };
730 
731 const char *ciInstanceKlass::replay_name() const {
732   return CURRENT_ENV->replay_name(get_instanceKlass());
733 }
734 
735 void ciInstanceKlass::dump_replay_instanceKlass(outputStream* out, InstanceKlass* ik) {
736   if (ik->is_hidden()) {
737     const char *name = CURRENT_ENV->dyno_name(ik);
738     if (name != NULL) {
739       out->print_cr("instanceKlass %s # %s", name, ik->name()->as_quoted_ascii());
740     } else {
741       out->print_cr("# instanceKlass %s", ik->name()->as_quoted_ascii());
742     }
743   } else {
744     out->print_cr("instanceKlass %s", ik->name()->as_quoted_ascii());
745   }
746 }
747 
748 void ciInstanceKlass::dump_replay_data(outputStream* out) {
749   ResourceMark rm;
750 
751   InstanceKlass* ik = get_instanceKlass();
752   ConstantPool*  cp = ik->constants();
753 
754   // Try to record related loaded classes
755   Klass* sub = ik->subklass();
756   while (sub != NULL) {
757     if (sub->is_instance_klass()) {
758       InstanceKlass *isub = InstanceKlass::cast(sub);
759       dump_replay_instanceKlass(out, isub);
760     }
761     sub = sub->next_sibling();
762   }
763 
764   // Dump out the state of the constant pool tags.  During replay the
765   // tags will be validated for things which shouldn't change and
766   // classes will be resolved if the tags indicate that they were
767   // resolved at compile time.
768   const char *name = replay_name();
769   out->print("ciInstanceKlass %s %d %d %d", name,
770              is_linked(), is_initialized(), cp->length());
771   for (int index = 1; index < cp->length(); index++) {
772     out->print(" %d", cp->tags()->at(index));
773   }
774   out->cr();
775   if (is_initialized()) {
776     //  Dump out the static final fields in case the compilation relies
777     //  on their value for correct replay.
778     StaticFinalFieldPrinter sffp(out, name);
779     ik->do_local_static_fields(&sffp);
780   }
781 }
782 
783 #ifdef ASSERT
784 bool ciInstanceKlass::debug_final_field_at(int offset) {
785   GUARDED_VM_ENTRY(
786     InstanceKlass* ik = get_instanceKlass();
787     fieldDescriptor fd;
788     if (ik->find_field_from_offset(offset, false, &fd)) {
789       return fd.is_final();
790     }
791   );
792   return false;
793 }
794 
795 bool ciInstanceKlass::debug_stable_field_at(int offset) {
796   GUARDED_VM_ENTRY(
797     InstanceKlass* ik = get_instanceKlass();
798     fieldDescriptor fd;
799     if (ik->find_field_from_offset(offset, false, &fd)) {
800       return fd.is_stable();
801     }
802   );
803   return false;
804 }
805 #endif