1 /*
  2  * Copyright (c) 1999, 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 "ci/ciField.hpp"
 26 #include "ci/ciInstanceKlass.hpp"
 27 #include "ci/ciSymbols.hpp"
 28 #include "ci/ciUtilities.inline.hpp"
 29 #include "classfile/javaClasses.hpp"
 30 #include "classfile/vmClasses.hpp"
 31 #include "code/SCCache.hpp"
 32 #include "gc/shared/collectedHeap.inline.hpp"
 33 #include "interpreter/linkResolver.hpp"
 34 #include "oops/klass.inline.hpp"
 35 #include "oops/oop.inline.hpp"
 36 #include "runtime/fieldDescriptor.inline.hpp"
 37 #include "runtime/handles.inline.hpp"
 38 #include "runtime/reflection.hpp"
 39 
 40 // ciField
 41 //
 42 // This class represents the result of a field lookup in the VM.
 43 // The lookup may not succeed, in which case the information in
 44 // the ciField will be incomplete.
 45 
 46 // The ciObjectFactory cannot create circular data structures in one query.
 47 // To avoid vicious circularities, we initialize ciField::_type to null
 48 // for reference types and derive it lazily from the ciField::_signature.
 49 // Primitive types are eagerly initialized, and basic layout queries
 50 // can succeed without initialization, using only the BasicType of the field.
 51 
 52 // Notes on bootstrapping and shared CI objects:  A field is shared if and
 53 // only if it is (a) non-static and (b) declared by a shared instance klass.
 54 // This allows non-static field lists to be cached on shared types.
 55 // Because the _type field is lazily initialized, however, there is a
 56 // special restriction that a shared field cannot cache an unshared type.
 57 // This puts a small performance penalty on shared fields with unshared
 58 // types, such as StackTraceElement[] Throwable.stackTrace.
 59 // (Throwable is shared because ClassCastException is shared, but
 60 // StackTraceElement is not presently shared.)
 61 
 62 // It is not a vicious circularity for a ciField to recursively create
 63 // the ciSymbols necessary to represent its name and signature.
 64 // Therefore, these items are created eagerly, and the name and signature
 65 // of a shared field are themselves shared symbols.  This somewhat
 66 // pollutes the set of shared CI objects:  It grows from 50 to 93 items,
 67 // with all of the additional 43 being uninteresting shared ciSymbols.
 68 // This adds at most one step to the binary search, an amount which
 69 // decreases for complex compilation tasks.
 70 
 71 // ------------------------------------------------------------------
 72 // ciField::ciField
 73 ciField::ciField(ciInstanceKlass* klass, int index, Bytecodes::Code bc) :
 74     _known_to_link_with_put(nullptr), _known_to_link_with_get(nullptr) {
 75   ASSERT_IN_VM;
 76   CompilerThread *THREAD = CompilerThread::current();
 77 
 78   assert(ciObjectFactory::is_initialized(), "not a shared field");
 79 
 80   assert(klass->get_instanceKlass()->is_linked(), "must be linked before using its constant-pool");
 81 
 82   constantPoolHandle cpool(THREAD, klass->get_instanceKlass()->constants());
 83 
 84   // Get the field's name, signature, and type.
 85   Symbol* name  = cpool->name_ref_at(index, bc);
 86   _name = ciEnv::current(THREAD)->get_symbol(name);
 87 
 88   int nt_index = cpool->name_and_type_ref_index_at(index, bc);
 89   int sig_index = cpool->signature_ref_index_at(nt_index);
 90   Symbol* signature = cpool->symbol_at(sig_index);
 91   _signature = ciEnv::current(THREAD)->get_symbol(signature);
 92 
 93   BasicType field_type = Signature::basic_type(signature);
 94 
 95   // If the field is a pointer type, get the klass of the
 96   // field.
 97   if (is_reference_type(field_type)) {
 98     bool ignore;
 99     // This is not really a class reference; the index always refers to the
100     // field's type signature, as a symbol.  Linkage checks do not apply.
101     _type = ciEnv::current(THREAD)->get_klass_by_index(cpool, sig_index, ignore, klass);
102   } else {
103     _type = ciType::make(field_type);
104   }
105 
106   // Get the field's declared holder.
107   //
108   // Note: we actually create a ciInstanceKlass for this klass,
109   // even though we may not need to.
110   int holder_index = cpool->klass_ref_index_at(index, bc);
111   bool holder_is_accessible;
112 
113   ciKlass* generic_declared_holder = ciEnv::current(THREAD)->get_klass_by_index(cpool, holder_index,
114                                                                                 holder_is_accessible,
115                                                                                 klass);
116 
117   if (generic_declared_holder->is_array_klass()) {
118     // If the declared holder of the field is an array class, assume that
119     // the canonical holder of that field is java.lang.Object. Arrays
120     // do not have fields; java.lang.Object is the only supertype of an
121     // array type that can declare fields and is therefore the canonical
122     // holder of the array type.
123     //
124     // Furthermore, the compilers assume that java.lang.Object does not
125     // have any fields. Therefore, the field is not looked up. Instead,
126     // the method returns partial information that will trigger special
127     // handling in ciField::will_link and will result in a
128     // java.lang.NoSuchFieldError exception being thrown by the compiled
129     // code (the expected behavior in this case).
130     _holder = ciEnv::current(THREAD)->Object_klass();
131     _offset = -1;
132     _is_constant = false;
133     return;
134   }
135 
136   ciInstanceKlass* declared_holder = generic_declared_holder->as_instance_klass();
137 
138   // The declared holder of this field may not have been loaded.
139   // Bail out with partial field information.
140   if (!holder_is_accessible) {
141     // _type has already been set.
142     // The default values for _flags and _constant_value will suffice.
143     // We need values for _holder, _offset,  and _is_constant,
144     _holder = declared_holder;
145     _offset = -1;
146     _is_constant = false;
147     return;
148   }
149 
150   InstanceKlass* loaded_decl_holder = declared_holder->get_instanceKlass();
151 
152   // Perform the field lookup.
153   fieldDescriptor field_desc;
154   Klass* canonical_holder =
155     loaded_decl_holder->find_field(name, signature, &field_desc);
156   if (canonical_holder == nullptr) {
157     // Field lookup failed.  Will be detected by will_link.
158     _holder = declared_holder;
159     _offset = -1;
160     _is_constant = false;
161     return;
162   }
163 
164   // Access check based on declared_holder. canonical_holder should not be used
165   // to check access because it can erroneously succeed. If this check fails,
166   // propagate the declared holder to will_link() which in turn will bail out
167   // compilation for this field access.
168   bool can_access = Reflection::verify_member_access(klass->get_Klass(),
169                                                      declared_holder->get_Klass(),
170                                                      canonical_holder,
171                                                      field_desc.access_flags(),
172                                                      true, false, THREAD);
173   if (!can_access) {
174     _holder = declared_holder;
175     _offset = -1;
176     _is_constant = false;
177     // It's possible the access check failed due to a nestmate access check
178     // encountering an exception. We can't propagate the exception from here
179     // so we have to clear it. If the access check happens again in a different
180     // context then the exception will be thrown there.
181     if (HAS_PENDING_EXCEPTION) {
182       CLEAR_PENDING_EXCEPTION;
183     }
184     return;
185   }
186 
187   assert(canonical_holder == field_desc.field_holder(), "just checking");
188   initialize_from(&field_desc);
189 }
190 
191 ciField::ciField(fieldDescriptor *fd) :
192     _known_to_link_with_put(nullptr), _known_to_link_with_get(nullptr) {
193   ASSERT_IN_VM;
194 
195   // Get the field's name, signature, and type.
196   ciEnv* env = CURRENT_ENV;
197   _name = env->get_symbol(fd->name());
198   _signature = env->get_symbol(fd->signature());
199 
200   BasicType field_type = fd->field_type();
201 
202   // If the field is a pointer type, get the klass of the
203   // field.
204   if (is_reference_type(field_type)) {
205     _type = nullptr;  // must call compute_type on first access
206   } else {
207     _type = ciType::make(field_type);
208   }
209 
210   initialize_from(fd);
211 
212   // Either (a) it is marked shared, or else (b) we are done bootstrapping.
213   assert(is_shared() || ciObjectFactory::is_initialized(),
214          "bootstrap classes must not create & cache unshared fields");
215 }
216 
217 static bool trust_final_non_static_fields(ciInstanceKlass* holder) {
218   if (holder == nullptr)
219     return false;
220   if (holder->name() == ciSymbols::java_lang_System())
221     // Never trust strangely unstable finals:  System.out, etc.
222     return false;
223   // Even if general trusting is disabled, trust system-built closures in these packages.
224   if (holder->is_in_package("java/lang/invoke") || holder->is_in_package("sun/invoke") ||
225       holder->is_in_package("java/lang/reflect") || holder->is_in_package("jdk/internal/reflect") ||
226       holder->is_in_package("jdk/internal/foreign/layout") || holder->is_in_package("jdk/internal/foreign") ||
227       holder->is_in_package("jdk/internal/vm/vector") || holder->is_in_package("jdk/incubator/vector") ||
228       holder->is_in_package("java/lang"))
229     return true;
230   // Trust hidden classes. They are created via Lookup.defineHiddenClass and
231   // can't be serialized, so there is no hacking of finals going on with them.
232   if (holder->is_hidden())
233     return true;
234   // Trust final fields in all boxed classes
235   if (holder->is_box_klass())
236     return true;
237   // Trust final fields in records
238   if (holder->is_record())
239     return true;
240   // Trust final fields in String
241   if (holder->name() == ciSymbols::java_lang_String())
242     return true;
243   // Trust Atomic*FieldUpdaters: they are very important for performance, and make up one
244   // more reason not to use Unsafe, if their final fields are trusted. See more in JDK-8140483.
245   if (holder->name() == ciSymbols::java_util_concurrent_atomic_AtomicIntegerFieldUpdater_Impl() ||
246       holder->name() == ciSymbols::java_util_concurrent_atomic_AtomicLongFieldUpdater_CASUpdater() ||
247       holder->name() == ciSymbols::java_util_concurrent_atomic_AtomicLongFieldUpdater_LockedUpdater() ||
248       holder->name() == ciSymbols::java_util_concurrent_atomic_AtomicReferenceFieldUpdater_Impl()) {
249     return true;
250   }
251   return TrustFinalNonStaticFields;
252 }
253 
254 void ciField::initialize_from(fieldDescriptor* fd) {
255   // Get the flags, offset, and canonical holder of the field.
256   _flags = ciFlags(fd->access_flags(), fd->field_flags().is_stable(), fd->field_status().is_initialized_final_update());
257   _offset = fd->offset();
258   Klass* field_holder = fd->field_holder();
259   assert(field_holder != nullptr, "null field_holder");
260   _holder = CURRENT_ENV->get_instance_klass(field_holder);
261 
262   // Check to see if the field is constant.
263   Klass* k = _holder->get_Klass();
264   bool is_stable_field = FoldStableValues && is_stable();
265   if ((is_final() && !has_initialized_final_update()) || is_stable_field) {
266     if (is_static()) {
267       // This field just may be constant.  The only case where it will
268       // not be constant is when the field is a *special* static & final field
269       // whose value may change.  The three examples are java.lang.System.in,
270       // java.lang.System.out, and java.lang.System.err.
271       assert(vmClasses::System_klass() != nullptr, "Check once per vm");
272       if (k == vmClasses::System_klass()) {
273         // Check offsets for case 2: System.in, System.out, or System.err
274         if (_offset == java_lang_System::in_offset()  ||
275             _offset == java_lang_System::out_offset() ||
276             _offset == java_lang_System::err_offset()) {
277           _is_constant = false;
278           return;
279         }
280       }
281       _is_constant = true;
282     } else {
283       // An instance field can be constant if it's a final static field or if
284       // it's a final non-static field of a trusted class (classes in
285       // java.lang.invoke and sun.invoke packages and subpackages).
286       _is_constant = is_stable_field || trust_final_non_static_fields(_holder);
287     }
288   } else {
289     // For CallSite objects treat the target field as a compile time constant.
290     assert(vmClasses::CallSite_klass() != nullptr, "should be already initialized");
291     if (k == vmClasses::CallSite_klass() &&
292         _offset == java_lang_invoke_CallSite::target_offset()) {
293       assert(!has_initialized_final_update(), "CallSite is not supposed to have writes to final fields outside initializers");
294       _is_constant = true;
295     } else {
296       // Non-final & non-stable fields are not constants.
297       _is_constant = false;
298     }
299   }
300 }
301 
302 // ------------------------------------------------------------------
303 // ciField::constant_value
304 // Get the constant value of a this static field.
305 ciConstant ciField::constant_value() {
306   assert(is_static() && is_constant(), "illegal call to constant_value()");
307   if (!_holder->is_initialized()) {
308     return ciConstant(); // Not initialized yet
309   }
310   if (_constant_value.basic_type() == T_ILLEGAL) {
311     // Static fields are placed in mirror objects.
312     ciInstance* mirror = _holder->java_mirror();
313     _constant_value = mirror->field_value_impl(type()->basic_type(), offset_in_bytes());
314   }
315   if (FoldStableValues && is_stable() && _constant_value.is_null_or_zero()) {
316     return ciConstant();
317   }
318   if (!SCCache::allow_const_field(_constant_value)) {
319     return ciConstant();
320   }
321   return _constant_value;
322 }
323 
324 // ------------------------------------------------------------------
325 // ciField::constant_value_of
326 // Get the constant value of non-static final field in the given object.
327 ciConstant ciField::constant_value_of(ciObject* object) {
328   assert(!is_static() && is_constant(), "only if field is non-static constant");
329   assert(object->is_instance(), "must be instance");
330   ciConstant field_value = object->as_instance()->field_value(this);
331   if (FoldStableValues && is_stable() && field_value.is_null_or_zero()) {
332     return ciConstant();
333   }
334   if (!SCCache::allow_const_field(field_value)) {
335     return ciConstant();
336   }
337   return field_value;
338 }
339 
340 // ------------------------------------------------------------------
341 // ciField::compute_type
342 //
343 // Lazily compute the type, if it is an instance klass.
344 ciType* ciField::compute_type() {
345   GUARDED_VM_ENTRY(return compute_type_impl();)
346 }
347 
348 ciType* ciField::compute_type_impl() {
349   ciKlass* type = CURRENT_ENV->get_klass_by_name_impl(_holder, constantPoolHandle(), _signature, false);
350   if (!type->is_primitive_type() && is_shared()) {
351     // We must not cache a pointer to an unshared type, in a shared field.
352     bool type_is_also_shared = false;
353     if (type->is_type_array_klass()) {
354       type_is_also_shared = true;  // int[] etc. are explicitly bootstrapped
355     } else if (type->is_instance_klass()) {
356       type_is_also_shared = type->as_instance_klass()->is_shared();
357     } else {
358       // Currently there is no 'shared' query for array types.
359       type_is_also_shared = !ciObjectFactory::is_initialized();
360     }
361     if (!type_is_also_shared)
362       return type;              // Bummer.
363   }
364   _type = type;
365   return type;
366 }
367 
368 
369 // ------------------------------------------------------------------
370 // ciField::will_link
371 //
372 // Can a specific access to this field be made without causing
373 // link errors?
374 bool ciField::will_link(ciMethod* accessing_method,
375                         Bytecodes::Code bc) {
376   VM_ENTRY_MARK;
377   assert(bc == Bytecodes::_getstatic || bc == Bytecodes::_putstatic ||
378          bc == Bytecodes::_getfield  || bc == Bytecodes::_putfield,
379          "unexpected bytecode");
380 
381   if (_offset == -1) {
382     // at creation we couldn't link to our holder so we need to
383     // maintain that stance, otherwise there's no safe way to use this
384     // ciField.
385     return false;
386   }
387 
388   // Check for static/nonstatic mismatch
389   bool is_static = (bc == Bytecodes::_getstatic || bc == Bytecodes::_putstatic);
390   if (is_static != this->is_static()) {
391     return false;
392   }
393 
394   // Get and put can have different accessibility rules
395   bool is_put    = (bc == Bytecodes::_putfield  || bc == Bytecodes::_putstatic);
396   if (is_put) {
397     if (_known_to_link_with_put == accessing_method) {
398       return true;
399     }
400   } else {
401     if (_known_to_link_with_get == accessing_method->holder()) {
402       return true;
403     }
404   }
405 
406   LinkInfo link_info(_holder->get_instanceKlass(),
407                      _name->get_symbol(), _signature->get_symbol(),
408                      methodHandle(THREAD, accessing_method->get_Method()));
409   fieldDescriptor result;
410   LinkResolver::resolve_field(result, link_info, bc, false, CHECK_AND_CLEAR_(false));
411 
412   // update the hit-cache, unless there is a problem with memory scoping:
413   if (accessing_method->holder()->is_shared() || !is_shared()) {
414     if (is_put) {
415       _known_to_link_with_put = accessing_method;
416     } else {
417       _known_to_link_with_get = accessing_method->holder();
418     }
419   }
420 
421   return true;
422 }
423 
424 bool ciField::is_call_site_target() {
425   ciInstanceKlass* callsite_klass = CURRENT_ENV->CallSite_klass();
426   if (callsite_klass == nullptr)
427     return false;
428   return (holder()->is_subclass_of(callsite_klass) && (name() == ciSymbols::target_name()));
429 }
430 
431 bool ciField::is_autobox_cache() {
432   ciSymbol* klass_name = holder()->name();
433   return (name() == ciSymbols::cache_field_name() &&
434           holder()->uses_default_loader() &&
435           (klass_name == ciSymbols::java_lang_Character_CharacterCache() ||
436             klass_name == ciSymbols::java_lang_Byte_ByteCache() ||
437             klass_name == ciSymbols::java_lang_Short_ShortCache() ||
438             klass_name == ciSymbols::java_lang_Integer_IntegerCache() ||
439             klass_name == ciSymbols::java_lang_Long_LongCache()));
440 }
441 
442 // ------------------------------------------------------------------
443 // ciField::print
444 void ciField::print() {
445   tty->print("<ciField name=");
446   _holder->print_name();
447   tty->print(".");
448   _name->print_symbol();
449   tty->print(" signature=");
450   _signature->print_symbol();
451   tty->print(" offset=%d type=", _offset);
452   if (_type != nullptr)
453     _type->print_name();
454   else
455     tty->print("(reference)");
456   tty->print(" flags=%04x", flags().as_int());
457   tty->print(" is_constant=%s", bool_to_str(_is_constant));
458   if (_is_constant && is_static()) {
459     tty->print(" constant_value=");
460     _constant_value.print();
461   }
462   tty->print(">");
463 }
464 
465 // ------------------------------------------------------------------
466 // ciField::print_name_on
467 //
468 // Print the name of this field
469 void ciField::print_name_on(outputStream* st) {
470   name()->print_symbol_on(st);
471 }