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