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