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