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) in %zu blocks", gap_bytes, gap_bottom, _total_gap_bytes, size());
307 return gap_bytes;
308 }
309
310 char* allocate_from_gap(size_t num_bytes) {
311 // The gaps are sorted in ascending order of their sizes. When two gaps have the same
312 // size, the one with a lower gap_bottom comes first.
313 //
314 // Find the first gap that's big enough, with the lowest gap_bottom.
315 AllocGap target(num_bytes, nullptr);
316 AllocGapNode* node = closest_ge(target);
317 if (node == nullptr) {
318 return nullptr; // Didn't find any usable gap.
319 }
320
321 size_t gap_bytes = node->key().gap_bytes();
322 char* gap_bottom = node->key().gap_bottom();
323 char* result = gap_bottom;
324 precond(is_aligned(result, SharedSpaceObjectAlignment));
325
326 remove(node);
327
328 precond(_total_gap_bytes >= num_bytes);
329 _total_gap_bytes -= num_bytes;
330 _total_gap_bytes_used += num_bytes;
331 _total_gap_allocs++;
332 DEBUG_ONLY(node = nullptr); // Don't use it anymore!
333
334 precond(gap_bytes >= num_bytes);
335 if (gap_bytes > num_bytes) {
336 gap_bytes -= num_bytes;
337 gap_bottom += num_bytes;
338
339 AllocGap gap(gap_bytes, gap_bottom); // constructor checks alignment
340 AllocGapNode* new_node = allocate_node(gap, Empty{});
341 insert(gap, new_node);
342 }
343 log_trace(aot, alloc)("%zu bytes @ %p in a gap of %zu bytes (used gaps %zu times, remain gap = %zu bytes in %zu blocks)",
344 num_bytes, result, gap_bytes, _total_gap_allocs, _total_gap_bytes, size());
345 return result;
346 }
347 };
348
349 size_t DumpRegion::_total_gap_bytes = 0;
350 size_t DumpRegion::_total_gap_bytes_used = 0;
351 size_t DumpRegion::_total_gap_allocs = 0;
352 DumpRegion::AllocGapTree DumpRegion::_gap_tree;
353
354 // Alignment gaps happen only for the RW space. Collect the gaps into the _gap_tree so they can be
355 // used for future small object allocation.
356 char* DumpRegion::allocate_metaspace_obj(size_t num_bytes, address src, MetaspaceClosureType type, bool read_only, DumpAllocStats* stats) {
357 num_bytes = align_up(num_bytes, SharedSpaceObjectAlignment);
358 size_t alignment = SharedSpaceObjectAlignment; // alignment for the dest pointer
359 bool is_class = (type == MetaspaceClosureType::ClassType);
360 bool is_instance_class = is_class && ((Klass*)src)->is_instance_klass();
361
362 #ifdef _LP64
363 // More strict alignments needed for Klass objects
364 if (is_class) {
365 size_t klass_alignment = checked_cast<size_t>(nth_bit(ArchiveBuilder::precomputed_narrow_klass_shift()));
366 alignment = MAX2(alignment, klass_alignment);
367 precond(is_aligned(alignment, SharedSpaceObjectAlignment));
368 }
369 #endif
370
371 if (alignment == SharedSpaceObjectAlignment && type != MetaspaceClosureType::SymbolType) {
372 // The addresses of Symbols must be in the same order as they are in ArchiveBuilder::SourceObjList.
373 // If we put them in gaps, their order will change.
374 //
375 // We have enough small objects that all gaps are usually filled.
376 char* p = _gap_tree.allocate_from_gap(num_bytes);
377 if (p != nullptr) {
378 // Already memset to 0 when adding the gap
379 stats->record(type, checked_cast<int>(num_bytes), /*read_only=*/false); // all gaps are from RW space (for classes)
380 return p;
381 }
382 }
383
384 // Reserve space for a pointer directly in front of the buffered InstanceKlass, so
385 // we can do a quick lookup from InstanceKlass* -> RunTimeClassInfo*
386 // without building another hashtable. See RunTimeClassInfo::get_for()
387 // in systemDictionaryShared.cpp.
388 const size_t RuntimeClassInfoPtrSize = is_instance_class ? sizeof(address) : 0;
389
390 if (is_class && !is_aligned(top() + RuntimeClassInfoPtrSize, alignment)) {
391 // We need to add a gap to align the buffered Klass. Save the gap for future small allocations.
392 assert(read_only == false, "only gaps in RW region are reusable");
393 char* gap_bottom = top();
394 char* gap_top = align_up(gap_bottom + RuntimeClassInfoPtrSize, alignment) - RuntimeClassInfoPtrSize;
395 size_t gap_bytes = _gap_tree.add_gap(gap_bottom, gap_top);
396 allocate(gap_bytes);
397 }
398
399 char* oldtop = top();
400 if (is_instance_class) {
401 SystemDictionaryShared::validate_before_archiving((InstanceKlass*)src);
402 allocate(RuntimeClassInfoPtrSize);
403 }
404
405 precond(is_aligned(top(), alignment));
406 char* result = allocate(num_bytes);
407 log_trace(aot, alloc)("%zu bytes @ %p", num_bytes, result);
408 stats->record(type, pointer_delta_as_int(top(), oldtop), read_only); // includes RuntimeClassInfoPtrSize for classes
409
410 return result;
411 }
412
413 // Usually we have no gaps left.
414 void DumpRegion::report_gaps(DumpAllocStats* stats) {
415 _gap_tree.visit_in_order([&](const AllocGapNode* node) {
416 stats->record_gap(checked_cast<int>(node->key().gap_bytes()));
417 return true;
418 });
419
420 double unfilled_percent = 0.0;
421 if (_gap_tree.size() > 0) {
422 unfilled_percent = percent_of(_total_gap_bytes, _total_gap_allocs);
423 if (unfilled_percent > 5.0) {
424 // We have a limited number of small objects, so some small gaps may remain
425 // unfilled. If more than 5% of the gaps are unfilled, this likely indicates
426 // a systematic error that should be investigated. Otherwise, do not warn to
427 // avoid noise.
428 log_warning(aot)("Unexpected %zu gaps (%zu bytes) for Klass alignment",
429 _gap_tree.size(), _total_gap_bytes);
430 }
431 }
432 if (_total_gap_allocs > 0) {
433 log_info(aot)("Allocated %zu objects of %zu bytes in gaps (remain = %zu bytes, %.2f%%)",
434 _total_gap_allocs, _total_gap_bytes_used, _total_gap_bytes, unfilled_percent);
435 }
436 }
437
438 void DumpRegion::append_intptr_t(intptr_t n, bool need_to_mark) {
439 assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment");
440 intptr_t *p = (intptr_t*)_top;
441 char* newtop = _top + sizeof(intptr_t);
442 expand_top_to(newtop);
443 *p = n;
444 if (need_to_mark) {
445 ArchivePtrMarker::mark_pointer(p);
446 }
447 }
448
449 void DumpRegion::print(size_t total_bytes) const {
450 char* base = used() > 0 ? ArchiveBuilder::current()->to_requested(_base) : nullptr;
451 log_debug(aot)("%s space: %9zu [ %4.1f%% of total] out of %9zu bytes [%5.1f%% used] at " INTPTR_FORMAT,
452 _name, used(), percent_of(used(), total_bytes), reserved(), percent_of(used(), reserved()),
453 p2i(base));
454 }
455
456 void DumpRegion::print_out_of_space_msg(const char* failing_region, size_t needed_bytes) {
457 aot_log_error(aot)("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d",
458 _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base));
459 if (strcmp(_name, failing_region) == 0) {
460 aot_log_error(aot)(" required = %d", int(needed_bytes));
461 }
462 }
463
464 void DumpRegion::init(ReservedSpace* rs, VirtualSpace* vs) {
465 _rs = rs;
466 _vs = vs;
467 // Start with 0 committed bytes. The memory will be committed as needed.
468 if (!_vs->initialize(*_rs, 0)) {
469 fatal("Unable to allocate memory for shared space");
470 }
471 _base = _top = _rs->base();
472 _end = _rs->end();
473 }
474
475 void DumpRegion::pack(DumpRegion* next) {
476 if (!is_packed()) {
477 _end = (char*)align_up(_top, AOTMetaspace::core_region_alignment());
478 _is_packed = true;
479 }
480 _end = (char*)align_up(_top, AOTMetaspace::core_region_alignment());
481 _is_packed = true;
482 if (next != nullptr) {
483 next->_rs = _rs;
484 next->_vs = _vs;
485 next->_base = next->_top = this->_end;
486 next->_end = _rs->end();
487 }
488 }
489
490 void WriteClosure::do_ptr(void** p) {
491 address ptr = *(address*)p;
492 AOTCompressedPointers::narrowPtr narrowp = AOTCompressedPointers::encode(ptr);
493 _dump_region->append_intptr_t(checked_cast<intptr_t>(narrowp), false);
494 }
495
496 void ReadClosure::do_ptr(void** p) {
497 assert(*p == nullptr, "initializing previous initialized pointer.");
498 u4 narrowp = checked_cast<u4>(nextPtr());
499 *p = AOTCompressedPointers::decode<void*>(cast_from_u4(narrowp), _base_address);
500 }
501
502 void ReadClosure::do_u4(u4* p) {
503 intptr_t obj = nextPtr();
504 *p = (u4)(uintx(obj));
505 }
506
507 void ReadClosure::do_int(int* p) {
508 intptr_t obj = nextPtr();
509 *p = (int)(intx(obj));
510 }
511
512 void ReadClosure::do_bool(bool* p) {
513 intptr_t obj = nextPtr();
514 *p = (bool)(uintx(obj));
515 }
516
517 void ReadClosure::do_tag(int tag) {
518 int old_tag;
519 old_tag = (int)(intptr_t)nextPtr();
520 // do_int(&old_tag);
521 assert(tag == old_tag, "tag doesn't match (%d, expected %d)", old_tag, tag);
522 FileMapInfo::assert_mark(tag == old_tag);
523 }
524
525 void ArchiveUtils::log_to_classlist(BootstrapInfo* bootstrap_specifier, TRAPS) {
526 if (ClassListWriter::is_enabled()) {
527 if (LambdaProxyClassDictionary::is_supported_invokedynamic(bootstrap_specifier)) {
528 const constantPoolHandle& pool = bootstrap_specifier->pool();
529 if (SystemDictionaryShared::is_builtin_loader(pool->pool_holder()->class_loader_data())) {
530 // Currently lambda proxy classes are supported only for the built-in loaders.
531 ResourceMark rm(THREAD);
532 int pool_index = bootstrap_specifier->bss_index();
533 ClassListWriter w;
534 w.stream()->print("%s %s", ClassListParser::lambda_proxy_tag(), pool->pool_holder()->name()->as_C_string());
535 CDSIndyInfo cii;
536 ClassListParser::populate_cds_indy_info(pool, pool_index, &cii, CHECK);
537 GrowableArray<const char*>* indy_items = cii.items();
538 for (int i = 0; i < indy_items->length(); i++) {
539 w.stream()->print(" %s", indy_items->at(i));
540 }
541 w.stream()->cr();
542 }
543 }
544 }
545 }
546
547 bool ArchiveUtils::has_aot_initialized_mirror(InstanceKlass* src_ik) {
548 if (!ArchiveBuilder::current()->has_been_archived(src_ik)) {
549 return false;
550 }
551 return ArchiveBuilder::current()->get_buffered_addr(src_ik)->has_aot_initialized_mirror();
552 }
553
554 size_t HeapRootSegments::size_in_bytes(size_t seg_idx) {
555 assert(seg_idx < _count, "In range");
556 return refArrayOopDesc::object_size(size_in_elems(seg_idx)) * HeapWordSize;
557 }
558
559 int HeapRootSegments::size_in_elems(size_t seg_idx) {
560 assert(seg_idx < _count, "In range");
561 if (seg_idx != _count - 1) {
562 return _max_size_in_elems;
563 } else {
564 // Last slice, leftover
565 return _roots_count % _max_size_in_elems;
566 }
567 }
568
569 size_t HeapRootSegments::segment_offset(size_t seg_idx) {
570 assert(seg_idx < _count, "In range");
571 return _base_offset + seg_idx * _max_size_in_bytes;
572 }
573
574 ArchiveWorkers::ArchiveWorkers() :
575 _end_semaphore(0),
576 _num_workers(max_workers()),
577 _started_workers(0),
578 _finish_tokens(0),
579 _state(UNUSED),
580 _task(nullptr) {}
581
582 ArchiveWorkers::~ArchiveWorkers() {
583 assert(AtomicAccess::load(&_state) != WORKING, "Should not be working");
584 }
585
586 int ArchiveWorkers::max_workers() {
587 // The pool is used for short-lived bursty tasks. We do not want to spend
588 // too much time creating and waking up threads unnecessarily. Plus, we do
589 // not want to overwhelm large machines. This is why we want to be very
590 // conservative about the number of workers actually needed.
591 return MAX2(0, log2i_graceful(os::active_processor_count()));
592 }
593
594 bool ArchiveWorkers::is_parallel() {
595 return _num_workers > 0;
596 }
597
598 void ArchiveWorkers::start_worker_if_needed() {
599 while (true) {
600 int cur = AtomicAccess::load(&_started_workers);
601 if (cur >= _num_workers) {
602 return;
603 }
604 if (AtomicAccess::cmpxchg(&_started_workers, cur, cur + 1, memory_order_relaxed) == cur) {
605 new ArchiveWorkerThread(this);
606 return;
607 }
608 }
609 }
610
611 void ArchiveWorkers::run_task(ArchiveWorkerTask* task) {
612 assert(AtomicAccess::load(&_state) == UNUSED, "Should be unused yet");
613 assert(AtomicAccess::load(&_task) == nullptr, "Should not have running tasks");
614 AtomicAccess::store(&_state, WORKING);
615
616 if (is_parallel()) {
617 run_task_multi(task);
618 } else {
619 run_task_single(task);
620 }
621
622 assert(AtomicAccess::load(&_state) == WORKING, "Should be working");
623 AtomicAccess::store(&_state, SHUTDOWN);
624 }
625
626 void ArchiveWorkers::run_task_single(ArchiveWorkerTask* task) {
627 // Single thread needs no chunking.
628 task->configure_max_chunks(1);
629
630 // Execute the task ourselves, as there are no workers.
631 task->work(0, 1);
632 }
633
634 void ArchiveWorkers::run_task_multi(ArchiveWorkerTask* task) {
635 // Multiple threads can work with multiple chunks.
636 task->configure_max_chunks(_num_workers * CHUNKS_PER_WORKER);
637
638 // Set up the run and publish the task. Issue one additional finish token
639 // to cover the semaphore shutdown path, see below.
640 AtomicAccess::store(&_finish_tokens, _num_workers + 1);
641 AtomicAccess::release_store(&_task, task);
642
643 // Kick off pool startup by starting a single worker, and proceed
644 // immediately to executing the task locally.
645 start_worker_if_needed();
646
647 // Execute the task ourselves, while workers are catching up.
648 // This allows us to hide parts of task handoff latency.
649 task->run();
650
651 // Done executing task locally, wait for any remaining workers to complete.
652 // Once all workers report, we can proceed to termination. To do this safely,
653 // we need to make sure every worker has left. A spin-wait alone would suffice,
654 // but we do not want to burn cycles on it. A semaphore alone would not be safe,
655 // since workers can still be inside it as we proceed from wait here. So we block
656 // on semaphore first, and then spin-wait for all workers to terminate.
657 _end_semaphore.wait();
658 SpinYield spin;
659 while (AtomicAccess::load(&_finish_tokens) != 0) {
660 spin.wait();
661 }
662
663 OrderAccess::fence();
664
665 assert(AtomicAccess::load(&_finish_tokens) == 0, "All tokens are consumed");
666 }
667
668 void ArchiveWorkers::run_as_worker() {
669 assert(is_parallel(), "Should be in parallel mode");
670
671 ArchiveWorkerTask* task = AtomicAccess::load_acquire(&_task);
672 task->run();
673
674 // All work done in threads should be visible to caller.
675 OrderAccess::fence();
676
677 // Signal the pool the work is complete, and we are exiting.
678 // Worker cannot do anything else with the pool after this.
679 if (AtomicAccess::sub(&_finish_tokens, 1, memory_order_relaxed) == 1) {
680 // Last worker leaving. Notify the pool it can unblock to spin-wait.
681 // Then consume the last token and leave.
682 _end_semaphore.signal();
683 int last = AtomicAccess::sub(&_finish_tokens, 1, memory_order_relaxed);
684 assert(last == 0, "Should be");
685 }
686 }
687
688 void ArchiveWorkerTask::run() {
689 while (true) {
690 int chunk = AtomicAccess::load(&_chunk);
691 if (chunk >= _max_chunks) {
692 return;
693 }
694 if (AtomicAccess::cmpxchg(&_chunk, chunk, chunk + 1, memory_order_relaxed) == chunk) {
695 assert(0 <= chunk && chunk < _max_chunks, "Sanity");
696 work(chunk, _max_chunks);
697 }
698 }
699 }
700
701 void ArchiveWorkerTask::configure_max_chunks(int max_chunks) {
702 if (_max_chunks == 0) {
703 _max_chunks = max_chunks;
704 }
705 }
706
707 ArchiveWorkerThread::ArchiveWorkerThread(ArchiveWorkers* pool) : NamedThread(), _pool(pool) {
708 set_name("ArchiveWorkerThread");
709 if (os::create_thread(this, os::os_thread)) {
710 os::start_thread(this);
711 } else {
712 vm_exit_during_initialization("Unable to create archive worker",
713 os::native_thread_creation_failed_msg());
714 }
715 }
716
717 void ArchiveWorkerThread::run() {
718 // Avalanche startup: each worker starts two others.
719 _pool->start_worker_if_needed();
720 _pool->start_worker_if_needed();
721
722 // Set ourselves up.
723 os::set_priority(this, NearMaxPriority);
724
725 // Work.
726 _pool->run_as_worker();
727 }
728
729 void ArchiveWorkerThread::post_run() {
730 this->NamedThread::post_run();
731 delete this;
732 }