1 /*
  2  * Copyright (c) 2020, 2025, 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/metaspace.hpp"
 31 #include "memory/metaspaceClosure.hpp"
 32 #include "memory/reservedSpace.hpp"
 33 #include "memory/virtualspace.hpp"
 34 #include "oops/array.hpp"
 35 #include "oops/klass.hpp"
 36 #include "runtime/os.hpp"
 37 #include "utilities/bitMap.hpp"
 38 #include "utilities/growableArray.hpp"
 39 #include "utilities/hashTable.hpp"
 40 #include "utilities/resizableHashTable.hpp"
 41 
 42 class ArchiveMappedHeapInfo;
 43 class ArchiveStreamedHeapInfo;
 44 class CHeapBitMap;
 45 class FileMapInfo;
 46 class Klass;
 47 class MemRegion;
 48 class Symbol;
 49 
 50 // The minimum alignment for non-Klass objects inside the CDS archive. Klass objects need
 51 // to follow CompressedKlassPointers::klass_alignment_in_bytes().
 52 constexpr size_t SharedSpaceObjectAlignment = Metaspace::min_allocation_alignment_bytes;
 53 
 54 // Overview of CDS archive creation (for both static and dynamic dump):
 55 //
 56 // [1] Load all classes (static dump: from the classlist, dynamic dump: as part of app execution)
 57 // [2] Allocate "output buffer"
 58 // [3] Copy contents of the 2 "core" regions (rw/ro) into the output buffer.
 59 //       - allocate the cpp vtables in rw (static dump only)
 60 //       - memcpy the MetaspaceObjs into rw/ro:
 61 //         dump_rw_region();
 62 //         dump_ro_region();
 63 //       - fix all the pointers in the MetaspaceObjs to point to the copies
 64 //         relocate_metaspaceobj_embedded_pointers()
 65 // [4] Copy symbol table, dictionary, etc, into the ro region
 66 // [5] Relocate all the pointers in rw/ro, so that the archive can be mapped to
 67 //     the "requested" location without runtime relocation. See relocate_to_requested()
 68 //
 69 // "source" vs "buffered" vs "requested"
 70 //
 71 // The ArchiveBuilder deals with three types of addresses.
 72 //
 73 // "source":    These are the addresses of objects created in step [1] above. They are the actual
 74 //              InstanceKlass*, Method*, etc, of the Java classes that are loaded for executing
 75 //              Java bytecodes in the JVM process that's dumping the CDS archive.
 76 //
 77 //              It may be necessary to contiue Java execution after ArchiveBuilder is finished.
 78 //              Therefore, we don't modify any of the "source" objects.
 79 //
 80 // "buffered":  The "source" objects that are deemed archivable are copied into a temporary buffer.
 81 //              Objects in the buffer are modified in steps [2, 3, 4] (e.g., unshareable info is
 82 //              removed, pointers are relocated, etc) to prepare them to be loaded at runtime.
 83 //
 84 // "requested": These are the addreses where the "buffered" objects should be loaded at runtime.
 85 //              When the "buffered" objects are written into the archive file, their addresses
 86 //              are adjusted in step [5] such that the lowest of these objects would be mapped
 87 //              at SharedBaseAddress.
 88 //
 89 // Translation between "source" and "buffered" addresses is done with two hashtables:
 90 //     _src_obj_table          : "source"   -> "buffered"
 91 //     _buffered_to_src_table  : "buffered" -> "source"
 92 //
 93 // Translation between "buffered" and "requested" addresses is done with a simple shift:
 94 //    buffered_address + _buffer_to_requested_delta == requested_address
 95 //
 96 class ArchiveBuilder : public StackObj {
 97   friend class AOTMapLogger;
 98 
 99 protected:
100   DumpRegion* _current_dump_region;
101   address _buffer_bottom;                      // for writing the contents of rw/ro regions
102 
103   // These are the addresses where we will request the static and dynamic archives to be
104   // mapped at run time. If the request fails (due to ASLR), we will map the archives at
105   // os-selected addresses.
106   address _requested_static_archive_bottom;     // This is determined solely by the value of
107                                                 // SharedBaseAddress during -Xshare:dump.
108   address _requested_static_archive_top;
109   address _requested_dynamic_archive_bottom;    // Used only during dynamic dump. It's placed
110                                                 // immediately above _requested_static_archive_top.
111   address _requested_dynamic_archive_top;
112 
113   // (Used only during dynamic dump) where the static archive is actually mapped. This
114   // may be different than _requested_static_archive_{bottom,top} due to ASLR
115   address _mapped_static_archive_bottom;
116   address _mapped_static_archive_top;
117 
118   intx _buffer_to_requested_delta;
119 
120   DumpRegion* current_dump_region() const {  return _current_dump_region;  }
121 
122 public:
123   enum FollowMode {
124     make_a_copy, point_to_it, set_to_null
125   };
126 
127 private:
128   class SourceObjInfo {
129     uintx _ptrmap_start;     // The bit-offset of the start of this object (inclusive)
130     uintx _ptrmap_end;       // The bit-offset of the end   of this object (exclusive)
131     bool _read_only;
132     bool _has_embedded_pointer;
133     FollowMode _follow_mode;
134     int _size_in_bytes;
135     int _id; // Each object has a unique serial ID, starting from zero. The ID is assigned
136              // when the object is added into _source_objs.
137     MetaspaceObj::Type _msotype;
138     address _source_addr;    // The source object to be copied.
139     address _buffered_addr;  // The copy of this object insider the buffer.
140   public:
141     SourceObjInfo(MetaspaceClosure::Ref* ref, bool read_only, FollowMode follow_mode) :
142       _ptrmap_start(0), _ptrmap_end(0), _read_only(read_only), _has_embedded_pointer(false), _follow_mode(follow_mode),
143       _size_in_bytes(ref->size() * BytesPerWord), _id(0), _msotype(ref->msotype()),
144       _source_addr(ref->obj()) {
145       if (follow_mode == point_to_it) {
146         _buffered_addr = ref->obj();
147       } else {
148         _buffered_addr = nullptr;
149       }
150     }
151 
152     // This constructor is only used for regenerated objects (created by LambdaFormInvokers, etc).
153     //   src = address of a Method or InstanceKlass that has been regenerated.
154     //   renegerated_obj_info = info for the regenerated version of src.
155     SourceObjInfo(address src, SourceObjInfo* renegerated_obj_info) :
156       _ptrmap_start(0), _ptrmap_end(0), _read_only(false),
157       _follow_mode(renegerated_obj_info->_follow_mode),
158       _size_in_bytes(0), _msotype(renegerated_obj_info->_msotype),
159       _source_addr(src),  _buffered_addr(renegerated_obj_info->_buffered_addr) {}
160 
161     bool should_copy() const { return _follow_mode == make_a_copy; }
162     void set_buffered_addr(address addr)  {
163       assert(should_copy(), "must be");
164       assert(_buffered_addr == nullptr, "cannot be copied twice");
165       assert(addr != nullptr, "must be a valid copy");
166       _buffered_addr = addr;
167     }
168     void set_ptrmap_start(uintx v) { _ptrmap_start = v;    }
169     void set_ptrmap_end(uintx v)   { _ptrmap_end = v;      }
170     uintx ptrmap_start()  const    { return _ptrmap_start; } // inclusive
171     uintx ptrmap_end()    const    { return _ptrmap_end;   } // exclusive
172     bool read_only()      const    { return _read_only;    }
173     bool has_embedded_pointer() const { return _has_embedded_pointer; }
174     void set_has_embedded_pointer()   { _has_embedded_pointer = true; }
175     int size_in_bytes()   const    { return _size_in_bytes; }
176     int id()              const    { return _id; }
177     void set_id(int i)             { _id = i; }
178     address source_addr() const    { return _source_addr; }
179     address buffered_addr() const  {
180       if (_follow_mode != set_to_null) {
181         assert(_buffered_addr != nullptr, "must be initialized");
182       }
183       return _buffered_addr;
184     }
185     MetaspaceObj::Type msotype() const { return _msotype; }
186     FollowMode follow_mode() const { return _follow_mode; }
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   static const int INITIAL_TABLE_SIZE = 15889;
209   static const int MAX_TABLE_SIZE     = 1000000;
210 
211   ReservedSpace _shared_rs;
212   VirtualSpace _shared_vs;
213 
214   // The "pz" region is used only during static dumps to reserve an unused space between SharedBaseAddress and
215   // the bottom of the rw region. During runtime, this space will be filled with a reserved area that disallows
216   // read/write/exec, so we can track for bad CompressedKlassPointers encoding.
217   // Note: this region does NOT exist in the cds archive.
218   DumpRegion _pz_region;
219 
220   DumpRegion _rw_region;
221   DumpRegion _ro_region;
222   DumpRegion _ac_region; // AOT code
223 
224   // Combined bitmap to track pointers in both RW and RO regions. This is updated
225   // as objects are copied into RW and RO.
226   CHeapBitMap _ptrmap;
227 
228   // _ptrmap is split into these two bitmaps which are written into the archive.
229   CHeapBitMap _rw_ptrmap;   // marks pointers in the RW region
230   CHeapBitMap _ro_ptrmap;   // marks pointers in the RO region
231 
232   SourceObjList _rw_src_objs;                 // objs to put in rw region
233   SourceObjList _ro_src_objs;                 // objs to put in ro region
234   ResizeableHashTable<address, SourceObjInfo, AnyObj::C_HEAP, mtClassShared> _src_obj_table;
235   ResizeableHashTable<address, address, AnyObj::C_HEAP, mtClassShared> _buffered_to_src_table;
236   GrowableArray<Klass*>* _klasses;
237   GrowableArray<Symbol*>* _symbols;
238   unsigned int _entropy_seed;
239 
240   // statistics
241   DumpAllocStats _alloc_stats;
242   size_t _total_heap_region_size;
243   struct {
244     size_t _num_ptrs;
245     size_t _num_tagged_ptrs;
246     size_t _num_nulled_ptrs;
247   } _relocated_ptr_info;
248 
249   void print_region_stats(FileMapInfo *map_info,
250                           ArchiveMappedHeapInfo* mapped_heap_info,
251                           ArchiveStreamedHeapInfo* streamed_heap_info);
252   void print_bitmap_region_stats(size_t size, size_t total_size);
253   void print_heap_region_stats(char* start, size_t size, size_t total_size);
254 
255   // For global access.
256   static ArchiveBuilder* _current;
257 
258 public:
259   // Use this when you allocate space outside of ArchiveBuilder::dump_{rw,ro}_region.
260   // These are usually for misc tables that are allocated in the RO space.
261   class OtherROAllocMark {
262     char* _oldtop;
263   public:
264     OtherROAllocMark() {
265       _oldtop = _current->_ro_region.top();
266     }
267     ~OtherROAllocMark();
268   };
269 
270   void count_relocated_pointer(bool tagged, bool nulled);
271 
272 private:
273   FollowMode get_follow_mode(MetaspaceClosure::Ref *ref);
274 
275   void iterate_sorted_roots(MetaspaceClosure* it);
276   void sort_klasses();
277   static int compare_symbols_by_address(Symbol** a, Symbol** b);
278   static int compare_klass_by_name(Klass** a, Klass** b);
279 
280   void make_shallow_copies(DumpRegion *dump_region, const SourceObjList* src_objs);
281   void make_shallow_copy(DumpRegion *dump_region, SourceObjInfo* src_info);
282 
283   void relocate_embedded_pointers(SourceObjList* src_objs);
284 
285   bool is_excluded(Klass* k);
286   void clean_up_src_obj_table();
287 
288 protected:
289   virtual void iterate_roots(MetaspaceClosure* it) = 0;
290   void start_dump_region(DumpRegion* next);
291 
292 public:
293   address reserve_buffer();
294 
295   address buffer_bottom()                    const { return _buffer_bottom;                        }
296   address buffer_top()                       const { return (address)current_dump_region()->top(); }
297   address requested_static_archive_bottom()  const { return  _requested_static_archive_bottom;     }
298   address mapped_static_archive_bottom()     const { return  _mapped_static_archive_bottom;        }
299   intx buffer_to_requested_delta()           const { return _buffer_to_requested_delta;            }
300 
301   bool is_in_buffer_space(address p) const {
302     return (buffer_bottom() != nullptr && buffer_bottom() <= p && p < buffer_top());
303   }
304 
305   template <typename T> bool is_in_requested_static_archive(T p) const {
306     return _requested_static_archive_bottom <= (address)p && (address)p < _requested_static_archive_top;
307   }
308 
309   template <typename T> bool is_in_mapped_static_archive(T p) const {
310     return _mapped_static_archive_bottom <= (address)p && (address)p < _mapped_static_archive_top;
311   }
312 
313   template <typename T> bool is_in_buffer_space(T obj) const {
314     return is_in_buffer_space(address(obj));
315   }
316 
317   template <typename T> T to_requested(T obj) const {
318     assert(is_in_buffer_space(obj), "must be");
319     return (T)(address(obj) + _buffer_to_requested_delta);
320   }
321 
322   template <typename T> T requested_to_buffered(T obj) const {
323     T b = (T)(address(obj) - _buffer_to_requested_delta);
324     assert(is_in_buffer_space(b), "must be");
325     return b;
326   }
327 
328   static intx get_buffer_to_requested_delta() {
329     return current()->buffer_to_requested_delta();
330   }
331 
332   inline static u4 to_offset_u4(uintx offset) {
333     guarantee(offset <= MAX_SHARED_DELTA, "must be 32-bit offset " INTPTR_FORMAT, offset);
334     return (u4)offset;
335   }
336 
337 public:
338   static const uintx MAX_SHARED_DELTA = ArchiveUtils::MAX_SHARED_DELTA;;
339 
340   // The address p points to an object inside the output buffer. When the archive is mapped
341   // at the requested address, what's the offset of this object from _requested_static_archive_bottom?
342   uintx buffer_to_offset(address p) const;
343 
344   // Same as buffer_to_offset, except that the address p points to either (a) an object
345   // inside the output buffer, or (b), an object in the currently mapped static archive.
346   uintx any_to_offset(address p) const;
347 
348   // The reverse of buffer_to_offset()
349   address offset_to_buffered_address(u4 offset) const;
350 
351   template <typename T>
352   u4 buffer_to_offset_u4(T p) const {
353     uintx offset = buffer_to_offset((address)p);
354     return to_offset_u4(offset);
355   }
356 
357   template <typename T>
358   u4 any_to_offset_u4(T p) const {
359     assert(p != nullptr, "must not be null");
360     uintx offset = any_to_offset((address)p);
361     return to_offset_u4(offset);
362   }
363 
364   template <typename T>
365   u4 any_or_null_to_offset_u4(T p) const {
366     if (p == nullptr) {
367       return 0;
368     } else {
369       return any_to_offset_u4<T>(p);
370     }
371   }
372 
373   template <typename T>
374   T offset_to_buffered(u4 offset) const {
375     return (T)offset_to_buffered_address(offset);
376   }
377 
378 public:
379   ArchiveBuilder();
380   ~ArchiveBuilder();
381 
382   int entropy();
383   void gather_klasses_and_symbols();
384   void gather_source_objs();
385   bool gather_klass_and_symbol(MetaspaceClosure::Ref* ref, bool read_only);
386   bool gather_one_source_obj(MetaspaceClosure::Ref* ref, bool read_only);
387   void remember_embedded_pointer_in_enclosing_obj(MetaspaceClosure::Ref* ref);
388 
389   DumpRegion* pz_region() { return &_pz_region; }
390   DumpRegion* rw_region() { return &_rw_region; }
391   DumpRegion* ro_region() { return &_ro_region; }
392   DumpRegion* ac_region() { return &_ac_region; }
393 
394   static char* rw_region_alloc(size_t num_bytes) {
395     return current()->rw_region()->allocate(num_bytes);
396   }
397   static char* ro_region_alloc(size_t num_bytes) {
398     return current()->ro_region()->allocate(num_bytes);
399   }
400   static char* ac_region_alloc(size_t num_bytes) {
401     return current()->ac_region()->allocate(num_bytes);
402   }
403 
404   void start_ac_region();
405   void end_ac_region();
406 
407   template <typename T>
408   static Array<T>* new_ro_array(int length) {
409     size_t byte_size = Array<T>::byte_sizeof(length, sizeof(T));
410     Array<T>* array = (Array<T>*)ro_region_alloc(byte_size);
411     array->initialize(length);
412     return array;
413   }
414 
415   template <typename T>
416   static Array<T>* new_rw_array(int length) {
417     size_t byte_size = Array<T>::byte_sizeof(length, sizeof(T));
418     Array<T>* array = (Array<T>*)rw_region_alloc(byte_size);
419     array->initialize(length);
420     return array;
421   }
422 
423   template <typename T>
424   static size_t ro_array_bytesize(int length) {
425     size_t byte_size = Array<T>::byte_sizeof(length, sizeof(T));
426     return align_up(byte_size, SharedSpaceObjectAlignment);
427   }
428 
429   char* ro_strdup(const char* s);
430 
431   static int compare_src_objs(SourceObjInfo** a, SourceObjInfo** b);
432   void sort_metadata_objs();
433   void dump_rw_metadata();
434   void dump_ro_metadata();
435   void relocate_metaspaceobj_embedded_pointers();
436   void record_regenerated_object(address orig_src_obj, address regen_src_obj);
437   void make_klasses_shareable();
438   void make_training_data_shareable();
439   void relocate_to_requested();
440   void write_archive(FileMapInfo* mapinfo,
441                      ArchiveMappedHeapInfo* mapped_heap_info,
442                      ArchiveStreamedHeapInfo* streamed_heap_info);
443   void write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region,
444                     bool read_only,  bool allow_exec);
445 
446   void write_pointer_in_buffer(address* ptr_location, address src_addr);
447   template <typename T> void write_pointer_in_buffer(T* ptr_location, T src_addr) {
448     write_pointer_in_buffer((address*)ptr_location, (address)src_addr);
449   }
450 
451   void mark_and_relocate_to_buffered_addr(address* ptr_location);
452   template <typename T> void mark_and_relocate_to_buffered_addr(T ptr_location) {
453     mark_and_relocate_to_buffered_addr((address*)ptr_location);
454   }
455 
456   bool has_been_archived(address src_addr) const;
457   template <typename T> bool has_been_archived(T src_addr) const {
458     return has_been_archived((address)src_addr);
459   }
460 
461   address get_buffered_addr(address src_addr) const;
462   template <typename T> T get_buffered_addr(T src_addr) const {
463     CDS_ONLY(return (T)get_buffered_addr((address)src_addr);)
464     NOT_CDS(return nullptr;)
465   }
466 
467   address get_source_addr(address buffered_addr) const;
468   template <typename T> T get_source_addr(T buffered_addr) const {
469     return (T)get_source_addr((address)buffered_addr);
470   }
471 
472   // All klasses and symbols that will be copied into the archive
473   GrowableArray<Klass*>*  klasses() const { return _klasses; }
474   GrowableArray<Symbol*>* symbols() const { return _symbols; }
475 
476   static bool is_active() {
477     CDS_ONLY(return (_current != nullptr));
478     NOT_CDS(return false;)
479   }
480 
481   static ArchiveBuilder* current() {
482     assert(_current != nullptr, "ArchiveBuilder must be active");
483     return _current;
484   }
485 
486   static DumpAllocStats* alloc_stats() {
487     return &(current()->_alloc_stats);
488   }
489 
490   static CompactHashtableStats* symbol_stats() {
491     return alloc_stats()->symbol_stats();
492   }
493 
494   static CompactHashtableStats* string_stats() {
495     return alloc_stats()->string_stats();
496   }
497 
498   narrowKlass get_requested_narrow_klass(Klass* k);
499 
500   static Klass* get_buffered_klass(Klass* src_klass) {
501     Klass* klass = (Klass*)current()->get_buffered_addr((address)src_klass);
502     assert(klass != nullptr && klass->is_klass(), "must be");
503     return klass;
504   }
505 
506   static Symbol* get_buffered_symbol(Symbol* src_symbol) {
507     return (Symbol*)current()->get_buffered_addr((address)src_symbol);
508   }
509 
510   static void log_as_hex(address base, address top, address requested_base, bool is_heap = false);
511   void print_stats();
512   void report_out_of_space(const char* name, size_t needed_bytes);
513 
514 #ifdef _LP64
515   // The CDS archive contains pre-computed narrow Klass IDs. It carries them in the headers of
516   // archived heap objects. With +UseCompactObjectHeaders, it also carries them in prototypes
517   // in Klass.
518   // When generating the archive, these narrow Klass IDs are computed using the following scheme:
519   // 1) The future encoding base is assumed to point to the first address of the generated mapping.
520   //    That means that at runtime, the narrow Klass encoding must be set up with base pointing to
521   //    the start address of the mapped CDS metadata archive (wherever that may be). This precludes
522   //    zero-based encoding.
523   // 2) The shift must be large enough to result in an encoding range that covers the future assumed
524   //    runtime Klass range. That future Klass range will contain both the CDS metadata archive and
525   //    the future runtime class space. Since we do not know the size of the future class space, we
526   //    need to chose an encoding base/shift combination that will result in a "large enough" size.
527   //    The details depend on whether we use compact object headers or legacy object headers.
528   //  In Legacy Mode, a narrow Klass ID is 32 bit. This gives us an encoding range size of 4G even
529   //    with shift = 0, which is all we need. Therefore, we use a shift=0 for pre-calculating the
530   //    narrow Klass IDs.
531   // TinyClassPointer Mode:
532   //    We use the highest possible shift value to maximize the encoding range size.
533   static int precomputed_narrow_klass_shift();
534 #endif // _LP64
535 
536 };
537 
538 #endif // SHARE_CDS_ARCHIVEBUILDER_HPP