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