-
Notifications
You must be signed in to change notification settings - Fork 1
/
kernel32.cpp
2776 lines (2519 loc) · 84.7 KB
/
kernel32.cpp
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 "kernel32.h"
#include "environment.h"
#include "wintypes.h"
using namespace wintypes;
#include "modules.h"
#include "native_api.h"
#include "intrusive_list.h"
#include <cstdint>
#include <mutex>
#include <deque>
#include <atomic>
#include <map>
#include <list>
#include <vector>
#include <chrono>
#include <ctime>
#include <thread>
#include <algorithm>
#include <array>
#include <memory>
#include <condition_variable>
#include <random>
namespace kernel32 {
;
modules::module_info* main_module_info = nullptr;
struct thread;
void deref_HANDLE(HANDLE h);
template<typename T>
struct handle {
HANDLE h = nullptr32;
T* ptr = nullptr;
handle() = default;
constexpr handle(std::nullptr_t) : ptr(nullptr) {}
explicit handle(HANDLE h, T* ptr) : h(h), ptr(ptr) {}
handle(const handle& n) = delete;
handle(handle&& n) {
h = n.h;
ptr = n.ptr;
n.ptr = nullptr;
n.h = nullptr32;
}
~handle() {
if (h) {
deref_HANDLE(h);
}
}
handle& operator=(const handle& n) = delete;
handle& operator=(handle&& n) {
std::swap(h, n.h);
std::swap(ptr, n.ptr);
return *this;
}
T& operator*() const {
return *ptr;
}
T* operator->() const {
return ptr;
}
T* get() const {
return ptr;
}
explicit operator bool() const {
return ptr != nullptr;
}
};
struct TLB {
DWORD last_error = 0;
DWORD thread_id = 0;
thread* current_thread = nullptr;
const handle<thread>* current_thread_handle;
};
thread_local TLB tlb;
FILETIME to_FILETIME(uint64_t val) {
return FILETIME { (DWORD)val, (DWORD)(val >> 32) };
}
uint64_t from_FILETIME(FILETIME val) {
return (uint64_t)val.dwLowDateTime | ((uint64_t)val.dwHighDateTime << 32);
}
static FILETIME time_point_to_FILETIME(std::chrono::system_clock::time_point time) {
auto c = std::chrono::duration_cast<std::chrono::duration<uint64_t, std::ratio<1, 10000000>>>(time - std::chrono::system_clock::from_time_t(0));
return to_FILETIME(c.count() + 116444736000000000);
}
static std::chrono::system_clock::time_point FILETIME_to_time_point(FILETIME time) {
auto r = std::chrono::system_clock::from_time_t(0);
return r + std::chrono::duration<uint64_t, std::ratio<1, 10000000>>(from_FILETIME(time) - 116444736000000000);
}
static FILETIME duration_to_FILETIME(std::chrono::system_clock::duration dur) {
auto c = std::chrono::duration_cast<std::chrono::duration<uint64_t, std::ratio<1, 10000000>>>(dur);
return to_FILETIME(c.count());
}
DWORD WINAPI GetLastError() {
return tlb.last_error;
}
void WINAPI SetLastError(DWORD err) {
//log("SetLastError %d\n", err);
tlb.last_error = err;
}
struct OSVERSIONINFOA {
DWORD dwOSVersionInfoSize;
DWORD dwMajorVersion;
DWORD dwMinorVersion;
DWORD dwBuildNumber;
DWORD dwPlatformId;
CHAR szCSDVersion[128];
};
BOOL WINAPI GetVersionExA(OSVERSIONINFOA* lpVersionInfo) {
if (lpVersionInfo->dwOSVersionInfoSize != sizeof(OSVERSIONINFOA)) {
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
lpVersionInfo->dwMajorVersion = 6;
lpVersionInfo->dwMinorVersion = 3;
lpVersionInfo->dwBuildNumber = 9200;
lpVersionInfo->dwPlatformId = 2;
return TRUE;
}
DWORD WINAPI GetVersion() {
return 6 | (3 << 8) | (9200 << 16);
}
HMODULE WINAPI GetModuleHandleA(const char* name) {
auto* i = name ? modules::get_module_info(name) : main_module_info;
if (!i) {
log("GetModuleHandle: module '%s' not found\n", name);
//fatal_error("'%s' not found", name);
SetLastError(ERROR_MOD_NOT_FOUND);
return nullptr32;
}
log("module '%s' is at %p\n", name, i->base);
return to_pointer32(i->base);
}
BOOL WINAPI GetModuleHandleExA(DWORD flags, const char* name, HMODULE* out_module) {
*out_module = nullptr32;
if (flags & 4) {
fatal_error("fixme: GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS");
}
auto* i = name ? modules::get_module_info(name) : main_module_info;
if (!i) {
log("GetModuleHandleEx: module '%s' not found\n", name);
//fatal_error("'%s' not found retaddr %p", name, _ReturnAddress());
SetLastError(ERROR_MOD_NOT_FOUND);
return FALSE;
}
*out_module = to_pointer32(i->base);
return TRUE;
}
void* WINAPI GetProcAddress(HMODULE hm, const char* name) {
auto* i = hm ? modules::get_module_info(to_pointer(hm)) : main_module_info;
if (!i) {
SetLastError(ERROR_MOD_NOT_FOUND);
log("GetProcAddress: module %p not found\n", to_pointer(hm));
return nullptr;
}
bool is_ordinal = (uintptr_t)name < 0x10000;
DWORD ordinal = (uintptr_t)name & 0xffff;
if (is_ordinal) name = "(ordinal)";
if (is_ordinal) {
size_t index = (size_t)ordinal - i->ordinal_base;
if (index < i->exports.size()) {
void* addr = i->exports[index];
log("GetProcAddress: %p ordinal %d found at %p\n", to_pointer(hm), ordinal, addr);
SetLastError(ERROR_SUCCESS);
return addr;
} else {
log("GetProcAddress: %p ordinal %d not found\n", to_pointer(hm), ordinal);
}
} else {
auto it = i->export_names.find(name);
if (it != i->export_names.end() && it->second < i->exports.size()) {
void* addr = i->exports[it->second];
log("GetProcAddress: %p::%s found at %p\n", to_pointer(hm), name, addr);
SetLastError(ERROR_SUCCESS);
return addr;
} else {
log("GetProcAddress: %p::%s not found\n", to_pointer(hm), name);
}
}
std::string override_name;
if (is_ordinal) override_name = format("%s:ordinal %d", i->lcase_name_no_ext, ordinal);
else override_name = format("%s:%s", i->lcase_name_no_ext, name);
void* r = environment::get_implemented_function(override_name);
//if (!r) r = environment::get_unimplemented_stub(override_name);
log("GetProcAddress: %p::%s (%s) -> %p\n", to_pointer(hm), name, override_name, r);
if (!r) {
SetLastError(ERROR_PROC_NOT_FOUND);
}
return r;
}
HMODULE WINAPI LoadLibraryA(const char* name) {
auto* i = modules::load_library(name, false, false);
if (!i) {
SetLastError(ERROR_FILE_NOT_FOUND);
return nullptr32;
}
log("LoadLibrary %s -> %p\n", name, i->base);
return to_pointer32(i->base);
}
HMODULE WINAPI LoadLibraryExA(const char* name, HANDLE h_reserved, DWORD flags) {
//fatal_error("LoadLibraryEx: name '%s', h_reserved %p, flags %x\n", name, h_reserved, flags);
log("LoadLibraryEx: name '%s', h_reserved %p, flags %x\n", name, h_reserved, flags);
auto* i = modules::load_library(name, false, false);
if (!i) {
log("not found :(\n");
SetLastError(ERROR_FILE_NOT_FOUND);
return nullptr32;
}
log("LoadLibraryEx %s -> %p\n", name, i->base);
return to_pointer32(i->base);
}
BOOL WINAPI FreeLibrary(HMODULE h) {
auto* i = modules::get_module_info(to_pointer(h));
if (!i) {
log("FreeLibrary: module %p not found\n", to_pointer(h));
SetLastError(ERROR_MOD_NOT_FOUND);
return FALSE;
}
log("FreeLibrary (%s): not supported\n", i->name);
return TRUE;
}
BOOL WINAPI DisableThreadLibraryCalls(HMODULE h) {
auto* i = modules::get_module_info(to_pointer(h));
if (!i) {
SetLastError(ERROR_MOD_NOT_FOUND);
return FALSE;
}
i->thread_library_calls_enabled = false;
return TRUE;
}
template<typename T, size_t list_size>
class id_list {
std::array<std::atomic<T>, list_size> list {};
// Just a hint, might be momentarily inaccurate.
std::atomic<size_t> n_available { list_size };
// Also just a hint to make searching faster.
std::atomic<size_t> next { 0 };
static const size_t npos = (size_t)-1;
public:
size_t allocate(T value) {
if (!value) fatal_error("id_list: allocate null value");
for (size_t i = next.load(std::memory_order_relaxed);; ++i) {
if (i >= list.size()) i = 0;
if (n_available.load(std::memory_order_relaxed) == 0) return npos;
auto& ref = list[i];
auto val = ref.load(std::memory_order_relaxed);
if (val) continue;
if (!ref.compare_exchange_weak(val, value, std::memory_order_relaxed)) continue;
next.store(i + 1, std::memory_order_relaxed);
n_available.fetch_sub(1, std::memory_order_relaxed);
return i;
}
}
T get(size_t index) {
return list[index].load(std::memory_order_consume);
}
void deallocate(size_t index) {
n_available.fetch_add(1, std::memory_order_relaxed);
list[index].store(nullptr, std::memory_order_relaxed);
}
bool deallocate_if_equal(size_t index, T compare_value) {
auto old_val = n_available.fetch_add(1, std::memory_order_relaxed);
if (replace_if_equal(index, compare_value, nullptr)) {
if (old_val == 0) next.store(index, std::memory_order_relaxed);
return true;
} else {
n_available.fetch_sub(1, std::memory_order_relaxed);
return false;
}
}
bool replace_if_equal(size_t index, T compare_value, T new_value) {
if (list[index].compare_exchange_weak(compare_value, new_value, std::memory_order_relaxed)) {
return true;
} else {
return false;
}
}
constexpr size_t size() const {
return list_size;
}
};
static const size_t npos = (size_t)-1;
struct object {
enum { t_invalid, t_thread, t_event, t_file, t_mutex, t_file_mapping };
virtual ~object() {}
int object_type = t_invalid;
std::atomic<size_t> refcount { 0 };
};
constexpr size_t handles_per_container = 0x100;
struct handle_container {
size_t base = 0;
std::atomic<handle_container*> next { nullptr };
id_list<object*, handles_per_container> list;
std::array<std::atomic_flag, handles_per_container> handle_is_closed {};
std::array<std::atomic<size_t>, handles_per_container> refcounts {};
};
handle_container root_handle_container;
std::mutex create_handle_container_mut;
std::atomic<handle_container*> next_handle_container { &root_handle_container };
std::atomic<size_t> total_allocated_handles;
HANDLE handle_n_to_HANDLE(size_t n) {
return to_pointer32((void*)((uintptr_t)(1 + n) << 2));
}
size_t HANDLE_to_handle_n(HANDLE h) {
return (size_t)(((uintptr_t)h >> 2) - 1);
}
std::pair<handle_container*, size_t> container_and_index_for_HANDLE(HANDLE h) {
size_t n = HANDLE_to_handle_n(h);
size_t container_n = n / handles_per_container;
handle_container* c = &root_handle_container;
for (; container_n; --container_n) {
c = c->next.load(std::memory_order_relaxed);
if (!c) return { nullptr, 0 };
}
size_t index = n % handles_per_container;
return { c, index };
}
template<typename T>
HANDLE new_HANDLE(T* obj) {
if (total_allocated_handles.load(std::memory_order_relaxed) >= 16 * 1024 * 1024) return nullptr32;
HANDLE r;
auto find = [&](handle_container* from, handle_container* to) {
for (auto* i = from; i != to; i = i->next.load(std::memory_order_consume)) {
size_t n = i->list.allocate(obj);
if (n != npos) {
next_handle_container.store(i, std::memory_order_relaxed);
if (i->refcounts[n].load(std::memory_order_relaxed)) fatal_error("new_HANDLE: refcount is non-zero");
i->refcounts[n].store(1, std::memory_order_relaxed);
r = handle_n_to_HANDLE(i->base + n);
log("created new handle %p\n", to_pointer(r));
return true;
}
}
return false;
};
auto* next = next_handle_container.load(std::memory_order_relaxed);
if (find(next, nullptr)) return r;
if (find(&root_handle_container, next)) return r;
std::lock_guard<std::mutex> l(create_handle_container_mut);
if (find(&root_handle_container, nullptr)) return r;
size_t base = 0;
handle_container* last_container = nullptr;
for (auto* i = &root_handle_container; i; i = i->next) {
base += handles_per_container;
last_container = i;
}
handle_container* new_container = new handle_container();
new_container->base = base;
if (!find(new_container, nullptr)) fatal_error("unreachable: failed to allocate handle from newly created container");
std::atomic_thread_fence(std::memory_order_release);
last_container->next.store(new_container, std::memory_order_relaxed);
return r;
}
void delete_object(object* o);
void deref_handle(handle_container* c, size_t index) {
if (c->refcounts[index].fetch_sub(1, std::memory_order_relaxed) == 1) {
auto* o = c->list.get(index);
c->list.deallocate(index);
if (o->refcount.fetch_sub(1, std::memory_order_release) == 1) {
delete_object(o);
}
}
}
void deref_HANDLE(HANDLE h) {
handle_container* c;
size_t index;
std::tie(c, index) = container_and_index_for_HANDLE(h);
if (!c) fatal_error("deref_HANDLE: no container for HANDLE %p\n", to_pointer(h));
deref_handle(c, index);
}
template<typename T>
HANDLE open_handle(T&& o) {
if (!o.h) fatal_error("attempt to open a null handle");
handle_container* c;
size_t index;
std::tie(c, index) = container_and_index_for_HANDLE(o.h);
c->handle_is_closed[index].clear(std::memory_order_relaxed);
HANDLE r = o.h;
o.h = nullptr32;
o.ptr = nullptr;
return r;
}
template<typename T>
handle<T> duplicate_handle(const handle<T>& o) {
HANDLE h = new_HANDLE(&*o);
if (!h) return nullptr;
return handle<T>(h, &*o);
}
template<typename T>
handle<T> new_object() {
auto o = std::make_unique<T>();
o->object_type = T::static_type;
o->refcount.fetch_add(1, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_release);
HANDLE h = new_HANDLE(&*o);
if (!h) {
fatal_error("new_object failed\n");
return nullptr;
}
log("new object %s handle %p\n", typeid(*o).name(), to_pointer(h));
return handle<T>(h, o.release());
}
void delete_object(object* o) {
log("delete object %s\n", typeid(*o).name());
std::atomic_thread_fence(std::memory_order_acquire);
delete o;
}
template<typename T>
bool object_is(object* o) {
return o->object_type == T::static_type;
}
template<>
bool object_is<object>(object* o) {
return true;
}
template<typename T>
handle<T> get_object(HANDLE h) {
handle_container* c;
size_t index;
std::tie(c, index) = container_and_index_for_HANDLE(h);
if (!c) {
log("get_object<%s> handle out of bounds\n", typeid(T).name());
return nullptr;
}
auto& ref = c->refcounts[index];
auto val = ref.load(std::memory_order_relaxed);
while (true) {
if (val == 0) {
log("get_object<%s> handle dead\n", typeid(T).name());
return nullptr;
}
if (ref.compare_exchange_weak(val, val + 1, std::memory_order_relaxed)) break;
}
auto o = c->list.get(index);
if (!object_is<T>(o)) {
log("get_object<%s> wrong object type\n", typeid(T).name());
deref_HANDLE(h);
return nullptr;
}
log("get_object<%s> success\n", typeid(T).name());
return handle<T>(h, (T*)o);
}
struct heap {
DWORD flags;
size_t initial_size;
size_t max_size;
};
std::list<heap> all_heaps;
std::mutex heap_mut;
struct alignas(int64_t) heap_block_header {
size_t size;
};
HANDLE WINAPI HeapCreate(DWORD flags, size_t initial_size, size_t max_size) {
std::lock_guard<std::mutex> l(heap_mut);
all_heaps.push_back({ flags,initial_size,max_size });
//log("HeapCreate %x %d %d\n", flags, initial_size, max_size);
return to_pointer32(&all_heaps.back()); // fixme pointer
}
void* WINAPI HeapAlloc(HANDLE hHeap, DWORD flags, size_t size) {
heap_block_header* h = (heap_block_header*)malloc(sizeof(heap_block_header) + size);
if (flags & 8) memset(h, 0, sizeof(heap_block_header) + size);
h->size = size;
//log("HeapAlloc -> %p\n", h + 1);
return h + 1;
}
void* WINAPI HeapReAlloc(HANDLE hHeap, DWORD flags, void* ptr, size_t size) {
void* new_ptr = HeapAlloc(hHeap, flags, size);
heap_block_header* h = (heap_block_header*)ptr - 1;
memcpy(new_ptr, ptr, std::min(size, h->size));
return new_ptr;
}
BOOL WINAPI HeapFree(HANDLE hHeap, DWORD flags, void* ptr) {
heap_block_header* h = (heap_block_header*)ptr - 1;
free(h);
return TRUE;
}
SIZE_T WINAPI HeapSize(HANDLE hHeap, DWORD flags, void* ptr) {
heap_block_header* h = (heap_block_header*)ptr - 1;
return h->size;
}
void WINAPI InitializeCriticalSection(CRITICAL_SECTION* cs) {
cs->DebugInfo = nullptr;
cs->LockCount = -1;
cs->RecursionCount = 0;
cs->OwningThread = nullptr32;
cs->LockSemaphore = to_pointer32(new std::recursive_mutex()); // fixme pointer
cs->SpinCount = 0;
}
BOOL WINAPI InitializeCriticalSectionAndSpinCount(CRITICAL_SECTION* cs, DWORD SpinCount) {
cs->DebugInfo = nullptr;
cs->LockCount = -1;
cs->RecursionCount = 0;
cs->OwningThread = nullptr32;
cs->LockSemaphore = to_pointer32(new std::recursive_mutex()); // fixme pointer
cs->SpinCount = SpinCount;
return TRUE;
}
void WINAPI DeleteCriticalSection(CRITICAL_SECTION* cs) {
cs->DebugInfo = nullptr;
cs->LockCount = 0;
cs->RecursionCount = 0;
cs->OwningThread = nullptr32;
delete (std::recursive_mutex*)to_pointer(cs->LockSemaphore); // fixme pointer
cs->LockSemaphore = nullptr32;
cs->SpinCount = 0;
}
void WINAPI EnterCriticalSection(CRITICAL_SECTION* cs) {
((std::recursive_mutex*)to_pointer(cs->LockSemaphore))->lock();
}
void WINAPI LeaveCriticalSection(CRITICAL_SECTION* cs) {
((std::recursive_mutex*)to_pointer(cs->LockSemaphore))->unlock();
}
struct local_storage_register {
struct index {
std::atomic<bool> busy { false };
void* callback = nullptr;
};
std::vector<index> ls = std::vector<index>(1088);
std::atomic<size_t> next_index;
};
struct local_storage {
std::vector<void*> ls = std::vector<void*>(1088);
local_storage_register& reg;
local_storage(local_storage_register& reg) : reg(reg) {}
void*& operator[](size_t index) {
return ls[index];
}
size_t get_next_index() {
size_t index = reg.next_index.load(std::memory_order_relaxed);
if (index >= ls.size()) {
return 0xffffffff;
}
while (!reg.next_index.compare_exchange_weak(index, index + 1, std::memory_order_relaxed, std::memory_order_relaxed)) {
if (index >= ls.size()) {
return 0xffffffff;
}
}
return index;
}
size_t get_free_index() {
auto take = [&](size_t index) {
bool was_busy = reg.ls[index].busy.load(std::memory_order_relaxed);
if (was_busy) return false;
return reg.ls[index].busy.compare_exchange_weak(was_busy, true, std::memory_order_relaxed, std::memory_order_relaxed);
};
size_t index = get_next_index();
while (index < ls.size()) {
if (take(index)) return index;
index = get_next_index();
}
for (index = 0; index != ls.size(); ++index) {
if (take(index)) return index;
}
return 0xffffffff;
}
};
local_storage_register fls_reg;
thread_local local_storage fls(fls_reg);
DWORD WINAPI FlsAlloc(void* callback) {
size_t index = fls.get_free_index();
if (index == 0xffffffff) return 0xffffffff;
fls.reg.ls[index].callback = callback;
log("FlsAlloc -> %d\n", index);
return index;
}
BOOL WINAPI FlsFree(DWORD index) {
if (index >= fls.reg.next_index || !fls.reg.ls[index].busy) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
fls.reg.ls[index].busy = false;
return TRUE;
}
BOOL WINAPI FlsSetValue(DWORD index, void* data) {
if (index >= fls.reg.next_index || !fls.reg.ls[index].busy) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
fls[index] = data;
//log("FlsSetValue %d -> %p\n", index, data);
return TRUE;
}
void* WINAPI FlsGetValue(DWORD index) {
if (index >= fls.reg.next_index || !fls.reg.ls[index].busy) {
SetLastError(ERROR_INVALID_PARAMETER);
//log("FlsGetValue failed\n");
return nullptr;
}
//log("FlsGetValue %d -> %p\n", index, fls[index].data);
return fls[index];
}
local_storage_register tls_reg;
thread_local local_storage tls(tls_reg);
DWORD WINAPI TlsAlloc() {
size_t index = tls.get_free_index();
if (index == 0xffffffff) return 0xffffffff;
tls.reg.ls[index].callback = nullptr;
//log("TlsAlloc -> %d\n", index);
return index;
}
BOOL WINAPI TlsFree(DWORD index) {
if (index >= tls.reg.next_index || !tls.reg.ls[index].busy) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
tls.reg.ls[index].busy = false;
return TRUE;
}
BOOL WINAPI TlsSetValue(DWORD index, void* data) {
if (index >= tls.reg.next_index || !tls.reg.ls[index].busy) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
tls[index] = data;
//log("TlsSetValue %d -> %p\n", index, data);
return TRUE;
}
void* WINAPI TlsGetValue(DWORD index) {
if (index >= tls.reg.next_index || !tls.reg.ls[index].busy) {
SetLastError(ERROR_INVALID_PARAMETER);
//log("TlsGetValue failed\n");
return nullptr;
}
//log("TlsGetValue %d -> %p\n", index, tls[index].data);
return tls[index];
}
DWORD WINAPI GetModuleFileNameA(HMODULE hm, char* dst, DWORD size) {
auto* i = hm ? modules::get_module_info(to_pointer(hm)) : main_module_info;
if (!i) {
log("GetModuleFileName %p module not found\n", to_pointer(hm));
SetLastError(ERROR_MOD_NOT_FOUND);
return 0;
}
auto& module_filename = i->full_path;
if (size < module_filename.size() + 1) {
if (size) {
memcpy(dst, module_filename.data(), size - 1);
dst[size - 1] = 0;
}
log("GetModuleFileName insufficient buffer\n");
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return size;
} else {
memcpy(dst, module_filename.data(), module_filename.size());
dst[module_filename.size()] = 0;
log("GetModuleFileName %p -> '%s'\n", to_pointer(hm), dst);
SetLastError(ERROR_SUCCESS);
return module_filename.size();
}
}
HANDLE WINAPI GetCurrentThread() {
return (HANDLE)-3;
}
DWORD WINAPI GetCurrentThreadId() {
return tlb.thread_id;
}
void WINAPI GetStartupInfoA(STARTUPINFOA* i) {
memset(i, 0, sizeof(*i));
i->cb = sizeof(STARTUPINFOA);
}
void WINAPI GetStartupInfoW(STARTUPINFOW* i) {
memset(i, 0, sizeof(*i));
i->cb = sizeof(STARTUPINFOW);
}
struct file : object {
static const auto static_type = object::t_file;
DWORD access = 0;
FILE_TYPE file_type = FILE_TYPE_UNKNOWN;
std::function<uint64_t(uint64_t offset, MOVE_METHOD method)> set_pos;
std::function<uint64_t()> get_pos;
std::function<bool(void* buffer, size_t to_read, size_t* read)> read;
std::function<bool(void* buffer, size_t to_write, size_t* written)> write;
std::function<uint64_t()> get_size;
};
handle<file> new_console_handle(bool input, bool output) {
auto o = new_object<file>();
if (o) {
if (input) o->access |= GENERIC_READ;
if (output) o->access |= GENERIC_WRITE;
}
o->file_type = FILE_TYPE_CHAR;
return o;
}
HANDLE std_input_handle;
HANDLE std_output_handle;
HANDLE std_error_handle;
HANDLE WINAPI GetStdHandle(DWORD n) {
if (n == (DWORD)-10) return std_input_handle;
if (n == (DWORD)-11) return std_output_handle;
if (n == (DWORD)-12) return std_error_handle;
SetLastError(ERROR_INVALID_PARAMETER);
return INVALID_HANDLE_VALUE;
}
DWORD WINAPI GetFileType(HANDLE h) {
auto o = get_object<file>(h);
if (!o) {
SetLastError(ERROR_INVALID_HANDLE);
return FILE_TYPE_UNKNOWN;
}
log("GetFileType %p -> %d\n", to_pointer(h), (DWORD)o->file_type);
SetLastError(ERROR_SUCCESS);
return o->file_type;
}
UINT WINAPI SetHandleCount(UINT n) {
return n;
}
struct page_attributes {
bool was_ever_committed = false;
PAGE_PROTECT protect = (PAGE_PROTECT)0;
MEM_STATE state = (MEM_STATE)0;
};
struct virtual_region {
void* base;
size_t size;
std::vector<page_attributes> pages;
PAGE_PROTECT allocation_protect;
};
std::map<void*, virtual_region> virtual_regions;
std::mutex virtual_mut;
size_t vm_total_allocated = 0;
void add_virtual_region_nolock(void* addr, size_t size, MEM_STATE state, PAGE_PROTECT protect) {
if ((uintptr_t)addr & 0xfff) fatal_error("attempt to add virtual region not on page boundary");
size = (size + 0xfff) & ~0xfff;
log("add virtual region [%p, %p)\n", addr, (char*)addr + size);
auto i = virtual_regions.lower_bound(addr);
if (i != virtual_regions.begin()) {
auto pi = i;
--pi;
auto* pr = &pi->second;
if ((char*)pr->base + pr->size > addr) fatal_error("attempt to add an already mapped virtual region");
}
if (i != virtual_regions.end()) {
auto* nr = &i->second;
if ((char*)addr + size > nr->base) fatal_error("attempt to add an already mapped virtual region");
}
size_t pages = size / 0x1000;
auto it = virtual_regions.emplace(addr, virtual_region { addr, size, std::vector<page_attributes>(pages), protect });
for (auto& v : it.first->second.pages) {
v.protect = protect;
v.state = state;
}
vm_total_allocated += size;
//log("added virtual region [%p, %p)\n", addr, (char*)addr + size);
}
void add_virtual_region(void* addr, size_t size, MEM_STATE state, PAGE_PROTECT protect) {
std::lock_guard<std::mutex> l(virtual_mut);
add_virtual_region_nolock(addr, size, state, protect);
}
void remove_virtual_region_nolock(void* addr) {
auto i = virtual_regions.find(addr);
vm_total_allocated -= i->second.size;
virtual_regions.erase(i);
}
void remove_virtual_region(void* addr) {
std::lock_guard<std::mutex> l(virtual_mut);
remove_virtual_region_nolock(addr);
}
virtual_region* find_virtual_region(void* addr) {
auto i = virtual_regions.upper_bound(addr);
if (i == virtual_regions.begin()) return nullptr;
--i;
auto* r = &i->second;
if ((char*)r->base + r->size <= addr) return nullptr;
return r;
}
native_api::memory_access access_from_protect(PAGE_PROTECT protect) {
if (protect & PAGE_READONLY) return native_api::memory_access::read;
else if (protect & PAGE_READWRITE) return native_api::memory_access::read_write;
else if (protect & PAGE_EXECUTE) return native_api::memory_access::read_execute;
else if (protect & PAGE_EXECUTE_READ) return native_api::memory_access::read_execute;
else if (protect & PAGE_EXECUTE_READWRITE) return native_api::memory_access::read_write_execute;
return native_api::memory_access::none;
}
const uintptr_t vm_begin_addr = (uintptr_t)64 * 1024 * 1024;
const uintptr_t vm_end_addr = (uintptr_t)2048 * 1024 * 1024;
const uintptr_t vm_search_granularity = (uintptr_t)1024 * 1024;
const uintptr_t vm_allocation_granularity = (uintptr_t)64 * 1024;
uintptr_t next_addr = vm_begin_addr;
void* virtual_allocate_nolock(void* addr, size_t size, MEM_STATE allocation_type, PAGE_PROTECT protect, void* preferred_addr) {
native_api::allocated_memory mem;
native_api::memory_access access = native_api::memory_access::none;
if (allocation_type == MEM_COMMIT) {
access = access_from_protect(protect);
} else if (allocation_type == MEM_RESERVE) {
protect = PAGE_NOACCESS;
access = access_from_protect(protect);
} else {
fatal_error("virtual_allocate_nolock: invalid allocation_type %#x\n", allocation_type);
}
size = (size + 0xfff) & ~0xfff;
if (addr) {
mem.allocate(addr, size, access);
} else {
auto next_allocation_granularity = [&](uintptr_t ptr) {
return (ptr + vm_allocation_granularity - 1) & ~(vm_allocation_granularity - 1);
};
auto trymap = [&](uintptr_t begin, uintptr_t end) {
log("trying to map in range [%p, %p)\n", (void*)begin, (void*)end);
begin = next_allocation_granularity(begin);
mem.allocate((void*)begin, size, access);
if (mem) return true;
auto next = next_allocation_granularity(begin + size);
if (next != begin) {
mem.allocate((void*)next, size, access);
if (mem) return true;
}
next += vm_allocation_granularity;
for (uintptr_t i = (begin + size + vm_search_granularity - 1)&~(vm_search_granularity - 1); i < end; i += vm_search_granularity) {
mem.allocate((void*)i, size, access);
if (mem) return true;
}
return false;
};
auto search = [&](uintptr_t begin, uintptr_t end) {
log("search %p %p\n", (void*)begin, (void*)end);
auto i = virtual_regions.upper_bound((void*)begin);
if (i != virtual_regions.begin()) {
--i;
uintptr_t ie = (uintptr_t)i->first + i->second.size;
if (ie > begin) begin = ie;
++i;
}
uintptr_t taddr = begin;
while (i != virtual_regions.end()) {
uintptr_t ib = (uintptr_t)i->first;
if (taddr + size <= ib && trymap(taddr, ib)) {
return;
}
taddr = ib + i->second.size;
++i;
}
trymap(taddr, end);
};
if (preferred_addr) {
search((uintptr_t)preferred_addr, vm_end_addr);
if (!mem) search(vm_begin_addr, (uintptr_t)preferred_addr);
} else {
search(next_addr, vm_end_addr);
if (!mem) search(vm_begin_addr, next_addr);
if (mem) next_addr = (uintptr_t)mem.ptr + size;
}
}
if (!mem) return nullptr;
void* ptr = mem.detach();
add_virtual_region_nolock(ptr, size, allocation_type, protect);
log("virtual allocate -> %p\n", ptr);
// log("virtual regions -\n");
// for (auto& v : virtual_regions) {
// log(" [%p, %p)\n", v.second.base, (uint8_t*)v.second.base + v.second.size);
// }
return ptr;
}
void virtual_deallocate_nolock(virtual_region* r) {
native_api::allocated_memory mem(r->base, r->size);
log("released [%p, %p)\n", r->base, (uint8_t*)r->base + r->size);
remove_virtual_region_nolock(r->base);
}
void* virtual_allocate(void* addr, size_t size, MEM_STATE allocation_type, PAGE_PROTECT protect, void* preferred_addr) {
std::lock_guard<std::mutex> l(virtual_mut);
return virtual_allocate_nolock(addr, size, allocation_type, protect, preferred_addr);
}
void virtual_deallocate(void* addr) {
std::lock_guard<std::mutex> l(virtual_mut);
auto* r = find_virtual_region(addr);
if (!r) fatal_error("attempt to free non-existing virtual region at %p\n", addr);
return virtual_deallocate_nolock(r);
}
void virtual_protect_nolock(virtual_region* r, size_t page_begin, size_t page_end, PAGE_PROTECT protect) {
auto access = access_from_protect(protect);
for (size_t p = page_begin; p != page_end; ++p) {
if (r->pages[p].state == MEM_COMMIT && ~r->pages[p].protect != protect) {
native_api::set_memory_access((uint8_t*)r->base + p * 0x1000, 0x1000, access);
r->pages[p].protect = protect;
}
}
}
void virtual_protect(void* addr, size_t size, PAGE_PROTECT protect) {
auto* r = find_virtual_region(addr);
if (!r) fatal_error("virtual_protect: no region at %p", addr);
uintptr_t offset = ((uintptr_t)addr - (uintptr_t)r->base) & ~0xfff;
size_t page = offset / 0x1000;
size_t pages = (size + 0xfff) / 0x1000;
virtual_protect_nolock(r, page, page + pages, protect);
}
SIZE_T WINAPI VirtualQuery(void* addr, MEMORY_BASIC_INFORMATION* buffer, size_t buffer_size) {
log("VirtualQuery %p\n", addr);
std::lock_guard<std::mutex> l(virtual_mut);
auto* r = find_virtual_region(addr);
if (buffer_size < sizeof(MEMORY_BASIC_INFORMATION)) {
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return 0;
}
uintptr_t offset = ((uintptr_t)addr - (uintptr_t)r->base) & ~0xfff;
size_t page = offset / 0x1000;
auto state = r->pages[page].state;
auto protect = r->pages[page].protect;
size_t pages = 1;
for (size_t i = page + 1; i != r->pages.size(); ++i) {
if (r->pages[page].state != state || r->pages[page].protect != protect) break;
++pages;
}
buffer->BaseAddress = (uint8_t*)r->base + offset;
buffer->AllocationBase = r->base;