7#if defined(__linux__) && !defined(_GNU_SOURCE)
22#define WIN32_LEAN_AND_MEAN
31#include <mach/mach_vm.h>
32#elif !defined(__linux__) && !defined(_WIN32)
33#error "jam requires macOS, Linux or Windows virtual-memory aliases"
40namespace jam::detail {
42struct heap_mapping::backing {
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");
49 ~backing() noexcept { ::CloseHandle(handle); }
53hint_cold hint_noreturn
54void heap_failure(
char const * operation,
int code)
noexcept {
55 std::fprintf(stderr,
"jam: %s (%d)\n", operation, code);
59generation_reservation::generation_reservation(std::size_t old_maximum, std::size_t young_maximum) noexcept
60 : bytes_(2 * (old_maximum + young_maximum)) {
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());
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);
72generation_reservation::~generation_reservation() noexcept {
74 MEMORY_BASIC_INFORMATION region{};
75 if (!::VirtualQuery(base_, ®ion,
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());
81 if (::munmap(base_, bytes_)) heap_failure(
"release generation reservation", errno);
85[[noreturn]]
void heap_mapping::system_failure(
char const * operation)
noexcept {
87 heap_failure(operation,
static_cast<int>(::GetLastError()));
89 heap_failure(operation, errno);
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");
98heap_mapping::heap_mapping(reservation, std::size_t bytes)
noexcept {
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");
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");
108 address =
static_cast<std::byte *
>(result);
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, ®ion,
sizeof(region))) system_failure(
"query heap placeholder");
119 if (region.State == MEM_RESERVE && region.BaseAddress != region.AllocationBase &&
120 !::VirtualQuery(region.AllocationBase, ®ion,
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");
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, ¤t, &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));
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);
156void heap_mapping::fresh(std::size_t begin, std::size_t count)
noexcept {
159 spans.push_back({begin, begin + count, std::make_shared<backing>(count), 0});
160 alias(spans.back(), address + begin, count);
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});
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)
173 alias(s, address + capacity + s.begin, s.end - s.begin);
175 alias(address + s.begin, address + capacity + s.begin, s.end - s.begin);
179void heap_mapping::discard_gap(std::size_t start, std::size_t live)
const noexcept {
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));
189 if (start + live <= capacity) {
191 discard(start + live, capacity);
192 }
else discard(start + live - capacity, start);
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;
201 constexpr auto advice = MADV_REMOVE;
204 if (first)
static_cast<void>(::madvise(address + begin, first, advice));
205 if (count > first)
static_cast<void>(::madvise(address, count - first, advice));
209void heap_mapping::reset_fixed() noexcept {
210 assert(fixed_extent);
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");
217 MEMORY_BASIC_INFORMATION region{};
218 if (!::VirtualQuery(address, ®ion,
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");
223 if (::mmap(address, fixed_extent, PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == MAP_FAILED)
224 system_failure(
"restore generation reservation");
229heap_mapping::heap_mapping(std::size_t bytes) noexcept : heap_mapping(reservation{},
bytes) {
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");
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");
248 capacity = staged.capacity;
249 for (
auto const & s : staged.spans) {
251 alias(s, address + s.begin, s.end - s.begin);
253 alias(staged.address + s.begin, address + s.begin, s.end - s.begin);
256 spans = staged.spans;
260heap_mapping::~heap_mapping() noexcept {
261 if (!address)
return;
262 if (fixed_extent) { reset_fixed();
return; }
264 for (
auto const & s : spans) {
265 ::UnmapViewOfFile(address + s.begin);
266 ::UnmapViewOfFile(address + capacity + s.begin);
269 static_cast<void>(::munmap(address, capacity * 2));
273std::size_t heap_mapping::page_size() noexcept {
276 ::GetSystemInfo(&info);
277 return info.dwPageSize;
279 return static_cast<std::size_t
>(::getpagesize());
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");
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);
293 alias(*where, target, part, start - where->begin);
295 alias(address + start, target, part);
297 start = (start + part) % capacity;
303void heap_mapping::map_arc(heap_mapping
const & source, std::size_t start,
304 std::size_t target, std::size_t count)
noexcept {
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);
311 span next{target, target + part, where->section, where->offset + start - where->begin};
312 alias(next, address + target, part);
314 span next{target, target + part};
315 alias(source.address + start, address + target, part);
317 spans.push_back(std::move(next));
318 start = (start + part) % source.capacity;
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();
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();
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");
352 auto * cursor = target;
353 auto remaining = count;
354 std::size_t views = 0;
356 MEMORY_BASIC_INFORMATION region{};
357 if (!::VirtualQuery(cursor, ®ion,
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;
367 if (views > 1 && !::VirtualFree(target, count, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS))
368 system_failure(
"coalesce published heap placeholders");
370 if (::mmap(target, count, PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == MAP_FAILED)
371 system_failure(
"restore published heap reservation");
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;
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});
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});
398 alias(address + source, result.address + target, count);
399 result.spans.push_back({target, target + count});
401 source = (source + count) % capacity;
402 target = (target + count) % new_bytes;
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);
space< std::size_t > bytes
Whole bytes.