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