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 UseCompressedClassPointers
364 if (is_class && UseCompressedClassPointers) {
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 if (_gap_tree.size() > 0) {
420 log_warning(aot)("Unexpected %zu gaps (%zu bytes) for Klass alignment",
421 _gap_tree.size(), _total_gap_bytes);
422 }
423 if (_total_gap_allocs > 0) {
424 log_info(aot)("Allocated %zu objects of %zu bytes in gaps (remain = %zu bytes)",
425 _total_gap_allocs, _total_gap_bytes_used, _total_gap_bytes);
426 }
427 }
428
429 void DumpRegion::append_intptr_t(intptr_t n, bool need_to_mark) {
430 assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment");
431 intptr_t *p = (intptr_t*)_top;
432 char* newtop = _top + sizeof(intptr_t);
433 expand_top_to(newtop);
434 *p = n;
435 if (need_to_mark) {
436 ArchivePtrMarker::mark_pointer(p);
437 }
438 }
439
440 void DumpRegion::print(size_t total_bytes) const {
441 char* base = used() > 0 ? ArchiveBuilder::current()->to_requested(_base) : nullptr;
442 log_debug(aot)("%s space: %9zu [ %4.1f%% of total] out of %9zu bytes [%5.1f%% used] at " INTPTR_FORMAT,
443 _name, used(), percent_of(used(), total_bytes), reserved(), percent_of(used(), reserved()),
444 p2i(base));
445 }
446
447 void DumpRegion::print_out_of_space_msg(const char* failing_region, size_t needed_bytes) {
448 aot_log_error(aot)("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d",
449 _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base));
450 if (strcmp(_name, failing_region) == 0) {
451 aot_log_error(aot)(" required = %d", int(needed_bytes));
452 }
453 }
454
455 void DumpRegion::init(ReservedSpace* rs, VirtualSpace* vs) {
456 _rs = rs;
457 _vs = vs;
458 // Start with 0 committed bytes. The memory will be committed as needed.
459 if (!_vs->initialize(*_rs, 0)) {
460 fatal("Unable to allocate memory for shared space");
461 }
462 _base = _top = _rs->base();
463 _end = _rs->end();
464 }
465
466 void DumpRegion::pack(DumpRegion* next) {
467 if (!is_packed()) {
468 _end = (char*)align_up(_top, AOTMetaspace::core_region_alignment());
469 _is_packed = true;
470 }
471 _end = (char*)align_up(_top, AOTMetaspace::core_region_alignment());
472 _is_packed = true;
473 if (next != nullptr) {
474 next->_rs = _rs;
475 next->_vs = _vs;
476 next->_base = next->_top = this->_end;
477 next->_end = _rs->end();
478 }
479 }
480
481 void WriteClosure::do_ptr(void** p) {
482 address ptr = *(address*)p;
483 AOTCompressedPointers::narrowPtr narrowp = AOTCompressedPointers::encode(ptr);
484 _dump_region->append_intptr_t(checked_cast<intptr_t>(narrowp), false);
485 }
486
487 void ReadClosure::do_ptr(void** p) {
488 assert(*p == nullptr, "initializing previous initialized pointer.");
489 u4 narrowp = checked_cast<u4>(nextPtr());
490 *p = AOTCompressedPointers::decode<void*>(cast_from_u4(narrowp), _base_address);
491 }
492
493 void ReadClosure::do_u4(u4* p) {
494 intptr_t obj = nextPtr();
495 *p = (u4)(uintx(obj));
496 }
497
498 void ReadClosure::do_int(int* p) {
499 intptr_t obj = nextPtr();
500 *p = (int)(intx(obj));
501 }
502
503 void ReadClosure::do_bool(bool* p) {
504 intptr_t obj = nextPtr();
505 *p = (bool)(uintx(obj));
506 }
507
508 void ReadClosure::do_tag(int tag) {
509 int old_tag;
510 old_tag = (int)(intptr_t)nextPtr();
511 // do_int(&old_tag);
512 assert(tag == old_tag, "tag doesn't match (%d, expected %d)", old_tag, tag);
513 FileMapInfo::assert_mark(tag == old_tag);
514 }
515
516 void ArchiveUtils::log_to_classlist(BootstrapInfo* bootstrap_specifier, TRAPS) {
517 if (ClassListWriter::is_enabled()) {
518 if (LambdaProxyClassDictionary::is_supported_invokedynamic(bootstrap_specifier)) {
519 const constantPoolHandle& pool = bootstrap_specifier->pool();
520 if (SystemDictionaryShared::is_builtin_loader(pool->pool_holder()->class_loader_data())) {
521 // Currently lambda proxy classes are supported only for the built-in loaders.
522 ResourceMark rm(THREAD);
523 int pool_index = bootstrap_specifier->bss_index();
524 ClassListWriter w;
525 w.stream()->print("%s %s", ClassListParser::lambda_proxy_tag(), pool->pool_holder()->name()->as_C_string());
526 CDSIndyInfo cii;
527 ClassListParser::populate_cds_indy_info(pool, pool_index, &cii, CHECK);
528 GrowableArray<const char*>* indy_items = cii.items();
529 for (int i = 0; i < indy_items->length(); i++) {
530 w.stream()->print(" %s", indy_items->at(i));
531 }
532 w.stream()->cr();
533 }
534 }
535 }
536 }
537
538 bool ArchiveUtils::has_aot_initialized_mirror(InstanceKlass* src_ik) {
539 if (!ArchiveBuilder::current()->has_been_archived(src_ik)) {
540 return false;
541 }
542 return ArchiveBuilder::current()->get_buffered_addr(src_ik)->has_aot_initialized_mirror();
543 }
544
545 size_t HeapRootSegments::size_in_bytes(size_t seg_idx) {
546 assert(seg_idx < _count, "In range");
547 return objArrayOopDesc::object_size(size_in_elems(seg_idx)) * HeapWordSize;
548 }
549
550 int HeapRootSegments::size_in_elems(size_t seg_idx) {
551 assert(seg_idx < _count, "In range");
552 if (seg_idx != _count - 1) {
553 return _max_size_in_elems;
554 } else {
555 // Last slice, leftover
556 return _roots_count % _max_size_in_elems;
557 }
558 }
559
560 size_t HeapRootSegments::segment_offset(size_t seg_idx) {
561 assert(seg_idx < _count, "In range");
562 return _base_offset + seg_idx * _max_size_in_bytes;
563 }
564
565 ArchiveWorkers::ArchiveWorkers() :
566 _end_semaphore(0),
567 _num_workers(max_workers()),
568 _started_workers(0),
569 _finish_tokens(0),
570 _state(UNUSED),
571 _task(nullptr) {}
572
573 ArchiveWorkers::~ArchiveWorkers() {
574 assert(AtomicAccess::load(&_state) != WORKING, "Should not be working");
575 }
576
577 int ArchiveWorkers::max_workers() {
578 // The pool is used for short-lived bursty tasks. We do not want to spend
579 // too much time creating and waking up threads unnecessarily. Plus, we do
580 // not want to overwhelm large machines. This is why we want to be very
581 // conservative about the number of workers actually needed.
582 return MAX2(0, log2i_graceful(os::active_processor_count()));
583 }
584
585 bool ArchiveWorkers::is_parallel() {
586 return _num_workers > 0;
587 }
588
589 void ArchiveWorkers::start_worker_if_needed() {
590 while (true) {
591 int cur = AtomicAccess::load(&_started_workers);
592 if (cur >= _num_workers) {
593 return;
594 }
595 if (AtomicAccess::cmpxchg(&_started_workers, cur, cur + 1, memory_order_relaxed) == cur) {
596 new ArchiveWorkerThread(this);
597 return;
598 }
599 }
600 }
601
602 void ArchiveWorkers::run_task(ArchiveWorkerTask* task) {
603 assert(AtomicAccess::load(&_state) == UNUSED, "Should be unused yet");
604 assert(AtomicAccess::load(&_task) == nullptr, "Should not have running tasks");
605 AtomicAccess::store(&_state, WORKING);
606
607 if (is_parallel()) {
608 run_task_multi(task);
609 } else {
610 run_task_single(task);
611 }
612
613 assert(AtomicAccess::load(&_state) == WORKING, "Should be working");
614 AtomicAccess::store(&_state, SHUTDOWN);
615 }
616
617 void ArchiveWorkers::run_task_single(ArchiveWorkerTask* task) {
618 // Single thread needs no chunking.
619 task->configure_max_chunks(1);
620
621 // Execute the task ourselves, as there are no workers.
622 task->work(0, 1);
623 }
624
625 void ArchiveWorkers::run_task_multi(ArchiveWorkerTask* task) {
626 // Multiple threads can work with multiple chunks.
627 task->configure_max_chunks(_num_workers * CHUNKS_PER_WORKER);
628
629 // Set up the run and publish the task. Issue one additional finish token
630 // to cover the semaphore shutdown path, see below.
631 AtomicAccess::store(&_finish_tokens, _num_workers + 1);
632 AtomicAccess::release_store(&_task, task);
633
634 // Kick off pool startup by starting a single worker, and proceed
635 // immediately to executing the task locally.
636 start_worker_if_needed();
637
638 // Execute the task ourselves, while workers are catching up.
639 // This allows us to hide parts of task handoff latency.
640 task->run();
641
642 // Done executing task locally, wait for any remaining workers to complete.
643 // Once all workers report, we can proceed to termination. To do this safely,
644 // we need to make sure every worker has left. A spin-wait alone would suffice,
645 // but we do not want to burn cycles on it. A semaphore alone would not be safe,
646 // since workers can still be inside it as we proceed from wait here. So we block
647 // on semaphore first, and then spin-wait for all workers to terminate.
648 _end_semaphore.wait();
649 SpinYield spin;
650 while (AtomicAccess::load(&_finish_tokens) != 0) {
651 spin.wait();
652 }
653
654 OrderAccess::fence();
655
656 assert(AtomicAccess::load(&_finish_tokens) == 0, "All tokens are consumed");
657 }
658
659 void ArchiveWorkers::run_as_worker() {
660 assert(is_parallel(), "Should be in parallel mode");
661
662 ArchiveWorkerTask* task = AtomicAccess::load_acquire(&_task);
663 task->run();
664
665 // All work done in threads should be visible to caller.
666 OrderAccess::fence();
667
668 // Signal the pool the work is complete, and we are exiting.
669 // Worker cannot do anything else with the pool after this.
670 if (AtomicAccess::sub(&_finish_tokens, 1, memory_order_relaxed) == 1) {
671 // Last worker leaving. Notify the pool it can unblock to spin-wait.
672 // Then consume the last token and leave.
673 _end_semaphore.signal();
674 int last = AtomicAccess::sub(&_finish_tokens, 1, memory_order_relaxed);
675 assert(last == 0, "Should be");
676 }
677 }
678
679 void ArchiveWorkerTask::run() {
680 while (true) {
681 int chunk = AtomicAccess::load(&_chunk);
682 if (chunk >= _max_chunks) {
683 return;
684 }
685 if (AtomicAccess::cmpxchg(&_chunk, chunk, chunk + 1, memory_order_relaxed) == chunk) {
686 assert(0 <= chunk && chunk < _max_chunks, "Sanity");
687 work(chunk, _max_chunks);
688 }
689 }
690 }
691
692 void ArchiveWorkerTask::configure_max_chunks(int max_chunks) {
693 if (_max_chunks == 0) {
694 _max_chunks = max_chunks;
695 }
696 }
697
698 ArchiveWorkerThread::ArchiveWorkerThread(ArchiveWorkers* pool) : NamedThread(), _pool(pool) {
699 set_name("ArchiveWorkerThread");
700 if (os::create_thread(this, os::os_thread)) {
701 os::start_thread(this);
702 } else {
703 vm_exit_during_initialization("Unable to create archive worker",
704 os::native_thread_creation_failed_msg());
705 }
706 }
707
708 void ArchiveWorkerThread::run() {
709 // Avalanche startup: each worker starts two others.
710 _pool->start_worker_if_needed();
711 _pool->start_worker_if_needed();
712
713 // Set ourselves up.
714 os::set_priority(this, NearMaxPriority);
715
716 // Work.
717 _pool->run_as_worker();
718 }
719
720 void ArchiveWorkerThread::post_run() {
721 this->NamedThread::post_run();
722 delete this;
723 }