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