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