1 /*
  2  * Copyright (c) 2003, 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_FILEMAP_HPP
 26 #define SHARE_CDS_FILEMAP_HPP
 27 
 28 #include "cds/archiveUtils.hpp"
 29 #include "cds/metaspaceShared.hpp"
 30 #include "include/cds.h"
 31 #include "logging/logLevel.hpp"
 32 #include "memory/allocation.hpp"
 33 #include "oops/array.hpp"
 34 #include "oops/compressedOops.hpp"
 35 #include "utilities/align.hpp"
 36 
 37 // To understand the layout of the CDS archive file:
 38 //
 39 // java -Xlog:cds+map=info:file=cds.map:none:filesize=0
 40 // java -Xlog:cds+map=debug:file=cds.map:none:filesize=0
 41 // java -Xlog:cds+map=trace:file=cds.map:none:filesize=0
 42 
 43 static const int JVM_IDENT_MAX = 256;
 44 
 45 class AOTClassLocationConfig;
 46 class ArchiveHeapInfo;
 47 class BitMapView;
 48 class CHeapBitMap;
 49 class ClassFileStream;
 50 class ClassLoaderData;
 51 class ClassPathEntry;
 52 class outputStream;
 53 class ReservedSpace;
 54 
 55 class FileMapRegion: private CDSFileMapRegion {
 56 public:
 57   void assert_is_heap_region() const {
 58     assert(_is_heap_region, "must be heap region");
 59   }
 60   void assert_is_not_heap_region() const {
 61     assert(!_is_heap_region, "must not be heap region");
 62   }
 63 
 64   static FileMapRegion* cast(CDSFileMapRegion* p) {
 65     return (FileMapRegion*)p;
 66   }
 67 
 68   // Accessors
 69   int crc()                         const { return _crc; }
 70   size_t file_offset()              const { return _file_offset; }
 71   size_t mapping_offset()           const { return _mapping_offset; }
 72   size_t mapping_end_offset()       const { return _mapping_offset + used_aligned(); }
 73   size_t used()                     const { return _used; }
 74   size_t used_aligned()             const; // aligned up to MetaspaceShared::core_region_alignment()
 75   char*  mapped_base()              const { return _mapped_base; }
 76   char*  mapped_end()               const { return mapped_base()        + used_aligned(); }
 77   bool   read_only()                const { return _read_only != 0; }
 78   bool   allow_exec()               const { return _allow_exec != 0; }
 79   bool   mapped_from_file()         const { return _mapped_from_file != 0; }
 80   size_t oopmap_offset()            const { assert_is_heap_region();     return _oopmap_offset; }
 81   size_t oopmap_size_in_bits()      const { assert_is_heap_region();     return _oopmap_size_in_bits; }
 82   size_t ptrmap_offset()            const { return _ptrmap_offset; }
 83   size_t ptrmap_size_in_bits()      const { return _ptrmap_size_in_bits; }
 84   bool   in_reserved_space()        const { return _in_reserved_space; }
 85 
 86   void set_file_offset(size_t s)     { _file_offset = s; }
 87   void set_read_only(bool v)         { _read_only = v; }
 88   void set_mapped_base(char* p)      { _mapped_base = p; }
 89   void set_mapped_from_file(bool v)  { _mapped_from_file = v; }
 90   void set_in_reserved_space(bool is_reserved) { _in_reserved_space = is_reserved; }
 91   void init(int region_index, size_t mapping_offset, size_t size, bool read_only,
 92             bool allow_exec, int crc);
 93   void init_oopmap(size_t offset, size_t size_in_bits);
 94   void init_ptrmap(size_t offset, size_t size_in_bits);
 95   bool has_ptrmap()                  { return _ptrmap_size_in_bits != 0; }
 96 
 97   bool check_region_crc(char* base) const;
 98   void print(outputStream* st, int region_index);
 99 };
100 
101 class FileMapHeader: private CDSFileMapHeaderBase {
102   friend class CDSConstants;
103   friend class VMStructs;
104 
105 private:
106   // The following fields record the states of the VM during dump time.
107   // They are compared with the runtime states to see if the archive
108   // can be used.
109   size_t _core_region_alignment;                  // how shared archive should be aligned
110   int    _obj_alignment;                          // value of ObjectAlignmentInBytes
111   address _narrow_oop_base;                       // compressed oop encoding base
112   int    _narrow_oop_shift;                       // compressed oop encoding shift
113   bool   _compact_strings;                        // value of CompactStrings
114   bool   _compact_headers;                        // value of UseCompactObjectHeaders
115   uintx  _max_heap_size;                          // java max heap size during dumping
116   CompressedOops::Mode _narrow_oop_mode;          // compressed oop encoding mode
117   bool    _compressed_oops;                       // save the flag UseCompressedOops
118   bool    _compressed_class_ptrs;                 // save the flag UseCompressedClassPointers
119   int     _narrow_klass_pointer_bits;             // save number of bits in narrowKlass
120   int     _narrow_klass_shift;                    // save shift width used to pre-compute narrowKlass IDs in archived heap objects
121   size_t  _cloned_vtables_offset;                 // The address of the first cloned vtable
122   size_t  _early_serialized_data_offset;          // Data accessed using {ReadClosure,WriteClosure}::serialize()
123   size_t  _serialized_data_offset;                // Data accessed using {ReadClosure,WriteClosure}::serialize()
124 
125   // The following fields are all sanity checks for whether this archive
126   // will function correctly with this JVM and the bootclasspath it's
127   // invoked with.
128   char  _jvm_ident[JVM_IDENT_MAX];  // identifier string of the jvm that created this dump
129 
130   size_t _class_location_config_offset;
131 
132   bool   _verify_local;                 // BytecodeVerificationLocal setting
133   bool   _verify_remote;                // BytecodeVerificationRemote setting
134   bool   _has_platform_or_app_classes;  // Archive contains app or platform classes
135   char*  _requested_base_address;       // Archive relocation is not necessary if we map with this base address.
136   char*  _mapped_base_address;          // Actual base address where archive is mapped.
137 
138   bool   _allow_archiving_with_java_agent; // setting of the AllowArchivingWithJavaAgent option
139   bool   _use_optimized_module_handling;// No module-relation VM options were specified, so we can skip
140                                         // some expensive operations.
141   bool   _has_aot_linked_classes;       // Was the CDS archive created with -XX:+AOTClassLinking
142   bool   _has_full_module_graph;        // Does this CDS archive contain the full archived module graph?
143   bool   _has_archived_invokedynamic;   // Does the archive have aot-linked invokedynamic CP entries?
144   bool   _has_archived_packages;
145   bool   _has_archived_protection_domains;
146   int    _gc_kind;                      // Universe::heap()->kind();
147   char   _gc_name[32];                  // Universe::heap()->name();
148   size_t _ptrmap_size_in_bits;          // Size of pointer relocation bitmap
149   HeapRootSegments _heap_root_segments; // Heap root segments info
150   size_t _heap_oopmap_start_pos;        // The first bit in the oopmap corresponds to this position in the heap.
151   size_t _heap_ptrmap_start_pos;        // The first bit in the ptrmap corresponds to this position in the heap.
152   size_t _rw_ptrmap_start_pos;          // The first bit in the ptrmap corresponds to this position in the rw region
153   size_t _ro_ptrmap_start_pos;          // The first bit in the ptrmap corresponds to this position in the ro region
154   template <typename T> T from_mapped_offset(size_t offset) const {
155     return (T)(mapped_base_address() + offset);
156   }
157   void set_as_offset(char* p, size_t *offset);
158   template <typename T> void set_as_offset(T p, size_t *offset) {
159     set_as_offset((char*)p, offset);
160   }
161 
162 public:
163   // Accessors -- fields declared in GenericCDSFileMapHeader
164   unsigned int magic()                            const { return _generic_header._magic;                    }
165   int crc()                                       const { return _generic_header._crc;                      }
166   int version()                                   const { return _generic_header._version;                  }
167   unsigned int header_size()                      const { return _generic_header._header_size;              }
168   unsigned int base_archive_name_offset()         const { return _generic_header._base_archive_name_offset; }
169   unsigned int base_archive_name_size()           const { return _generic_header._base_archive_name_size;   }
170 
171   void set_magic(unsigned int m)                            { _generic_header._magic = m;                    }
172   void set_crc(int crc_value)                               { _generic_header._crc = crc_value;              }
173   void set_version(int v)                                   { _generic_header._version = v;                  }
174   void set_header_size(unsigned int s)                      { _generic_header._header_size = s;              }
175   void set_base_archive_name_offset(unsigned int s)         { _generic_header._base_archive_name_offset = s; }
176   void set_base_archive_name_size(unsigned int s)           { _generic_header._base_archive_name_size = s;   }
177 
178   bool is_static()                         const { return magic() == CDS_ARCHIVE_MAGIC; }
179   size_t core_region_alignment()           const { return _core_region_alignment; }
180   int obj_alignment()                      const { return _obj_alignment; }
181   address narrow_oop_base()                const { return _narrow_oop_base; }
182   int narrow_oop_shift()                   const { return _narrow_oop_shift; }
183   bool compact_strings()                   const { return _compact_strings; }
184   bool compact_headers()                   const { return _compact_headers; }
185   uintx max_heap_size()                    const { return _max_heap_size; }
186   CompressedOops::Mode narrow_oop_mode()   const { return _narrow_oop_mode; }
187   char* cloned_vtables()                   const { return from_mapped_offset<char*>(_cloned_vtables_offset); }
188   char* early_serialized_data()            const { return from_mapped_offset<char*>(_early_serialized_data_offset); }
189   char* serialized_data()                  const { return from_mapped_offset<char*>(_serialized_data_offset); }
190   const char* jvm_ident()                  const { return _jvm_ident; }
191   char* requested_base_address()           const { return _requested_base_address; }
192   char* mapped_base_address()              const { return _mapped_base_address; }
193   bool has_platform_or_app_classes()       const { return _has_platform_or_app_classes; }
194   bool has_aot_linked_classes()            const { return _has_aot_linked_classes; }
195   int gc_kind()                            const { return _gc_kind; }
196   const char* gc_name()                    const { return _gc_name; }
197   size_t ptrmap_size_in_bits()             const { return _ptrmap_size_in_bits; }
198   bool compressed_oops()                   const { return _compressed_oops; }
199   bool compressed_class_pointers()         const { return _compressed_class_ptrs; }
200   int narrow_klass_pointer_bits()          const { return _narrow_klass_pointer_bits; }
201   int narrow_klass_shift()                 const { return _narrow_klass_shift; }
202   HeapRootSegments heap_root_segments()    const { return _heap_root_segments; }
203   bool has_full_module_graph()             const { return _has_full_module_graph; }
204   size_t heap_oopmap_start_pos()           const { return _heap_oopmap_start_pos; }
205   size_t heap_ptrmap_start_pos()           const { return _heap_ptrmap_start_pos; }
206   size_t rw_ptrmap_start_pos()             const { return _rw_ptrmap_start_pos; }
207   size_t ro_ptrmap_start_pos()             const { return _ro_ptrmap_start_pos; }
208 
209   void set_has_platform_or_app_classes(bool v)   { _has_platform_or_app_classes = v; }
210   void set_cloned_vtables(char* p)               { set_as_offset(p, &_cloned_vtables_offset); }
211   void set_early_serialized_data(char* p)        { set_as_offset(p, &_early_serialized_data_offset); }
212   void set_serialized_data(char* p)              { set_as_offset(p, &_serialized_data_offset); }
213   void set_mapped_base_address(char* p)          { _mapped_base_address = p; }
214   void set_heap_root_segments(HeapRootSegments segments) { _heap_root_segments = segments; }
215   void set_heap_oopmap_start_pos(size_t n)       { _heap_oopmap_start_pos = n; }
216   void set_heap_ptrmap_start_pos(size_t n)       { _heap_ptrmap_start_pos = n; }
217   void set_rw_ptrmap_start_pos(size_t n)         { _rw_ptrmap_start_pos = n; }
218   void set_ro_ptrmap_start_pos(size_t n)         { _ro_ptrmap_start_pos = n; }
219   void copy_base_archive_name(const char* name);
220 
221   void set_class_location_config(AOTClassLocationConfig* table) {
222     set_as_offset(table, &_class_location_config_offset);
223   }
224 
225   AOTClassLocationConfig* class_location_config() {
226     return from_mapped_offset<AOTClassLocationConfig*>(_class_location_config_offset);
227   }
228 
229   void set_requested_base(char* b) {
230     _requested_base_address = b;
231     _mapped_base_address = nullptr;
232   }
233 
234   bool validate();
235   int compute_crc();
236 
237   FileMapRegion* region_at(int i) {
238     assert(is_valid_region(i), "invalid region");
239     return FileMapRegion::cast(&_regions[i]);
240   }
241 
242   void populate(FileMapInfo *info, size_t core_region_alignment, size_t header_size,
243                 size_t base_archive_name_size, size_t base_archive_name_offset);
244   static bool is_valid_region(int region) {
245     return (0 <= region && region < NUM_CDS_REGIONS);
246   }
247 
248   void print(outputStream* st);
249 };
250 
251 class FileMapInfo : public CHeapObj<mtInternal> {
252 private:
253   friend class ManifestStream;
254   friend class VMStructs;
255   friend class ArchiveBuilder;
256   friend class CDSOffsets;
257   friend class FileMapHeader;
258 
259   bool           _is_static;
260   bool           _file_open;
261   bool           _is_mapped;
262   int            _fd;
263   size_t         _file_offset;
264   const char*    _full_path;
265   const char*    _base_archive_name;
266   FileMapHeader* _header;
267 
268   // FileMapHeader describes the shared space data in the file to be
269   // mapped.  This structure gets written to a file.  It is not a class, so
270   // that the compilers don't add any compiler-private data to it.
271 
272   static FileMapInfo* _current_info;
273   static FileMapInfo* _dynamic_archive_info;
274   static bool _heap_pointers_need_patching;
275   static bool _memory_mapping_failed;
276 
277 public:
278   FileMapHeader *header() const       { return _header; }
279   static bool get_base_archive_name_from_header(const char* archive_name,
280                                                 char** base_archive_name);
281   static bool is_preimage_static_archive(const char* file);
282 
283   bool init_from_file(int fd);
284 
285   void log_paths(const char* msg, int start_idx, int end_idx);
286 
287   FileMapInfo(const char* full_apth, bool is_static);
288   ~FileMapInfo();
289   static void free_current_info();
290 
291   // Accessors
292   int    compute_header_crc()  const { return header()->compute_crc(); }
293   void   set_header_crc(int crc)     { header()->set_crc(crc); }
294   int    region_crc(int i)     const { return region_at(i)->crc(); }
295   void   populate_header(size_t core_region_alignment);
296   bool   validate_header();
297   void   invalidate();
298   int    crc()                 const { return header()->crc(); }
299   int    version()             const { return header()->version(); }
300   unsigned int magic()         const { return header()->magic(); }
301   address narrow_oop_base()    const { return header()->narrow_oop_base(); }
302   int     narrow_oop_shift()   const { return header()->narrow_oop_shift(); }
303   uintx   max_heap_size()      const { return header()->max_heap_size(); }
304   HeapRootSegments heap_root_segments() const { return header()->heap_root_segments(); }
305   size_t  core_region_alignment() const { return header()->core_region_alignment(); }
306   size_t  heap_oopmap_start_pos() const { return header()->heap_oopmap_start_pos(); }
307   size_t  heap_ptrmap_start_pos() const { return header()->heap_ptrmap_start_pos(); }
308 
309   CompressedOops::Mode narrow_oop_mode()      const { return header()->narrow_oop_mode(); }
310 
311   char* cloned_vtables()                      const { return header()->cloned_vtables(); }
312   void  set_cloned_vtables(char* p)           const { header()->set_cloned_vtables(p); }
313   char* early_serialized_data()               const { return header()->early_serialized_data(); }
314   void  set_early_serialized_data(char* p)    const { header()->set_early_serialized_data(p); }
315   char* serialized_data()                     const { return header()->serialized_data(); }
316   void  set_serialized_data(char* p)          const { header()->set_serialized_data(p); }
317 
318   bool  is_file_position_aligned() const;
319   void  align_file_position();
320 
321   bool is_static()                            const { return _is_static; }
322   bool is_mapped()                            const { return _is_mapped; }
323   void set_is_mapped(bool v)                        { _is_mapped = v; }
324   const char* full_path()                     const { return _full_path; }
325 
326   void set_requested_base(char* b)                  { header()->set_requested_base(b); }
327   char* requested_base_address()           const    { return header()->requested_base_address(); }
328 
329   class DynamicArchiveHeader* dynamic_header() const {
330     assert(!is_static(), "must be");
331     return (DynamicArchiveHeader*)header();
332   }
333 
334   void set_has_platform_or_app_classes(bool v) {
335     header()->set_has_platform_or_app_classes(v);
336   }
337   bool has_platform_or_app_classes() const {
338     return header()->has_platform_or_app_classes();
339   }
340 
341   static FileMapInfo* current_info() {
342     CDS_ONLY(return _current_info;)
343     NOT_CDS(return nullptr;)
344   }
345 
346   static void set_current_info(FileMapInfo* info) {
347     CDS_ONLY(_current_info = info;)
348   }
349 
350   static FileMapInfo* dynamic_info() {
351     CDS_ONLY(return _dynamic_archive_info;)
352     NOT_CDS(return nullptr;)
353   }
354 
355   static void assert_mark(bool check);
356 
357   // File manipulation.
358   bool  initialize() NOT_CDS_RETURN_(false);
359   bool  open_for_read();
360   void  open_for_write();
361   void  write_header();
362   void  write_region(int region, char* base, size_t size,
363                      bool read_only, bool allow_exec);
364   size_t remove_bitmap_zeros(CHeapBitMap* map);
365   char* write_bitmap_region(CHeapBitMap* rw_ptrmap, CHeapBitMap* ro_ptrmap,
366                             CHeapBitMap* cc_ptrmap, ArchiveHeapInfo* heap_info,
367                             size_t &size_in_bytes);
368   size_t write_heap_region(ArchiveHeapInfo* heap_info);
369   void  write_bytes(const void* buffer, size_t count);
370   void  write_bytes_aligned(const void* buffer, size_t count);
371   size_t  read_bytes(void* buffer, size_t count);
372   static size_t readonly_total();
373   MapArchiveResult map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs);
374   void  unmap_regions(int regions[], int num_regions);
375   void  map_or_load_heap_region() NOT_CDS_JAVA_HEAP_RETURN;
376   void  fixup_mapped_heap_region() NOT_CDS_JAVA_HEAP_RETURN;
377   void  patch_heap_embedded_pointers() NOT_CDS_JAVA_HEAP_RETURN;
378   bool  has_heap_region()  NOT_CDS_JAVA_HEAP_RETURN_(false);
379   MemRegion get_heap_region_requested_range() NOT_CDS_JAVA_HEAP_RETURN_(MemRegion());
380   bool  read_region(int i, char* base, size_t size, bool do_commit);
381   char* map_bitmap_region();
382   bool map_cached_code_region(ReservedSpace rs);
383   void  unmap_region(int i);
384   void  close();
385   bool  is_open() { return _file_open; }
386 
387   // JVM/TI RedefineClasses() support:
388   // Remap the shared readonly space to shared readwrite, private.
389   bool  remap_shared_readonly_as_readwrite();
390 
391   static bool memory_mapping_failed() {
392     CDS_ONLY(return _memory_mapping_failed;)
393     NOT_CDS(return false;)
394   }
395 
396   bool validate_class_location();
397   bool validate_aot_class_linking();
398 
399 #if INCLUDE_JVMTI
400   // Caller needs a ResourceMark because parts of the returned cfs are resource-allocated.
401   static ClassFileStream* open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS);
402   static ClassFileStream* get_stream_from_class_loader(Handle class_loader,
403                                                        ClassPathEntry* cpe,
404                                                        const char* file_name,
405                                                        TRAPS);
406 #endif
407 
408   // The offset of the first core region in the archive, relative to SharedBaseAddress
409   size_t mapping_base_offset() const { return first_core_region()->mapping_offset();    }
410   // The offset of the (exclusive) end of the last core region in this archive, relative to SharedBaseAddress
411   size_t mapping_end_offset()  const { return last_core_region()->mapping_end_offset(); }
412 
413   char* mapped_base()    const { return first_core_region()->mapped_base(); }
414   char* mapped_end()     const { return last_core_region()->mapped_end();   }
415 
416   // Non-zero if the archive needs to be mapped a non-default location due to ASLR.
417   intx relocation_delta() const {
418     return header()->mapped_base_address() - header()->requested_base_address();
419   }
420 
421   FileMapRegion* first_core_region() const;
422   FileMapRegion* last_core_region()  const;
423 
424   FileMapRegion* region_at(int i) const {
425     return header()->region_at(i);
426   }
427 
428   BitMapView bitmap_view(int region_index, bool is_oopmap);
429   BitMapView oopmap_view(int region_index);
430   BitMapView ptrmap_view(int region_index);
431 
432   void print(outputStream* st) const;
433 
434   const char* vm_version() {
435     return header()->jvm_ident();
436   }
437 
438  private:
439   void  seek_to_position(size_t pos);
440   bool  map_heap_region_impl() NOT_CDS_JAVA_HEAP_RETURN_(false);
441   void  dealloc_heap_region() NOT_CDS_JAVA_HEAP_RETURN;
442   bool  can_use_heap_region();
443   bool  load_heap_region() NOT_CDS_JAVA_HEAP_RETURN_(false);
444   bool  map_heap_region() NOT_CDS_JAVA_HEAP_RETURN_(false);
445   void  init_heap_region_relocation();
446   MapArchiveResult map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs);
447   bool  relocate_pointers_in_core_regions(intx addr_delta);
448   void  relocate_pointers_in_cached_code_region();
449   static MemRegion _mapped_heap_memregion;
450 
451 public:
452   address heap_region_dumptime_address() NOT_CDS_JAVA_HEAP_RETURN_(nullptr);
453   address heap_region_requested_address() NOT_CDS_JAVA_HEAP_RETURN_(nullptr);
454   narrowOop encoded_heap_region_dumptime_address();
455 
456 private:
457 
458 #if INCLUDE_JVMTI
459   static ClassPathEntry** _classpath_entries_for_jvmti;
460   static ClassPathEntry* get_classpath_entry_for_jvmti(int i, TRAPS);
461 #endif
462 };
463 
464 #endif // SHARE_CDS_FILEMAP_HPP