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