-
Notifications
You must be signed in to change notification settings - Fork 4
/
minircheats-model.cpp
1668 lines (1458 loc) · 52.6 KB
/
minircheats-model.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 "minir.h"
#undef malloc
#undef realloc
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <inttypes.h>
#include "libretro.h"
//For compatibilty with Windows before 7, this file may not use
//- printf with 'z' size specifier - use PRIuPTR (yes, it's ugly)
// ('z' is (s)size_t while PRIuPTR is (u)intptr_t, but they have the same size on everything since MS-DOS)
//force some year-old C code to compile properly as C++ - I decided to switch long ago but still haven't finished.
#define this This
//how address conversion works
//----------------------------
//
//preparation:
//for each mapping:
// if both 'len' and 'select' are zero, whine
// if 'select' is zero, fill it in with len-1
//
// if a bit is set in start but not in select (start & ~select) is nonzero, panic
// panicing can be done with abort()
//
// calculate the highest possible address in this address space
// math: top_addr|=select
// top_addr=add_bits_down(top_addr)
//
//for each mapping:
// if 'len' is zero, fill it in with the number of bytes defined by this mapping
// math: add_bits_down(reduce(~select&top_addr, disconnect))+1
// while reduce(highest possible address for this mapping, disconnect) is greater than len, disconnect the top still-connected bit
// math: while (reduce(~select&top_addr, disconnect)>>1 > len-1) disconnect|=highest_bit(~select&top_addr&~disconnect)
//
// create variable 'variable_bits' for mapping; it contains which bits could change in the guest address and still refer to the same byte
// set variable_bits to all disconnected and not selected bits
// if 'len' is not a power of two:
// inflate 'len' with 'disconnect', take the highest bit of that, and add it to variable_bits
// (do not optimize to topbit(len)<<popcount(disconnect & topbit(len)-1); it's painful if the shift adds more disconnected bits)
//
// create variable 'disconnect_mask' for mapping, set it to add_bits_down(len)
// clear any bit in 'disconnect' that's clear in 'disconnect_mask'
// while the highest set bit in 'disconnect' is directly below the lowest clear bit in 'disconnect_mask', move it over
// in any future reference to 'disconnect', use 'disconnect_mask' too
// math:
// disconnect_mask = add_bits_down(len-1)
// disconnect &= disconnect_mask
// while ((~disconnect_mask)>>1 & disconnect)
// {
// disconnect_mask >>= 1
// disconnect &= disconnect_mask
// }
//
// check if any previous mapping claims any byte claimed by this mapping
// math: there is a collision if (A.select & B.select & (A.start^B.start)) == 0
// if not, mark the mapping as such, and avoid the inner loop when converting physical to guest
//
//
//guest to physical:
//pick the first mapping where start and select match
//if address is NULL, return failure
//subtract start, pick off disconnect, apply len, add offset
//
//
//physical to guest:
//check cache
// if hit, subtract cached difference and return this address
//select all mappings which map this address ('ptr' and 'offset'/'length')
//for each:
// subtract offset
// do nothing with length
// fill in disconnect with zeroes
// add start
// check all previous mappings, to see if this is the first one to claim this address; if so:
// find how long this mapping is linear, that is how far we can go while still ensuring that moving one guest byte
// still moves one physical byte (use the most strict of 'length', 'disconnect', 'select', and other mappings)
// put start and size of linear area, as well as where it points, in the cache
// return this address, ignoring the above linearity calculations
// else:
// fill in an 1 in the lowest hole permitted by 'length' or 'disconnect', try again
// if we're out of holes, use next mapping
// if there is no next mapping, segfault because all bytes must be mapped somewhere.
//in this file, 'address' means address in any emulated address space (also known as guest address),
// and 'offset' means offset to any memory block (physical address)
//For compatibility with RetroArch, this file has the following restrictions, in addition to the global rules:
//- Do not call any function from minir.h; force the user of the object to do that. The only allowed
// parts of minir.h are static_assert, struct minircheats_model and friends, and UNION_BEGIN and friends.
//- Do not dynamically change the interface; use a switch. If that becomes a too big pain, stick a
// function pointer in minircheats_model_impl.
//- No C++ incompatibilities, except using 'this' as variable name. This includes C++11. malloc return values must be casted.
//- A global s/this/This/i must not alter the program behaviour. The word 'this' (case insensitive)
// may not be used in any embedded string (other than debug output), and no case other than pure-lower may be used outside comments.
//However, as RetroArch is not consistent on its malloc checking, we don't do that either.
//The following assumptions are made:
//- The child system uses 8bit bytes.
//- The child system uses two's complement.
//- The child system uses little endian, or big endian.
//- It is safe to read up to 3 bytes after any memory area. (The results are discarded.)
//- The host system uses 8bit bytes.
//- sizeof(int) >= 32 bits
//- Two threads may access two adjacent uint32s in any way without causing incorrect results. Bad performance is okay.
//The host system is allowed to use any endianness, including weird ones.
static size_t add_bits_down(size_t n)
{
static_assert(sizeof(size_t)==4 || sizeof(size_t)==8);
n|=(n>> 1);
n|=(n>> 2);
n|=(n>> 4);
n|=(n>> 8);
n|=(n>>16);
if (sizeof(size_t)>4) n|=(n>>16>>16);//double shift to avoid warnings on 32bit (it's dead code, but compilers suck)
return n;
}
static size_t highest_bit(size_t n)
{
n=add_bits_down(n);
return n^(n>>1);
}
static uint8_t popcount32(uint32_t i)
{
//In LLVM, __builtin_popcount seems to be similar to my popcount64, but without the multiplication.
//In GCC, it's a loop over a lookup table!
//In both cases is it faster to just do the bithack, and we can ignore the popcounter.
//#ifdef __GNUC__
// return __builtin_popcount(i);
//#else
//from http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel, public domain
i = i - ((i >> 1) & 0x55555555); // reuse input as temporary
i = (i & 0x33333333) + ((i >> 2) & 0x33333333); // temp
return (((i + (i >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; // count
//#endif
}
static uint8_t popcount64(uint64_t v)
{
//#ifdef __GNUC__
// return __builtin_popcountll(v);
//#else
//http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel again
#define T uint64_t
v = v - ((v >> 1) & (T)~(T)0/3); // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15; // temp
//tried this, no speedup
//v = (v + (v >> 8)) & (T)~(T)0/255*255; // temp
//v = (v + (v >> 16)) & (T)~(T)0/255*65535; // temp
//v = (v + (v >> 32)) & (T)~(T)0/255*0xFFFFFFFF; // temp
v = (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * CHAR_BIT; // count
#undef T
return v;
//#endif
}
static uint8_t popcountS(size_t i)
{
static_assert(sizeof(size_t)==4 || sizeof(size_t)==8);
if (sizeof(size_t)==4) return popcount32(i);
if (sizeof(size_t)==8) return popcount64(i);
return 0;//unreachable
}
#define div_rndup(a,b) (((a)+(b)-1)/(b))
static size_t reduce(size_t addr, size_t mask)
{
while (mask)
{
size_t tmp=((mask-1)&(~mask));
addr=(addr&tmp)|((addr>>1)&~tmp);
mask=(mask&(mask-1))>>1;
}
return addr;
}
//Inverts reduce().
//reduce(inflate(x, y), y) == x (assuming no overflow)
//inflate(reduce(x, y), y) == x & ~y
static size_t inflate(size_t addr, size_t mask)
{
while (mask)
{
size_t tmp=((mask-1)&(~mask));
//to put in an 1 bit instead, OR in tmp+1
addr=((addr&~tmp)<<1)|(addr&tmp);
mask=(mask&(mask-1));
}
return addr;
}
static uint32_t readmem(const unsigned char * ptr, unsigned int nbytes, bool bigendian)
{
if (nbytes==1) return *ptr;
if (bigendian)
{
uint32_t ret=0;
while (nbytes--)
{
ret=(ret<<8)|(*ptr++);
}
return ret;
}
else
{
uint32_t ret=0;
ptr+=nbytes;
while (nbytes--)
{
ret=(ret<<8)|(*--ptr);
}
return ret;
}
}
static void writemem(unsigned char * ptr, unsigned int nbytes, bool bigendian, uint32_t value)
{
if (nbytes==1)
{
*ptr=value;
return;
}
if (bigendian)
{
while (nbytes--)
{
(*ptr++)=value;
value>>=8;
}
}
else
{
ptr+=nbytes;
while (nbytes--)
{
(*--ptr)=value;
value>>=8;
}
}
}
static const uint32_t signs[]={0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000};
static uint32_t signex(uint32_t val, unsigned int nbytes, bool signextend)
{
if (signextend && (val&signs[nbytes-1])) return (val|signs[nbytes-1]);
else return val;
}
static uint32_t readmemext(const unsigned char * ptr, unsigned int nbytes, bool bigendian, bool signextend)
{
return signex(readmem(ptr, nbytes, bigendian), nbytes, signextend);
}
struct mapping {
unsigned int memid;
bool has_overlaps;//Whether any previous mapping overrides any part of this mapping.
size_t start;
size_t select;
size_t disconnect;
size_t disconnect_mask;
size_t len;
size_t offset;
//which bits could potentially change and still refer to the same byte (not just the same mapping)
//len not being a power of two gives one 'maybe' here
size_t variable_bits;
};
struct memblock {
uint8_t * ptr;
uint8_t * prev;
#define SIZET_BITS (sizeof(size_t)*8)
size_t * show;//the top row (lowest address) in each of those has value 1; bottom is 0x80000000 (add eight 0s for 64bit)
#define SIZE_PAGE_LOW 0x2000//2^13, 8192
uint16_t * show_treelow;//one entry per SIZE_PAGE_LOW bytes of mem, counts number of set bits within these bytes
#define SIZE_PAGE_HIGH 0x400000//2^22, 1048576
uint32_t * show_treehigh;//same format as above
size_t show_tot;//this applies to the entire memory block
//both page sizes must be powers of 2
//LOW must be in the range [SIZET_BITS .. 32768]
//HIGH must be larger than LOW, and equal to or lower than 2^31
size_t len;
//No attempt has been made to care about performance for mem blocks larger than 2^32; I don't think there are any of those.
//That, and performance will be trash at other places too for large mem blocks. Manipulating 2^29 bytes in 'show' isn't cheap,
// and neither is manipulating the actual 2^32 bytes.
unsigned int addrspace;
bool showinsearch;
bool align;
bool bigendian;
UNION_BEGIN
STRUCT_BEGIN
//TODO: use these
uint32_t * show_true;
uint16_t * show_true_treelow;
uint32_t * show_true_treehigh;
size_t show_true_tot;
STRUCT_END
STRUCT_BEGIN
bool show_last_true[3];
STRUCT_END
UNION_END
};
struct addressspace {
char name[9];
uint8_t addrlen;//how many hex digits are needed for an address here (1..16, 6 for SNES; the actual number of bits isn't used)
//char padding[2];
unsigned int nummap;
struct mapping * map;
};
struct cheat_impl {
unsigned int memid;
//char padding[4];
size_t offset;
unsigned int changetype :2;
unsigned int datsize :3;//only values 1..4 are allowed, but it's easier to give an extra bit than adding 1 on every use.
bool issigned :1;
bool enabled :1;
bool restore :1;
//char padding2[2];
uint32_t value;//for cht_const: value it's forced to remain at
//for inconly/deconly: value of previous frame
//for once: cht_once does not get a cheat_impl
uint32_t orgvalue;//value to restore to if the cheat is disabled
char* desc;
};
enum { threadfunc_nothing, threadfunc_search };
struct minircheats_model_impl {
struct minircheats_model i;
struct addressspace * addrspaces;
unsigned int numaddrspace;
unsigned int nummem;
struct memblock * mem;
uint8_t search_datsize;
bool search_signed;
bool prev_enabled;
bool addrspace_case_sensitive;
unsigned int addrcache_memid;
size_t addrcache_start;
size_t addrcache_end;
size_t addrcache_offset;
struct cheat_impl * cheats;
unsigned int numcheats;
unsigned int search_lastblock;
size_t search_lastrow;
size_t search_lastmempos;
unsigned char numthreads;//1 for no threading
unsigned char threadfunc;
unsigned char threadsearch_compfunc;
bool threadsearch_comptoprev;
uint32_t threadsearch_compto;
char * lastcheat;
};
#if 0
static
void
search_scan_sanity
(struct minircheats_model_impl * this,
const char * why)
{
for (unsigned int i=0;i<this->nummem;i++)
{
struct memblock * mem=&this->mem[i];
//size_t tot=mem->show_tot;
size_t treehigh=0;
size_t treelow=0;
for (size_t i=0;i<mem->len;i+=SIZET_BITS)
{
if(i%SIZE_PAGE_HIGH==0){
//tot-=mem->show_treehigh[i/SIZE_PAGE_HIGH];
if(treehigh!=0){printf("%s: treelow!=treehigh\n",why);char*e=0;*e=0;}
treehigh=mem->show_treehigh[i/SIZE_PAGE_HIGH];}
if(i%SIZE_PAGE_LOW==0){
treehigh-=mem->show_treelow[i/SIZE_PAGE_LOW];
if(treelow!=0){printf("%s: show!=treelow\n",why);char*e=0;*e=0;}
treelow=mem->show_treelow[i/SIZE_PAGE_LOW];}
treelow-=popcountS(mem->show[i/SIZET_BITS]);
}
if(treelow!=0){printf("%s: show!=treelow\n",why);char*e=0;*e=0;}
if(treehigh!=0){printf("%s: treelow!=treehigh\n",why);char*e=0;*e=0;}
//if(tot!=0){printf("%s: treehigh!=tot\n",why);char*e=0;*e=0;}
}
}
#endif
static void free_mem(struct minircheats_model_impl * this);
static void free_cheats(struct minircheats_model_impl * this);
static void set_memory(struct minircheats_model * this_, const struct retro_memory_descriptor * memory, unsigned int nummemory)
{
#ifdef DEBUG
for (unsigned int i=0;i<nummemory;i++)
{
printf("desc: fl=%X pt=%p of=%" PRIXPTR " st=%" PRIXPTR " se=%" PRIXPTR " di=%" PRIXPTR " le=%" PRIXPTR " sp=%s\n",
(unsigned int)memory[i].flags,
memory[i].ptr,
memory[i].offset,
memory[i].start,
memory[i].select,
memory[i].disconnect,
memory[i].len,
memory[i].addrspace);
}
#endif
struct minircheats_model_impl * this=(struct minircheats_model_impl*)this_;
free_mem(this);
free_cheats(this);
this->addrspace_case_sensitive=false;
//all the weird math in this file is explained at the top
for (unsigned int i=0;i<nummemory;i++)
{
const struct retro_memory_descriptor * desc=&memory[i];
struct addressspace * addr;
unsigned int addrspace;
for (addrspace=0;addrspace<this->numaddrspace;addrspace++)
{
if (!strcmp(this->addrspaces[addrspace].name, desc->addrspace ? desc->addrspace : "")) break;
}
if (addrspace == this->numaddrspace)
{
this->numaddrspace++;
this->addrspaces=(struct addressspace*)realloc(this->addrspaces, sizeof(struct addressspace)*this->numaddrspace);
//TODO: handle failure
addr=&this->addrspaces[addrspace];
strcpy(addr->name, desc->addrspace ? desc->addrspace : "");
for (int i=0;addr->name[i];i++)
{
if (islower(addr->name[i])) this->addrspace_case_sensitive=true;
if (!isalnum(addr->name[i]) && addr->name[i]!='_' && addr->name[i]!='-') abort();//invalid character in the name
}
addr->nummap=0;
addr->map=NULL;
}
addr=&this->addrspaces[addrspace];
struct memblock * mem;
unsigned int memid;
for (memid=0;memid<this->nummem;memid++)
{
if (this->mem[memid].ptr==desc->ptr) break;
}
if (memid == this->nummem)
{
this->nummem++;
this->mem=(struct memblock*)realloc(this->mem, sizeof(struct memblock)*this->nummem);
//TODO: handle failure
mem=&this->mem[memid];
memset(mem, 0, sizeof(struct memblock));
mem->ptr=(uint8_t*)desc->ptr;
mem->prev=NULL;
mem->len=0;
mem->showinsearch=!(desc->flags & RETRO_MEMDESC_CONST);
mem->align=false;//TODO
mem->bigendian=(desc->flags & RETRO_MEMDESC_BIGENDIAN);
mem->addrspace=addrspace;
}
mem=&this->mem[memid];
if (desc->len > mem->len) mem->len=desc->len;
addr->nummap++;
addr->map=(struct mapping*)realloc(addr->map, sizeof(struct mapping)*addr->nummap);
//TODO: handle failure
struct mapping * map=&addr->map[addr->nummap-1];
map->memid=memid;
map->start=desc->start;
map->select=desc->select;
map->disconnect=desc->disconnect;
map->len=desc->len;
map->offset=desc->offset;
}
//at this point:
//addr->addrlen is uninitialized
//map->select is possibly zero
//map->len is possibly zero
//map->variable_bits is uninitialized
//map->disconnect_mask is uninitialized
//map->has_overlaps is false
//other things are correct
for (unsigned int i=0;i<this->numaddrspace;i++)
{
struct addressspace * addr=&this->addrspaces[i];
size_t top_addr=1;//to avoid trouble if the size is 0. A zero-bit address space isn't an address space at all, anyways.
for (unsigned int i=0;i<addr->nummap;i++)
{
struct mapping * map=&addr->map[i];
top_addr|=map->select;
//start+len is garbage if the length isn't a power of 2, if disconnect is nonzero, or if len is larger than select
//but in that case, select is the one we want, so we can ignore this.
if (map->select==0) top_addr |= map->start+map->len-1;
}
top_addr=add_bits_down(top_addr);
for (unsigned int i=0;i<addr->nummap;i++)
{
struct mapping * map=&addr->map[i];
if (map->select==0)
{
if (map->len==0) abort();//select==0 and len==0 is bad
if (map->len & (map->len-1)) abort();//select==0 and len not power of two
map->select=top_addr&~inflate(add_bits_down(map->len-1), map->disconnect);
}
if (!map->len)
{
map->len=add_bits_down(reduce(top_addr&~map->select, map->disconnect))+1;
}
if (map->len > this->mem[map->memid].len) this->mem[map->memid].len=map->len;
if (map->start & ~map->select) abort();//this combination is invalid
while (reduce(top_addr&~map->select, map->disconnect)>>1 > map->len-1)
{
map->disconnect|=highest_bit(top_addr&~map->select&~map->disconnect);
}
map->variable_bits=(map->disconnect&~map->select);
//this may look like it can be rewritten as topbit(len)<<popcount(disconnect & topbit(len)-1);,
// but it'd be painful if the shift adds more disconnected bits
if (map->len & (map->len-1)) map->variable_bits|=highest_bit(inflate(map->len, map->disconnect));
map->disconnect_mask=add_bits_down(map->len-1);
map->disconnect&=map->disconnect_mask;
while ((~map->disconnect_mask)>>1 & map->disconnect)
{
map->disconnect_mask >>= 1;
map->disconnect &= map->disconnect_mask;
}
map->has_overlaps=false;
for (unsigned int j=0;j<i;j++)
{
if ((addr->map[i].select & addr->map[j].select & (addr->map[i].start ^ addr->map[j].start)) == 0)
{
map->has_overlaps=true;
break;
}
}
}
addr->addrlen=div_rndup(popcountS(top_addr), 4);
}
return;
}
static bool addr_guest_to_phys(struct minircheats_model_impl * this, unsigned int addrspace, size_t addr, unsigned int * memid, size_t * offset)
{
for (unsigned int i=0;i<this->addrspaces[addrspace].nummap;i++)
{
struct mapping * map=&this->addrspaces[addrspace].map[i];
if (((map->start ^ addr) & map->select) == 0)
{
struct memblock * mem=&this->mem[map->memid];
if (!mem->ptr) return false;
addr=reduce((addr - map->start)&map->disconnect_mask, map->disconnect);
if (addr >= mem->len) addr-=highest_bit(addr);
*memid = map->memid;
*offset = addr+map->offset;
return true;
}
}
return false;
}
static size_t addr_phys_to_guest(struct minircheats_model_impl * this, unsigned int memid, size_t offset)
//this one can't fail
//address space is neither input nor output; you can find it at this->mem[memid].addrspace
{
if (memid==this->addrcache_memid && offset>=this->addrcache_start && offset<this->addrcache_end)
{
return offset-this->addrcache_start+this->addrcache_offset;
}
struct mapping * addrmaps=this->addrspaces[this->mem[memid].addrspace].map;
struct mapping * map=addrmaps;
while (true)
{
//there is no end condition if this byte shows up nowhere - such a situation is forbidden
struct memblock * mem=&this->mem[map->memid];
size_t thisaddr;
if (map->memid!=memid || map->offset>offset || offset-map->offset > map->len) goto wrongmapping;
thisaddr=inflate(offset, map->disconnect)+map->start;
if (false)
{
add_a_bit: ;
size_t canadd=(~thisaddr & map->variable_bits);//bits that can change
if (!canadd) goto wrongmapping;
canadd&=-canadd;//bit that should change
thisaddr|=canadd;
thisaddr&=~((canadd-1) & map->variable_bits);//clear lower bits
//check if adding that bit allows len to screw us over
size_t tryaddr=reduce((thisaddr - map->start)&map->disconnect_mask, map->disconnect);
if (tryaddr >= mem->len) goto add_a_bit;
}
if (map->has_overlaps)
{
struct mapping * prevmap=addrmaps;
while (prevmap < map)
{
if (((prevmap->start ^ thisaddr) & prevmap->select) == 0)
{
goto add_a_bit;
}
prevmap++;
}
}
//size_t cachesize=(map->disconnect|~map->disconnect_mask|map->select);
//cachesize&=-cachesize;
//cachesize now contains lowest bit set in either 'disconnect' or 'select'
//size_t cachestart=offset
//TODO:
// find how long this mapping is linear, that is how far we can go while still ensuring that moving one guest byte still moves one physical byte
// (use the most strict of 'length', 'disconnect', 'select', and other mappings)
// put start and size of linear area, as well as where it points, in the cache
// return this address, ignoring the above linearity calculations
//void* addrcache_ptr;
//size_t addrcache_start;
//size_t addrcache_end;
//size_t addrcache_offset;
//printf("cache=%zX-%zX\n",this->addrcache_start,this->addrcache_end);
return thisaddr;
wrongmapping:
map++;
continue;
}
}
static bool addr_parse(struct minircheats_model_impl * this, const char * rawaddr, unsigned int * addrlen, unsigned int * addrspace, size_t * addr)
{
unsigned int minblklen=0;
for (unsigned int i=0;isalpha(rawaddr[i]) || rawaddr[i]=='_';i++)
{
if (rawaddr[i]<'A' || rawaddr[i]>'F') minblklen=i;
}
unsigned int i;
size_t addrnamelen;//these are declared up here so that I can use a goto
if (this->addrspace_case_sensitive)
{
for (i=0;i<this->numaddrspace;i++)
{
addrnamelen=strlen(this->addrspaces[i].name);
if (addrnamelen>=minblklen && !strncmp(rawaddr, this->addrspaces[i].name, addrnamelen))
{
goto rightaddrspace;
}
}
}
for (i=0;i<this->numaddrspace;i++)
{
addrnamelen=strlen(this->addrspaces[i].name);
if (addrnamelen>=minblklen && !strncasecmp(rawaddr, this->addrspaces[i].name, addrnamelen))
{
rightaddrspace: ;
char addrcopy[17];
for (unsigned int j=0;j<this->addrspaces[i].addrlen;j++)
{
if (!isxdigit(rawaddr[addrnamelen+j])) return false;
addrcopy[j]=rawaddr[addrnamelen+j];
}
addrcopy[this->addrspaces[i].addrlen]='\0';
if (addrlen) *addrlen=addrnamelen+this->addrspaces[i].addrlen;
else if (rawaddr[addrnamelen+this->addrspaces[i].addrlen]!='\0') return false;
if (addrspace) *addrspace=i;
if (addr) *addr=strtoul(addrcopy, NULL, 16);
return true;
}
}
return false;
}
static void search_prev_set_to_cur(struct minircheats_model_impl * this)
{
for (unsigned int i=0;i<this->nummem;i++)
{
if (this->mem[i].prev) memcpy(this->mem[i].prev, this->mem[i].ptr, this->mem[i].len);
}
}
static size_t prev_get_size(struct minircheats_model * this_)
{
struct minircheats_model_impl * this=(struct minircheats_model_impl*)this_;
size_t size=0;
for (unsigned int i=0;i<this->nummem;i++)
{
if (this->mem[i].showinsearch) size+=this->mem[i].len;
}
return size;
}
static void prev_set_enabled(struct minircheats_model * this_, bool enable)
{
struct minircheats_model_impl * this=(struct minircheats_model_impl*)this_;
for (unsigned int i=0;i<this->nummem;i++)
{
free(this->mem[i].prev);
this->mem[i].prev=NULL;
}
this->prev_enabled=enable;
for (unsigned int i=0;i<this->nummem;i++)
{
if (this->mem[i].showinsearch) this->mem[i].prev=(uint8_t*)malloc(this->mem[i].len);
//TODO: handle failure
}
search_prev_set_to_cur(this);
}
static bool prev_get_enabled(struct minircheats_model * this_)
{
struct minircheats_model_impl * this=(struct minircheats_model_impl*)this_;
return this->prev_enabled;
}
static void search_show_all(struct memblock * mem, unsigned int datsize)
{
if (!mem->show) return;
unsigned int len=div_rndup(mem->len, SIZET_BITS);
memset(mem->show, 0xFF, len*sizeof(size_t));
mem->show[len-1]>>=(mem->len&(SIZET_BITS-1));
len=div_rndup(mem->len, SIZE_PAGE_LOW);
for (unsigned int j=0;j<len;j++) mem->show_treelow[j]=SIZE_PAGE_LOW;
if (mem->len&(SIZE_PAGE_LOW-1)) mem->show_treelow[len-1]=mem->len&(SIZE_PAGE_LOW-1);
len=div_rndup(mem->len, SIZE_PAGE_HIGH);
for (unsigned int j=0;j<len;j++) mem->show_treehigh[j]=SIZE_PAGE_HIGH;
if (mem->len&(SIZE_PAGE_HIGH-1)) mem->show_treehigh[len-1]=mem->len&(SIZE_PAGE_HIGH-1);
mem->show_tot=mem->len;
}
static void search_ensure_mem_exists(struct minircheats_model_impl * this)
{
for (unsigned int i=0;i<this->nummem;i++)
{
struct memblock * mem=&this->mem[i];
if (mem->showinsearch && !mem->show)
{
mem->show=(size_t*)malloc(div_rndup(mem->len, SIZET_BITS)*sizeof(size_t));
mem->show_treelow=(uint16_t*)malloc(div_rndup(mem->len, SIZE_PAGE_LOW)*sizeof(uint16_t));
mem->show_treehigh=(uint32_t*)malloc(div_rndup(mem->len, SIZE_PAGE_HIGH)*sizeof(uint32_t));
//TODO: handle failure
search_show_all(mem, this->search_datsize);
}
}
}
static void search_reset(struct minircheats_model * this_)
{
struct minircheats_model_impl * this=(struct minircheats_model_impl*)this_;
for (unsigned int i=0;i<this->nummem;i++)
{
struct memblock * mem=&this->mem[i];
search_show_all(mem, this->search_datsize);
if (mem->prev) memcpy(mem->prev, mem->ptr, mem->len);
}
}
static void search_set_datsize(struct minircheats_model * this_, unsigned int datsize)
{
struct minircheats_model_impl * this=(struct minircheats_model_impl*)this_;
this->search_datsize=datsize;
//TODO: update the ghost values that change due to data size
}
static void search_set_signed(struct minircheats_model * this_, bool issigned)
{
struct minircheats_model_impl * this=(struct minircheats_model_impl*)this_;
this->search_signed=issigned;
}
static void thread_do_search(struct minircheats_model_impl * this, unsigned int threadid);
static void thread_finish_search(struct minircheats_model_impl * this);
static void search_do_search(struct minircheats_model * this_, enum cheat_compfunc compfunc, bool comptoprev, uint32_t compto)
{
struct minircheats_model_impl * this=(struct minircheats_model_impl*)this_;
search_ensure_mem_exists(this);
this->threadsearch_compfunc=compfunc;
this->threadsearch_comptoprev=comptoprev;
this->threadsearch_compto=compto;
uint32_t signadd=0;
if (this->search_signed)
{
signadd=signs[this->search_datsize-1];
}
this->threadsearch_compto-=signadd;
//we must run this unthreaded - it could touch two adjacent high trees
//it's fast, anyways.
for (unsigned int i=0;i<this->nummem;i++)
{
struct memblock * mem=&this->mem[i];
if (!mem->showinsearch) continue;
signed int removebits=((SIZET_BITS - mem->len%SIZET_BITS)%SIZET_BITS + this->search_datsize-1);
unsigned int possub=1;
while (removebits > 0)
{
size_t keep;
if ((unsigned int)removebits >= SIZET_BITS) keep=0;
else keep=(~(size_t)0 >> removebits);
unsigned int deleted=popcountS(~keep & mem->show[(mem->len-possub)/SIZET_BITS]);
mem->show_treehigh[(mem->len-possub)/SIZE_PAGE_HIGH]-=deleted;
mem->show_treelow[(mem->len-possub)/SIZE_PAGE_LOW]-=deleted;
mem->show[(mem->len-possub)/SIZET_BITS]&=keep;
removebits -= SIZET_BITS;
}
}
if (this->numthreads==1)
{
thread_do_search(this, 0);
thread_finish_search(this);
}
else this->threadfunc=threadfunc_search;
}
#ifdef __SSE2__
#include <emmintrin.h>
#define FAST_ALIGN 1
#else
#if defined(__i386__) || defined(__i486__) || defined(__i686__) || defined(__x86_64__)
#define FAST_ALIGN 1
#else
#define FAST_ALIGN sizeof(size_t)
#endif
//this constant will, when multiplied by a value of the form 0000000a 0000000b 0000000c 0000000d (native endian), transform
//it into abcd???? ???????? ????????? ???????? (big endian), which can then be shifted down
//works for uniting up to 8 bits
//works on crazy-endian systems too
//does, however, assume a rather powerful optimizer
static size_t calc_bit_shuffle_constant()
{
union {
uint8_t a[8];
size_t b;
} v;
v.a[0]=0x80; v.a[1]=0x40; v.a[2]=0x20; v.a[3]=0x10;
v.a[4]=0x08; v.a[5]=0x04; v.a[6]=0x02; v.a[7]=0x01;
return v.b;
}
#endif
static void thread_do_search(struct minircheats_model_impl * this, unsigned int threadid)
{
uint8_t compfunc = this->threadsearch_compfunc;
bool comptoprev = this->threadsearch_comptoprev;
uint32_t compto = this->threadsearch_compto;
//enum cheat_compfunc { cht_lt, cht_gt, cht_lte, cht_gte, cht_eq, cht_neq };
unsigned char compfunc_perm[]={cht_lt, cht_lte, cht_lte, cht_lt, cht_eq, cht_eq};
bool compfunc_exp=(compfunc&1);
size_t compfunc_exp_size = compfunc_exp ? ~(size_t)0 : 0;
unsigned char compfunc_fun=compfunc_perm[compfunc];
unsigned int datsize=this->search_datsize;//caching this here gives a ~15% speed boost, and cleans some stuff up
uint32_t signadd=0;
if (this->search_signed)
{
signadd=signs[this->search_datsize-1];
}
#if __SSE2__
//SSE comparisons are signed; we'll have to flip the sign if we prefer unsigned. (Or if we want signed, XOR with zero.)
__m128i signflip=_mm_set1_epi8(this->search_signed ? 0x00 : 0x80);
#else
size_t bitmerge=calc_bit_shuffle_constant();
size_t compto_byterep=compto*(~(size_t)0/255);
size_t signadd_byterep=signadd*(~(size_t)0/255);
#endif
unsigned int workid=0;
for (unsigned int i=0;i<this->nummem;i++)
{
struct memblock * mem=&this->mem[i];
if (mem->show_tot==0) continue;
bool bigendian=mem->bigendian;
size_t pagepos=0;
while (pagepos<mem->len)
{
if (threadid==workid && mem->show_treehigh[pagepos/SIZE_PAGE_HIGH]!=0)
{
size_t worklen=SIZE_PAGE_HIGH;
if (pagepos+SIZE_PAGE_HIGH >= mem->len) worklen=mem->len-pagepos;
size_t pos=0;
while (pos<worklen)
{
if (!(pos&SIZE_PAGE_LOW) && mem->show_treelow[(pagepos+pos)/SIZE_PAGE_LOW]==0)
{
pos+=SIZE_PAGE_LOW;
continue;
}
size_t show=mem->show[(pagepos+pos)/SIZET_BITS];
if (show==0)
{
pos+=SIZET_BITS;
continue;
}
const unsigned char * ptr=mem->ptr+pagepos+pos;
const unsigned char * ptrprev=mem->prev+pagepos+pos;
if (datsize==1 && pagepos+pos+SIZE_PAGE_LOW <= mem->len && (((uintptr_t)ptr)&(FAST_ALIGN-1)) == 0)
{
#if __SSE2__
__m128i* ptrS=(__m128i*)ptr;
size_t keep=0;
if (comptoprev)
{
__m128i* ptrprevS=(__m128i*)ptrprev;
static_assert(SIZET_BITS==32 || SIZET_BITS==64);
__m128i a1=_mm_loadu_si128(ptrS++);
__m128i a2=_mm_loadu_si128(ptrS++);
__m128i a3=_mm_loadu_si128(ptrS++);//no conditionals on the 64bit-only ones over here; let the optimizer eat them
__m128i a4=_mm_loadu_si128(ptrS++);
__m128i b1=_mm_load_si128(ptrprevS++);
__m128i b2=_mm_load_si128(ptrprevS++);
__m128i b3=_mm_load_si128(ptrprevS++);
__m128i b4=_mm_load_si128(ptrprevS++);
a1=_mm_xor_si128(a1, signflip);
a2=_mm_xor_si128(a2, signflip);
a3=_mm_xor_si128(a3, signflip);
a4=_mm_xor_si128(a4, signflip);
b1=_mm_xor_si128(b1, signflip);
b2=_mm_xor_si128(b2, signflip);
b3=_mm_xor_si128(b3, signflip);
b4=_mm_xor_si128(b4, signflip);
if (compfunc_fun<=cht_lte)
{
keep |= (size_t)_mm_movemask_epi8(_mm_cmplt_epi8(a1, b1));
keep |= (size_t)_mm_movemask_epi8(_mm_cmplt_epi8(a2, b2)) << 16;
if (SIZET_BITS==64) keep |= (size_t)_mm_movemask_epi8(_mm_cmplt_epi8(a3, b4)) << 16 << 16;
if (SIZET_BITS==64) keep |= (size_t)_mm_movemask_epi8(_mm_cmplt_epi8(a3, b4)) << 16 << 16 << 16;
}
if (compfunc_fun>=cht_lte)
{
keep |= (size_t)_mm_movemask_epi8(_mm_cmpeq_epi8(a1, b1));
keep |= (size_t)_mm_movemask_epi8(_mm_cmpeq_epi8(a2, b2)) << 16;
if (SIZET_BITS==64) keep |= (size_t)_mm_movemask_epi8(_mm_cmpeq_epi8(a4, b4)) << 16 << 16;