summaryrefslogtreecommitdiff
path: root/view/sharedcache/core/VM.cpp
blob: 711c2a8892ec1a6f5e2ef05fcd46456ef9681182 (plain)
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
//
// Created by kat on 5/23/23.
//

/*
	This is the cross-plat file buffering logic used for SharedCache processing.
 	This is used for reading large amounts of large files in a performant manner.

 	Here be no dragons, but this code is very complex, beware.

 	We in _all_ cases memory map the files, as we hardly ever need more than a few pages per file for most intensive operations.

 	Memory Map Implementation:
 		Of interest is that on several platforms we have to account for very low file pointer limits, and when mapping
 		40+ files, these are trivially reachable.

 		We handle this with a "SelfAllocatingWeakPtr":
 			- Calling .lock() ALWAYS delivers a shared_ptr guaranteed to stay valid. This may block waiting for a free pointer
			- As soon as that lock is released, that file pointer MAY be freed if another thread wants to open a new one, and we are at our limit.
			- Calling .lock() again on this same theoretical object will then wait for another file pointer to be freeable.

	VM Implementation:


 	Since the caches we're operating on are by nature page aligned, we are able to use nice optimizations under the hood to translate
 	"VM Addresses" to their actual in-memory counterparts.

 	We do this with a page table, which is a map of page -> file offset.

 	We also implement a "VMReader" here, which is a drop-in replacement for BinaryReader that operates on the VM.
 		see "ObjC.cpp" for where this is used.

*/


#include "VM.h"
#include <utility>
#include <memory>
#include <cstring>
#include <stdio.h>
#include <filesystem>
#include <binaryninjaapi.h>

#ifdef _MSC_VER
	#include <windows.h>
#else
	#include <sys/mman.h>
	#include <fcntl.h>
	#include <stdlib.h>
	#include <sys/resource.h>
#endif

static std::atomic<uint64_t> mmapCount = 0;

uint64_t MMapCount()
{
	return mmapCount;
}

void VMShutdown() {}


std::string ResolveFilePath(BinaryNinja::Ref<BinaryNinja::BinaryView> dscView, const std::string& path)
{
	auto dscProjectFile = dscView->GetFile()->GetProjectFile();
	BinaryNinja::LogDebugF(
		"ResolveFilePath:\n    of: {}\n    path: {}\n    pfn: {}\n    pfp: {}",
		dscView->GetFile()->GetOriginalFilename(),
		path,
		dscProjectFile ? dscProjectFile->GetName() : "",
		dscProjectFile ? dscProjectFile->GetPathOnDisk() : ""
	);

	// If we're not in a project, just return the path we were given
	if (!dscProjectFile)
	{
		return path;
	}

	// TODO: do we need to support looking in subfolders?
	// Replace project file path on disk with project file name for resolution
	std::string projectFilePathOnDisk = dscProjectFile->GetPathOnDisk();
	std::string originalFilePathOnDisk = dscView->GetFile()->GetOriginalFilename();
	std::string cleanPath = path;
	if (auto pindex = cleanPath.find(projectFilePathOnDisk); pindex != std::string::npos)
	{
		cleanPath.replace(pindex, projectFilePathOnDisk.size(), dscProjectFile->GetName());
	}
	else if (auto oindex = cleanPath.find(originalFilePathOnDisk); oindex != std::string::npos)
	{
		BinaryNinja::Ref<BinaryNinja::ProjectFile> originalProjectFile = dscProjectFile->GetProject()->GetFileByPathOnDisk(originalFilePathOnDisk);
		if (!originalProjectFile)
		{
			BinaryNinja::LogErrorF("Failed to resolve file path for {}: original file {} not found", path, originalFilePathOnDisk);
			return path;
		}
		cleanPath.replace(oindex, originalFilePathOnDisk.size(), originalProjectFile->GetName());
	}

	size_t lastSlashPos = cleanPath.find_last_of("/\\");
	std::string fileName;

	if (lastSlashPos != std::string::npos) {
		fileName = cleanPath.substr(lastSlashPos + 1);
	} else {
		fileName = cleanPath;
	}

	auto project = dscProjectFile->GetProject();
	auto dscProjectFolder = dscProjectFile->GetFolder();
	for (const auto& file : project->GetFiles())
	{
		auto fileFolder = file->GetFolder();
		bool isSibling = false;
		if (!dscProjectFolder && !fileFolder)
		{
			// Both top-level
			isSibling = true;
		}
		else if (dscProjectFolder && fileFolder)
		{
			// Have same parent folder
			isSibling = dscProjectFolder->GetId() == fileFolder->GetId();
		}

		if (isSibling && file->GetName() == fileName)
		{
			return file->GetPathOnDisk();
		}
	}

	BinaryNinja::LogErrorF("Failed to resolve file path for {}", path);

	// If we couldn't find a sibling filename, just return the path we were given
	return path;
}


void MMAP::Map()
{
	if (mapped)
		return;
#ifdef _MSC_VER
	LARGE_INTEGER fileSize;
	if (!GetFileSizeEx(hFile, &fileSize))
	{
		// Handle error
		CloseHandle(hFile);
		return;
	}
	len = static_cast<size_t>(fileSize.QuadPart);

	HANDLE hMapping = CreateFileMapping(
		hFile,                       // file handle
		NULL,                        // security attributes
		PAGE_WRITECOPY,              // protection
		0,                           // maximum size (high-order DWORD)
		0,                           // maximum size (low-order DWORD)
		NULL);                       // name of the mapping object

	if (hMapping == NULL)
	{
		// Handle error
		CloseHandle(hFile);
		return;
	}

	_mmap = static_cast<uint8_t*>(MapViewOfFile(
		hMapping,                    // handle to the file mapping object
		FILE_MAP_COPY,         		 // desired access
		0,                           // file offset (high-order DWORD)
		0,                           // file offset (low-order DWORD)
		0));                         // number of bytes to map (0 = entire file)

	if (_mmap == nullptr)
	{
		// Handle error
		CloseHandle(hMapping);
		CloseHandle(hFile);
		return;
	}

	mapped = true;

	CloseHandle(hMapping);
	CloseHandle(hFile);

#else
	fseek(fd, 0L, SEEK_END);
	len = ftell(fd);
	fseek(fd, 0L, SEEK_SET);

	void *result = mmap(nullptr, len, PROT_READ | PROT_WRITE, MAP_PRIVATE, fileno(fd), 0u);
	if (result == MAP_FAILED)
	{
		// Handle error
		return;
	}

	_mmap = static_cast<uint8_t*>(result);
	mapped = true;
#endif
}

void MMAP::Unmap()
{
#ifdef _MSC_VER
	if (_mmap)
	{
		UnmapViewOfFile(_mmap);
		mapped = false;
	}
#else
	if (mapped)
	{
		munmap(_mmap, len);
		mapped = false;
	}
#endif
}

FileAccessorCache& FileAccessorCache::Shared()
{
	static FileAccessorCache& shared = *new FileAccessorCache;
	return shared;
};

FileAccessorCache::FileAccessorCache() = default;

void FileAccessorCache::SetCacheSize(uint64_t cacheSize)
{
	m_cacheSize = cacheSize;
	EvictFromCacheIfNeeded();
}

void FileAccessorCache::RecordAccess(const std::string& path)
{
	auto it = m_accessors.find(path);
	if (it == m_accessors.end())
		return;

	// Move the entry for `path` to the end of `m_leastRecentlyOpened`.
	m_leastRecentlyOpened.splice(m_leastRecentlyOpened.end(), m_leastRecentlyOpened, it->second.second);
}

void FileAccessorCache::EvictFromCacheIfNeeded()
{
	std::lock_guard lock(m_mutex);
	while (m_accessors.size() > m_cacheSize)
	{
		m_accessors.erase(m_leastRecentlyOpened.front());
		m_leastRecentlyOpened.pop_front();
	}
}

std::shared_ptr<LazyMappedFileAccessor> FileAccessorCache::OpenLazily(
	const uint64_t sessionID, const std::string& path,
	std::function<void(std::shared_ptr<MMappedFileAccessor>)> postAllocationRoutine)
{
	std::lock_guard lock(m_mutex);
	if (auto it = m_lazyAccessors.find(path); it != m_lazyAccessors.end())
	{
		RecordAccess(path);
		return it->second;
	}

	auto accessor = std::make_shared<LazyMappedFileAccessor>(path,
		[=, postAllocationRoutine = std::move(postAllocationRoutine)](
			const std::string& path) {
			auto accessor = Open(sessionID, path);
			if (postAllocationRoutine)
			{
				postAllocationRoutine(accessor);
			}
			return accessor;
		});

	m_lazyAccessors.insert_or_assign(path, accessor);
	return accessor;
}

std::shared_ptr<MMappedFileAccessor> FileAccessorCache::Open(
	const uint64_t sessionID, const std::string& path)
{
	EvictFromCacheIfNeeded();

	mmapCount++;
	auto accessor = std::shared_ptr<MMappedFileAccessor>(new MMappedFileAccessor(path),
		[this](MMappedFileAccessor* accessor) { Close(accessor); });

	std::lock_guard lock(m_mutex);
	auto [it, inserted] = m_accessors.insert({path, {accessor, m_leastRecentlyOpened.end()}});
	if (inserted)
	{
		m_leastRecentlyOpened.push_back(path);
		it->second.second = std::prev(it->second.second);
	}
	else
	{
		RecordAccess(path);
	}

	return accessor;
}

void FileAccessorCache::Close(MMappedFileAccessor* accessor)
{
	mmapCount--;
	delete accessor;
}

std::shared_ptr<LazyMappedFileAccessor> MMappedFileAccessor::Open(
	const uint64_t sessionID, const std::string& path,
	std::function<void(std::shared_ptr<MMappedFileAccessor>)> postAllocationRoutine)
{
	return FileAccessorCache::Shared().OpenLazily(sessionID, path, std::move(postAllocationRoutine));
}

void MMappedFileAccessor::InitialVMSetup()
{
	static std::once_flag once;
	std::call_once(once, []{
		// check for BN_SHAREDCACHE_FP_MAX
		// if it exists, set maxFPLimit to that value
		unsigned long long maxFPLimit = 0;
		if (auto env = getenv("BN_SHAREDCACHE_FP_MAX"); env)
		{
			// FIXME behav on 0 here is unintuitive, '0123' will interpret as octal and be 83 according to manpage. meh.
			maxFPLimit = strtoull(env, nullptr, 0);
			if (maxFPLimit < 10)
			{
				BinaryNinja::LogWarn("BN_SHAREDCACHE_FP_MAX set to below 10. A value of at least 10 is recommended for performant analysis on SharedCache Binaries.");
			}
			if (maxFPLimit == 0)
			{
				BinaryNinja::LogError("BN_SHAREDCACHE_FP_MAX set to 0. Adjusting to 1");
				maxFPLimit = 1;
			}
		}
		else
		{
#ifdef _MSC_VER
			// It is not _super_ clear what the max file pointer limit is on windows,
			// 	but to my understanding, we are using the windows API to map files,
			// 	so we should have at least 2^24;
			// kind of funny to me that windows would be the most effecient OS to
			// parallelize sharedcache processing on in terms of FP usage concerns
			maxFPLimit = 0x1000000;
#else
			// The soft file descriptor limit on Linux and Mac is a lot lower than
			// on Windows (1024 for Linux, 256 for Mac). Recent iOS shared caches
			// have 60+ files which may not leave much headroom if a user opens
			// more than one at a time. Attempt to increase the file descriptor
			// limit to 1024, and limit ourselves to caching half of them as a
			// memory vs performance trade-off (closing and re-opening a file
			// requires parsing and applying the slide information again).
			constexpr rlim_t TargetFileDescriptorLimit = 1024;
			struct rlimit rlim;
			getrlimit(RLIMIT_NOFILE, &rlim);
			unsigned long long previousLimit = rlim.rlim_cur;
			if (rlim.rlim_cur < TargetFileDescriptorLimit)
			{
				rlim.rlim_cur = std::min(TargetFileDescriptorLimit, rlim.rlim_max);
				if (setrlimit(RLIMIT_NOFILE, &rlim) < 0)
				{
					perror("setrlimit(RLIMIT_NOFILE)");
					rlim.rlim_cur = previousLimit;
				}
			}
			maxFPLimit = rlim.rlim_cur / 2;
#endif
		}
		BinaryNinja::LogInfo("Shared Cache processing initialized with a max file descriptor limit of %lld", maxFPLimit);
		FileAccessorCache::Shared().SetCacheSize(maxFPLimit);
	});
}


MMappedFileAccessor::MMappedFileAccessor(const std::string& path) : m_path(path)
{
#ifdef _MSC_VER
	m_mmap.hFile = CreateFile(
		path.c_str(),              // file name
		GENERIC_READ,              // desired access (read-only)
        FILE_SHARE_READ,                         // share mode
		NULL,                      // security attributes
		OPEN_EXISTING,             // creation disposition
		FILE_ATTRIBUTE_NORMAL,     // flags and attributes
		NULL);                     // template file

	if (m_mmap.hFile == INVALID_HANDLE_VALUE)
	{
		// BNLogInfo("Couldn't read file at %s", path.c_str());
		throw MissingFileException();
	}

#else
#ifdef ABORT_FAILURES
	if (path.empty())
	{
		cerr << "Path is empty." << endl;
		abort();
	}
#endif
	m_mmap.fd = fopen(path.c_str(), "r");
	if (m_mmap.fd == nullptr)
	{
		BNLogError("Serious VM Error: Couldn't read file at %s", path.c_str());

#ifndef _MSC_VER
		try {
			throw BinaryNinja::ExceptionWithStackTrace("Unable to Read file");
		}
		catch (ExceptionWithStackTrace &ex)
		{
			BNLogError("%s", ex.m_stackTrace.c_str());
			BNLogError("Error: %d (%s)", errno, strerror(errno));
		}
#endif
		throw MissingFileException();
	}
#endif

	m_mmap.Map();
}

MMappedFileAccessor::~MMappedFileAccessor()
{
	// BNLogInfo("Unmapping %s", m_path.c_str());
	m_mmap.Unmap();

#ifdef _MSC_VER
	if (m_mmap.hFile != INVALID_HANDLE_VALUE)
	{
		CloseHandle(m_mmap.hFile);
	}
#else
	if (m_mmap.fd != nullptr)
	{
		fclose(m_mmap.fd);
	}
#endif
}

void MMappedFileAccessor::WritePointer(size_t address, size_t pointer)
{
	*(size_t*)&m_mmap._mmap[address] = pointer;
}

template <typename T>
T MMappedFileAccessor::Read(size_t address)
{
	T result;
	Read(&result, address, sizeof(T));
	return result;
}

std::string MMappedFileAccessor::ReadNullTermString(size_t address)
{
	if (address > m_mmap.len)
		return "";
	auto start = m_mmap._mmap + address;
	auto end = m_mmap._mmap + m_mmap.len;
	auto nul = std::find(start, end, 0);
	return std::string(start, nul);
}

uint8_t MMappedFileAccessor::ReadUChar(size_t address)
{
	return Read<uint8_t>(address);
}

int8_t MMappedFileAccessor::ReadChar(size_t address)
{
	return Read<int8_t>(address);
}

uint16_t MMappedFileAccessor::ReadUShort(size_t address)
{
	return Read<uint16_t>(address);
}

int16_t MMappedFileAccessor::ReadShort(size_t address)
{
	return Read<int16_t>(address);
}

uint32_t MMappedFileAccessor::ReadUInt32(size_t address)
{
	return Read<uint32_t>(address);
}

int32_t MMappedFileAccessor::ReadInt32(size_t address)
{
	return Read<int32_t>(address);
}

uint64_t MMappedFileAccessor::ReadULong(size_t address)
{
	return Read<uint64_t>(address);
}

int64_t MMappedFileAccessor::ReadLong(size_t address)
{
	return Read<int64_t>(address);
}

BinaryNinja::DataBuffer MMappedFileAccessor::ReadBuffer(size_t address, size_t length)
{
	if (m_mmap.len <= length || address > m_mmap.len - length)
		throw MappingReadException();

	return BinaryNinja::DataBuffer(&m_mmap._mmap[address], length);
}

std::pair<const uint8_t*, const uint8_t*> MMappedFileAccessor::ReadSpan(size_t address, size_t length)
{
	if (address > m_mmap.len)
		throw MappingReadException();
	if (address + length > m_mmap.len)
		throw MappingReadException();
	const uint8_t* data = (&(((uint8_t*)m_mmap._mmap)[address]));
	return {data, data + length};
}


void MMappedFileAccessor::Read(void* dest, size_t address, size_t length)
{
	if (m_mmap.len <= length || address > m_mmap.len - length)
		throw MappingReadException();

	memcpy(dest, &m_mmap._mmap[address], length);
}


VM::VM(size_t pageSize, bool safe) : m_pageSize(pageSize), m_safe(safe)
{
}

VM::~VM()
{
}


void VM::MapPages(BinaryNinja::Ref<BinaryNinja::BinaryView> dscView, uint64_t sessionID, size_t vm_address, size_t fileoff, size_t size, const std::string& filePath, std::function<void(std::shared_ptr<MMappedFileAccessor>)> postAllocationRoutine)
{
	// The mappings provided for shared caches will always be page aligned.
	// We can use this to our advantage and gain considerable performance via page tables.
	// This could probably be sped up if c++ were avoided?
	// We want to create a map of page -> file offset

	if (vm_address % m_pageSize != 0 || size % m_pageSize != 0)
	{
		throw MappingPageAlignmentException();
	}

	auto accessor =
		MMappedFileAccessor::Open(sessionID, ResolveFilePath(dscView, filePath), std::move(postAllocationRoutine));
	auto [it, inserted] = m_map.insert_or_assign({vm_address, vm_address + size}, PageMapping(std::move(accessor), fileoff));
	if (m_safe && !inserted)
	{
		BNLogWarn("Remapping page 0x%zx (f: 0x%zx)", vm_address, fileoff);
		throw MappingCollisionException();
	}
}

std::pair<PageMapping, size_t> VM::MappingAtAddress(size_t address)
{
	if (auto it = m_map.find(address); it != m_map.end())
	{
		// The PageMapping object returned contains the page, and more importantly, the file pointer (there can be
		// multiple in newer caches) This is relevant for reading out the data in the rest of this file.
		// The second item in the returned pair is the offset of `address` within the file.
		auto& range = it->first;
		auto& mapping = it->second;
		return {mapping, mapping.fileOffset + (address - range.start)};
	}

	throw MappingReadException();
}


bool VM::AddressIsMapped(uint64_t address)
{
	auto it = m_map.find(address);
	return it != m_map.end();
}


uint64_t VMReader::ReadULEB128(size_t limit)
{
	uint64_t result = 0;
	int bit = 0;
	auto mapping = m_vm->MappingAtAddress(m_cursor);
	auto fileCursor = mapping.second;
	auto fileLimit = fileCursor + (limit - m_cursor);
	auto fa = mapping.first.fileAccessor->lock();
	auto* fileBuff = (uint8_t*)fa->Data();
	do
	{
		if (fileCursor >= fileLimit)
			return -1;
		uint64_t slice = ((uint64_t*)&((fileBuff)[fileCursor]))[0] & 0x7f;
		if (bit > 63)
			return -1;
		else
		{
			result |= (slice << bit);
			bit += 7;
		}
	} while (((uint64_t*)&(fileBuff[fileCursor++]))[0] & 0x80);
	fa->Data(); // prevent deallocation of the fileAccessor as we're operating on the raw data buffer
	return result;
}


int64_t VMReader::ReadSLEB128(size_t limit)
{
	uint8_t cur;
	int64_t value = 0;
	size_t shift = 0;

	auto mapping = m_vm->MappingAtAddress(m_cursor);
	auto fileCursor = mapping.second;
	auto fileLimit = fileCursor + (limit - m_cursor);
	auto fa = mapping.first.fileAccessor->lock();
	auto* fileBuff = (uint8_t*)fa->Data();

	while (fileCursor < fileLimit)
	{
		cur = ((uint64_t*)&((fileBuff)[fileCursor]))[0];
		fileCursor++;
		value |= (cur & 0x7f) << shift;
		shift += 7;
		if ((cur & 0x80) == 0)
			break;
	}
	value = (value << (64 - shift)) >> (64 - shift);
	fa->Data(); // prevent deallocation of the fileAccessor as we're operating on the raw data buffer
	return value;
}

std::string VM::ReadNullTermString(size_t address)
{
	auto mapping = MappingAtAddress(address);
	return mapping.first.fileAccessor->lock()->ReadNullTermString(mapping.second);
}

uint8_t VM::ReadUChar(size_t address)
{
	auto mapping = MappingAtAddress(address);
	return mapping.first.fileAccessor->lock()->ReadUChar(mapping.second);
}

int8_t VM::ReadChar(size_t address)
{
	auto mapping = MappingAtAddress(address);
	return mapping.first.fileAccessor->lock()->ReadChar(mapping.second);
}

uint16_t VM::ReadUShort(size_t address)
{
	auto mapping = MappingAtAddress(address);
	return mapping.first.fileAccessor->lock()->ReadUShort(mapping.second);
}

int16_t VM::ReadShort(size_t address)
{
	auto mapping = MappingAtAddress(address);
	return mapping.first.fileAccessor->lock()->ReadShort(mapping.second);
}

uint32_t VM::ReadUInt32(size_t address)
{
	auto mapping = MappingAtAddress(address);
	return mapping.first.fileAccessor->lock()->ReadUInt32(mapping.second);
}

int32_t VM::ReadInt32(size_t address)
{
	auto mapping = MappingAtAddress(address);
	return mapping.first.fileAccessor->lock()->ReadInt32(mapping.second);
}

uint64_t VM::ReadULong(size_t address)
{
	auto mapping = MappingAtAddress(address);
	return mapping.first.fileAccessor->lock()->ReadULong(mapping.second);
}

int64_t VM::ReadLong(size_t address)
{
	auto mapping = MappingAtAddress(address);
	return mapping.first.fileAccessor->lock()->ReadLong(mapping.second);
}

BinaryNinja::DataBuffer VM::ReadBuffer(size_t addr, size_t length)
{
	auto mapping = MappingAtAddress(addr);
	return mapping.first.fileAccessor->lock()->ReadBuffer(mapping.second, length);
}


void VM::Read(void* dest, size_t addr, size_t length)
{
	auto mapping = MappingAtAddress(addr);
	mapping.first.fileAccessor->lock()->Read(dest, mapping.second, length);
}

VMReader::VMReader(std::shared_ptr<VM> vm, size_t addressSize) : m_vm(vm), m_cursor(0), m_addressSize(addressSize) {}


void VMReader::Seek(size_t address)
{
	m_cursor = address;
}

void VMReader::SeekRelative(size_t offset)
{
	m_cursor += offset;
}

std::string VMReader::ReadCString(size_t address)
{
	auto mapping = m_vm->MappingAtAddress(address);
	return mapping.first.fileAccessor->lock()->ReadNullTermString(mapping.second);
}

uint8_t VMReader::ReadUChar(size_t address)
{
	auto mapping = m_vm->MappingAtAddress(address);
	m_cursor = address + 1;
	return mapping.first.fileAccessor->lock()->ReadUChar(mapping.second);
}

int8_t VMReader::ReadChar(size_t address)
{
	auto mapping = m_vm->MappingAtAddress(address);
	m_cursor = address + 1;
	return mapping.first.fileAccessor->lock()->ReadChar(mapping.second);
}

uint16_t VMReader::ReadUShort(size_t address)
{
	auto mapping = m_vm->MappingAtAddress(address);
	m_cursor = address + 2;
	return mapping.first.fileAccessor->lock()->ReadUShort(mapping.second);
}

int16_t VMReader::ReadShort(size_t address)
{
	auto mapping = m_vm->MappingAtAddress(address);
	m_cursor = address + 2;
	return mapping.first.fileAccessor->lock()->ReadShort(mapping.second);
}

uint32_t VMReader::ReadUInt32(size_t address)
{
	auto mapping = m_vm->MappingAtAddress(address);
	m_cursor = address + 4;
	return mapping.first.fileAccessor->lock()->ReadUInt32(mapping.second);
}

int32_t VMReader::ReadInt32(size_t address)
{
	auto mapping = m_vm->MappingAtAddress(address);
	m_cursor = address + 4;
	return mapping.first.fileAccessor->lock()->ReadInt32(mapping.second);
}

uint64_t VMReader::ReadULong(size_t address)
{
	auto mapping = m_vm->MappingAtAddress(address);
	m_cursor = address + 8;
	return mapping.first.fileAccessor->lock()->ReadULong(mapping.second);
}

int64_t VMReader::ReadLong(size_t address)
{
	auto mapping = m_vm->MappingAtAddress(address);
	m_cursor = address + 8;
	return mapping.first.fileAccessor->lock()->ReadLong(mapping.second);
}


size_t VMReader::ReadPointer(size_t address)
{
	if (m_addressSize == 8)
		return ReadULong(address);
	else if (m_addressSize == 4)
		return ReadUInt32(address);

	// no idea what horrible arch we have, should probably die here.
	return 0;
}


size_t VMReader::ReadPointer()
{
	if (m_addressSize == 8)
		return Read64();
	else if (m_addressSize == 4)
		return Read32();

	return 0;
}

BinaryNinja::DataBuffer VMReader::ReadBuffer(size_t length)
{
	auto mapping = m_vm->MappingAtAddress(m_cursor);
	m_cursor += length;
	return mapping.first.fileAccessor->lock()->ReadBuffer(mapping.second, length);
}

BinaryNinja::DataBuffer VMReader::ReadBuffer(size_t addr, size_t length)
{
	auto mapping = m_vm->MappingAtAddress(addr);
	m_cursor = addr + length;
	return mapping.first.fileAccessor->lock()->ReadBuffer(mapping.second, length);
}

void VMReader::Read(void* dest, size_t length)
{
	auto mapping = m_vm->MappingAtAddress(m_cursor);
	m_cursor += length;
	mapping.first.fileAccessor->lock()->Read(dest, mapping.second, length);
}

void VMReader::Read(void* dest, size_t addr, size_t length)
{
	auto mapping = m_vm->MappingAtAddress(addr);
	m_cursor = addr + length;
	mapping.first.fileAccessor->lock()->Read(dest, mapping.second, length);
}


uint8_t VMReader::Read8()
{
	auto mapping = m_vm->MappingAtAddress(m_cursor);
	m_cursor += 1;
	return mapping.first.fileAccessor->lock()->ReadUChar(mapping.second);
}

int8_t VMReader::ReadS8()
{
	auto mapping = m_vm->MappingAtAddress(m_cursor);
	m_cursor += 1;
	return mapping.first.fileAccessor->lock()->ReadChar(mapping.second);
}

uint16_t VMReader::Read16()
{
	auto mapping = m_vm->MappingAtAddress(m_cursor);
	m_cursor += 2;
	return mapping.first.fileAccessor->lock()->ReadUShort(mapping.second);
}

int16_t VMReader::ReadS16()
{
	auto mapping = m_vm->MappingAtAddress(m_cursor);
	m_cursor += 2;
	return mapping.first.fileAccessor->lock()->ReadShort(mapping.second);
}

uint32_t VMReader::Read32()
{
	auto mapping = m_vm->MappingAtAddress(m_cursor);
	m_cursor += 4;
	return mapping.first.fileAccessor->lock()->ReadUInt32(mapping.second);
}

int32_t VMReader::ReadS32()
{
	auto mapping = m_vm->MappingAtAddress(m_cursor);
	m_cursor += 4;
	return mapping.first.fileAccessor->lock()->ReadInt32(mapping.second);
}

uint64_t VMReader::Read64()
{
	auto mapping = m_vm->MappingAtAddress(m_cursor);
	m_cursor += 8;
	return mapping.first.fileAccessor->lock()->ReadULong(mapping.second);
}

int64_t VMReader::ReadS64()
{
	auto mapping = m_vm->MappingAtAddress(m_cursor);
	m_cursor += 8;
	return mapping.first.fileAccessor->lock()->ReadLong(mapping.second);
}