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