jam 0.0.1
A compacting generational garbage collector for C++26
Loading...
Searching...
No Matches
mapping_impl.cc
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Edward Kmett <ekmett@gmail.com>
2// SPDX-License-Identifier: BSD-2-Clause OR Apache-2.0
3
6module;
7#if defined(__linux__) && !defined(_GNU_SOURCE)
8#define _GNU_SOURCE
9#endif
10#include <hint.h>
11#include <cstdio>
12#include <cstdlib>
13#include <algorithm>
14#include <cassert>
15#include <cerrno>
16#include <cstddef>
17#include <limits>
18#include <memory>
19#include <utility>
20#include <vector>
21#if defined(_WIN32)
22#define WIN32_LEAN_AND_MEAN
23#define NOMINMAX
24#include <windows.h>
25#else
26#include <sys/mman.h>
27#include <unistd.h>
28#endif
29#if defined(__APPLE__)
30#include <mach/mach.h>
31#include <mach/mach_vm.h>
32#elif !defined(__linux__) && !defined(_WIN32)
33#error "jam requires macOS, Linux or Windows virtual-memory aliases"
34#endif
35
36#include <cstdint>
37
38module jam.mapping;
39
40namespace jam::detail {
41#if defined(_WIN32)
42struct heap_mapping::backing {
43 HANDLE handle;
44 explicit backing(std::size_t bytes) noexcept
45 : handle(::CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
46 static_cast<DWORD>(bytes >> 32), static_cast<DWORD>(bytes), nullptr)) {
47 if (!handle) system_failure("create heap backing");
48 }
49 ~backing() noexcept { ::CloseHandle(handle); }
50};
51#endif
52
53hint_cold hint_noreturn
54void heap_failure(char const * operation, int code) noexcept {
55 std::fprintf(stderr, "jam: %s (%d)\n", operation, code);
56 std::abort();
57}
58
59generation_reservation::generation_reservation(std::size_t old_maximum, std::size_t young_maximum) noexcept
60 : bytes_(2 * (old_maximum + young_maximum)) {
61#if defined(_WIN32)
62 base_ = static_cast<std::byte *>(::VirtualAlloc2(nullptr, nullptr, bytes_,
63 MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0));
64 if (!base_) heap_failure("reserve generation address space", ::GetLastError());
65#else
66 auto * p = ::mmap(nullptr, bytes_, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
67 if (p == MAP_FAILED) heap_failure("reserve generation address space", errno);
68 base_ = static_cast<std::byte *>(p);
69#endif
70}
71
72generation_reservation::~generation_reservation() noexcept {
73#if defined(_WIN32)
74 MEMORY_BASIC_INFORMATION region{};
75 if (!::VirtualQuery(base_, &region, sizeof(region))) heap_failure("query generation reservation", ::GetLastError());
76 if (region.RegionSize != bytes_ &&
77 !::VirtualFree(base_, bytes_, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS))
78 heap_failure("coalesce generation reservation", ::GetLastError());
79 if (!::VirtualFree(base_, 0, MEM_RELEASE)) heap_failure("release generation reservation", ::GetLastError());
80#else
81 if (::munmap(base_, bytes_)) heap_failure("release generation reservation", errno);
82#endif
83}
84
85[[noreturn]] void heap_mapping::system_failure(char const * operation) noexcept {
86#if defined(_WIN32)
87 heap_failure(operation, static_cast<int>(::GetLastError()));
88#else
89 heap_failure(operation, errno);
90#endif
91}
92
93void heap_mapping::validate_size(std::size_t bytes) noexcept {
94 if (!bytes || bytes % page_size() || bytes > std::numeric_limits<std::size_t>::max() / 2)
95 heap_failure("capacity must be a nonzero whole-page size");
96}
97
98heap_mapping::heap_mapping(reservation, std::size_t bytes) noexcept {
99 validate_size(bytes);
100#if defined(_WIN32)
101 auto const result = ::VirtualAlloc2(nullptr, nullptr, bytes * 2,
102 MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0);
103 if (!result) system_failure("reserve heap placeholders");
104#else
105 auto const result = ::mmap(nullptr, bytes * 2, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
106 if (result == MAP_FAILED) system_failure("jam: reserve virtual memory");
107#endif
108 address = static_cast<std::byte *>(result);
109 capacity = bytes;
110}
111
112#if defined(_WIN32)
113void heap_mapping::alias(span const & source, std::byte * target, std::size_t count,
114 std::size_t offset) noexcept {
115 MEMORY_BASIC_INFORMATION region{};
116 if (!::VirtualQuery(target, &region, sizeof(region))) system_failure("query heap placeholder");
117 // VirtualQuery starts at the queried page, which can be inside a placeholder.
118 // Query its allocation base before deciding whether either end needs splitting.
119 if (region.State == MEM_RESERVE && region.BaseAddress != region.AllocationBase &&
120 !::VirtualQuery(region.AllocationBase, &region, sizeof(region)))
121 system_failure("query whole heap placeholder");
122 auto const begin = static_cast<std::byte *>(region.BaseAddress);
123 auto const prefix = static_cast<std::size_t>(target - begin);
124 if (region.State != MEM_RESERVE || prefix > region.RegionSize || count > region.RegionSize - prefix)
125 heap_failure("heap alias requires a containing placeholder");
126 if (prefix && !::VirtualFree(begin, prefix, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER))
127 system_failure("split heap placeholder prefix");
128 if (count < region.RegionSize - prefix &&
129 !::VirtualFree(target, count, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER))
130 system_failure("split heap placeholder suffix");
131 if (!::MapViewOfFile3(source.section->handle, ::GetCurrentProcess(), target,
132 source.offset + offset, count, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0))
133 system_failure("alias heap backing");
134}
135#endif
136
137#if !defined(_WIN32)
138void heap_mapping::alias(std::byte * source, std::byte * target, std::size_t count) noexcept {
139#if defined(__APPLE__)
140 auto destination = reinterpret_cast<mach_vm_address_t>(target);
141 vm_prot_t current = 0, maximum = 0;
142 auto const result = ::mach_vm_remap(::mach_task_self(), &destination, count, 0,
143 VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, ::mach_task_self(),
144 reinterpret_cast<mach_vm_address_t>(source), false, &current, &maximum, VM_INHERIT_SHARE);
145 if (result != KERN_SUCCESS)
146 heap_failure("alias virtual memory", result);
147 assert(destination == reinterpret_cast<mach_vm_address_t>(target));
148#else
149 auto const result = ::mremap(source, 0, count, MREMAP_MAYMOVE | MREMAP_FIXED, target);
150 if (result == MAP_FAILED) system_failure("jam: alias virtual memory");
151 assert(result == target);
152#endif
153}
154#endif
155
156void heap_mapping::fresh(std::size_t begin, std::size_t count) noexcept {
157 if (!count) return;
158#if defined(_WIN32)
159 spans.push_back({begin, begin + count, std::make_shared<backing>(count), 0});
160 alias(spans.back(), address + begin, count);
161#else
162 auto const result = ::mmap(address + begin, count, PROT_READ | PROT_WRITE,
163 MAP_FIXED | MAP_SHARED | MAP_ANONYMOUS, -1, 0);
164 if (result == MAP_FAILED) system_failure("jam: map fresh backing");
165 spans.push_back({begin, begin + count});
166#endif
167}
168
169void heap_mapping::finish_aliases() noexcept {
170 std::sort(spans.begin(), spans.end(), [](auto const & a, auto const & b) noexcept { return a.begin < b.begin; });
171 for (auto const & s : spans)
172#if defined(_WIN32)
173 alias(s, address + capacity + s.begin, s.end - s.begin);
174#else
175 alias(address + s.begin, address + capacity + s.begin, s.end - s.begin);
176#endif
177}
178
179void heap_mapping::discard_gap(std::size_t start, std::size_t live) const noexcept {
180#if defined(_WIN32)
181 // Advisory discard releases dead physical pages; a partially retained section
182 // keeps its commit charge until the last surviving view/handle is released.
183 for (auto const & s : spans) {
184 auto const discard = [&](std::size_t begin, std::size_t end) noexcept {
185 begin = std::max(begin, s.begin);
186 end = std::min(end, s.end);
187 if (begin < end) static_cast<void>(::VirtualAlloc(address + begin, end - begin, MEM_RESET, PAGE_READWRITE));
188 };
189 if (start + live <= capacity) {
190 discard(0, start);
191 discard(start + live, capacity);
192 } else discard(start + live - capacity, start);
193 }
194#else
195 auto const begin = (start + live) % capacity;
196 auto const count = capacity - live;
197 auto const first = std::min(count, capacity - begin);
198#if defined(__APPLE__)
199 constexpr auto advice = MADV_FREE_REUSABLE;
200#else
201 constexpr auto advice = MADV_REMOVE;
202#endif
203 // dev: advisory release; kernels may retain dead pages until memory pressure.
204 if (first) static_cast<void>(::madvise(address + begin, first, advice));
205 if (count > first) static_cast<void>(::madvise(address, count - first, advice));
206#endif
207}
208
209void heap_mapping::reset_fixed() noexcept {
210 assert(fixed_extent);
211#if defined(_WIN32)
212 for (auto const & s : spans) {
213 if (!::UnmapViewOfFile2(::GetCurrentProcess(), address + s.begin, MEM_PRESERVE_PLACEHOLDER) ||
214 !::UnmapViewOfFile2(::GetCurrentProcess(), address + capacity + s.begin, MEM_PRESERVE_PLACEHOLDER))
215 system_failure("restore generation placeholders");
216 }
217 MEMORY_BASIC_INFORMATION region{};
218 if (!::VirtualQuery(address, &region, sizeof(region))) system_failure("query generation placeholder");
219 if (region.RegionSize < fixed_extent &&
220 !::VirtualFree(address, fixed_extent, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS))
221 system_failure("coalesce generation placeholders");
222#else
223 if (::mmap(address, fixed_extent, PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == MAP_FAILED)
224 system_failure("restore generation reservation");
225#endif
226 spans.clear();
227}
228
229heap_mapping::heap_mapping(std::size_t bytes) noexcept : heap_mapping(reservation{}, bytes) {
230 spans.reserve(1);
231 fresh(0, bytes);
232 finish_aliases();
233}
234
235heap_mapping::heap_mapping(std::size_t bytes, std::byte * base, std::size_t maximum) noexcept
236 : address(base), capacity(bytes), fixed_extent(2 * maximum) {
237 validate_size(bytes);
238 if (bytes > maximum) heap_failure("generation exceeds reserved address range");
239 spans.reserve(1);
240 fresh(0, bytes);
241 finish_aliases();
242}
243
244void heap_mapping::replace(heap_mapping & staged) noexcept {
245 if (!fixed_extent) { swap(staged); return; }
246 if (staged.capacity * 2 > fixed_extent) heap_failure("generation growth exceeds maximum");
247 reset_fixed();
248 capacity = staged.capacity;
249 for (auto const & s : staged.spans) {
250#if defined(_WIN32)
251 alias(s, address + s.begin, s.end - s.begin);
252#else
253 alias(staged.address + s.begin, address + s.begin, s.end - s.begin);
254#endif
255 }
256 spans = staged.spans;
257 finish_aliases();
258}
259
260heap_mapping::~heap_mapping() noexcept {
261 if (!address) return;
262 if (fixed_extent) { reset_fixed(); return; }
263#if defined(_WIN32)
264 for (auto const & s : spans) {
265 ::UnmapViewOfFile(address + s.begin);
266 ::UnmapViewOfFile(address + capacity + s.begin);
267 }
268#else
269 static_cast<void>(::munmap(address, capacity * 2));
270#endif
271}
272
273std::size_t heap_mapping::page_size() noexcept {
274#if defined(_WIN32)
275 SYSTEM_INFO info{};
276 ::GetSystemInfo(&info);
277 return info.dwPageSize;
278#else
279 return static_cast<std::size_t>(::getpagesize());
280#endif
281}
282
283void heap_mapping::publish(std::size_t start, std::byte * target, std::size_t count) const noexcept {
284 if (start >= capacity || start % page_size() || count % page_size() ||
285 count > capacity || reinterpret_cast<std::uintptr_t>(target) % page_size())
286 heap_failure("invalid published heap arc");
287 while (count) {
288 auto const where = std::lower_bound(spans.begin(), spans.end(), start,
289 [](span const & s, std::size_t value) noexcept { return s.end <= value; });
290 assert(where != spans.end() && where->begin <= start);
291 auto const part = std::min(count, where->end - start);
292#if defined(_WIN32)
293 alias(*where, target, part, start - where->begin);
294#else
295 alias(address + start, target, part);
296#endif
297 start = (start + part) % capacity;
298 target += part;
299 count -= part;
300 }
301}
302
303void heap_mapping::map_arc(heap_mapping const & source, std::size_t start,
304 std::size_t target, std::size_t count) noexcept {
305 while (count) {
306 auto const where = std::lower_bound(source.spans.begin(), source.spans.end(), start,
307 [](span const & s, std::size_t value) noexcept { return s.end <= value; });
308 assert(where != source.spans.end() && where->begin <= start);
309 auto const part = std::min(count, where->end - start);
310#if defined(_WIN32)
311 span next{target, target + part, where->section, where->offset + start - where->begin};
312 alias(next, address + target, part);
313#else
314 span next{target, target + part};
315 alias(source.address + start, address + target, part);
316#endif
317 spans.push_back(std::move(next));
318 start = (start + part) % source.capacity;
319 target += part;
320 count -= part;
321 }
322}
323
324heap_mapping heap_mapping::alias_run(std::size_t start, std::size_t count) const noexcept {
325 auto const page = page_size();
326 if (!count || start >= capacity || start % page || count % page || count > capacity)
327 heap_failure("invalid side alias");
328 heap_mapping result(reservation{}, count);
329 result.map_arc(*this, start, 0, count);
330 result.finish_aliases();
331 return result;
332}
333
334void heap_mapping::replace_pages(heap_mapping const & source, std::size_t start,
335 std::size_t target, std::size_t count) noexcept {
336 auto const page = page_size();
337 if (!count || start >= source.capacity || start % page || target % page || count % page ||
338 count > source.capacity || target > capacity || count > capacity - target)
339 heap_failure("invalid page replacement");
340 heap_mapping result(reservation{}, capacity);
341 result.map_arc(*this, 0, 0, target);
342 result.map_arc(source, start, target, count);
343 result.map_arc(*this, target + count, target + count, capacity - target - count);
344 result.finish_aliases();
345 replace(result);
346}
347
348void heap_mapping::unpublish(std::byte * target, std::size_t count) noexcept {
349 if (!count || count % page_size() || reinterpret_cast<std::uintptr_t>(target) % page_size())
350 heap_failure("invalid unpublished heap window");
351#if defined(_WIN32)
352 auto * cursor = target;
353 auto remaining = count;
354 std::size_t views = 0;
355 while (remaining) {
356 MEMORY_BASIC_INFORMATION region{};
357 if (!::VirtualQuery(cursor, &region, sizeof(region))) system_failure("query published heap view");
358 if (region.AllocationBase != cursor || region.BaseAddress != cursor || region.Type != MEM_MAPPED ||
359 region.State != MEM_COMMIT || !region.RegionSize || region.RegionSize > remaining)
360 heap_failure("published heap window was modified by its host");
361 if (!::UnmapViewOfFile2(::GetCurrentProcess(), cursor, MEM_PRESERVE_PLACEHOLDER))
362 system_failure("restore published heap placeholder");
363 cursor += region.RegionSize;
364 remaining -= region.RegionSize;
365 ++views;
366 }
367 if (views > 1 && !::VirtualFree(target, count, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS))
368 system_failure("coalesce published heap placeholders");
369#else
370 if (::mmap(target, count, PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == MAP_FAILED)
371 system_failure("restore published heap reservation");
372#endif
373}
374
375heap_mapping heap_mapping::resized(std::size_t old_start_bytes, std::size_t live_bytes,
376 std::size_t new_bytes, std::size_t new_start_bytes) const noexcept {
377 validate_size(new_bytes);
378 auto const page = page_size();
379 if (!address || old_start_bytes >= capacity || new_start_bytes >= new_bytes ||
380 old_start_bytes % page || new_start_bytes % page ||
381 live_bytes > capacity || live_bytes > new_bytes)
382 heap_failure("invalid circular remap range");
383 auto const live = ((live_bytes + page - 1) / page) * page;
384 heap_mapping result(reservation{}, new_bytes);
385 result.spans.reserve(spans.size() + 4);
386 auto source = old_start_bytes;
387 auto target = new_start_bytes;
388 auto remaining = live;
389 while (remaining) {
390 auto const where = std::lower_bound(spans.begin(), spans.end(), source,
391 [](span const & s, std::size_t value) noexcept { return s.end <= value; });
392 assert(where != spans.end() && where->begin <= source);
393 auto const count = std::min({remaining, where->end - source, new_bytes - target});
394#if defined(_WIN32)
395 alias(*where, result.address + target, count, source - where->begin);
396 result.spans.push_back({target, target + count, where->section, where->offset + source - where->begin});
397#else
398 alias(address + source, result.address + target, count);
399 result.spans.push_back({target, target + count});
400#endif
401 source = (source + count) % capacity;
402 target = (target + count) % new_bytes;
403 remaining -= count;
404 }
405 if (!live) result.fresh(0, new_bytes);
406 else if (new_start_bytes + live <= new_bytes) {
407 result.fresh(0, new_start_bytes);
408 result.fresh(new_start_bytes + live, new_bytes - new_start_bytes - live);
409 } else result.fresh(new_start_bytes + live - new_bytes, new_bytes - live);
410 result.finish_aliases();
411 discard_gap(old_start_bytes, live);
412 return result;
413}
414}
space< std::size_t > bytes
Whole bytes.
Definition units.ccm:238