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