1 /*
  2  * Copyright (c) 2020, 2024, 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 #ifndef SHARE_CDS_ARCHIVEBUILDER_HPP
 26 #define SHARE_CDS_ARCHIVEBUILDER_HPP
 27 
 28 #include "cds/archiveUtils.hpp"
 29 #include "cds/dumpAllocStats.hpp"
 30 #include "memory/metaspaceClosure.hpp"
 31 #include "oops/array.hpp"
 32 #include "oops/klass.hpp"
 33 #include "runtime/os.hpp"
 34 #include "utilities/bitMap.hpp"
 35 #include "utilities/growableArray.hpp"
 36 #include "utilities/resizeableResourceHash.hpp"
 37 #include "utilities/resourceHash.hpp"
 38 
 39 class ArchiveHeapInfo;
 40 class CHeapBitMap;
 41 class FileMapInfo;
 42 class Klass;
 43 class MemRegion;
 44 class Symbol;
 45 
 46 // Metaspace::allocate() requires that all blocks must be aligned with KlassAlignmentInBytes.
 47 // We enforce the same alignment rule in blocks allocated from the shared space.
 48 const int SharedSpaceObjectAlignment = KlassAlignmentInBytes;
 49 
 50 // Overview of CDS archive creation (for both static and dynamic dump):
 51 //
 52 // [1] Load all classes (static dump: from the classlist, dynamic dump: as part of app execution)
 53 // [2] Allocate "output buffer"
 54 // [3] Copy contents of the 2 "core" regions (rw/ro) into the output buffer.
 55 //       - allocate the cpp vtables in rw (static dump only)
 56 //       - memcpy the MetaspaceObjs into rw/ro:
 57 //         dump_rw_region();
 58 //         dump_ro_region();
 59 //       - fix all the pointers in the MetaspaceObjs to point to the copies
 60 //         relocate_metaspaceobj_embedded_pointers()
 61 // [4] Copy symbol table, dictionary, etc, into the ro region
 62 // [5] Relocate all the pointers in rw/ro, so that the archive can be mapped to
 63 //     the "requested" location without runtime relocation. See relocate_to_requested()
 64 //
 65 // "source" vs "buffered" vs "requested"
 66 //
 67 // The ArchiveBuilder deals with three types of addresses.
 68 //
 69 // "source":    These are the addresses of objects created in step [1] above. They are the actual
 70 //              InstanceKlass*, Method*, etc, of the Java classes that are loaded for executing
 71 //              Java bytecodes in the JVM process that's dumping the CDS archive.
 72 //
 73 //              It may be necessary to contiue Java execution after ArchiveBuilder is finished.
 74 //              Therefore, we don't modify any of the "source" objects.
 75 //
 76 // "buffered":  The "source" objects that are deemed archivable are copied into a temporary buffer.
 77 //              Objects in the buffer are modified in steps [2, 3, 4] (e.g., unshareable info is
 78 //              removed, pointers are relocated, etc) to prepare them to be loaded at runtime.
 79 //
 80 // "requested": These are the addreses where the "buffered" objects should be loaded at runtime.
 81 //              When the "buffered" objects are written into the archive file, their addresses
 82 //              are adjusted in step [5] such that the lowest of these objects would be mapped
 83 //              at SharedBaseAddress.
 84 //
 85 // Translation between "source" and "buffered" addresses is done with two hashtables:
 86 //     _src_obj_table          : "source"   -> "buffered"
 87 //     _buffered_to_src_table  : "buffered" -> "source"
 88 //
 89 // Translation between "buffered" and "requested" addresses is done with a simple shift:
 90 //    buffered_address + _buffer_to_requested_delta == requested_address
 91 //
 92 class ArchiveBuilder : public StackObj {
 93 protected:
 94   DumpRegion* _current_dump_region;
 95   address _buffer_bottom;                      // for writing the contents of rw/ro regions
 96   address _last_verified_top;
 97   int _num_dump_regions_used;
 98   size_t _other_region_used_bytes;
 99 
100   // These are the addresses where we will request the static and dynamic archives to be
101   // mapped at run time. If the request fails (due to ASLR), we will map the archives at
102   // os-selected addresses.
103   address _requested_static_archive_bottom;     // This is determined solely by the value of
104                                                 // SharedBaseAddress during -Xshare:dump.
105   address _requested_static_archive_top;
106   address _requested_dynamic_archive_bottom;    // Used only during dynamic dump. It's placed
107                                                 // immediately above _requested_static_archive_top.
108   address _requested_dynamic_archive_top;
109 
110   // (Used only during dynamic dump) where the static archive is actually mapped. This
111   // may be different than _requested_static_archive_{bottom,top} due to ASLR
112   address _mapped_static_archive_bottom;
113   address _mapped_static_archive_top;
114 
115   intx _buffer_to_requested_delta;
116 
117   DumpRegion* current_dump_region() const {  return _current_dump_region;  }
118 
119 public:
120   enum FollowMode {
121     make_a_copy, point_to_it, set_to_null
122   };
123 
124 private:
125   class SourceObjInfo {
126     uintx _ptrmap_start;     // The bit-offset of the start of this object (inclusive)
127     uintx _ptrmap_end;       // The bit-offset of the end   of this object (exclusive)
128     bool _read_only;
129     bool _has_embedded_pointer;
130     FollowMode _follow_mode;
131     int _size_in_bytes;
132     int _id; // Each object has a unique serial ID, starting from zero. The ID is assigned
133              // when the object is added into _source_objs.
134     MetaspaceObj::Type _msotype;
135     address _source_addr;    // The source object to be copied.
136     address _buffered_addr;  // The copy of this object insider the buffer.
137   public:
138     SourceObjInfo(MetaspaceClosure::Ref* ref, bool read_only, FollowMode follow_mode) :
139       _ptrmap_start(0), _ptrmap_end(0), _read_only(read_only), _has_embedded_pointer(false), _follow_mode(follow_mode),
140       _size_in_bytes(ref->size() * BytesPerWord), _id(0), _msotype(ref->msotype()),
141       _source_addr(ref->obj()) {
142       if (follow_mode == point_to_it) {
143         _buffered_addr = ref->obj();
144       } else {
145         _buffered_addr = nullptr;
146       }
147     }
148     SourceObjInfo(address src, address buf) {
149       _source_addr = src;
150       _buffered_addr = buf;
151     }
152 
153     // This constructor is only used for regenerated objects (created by LambdaFormInvokers, etc).
154     //   src = address of a Method or InstanceKlass that has been regenerated.
155     //   renegerated_obj_info = info for the regenerated version of src.
156     SourceObjInfo(address src, SourceObjInfo* renegerated_obj_info) :
157       _ptrmap_start(0), _ptrmap_end(0), _read_only(false),
158       _follow_mode(renegerated_obj_info->_follow_mode),
159       _size_in_bytes(0), _msotype(renegerated_obj_info->_msotype),
160       _source_addr(src),  _buffered_addr(renegerated_obj_info->_buffered_addr) {}
161 
162     bool should_copy() const { return _follow_mode == make_a_copy; }
163     void set_buffered_addr(address addr)  {
164       assert(should_copy(), "must be");
165       assert(_buffered_addr == nullptr, "cannot be copied twice");
166       assert(addr != nullptr, "must be a valid copy");
167       _buffered_addr = addr;
168     }
169     void set_ptrmap_start(uintx v) { _ptrmap_start = v;    }
170     void set_ptrmap_end(uintx v)   { _ptrmap_end = v;      }
171     uintx ptrmap_start()  const    { return _ptrmap_start; } // inclusive
172     uintx ptrmap_end()    const    { return _ptrmap_end;   } // exclusive
173     bool read_only()      const    { return _read_only;    }
174     bool has_embedded_pointer() const { return _has_embedded_pointer; }
175     void set_has_embedded_pointer()   { _has_embedded_pointer = true; }
176     int size_in_bytes()   const    { return _size_in_bytes; }
177     int id()              const    { return _id; }
178     void set_id(int i)             { _id = i; }
179     address source_addr() const    { return _source_addr; }
180     address buffered_addr() const  {
181       if (_follow_mode != set_to_null) {
182         assert(_buffered_addr != nullptr, "must be initialized");
183       }
184       return _buffered_addr;
185     }
186     MetaspaceObj::Type msotype() const { return _msotype; }
187   };
188 
189   class SourceObjList {
190     uintx _total_bytes;
191     GrowableArray<SourceObjInfo*>* _objs;     // Source objects to be archived
192     CHeapBitMap _ptrmap;                      // Marks the addresses of the pointer fields
193                                               // in the source objects
194   public:
195     SourceObjList();
196     ~SourceObjList();
197 
198     GrowableArray<SourceObjInfo*>* objs() const { return _objs; }
199 
200     void append(SourceObjInfo* src_info);
201     void remember_embedded_pointer(SourceObjInfo* pointing_obj, MetaspaceClosure::Ref* ref);
202     void relocate(int i, ArchiveBuilder* builder);
203 
204     // convenience accessor
205     SourceObjInfo* at(int i) const { return objs()->at(i); }
206   };
207 
208   class CDSMapLogger;
209 
210   static const int INITIAL_TABLE_SIZE = 15889;
211   static const int MAX_TABLE_SIZE     = 1000000;
212 
213   ReservedSpace _shared_rs;
214   VirtualSpace _shared_vs;
215 
216   DumpRegion _rw_region;
217   DumpRegion _ro_region;
218   DumpRegion _cc_region;
219 
220   // Combined bitmap to track pointers in both RW and RO regions. This is updated
221   // as objects are copied into RW and RO.
222   CHeapBitMap _ptrmap;
223 
224   // _ptrmap is split into these two bitmaps which are written into the archive.
225   CHeapBitMap _rw_ptrmap;   // marks pointers in the RW region
226   CHeapBitMap _ro_ptrmap;   // marks pointers in the RO region
227   CHeapBitMap _cc_ptrmap;   // marks pointers in the CC region
228 
229   SourceObjList _rw_src_objs;                 // objs to put in rw region
230   SourceObjList _ro_src_objs;                 // objs to put in ro region
231   ResizeableResourceHashtable<address, SourceObjInfo, AnyObj::C_HEAP, mtClassShared> _src_obj_table;
232   ResizeableResourceHashtable<address, address, AnyObj::C_HEAP, mtClassShared> _buffered_to_src_table;
233   GrowableArray<Klass*>* _klasses;
234   GrowableArray<Symbol*>* _symbols;
235   unsigned int _entropy_seed;
236 
237   // statistics
238   DumpAllocStats _alloc_stats;
239   size_t _total_heap_region_size;
240 
241   void print_region_stats(FileMapInfo *map_info, ArchiveHeapInfo* heap_info);
242   void print_bitmap_region_stats(size_t size, size_t total_size);
243   void print_heap_region_stats(ArchiveHeapInfo* heap_info, size_t total_size);
244 
245   // For global access.
246   static ArchiveBuilder* _current;
247 
248 public:
249   // Use this when you allocate space outside of ArchiveBuilder::dump_{rw,ro}_region.
250   // These are usually for misc tables that are allocated in the RO space.
251   class OtherROAllocMark {
252     char* _oldtop;
253   public:
254     OtherROAllocMark() {
255       _oldtop = _current->_ro_region.top();
256     }
257     ~OtherROAllocMark();
258   };
259 
260 private:
261   FollowMode get_follow_mode(MetaspaceClosure::Ref *ref);
262 
263   void iterate_sorted_roots(MetaspaceClosure* it);
264   void sort_klasses();
265   static int compare_symbols_by_address(Symbol** a, Symbol** b);
266   static int compare_klass_by_name(Klass** a, Klass** b);
267   void update_hidden_class_loader_type(InstanceKlass* ik) NOT_CDS_JAVA_HEAP_RETURN;
268 
269   void make_shallow_copies(DumpRegion *dump_region, const SourceObjList* src_objs);
270   void make_shallow_copy(DumpRegion *dump_region, SourceObjInfo* src_info);
271 
272   void relocate_embedded_pointers(SourceObjList* src_objs);
273 
274   bool is_excluded(Klass* k);
275   void clean_up_src_obj_table();
276 
277 protected:
278   virtual void iterate_roots(MetaspaceClosure* it) = 0;
279 
280   // Conservative estimate for number of bytes needed for:
281   size_t _estimated_metaspaceobj_bytes;   // all archived MetaspaceObj's.
282   size_t _estimated_hashtable_bytes;     // symbol table and dictionaries
283 
284   static const int _total_dump_regions = 2;
285 
286   size_t estimate_archive_size();
287 
288   void start_dump_region(DumpRegion* next);
289   void verify_estimate_size(size_t estimate, const char* which);
290 
291 public:
292   address reserve_buffer();
293 
294   address buffer_bottom()                    const { return _buffer_bottom;                        }
295   address buffer_top()                       const { return (address)current_dump_region()->top(); }
296   address requested_static_archive_bottom()  const { return  _requested_static_archive_bottom;     }
297   address mapped_static_archive_bottom()     const { return  _mapped_static_archive_bottom;        }
298   intx buffer_to_requested_delta()           const { return _buffer_to_requested_delta;            }
299 
300   bool is_in_buffer_space(address p) const {
301     if (current_dump_region() == nullptr) {
302       return false;
303     }
304     return (buffer_bottom() <= p && p < buffer_top());
305   }
306 
307   template <typename T> bool is_in_requested_static_archive(T p) const {
308     return _requested_static_archive_bottom <= (address)p && (address)p < _requested_static_archive_top;
309   }
310 
311   template <typename T> bool is_in_mapped_static_archive(T p) const {
312     return _mapped_static_archive_bottom <= (address)p && (address)p < _mapped_static_archive_top;
313   }
314 
315   template <typename T> bool is_in_buffer_space(T obj) const {
316     return is_in_buffer_space(address(obj));
317   }
318 
319   template <typename T> T to_requested(T obj) const {
320     assert(is_in_buffer_space(obj), "must be");
321     return (T)(address(obj) + _buffer_to_requested_delta);
322   }
323 
324   static intx get_buffer_to_requested_delta() {
325     return current()->buffer_to_requested_delta();
326   }
327 
328   inline static u4 to_offset_u4(uintx offset) {
329     guarantee(offset <= MAX_SHARED_DELTA, "must be 32-bit offset " INTPTR_FORMAT, offset);
330     return (u4)offset;
331   }
332 
333 public:
334   static const uintx MAX_SHARED_DELTA = 0x7FFFFFFF;
335 
336   // The address p points to an object inside the output buffer. When the archive is mapped
337   // at the requested address, what's the offset of this object from _requested_static_archive_bottom?
338   uintx buffer_to_offset(address p) const;
339 
340   // Same as buffer_to_offset, except that the address p points to either (a) an object
341   // inside the output buffer, or (b), an object in the currently mapped static archive.
342   uintx any_to_offset(address p) const;
343 
344   template <typename T>
345   u4 buffer_to_offset_u4(T p) const {
346     uintx offset = buffer_to_offset((address)p);
347     return to_offset_u4(offset);
348   }
349 
350   template <typename T>
351   u4 any_to_offset_u4(T p) const {
352     uintx offset = any_to_offset((address)p);
353     return to_offset_u4(offset);
354   }
355 
356 public:
357   ArchiveBuilder();
358   ~ArchiveBuilder();
359 
360   int entropy();
361   void gather_klasses_and_symbols();
362   void gather_source_objs();
363   bool gather_klass_and_symbol(MetaspaceClosure::Ref* ref, bool read_only);
364   bool gather_one_source_obj(MetaspaceClosure::Ref* ref, bool read_only);
365   void remember_embedded_pointer_in_enclosing_obj(MetaspaceClosure::Ref* ref);
366   static void serialize_dynamic_archivable_items(SerializeClosure* soc);
367 
368   DumpRegion* rw_region() { return &_rw_region; }
369   DumpRegion* ro_region() { return &_ro_region; }
370   DumpRegion* cc_region() { return &_cc_region; }
371 
372   void start_cc_region();
373   void end_cc_region();
374 
375   static char* rw_region_alloc(size_t num_bytes) {
376     return current()->rw_region()->allocate(num_bytes);
377   }
378   static char* ro_region_alloc(size_t num_bytes) {
379     return current()->ro_region()->allocate(num_bytes);
380   }
381   static char* cc_region_alloc(size_t num_bytes) {
382     return current()->cc_region()->allocate(num_bytes);
383   }
384 
385   template <typename T>
386   static Array<T>* new_ro_array(int length) {
387     size_t byte_size = Array<T>::byte_sizeof(length, sizeof(T));
388     Array<T>* array = (Array<T>*)ro_region_alloc(byte_size);
389     array->initialize(length);
390     return array;
391   }
392 
393   template <typename T>
394   static Array<T>* new_rw_array(int length) {
395     size_t byte_size = Array<T>::byte_sizeof(length, sizeof(T));
396     Array<T>* array = (Array<T>*)rw_region_alloc(byte_size);
397     array->initialize(length);
398     return array;
399   }
400 
401   template <typename T>
402   static size_t ro_array_bytesize(int length) {
403     size_t byte_size = Array<T>::byte_sizeof(length, sizeof(T));
404     return align_up(byte_size, SharedSpaceObjectAlignment);
405   }
406 
407   char* ro_strdup(const char* s);
408 
409   static int compare_src_objs(SourceObjInfo** a, SourceObjInfo** b);
410   void sort_metadata_objs();
411   void dump_rw_metadata();
412   void dump_ro_metadata();
413   void relocate_metaspaceobj_embedded_pointers();
414   void record_regenerated_object(address orig_src_obj, address regen_src_obj);
415   void make_klasses_shareable();
416   void make_training_data_shareable();
417   void relocate_to_requested();
418   void write_archive(FileMapInfo* mapinfo, ArchiveHeapInfo* heap_info);
419   void write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region,
420                     bool read_only,  bool allow_exec);
421 
422   void write_pointer_in_buffer(address* ptr_location, address src_addr);
423   template <typename T> void write_pointer_in_buffer(T* ptr_location, T src_addr) {
424     write_pointer_in_buffer((address*)ptr_location, (address)src_addr);
425   }
426 
427   void mark_and_relocate_to_buffered_addr(address* ptr_location);
428   template <typename T> void mark_and_relocate_to_buffered_addr(T ptr_location) {
429     mark_and_relocate_to_buffered_addr((address*)ptr_location);
430   }
431 
432   bool has_been_archived(address src_addr) const;
433   address get_buffered_addr(address src_addr) const;
434   template <typename T> T get_buffered_addr(T src_addr) const {
435     return (T)get_buffered_addr((address)src_addr);
436   }
437 
438   address get_source_addr(address buffered_addr) const;
439   template <typename T> T get_source_addr(T buffered_addr) const {
440     return (T)get_source_addr((address)buffered_addr);
441   }
442 
443   // All klasses and symbols that will be copied into the archive
444   GrowableArray<Klass*>*  klasses() const { return _klasses; }
445   GrowableArray<Symbol*>* symbols() const { return _symbols; }
446 
447   static bool is_active() {
448     CDS_ONLY(return (_current != nullptr));
449     NOT_CDS(return false;)
450   }
451 
452   static ArchiveBuilder* current() {
453     assert(_current != nullptr, "ArchiveBuilder must be active");
454     return _current;
455   }
456 
457   static DumpAllocStats* alloc_stats() {
458     return &(current()->_alloc_stats);
459   }
460 
461   static CompactHashtableStats* symbol_stats() {
462     return alloc_stats()->symbol_stats();
463   }
464 
465   static CompactHashtableStats* string_stats() {
466     return alloc_stats()->string_stats();
467   }
468 
469   narrowKlass get_requested_narrow_klass(Klass* k);
470 
471   static Klass* get_buffered_klass(Klass* src_klass) {
472     Klass* klass = (Klass*)current()->get_buffered_addr((address)src_klass);
473     assert(klass != nullptr && klass->is_klass(), "must be");
474     return klass;
475   }
476 
477   static Symbol* get_buffered_symbol(Symbol* src_symbol) {
478     return (Symbol*)current()->get_buffered_addr((address)src_symbol);
479   }
480 
481   void print_stats();
482   void report_out_of_space(const char* name, size_t needed_bytes);
483 };
484 
485 #endif // SHARE_CDS_ARCHIVEBUILDER_HPP