Repository navigation
Expand file tree
/
Copy pathtitle_memory.cpp
More file actions
1137 lines (1112 loc) · 52.9 KB
/
Copy pathtitle_memory.cpp
File metadata and controls
1137 lines (1112 loc) · 52.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "title_memory.h"
#include <d3d12.h>
#include <processsnapshot.h>
#include <psapi.h>
#include <wrl/implements.h>
#include <wrl/wrappers/corewrappers.h>
#include <algorithm>
#include <array>
#include <bit>
#include <cstring>
#include <map>
#include <memory>
#include <mutex>
#include <vector>
namespace {
using namespace rage::memory;
using namespace Microsoft::WRL;
using Section = Wrappers::HandleT<Wrappers::HandleTraits::HANDLENullTraits>;
constexpr SIZE_T gib = SIZE_T{1} << 30;
constexpr UINT64 graphics_minimum = 2 * gib;
constexpr UINT default_table_units = 5;
// Scale the documented default 159.375 GiB aperture across its five 4 MiB units.
// These limits govern guest addresses. Windows owns the physical GPU page tables.
constexpr UINT64 graphics_end(UINT units) {
constexpr UINT64 bytes_per_unit = 255 * (gib / 8);
return (std::min)(UINT64{1024} * gib, units * bytes_per_unit);
}
constexpr SIZE_T optimal_limit = 10 * gib;
constexpr SIZE_T standard_limit = 7 * gib / 2;
constexpr DWORD physical_page_type = MEM_64K_PAGES;
constexpr ULONG_PTR last_page = UINTPTR_MAX >> 4;
bool fail(DWORD error = ERROR_INVALID_PARAMETER) {
SetLastError(error);
return false;
}
Section make_section(SIZE_T bytes) {
return Section(CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_COMMIT,
DWORD(bytes >> 32), DWORD(bytes), nullptr));
}
// Consecutive physical page IDs can be mapped individually, in any order, and at several addresses.
// Give them stable offsets in a common section and commit each 64 KiB only on its first binding.
struct PhysicalSection {
SIZE_T pages{}, bound{};
Section file;
BYTE* base{};
~PhysicalSection() { if (base) UnmapViewOfFile(base); }
bool bind(SIZE_T slot) {
if (!base) {
const UINT64 bytes = UINT64(pages) * page_size;
Section next(CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE,
DWORD(bytes >> 32), DWORD(bytes), nullptr));
if (!next.IsValid()) return false;
base = static_cast<BYTE*>(MapViewOfFile(next.Get(), FILE_MAP_WRITE, 0, 0, 0));
if (!base) return false;
file = std::move(next);
}
if (!VirtualAlloc(base + slot * page_size, page_size, MEM_COMMIT, PAGE_READWRITE)) return false;
++bound;
return true;
}
void release(SIZE_T slot) {
if (--bound == 0) {
UnmapViewOfFile(base);
base = nullptr;
file.Close();
} else {
// All CPU mappings, GPU leases and title ownership have released this page.
// Windows can reclaim the contents even while another page keeps the section committed.
DiscardVirtualMemory(base + slot * page_size, page_size);
}
}
};
struct GraphicsSection {
Section file;
enum class Slot : BYTE { fresh, used, released };
std::vector<Slot> slots;
bool claim(SIZE_T slot) {
if (slots[slot] == Slot::used) return false;
if (slots[slot] == Slot::released) {
const UINT64 offset = slot * page_size;
auto* alias = MapViewOfFile(file.Get(), FILE_MAP_WRITE, DWORD(offset >> 32), DWORD(offset), page_size);
if (!alias) return false;
std::memset(alias, 0, page_size);
UnmapViewOfFile(alias);
}
slots[slot] = Slot::used;
return true;
}
};
struct GraphicsReservation {
uintptr_t base{};
SIZE_T pages{};
std::weak_ptr<GraphicsSection> backing;
std::shared_ptr<GraphicsSection> for_mapping(SIZE_T count, SIZE_T batch_pages) {
if (auto existing = backing.lock()) return existing;
// A placeholder can be many GiB. Commit a common section only for a matching
// physical allocation when the caller is mapping a substantial part of it.
if (batch_pages != pages || count < (pages + 3) / 4) return {};
auto section = std::make_shared<GraphicsSection>();
section->file = make_section(pages * page_size);
if (!section->file.IsValid()) return {};
section->slots.resize(pages);
backing = section;
return section;
}
};
struct GraphicsPage {
std::shared_ptr<GraphicsSection> section;
SIZE_T slot{};
};
struct Group {
Section section;
std::shared_ptr<PhysicalSection> physical;
SIZE_T first_slot{};
SIZE_T count{}, batch_pages{};
bool optimal{}, clustered{};
UINT32 owned{}, local_pages{};
std::unique_ptr<std::array<GraphicsPage, cluster_pages>> graphics_pages;
std::array<unsigned, cluster_pages> references{};
std::array<DWORD, cluster_pages> cache_policy{};
std::array<unsigned, cluster_pages> mappings{};
const GraphicsPage* graphics_page(unsigned index) const {
return graphics_pages && (*graphics_pages)[index].section ? &(*graphics_pages)[index] : nullptr;
}
HANDLE file(unsigned index) const {
const auto* mapped = graphics_page(index);
if (mapped) return mapped->section->file.Get();
return physical ? physical->file.Get() : section.Get();
}
UINT64 file_offset(unsigned index) const {
const auto* mapped = graphics_page(index);
return (mapped ? mapped->slot : first_slot + index) * page_size;
}
bool bind(unsigned index, const std::shared_ptr<GraphicsSection>& target = {}, SIZE_T slot = 0) {
const auto bit = UINT32{1} << index;
if ((local_pages & bit) || graphics_page(index)) return true;
if (target) {
if (!graphics_pages) graphics_pages = std::make_unique<std::array<GraphicsPage, cluster_pages>>();
if (target->claim(slot)) {
(*graphics_pages)[index] = {target, slot};
return true;
}
}
if (physical) {
if (!physical->bind(first_slot + index)) return false;
} else {
if (!section.IsValid()) section = make_section(count * page_size);
if (!section.IsValid()) return false;
}
local_pages |= bit;
return true;
}
void release_page(unsigned index) {
if (const auto* mapped = graphics_page(index)) {
mapped->section->slots[mapped->slot] = GraphicsSection::Slot::released;
(*graphics_pages)[index] = {};
} else if (physical && (local_pages & (UINT32{1} << index))) {
local_pages &= ~(UINT32{1} << index);
physical->release(first_slot + index);
}
}
};
struct Page {
std::shared_ptr<Group> group;
unsigned index{};
bool operator==(const Page&) const = default;
};
struct Window {
uintptr_t end;
UINT64 flags;
DWORD protection;
SIZE_T granularity;
bool placeholder;
DWORD page_type;
std::shared_ptr<GraphicsReservation> reservation;
};
struct Memory {
std::mutex lock;
std::map<ULONG_PTR, std::shared_ptr<Group>> groups;
std::map<uintptr_t, Window> windows;
std::map<uintptr_t, Page> views;
struct GpuView { Page source; ComPtr<ID3D12Fence> fence; UINT64 value{}; };
std::map<uintptr_t, GpuView> gpu_views;
struct NativeRange { uintptr_t base; const std::vector<Page>* pages; };
std::map<const void*, NativeRange> native_ranges;
Section zero_page;
ULONG_PTR next_page = cluster_pages;
SIZE_T standard{}, optimal{}, transferred{};
unsigned reservations_since_cleanup{};
UINT64 graphics_limit = graphics_end(default_table_units);
bool graphics_in_use{};
};
Memory& memory() { static Memory state; return state; }
Page lookup(Memory& m, ULONG_PTR token) {
if (!token || token % 16) return {};
const auto frame = token >> 4;
auto it = m.groups.upper_bound(frame);
if (it == m.groups.begin()) return {};
--it;
const auto index = frame - it->first;
if (index >= it->second->count || !(it->second->owned & (UINT32{1} << index))) return {};
return {it->second, static_cast<unsigned>(index)};
}
void release_reference(Memory& m, const Page& page) {
auto& g = *page.group;
if (--g.references[page.index] == 0) {
(g.optimal ? m.optimal : m.standard) -= page_size;
g.release_page(page.index);
}
}
void clear_gpu_views(Memory& m, uintptr_t base, uintptr_t end) {
for (auto it = m.gpu_views.lower_bound(base); it != m.gpu_views.end() && it->first < end;) {
if (it->second.source.group) release_reference(m, it->second.source);
it = m.gpu_views.erase(it);
}
}
auto window_at(Memory& m, uintptr_t address) {
auto it = m.windows.upper_bound(address);
if (it != m.windows.begin() && address < std::prev(it)->second.end) return std::prev(it);
return m.windows.end();
}
bool isolate(uintptr_t address, SIZE_T size) {
MEMORY_BASIC_INFORMATION info{};
auto* target = reinterpret_cast<void*>(address);
if (!VirtualQuery(target, &info, sizeof info) || info.State != MEM_RESERVE || info.Type != MEM_PRIVATE)
return fail(ERROR_INVALID_ADDRESS);
const auto start = reinterpret_cast<uintptr_t>(info.AllocationBase);
const auto end = reinterpret_cast<uintptr_t>(info.BaseAddress) + info.RegionSize;
if (end - address < size) return fail(ERROR_INVALID_ADDRESS);
if (address != start &&
!VirtualFree(info.AllocationBase, address - start, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) return false;
return size == end - address || VirtualFree(target, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
}
void coalesce_if_empty(Memory& m, uintptr_t address) {
const auto it = window_at(m, address);
if (it == m.windows.end()) return;
const auto [base, window] = *it;
auto view = m.views.lower_bound(base);
if (view != m.views.end() && view->first < window.end) return;
auto* p = reinterpret_cast<void*>(base);
MEMORY_BASIC_INFORMATION info{};
if (VirtualQuery(p, &info, sizeof info) && info.AllocationBase == p &&
info.State == MEM_RESERVE && info.RegionSize < window.end - base)
VirtualFree(p, window.end - base, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS);
}
void prune_released_windows(Memory& m) {
// Titles release native reservations with VirtualFree, without entering
// the DLL. Periodically drop records whose underlying reservation is gone.
if (++m.reservations_since_cleanup < 256) return;
m.reservations_since_cleanup = 0;
for (auto it = m.gpu_views.begin(); it != m.gpu_views.end();) {
MEMORY_BASIC_INFORMATION region{};
const auto at = it->first;
if (!VirtualQuery(reinterpret_cast<void*>(at), ®ion, sizeof(region))) { ++it; continue; }
const auto end = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
if (region.State == MEM_FREE) clear_gpu_views(m, at, end);
it = m.gpu_views.lower_bound(end);
}
std::erase_if(m.windows, [&](const auto& entry) {
MEMORY_BASIC_INFORMATION region{};
auto* base = reinterpret_cast<void*>(entry.first);
const auto view = m.views.lower_bound(entry.first);
return (view == m.views.end() || view->first >= entry.second.end) &&
VirtualQuery(base, ®ion, sizeof region) &&
(region.State == MEM_FREE || region.AllocationBase != base);
});
}
void* reserve(Memory& m, void* base, SIZE_T size, DWORD type, UINT64 flags, DWORD protect) {
const auto address = reinterpret_cast<uintptr_t>(base);
const DWORD page_type = type & physical_page_type;
const bool large = page_type == MEM_2MB_PAGES;
const SIZE_T alignment = large ? cluster_size : page_size;
const bool explicit_placeholder = (type & MEM_RESERVE_PLACEHOLDER) != 0;
const bool mappable = (flags & XMEM_MAPPABLE) != 0;
const bool graphics = (flags & XMEM_GRAPHICS) == XMEM_GRAPHICS;
const bool gpu_window = graphics && (protect & 0xff) == PAGE_NOACCESS;
const bool placeholder = explicit_placeholder || ((mappable || gpu_window) && page_type && !(type & MEM_COMMIT));
if (!size || size > UINTPTR_MAX - address || size > SIZE_MAX - alignment ||
(mappable && (!page_type || !(type & MEM_RESERVE) || (type & MEM_COMMIT)))) {
fail(); return nullptr;
}
if (flags & XMEM_TOOL) { fail(ERROR_NOT_SUPPORTED); return nullptr; }
if (page_type || placeholder) size = (size + alignment - 1) & ~(alignment - 1);
if (size > UINTPTR_MAX - address) { fail(); return nullptr; }
const bool low = (flags & 4) || (type & 0x00800000);
const unsigned field = static_cast<unsigned>((flags >> 12) & 7);
const unsigned bits = low ? 32 : field ? 47 - field : 40;
const UINT64 end_limit = graphics ? (std::min)(UINT64{1} << bits, m.graphics_limit) : UINT64{1} << bits;
if (graphics && base && (address < graphics_minimum || address >= end_limit || size > end_limit - address)) {
fail(ERROR_INVALID_ADDRESS); return nullptr;
}
if (base && placeholder && (type & MEM_REPLACE_PLACEHOLDER)) {
auto it = window_at(m, address);
if (it == m.windows.end() || !it->second.placeholder || address % alignment || size > it->second.end - address) {
fail(ERROR_INVALID_ADDRESS); return nullptr;
}
const auto [start, old] = *it;
std::map<uintptr_t, Window> pieces;
if (start < address) pieces.emplace(start, Window{address, old.flags, old.protection, old.granularity, true, old.page_type, old.reservation});
pieces.emplace(address, Window{address + size, flags, protect, alignment, true, page_type, old.reservation});
if (address + size < old.end) pieces.emplace(address + size, old);
if (!isolate(address, size)) return nullptr;
m.windows.erase(it);
m.windows.merge(pieces);
if (graphics) m.graphics_in_use = true;
return base;
}
// The kit's heap.c also uses its legacy low-address bit for CPU allocations.
type &= ~(physical_page_type | 0x00800000);
if (placeholder) type |= MEM_RESERVE | MEM_RESERVE_PLACEHOLDER;
MEM_ADDRESS_REQUIREMENTS range{};
MEM_EXTENDED_PARAMETER param{};
const bool choose = !base && (type & (MEM_RESERVE | MEM_COMMIT));
if (choose) {
type |= MEM_RESERVE;
range.HighestEndingAddress = reinterpret_cast<void*>(end_limit - 1);
if (graphics && low) range.LowestStartingAddress = reinterpret_cast<void*>(graphics_minimum);
else if (!low) range.LowestStartingAddress = reinterpret_cast<void*>(gib * 4);
range.Alignment = alignment;
param.Type = MemExtendedParameterAddressRequirements;
param.Pointer = ⦥
}
const DWORD cpu_protect = protect & 0x7ff;
void* result = VirtualAlloc2(GetCurrentProcess(), base, size, type, placeholder ? PAGE_NOACCESS : cpu_protect,
choose ? ¶m : nullptr, choose ? 1 : 0);
if (!result) return nullptr;
if (!(type & MEM_RESERVE)) {
if (graphics) m.graphics_in_use = true;
return result;
}
MEMORY_BASIC_INFORMATION info{};
if (!VirtualQuery(result, &info, sizeof info)) {
const auto error = GetLastError(); VirtualFree(result, 0, MEM_RELEASE); fail(error); return nullptr;
}
const auto start = reinterpret_cast<uintptr_t>(result);
const auto end = start + info.RegionSize;
try {
// A caller releases reservations through ordinary VirtualFree. Discard
// stale descriptors when Windows hands the same addresses out again.
prune_released_windows(m);
clear_gpu_views(m, start, end);
const auto previous = window_at(m, start);
if (previous != m.windows.end() && previous->first < start) previous->second.end = start;
if (placeholder || flags != XMEM_CPU || page_type || (protect & ~DWORD{0x7ff})) {
std::shared_ptr<GraphicsReservation> reservation;
if (explicit_placeholder && graphics) {
reservation = std::make_shared<GraphicsReservation>();
reservation->base = start;
reservation->pages = (end - start) / page_size;
}
m.windows.insert_or_assign(start, Window{end, flags, protect, alignment, placeholder, page_type, std::move(reservation)});
m.windows.erase(m.windows.upper_bound(start), m.windows.lower_bound(end));
} else m.windows.erase(m.windows.lower_bound(start), m.windows.lower_bound(end));
} catch (...) {
VirtualFree(result, 0, MEM_RELEASE);
throw;
}
if (graphics) m.graphics_in_use = true;
return result;
}
struct Change {
uintptr_t address;
Page next, previous;
DWORD protection;
SIZE_T granularity;
};
bool install(uintptr_t address, const Page& page, DWORD protection) {
if (!page.group) return true;
auto* p = reinterpret_cast<void*>(address);
if (!isolate(address, page_size)) return false;
if (!MapViewOfFile3(page.group->file(page.index), GetCurrentProcess(), p, page.group->file_offset(page.index),
page_size, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) return false;
// File-mapping aliases use the desktop section's cache policy. Apply the
// caller's CPU access here. GPU access flags are metadata for D3D12.
const DWORD access = protection & (0xff | PAGE_GUARD);
DWORD old{};
if (access == PAGE_READWRITE || VirtualProtect(p, page_size, access, &old)) return true;
DWORD error = GetLastError();
UnmapViewOfFile2(GetCurrentProcess(), p, MEM_PRESERVE_PLACEHOLDER);
return fail(error);
}
bool replace(Memory& m, const Change& c, const Page& next) {
auto& current = m.views.at(c.address);
if (current == next) return true;
const DWORD policy = c.protection & (PAGE_NOCACHE | PAGE_WRITECOMBINE);
if (next.group && next.group->mappings[next.index] && next.group->cache_policy[next.index] != policy)
return fail();
if (current.group && !UnmapViewOfFile2(GetCurrentProcess(), reinterpret_cast<void*>(c.address),
MEM_PRESERVE_PLACEHOLDER)) return false;
if (!install(c.address, next, c.protection)) {
const auto error = GetLastError();
if (current.group && !install(c.address, current, c.protection)) {
--current.group->mappings[current.index];
release_reference(m, current);
current = {};
}
return fail(error);
}
if (current.group) {
--current.group->mappings[current.index];
release_reference(m, current);
}
current = next;
if (next.group) {
++next.group->references[next.index];
++next.group->mappings[next.index];
next.group->cache_policy[next.index] = policy;
}
return true;
}
bool valid_clusters(const std::vector<Change>& changes) {
for (SIZE_T i = 0; i < changes.size();) {
const auto& first = changes[i];
if (first.granularity != cluster_size) { ++i; continue; }
if (first.address % cluster_size || changes.size() - i < cluster_pages ||
(first.next.group && (!first.next.group->clustered || first.next.index != 0))) return fail();
for (unsigned j = 0; j < cluster_pages; ++j) {
const auto& c = changes[i + j];
if (c.address != first.address + j * page_size || c.granularity != cluster_size ||
c.next.group != first.next.group || (c.next.group && c.next.index != j)) return fail();
}
i += cluster_pages;
}
return true;
}
bool map_pages(void* base, void* const* scatter, SIZE_T count, const ULONG_PTR* tokens) {
const auto start = reinterpret_cast<uintptr_t>(base);
std::vector<Change> changes;
if (!count || count > changes.max_size() ||
(!scatter && (!start || count > (UINTPTR_MAX - start) / page_size))) return fail();
auto& m = memory();
std::lock_guard lock(m.lock);
changes.reserve(count);
for (SIZE_T i = 0; i < count; ++i) {
const auto at = scatter ? reinterpret_cast<uintptr_t>(scatter[i]) : start + i * page_size;
auto it = window_at(m, at);
if (at % page_size || it == m.windows.end() || !it->second.placeholder || page_size > it->second.end - at)
return fail(ERROR_INVALID_ADDRESS);
Page page;
if (tokens && (tokens[i] || !scatter)) {
page = lookup(m, tokens[i]);
if (!page.group) return fail();
}
changes.push_back({at, page, {}, it->second.protection, it->second.granularity});
}
if (scatter && std::any_of(changes.begin(), changes.end(), [](const Change& c) { return c.granularity == cluster_size; }))
std::stable_sort(changes.begin(), changes.end(), [](const Change& a, const Change& b) { return a.address < b.address; });
if (!valid_clusters(changes)) return false;
std::shared_ptr<GraphicsSection> graphics_section;
uintptr_t graphics_base{};
if (!scatter && tokens) {
const auto& window = window_at(m, start)->second;
if (window.reservation && (window.flags & XMEM_MAPPABLE) && count <= (window.end - start) / page_size) {
graphics_base = window.reservation->base;
graphics_section = window.reservation->for_mapping(count, changes.front().next.group->batch_pages);
}
}
// Allocate every map node before altering the address space. Reference
// previous bindings until rollback is over, including already-freed PFNs.
std::map<uintptr_t, Page> empty_nodes;
for (const auto& c : changes) {
if (c.next.group && !c.next.group->bind(c.next.index, graphics_section, (c.address - graphics_base) / page_size))
return false;
if (!m.views.contains(c.address)) empty_nodes.try_emplace(c.address);
}
m.views.merge(empty_nodes);
SIZE_T done = 0;
for (; done < count; ++done) {
auto& c = changes[done];
c.previous = m.views.at(c.address);
if (c.previous.group) ++c.previous.group->references[c.previous.index];
if (!replace(m, c, c.next)) break;
}
const bool ok = done == count;
const DWORD error = GetLastError();
if (!ok) {
for (auto i = done; i > 0; --i) replace(m, changes[i - 1], changes[i - 1].previous);
}
for (const auto& c : changes) {
if (c.previous.group) release_reference(m, c.previous);
auto it = m.views.find(c.address);
if (it != m.views.end() && !it->second.group) m.views.erase(it);
}
uintptr_t last_window_end{};
for (const auto& c : changes) {
if (m.views.contains(c.address)) continue;
const auto it = window_at(m, c.address);
if (it != m.windows.end() && it->second.end != last_window_end) {
last_window_end = it->second.end;
coalesce_if_empty(m, c.address);
}
}
return ok || fail(error);
}
bool process_usage(PROCESS_MEMORY_COUNTERS_EX& counters) {
counters.cb = sizeof counters;
return GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&counters),
sizeof counters) != FALSE;
}
DWORD stack_usage(UINT32& bytes) {
HPSS snapshot{};
DWORD error = PssCaptureSnapshot(GetCurrentProcess(), PSS_CAPTURE_THREADS, 0, &snapshot);
if (error) return error;
HPSSWALK marker{};
error = PssWalkMarkerCreate(nullptr, &marker);
if (!error) {
SIZE_T total{};
PSS_THREAD_ENTRY thread{};
while ((error = PssWalkSnapshot(snapshot, PSS_WALK_THREADS, marker, &thread, sizeof thread)) == ERROR_SUCCESS) {
// Threads can exit between capturing the list and reading their
// stack bounds. Only count a TIB still readable in this process.
NT_TIB tib{};
if (ReadProcessMemory(GetCurrentProcess(), thread.TebBaseAddress, &tib, sizeof tib, nullptr)) {
const auto top = reinterpret_cast<uintptr_t>(tib.StackBase);
const auto low = reinterpret_cast<uintptr_t>(tib.StackLimit);
if (top >= low) total += top - low;
}
}
if (error == ERROR_NO_MORE_ITEMS) {
bytes = static_cast<UINT32>((std::min)(total, SIZE_T{UINT32_MAX}));
error = ERROR_SUCCESS;
}
PssWalkMarkerFree(marker);
}
PssFreeSnapshot(GetCurrentProcess(), snapshot);
return error;
}
SIZE_T available(SIZE_T limit, SIZE_T used) { return used < limit ? limit - used : 0; }
bool allocate_pages(UINT64 flags, SIZE_T requested, ULONG_PTR* count, ULONG_PTR* tokens) {
const bool cluster = (flags & XMEM_2MB_CLUSTERS) != 0;
if (!tokens || !requested || (cluster && requested % cluster_pages) ||
(flags & ~(UINT64{XMEM_2MB_CLUSTERS} | XMEM_GPU_OPTBW_PREF))) return fail();
auto& m = memory();
std::lock_guard lock(m.lock);
PROCESS_MEMORY_COUNTERS_EX process{};
if (!process_usage(process)) return false;
const auto total = available(standard_limit + optimal_limit - m.transferred,
process.PrivateUsage + m.optimal + m.standard) / page_size;
SIZE_T remaining = (std::min)(requested, total);
const bool prefer_optimal = (flags & 0x200) != 0;
const bool strict = (flags & XMEM_STD_BW_REQ) && !(flags & 0x100);
ULONG_PTR next = m.next_page;
SIZE_T assigned{}, optimal_bytes{}, standard_bytes{};
std::map<ULONG_PTR, std::shared_ptr<Group>> pending;
for (int pass = 0; pass < (strict ? 1 : 2) && remaining; ++pass) {
const bool optimal = pass == 0 ? prefer_optimal : !prefer_optimal;
const auto capacity = optimal ? available(optimal_limit, m.optimal)
: available(standard_limit - m.transferred, m.standard);
SIZE_T n = (std::min)(remaining, capacity / page_size);
if (cluster) n -= n % cluster_pages;
(optimal ? optimal_bytes : standard_bytes) += n * page_size;
assigned += n;
remaining -= n;
while (n) {
const SIZE_T take = (std::min)(n, cluster_pages);
if (next > last_page - 2 * cluster_pages) return fail(ERROR_NOT_ENOUGH_MEMORY);
if (cluster) next = (next + cluster_pages - 1) & ~(cluster_pages - 1);
auto group = std::make_shared<Group>();
group->count = take;
group->optimal = optimal;
group->clustered = cluster;
group->owned = take == 32 ? UINT32_MAX : (UINT32{1} << take) - 1;
std::fill_n(group->references.begin(), take, 1u);
pending.emplace(next, std::move(group));
next += take;
n -= take;
}
}
if (!assigned) return fail(ERROR_NOT_ENOUGH_MEMORY);
if (pending.size() > 1) {
// A live page can keep its section's earlier commits charged until the last binding is released.
// Bound that cost to 128 MiB and distribute clusters evenly to avoid a tiny final section.
constexpr SIZE_T max_groups = (128 * 1024 * 1024) / cluster_size;
const SIZE_T sections = (pending.size() + max_groups - 1) / max_groups;
const SIZE_T groups_per_section = (pending.size() + sections - 1) / sections;
auto it = pending.begin();
while (it != pending.end()) {
auto section = std::make_shared<PhysicalSection>();
for (SIZE_T i = 0; i < groups_per_section && it != pending.end(); ++i, ++it) {
auto& group = *it->second;
group.physical = section;
group.first_slot = section->pages;
section->pages += group.count;
}
}
}
SIZE_T written = 0;
for (const auto& [first, group] : pending) {
group->batch_pages = assigned;
for (SIZE_T i = 0; i < group->count; ++i) tokens[written++] = (first + i) << 4;
}
m.groups.merge(pending);
m.next_page = next;
m.optimal += optimal_bytes;
m.standard += standard_bytes;
*count = assigned;
return true;
}
class PageLease final : public RuntimeClass<RuntimeClassFlags<ClassicCom>, IUnknown> {
public:
Page page;
~PageLease() override {
if (page.group) {
auto& m = memory();
std::lock_guard lock(m.lock);
release_reference(m, page);
}
}
};
enum class RangeUse { cpu, pool, sampled, native_buffer };
class RangeLease final : public RuntimeClass<RuntimeClassFlags<ClassicCom>, IRdnaMappedRange, IRdnaPageRuns> {
public:
HRESULT STDMETHODCALLTYPE GetRun(SIZE_T index, HANDLE* section, UINT64* offset, SIZE_T* bytes) override {
if (!section || !offset || !bytes) return E_POINTER;
*section = nullptr;
*offset = *bytes = 0;
if (index >= runs_.size()) return S_FALSE;
const auto& run = runs_[index];
*section = run.section;
*offset = run.offset;
*bytes = run.size;
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetSection(HANDLE* section, UINT64* offset) override {
if (!section || !offset) return E_POINTER;
*section = nullptr;
*offset = 0;
if (runs_.size() != 1) return S_FALSE;
*section = runs_[0].section;
*offset = runs_[0].offset + first_byte_;
return S_OK;
}
HRESULT acquire(uintptr_t address, SIZE_T size, const void** data, RangeUse use) {
const SIZE_T skip = address % page_size;
if (!address || !size || size - 1 > UINTPTR_MAX - address || size > SIZE_MAX - skip - (page_size - 1))
return E_INVALIDARG;
span_ = (skip + size + page_size - 1) & ~(page_size - 1);
if (address - skip > UINTPTR_MAX - span_) return E_INVALIDARG;
const auto page_count = span_ / page_size;
HANDLE zero{};
const bool gpu = use == RangeUse::sampled || use == RangeUse::native_buffer;
std::map<ComPtr<ID3D12Fence>, UINT64> waits;
{
auto& m = memory();
std::lock_guard lock(m.lock);
if (page_count > m.views.size() + (gpu ? m.gpu_views.size() : 0)) return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
auto at = address - skip;
if (use == RangeUse::pool) {
const UINT64 end = at + span_;
for (auto pos = at; pos < end;) {
const auto window = window_at(m, pos);
if (window == m.windows.end() || (window->second.flags & XMEM_GRAPHICS) != XMEM_GRAPHICS) return E_INVALIDARG;
pos = (std::min)(UINT64(window->second.end), end);
}
}
auto cpu_view = m.views.lower_bound(at);
auto gpu_view = gpu ? m.gpu_views.lower_bound(at) : m.gpu_views.end();
std::vector<Page> selected;
selected.reserve(page_count);
for (SIZE_T i = 0; i < page_count; ++i, at += page_size) {
if (gpu_view != m.gpu_views.end() && gpu_view->first == at) {
const auto& view = (gpu_view++)->second;
if (!view.source.group && use == RangeUse::native_buffer) return DXGI_ERROR_UNSUPPORTED;
if (use == RangeUse::sampled && view.fence) {
auto& last_signal = waits[view.fence];
last_signal = (std::max)(last_signal, view.value);
}
selected.push_back(view.source);
} else if (cpu_view != m.views.end() && cpu_view->first == at && cpu_view->second.group) {
selected.push_back(cpu_view->second);
} else return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
if (cpu_view != m.views.end() && cpu_view->first == at) ++cpu_view;
}
if (use == RangeUse::native_buffer) m.native_ranges.emplace(this, Memory::NativeRange{address - skip, &pages_});
zero = m.zero_page.Get();
for (const auto& p : selected) if (p.group) ++p.group->references[p.index];
pages_ = std::move(selected);
}
for (const auto& [fence, last_signal] : waits) {
if (fence->GetCompletedValue() < last_signal) {
const HRESULT hr = fence->SetEventOnCompletion(last_signal, nullptr);
if (FAILED(hr)) return hr;
}
if (fence->GetCompletedValue() == UINT64_MAX) return DXGI_ERROR_DEVICE_REMOVED;
}
// Most small textures occupy one section run, even with a nonzero
// placement offset. Fragmented allocations get contiguous read-only
// Windows views so XG can use its ordinary resource-base pointer.
for (const auto& p : pages_) {
const auto section = p.group ? p.group->file(p.index) : zero;
const UINT64 offset = p.group ? p.group->file_offset(p.index) : 0;
if (runs_.empty() || section != runs_.back().section || offset != runs_.back().offset + runs_.back().size)
runs_.push_back({section, offset, 0, nullptr});
runs_.back().size += page_size;
}
if (!data) return S_OK;
if (runs_.size() == 1) {
const auto& r = runs_.front();
base_ = static_cast<BYTE*>(MapViewOfFile(r.section, FILE_MAP_READ, static_cast<DWORD>(r.offset >> 32),
static_cast<DWORD>(r.offset), r.size));
if (!base_) return HRESULT_FROM_WIN32(GetLastError());
} else {
base_ = static_cast<BYTE*>(VirtualAlloc2(GetCurrentProcess(), nullptr, span_,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0));
if (!base_) return HRESULT_FROM_WIN32(GetLastError());
SIZE_T placed{};
for (auto& r : runs_) {
auto* next = base_ + placed;
placed += r.size;
if (placed < span_ && !VirtualFree(next, r.size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER))
return HRESULT_FROM_WIN32(GetLastError());
r.view = MapViewOfFile3(r.section, GetCurrentProcess(), next, r.offset, r.size,
MEM_REPLACE_PLACEHOLDER, PAGE_READONLY, nullptr, 0);
if (!r.view) return HRESULT_FROM_WIN32(GetLastError());
}
}
first_byte_ = skip;
*data = base_ + skip;
return S_OK;
}
~RangeLease() override {
if (base_ && runs_.size() == 1) UnmapViewOfFile(base_);
else if (base_) {
for (const auto& r : runs_) if (r.view) UnmapViewOfFile2(GetCurrentProcess(), r.view, MEM_PRESERVE_PLACEHOLDER);
VirtualFree(base_, span_, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS);
VirtualFree(base_, 0, MEM_RELEASE);
}
if (!pages_.empty()) {
auto& m = memory();
std::lock_guard lock(m.lock);
m.native_ranges.erase(this);
for (const auto& p : pages_) if (p.group) release_reference(m, p);
}
}
private:
struct Run { HANDLE section; UINT64 offset; SIZE_T size; void* view; };
std::vector<Page> pages_;
std::vector<Run> runs_;
BYTE* base_{};
SIZE_T span_{};
SIZE_T first_byte_{};
};
const XMEM_ALLOCATION_HOOKS* hooks() {
static const auto* table = std::bit_cast<const XMEM_ALLOCATION_HOOKS*>(
GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__"));
return table;
}
class TextureAddress final : public RuntimeClass<RuntimeClassFlags<ClassicCom>, IUnknown> {
public:
void* allocation{};
PXMEMFREE_ROUTINE free_hook{};
UINT64 attributes{};
~TextureAddress() {
if (allocation) {
if (free_hook) free_hook(allocation, attributes);
else VirtualFree(allocation, 0, MEM_RELEASE);
}
}
};
}
extern "C" XMEMALLOC_ROUTINE GdkHeapAllocDefault;
extern "C" XMEMFREE_ROUTINE GdkHeapFreeDefault;
HRESULT WINAPI RdnaConfigureGraphicsMemory(UINT units, UINT64* minimum, UINT64* exclusive_end) {
if (!minimum || !exclusive_end) return E_POINTER;
auto& m = memory();
std::lock_guard lock(m.lock);
if (!m.graphics_in_use) m.graphics_limit = graphics_end(units ? (std::min)(units, 33u) : default_table_units);
*minimum = graphics_minimum;
*exclusive_end = m.graphics_limit;
return m.graphics_in_use ? E_FAIL : S_OK;
}
void WINAPI RdnaGraphicsDeviceCreated() {
auto& m = memory();
std::lock_guard lock(m.lock);
m.graphics_in_use = true;
}
HRESULT WINAPI RdnaAcquireTextureAddress(SIZE_T bytes, SIZE_T alignment, BOOL display, UINT64* address, IUnknown** lease) {
if (!address || !lease) return E_POINTER;
*address = 0;
*lease = nullptr;
if (!bytes || !std::has_single_bit(alignment)) return E_INVALIDARG;
auto pin = Make<TextureAddress>();
if (!pin) return E_OUTOFMEMORY;
const auto* callbacks = display ? hooks() : nullptr;
UINT64 start{};
if (callbacks && callbacks->AllocRoutine && callbacks->FreeRoutine) {
// The Scarlett driver's FrontBufferAllocate requests a write-combined D3D front buffer (object 19)
// on 2 MiB pages. The title owns the pool and suballocates each texture at its layout alignment.
const UINT align = alignment <= 4 ? XALLOC_ALIGNMENT_4 : alignment <= 256 ? XALLOC_ALIGNMENT_256 :
alignment <= 4096 ? XALLOC_ALIGNMENT_4K : alignment <= page_size ? XALLOC_ALIGNMENT_64K : XALLOC_ALIGNMENT_128K;
pin->attributes = MAKE_XALLOC_ATTRIBUTES(eXALLOCAllocatorId_D3D, 19, XALLOC_MEMTYPE_GRAPHICS_WRITECOMBINE,
XALLOC_PAGESIZE_2MB, align, 0);
pin->free_hook = callbacks->FreeRoutine;
pin->allocation = callbacks->AllocRoutine(bytes, pin->attributes);
if (!pin->allocation) return E_OUTOFMEMORY;
start = reinterpret_cast<UINT64>(pin->allocation);
if (start % alignment) return HRESULT_FROM_WIN32(ERROR_MAPPED_ALIGNMENT);
auto& m = memory();
std::lock_guard lock(m.lock);
if (start < graphics_minimum || start >= m.graphics_limit || bytes > m.graphics_limit - start)
return HRESULT_FROM_WIN32(ERROR_INVALID_ADDRESS);
} else {
const SIZE_T extra = alignment > page_size ? alignment - page_size : 0;
if (bytes > SIZE_MAX - extra) return E_OUTOFMEMORY;
pin->allocation = XMemVirtualAlloc(nullptr, bytes + extra, MEM_RESERVE, XMEM_GRAPHICS, PAGE_NOACCESS);
if (!pin->allocation) return HRESULT_FROM_WIN32(GetLastError());
start = (reinterpret_cast<UINT64>(pin->allocation) + alignment - 1) & ~(alignment - 1);
}
*address = start;
*lease = pin.Detach();
return S_OK;
}
namespace {
bool needs_low_cpu_heap(ULONGLONG raw) {
const XALLOC_ATTRIBUTES a{raw};
return a.s.Address32BitMapping && a.s.MemoryType == XALLOC_MEMTYPE_HEAP_CACHEABLE &&
a.s.PageSize == XALLOC_PAGESIZE_4KB && a.s.Alignment <= XALLOC_ALIGNMENT_16;
}
}
PVOID WINAPI XMemGetTitleHeap() { return GetProcessHeap(); }
PVOID WINAPI XMemAllocDefault(SIZE_T size, ULONGLONG attributes) {
if (!size) return nullptr;
// This kit's plain HeapAlloc path ignores Address32BitMapping. The
// desktop process heap can exceed 4 GiB even for a small allocation.
if (needs_low_cpu_heap(attributes))
return XMemVirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT | 0x00800000, XMEM_CPU, PAGE_READWRITE);
return GdkHeapAllocDefault(size, attributes);
}
void WINAPI XMemFreeDefault(void* ptr, ULONGLONG attributes) {
if (!ptr) return;
if (needs_low_cpu_heap(attributes)) VirtualFree(ptr, 0, MEM_RELEASE);
else GdkHeapFreeDefault(ptr, attributes);
}
PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes) {
const auto* h = hooks();
return h && h->AllocRoutine ? h->AllocRoutine(size, attributes) : XMemAllocDefault(size, attributes);
}
void WINAPI XMemFree(void* ptr, ULONGLONG attributes) {
const auto* h = hooks();
if (h && h->FreeRoutine) h->FreeRoutine(ptr, attributes);
else if (ptr) XMemFreeDefault(ptr, attributes);
}
PVOID WINAPI XMemVirtualAlloc(PVOID base, SIZE_T size, DWORD type, ULONGLONG flags, DWORD protect) {
try {
auto& m = memory();
std::lock_guard lock(m.lock);
return reserve(m, base, size, type, flags, protect);
} catch (const std::bad_alloc&) { fail(ERROR_NOT_ENOUGH_MEMORY); return nullptr; }
}
BOOL WINAPI XMemVirtualQuery(HANDLE process, PVOID address, PXMEM_BASIC_INFORMATION out) {
if (!out || GetProcessId(process) != GetCurrentProcessId()) return fail();
auto& m = memory();
std::lock_guard lock(m.lock);
MEMORY_BASIC_INFORMATION info{};
if (!VirtualQueryEx(process, address, &info, sizeof info)) return FALSE;
*out = {};
out->BaseAddress = info.BaseAddress;
out->AllocationBase = info.AllocationBase;
out->AllocationProtect = info.AllocationProtect;
out->RegionSize = info.RegionSize;
out->State = info.State;
out->Protect = info.Protect;
out->Type = info.Type;
if (info.State != MEM_FREE) {
const auto it = window_at(m, reinterpret_cast<uintptr_t>(address));
if (it != m.windows.end() && (it->second.placeholder || reinterpret_cast<uintptr_t>(info.AllocationBase) == it->first)) {
out->XMemFlags = it->second.flags;
out->State |= it->second.page_type;
out->AllocationBase = reinterpret_cast<void*>(it->first);
out->AllocationProtect = it->second.protection;
if (info.State == MEM_COMMIT) out->Protect |= it->second.protection & ~DWORD{0x7ff};
out->TagCode = static_cast<DWORD>(out->XMemFlags >> 40);
if (out->TagCode) {
constexpr char alphabet[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$*";
for (unsigned i = 0; i < 4; ++i) out->TagFourCC[i] = alphabet[(out->TagCode >> (6 * i)) & 63];
}
} else if (info.Type == MEM_PRIVATE) out->XMemFlags = XMEM_CPU;
}
return TRUE;
}
BOOL WINAPI XMemAllocatePhysicalPages(ULONGLONG flags, PULONG_PTR count, PULONG_PTR pages) {
if (!count) return fail();
const auto n = *count;
*count = 0;
try { return allocate_pages(flags, n, count, pages); }
catch (const std::bad_alloc&) { return fail(ERROR_NOT_ENOUGH_MEMORY); }
}
BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR pages) {
if (!pages || !count || count > (standard_limit + optimal_limit) / page_size) return fail();
try {
std::vector<ULONG_PTR> sorted(pages, pages + count);
std::sort(sorted.begin(), sorted.end());
if (std::adjacent_find(sorted.begin(), sorted.end()) != sorted.end()) return fail();
auto& m = memory();
std::lock_guard lock(m.lock);
for (const auto token : sorted) if (!lookup(m, token).group) return fail();
for (const auto token : sorted) {
auto p = lookup(m, token);
p.group->owned &= ~(UINT32{1} << p.index);
release_reference(m, p);
if (!p.group->owned) m.groups.erase((token >> 4) - p.index);
}
return TRUE;
} catch (const std::bad_alloc&) { return fail(ERROR_NOT_ENOUGH_MEMORY); }
}
PVOID WINAPI XMemMapPhysicalPages(PVOID base, ULONG_PTR count, PULONG_PTR pages) {
try { return map_pages(base, nullptr, count, pages) ? base : nullptr; }
catch (const std::bad_alloc&) { fail(ERROR_NOT_ENOUGH_MEMORY); return nullptr; }
}
BOOL WINAPI XMemMapPhysicalPagesScatter(PVOID* addresses, ULONG_PTR count, PULONG_PTR pages) {
if (!addresses) return fail();
try { return map_pages(nullptr, addresses, count, pages); }
catch (const std::bad_alloc&) { return fail(ERROR_NOT_ENOUGH_MEMORY); }
}
BOOL WINAPI XMemIsToolsMemAvailable() { return FALSE; }
BOOL WINAPI XMemTransferMemory(XMEM_TRANSFER_TYPE direction, SIZE_T bytes) {
if (direction < XMemTransferTitleToSystem || direction > XMemTransferToolsToTitle) return fail();
if (!bytes) return TRUE;
if (direction != XMemTransferTitleToSystem) return fail(ERROR_NOT_SUPPORTED);
if (bytes > standard_limit) return fail(ERROR_NOT_ENOUGH_MEMORY);
const SIZE_T amount = (bytes + cluster_size - 1) & ~(cluster_size - 1);
auto& m = memory();
std::lock_guard lock(m.lock);
PROCESS_MEMORY_COUNTERS_EX process{};
if (!process_usage(process)) return FALSE;
if (amount > available(standard_limit - m.transferred, m.standard) ||
amount > available(standard_limit + optimal_limit - m.transferred, process.PrivateUsage + m.standard + m.optimal))
return fail(ERROR_NOT_ENOUGH_MEMORY);
m.transferred += amount;
return TRUE;
}
BOOL WINAPI XMemGetWorkingSetStatistics(DWORD flags, PXMEM_WORKING_SET_STATISTICS out) {
const bool extended = flags == 0x20000001 || flags == 0x2000000a;
if (!out || !flags || (!extended && (flags & ~XMEM_WORKING_SET_ALL))) return fail();
XMEM_WORKING_SET_STATISTICS result{};
if (flags & XMEM_WORKING_SET_STACK) {
const auto error = stack_usage(result.StackUsed);
if (error) return fail(error);
}
auto& m = memory();
std::lock_guard lock(m.lock);
PROCESS_MEMORY_COUNTERS_EX process{};
if (!process_usage(process)) return FALSE;
if ((flags & XMEM_WORKING_SET_TITLE) || extended) {
result.GameLimit = standard_limit + optimal_limit - m.transferred;
result.GameUsed = process.PrivateUsage + m.standard + m.optimal;
result.GpuOptimalBandwidthLimit = optimal_limit;
result.GpuOptimalBandwidthUsed = m.optimal;
}
const auto pool = static_cast<UINT32>((std::min)(SIZE_T{UINT32_MAX}, process.QuotaPagedPoolUsage + process.QuotaNonPagedPoolUsage));
if (extended) {
// The title's newer selector reads two additional DWORDs at 0x48 and
// 0x4c. Its 0x24 field counts physical pages. Legacy callers supply
// only the 72-byte structure from xmem.h.
struct TitleStatistics { XMEM_WORKING_SET_STATISTICS common; UINT32 pool_used, pool_limit; };
static_assert(offsetof(TitleStatistics, pool_used) == 0x48 && sizeof(TitleStatistics) == 0x50);
result.KernelPoolUsed = static_cast<UINT32>((m.standard + m.optimal) / page_size);
const TitleStatistics title{result, pool, 0};
std::memcpy(out, &title, sizeof title);
} else {
if (flags & XMEM_WORKING_SET_KERNEL_POOL) result.KernelPoolUsed = pool;
*out = result;
}
return TRUE;
}
HRESULT WINAPI RdnaAcquirePageSection(ULONG_PTR token, HANDLE* section, UINT64* offset, IUnknown** lease) {
if (!section || !offset || !lease) return E_POINTER;
*section = nullptr; *offset = 0; *lease = nullptr;
auto pin = Make<PageLease>();
if (!pin) return E_OUTOFMEMORY;
auto& m = memory();
std::lock_guard lock(m.lock);
auto page = lookup(m, token);
if (!page.group) return E_INVALIDARG;
if (!page.group->bind(page.index)) return HRESULT_FROM_WIN32(GetLastError());
++page.group->references[page.index];
*section = page.group->file(page.index);
*offset = page.group->file_offset(page.index);
pin->page = std::move(page);
*lease = pin.Detach();
return S_OK;
}