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