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