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