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 CppVtableInfo** CppVtables::_index = nullptr;
225 
226 char* CppVtables::dumptime_init(ArchiveBuilder* builder) {
227   assert(CDSConfig::is_dumping_static_archive(), "cpp tables are only dumped into static archive");
228   size_t vtptrs_bytes = _num_cloned_vtable_kinds * sizeof(CppVtableInfo*);
229   _index = (CppVtableInfo**)builder->rw_region()->allocate(vtptrs_bytes);
230 
231   CPP_VTABLE_TYPES_DO(ALLOCATE_AND_INITIALIZE_VTABLE);
232 
233   if (!CDSConfig::is_dumping_final_static_archive()) {
234     for (int kind = 0; kind < _num_cloned_vtable_kinds; kind++) {
235       _archived_cpp_vtptrs[kind] = _index[kind]->cloned_vtable();
236     }
237   }
238 
239   size_t cpp_tables_size = builder->rw_region()->top() - builder->rw_region()->base();
240   builder->alloc_stats()->record_cpp_vtables((int)cpp_tables_size);
241 
242   return (char*)_index;
243 }
244 
245 void CppVtables::serialize(SerializeClosure* soc) {
246   soc->do_ptr(&_index);
247   if (soc->reading()) {
248     CPP_VTABLE_TYPES_DO(INITIALIZE_VTABLE);
249   }
250 
251   if (soc->writing() && CDSConfig::is_dumping_final_static_archive()) {
252     memset(_archived_cpp_vtptrs, 0, sizeof(_archived_cpp_vtptrs));
253   }
254 
255   for (int kind = 0; kind < _num_cloned_vtable_kinds; kind++) {
256     soc->do_ptr(&_archived_cpp_vtptrs[kind]);
257   }
258 }
259 
260 intptr_t* CppVtables::get_archived_vtable(MetaspaceObj::Type msotype, address obj) {
261   if (!_orig_cpp_vtptrs_inited) {
262     CPP_VTABLE_TYPES_DO(INIT_ORIG_CPP_VTPTRS);
263     _orig_cpp_vtptrs_inited = true;
264   }
265 
266   assert(CDSConfig::is_dumping_archive(), "sanity");
267   int kind = -1;
268   switch (msotype) {
269   case MetaspaceObj::SymbolType:
270   case MetaspaceObj::TypeArrayU1Type:
271   case MetaspaceObj::TypeArrayU2Type:
272   case MetaspaceObj::TypeArrayU4Type:
273   case MetaspaceObj::TypeArrayU8Type:
274   case MetaspaceObj::TypeArrayOtherType:
275   case MetaspaceObj::ConstMethodType:
276   case MetaspaceObj::ConstantPoolCacheType:
277   case MetaspaceObj::AnnotationsType:

278   case MetaspaceObj::SharedClassPathEntryType:
279   case MetaspaceObj::RecordComponentType:
280     // These have no vtables.
281     break;




282   default:
283     for (kind = 0; kind < _num_cloned_vtable_kinds; kind ++) {
284       if (vtable_of((Metadata*)obj) == _orig_cpp_vtptrs[kind] ||
285           vtable_of((Metadata*)obj) == _archived_cpp_vtptrs[kind]) {
286         break;
287       }
288     }
289     if (kind >= _num_cloned_vtable_kinds) {
290       fatal("Cannot find C++ vtable for " INTPTR_FORMAT " -- you probably added"
291             " a new subtype of Klass or MetaData without updating CPP_VTABLE_TYPES_DO or the cases in this 'switch' statement",
292             p2i(obj));
293     }
294   }
295 
296   if (kind >= 0) {
297     assert(kind < _num_cloned_vtable_kinds, "must be");
298     return _index[kind]->cloned_vtable();
299   } else {
300     return nullptr;
301   }
302 }
303 
304 void CppVtables::zero_archived_vtables() {
305   assert(CDSConfig::is_dumping_static_archive(), "cpp tables are only dumped into static archive");
306   for (int kind = 0; kind < _num_cloned_vtable_kinds; kind ++) {
307     _index[kind]->zero();
308   }
309 }
310 
311 bool CppVtables::is_valid_shared_method(const Method* m) {
312   assert(MetaspaceShared::is_in_shared_metaspace(m), "must be");
313   return vtable_of(m) == _index[Method_Kind]->cloned_vtable();
314 }
--- EOF ---