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