1 /*
  2  * Copyright (c) 2020, 2026, 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/aotGrowableArray.hpp"
 26 #include "cds/aotMetaspace.hpp"
 27 #include "cds/archiveBuilder.hpp"
 28 #include "cds/archiveUtils.hpp"
 29 #include "cds/cdsConfig.hpp"
 30 #include "cds/cppVtables.hpp"
 31 #include "logging/log.hpp"
 32 #include "memory/resourceArea.hpp"
 33 #include "oops/instanceClassLoaderKlass.hpp"
 34 #include "oops/instanceMirrorKlass.hpp"
 35 #include "oops/instanceRefKlass.hpp"
 36 #include "oops/instanceStackChunkKlass.hpp"
 37 #include "oops/methodCounters.hpp"
 38 #include "oops/methodData.hpp"
 39 #include "oops/objArrayKlass.hpp"
 40 #include "oops/trainingData.hpp"
 41 #include "oops/typeArrayKlass.hpp"
 42 #include "runtime/arguments.hpp"
 43 #include "utilities/globalDefinitions.hpp"
 44 
 45 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables.
 46 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.)
 47 //
 48 // Addresses of the vtables and the methods may be different across JVM runs,
 49 // if libjvm.so is dynamically loaded at a different base address.
 50 //
 51 // To ensure that the Metadata objects in the CDS archive always have the correct vtable:
 52 //
 53 // + at dump time:  we redirect the _vptr to point to our own vtables inside
 54 //                  the CDS image
 55 // + at run time:   we clone the actual contents of the vtables from libjvm.so
 56 //                  into our own tables.
 57 
 58 
 59 #ifndef PRODUCT
 60 
 61 // AOTGrowableArray has a vtable only when in non-product builds (due to
 62 // the virtual printing functions in AnyObj).
 63 
 64 using GrowableArray_ModuleEntry_ptr = AOTGrowableArray<ModuleEntry*>;
 65 
 66 #define DEBUG_CPP_VTABLE_TYPES_DO(f) \
 67   f(GrowableArray_ModuleEntry_ptr) \
 68 
 69 #endif
 70 
 71 // Currently, the archive contains ONLY the following types of objects that have C++ vtables.
 72 #define CPP_VTABLE_TYPES_DO(f) \
 73   f(ConstantPool) \
 74   f(InstanceKlass) \
 75   f(InstanceClassLoaderKlass) \
 76   f(InstanceMirrorKlass) \
 77   f(InstanceRefKlass) \
 78   f(InstanceStackChunkKlass) \
 79   f(Method) \
 80   f(MethodData) \
 81   f(MethodCounters) \
 82   f(ObjArrayKlass) \
 83   f(TypeArrayKlass) \
 84   f(KlassTrainingData) \
 85   f(MethodTrainingData) \
 86   f(CompileTrainingData) \
 87   NOT_PRODUCT(DEBUG_CPP_VTABLE_TYPES_DO(f))
 88 
 89 class CppVtableInfo {
 90   intptr_t _vtable_size;
 91   intptr_t _cloned_vtable[1]; // Pseudo flexible array member.
 92   static size_t cloned_vtable_offset() { return offset_of(CppVtableInfo, _cloned_vtable); }
 93 public:
 94   int vtable_size()           { return int(uintx(_vtable_size)); }
 95   void set_vtable_size(int n) { _vtable_size = intptr_t(n); }
 96   // Using _cloned_vtable[i] for i > 0 causes undefined behavior. We use address calculation instead.
 97   intptr_t* cloned_vtable()   { return (intptr_t*)((char*)this + cloned_vtable_offset()); }
 98   void zero()                 { memset(cloned_vtable(), 0, sizeof(intptr_t) * vtable_size()); }
 99   // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo
100   static size_t byte_size(int vtable_size) {
101     return cloned_vtable_offset() + (sizeof(intptr_t) * vtable_size);
102   }
103 };
104 
105 static inline intptr_t* vtable_of(const void* m) {
106   return *((intptr_t**)m);
107 }
108 
109 template <class T> class CppVtableCloner {
110   static int get_vtable_length(const char* name);
111 
112 public:
113   // Allocate a clone of the vtable of T from the shared metaspace;
114   // Initialize the contents of this clone.
115   static CppVtableInfo* allocate_and_initialize(const char* name);
116 
117   // Copy the contents of the vtable of T into info->_cloned_vtable;
118   static void initialize(const char* name, CppVtableInfo* info);
119 
120   static void init_orig_cpp_vtptr(int kind);
121 };
122 
123 template <class T>
124 CppVtableInfo* CppVtableCloner<T>::allocate_and_initialize(const char* name) {
125   int n = get_vtable_length(name);
126   CppVtableInfo* info =
127       (CppVtableInfo*)ArchiveBuilder::current()->rw_region()->allocate(CppVtableInfo::byte_size(n));
128   info->set_vtable_size(n);
129   initialize(name, info);
130   return info;
131 }
132 
133 template <class T>
134 void CppVtableCloner<T>::initialize(const char* name, CppVtableInfo* info) {
135   ResourceMark rm;
136   T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
137   int n = info->vtable_size();
138   intptr_t* srcvtable = vtable_of(&tmp);
139   intptr_t* dstvtable = info->cloned_vtable();
140 
141   // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are
142   // safe to do memcpy.
143   log_debug(aot, vtables)("Copying %3d vtable entries for %s to " INTPTR_FORMAT, n, name, p2i(dstvtable));
144   memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n);
145 }
146 
147 // To determine the size of the vtable for each type, we use the following
148 // trick by declaring 2 subclasses:
149 //
150 //   class CppVtableTesterA: public InstanceKlass {virtual int   last_virtual_method() {return 1;}    };
151 //   class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return nullptr}; };
152 //
153 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties:
154 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N)
155 // - The first N entries have are exactly the same as in InstanceKlass's vtable.
156 // - Their last entry is different.
157 //
158 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables
159 // and find the first entry that's different.
160 //
161 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more
162 // esoteric compilers.
163 
164 template <class T> class CppVtableTesterB: public T {
165 public:
166   virtual int last_virtual_method() {return 1;}
167 };
168 
169 template <class T> class CppVtableTesterA : public T {
170 public:
171   virtual void* last_virtual_method() {
172     // Make this different than CppVtableTesterB::last_virtual_method so the C++
173     // compiler/linker won't alias the two functions.
174     return nullptr;
175   }
176 };
177 
178 template <class T>
179 int CppVtableCloner<T>::get_vtable_length(const char* name) {
180   CppVtableTesterA<T> a;
181   CppVtableTesterB<T> b;
182 
183   intptr_t* avtable = vtable_of(&a);
184   intptr_t* bvtable = vtable_of(&b);
185 
186   // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc)
187   int vtable_len = 1;
188   for (; ; vtable_len++) {
189     if (avtable[vtable_len] != bvtable[vtable_len]) {
190       break;
191     }
192   }
193   log_debug(aot, vtables)("Found   %3d vtable entries for %s", vtable_len, name);
194 
195   return vtable_len;
196 }
197 
198 #define ALLOCATE_AND_INITIALIZE_VTABLE(c) \
199   _index[c##_Kind] = CppVtableCloner<c>::allocate_and_initialize(#c); \
200   ArchivePtrMarker::mark_pointer(&_index[c##_Kind]);
201 
202 #define INITIALIZE_VTABLE(c) \
203   CppVtableCloner<c>::initialize(#c, _index[c##_Kind]);
204 
205 #define INIT_ORIG_CPP_VTPTRS(c) \
206   CppVtableCloner<c>::init_orig_cpp_vtptr(c##_Kind);
207 
208 #define DECLARE_CLONED_VTABLE_KIND(c) c ## _Kind,
209 
210 enum ClonedVtableKind {
211   // E.g., ConstantPool_Kind == 0, InstanceKlass_Kind == 1, etc.
212   CPP_VTABLE_TYPES_DO(DECLARE_CLONED_VTABLE_KIND)
213   _num_cloned_vtable_kinds
214 };
215 
216 // _orig_cpp_vtptrs and _archived_cpp_vtptrs are used for type checking in
217 // CppVtables::get_archived_vtable().
218 //
219 // _orig_cpp_vtptrs is a map of all the original vtptrs. E.g., for
220 //     ConstantPool *cp = new (...) ConstantPool(...) ; // a dynamically allocated constant pool
221 // the following holds true:
222 //     _orig_cpp_vtptrs[ConstantPool_Kind] == ((intptr_t**)cp)[0]
223 //
224 // _archived_cpp_vtptrs is a map of all the vptprs used by classes in a preimage. E.g., for
225 //    InstanceKlass* k = a class loaded from the preimage;
226 //    ConstantPool* cp = k->constants();
227 // the following holds true:
228 //     _archived_cpp_vtptrs[ConstantPool_Kind] == ((intptr_t**)cp)[0]
229 static bool _orig_cpp_vtptrs_inited = false;
230 static intptr_t* _orig_cpp_vtptrs[_num_cloned_vtable_kinds];
231 static intptr_t* _archived_cpp_vtptrs[_num_cloned_vtable_kinds];
232 
233 template <class T>
234 void CppVtableCloner<T>::init_orig_cpp_vtptr(int kind) {
235   assert(kind < _num_cloned_vtable_kinds, "sanity");
236   T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
237   intptr_t* srcvtable = vtable_of(&tmp);
238   _orig_cpp_vtptrs[kind] = srcvtable;
239 }
240 
241 // This is the index of all the cloned vtables. E.g., for
242 //     ConstantPool* cp = ....; // an archived constant pool
243 //     InstanceKlass* ik = ....;// an archived class
244 // the following holds true:
245 //     _index[ConstantPool_Kind]->cloned_vtable()  == ((intptr_t**)cp)[0]
246 //     _index[InstanceKlass_Kind]->cloned_vtable() == ((intptr_t**)ik)[0]
247 static CppVtableInfo* _index[_num_cloned_vtable_kinds];
248 
249 // This marks the location in the archive where _index[0] is stored. This location
250 // will be stored as FileMapHeader::_cloned_vtables_offset into the archive header.
251 // Serviceability Agent uses this information to determine the vtables of
252 // archived Metadata objects.
253 char* CppVtables::_vtables_serialized_base = nullptr;
254 
255 void CppVtables::dumptime_init(ArchiveBuilder* builder) {
256   assert(CDSConfig::is_dumping_static_archive(), "cpp tables are only dumped into static archive");
257 
258   if (CDSConfig::is_dumping_final_static_archive()) {
259     // When dumping final archive, _index[kind] at this point is in the preimage.
260     // Remember these vtable pointers in _archived_cpp_vtptrs, as _index[kind] will now be rewritten
261     // to point to the runtime vtable data.
262     for (int i = 0; i < _num_cloned_vtable_kinds; i++) {
263       assert(_index[i] != nullptr, "must have been restored by CppVtables::serialize()");
264       _archived_cpp_vtptrs[i] = _index[i]->cloned_vtable();
265     }
266   } else {
267     memset(_archived_cpp_vtptrs, 0, sizeof(_archived_cpp_vtptrs));
268   }
269 
270   CPP_VTABLE_TYPES_DO(ALLOCATE_AND_INITIALIZE_VTABLE);
271 
272   size_t cpp_tables_size = builder->rw_region()->top() - builder->rw_region()->base();
273   builder->alloc_stats()->record_cpp_vtables((int)cpp_tables_size);
274 }
275 
276 void CppVtables::serialize(SerializeClosure* soc) {
277   if (!soc->reading()) {
278     _vtables_serialized_base = (char*)ArchiveBuilder::current()->buffer_top();
279   }
280   for (int i = 0; i < _num_cloned_vtable_kinds; i++) {
281     soc->do_ptr(&_index[i]);
282   }
283   if (soc->reading()) {
284     CPP_VTABLE_TYPES_DO(INITIALIZE_VTABLE);
285   }
286 }
287 
288 intptr_t* CppVtables::get_archived_vtable(MetaspaceClosureType type, address obj) {
289   if (!_orig_cpp_vtptrs_inited) {
290     CPP_VTABLE_TYPES_DO(INIT_ORIG_CPP_VTPTRS);
291     _orig_cpp_vtptrs_inited = true;
292   }
293 
294   assert(CDSConfig::is_dumping_archive(), "sanity");
295   int kind = -1;
296   switch (type) {
297   case MetaspaceClosureType::SymbolType:
298   case MetaspaceClosureType::TypeArrayU1Type:
299   case MetaspaceClosureType::TypeArrayU2Type:
300   case MetaspaceClosureType::TypeArrayU4Type:
301   case MetaspaceClosureType::TypeArrayU8Type:
302   case MetaspaceClosureType::TypeArrayOtherType:
303   case MetaspaceClosureType::CArrayType:
304   case MetaspaceClosureType::ConstMethodType:
305   case MetaspaceClosureType::ConstantPoolCacheType:
306   case MetaspaceClosureType::AnnotationsType:
307   case MetaspaceClosureType::ModuleEntryType:
308   case MetaspaceClosureType::PackageEntryType:
309   case MetaspaceClosureType::RecordComponentType:
310   case MetaspaceClosureType::AdapterHandlerEntryType:
311   case MetaspaceClosureType::AdapterFingerPrintType:
312   PRODUCT_ONLY(case MetaspaceClosureType::GrowableArrayType:)
313     // These have no vtables.
314     break;
315   default:
316     for (kind = 0; kind < _num_cloned_vtable_kinds; kind ++) {
317       if (vtable_of((Metadata*)obj) == _orig_cpp_vtptrs[kind] ||
318           vtable_of((Metadata*)obj) == _archived_cpp_vtptrs[kind]) {
319         break;
320       }
321     }
322     if (kind >= _num_cloned_vtable_kinds) {
323       fatal("Cannot find C++ vtable for " INTPTR_FORMAT " -- you probably added"
324             " a new subtype of Klass or MetaData without updating CPP_VTABLE_TYPES_DO or the cases in this 'switch' statement",
325             p2i(obj));
326     }
327   }
328 
329   if (kind >= 0) {
330     assert(kind < _num_cloned_vtable_kinds, "must be");
331     return _index[kind]->cloned_vtable();
332   } else {
333     return nullptr;
334   }
335 }
336 
337 void CppVtables::zero_archived_vtables() {
338   assert(CDSConfig::is_dumping_static_archive(), "cpp tables are only dumped into static archive");
339   for (int kind = 0; kind < _num_cloned_vtable_kinds; kind ++) {
340     _index[kind]->zero();
341   }
342 }
343 
344 bool CppVtables::is_valid_shared_method(const Method* m) {
345   assert(AOTMetaspace::in_aot_cache(m), "must be");
346   return vtable_of(m) == _index[Method_Kind]->cloned_vtable() ||
347          vtable_of(m) == _archived_cpp_vtptrs[Method_Kind];
348 }