1 /*
  2  * Copyright (c) 2019, 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 #include "precompiled.hpp"
 26 #include "cds/archiveBuilder.hpp"
 27 #include "cds/archiveHeapLoader.inline.hpp"
 28 #include "cds/archiveUtils.hpp"
 29 #include "cds/cdsConfig.hpp"
 30 #include "cds/classListParser.hpp"
 31 #include "cds/classListWriter.hpp"
 32 #include "cds/dynamicArchive.hpp"
 33 #include "cds/filemap.hpp"
 34 #include "cds/heapShared.hpp"
 35 #include "cds/metaspaceShared.hpp"
 36 #include "classfile/systemDictionaryShared.hpp"
 37 #include "classfile/vmClasses.hpp"
 38 #include "interpreter/bootstrapInfo.hpp"
 39 #include "memory/metaspaceUtils.hpp"
 40 #include "memory/resourceArea.hpp"
 41 #include "oops/compressedOops.inline.hpp"
 42 #include "oops/klass.inline.hpp"
 43 #include "runtime/arguments.hpp"
 44 #include "utilities/bitMap.inline.hpp"
 45 #include "utilities/debug.hpp"
 46 #include "utilities/formatBuffer.hpp"
 47 #include "utilities/globalDefinitions.hpp"
 48 
 49 CHeapBitMap* ArchivePtrMarker::_ptrmap = nullptr;
 50 CHeapBitMap* ArchivePtrMarker::_rw_ptrmap = nullptr;
 51 CHeapBitMap* ArchivePtrMarker::_ro_ptrmap = nullptr;
 52 VirtualSpace* ArchivePtrMarker::_vs;
 53 
 54 bool ArchivePtrMarker::_compacted;
 55 
 56 void ArchivePtrMarker::initialize(CHeapBitMap* ptrmap, VirtualSpace* vs) {
 57   assert(_ptrmap == nullptr, "initialize only once");
 58   assert(_rw_ptrmap == nullptr, "initialize only once");
 59   assert(_ro_ptrmap == nullptr, "initialize only once");
 60   _vs = vs;
 61   _compacted = false;
 62   _ptrmap = ptrmap;
 63 
 64   // Use this as initial guesstimate. We should need less space in the
 65   // archive, but if we're wrong the bitmap will be expanded automatically.
 66   size_t estimated_archive_size = MetaspaceGC::capacity_until_GC();
 67   // But set it smaller in debug builds so we always test the expansion code.
 68   // (Default archive is about 12MB).
 69   DEBUG_ONLY(estimated_archive_size = 6 * M);
 70 
 71   // We need one bit per pointer in the archive.
 72   _ptrmap->initialize(estimated_archive_size / sizeof(intptr_t));
 73 }
 74 
 75 void ArchivePtrMarker::initialize_rw_ro_maps(CHeapBitMap* rw_ptrmap, CHeapBitMap* ro_ptrmap) {
 76   address* rw_bottom = (address*)ArchiveBuilder::current()->rw_region()->base();
 77   address* ro_bottom = (address*)ArchiveBuilder::current()->ro_region()->base();
 78 
 79   _rw_ptrmap = rw_ptrmap;
 80   _ro_ptrmap = ro_ptrmap;
 81 
 82   size_t rw_size = ArchiveBuilder::current()->rw_region()->used() / sizeof(address);
 83   size_t ro_size = ArchiveBuilder::current()->ro_region()->used() / sizeof(address);
 84   // ro_start is the first bit in _ptrmap that covers the pointer that would sit at ro_bottom.
 85   // E.g., if rw_bottom = (address*)100
 86   //          ro_bottom = (address*)116
 87   //       then for 64-bit platform:
 88   //          ro_start = ro_bottom - rw_bottom = (116 - 100) / sizeof(address) = 2;
 89   size_t ro_start = ro_bottom - rw_bottom;
 90 
 91   // Note: ptrmap is big enough only to cover the last pointer in ro_region.
 92   // See ArchivePtrMarker::compact()
 93   _rw_ptrmap->initialize(rw_size);
 94   _ro_ptrmap->initialize(_ptrmap->size() - ro_start);
 95 
 96   for (size_t rw_bit = 0; rw_bit < _rw_ptrmap->size(); rw_bit++) {
 97     _rw_ptrmap->at_put(rw_bit, _ptrmap->at(rw_bit));
 98   }
 99 
100   for(size_t ro_bit = ro_start; ro_bit < _ptrmap->size(); ro_bit++) {
101     _ro_ptrmap->at_put(ro_bit-ro_start, _ptrmap->at(ro_bit));
102   }
103   assert(_ptrmap->size() - ro_start == _ro_ptrmap->size(), "must be");
104 }
105 
106 void ArchivePtrMarker::mark_pointer(address* ptr_loc) {
107   assert(_ptrmap != nullptr, "not initialized");
108   assert(!_compacted, "cannot mark anymore");
109 
110   if (ptr_base() <= ptr_loc && ptr_loc < ptr_end()) {
111     address value = *ptr_loc;
112     // We don't want any pointer that points to very bottom of the archive, otherwise when
113     // MetaspaceShared::default_base_address()==0, we can't distinguish between a pointer
114     // to nothing (null) vs a pointer to an objects that happens to be at the very bottom
115     // of the archive.
116     assert(value != (address)ptr_base(), "don't point to the bottom of the archive");
117 
118     if (value != nullptr) {
119       assert(uintx(ptr_loc) % sizeof(intptr_t) == 0, "pointers must be stored in aligned addresses");
120       size_t idx = ptr_loc - ptr_base();
121       if (_ptrmap->size() <= idx) {
122         _ptrmap->resize((idx + 1) * 2);
123       }
124       assert(idx < _ptrmap->size(), "must be");
125       _ptrmap->set_bit(idx);
126       //tty->print_cr("Marking pointer [" PTR_FORMAT "] -> " PTR_FORMAT " @ " SIZE_FORMAT_W(5), p2i(ptr_loc), p2i(*ptr_loc), idx);
127     }
128   }
129 }
130 
131 void ArchivePtrMarker::clear_pointer(address* ptr_loc) {
132   assert(_ptrmap != nullptr, "not initialized");
133   assert(!_compacted, "cannot clear anymore");
134 
135   assert(ptr_base() <= ptr_loc && ptr_loc < ptr_end(), "must be");
136   assert(uintx(ptr_loc) % sizeof(intptr_t) == 0, "pointers must be stored in aligned addresses");
137   size_t idx = ptr_loc - ptr_base();
138   assert(idx < _ptrmap->size(), "cannot clear pointers that have not been marked");
139   _ptrmap->clear_bit(idx);
140   //tty->print_cr("Clearing pointer [" PTR_FORMAT "] -> " PTR_FORMAT " @ " SIZE_FORMAT_W(5), p2i(ptr_loc), p2i(*ptr_loc), idx);
141 }
142 
143 class ArchivePtrBitmapCleaner: public BitMapClosure {
144   CHeapBitMap* _ptrmap;
145   address* _ptr_base;
146   address  _relocatable_base;
147   address  _relocatable_end;
148   size_t   _max_non_null_offset;
149 
150 public:
151   ArchivePtrBitmapCleaner(CHeapBitMap* ptrmap, address* ptr_base, address relocatable_base, address relocatable_end) :
152     _ptrmap(ptrmap), _ptr_base(ptr_base),
153     _relocatable_base(relocatable_base), _relocatable_end(relocatable_end), _max_non_null_offset(0) {}
154 
155   bool do_bit(size_t offset) {
156     address* ptr_loc = _ptr_base + offset;
157     address  ptr_value = *ptr_loc;
158     if (ptr_value != nullptr) {
159       assert(_relocatable_base <= ptr_value && ptr_value < _relocatable_end, "do not point to arbitrary locations!");
160       if (_max_non_null_offset < offset) {
161         _max_non_null_offset = offset;
162       }
163     } else {
164       _ptrmap->clear_bit(offset);
165       DEBUG_ONLY(log_trace(cds, reloc)("Clearing pointer [" PTR_FORMAT  "] -> null @ " SIZE_FORMAT_W(9), p2i(ptr_loc), offset));
166     }
167 
168     return true;
169   }
170 
171   size_t max_non_null_offset() const { return _max_non_null_offset; }
172 };
173 
174 void ArchivePtrMarker::compact(address relocatable_base, address relocatable_end) {
175   assert(!_compacted, "cannot compact again");
176   ArchivePtrBitmapCleaner cleaner(_ptrmap, ptr_base(), relocatable_base, relocatable_end);
177   _ptrmap->iterate(&cleaner);
178   compact(cleaner.max_non_null_offset());
179 }
180 
181 void ArchivePtrMarker::compact(size_t max_non_null_offset) {
182   assert(!_compacted, "cannot compact again");
183   _ptrmap->resize(max_non_null_offset + 1);
184   _compacted = true;
185 }
186 
187 char* DumpRegion::expand_top_to(char* newtop) {
188   assert(is_allocatable(), "must be initialized and not packed");
189   assert(newtop >= _top, "must not grow backwards");
190   if (newtop > _end) {
191     ArchiveBuilder::current()->report_out_of_space(_name, newtop - _top);
192     ShouldNotReachHere();
193   }
194 
195   commit_to(newtop);
196   _top = newtop;
197 
198   if (_max_delta > 0) {
199     uintx delta = ArchiveBuilder::current()->buffer_to_offset((address)(newtop-1));
200     if (delta > _max_delta) {
201       // This is just a sanity check and should not appear in any real world usage. This
202       // happens only if you allocate more than 2GB of shared objects and would require
203       // millions of shared classes.
204       log_error(cds)("Out of memory in the CDS archive: Please reduce the number of shared classes.");
205       MetaspaceShared::unrecoverable_writing_error();
206     }
207   }
208 
209   return _top;
210 }
211 
212 void DumpRegion::commit_to(char* newtop) {
213   assert(CDSConfig::is_dumping_archive(), "sanity");
214   char* base = _rs->base();
215   size_t need_committed_size = newtop - base;
216   size_t has_committed_size = _vs->committed_size();
217   if (need_committed_size < has_committed_size) {
218     return;
219   }
220 
221   size_t min_bytes = need_committed_size - has_committed_size;
222   size_t preferred_bytes = 1 * M;
223   size_t uncommitted = _vs->reserved_size() - has_committed_size;
224 
225   size_t commit = MAX2(min_bytes, preferred_bytes);
226   commit = MIN2(commit, uncommitted);
227   assert(commit <= uncommitted, "sanity");
228 
229   if (!_vs->expand_by(commit, false)) {
230     log_error(cds)("Failed to expand shared space to " SIZE_FORMAT " bytes",
231                     need_committed_size);
232     MetaspaceShared::unrecoverable_writing_error();
233   }
234 
235   const char* which;
236   if (_rs->base() == (char*)MetaspaceShared::symbol_rs_base()) {
237     which = "symbol";
238   } else {
239     which = "shared";
240   }
241   log_debug(cds)("Expanding %s spaces by " SIZE_FORMAT_W(7) " bytes [total " SIZE_FORMAT_W(9)  " bytes ending at %p]",
242                  which, commit, _vs->actual_committed_size(), _vs->high());
243 }
244 
245 char* DumpRegion::allocate(size_t num_bytes, size_t alignment) {
246   // Always align to at least minimum alignment
247   alignment = MAX2(SharedSpaceObjectAlignment, alignment);
248   char* p = (char*)align_up(_top, alignment);
249   char* newtop = p + align_up(num_bytes, (size_t)SharedSpaceObjectAlignment);
250   expand_top_to(newtop);
251   memset(p, 0, newtop - p);
252   return p;
253 }
254 
255 void DumpRegion::append_intptr_t(intptr_t n, bool need_to_mark) {
256   assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment");
257   intptr_t *p = (intptr_t*)_top;
258   char* newtop = _top + sizeof(intptr_t);
259   expand_top_to(newtop);
260   *p = n;
261   if (need_to_mark) {
262     ArchivePtrMarker::mark_pointer(p);
263   }
264 }
265 
266 void DumpRegion::print(size_t total_bytes) const {
267   log_debug(cds)("%s space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used] at " INTPTR_FORMAT,
268                  _name, used(), percent_of(used(), total_bytes), reserved(), percent_of(used(), reserved()),
269                  p2i(ArchiveBuilder::current()->to_requested(_base)));
270 }
271 
272 void DumpRegion::print_out_of_space_msg(const char* failing_region, size_t needed_bytes) {
273   log_error(cds)("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d",
274                  _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base));
275   if (strcmp(_name, failing_region) == 0) {
276     log_error(cds)(" required = %d", int(needed_bytes));
277   }
278 }
279 
280 void DumpRegion::init(ReservedSpace* rs, VirtualSpace* vs) {
281   _rs = rs;
282   _vs = vs;
283   // Start with 0 committed bytes. The memory will be committed as needed.
284   if (!_vs->initialize(*_rs, 0)) {
285     fatal("Unable to allocate memory for shared space");
286   }
287   _base = _top = _rs->base();
288   _end = _rs->end();
289 }
290 
291 void DumpRegion::pack(DumpRegion* next) {
292   assert(!is_packed(), "sanity");
293   _end = (char*)align_up(_top, MetaspaceShared::core_region_alignment());
294   _is_packed = true;
295   if (next != nullptr) {
296     next->_rs = _rs;
297     next->_vs = _vs;
298     next->_base = next->_top = this->_end;
299     next->_end = _rs->end();
300   }
301 }
302 
303 void WriteClosure::do_ptr(void** p) {
304   // Write ptr into the archive; ptr can be:
305   //   (a) null                 -> written as 0
306   //   (b) a "buffered" address -> written as is
307   //   (c) a "source"   address -> convert to "buffered" and write
308   // The common case is (c). E.g., when writing the vmClasses into the archive.
309   // We have (b) only when we don't have a corresponding source object. E.g.,
310   // the archived c++ vtable entries.
311   address ptr = *(address*)p;
312   if (ptr != nullptr && !ArchiveBuilder::current()->is_in_buffer_space(ptr)) {
313     ptr = ArchiveBuilder::current()->get_buffered_addr(ptr);
314   }
315   // null pointers do not need to be converted to offsets
316   if (ptr != nullptr) {
317     ptr = (address)ArchiveBuilder::current()->buffer_to_offset(ptr);
318   }
319   _dump_region->append_intptr_t((intptr_t)ptr, false);
320 }
321 
322 void ReadClosure::do_ptr(void** p) {
323   assert(*p == nullptr, "initializing previous initialized pointer.");
324   intptr_t obj = nextPtr();
325   assert(obj >= 0, "sanity.");
326   *p = (obj != 0) ? (void*)(_base_address + obj) : (void*)obj;
327 }
328 
329 void ReadClosure::do_u4(u4* p) {
330   intptr_t obj = nextPtr();
331   *p = (u4)(uintx(obj));
332 }
333 
334 void ReadClosure::do_int(int* p) {
335   intptr_t obj = nextPtr();
336   *p = (int)(intx(obj));
337 }
338 
339 void ReadClosure::do_bool(bool* p) {
340   intptr_t obj = nextPtr();
341   *p = (bool)(uintx(obj));
342 }
343 
344 void ReadClosure::do_tag(int tag) {
345   int old_tag;
346   old_tag = (int)(intptr_t)nextPtr();
347   // do_int(&old_tag);
348   assert(tag == old_tag, "tag doesn't match (%d, expected %d)", old_tag, tag);
349   FileMapInfo::assert_mark(tag == old_tag);
350 }
351 
352 void ArchiveUtils::log_to_classlist(BootstrapInfo* bootstrap_specifier, TRAPS) {
353   if (ClassListWriter::is_enabled()) {
354     if (SystemDictionaryShared::is_supported_invokedynamic(bootstrap_specifier)) {
355       const constantPoolHandle& pool = bootstrap_specifier->pool();
356       if (SystemDictionaryShared::is_builtin_loader(pool->pool_holder()->class_loader_data())) {
357         // Currently lambda proxy classes are supported only for the built-in loaders.
358         ResourceMark rm(THREAD);
359         int pool_index = bootstrap_specifier->bss_index();
360         ClassListWriter w;
361         w.stream()->print("%s %s", ClassListParser::lambda_proxy_tag(), pool->pool_holder()->name()->as_C_string());
362         CDSIndyInfo cii;
363         ClassListParser::populate_cds_indy_info(pool, pool_index, &cii, CHECK);
364         GrowableArray<const char*>* indy_items = cii.items();
365         for (int i = 0; i < indy_items->length(); i++) {
366           w.stream()->print(" %s", indy_items->at(i));
367         }
368         w.stream()->cr();
369       }
370     }
371   }
372 }
373 
374 bool ArchiveUtils::has_aot_initialized_mirror(InstanceKlass* src_ik) {
375   if (SystemDictionaryShared::is_excluded_class(src_ik)) {
376     assert(!ArchiveBuilder::current()->has_been_buffered(src_ik), "sanity");
377     return false;
378   }
379   return ArchiveBuilder::current()->get_buffered_addr(src_ik)->has_aot_initialized_mirror();
380 }
381 
382 size_t HeapRootSegments::size_in_bytes(size_t seg_idx) {
383   assert(seg_idx < _count, "In range");
384   return objArrayOopDesc::object_size(size_in_elems(seg_idx)) * HeapWordSize;
385 }
386 
387 int HeapRootSegments::size_in_elems(size_t seg_idx) {
388   assert(seg_idx < _count, "In range");
389   if (seg_idx != _count - 1) {
390     return _max_size_in_elems;
391   } else {
392     // Last slice, leftover
393     return _roots_count % _max_size_in_elems;
394   }
395 }
396 
397 size_t HeapRootSegments::segment_offset(size_t seg_idx) {
398   assert(seg_idx < _count, "In range");
399   return _base_offset + seg_idx * _max_size_in_bytes;
400 }
401