1 /*
2 * Copyright (c) 2019, 2026, 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 "cds/aotCompressedPointers.hpp"
26 #include "cds/aotLogging.hpp"
27 #include "cds/aotMetaspace.hpp"
28 #include "cds/archiveBuilder.hpp"
29 #include "cds/archiveUtils.hpp"
30 #include "cds/cdsConfig.hpp"
31 #include "cds/classListParser.hpp"
32 #include "cds/classListWriter.hpp"
33 #include "cds/dumpAllocStats.hpp"
34 #include "cds/dynamicArchive.hpp"
35 #include "cds/filemap.hpp"
36 #include "cds/heapShared.hpp"
37 #include "cds/lambdaProxyClassDictionary.hpp"
38 #include "classfile/systemDictionaryShared.hpp"
39 #include "classfile/vmClasses.hpp"
40 #include "interpreter/bootstrapInfo.hpp"
41 #include "memory/metaspaceUtils.hpp"
42 #include "memory/resourceArea.hpp"
43 #include "oops/compressedOops.inline.hpp"
44 #include "oops/klass.inline.hpp"
45 #include "runtime/arguments.hpp"
46 #include "utilities/bitMap.inline.hpp"
47 #include "utilities/debug.hpp"
48 #include "utilities/formatBuffer.hpp"
49 #include "utilities/globalDefinitions.hpp"
50 #include "utilities/rbTree.inline.hpp"
51 #include "utilities/spinYield.hpp"
52
53 CHeapBitMap* ArchivePtrMarker::_ptrmap = nullptr;
54 CHeapBitMap* ArchivePtrMarker::_rw_ptrmap = nullptr;
55 CHeapBitMap* ArchivePtrMarker::_ro_ptrmap = nullptr;
56 VirtualSpace* ArchivePtrMarker::_vs;
57
58 bool ArchivePtrMarker::_compacted;
59
60 void ArchivePtrMarker::initialize(CHeapBitMap* ptrmap, VirtualSpace* vs) {
61 assert(_ptrmap == nullptr, "initialize only once");
62 assert(_rw_ptrmap == nullptr, "initialize only once");
63 assert(_ro_ptrmap == nullptr, "initialize only once");
64 _vs = vs;
65 _compacted = false;
66 _ptrmap = ptrmap;
67
68 // Use this as initial guesstimate. We should need less space in the
69 // archive, but if we're wrong the bitmap will be expanded automatically.
70 size_t estimated_archive_size = MetaspaceGC::capacity_until_GC();
71 // But set it smaller in debug builds so we always test the expansion code.
72 // (Default archive is about 12MB).
73 DEBUG_ONLY(estimated_archive_size = 6 * M);
74
75 // We need one bit per pointer in the archive.
76 _ptrmap->initialize(estimated_archive_size / sizeof(intptr_t));
77 }
78
79 void ArchivePtrMarker::initialize_rw_ro_maps(CHeapBitMap* rw_ptrmap, CHeapBitMap* ro_ptrmap) {
80 address* buff_bottom = (address*)ArchiveBuilder::current()->buffer_bottom();
81 address* rw_bottom = (address*)ArchiveBuilder::current()->rw_region()->base();
82 address* ro_bottom = (address*)ArchiveBuilder::current()->ro_region()->base();
83
84 // The bit in _ptrmap that cover the very first word in the rw/ro regions.
85 size_t rw_start = rw_bottom - buff_bottom;
86 size_t ro_start = ro_bottom - buff_bottom;
87
88 // The number of bits used by the rw/ro ptrmaps. We might have lots of zero
89 // bits at the bottom and top of rw/ro ptrmaps, but these zeros will be
90 // removed by FileMapInfo::write_bitmap_region().
91 size_t rw_size = ArchiveBuilder::current()->rw_region()->used() / sizeof(address);
92 size_t ro_size = ArchiveBuilder::current()->ro_region()->used() / sizeof(address);
93
94 // The last (exclusive) bit in _ptrmap that covers the rw/ro regions.
95 // Note: _ptrmap is dynamically expanded only when an actual pointer is written, so
96 // it may not be as large as we want.
97 size_t rw_end = MIN2<size_t>(rw_start + rw_size, _ptrmap->size());
98 size_t ro_end = MIN2<size_t>(ro_start + ro_size, _ptrmap->size());
99
100 rw_ptrmap->initialize(rw_size);
101 ro_ptrmap->initialize(ro_size);
102
103 for (size_t rw_bit = rw_start; rw_bit < rw_end; rw_bit++) {
104 rw_ptrmap->at_put(rw_bit - rw_start, _ptrmap->at(rw_bit));
105 }
106
107 for(size_t ro_bit = ro_start; ro_bit < ro_end; ro_bit++) {
108 ro_ptrmap->at_put(ro_bit - ro_start, _ptrmap->at(ro_bit));
109 }
110
111 _rw_ptrmap = rw_ptrmap;
112 _ro_ptrmap = ro_ptrmap;
113 }
114
115 void ArchivePtrMarker::mark_pointer(address* ptr_loc) {
116 assert(_ptrmap != nullptr, "not initialized");
117 assert(!_compacted, "cannot mark anymore");
118
119 if (ptr_base() <= ptr_loc && ptr_loc < ptr_end()) {
120 address value = *ptr_loc;
121 if (value != nullptr) {
122 // We don't want any pointer that points to very bottom of the AOT metaspace, otherwise
123 // when AOTMetaspace::default_base_address()==0, we can't distinguish between a pointer
124 // to nothing (null) vs a pointer to an objects that happens to be at the very bottom
125 // of the AOT metaspace.
126 //
127 // This should never happen because the protection zone prevents any valid objects from
128 // being allocated at the bottom of the AOT metaspace.
129 assert(AOTMetaspace::protection_zone_size() > 0, "must be");
130 assert(ArchiveBuilder::current()->any_to_offset(value) > 0, "cannot point to bottom of AOT metaspace");
131
132 assert(uintx(ptr_loc) % sizeof(intptr_t) == 0, "pointers must be stored in aligned addresses");
133 size_t idx = ptr_loc - ptr_base();
134 if (_ptrmap->size() <= idx) {
135 _ptrmap->resize((idx + 1) * 2);
136 }
137 assert(idx < _ptrmap->size(), "must be");
138 _ptrmap->set_bit(idx);
139 }
140 }
141 }
142
143 void ArchivePtrMarker::clear_pointer(address* ptr_loc) {
144 assert(_ptrmap != nullptr, "not initialized");
145 assert(!_compacted, "cannot clear anymore");
146
147 assert(ptr_base() <= ptr_loc && ptr_loc < ptr_end(), "must be");
148 assert(uintx(ptr_loc) % sizeof(intptr_t) == 0, "pointers must be stored in aligned addresses");
149 size_t idx = ptr_loc - ptr_base();
150 assert(idx < _ptrmap->size(), "cannot clear pointers that have not been marked");
151 _ptrmap->clear_bit(idx);
152 }
153
154 class ArchivePtrBitmapCleaner: public BitMapClosure {
155 CHeapBitMap* _ptrmap;
156 address* _ptr_base;
157 address _relocatable_base;
158 address _relocatable_end;
159 size_t _max_non_null_offset;
160
161 public:
162 ArchivePtrBitmapCleaner(CHeapBitMap* ptrmap, address* ptr_base, address relocatable_base, address relocatable_end) :
163 _ptrmap(ptrmap), _ptr_base(ptr_base),
164 _relocatable_base(relocatable_base), _relocatable_end(relocatable_end), _max_non_null_offset(0) {}
165
166 bool do_bit(size_t offset) {
167 address* ptr_loc = _ptr_base + offset;
168 address ptr_value = *ptr_loc;
169 if (ptr_value != nullptr) {
170 assert(_relocatable_base <= ptr_value && ptr_value < _relocatable_end, "do not point to arbitrary locations!");
171 if (_max_non_null_offset < offset) {
172 _max_non_null_offset = offset;
173 }
174 } else {
175 _ptrmap->clear_bit(offset);
176 DEBUG_ONLY(log_trace(aot, reloc)("Clearing pointer [" PTR_FORMAT "] -> null @ %9zu", p2i(ptr_loc), offset));
177 }
178
179 return true;
180 }
181
182 size_t max_non_null_offset() const { return _max_non_null_offset; }
183 };
184
185 void ArchivePtrMarker::compact(address relocatable_base, address relocatable_end) {
186 assert(!_compacted, "cannot compact again");
187 ArchivePtrBitmapCleaner cleaner(_ptrmap, ptr_base(), relocatable_base, relocatable_end);
188 _ptrmap->iterate(&cleaner);
189 compact(cleaner.max_non_null_offset());
190 }
191
192 void ArchivePtrMarker::compact(size_t max_non_null_offset) {
193 assert(!_compacted, "cannot compact again");
194 _ptrmap->resize(max_non_null_offset + 1);
195 _compacted = true;
196 }
197
198 char* DumpRegion::expand_top_to(char* newtop) {
199 assert(is_allocatable(), "must be initialized and not packed");
200 assert(newtop >= _top, "must not grow backwards");
201 if (newtop > _end) {
202 ArchiveBuilder::current()->report_out_of_space(_name, newtop - _top);
203 ShouldNotReachHere();
204 }
205
206 commit_to(newtop);
207 _top = newtop;
208
209 if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(_base)) {
210 uintx delta = ArchiveBuilder::current()->buffer_to_offset((address)(newtop-1));
211 if (delta > AOTCompressedPointers::MaxMetadataOffsetBytes) {
212 // This is just a sanity check and should not appear in any real world usage. This
213 // happens only if you allocate more than 2GB of shared objects and would require
214 // millions of shared classes.
215 aot_log_error(aot)("Out of memory in the %s: Please reduce the number of shared classes.", CDSConfig::type_of_archive_being_written());
216 AOTMetaspace::unrecoverable_writing_error();
217 }
218 }
219
220 return _top;
221 }
222
223 void DumpRegion::commit_to(char* newtop) {
224 assert(CDSConfig::is_dumping_archive(), "sanity");
225 char* base = _rs->base();
226 size_t need_committed_size = newtop - base;
227 size_t has_committed_size = _vs->committed_size();
228 if (need_committed_size < has_committed_size) {
229 return;
230 }
231
232 size_t min_bytes = need_committed_size - has_committed_size;
233 size_t preferred_bytes = 1 * M;
234 size_t uncommitted = _vs->reserved_size() - has_committed_size;
235
236 size_t commit = MAX2(min_bytes, preferred_bytes);
237 commit = MIN2(commit, uncommitted);
238 assert(commit <= uncommitted, "sanity");
239
240 if (!_vs->expand_by(commit, false)) {
241 aot_log_error(aot)("Failed to expand shared space to %zu bytes",
242 need_committed_size);
243 AOTMetaspace::unrecoverable_writing_error();
244 }
245
246 const char* which;
247 if (_rs->base() == (char*)AOTMetaspace::symbol_rs_base()) {
248 which = "symbol";
249 } else {
250 which = "shared";
251 }
252 log_debug(aot)("Expanding %s spaces by %7zu bytes [total %9zu bytes ending at %p]",
253 which, commit, _vs->actual_committed_size(), _vs->high());
254 }
255
256 // Basic allocation. Any alignment gaps will be wasted.
257 char* DumpRegion::allocate(size_t num_bytes, size_t alignment) {
258 // Always align to at least minimum alignment
259 alignment = MAX2(SharedSpaceObjectAlignment, alignment);
260 char* p = (char*)align_up(_top, alignment);
261 char* newtop = p + align_up(num_bytes, SharedSpaceObjectAlignment);
262 expand_top_to(newtop);
263 memset(p, 0, newtop - p);
264 return p;
265 }
266
267 class DumpRegion::AllocGap {
268 size_t _gap_bytes; // size of this gap in bytes
269 char* _gap_bottom; // must be SharedSpaceObjectAlignment aligned
270 public:
271 size_t gap_bytes() const { return _gap_bytes; }
272 char* gap_bottom() const { return _gap_bottom; }
273
274 AllocGap(size_t bytes, char* bottom) : _gap_bytes(bytes), _gap_bottom(bottom) {
275 precond(is_aligned(gap_bytes(), SharedSpaceObjectAlignment));
276 precond(is_aligned(gap_bottom(), SharedSpaceObjectAlignment));
277 }
278 };
279
280 struct DumpRegion::AllocGapCmp {
281 static RBTreeOrdering cmp(AllocGap a, AllocGap b) {
282 RBTreeOrdering order = rbtree_primitive_cmp(a.gap_bytes(), b.gap_bytes());
283 if (order == RBTreeOrdering::EQ) {
284 order = rbtree_primitive_cmp(a.gap_bottom(), b.gap_bottom());
285 }
286 return order;
287 }
288 };
289
290 struct Empty {};
291 using AllocGapNode = RBNode<DumpRegion::AllocGap, Empty>;
292
293 class DumpRegion::AllocGapTree : public RBTreeCHeap<AllocGap, Empty, AllocGapCmp, mtClassShared> {
294 public:
295 size_t add_gap(char* gap_bottom, char* gap_top) {
296 precond(gap_bottom < gap_top);
297 size_t gap_bytes = pointer_delta(gap_top, gap_bottom, 1);
298 precond(gap_bytes > 0);
299
300 _total_gap_bytes += gap_bytes;
301
302 AllocGap gap(gap_bytes, gap_bottom); // constructor checks alignment
303 AllocGapNode* node = allocate_node(gap, Empty{});
304 insert(gap, node);
305
306 log_trace(aot, alloc)("adding a gap of %zu bytes @ %p (total = %zu, used = %zu) in %zu blocks",
307 gap_bytes, gap_bottom, _total_gap_bytes, _total_gap_bytes_used, size());
308 return gap_bytes;
309 }
310
311 char* allocate_from_gap(size_t num_bytes) {
312 // The gaps are sorted in ascending order of their sizes. When two gaps have the same
313 // size, the one with a lower gap_bottom comes first.
314 //
315 // Find the first gap that's big enough, with the lowest gap_bottom.
316 AllocGap target(num_bytes, nullptr);
317 AllocGapNode* node = closest_ge(target);
318 if (node == nullptr) {
319 return nullptr; // Didn't find any usable gap.
320 }
321
322 size_t gap_bytes = node->key().gap_bytes();
323 char* gap_bottom = node->key().gap_bottom();
324 char* result = gap_bottom;
325 precond(is_aligned(result, SharedSpaceObjectAlignment));
326
327 remove(node);
328
329 _total_gap_bytes_used += num_bytes;
330 _total_gap_allocs++;
331 DEBUG_ONLY(node = nullptr); // Don't use it anymore!
332
333 precond(gap_bytes >= num_bytes);
334 if (gap_bytes > num_bytes) {
335 AllocGap gap(gap_bytes - num_bytes, gap_bottom + num_bytes); // constructor checks alignment
336 AllocGapNode* new_node = allocate_node(gap, Empty{});
337 insert(gap, new_node);
338 }
339 size_t unfilled_bytes = _total_gap_bytes - _total_gap_bytes_used;
340 log_trace(aot, alloc)("%zu bytes @ %p in a gap of %zu bytes (used gaps %zu times, remain gap = %zu bytes in %zu blocks)",
341 num_bytes, result, gap_bytes, _total_gap_allocs, unfilled_bytes, size());
342 return result;
343 }
344 };
345
346 size_t DumpRegion::_total_gap_bytes = 0; // All the gaps that have ever been created
347 size_t DumpRegion::_total_gap_bytes_used = 0; // All the gaps that have been used
348 size_t DumpRegion::_total_gap_allocs = 0;
349 DumpRegion::AllocGapTree DumpRegion::_gap_tree;
350
351 // Alignment gaps happen only for the RW space. Collect the gaps into the _gap_tree so they can be
352 // used for future small object allocation.
353 char* DumpRegion::allocate_metaspace_obj(size_t num_bytes, address src, MetaspaceClosureType type, bool read_only, DumpAllocStats* stats) {
354 num_bytes = align_up(num_bytes, SharedSpaceObjectAlignment);
355 size_t alignment = SharedSpaceObjectAlignment; // alignment for the dest pointer
356 bool is_class = (type == MetaspaceClosureType::ClassType);
357 bool is_instance_class = is_class && ((Klass*)src)->is_instance_klass();
358
359 #ifdef _LP64
360 // More strict alignments needed for Klass objects
361 if (is_class) {
362 size_t klass_alignment = checked_cast<size_t>(nth_bit(ArchiveBuilder::precomputed_narrow_klass_shift()));
363 alignment = MAX2(alignment, klass_alignment);
364 precond(is_aligned(alignment, SharedSpaceObjectAlignment));
365 }
366 #endif
367
368 if (alignment == SharedSpaceObjectAlignment && type != MetaspaceClosureType::SymbolType) {
369 // The addresses of Symbols must be in the same order as they are in ArchiveBuilder::SourceObjList.
370 // If we put them in gaps, their order will change.
371 //
372 // We have enough small objects that all gaps are usually filled.
373 char* p = _gap_tree.allocate_from_gap(num_bytes);
374 if (p != nullptr) {
375 // Already memset to 0 when adding the gap
376 stats->record(type, checked_cast<int>(num_bytes), /*read_only=*/false); // all gaps are from RW space (for classes)
377 return p;
378 }
379 }
380
381 // Reserve space for a pointer directly in front of the buffered InstanceKlass, so
382 // we can do a quick lookup from InstanceKlass* -> RunTimeClassInfo*
383 // without building another hashtable. See RunTimeClassInfo::get_for()
384 // in systemDictionaryShared.cpp.
385 const size_t RuntimeClassInfoPtrSize = is_instance_class ? sizeof(address) : 0;
386
387 if (is_class && !is_aligned(top() + RuntimeClassInfoPtrSize, alignment)) {
388 // We need to add a gap to align the buffered Klass. Save the gap for future small allocations.
389 assert(read_only == false, "only gaps in RW region are reusable");
390 char* gap_bottom = top();
391 char* gap_top = align_up(gap_bottom + RuntimeClassInfoPtrSize, alignment) - RuntimeClassInfoPtrSize;
392 size_t gap_bytes = _gap_tree.add_gap(gap_bottom, gap_top);
393 allocate(gap_bytes);
394 }
395
396 char* oldtop = top();
397 if (is_instance_class) {
398 SystemDictionaryShared::validate_before_archiving((InstanceKlass*)src);
399 allocate(RuntimeClassInfoPtrSize);
400 }
401
402 precond(is_aligned(top(), alignment));
403 char* result = allocate(num_bytes);
404 log_trace(aot, alloc)("%zu bytes @ %p", num_bytes, result);
405 stats->record(type, pointer_delta_as_int(top(), oldtop), read_only); // includes RuntimeClassInfoPtrSize for classes
406
407 return result;
408 }
409
410 // Usually we have no gaps left.
411 void DumpRegion::report_gaps(DumpAllocStats* stats) {
412 _gap_tree.visit_in_order([&](const AllocGapNode* node) {
413 stats->record_gap(checked_cast<int>(node->key().gap_bytes()));
414 return true;
415 });
416
417 double unfilled_percent = 0.0;
418 size_t unfilled_bytes = _total_gap_bytes - _total_gap_bytes_used;
419 if (_gap_tree.size() > 0) {
420 unfilled_percent = percent_of(unfilled_bytes, _total_gap_bytes);
421 if (unfilled_percent > 5.0) {
422 // We have a limited number of small objects, so some small gaps may remain
423 // unfilled. If more than 5% of the gaps are unfilled, this likely indicates
424 // a systematic error that should be investigated. Otherwise, do not warn to
425 // avoid noise.
426 log_warning(aot)("Unexpected %zu gaps (%zu bytes, %.2f%%) for Klass alignment",
427 _gap_tree.size(), _total_gap_bytes, unfilled_percent);
428 }
429 }
430 if (_total_gap_allocs > 0) {
431 log_info(aot)("Allocated %zu objects of %zu bytes in gaps (remain = %zu bytes, %.2f%%)",
432 _total_gap_allocs, _total_gap_bytes_used, unfilled_bytes, unfilled_percent);
433 }
434 }
435
436 void DumpRegion::append_intptr_t(intptr_t n, bool need_to_mark) {
437 assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment");
438 intptr_t *p = (intptr_t*)_top;
439 char* newtop = _top + sizeof(intptr_t);
440 expand_top_to(newtop);
441 *p = n;
442 if (need_to_mark) {
443 ArchivePtrMarker::mark_pointer(p);
444 }
445 }
446
447 void DumpRegion::print(size_t total_bytes) const {
448 char* base = used() > 0 ? ArchiveBuilder::current()->to_requested(_base) : nullptr;
449 log_debug(aot)("%s space: %9zu [ %4.1f%% of total] out of %9zu bytes [%5.1f%% used] at " INTPTR_FORMAT,
450 _name, used(), percent_of(used(), total_bytes), reserved(), percent_of(used(), reserved()),
451 p2i(base));
452 }
453
454 void DumpRegion::print_out_of_space_msg(const char* failing_region, size_t needed_bytes) {
455 aot_log_error(aot)("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d",
456 _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base));
457 if (strcmp(_name, failing_region) == 0) {
458 aot_log_error(aot)(" required = %d", int(needed_bytes));
459 }
460 }
461
462 void DumpRegion::init(ReservedSpace* rs, VirtualSpace* vs) {
463 _rs = rs;
464 _vs = vs;
465 // Start with 0 committed bytes. The memory will be committed as needed.
466 if (!_vs->initialize(*_rs, 0)) {
467 fatal("Unable to allocate memory for shared space");
468 }
469 _base = _top = _rs->base();
470 _end = _rs->end();
471 }
472
473 void DumpRegion::pack(DumpRegion* next) {
474 if (!is_packed()) {
475 _end = (char*)align_up(_top, AOTMetaspace::core_region_alignment());
476 _is_packed = true;
477 }
478 _end = (char*)align_up(_top, AOTMetaspace::core_region_alignment());
479 _is_packed = true;
480 if (next != nullptr) {
481 next->_rs = _rs;
482 next->_vs = _vs;
483 next->_base = next->_top = this->_end;
484 next->_end = _rs->end();
485 }
486 }
487
488 void WriteClosure::do_ptr(void** p) {
489 address ptr = *(address*)p;
490 AOTCompressedPointers::narrowPtr narrowp = AOTCompressedPointers::encode(ptr);
491 _dump_region->append_intptr_t(checked_cast<intptr_t>(narrowp), false);
492 }
493
494 void ReadClosure::do_ptr(void** p) {
495 assert(*p == nullptr, "initializing previous initialized pointer.");
496 u4 narrowp = checked_cast<u4>(nextPtr());
497 *p = AOTCompressedPointers::decode<void*>(cast_from_u4(narrowp), _base_address);
498 }
499
500 void ReadClosure::do_u4(u4* p) {
501 intptr_t obj = nextPtr();
502 *p = (u4)(uintx(obj));
503 }
504
505 void ReadClosure::do_int(int* p) {
506 intptr_t obj = nextPtr();
507 *p = (int)(intx(obj));
508 }
509
510 void ReadClosure::do_bool(bool* p) {
511 intptr_t obj = nextPtr();
512 *p = (bool)(uintx(obj));
513 }
514
515 void ReadClosure::do_tag(int tag) {
516 int old_tag;
517 old_tag = (int)(intptr_t)nextPtr();
518 // do_int(&old_tag);
519 assert(tag == old_tag, "tag doesn't match (%d, expected %d)", old_tag, tag);
520 FileMapInfo::assert_mark(tag == old_tag);
521 }
522
523 void ArchiveUtils::log_to_classlist(BootstrapInfo* bootstrap_specifier, TRAPS) {
524 if (ClassListWriter::is_enabled()) {
525 if (LambdaProxyClassDictionary::is_supported_invokedynamic(bootstrap_specifier)) {
526 const constantPoolHandle& pool = bootstrap_specifier->pool();
527 if (SystemDictionaryShared::is_builtin_loader(pool->pool_holder()->class_loader_data())) {
528 // Currently lambda proxy classes are supported only for the built-in loaders.
529 ResourceMark rm(THREAD);
530 int pool_index = bootstrap_specifier->bss_index();
531 ClassListWriter w;
532 w.stream()->print("%s %s", ClassListParser::lambda_proxy_tag(), pool->pool_holder()->name()->as_C_string());
533 CDSIndyInfo cii;
534 ClassListParser::populate_cds_indy_info(pool, pool_index, &cii, CHECK);
535 GrowableArray<const char*>* indy_items = cii.items();
536 for (int i = 0; i < indy_items->length(); i++) {
537 w.stream()->print(" %s", indy_items->at(i));
538 }
539 w.stream()->cr();
540 }
541 }
542 }
543 }
544
545 bool ArchiveUtils::has_aot_initialized_mirror(InstanceKlass* src_ik) {
546 if (!ArchiveBuilder::current()->has_been_archived(src_ik)) {
547 return false;
548 }
549 return ArchiveBuilder::current()->get_buffered_addr(src_ik)->has_aot_initialized_mirror();
550 }
551
552 size_t HeapRootSegments::size_in_bytes(size_t seg_idx) {
553 assert(seg_idx < _count, "In range");
554 return objArrayOopDesc::object_size(size_in_elems(seg_idx)) * HeapWordSize;
555 }
556
557 int HeapRootSegments::size_in_elems(size_t seg_idx) {
558 assert(seg_idx < _count, "In range");
559 if (seg_idx != _count - 1) {
560 return _max_size_in_elems;
561 } else {
562 // Last slice, leftover
563 return _roots_count % _max_size_in_elems;
564 }
565 }
566
567 size_t HeapRootSegments::segment_offset(size_t seg_idx) {
568 assert(seg_idx < _count, "In range");
569 return _base_offset + seg_idx * _max_size_in_bytes;
570 }
571
572 ArchiveWorkers::ArchiveWorkers() :
573 _end_semaphore(0),
574 _num_workers(max_workers()),
575 _started_workers(0),
576 _finish_tokens(0),
577 _state(UNUSED),
578 _task(nullptr) {}
579
580 ArchiveWorkers::~ArchiveWorkers() {
581 assert(AtomicAccess::load(&_state) != WORKING, "Should not be working");
582 }
583
584 int ArchiveWorkers::max_workers() {
585 // The pool is used for short-lived bursty tasks. We do not want to spend
586 // too much time creating and waking up threads unnecessarily. Plus, we do
587 // not want to overwhelm large machines. This is why we want to be very
588 // conservative about the number of workers actually needed.
589 return MAX2(0, log2i_graceful(os::active_processor_count()));
590 }
591
592 bool ArchiveWorkers::is_parallel() {
593 return _num_workers > 0;
594 }
595
596 void ArchiveWorkers::start_worker_if_needed() {
597 while (true) {
598 int cur = AtomicAccess::load(&_started_workers);
599 if (cur >= _num_workers) {
600 return;
601 }
602 if (AtomicAccess::cmpxchg(&_started_workers, cur, cur + 1, memory_order_relaxed) == cur) {
603 new ArchiveWorkerThread(this);
604 return;
605 }
606 }
607 }
608
609 void ArchiveWorkers::run_task(ArchiveWorkerTask* task) {
610 assert(AtomicAccess::load(&_state) == UNUSED, "Should be unused yet");
611 assert(AtomicAccess::load(&_task) == nullptr, "Should not have running tasks");
612 AtomicAccess::store(&_state, WORKING);
613
614 if (is_parallel()) {
615 run_task_multi(task);
616 } else {
617 run_task_single(task);
618 }
619
620 assert(AtomicAccess::load(&_state) == WORKING, "Should be working");
621 AtomicAccess::store(&_state, SHUTDOWN);
622 }
623
624 void ArchiveWorkers::run_task_single(ArchiveWorkerTask* task) {
625 // Single thread needs no chunking.
626 task->configure_max_chunks(1);
627
628 // Execute the task ourselves, as there are no workers.
629 task->work(0, 1);
630 }
631
632 void ArchiveWorkers::run_task_multi(ArchiveWorkerTask* task) {
633 // Multiple threads can work with multiple chunks.
634 task->configure_max_chunks(_num_workers * CHUNKS_PER_WORKER);
635
636 // Set up the run and publish the task. Issue one additional finish token
637 // to cover the semaphore shutdown path, see below.
638 AtomicAccess::store(&_finish_tokens, _num_workers + 1);
639 AtomicAccess::release_store(&_task, task);
640
641 // Kick off pool startup by starting a single worker, and proceed
642 // immediately to executing the task locally.
643 start_worker_if_needed();
644
645 // Execute the task ourselves, while workers are catching up.
646 // This allows us to hide parts of task handoff latency.
647 task->run();
648
649 // Done executing task locally, wait for any remaining workers to complete.
650 // Once all workers report, we can proceed to termination. To do this safely,
651 // we need to make sure every worker has left. A spin-wait alone would suffice,
652 // but we do not want to burn cycles on it. A semaphore alone would not be safe,
653 // since workers can still be inside it as we proceed from wait here. So we block
654 // on semaphore first, and then spin-wait for all workers to terminate.
655 _end_semaphore.wait();
656 SpinYield spin;
657 while (AtomicAccess::load(&_finish_tokens) != 0) {
658 spin.wait();
659 }
660
661 OrderAccess::fence();
662
663 assert(AtomicAccess::load(&_finish_tokens) == 0, "All tokens are consumed");
664 }
665
666 void ArchiveWorkers::run_as_worker() {
667 assert(is_parallel(), "Should be in parallel mode");
668
669 ArchiveWorkerTask* task = AtomicAccess::load_acquire(&_task);
670 task->run();
671
672 // All work done in threads should be visible to caller.
673 OrderAccess::fence();
674
675 // Signal the pool the work is complete, and we are exiting.
676 // Worker cannot do anything else with the pool after this.
677 if (AtomicAccess::sub(&_finish_tokens, 1, memory_order_relaxed) == 1) {
678 // Last worker leaving. Notify the pool it can unblock to spin-wait.
679 // Then consume the last token and leave.
680 _end_semaphore.signal();
681 int last = AtomicAccess::sub(&_finish_tokens, 1, memory_order_relaxed);
682 assert(last == 0, "Should be");
683 }
684 }
685
686 void ArchiveWorkerTask::run() {
687 while (true) {
688 int chunk = AtomicAccess::load(&_chunk);
689 if (chunk >= _max_chunks) {
690 return;
691 }
692 if (AtomicAccess::cmpxchg(&_chunk, chunk, chunk + 1, memory_order_relaxed) == chunk) {
693 assert(0 <= chunk && chunk < _max_chunks, "Sanity");
694 work(chunk, _max_chunks);
695 }
696 }
697 }
698
699 void ArchiveWorkerTask::configure_max_chunks(int max_chunks) {
700 if (_max_chunks == 0) {
701 _max_chunks = max_chunks;
702 }
703 }
704
705 ArchiveWorkerThread::ArchiveWorkerThread(ArchiveWorkers* pool) : NamedThread(), _pool(pool) {
706 set_name("ArchiveWorkerThread");
707 if (os::create_thread(this, os::os_thread)) {
708 os::start_thread(this);
709 } else {
710 vm_exit_during_initialization("Unable to create archive worker",
711 os::native_thread_creation_failed_msg());
712 }
713 }
714
715 void ArchiveWorkerThread::run() {
716 // Avalanche startup: each worker starts two others.
717 _pool->start_worker_if_needed();
718 _pool->start_worker_if_needed();
719
720 // Set ourselves up.
721 os::set_priority(this, NearMaxPriority);
722
723 // Work.
724 _pool->run_as_worker();
725 }
726
727 void ArchiveWorkerThread::post_run() {
728 this->NamedThread::post_run();
729 delete this;
730 }