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