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, size_t alignment) {
206   // We align the starting address of each allocation.
207   char* p = (char*)align_up(_top, alignment);
208   char* newtop = p + num_bytes;
209   // Leave _top always SharedSpaceObjectAlignment aligned. But not more -
210   //  if we allocate with large alignments, lets not waste the gaps.
211   // Ideally we would not need to align _top to anything here but CDS has
212   //  a number of implicit alignment assumptions. Leaving this unaligned
213   //  here will trip of at least ReadClosure (assuming word alignment) and
214   //  DumpAllocStats (will get confused about counting bytes on 32-bit
215   //  platforms if we align to anything less than SharedSpaceObjectAlignment
216   //  here).
217   newtop = align_up(newtop, SharedSpaceObjectAlignment);
218   expand_top_to(newtop);
219   memset(p, 0, newtop - p); // todo: needed? debug_only?
220   return p;
221 }
222 
223 char* DumpRegion::allocate(size_t num_bytes) {
224   return allocate(num_bytes, SharedSpaceObjectAlignment);
225 }
226 
227 void DumpRegion::append_intptr_t(intptr_t n, bool need_to_mark) {
228   assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment");
229   intptr_t *p = (intptr_t*)_top;
230   char* newtop = _top + sizeof(intptr_t);
231   expand_top_to(newtop);
232   *p = n;
233   if (need_to_mark) {
234     ArchivePtrMarker::mark_pointer(p);
235   }
236 }
237 
238 void DumpRegion::print(size_t total_bytes) const {
239   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,
240                  _name, used(), percent_of(used(), total_bytes), reserved(), percent_of(used(), reserved()),
241                  p2i(ArchiveBuilder::current()->to_requested(_base)));
242 }
243 
244 void DumpRegion::print_out_of_space_msg(const char* failing_region, size_t needed_bytes) {
245   log_error(cds)("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d",
246                  _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base));
247   if (strcmp(_name, failing_region) == 0) {
248     log_error(cds)(" required = %d", int(needed_bytes));
249   }
250 }
251 
252 void DumpRegion::init(ReservedSpace* rs, VirtualSpace* vs) {
253   _rs = rs;
254   _vs = vs;
255   // Start with 0 committed bytes. The memory will be committed as needed.
256   if (!_vs->initialize(*_rs, 0)) {
257     fatal("Unable to allocate memory for shared space");
258   }
259   _base = _top = _rs->base();
260   _end = _rs->end();
261 }
262 
263 void DumpRegion::pack(DumpRegion* next) {
264   assert(!is_packed(), "sanity");
265   _end = (char*)align_up(_top, MetaspaceShared::core_region_alignment());
266   _is_packed = true;
267   if (next != NULL) {
268     next->_rs = _rs;
269     next->_vs = _vs;
270     next->_base = next->_top = this->_end;
271     next->_end = _rs->end();
272   }
273 }
274 
275 void WriteClosure::do_oop(oop* o) {
276   if (*o == NULL) {
277     _dump_region->append_intptr_t(0);
278   } else {
279     assert(HeapShared::can_write(), "sanity");
280     _dump_region->append_intptr_t(
281       (intptr_t)CompressedOops::encode_not_null(*o));
282   }
283 }
284 
285 void WriteClosure::do_region(u_char* start, size_t size) {
286   assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
287   assert(size % sizeof(intptr_t) == 0, "bad size");
288   do_tag((int)size);
289   while (size > 0) {
290     _dump_region->append_intptr_t(*(intptr_t*)start, true);
291     start += sizeof(intptr_t);
292     size -= sizeof(intptr_t);
293   }
294 }
295 
296 void ReadClosure::do_ptr(void** p) {
297   assert(*p == NULL, "initializing previous initialized pointer.");
298   intptr_t obj = nextPtr();
299   assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
300          "hit tag while initializing ptrs.");
301   *p = (void*)obj;
302 }
303 
304 void ReadClosure::do_u4(u4* p) {
305   intptr_t obj = nextPtr();
306   *p = (u4)(uintx(obj));
307 }
308 
309 void ReadClosure::do_bool(bool* p) {
310   intptr_t obj = nextPtr();
311   *p = (bool)(uintx(obj));
312 }
313 
314 void ReadClosure::do_tag(int tag) {
315   int old_tag;
316   old_tag = (int)(intptr_t)nextPtr();
317   // do_int(&old_tag);
318   assert(tag == old_tag, "tag doesn't match (%d, expected %d)", old_tag, tag);
319   FileMapInfo::assert_mark(tag == old_tag);
320 }
321 
322 void ReadClosure::do_oop(oop *p) {
323   narrowOop o = CompressedOops::narrow_oop_cast(nextPtr());
324   if (CompressedOops::is_null(o) || !HeapShared::is_fully_available()) {
325     *p = NULL;
326   } else {
327     assert(HeapShared::can_use(), "sanity");
328     assert(HeapShared::is_fully_available(), "must be");
329     *p = HeapShared::decode_from_archive(o);
330   }
331 }
332 
333 void ReadClosure::do_region(u_char* start, size_t size) {
334   assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
335   assert(size % sizeof(intptr_t) == 0, "bad size");
336   do_tag((int)size);
337   while (size > 0) {
338     *(intptr_t*)start = nextPtr();
339     start += sizeof(intptr_t);
340     size -= sizeof(intptr_t);
341   }
342 }
343 
344 void ArchiveUtils::log_to_classlist(BootstrapInfo* bootstrap_specifier, TRAPS) {
345   if (ClassListWriter::is_enabled()) {
346     if (SystemDictionaryShared::is_supported_invokedynamic(bootstrap_specifier)) {
347       const constantPoolHandle& pool = bootstrap_specifier->pool();
348       if (SystemDictionaryShared::is_builtin_loader(pool->pool_holder()->class_loader_data())) {
349         // Currently lambda proxy classes are supported only for the built-in loaders.
350         ResourceMark rm(THREAD);
351         int pool_index = bootstrap_specifier->bss_index();
352         ClassListWriter w;
353         w.stream()->print("%s %s", LAMBDA_PROXY_TAG, pool->pool_holder()->name()->as_C_string());
354         CDSIndyInfo cii;
355         ClassListParser::populate_cds_indy_info(pool, pool_index, &cii, CHECK);
356         GrowableArray<const char*>* indy_items = cii.items();
357         for (int i = 0; i < indy_items->length(); i++) {
358           w.stream()->print(" %s", indy_items->at(i));
359         }
360         w.stream()->cr();
361       }
362     }
363   }
364 }