/
Memory.cc
1597 lines (1220 loc) · 38.2 KB
/
Memory.cc
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
////////////////////////////////////////////////////////////////////////////////
// -------------------------------------------------------------------------- //
// //
// (C) 2010-2017 Robot Developers //
// See LICENSE for licensing info //
// //
// -------------------------------------------------------------------------- //
////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------//
// Prefaces //
//----------------------------------------------------------------------------//
#include <cassert>
#include "Process.h"
#include "Memory.h"
#include "System.h"
#include <algorithm>
using std::search;
using std::vector;
#include <unordered_map>
using std::unordered_map;
#ifdef ROBOT_OS_LINUX
#include <string>
using std::string;
using std::sort;
#include <cstring>
#include <fstream>
using std::ios;
using std::fstream;
using std::getline;
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
// Path to proc directory
#define PROC_PATH "/proc/"
#endif
#ifdef ROBOT_OS_MAC
#include <unistd.h>
#include <mach/mach_vm.h>
// Handle shortcut
#define ProcHandle \
((task_t) mData->Proc.GetHandle())
#endif
#ifdef ROBOT_OS_WIN
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
// Handle shortcut
#define ProcHandle \
((HANDLE) mData->Proc.GetHandle())
#endif
ROBOT_NS_BEGIN
//----------------------------------------------------------------------------//
// Macros //
//----------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////
#define SET_A_FLAG( i, aID, aV ) \
if (accessFlags[i] == '\0') \
goto skip; \
\
if (accessFlags[i] != ' ' && \
accessFlags[i] != '-' && \
accessFlags[i] != aID && \
accessFlags[i] !=(aID|32)) \
return result; \
\
aV =accessFlags[i] | 32;
////////////////////////////////////////////////////////////////////////////////
#define HEX_TO_INT( hiVal, loVal ) \
if (high) \
{ \
byte.Data = hiVal; \
byte.Wild = false; \
} \
\
else \
{ \
byte.Data += loVal; \
compiled.push_back (byte); \
} \
\
high = !high; break;
//----------------------------------------------------------------------------//
// Locals //
//----------------------------------------------------------------------------//
#ifdef ROBOT_OS_LINUX
////////////////////////////////////////////////////////////////////////////////
struct Mapping
{
uintptr Start; // Start address of region
uintptr Stop; // Stop address of region
char Access[5]; // Region protection value
};
#endif
////////////////////////////////////////////////////////////////////////////////
struct PatternByte
{
uint8 Data; // Single byte of data
bool Wild; // If data is wildcard
};
////////////////////////////////////////////////////////////////////////////////
static bool SearchWild (uint8 c, const PatternByte& b)
{
// Check for wildcard values
return b.Wild || c == b.Data;
}
////////////////////////////////////////////////////////////////////////////////
static bool SearchNorm (uint8 c, const PatternByte& b)
{
// Ignore wildcards
return c == b.Data;
}
//----------------------------------------------------------------------------//
// Classes Memory //
//----------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////
typedef unordered_map<uintptr, uintptr> PageMap;
////////////////////////////////////////////////////////////////////////////////
struct Memory::Data
{
Process Proc; // The process object
uint8* Cache; // Cached memory data
PageMap Pages; // Page pointers (R->C)
uintptr Next; // The next free page
uintptr BlockLength; // Single block size
uintptr BlockBuffer; // Maximum read size
uintptr CacheSize; // Current cache size
uintptr EnlargeSize; // Cache enlarge size
uintptr MaximumSize; // Maximum cache size
uint32 SystemReads; // Total system reads
uint32 CachedReads; // Total cached reads
uint32 SystemWrites; // Total system writes
uint32 AccessWrites; // Total access writes
uint32 ReadErrors; // Total read errors
uint32 WriteErrors; // Total write errors
int32 MemoryFile; // Linux proc mem file
};
//----------------------------------------------------------------------------//
// Operators Memory::Stats //
//----------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////
bool Memory::Stats::operator == (const Stats& stats) const
{
return SystemReads == stats.SystemReads &&
CachedReads == stats.CachedReads &&
SystemWrites == stats.SystemWrites &&
AccessWrites == stats.AccessWrites &&
ReadErrors == stats. ReadErrors &&
WriteErrors == stats.WriteErrors;
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::Stats::operator != (const Stats& stats) const
{
return SystemReads != stats.SystemReads ||
CachedReads != stats.CachedReads ||
SystemWrites != stats.SystemWrites ||
AccessWrites != stats.AccessWrites ||
ReadErrors != stats. ReadErrors ||
WriteErrors != stats.WriteErrors;
}
//----------------------------------------------------------------------------//
// Functions Memory::Region //
//----------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////
bool Memory::Region::Contains (uintptr address) const
{
return Start <= address && address < Stop;
}
//----------------------------------------------------------------------------//
// Operators Memory::Region //
//----------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////
bool Memory::Region::operator < (uintptr address) const
{
return Start < address;
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::Region::operator > (uintptr address) const
{
return Start > address;
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::Region::operator <= (uintptr address) const
{
return Start <= address;
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::Region::operator >= (uintptr address) const
{
return Start >= address;
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::Region::operator < (const Region& region) const
{
return Start < region.Start;
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::Region::operator > (const Region& region) const
{
return Start > region.Start;
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::Region::operator <= (const Region& region) const
{
return Start <= region.Start;
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::Region::operator >= (const Region& region) const
{
return Start >= region.Start;
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::Region::operator == (const Region& region) const
{
return Valid == region.Valid &&
Bound == region.Bound &&
Start == region.Start &&
Stop == region.Stop &&
Size == region.Size &&
Readable == region.Readable &&
Writable == region.Writable &&
Executable == region.Executable &&
Access == region.Access &&
Private == region.Private &&
Guarded == region.Guarded;
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::Region::operator != (const Region& region) const
{
return Valid != region.Valid ||
Bound != region.Bound ||
Start != region.Start ||
Stop != region.Stop ||
Size != region.Size ||
Readable != region.Readable ||
Writable != region.Writable ||
Executable != region.Executable ||
Access != region.Access ||
Private != region.Private ||
Guarded != region.Guarded;
}
//----------------------------------------------------------------------------//
// Constructors Memory //
//----------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////
Memory::Memory (const Process& p)
: mData (new Memory::Data(),
[] (Memory::Data* data)
{
// Delete the memory cache
if (data->Cache != nullptr)
delete[] data->Cache;
#ifdef ROBOT_OS_LINUX
// Close memory file if open
if (data->MemoryFile != -1)
close (data->MemoryFile);
#endif
// Free data
delete data;
})
{
mData->Proc = p;
mData->Cache = nullptr;
mData->Next = 0;
mData->BlockLength = 0;
mData->BlockBuffer = 0;
mData-> CacheSize = 0;
mData->EnlargeSize = 0;
mData->MaximumSize = 0;
mData->SystemReads = 0;
mData->CachedReads = 0;
mData->SystemWrites = 0;
mData->AccessWrites = 0;
mData-> ReadErrors = 0;
mData->WriteErrors = 0;
mData->MemoryFile = -1;
#ifdef ROBOT_OS_LINUX
char mem[32];
// Build a path to mem file
snprintf (mem, 32, PROC_PATH
"%d/mem", p.GetPID());
// Attempt to open the proc memory file
mData->MemoryFile = open (mem, O_RDWR);
#endif
}
//----------------------------------------------------------------------------//
// Functions Memory //
//----------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////
bool Memory::IsValid (void) const
{
#ifdef ROBOT_OS_LINUX
// Verify that process is valid
return mData->Proc.IsValid();
#endif
#ifdef ROBOT_OS_MAC
// Verify that process is valid
// and a mach task is available
return mData->Proc.IsValid () &&
mData->Proc.GetHandle() != 0;
#endif
#ifdef ROBOT_OS_WIN
// Verify that process is valid
return mData->Proc.IsValid();
#endif
}
////////////////////////////////////////////////////////////////////////////////
Process Memory::GetProcess (void) const
{
return mData->Proc;
}
////////////////////////////////////////////////////////////////////////////////
Memory::Stats Memory::GetStats (void) const
{
Memory::Stats s;
s.SystemReads = mData->SystemReads;
s.CachedReads = mData->CachedReads;
s.SystemWrites = mData->SystemWrites;
s.AccessWrites = mData->AccessWrites;
s. ReadErrors = mData-> ReadErrors;
s.WriteErrors = mData->WriteErrors;
return s;
}
////////////////////////////////////////////////////////////////////////////////
Memory::Stats Memory::GetStats (bool reset)
{
Memory::Stats s;
s.SystemReads = mData->SystemReads;
s.CachedReads = mData->CachedReads;
s.SystemWrites = mData->SystemWrites;
s.AccessWrites = mData->AccessWrites;
s. ReadErrors = mData-> ReadErrors;
s.WriteErrors = mData->WriteErrors;
if (reset)
{
mData->SystemReads = 0;
mData->CachedReads = 0;
mData->SystemWrites = 0;
mData->AccessWrites = 0;
mData-> ReadErrors = 0;
mData->WriteErrors = 0;
}
return s;
}
////////////////////////////////////////////////////////////////////////////////
Memory::Region Memory::GetRegion (uintptr address) const
{
Region region = { 0 };
region.Valid = false;
// Check whether address is valid
if (address < GetMinAddress() ||
address >= GetMaxAddress() ||
!IsValid()) return region;
// Align address to page boundary
address &= ~(GetPageSize() - 1);
#ifdef ROBOT_OS_LINUX
RegionList list =
// Get the region at the address
GetRegions (address, address + 1);
// If list isn't empty, return front
return list.empty() ? region : list[0];
#endif
#ifdef ROBOT_OS_MAC
mach_port_t port = MACH_PORT_NULL;
mach_msg_type_number_t count =
VM_REGION_BASIC_INFO_COUNT_64;
uint64 base = address, size;
vm_region_basic_info_64 info;
vm_region_flavor_t flavor =
VM_REGION_BASIC_INFO_64;
// Query region info using specified address
if (mach_vm_region (ProcHandle, &base, &size,
flavor, (vm_region_info_t) &info, &count,
&port)) return region;
// Determine the start and stop
uintptr start = (uintptr) base;
uintptr stop = (uintptr) base +
(uintptr) size;
// Avoid returning invalid memory regions
if (stop > GetMaxAddress()) return region;
region.Start = address;
// Check if address is within the result
if (start <= address && address < stop)
{
region.Bound = true;
region.Stop = stop;
region.Size = stop - address;
// Determine the access of the region
region.Access = (info.protection);
region.Executable = (info.protection & VM_PROT_EXECUTE) != 0;
region.Readable = (info.protection & VM_PROT_READ ) != 0;
region.Writable = (info.protection & VM_PROT_WRITE ) != 0;
// Is the region private or shared
region.Private = info.shared == 0;
}
else
{
// Region is unbound
region.Stop = start;
region.Size = start - address;
}
assert (region.Start % GetPageSize() == 0);
assert (region.Stop % GetPageSize() == 0);
assert (region.Size % GetPageSize() == 0);
assert (region.Size != 0);
region.Valid = true; return region;
#endif
#ifdef ROBOT_OS_WIN
MEMORY_BASIC_INFORMATION mbInfo;
// Determine region info using specified address
if (VirtualQueryEx (ProcHandle, (LPCVOID) address,
&mbInfo, sizeof (mbInfo)) != sizeof (mbInfo))
return region;
// Ignore invalid memory regions
if ((uintptr) mbInfo.BaseAddress +
(uintptr) mbInfo.RegionSize >
GetMaxAddress()) return region;
// Set the size and base address of region
region.Start = (uintptr) mbInfo.BaseAddress;
region.Stop = (uintptr) mbInfo.BaseAddress +
(uintptr) mbInfo.RegionSize;
region.Size = (uintptr) mbInfo.RegionSize;
assert (region.Start % GetPageSize() == 0);
assert (region.Stop % GetPageSize() == 0);
assert (region.Size % GetPageSize() == 0);
assert (region.Size != 0);
region.Access = PAGE_NOACCESS;
// Check if storage is assigned
if (mbInfo.State == MEM_COMMIT)
{
region.Bound = true;
// Define constants encompassing various access rights
static const DWORD R = PAGE_READONLY | PAGE_READWRITE |
PAGE_WRITECOPY | PAGE_EXECUTE | PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
static const DWORD W = PAGE_READWRITE | PAGE_WRITECOPY |
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
static const DWORD X = PAGE_EXECUTE | PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
region.Readable = (mbInfo.Protect & R) != 0;
region.Writable = (mbInfo.Protect & W) != 0;
region.Executable = (mbInfo.Protect & X) != 0;
region.Access = mbInfo.Protect;
region.Private = (mbInfo.Type & MEM_PRIVATE) != 0;
region.Guarded = (mbInfo.Protect & PAGE_GUARD ) != 0;
}
region.Valid = true; return region;
#endif
}
////////////////////////////////////////////////////////////////////////////////
Memory::RegionList Memory::GetRegions
(uintptr start, uintptr stop) const
{
RegionList result;
// Verify the memory validity
if (!IsValid()) return result;
// Ensure start is in range
if (start < GetMinAddress())
start = GetMinAddress();
// Ensure stop is in range
if (stop > GetMaxAddress())
stop = GetMaxAddress();
uintptr oldStop = stop;
// Align range to the page size
start &= ~(GetPageSize() - 1);
stop &= ~(GetPageSize() - 1);
if (oldStop != stop)
stop += GetPageSize();
// Make sure the range is correct
if (start >= stop) return result;
#ifdef ROBOT_OS_LINUX
char maps[32];
// Build path to proc PID maps
snprintf (maps, 32, PROC_PATH
"%d/maps", mData->Proc.GetPID());
// Attempt to open maps file
fstream file (maps, ios::in);
if (!file) return result;
Mapping mapping; string line;
std::vector<Mapping> mappings;
// Create the mappings list
while (getline (file, line))
{
size_t begin, end;
// Parse current line into single mapping entry
if (sscanf (line.data(), "%zx-%zx %4s", &begin,
&end, mapping.Access) != 3) return result;
// Ignore any invalid memory regions
if (end > GetMaxAddress()) continue;
// Avoid GCC warning
mapping.Start = begin;
mapping.Stop = end;
mappings.push_back (mapping);
}
// Sort the mappings based on their address
std::sort (mappings.begin(), mappings.end(),
[](const Mapping& a, const Mapping& b)
-> bool { return a.Start < b.Start; });
Region region = { 0 };
region.Valid = true;
region.Start = start;
// Loop through each mapping in list
for (const auto& current : mappings)
{
// Position at the start address
if (region.Start >= current.Stop)
continue;
// Check if region is unbounded
if (region.Start < current.Start)
{
region.Bound = false;
region.Stop = current.Start;
region.Size = current.Start - region.Start;
region.Readable = false;
region.Writable = false;
region.Executable = false;
region.Access = PROT_NONE;
region.Private = false;
result.push_back (region);
assert (region.Start % GetPageSize() == 0);
assert (region.Stop % GetPageSize() == 0);
assert (region.Size % GetPageSize() == 0);
assert (region.Size != 0);
// Increase the base address
region.Start = current.Start;
if (region.Start >= stop) break;
}
region.Bound = true;
region.Stop = current.Stop;
region.Size = current.Stop - region.Start;
region.Readable = current.Access[0] == 'r';
region.Writable = current.Access[1] == 'w';
region.Executable = current.Access[2] == 'x';
region.Private = current.Access[3] == 'p';
region.Access = PROT_NONE;
if (region.Executable) region.Access |= PROT_EXEC;
if (region.Readable ) region.Access |= PROT_READ;
if (region.Writable ) region.Access |= PROT_WRITE;
result.push_back (region);
assert (region.Start % GetPageSize() == 0);
assert (region.Stop % GetPageSize() == 0);
assert (region.Size % GetPageSize() == 0);
assert (region.Size != 0);
// Increase the base address
region.Start = current.Stop;
if (region.Start >= stop) break;
}
return result;
#endif
#if defined (ROBOT_OS_MAC) || \
defined (ROBOT_OS_WIN)
Region region;
// Read memory, region by region
for (uintptr addr = start; addr
< stop; addr = region.Stop)
{
// Get region info and verify validity
if (!(region = GetRegion (addr)).Valid)
break;
// Append current region
result.push_back (region);
}
return result;
#endif
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::SetAccess (const Region& region, uint32 access)
{
// Verify the parameters and status
if (!region.Valid || !region.Bound ||
IsValid() == false) return false;
#ifdef ROBOT_OS_LINUX
// NOTE: Not able to be implemented safely
return false;
#endif
#ifdef ROBOT_OS_MAC
// Modify access value of the specified region
if (mach_vm_protect (ProcHandle, region.Start,
region.Size, 0, access)) return false;
// Update stats value
++mData->AccessWrites;
return true;
#endif
#ifdef ROBOT_OS_WIN
DWORD old = 0;
// Modify access value of specified region
if (!VirtualProtectEx (ProcHandle, (LPVOID)
region.Start, region.Size, access, &old))
return false;
// Update stats value
++mData->AccessWrites;
return true;
#endif
}
////////////////////////////////////////////////////////////////////////////////
bool Memory::SetAccess (const Region& region,
bool read, bool write, bool exec)
{
#ifdef ROBOT_OS_LINUX
uint32 access = PROT_NONE;
// Compute new protection value
if (exec ) access |= PROT_EXEC;
if (read ) access |= PROT_READ;
if (write) access |= PROT_WRITE;
return SetAccess (region, access);
#endif
#ifdef ROBOT_OS_MAC
uint32 access = VM_PROT_NONE;
// Compute the new protection value
if (exec ) access |= VM_PROT_EXECUTE;
if (read ) access |= VM_PROT_READ;
if (write) access |= VM_PROT_WRITE;
return SetAccess (region, access);
#endif
#ifdef ROBOT_OS_WIN
uint32 access;
if (exec)
{
if (write)
access = PAGE_EXECUTE_READWRITE;
else
{
if (read)
access = PAGE_EXECUTE_READ;
else
access = PAGE_EXECUTE;
}
}
else
{
if (write)
access = PAGE_READWRITE;
else
{
if (read)
access = PAGE_READONLY;
else
access = PAGE_NOACCESS;
}
}
return SetAccess (region, access);
#endif
}
////////////////////////////////////////////////////////////////////////////////
AddressList Memory::Find (const char* pattern, uintptr start,
uintptr stop, uintptr limit, const char* accessFlags)
{
AddressList result;
// Check the parameters and the status
if (pattern == nullptr || !IsValid())
return result;
char aw = ' '; char ax = ' ';
char ap = ' '; char ag = ' ';
// Check if flags are valid
if (accessFlags != nullptr)
{
SET_A_FLAG (0, 'W', aw);
SET_A_FLAG (1, 'X', ax);
SET_A_FLAG (2, 'P', ap);
SET_A_FLAG (3, 'G', ag);
skip:
assert (aw == ' ' || aw == '-' || aw == 'w');
assert (ax == ' ' || ax == '-' || ax == 'x');
assert (ap == ' ' || ap == '-' || ap == 'p');
assert (ag == ' ' || ag == '-' || ag == 'g');
}
bool wild = false;
bool high = true;
PatternByte byte;
vector<PatternByte> compiled;
// Compile the pattern into an array format
for (uintptr i = 0; pattern[i] != '\0'; ++i)
{
switch (pattern[i])
{
case '0': HEX_TO_INT ( 0, 0);
case '1': HEX_TO_INT ( 16, 1);
case '2': HEX_TO_INT ( 32, 2);
case '3': HEX_TO_INT ( 48, 3);
case '4': HEX_TO_INT ( 64, 4);
case '5': HEX_TO_INT ( 80, 5);
case '6': HEX_TO_INT ( 96, 6);
case '7': HEX_TO_INT (112, 7);
case '8': HEX_TO_INT (128, 8);
case '9': HEX_TO_INT (144, 9);
case 'A': HEX_TO_INT (160, 10);
case 'a': HEX_TO_INT (160, 10);
case 'B': HEX_TO_INT (176, 11);
case 'b': HEX_TO_INT (176, 11);
case 'C': HEX_TO_INT (192, 12);
case 'c': HEX_TO_INT (192, 12);
case 'D': HEX_TO_INT (208, 13);
case 'd': HEX_TO_INT (208, 13);
case 'E': HEX_TO_INT (224, 14);
case 'e': HEX_TO_INT (224, 14);
case 'F': HEX_TO_INT (240, 15);
case 'f': HEX_TO_INT (240, 15);
case ' ':
if (!high) return result;
break;
case '?':
if (!high) return result;
byte.Wild = wild = true;
compiled.push_back (byte);
break;
default:
return result;
}
}
// Do the last compiler checks
if (!high || compiled.empty())
return result;
RegionList list =
// Get a list of regions
GetRegions (start, stop);
// Check for at least one region
if (list.empty()) return result;
uintptr size = 1048576;
// Initially allocate single MB
uint8* data = new uint8[size];
// Loop through memory region list
for (uintptr a = start, i = 0; i <
list.size(); a = list[i++].Stop)
{
// Avoid dereferencing each time
const Region& current = list[i];
#ifndef NDEBUG
// Paranoid bounds check
if (current.Stop >= stop)
assert (i+1 == list.size());
#endif
// Skip if region is unreadable
if (!current.Readable) continue;
// Don't check if defaults
if (accessFlags != nullptr)
{
// Filter regions not matching the access flags
if (aw == '-' && current.Writable ) continue;
if (aw == 'w' && !current.Writable ) continue;
if (ax == '-' && current.Executable) continue;
if (ax == 'x' && !current.Executable) continue;
if (ap == '-' && current.Private ) continue;
if (ap == 'p' && !current.Private ) continue;
if (ag == '-' && current.Guarded ) continue;
if (ag == 'g' && !current.Guarded ) continue;
}
// Compute the current value of length parameter
uintptr len = std::min (current.Stop, stop) - a;
if (size < len)
{
// Multiply by two until
// the length is reached
while ((size *= 2) < len);
delete[] data;
// Reallocate the buffer
data = new uint8[size];
}
// Attempt to read the memory region
if (ReadData (a, data, len) != len)