-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcodescan.inc
1318 lines (1228 loc) · 43.6 KB
/
codescan.inc
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
// Copyright (C) 2016 Y_Less
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#if defined CODESCAN_INC
#endinput
#endif
#define CODESCAN_INC
/**
* <library name="amx_assembly codescan" summary="AMX Assembly Library: Compiled code scanning and pattern matching.">
* <summary pawndoc="true">
* This library uses the enhanced <em>pawndoc.xsl</em> from
* <a href="https://github.com/pawn-lang/pawndoc">pawn-lang/pawndoc</a>.
* This XSL has features such as library and markdown support, and will not
* render this message when used.
* </summary>
* </library>
*/
/// <p/>
/*
// Example:
forward TailCall_FoundCallback(m[CodeScanner])
main() {
new scanner[CodeScanner];
CodeScanInit(scanner);
new csm0[CodeScanMatcher];
CodeScanMatcherInit(csm0, &TailCall_FoundCallback);
CodeScanMatcherPattern(csm0,
OP(PUSH_C, ???)
OP(CALL, &MyFunc)
OP(RETN)
);
CodeScanAddMatcher(scanner, csm0);
// Add other matcher patterns here.
// Run all the scanners in parallel.
CodeScanRun(scanner);
}
public TailCall_FoundCallback(m[CodeScanner]) {
// Do something with the found address (of the START of the match), and the
// stack size (of the END of the match) - different for reasons...
}
// Create a default call for this function, so that we can include it in the AMX
// and take the address in "OP". Note that you do NOT need to do this for
// scanner callbacks if you only use their address in "CodeScanMatcherInit".
#define CALL@MyFunc%8() MyFunc%8(0, "")
stock MyFunc(a, b[], ...) {
// Normal function.
}
*/
#include <core>
#include "frame_info"
#include "disasm"
#include "asm"
#include "addressof"
#define SCANNER_FAIL_ON_INVALID (1)
#define SCANNER_IGNORE_NOP (2)
#define SCANNER_IGNORE_BREAK (4)
#define SCANNER_NAME_FUNCTIONS (8)
#define SCANNER_IGNORE_HALT (16)
#define SCANNER_IGNORE_BOUNDS (32)
#define SCANNER_HAS_USER_DATA (64)
#define O@I_ (0) // Type integer.
#define O@U_ (1) // Type unknown (???).
#define O@F_ (2) // Type function (&func).
#define O@O_ (4) // Type opcode.
#define OP_TYPE_INTEGER_ (O@I_) // Type integer.
#define OP_TYPE_UNKNOWN_ (O@U_) // Type unknown (???).
#define OP_TYPE_FUNCTION_ (O@F_) // Type function (&func).
#define OP_TYPE_OPCODE_ (O@O_) // Type opcode.
// If we can determine a function's name, we can determine if it is a public or
// not. If we can't name it, it is a normal one. However, if naming is skipped
// then we will have no idea what type it is.
#define SCANNER_FUNC_PUBLIC (1)
#define SCANNER_FUNC_OTHER (2)
#define SCANNER_FUNC_AUTOMATA (3)
#define SCANNER_FUNC_HALT (4)
#define SCANNER_FUNC_UNKNOWN (5)
#define SCANNER_FUNC_AUTOMATA_NO_NAME (7)
#define SCANNER_FUNC_HALT_NO_NAME (8)
// The "OP()" macro is used to easilly define code patterns to scan for:
//
// new csm[CodeScanMatcher];
// CodeScanMatcherInit(csm, &callback);
// CodeScanMatcherPattern(csm,
// OP(CONST_PRI, 42)
// OP(ADD_C, ???)
// OP(CALL, &my_func)
// )
//
// Any function that you want to take the address of in this way must have its
// call pattern defined as:
//
// #define CALL@my_func%8() my_func%8(0, "", false)
//
// Because otherwise a) the code can't guarantee that the function will be in
// the final amx, and b) we need a call to it from which to extract the addr.
//
// You can use this style explcitly within an "OP" scanner, or there is a new
// dedicated keyword for it - "addressof(func)" (note the lack of "&" there).
//
#define OP(%0) ,(_:O@O_),(Opcode:O@X_:O@Y_:O@W_:$OP_%0)
#define OP_%0\32;%1) OP_%0%1)
#define O@X_:%9$%0,%1,%2) %0),(_:O@1_:O@2_:O@3_:$%1|||,%2)
#define O@Y_:%9$%0,%1) %0),(_:O@1_:O@2_:O@3_:$%1|||)
#define O@Z_:%9$%0) %0)
#define O@W_:%9$%0) %0)
#define O@1_:%9$%0???%1|||%2) O@U_ ),(_:O@X_:O@Y_:O@Z_:$0%2)
#if defined AMX_OLD_CALL
#define O@2_:%9$%0&%1|||%2) O@F_),((O@D_:O@A_())?(((CALL@%1),O@V_)?1:2):_:O@X_:O@Y_:O@Z_:$(O@V_)%2)
#else
#define O@2_:%9$%0&%1|||%2) O@F_),((O@D_:O@A_())?(((CALL@%1()),O@V_)?1:2):_:O@X_:O@Y_:O@Z_:$(O@V_)%2)
#endif
#define O@3_:%9$%1|||%2) O@I_ ),(_:O@X_:O@Y_:O@Z_:$(%1)%2)
#if !defined CODE_SCAN_MAX_PATTERN
#define CODE_SCAN_MAX_PATTERN (16)
#endif
#define CODE_SCAN_MAX_PATTERN_ARRAY (CODE_SCAN_MAX_PATTERN * 2)
#define CODE_SCAN_MAX_HOLES (CODE_SCAN_MAX_PATTERN / 2)
#if !defined CODE_SCAN_MAX_PARALLEL
#define CODE_SCAN_MAX_PARALLEL (2)
#endif
#if !defined CODE_SCAN_MAX_JUMP_TARGETS
#define CODE_SCAN_MAX_JUMP_TARGETS (32)
#endif
#define DISASM_GET_OPERAND_INLINE(%0,%1) ReadAmxMemory((%0) + (%1 + 1) * cellbytes)
#define CODE_SCAN_NOT_IN_RANGE(%0,%1,%2) ((_:(%0)-(_:(%1)+cellmin))>=(_:(%2)-(_:(%1)+cellmin)))
/// <p/>
/// <library>amx_assembly codescan</library>
/// <summary>
/// All the information for scanning through an AMX and extracting lots of nice
/// information about it.
/// </summary>
enum CodeScanner {
CodeScanMatch_func, // Start of the containing function.
CodeScanMatch_size, // Size of the match.
CodeScanMatch_type, // Public, normal, automata, etc.
CodeScanMatch_heap, // At the point of this scanner.
CodeScanMatch_stack, // At the point of this scanner.
CodeScanMatch_params, // Likely unknown statically.
CodeScanMatch_cip, // The point of the pattern match.
CodeScanMatch_holes[CODE_SCAN_MAX_HOLES], // Results of "???"s.
CodeScanMatch_hole_count, // How many holes were seen.
CodeScanMatch_name[64 char],
CodeScanner_first,
CodeScanner_minn,
CodeScanner_jump_switch[CODE_SCAN_MAX_JUMP_TARGETS], // For "CASETBL" not regular jumps.
CodeScanner_jump_target[CODE_SCAN_MAX_JUMP_TARGETS], // Zero when this slot is available.
CodeScanner_jump_stack [CODE_SCAN_MAX_JUMP_TARGETS], // Sizes at the time of the jump.
CodeScanner_jump_heap [CODE_SCAN_MAX_JUMP_TARGETS], // Sizes at the time of the jump.
CodeScanner_state,
CodeScanner_param
}
/// <library>amx_assembly codescan</library>
const CodeScanner:CodeScanner__ = CodeScanner;
/// <p/>
/// <library>amx_assembly codescan</library>
enum CodeScanMatcher {
CodeScanMatcher_func, // A pointer to the callback.
CodeScanMatcher_user_data, // User data to pass to their callback.
CodeScanMatcher_type[CODE_SCAN_MAX_PATTERN_ARRAY], // The code slot types.
CodeScanMatcher_code[CODE_SCAN_MAX_PATTERN_ARRAY], // The code to look for.
CodeScanMatcher_len,
CodeScanMatcher_offset[CODE_SCAN_MAX_PARALLEL], // Where the current scanner is in this code.
CodeScanMatcher_start[CODE_SCAN_MAX_PARALLEL],
CodeScanMatcher_holeidx[CODE_SCAN_MAX_PARALLEL],
CodeScanMatcher_holes[CODE_SCAN_MAX_PARALLEL * CODE_SCAN_MAX_HOLES],
CodeScanMatcher_next, // The next match array.
CodeScanMatcher_flags // Customisation.
}
/// <library>amx_assembly codescan</library>
const CodeScanMatcher:CodeScanMatcher__ = CodeScanMatcher;
// This macro is to let anyone use `&callback` for a scanner callback without
// having to define the `CALL@...` macro for the required parameters (since we
// know to call scanner callbacks in this code).
#define addressof_ScannerCallback_(%1) ((O@D_:O@A_())?(((%1((gCodeScanCallback_match))),O@V_)?1:2):(O@V_))
/// <library>amx_assembly codescan</library>
stock gCodeScanCallback_match[CodeScanner] = {};
#define CodeScanDeref(%0) gFakeMatcher,(%0)
/// <library>amx_assembly codescan</library>
static stock gFakeMatcher[CodeScanMatcher];
/// <library>amx_assembly codescan</library>
static stock gOP_NOP = 0;
/// <library>amx_assembly codescan</library>
static stock gOP_CASETBL = 0;
/// <library>amx_assembly codescan</library>
static stock gHdr[AMX_HDR];
/// <library>amx_assembly codescan</library>
static stock gBase = 0;
/// <library>amx_assembly codescan</library>
static stock gCodBase = 0;
/// <library>amx_assembly codescan</library>
static stock gDat = 0;
/// <library>amx_assembly codescan</library>
static stock bool:CodeScanCheckJumpTarget(cip, deloc, &stk, &hea, jumpTargets[CodeScanner], num = CODE_SCAN_MAX_JUMP_TARGETS) {
// Use "minn" to restrict the number of jump targets that we check. Returns
// "true" if the current address is equal to an address that any jump goes
// to.
new
minn = jumpTargets[CodeScanner_minn],
sip = 0;
while (num-- > minn) {
if (jumpTargets[CodeScanner_jump_target][num] == cip) {
return
jumpTargets[CodeScanner_jump_target][num] = cellmin,
stk = jumpTargets[CodeScanner_jump_stack][num],
hea = jumpTargets[CodeScanner_jump_heap][num],
true;
} else if ((sip = jumpTargets[CodeScanner_jump_switch][num]) && jumpTargets[CodeScanner_jump_target][num] > cip) {
for (new count = ReadAmxMemory(sip + cellbytes) + 1; count; --count) {
if (ReadAmxMemory(sip + count * (2 * cellbytes)) == deloc) {
return
stk = jumpTargets[CodeScanner_jump_stack][num],
hea = jumpTargets[CodeScanner_jump_heap][num],
true;
}
}
}
}
return false;
}
/// <library>amx_assembly codescan</library>
static stock CodeScanResetJumpTargets(jumpTargets[CodeScanner], num = CODE_SCAN_MAX_JUMP_TARGETS) {
jumpTargets[CodeScanner_minn] = num;
while (num--) {
jumpTargets[CodeScanner_jump_target][num] = cellmin;
}
}
/// <library>amx_assembly codescan</library>
static stock CodeScanAddJumpTarget(cip, target, stk, hea, jumpTargets[CodeScanner], num = CODE_SCAN_MAX_JUMP_TARGETS) {
while (num--) {
// Multiple jumps to the same place?
if (jumpTargets[CodeScanner_jump_target][num] == target) {
return;
} else if (jumpTargets[CodeScanner_jump_target][num] < cip) {
jumpTargets[CodeScanner_jump_switch][num] = 0;
jumpTargets[CodeScanner_jump_target][num] = target;
jumpTargets[CodeScanner_jump_stack][num] = stk;
jumpTargets[CodeScanner_jump_heap][num] = hea;
jumpTargets[CodeScanner_minn] = min(jumpTargets[CodeScanner_minn], num);
return;
}
}
}
/// <library>amx_assembly codescan</library>
static stock CodeScanAddSwitchTarget(cip, stk, hea, jumpTargets[CodeScanner], num = CODE_SCAN_MAX_JUMP_TARGETS) {
// Get the case table for this switch.
new
sip = DISASM_GET_OPERAND_INLINE(cip, 0) - gBase,
codepos = sip + gHdr[AMX_HDR_DAT] - gHdr[AMX_HDR_COD];
if ((codepos < 0) || (codepos > gHdr[AMX_HDR_DAT]) || (_:ReadAmxMemory(sip) != _:gOP_CASETBL)) {
// Can happen when we parse "RelocateOpcodeNow" because it has an
// explicit "#emit switch 0" in.
return;
}
// Find the highest address in this case table. Add 1 because the count
// doesn't include the default.
new highest = cellmin;
new count = ReadAmxMemory(sip + cellbytes) + 1;
for (new i = 1; i <= count; ++i) {
// Not an OBOE, all relative to the start.
if ((codepos = ReadAmxMemory(sip + i * (2 * cellbytes))) > highest) {
highest = codepos;
}
}
while (num--) {
// Multiple jumps to the same place?
if (jumpTargets[CodeScanner_jump_target][num] < cip) {
jumpTargets[CodeScanner_jump_switch][num] = sip,
jumpTargets[CodeScanner_jump_target][num] = highest,
jumpTargets[CodeScanner_jump_stack][num] = stk,
jumpTargets[CodeScanner_jump_heap][num] = hea,
jumpTargets[CodeScanner_minn] = min(jumpTargets[CodeScanner_minn], num);
return;
}
}
}
/// <library>amx_assembly codescan</library>
static stock CodeScanReset(cs[CodeScanMatcher], matcher__, &next) {
#emit LOAD.S.pri matcher__
#emit STOR.S.pri cs
static
lReset[CODE_SCAN_MAX_PARALLEL];
next = cs[CodeScanMatcher_next],
cs[CodeScanMatcher_offset] = lReset,
cs[CodeScanMatcher_holeidx] = lReset;
if (!cs[CodeScanMatcher_func]) {
cs[CodeScanMatcher_len] = 0;
}
}
/// <library>amx_assembly codescan</library>
stock CodeScanAddMatcher(scanner[CodeScanner], searcher[CodeScanMatcher]) {
searcher[CodeScanMatcher_next] = scanner[CodeScanner_first],
scanner[CodeScanner_first] = ref(searcher);
}
/// <library>amx_assembly codescan</library>
static stock bool:gRelocateRequired;
/// <library>amx_assembly codescan</library>
stock CodeScanMatcherInit_(searcher[CodeScanMatcher], address, flags = SCANNER_IGNORE_NOP | SCANNER_IGNORE_BOUNDS | SCANNER_IGNORE_BREAK | SCANNER_IGNORE_HALT) {
if (flags != SCANNER_IGNORE_NOP | SCANNER_IGNORE_BOUNDS | SCANNER_IGNORE_BREAK | SCANNER_IGNORE_HALT) {
printf("Warning: Flags are no longer used.");
printf(" NOP, BREAK, BOUNDS, and HALT are always ignored.");
}
static
lReset[CODE_SCAN_MAX_PARALLEL];
// This used to look the function up by name from the public functions
// table, but that was very silly since we already had code in this exact
// file to get the address of ANY function at run-time (`addressof`). The
// only difference between the normal `addressof` and the one used here is
// that because we know exactly what sort of functions we are expecting, we
// know exactly what parameters they require to construct the fake call, so
// we can do away with the `CALL@...` macro requirement for defining the
// standard call pattern. This also means that we actually ensure that the
// passed function has the correct shape.
searcher[CodeScanMatcher_func] = address,
searcher[CodeScanMatcher_flags] = flags & ~SCANNER_HAS_USER_DATA,
searcher[CodeScanMatcher_next] = -1,
searcher[CodeScanMatcher_len] = 0,
searcher[CodeScanMatcher_user_data] = 0,
searcher[CodeScanMatcher_offset] = lReset,
searcher[CodeScanMatcher_holeidx] = lReset,
RelocateOpcode(OP_NOP); // Initialise the opcode system safely.
gRelocateRequired = IsOpcodeRelocationRequired();
}
/// <library>amx_assembly codescan</library>
stock CodeScanMatcherData(searcher[CodeScanMatcher], val) {
// Use `ref()` to pass an array.
searcher[CodeScanMatcher_flags] |= SCANNER_HAS_USER_DATA,
searcher[CodeScanMatcher_user_data] = val;
}
// Will not call the function because the check will fail, but will not compile
// if the function doesn't exist, while still passing it in as a string.
#define CodeScanMatcherInit(%0,&%1) CodeScanMatcherInit_((%0),addressof_ScannerCallback_(%1))
#define CodeScanMatcherInit_(%0,addressof_ScannerCallback_(%1,%2)) CodeScanMatcherInit_(%0,addressof_ScannerCallback_(%1),%2)
/// <library>amx_assembly codescan</library>
stock CodeScanMatcherPattern_(searcher[CodeScanMatcher], {Opcode, Float, _}:...) {
new
len = numargs() - 1;
if (len > CODE_SCAN_MAX_PATTERN_ARRAY) {
return -1;
}
if (len & 0x01) {
// Not a multiple of 2 in the scanner.
return -2;
}
for (new i = 0, j = 0; i != len; ) {
new
optype = getarg(i + 1),
Opcode:op = Opcode:getarg(i + 2);
searcher[CodeScanMatcher_type][j] = optype;
searcher[CodeScanMatcher_code][j] = _:op;
i += 2;
++j;
switch (optype) {
case OP_TYPE_OPCODE_: {
new opcount = gAMXOpcodeParameterCounts[_:op];
for (new partype = 0; i != len; )
{
partype = getarg(i + 1);
switch (partype) {
case OP_TYPE_INTEGER_, OP_TYPE_UNKNOWN_, OP_TYPE_FUNCTION_: {
// Got an unexpected parameter.
if (opcount == 0) {
return j + 1;
}
// Decrement the remaining number of parameters.
// The variable OPs like `CASETBL` have negative
// parameter counts, so will never not match.
--opcount;
searcher[CodeScanMatcher_type][j] = partype;
searcher[CodeScanMatcher_code][j] = getarg(i + 2);
i += 2;
++j;
}
default: {
break;
}
}
}
// Missing a required (non-optional) parameter.
if (opcount > 0) {
return j + 1;
}
}
default: {
// Incorrect parameter type. Return the op where it happened.
return j + 1;
}
}
}
searcher[CodeScanMatcher_len] = len / 2;
// No error.
return 0;
}
// Note the lack of trailing comma. This is to make the code patterns work.
#define CodeScanMatcherPattern(%0, CodeScanMatcherPattern_(%0
/// <library>amx_assembly codescan</library>
static stock bool:CodeScanCheck(Opcode:op, const dctx[DisasmContext], cs[CodeScanMatcher], matcher__, fctx[CodeScanner], &next) {
#emit LOAD.S.pri matcher__
#emit STOR.S.pri cs
new
bool:zero = true,
off,
cnt = (op == OP_CASETBL) ? (_:ReadAmxMemory(dctx[DisasmContext_cip] + cellbytes)) : (gAMXOpcodeParameterCounts[_:op]),
len = cs[CodeScanMatcher_len];
for (new idx = 0; idx != CODE_SCAN_MAX_PARALLEL; ++idx) {
off = cs[CodeScanMatcher_offset][idx];
// Ensure that only one of the parallel scanners starts from the
// beginning on each instruction.
if (off) {
} else if (zero) {
// Get the start point of this match.
cs[CodeScanMatcher_start][idx] = dctx[DisasmContext_cip],
zero = false;
} else {
continue;
}
if (cs[CodeScanMatcher_type][off] == OP_TYPE_OPCODE_ && Opcode:cs[CodeScanMatcher_code][off] == op) {
// Check if there are enough parameters for this opcode.
++off;
for (new i = 0; i != cnt; ++i) {
switch (cs[CodeScanMatcher_type][off]) {
// Because we now abstract relocations to the disasm system,
// we don't need to differentiate between fixed parameters
// and function parameters any more - they are always fully
// resolved.
case OP_TYPE_INTEGER_, OP_TYPE_FUNCTION_: {
if (cs[CodeScanMatcher_code][off] != DisasmGetOperandReloc(dctx, i)) {
goto CodeScanCheck_fail;
}
}
case OP_TYPE_UNKNOWN_: {
// Save the parameter.
cs[CodeScanMatcher_holes][idx * CODE_SCAN_MAX_HOLES + cs[CodeScanMatcher_holeidx][idx]++] = DisasmGetOperandReloc(dctx, i);
}
case OP_TYPE_OPCODE_: {
goto CodeScanCheck_fail;
}
}
++off;
}
if (off == len) {
// Get the address of the START of the match.
return
memcpy(fctx[CodeScanMatch_holes], cs[CodeScanMatcher_holes][idx * CODE_SCAN_MAX_HOLES], 0, cs[CodeScanMatcher_holeidx][idx] * cellbytes, CODE_SCAN_MAX_HOLES),
fctx[CodeScanMatch_hole_count] = cs[CodeScanMatcher_holeidx][idx],
fctx[CodeScanMatch_cip] = cs[CodeScanMatcher_start][idx],
fctx[CodeScanMatch_size] = dctx[DisasmContext_nip] - cs[CodeScanMatcher_start][idx],
true;
} else switch (cs[CodeScanMatcher_type][off]) {
case OP_TYPE_INTEGER_, OP_TYPE_FUNCTION_, OP_TYPE_UNKNOWN_: {
// Parameters remaining, none expected.
goto CodeScanCheck_fail;
}
default: {
// Out of parameters to check but still looking correct.
cs[CodeScanMatcher_offset][idx] = off;
continue;
}
}
}
CodeScanCheck_fail:
// The parameter is wrong.
cs[CodeScanMatcher_holeidx][idx] = cs[CodeScanMatcher_offset][idx] = 0;
}
return
next = cs[CodeScanMatcher_next],
false;
}
/// <library>amx_assembly codescan</library>
static stock bool:CodeScanGetFuncName(addr, name[]) {
// The "name" parameter is longer than 64 (which is the maximum function
// name length normally) beacause we append states to some.
// Name not found.
new
index = GetPublicIndexFromAddress(addr);
if (index < 0) {
return
name[0] = 0,
false;
}
// This code will not return great results for public functions with states.
return
GetPublicNameFromIndex(index, name, 64),
true;
}
/// <library>amx_assembly codescan</library>
static stock bool:CodeScanStepInternal(dctx[DisasmContext], csState[CodeScanner], &parseState, &parseParam) {
// Loop over the data. Since our end condition is "out of data", we know
// that any "false" returns are because of invalid data since the "< 0"
// check is also the only other way that "false" can be returned and we pre-
// empt that one.
new
cip = dctx[DisasmContext_nip],
Opcode:op,
stk = csState[CodeScanMatch_stack],
hea = csState[CodeScanMatch_heap];
for ( ; ; ) {
if (cip >= dctx[DisasmContext_end_ip]) {
return
dctx[DisasmContext_cip] = cip,
false;
}
op = UnsafeUnrelocateOpcode(Opcode:ReadAmxMemory(cip));
// The compiler sometimes inserts extra instructions like "NOP" and
// "BREAK" for debugging and padding (as do we) - maybe ignore them.
if (parseState & cellmin) {
// Only check the jump target if this point can't be reached
// naturally. If the code can fall through from the previous
// instruction the stack and heap must be the same as if we had
// jumped here, thus there's no point doing the complex jump checks.
//
// To facilitate this, the jump targets now ignore any addresses
// passed by, because we only check a small percentage of them.
CodeScanCheckJumpTarget(cip, cip + gBase, stk, hea, csState);
parseState &= ~cellmin;
}
if (CODE_SCAN_NOT_IN_RANGE(op, _:OP_NONE + 1, NUM_OPCODES)) {
cip += cellbytes,
parseState |= cellmin;
continue;
}
switch (op) {
case OP_BREAK, OP_NOP: {
cip += cellbytes,
parseState |= cellmin;
continue;
}
case OP_CASETBL: {
cip += cellbytes,
cip += ReadAmxMemory(cip) * (2 * cellbytes),
parseState = cellmin;
break;
}
case OP_HALT: {
if (parseState == 4) {
csState[CodeScanMatch_type] = SCANNER_FUNC_HALT_NO_NAME,
csState[CodeScanMatch_func] = cip,
stk = hea = 0,
CodeScanResetJumpTargets(csState);
} else {
parseState |= cellmin;
}
cip += 2 * cellbytes;
continue;
}
case OP_BOUNDS: {
cip += 2 * cellbytes;
continue;
}
case OP_PROC: {
// This is the start of a new function. The only functions
// that don't start like this are the automata stubs.
csState[CodeScanMatch_type] = SCANNER_FUNC_UNKNOWN,
csState[CodeScanMatch_func] = cip,
CodeScanResetJumpTargets(csState),
stk = hea = parseState = 0;
break;
}
case OP_LOAD_PRI: {
// If we are not in the main functions yet and this is the
// first instruction seen, then it is the start of an
// automata function stub.
if (parseState == 4) {
csState[CodeScanMatch_type] = SCANNER_FUNC_AUTOMATA_NO_NAME,
csState[CodeScanMatch_func] = cip,
stk = hea = 0,
CodeScanResetJumpTargets(csState);
}
break;
}
case OP_PUSH_PRI, OP_PUSH_ALT, OP_PUSH_R, OP_PUSH_S, OP_PUSH, OP_PUSH_ADR: {
if (stk != cellmin) {
stk += cellbytes;
}
parseState = 0;
break;
}
#if OPCODE_HAS_O2
case OP_PUSH2_C, OP_PUSH2, OP_PUSH2_S, OP_PUSH2_ADR: {
if (stk != cellmin) {
stk += cellbytes * 2;
}
parseState = 0;
break;
}
case OP_PUSH3_C, OP_PUSH3, OP_PUSH3_S, OP_PUSH3_ADR: {
if (stk != cellmin) {
stk += cellbytes * 3;
}
parseState = 0;
break;
}
case OP_PUSH4_C, OP_PUSH4, OP_PUSH4_S, OP_PUSH4_ADR: {
if (stk != cellmin) {
stk += cellbytes * 4;
}
parseState = 0;
break;
}
case OP_PUSH5_C, OP_PUSH5, OP_PUSH5_S, OP_PUSH5_ADR: {
if (stk != cellmin) {
stk += cellbytes * 5;
}
parseState = 0;
break;
}
case OP_SYSREQ_N: {
// sysreq.n cleans itself up, it isn't followed by `stack`.
if (stk != cellmin) {
stk -= DISASM_GET_OPERAND_INLINE(cip, 1);
}
parseState = 0;
break;
}
#endif
case OP_STACK: {
// The stack grows down, but our count is positive.
if (stk != cellmin) {
stk -= DISASM_GET_OPERAND_INLINE(cip, 0);
}
// I don't know why this needs `cellmin` instead of `0`. It
// should handle the stack just fine. It is literally an opcode
// for managing the stack, so why do we need to check the status
// right after it?
parseState = cellmin;
break;
}
case OP_HEAP: {
if (hea != cellmin) {
hea += DISASM_GET_OPERAND_INLINE(cip, 0);
}
parseState = 0;
break;
}
case OP_POP_PRI, OP_POP_ALT: {
if (stk != cellmin) {
stk -= cellbytes;
}
parseState = 0;
break;
}
case OP_CALL, OP_CALL_PRI: {
// Remove all the function parameters.
if (parseState == 3) {
stk -= parseParam;
}
parseState = 0;
break;
}
case OP_PUSH_C: {
// The "+ cellbytes" is because when calling a function, the
// parameter is the number of bytes pushed, not including
// this one, with that one implicitly popped on return.
parseParam = DISASM_GET_OPERAND_INLINE(cip, 0) + cellbytes;
if (stk != cellmin) {
stk += cellbytes,
parseState = 3;
}
break;
}
// There is a code-get pattern of:
//
// LCTRL 5
// ADD.C n
// SCTRL 4
//
// Which adjusts the stack to the correct size after "goto". We
// have to deal with that explcitly. Note that the "ADD.C" may
// be missing if there are no variables currently in scope.
case OP_LCTRL: {
if (DISASM_GET_OPERAND_INLINE(cip, 0) == 5) {
parseParam = 0;
parseState = 1;
} else {
parseState = 0;
}
break;
}
case OP_ADD_C: {
if (parseState == 1) {
parseParam = -DISASM_GET_OPERAND_INLINE(cip, 0),
parseState = 2;
} else {
parseState = 0;
}
break;
}
case OP_SCTRL: {
// This is the tricky one, since it can mess up the stack in
// strange ways. Deal with the case where it comes from
// "goto", even though that is generally considered bad.
switch (DISASM_GET_OPERAND_INLINE(cip, 0)) {
case 2: {
hea = cellmin;
}
case 4: {
switch (parseState) {
case 1: {
stk = 0;
}
case 2: {
stk = parseParam;
}
default: {
stk = cellmin;
}
}
}
case 5: {
stk = cellmin;
}
}
parseState = 0;
break;
}
case OP_JUMP: {
parseParam = DISASM_GET_OPERAND_INLINE(cip, 0) - gBase,
parseState = cellmin;
if (parseParam > cip) {
CodeScanAddJumpTarget(cip, parseParam, stk, hea, csState);
}
break;
}
case OP_JZER, OP_JNZ, OP_JEQ, OP_JNEQ, OP_JLESS, OP_JLEQ, OP_JGRTR, OP_JGEQ, OP_JSLESS, OP_JSLEQ, OP_JSGRTR, OP_JSGEQ: {
// Add a jump target. These require relocation as they are
// translated to absolute RAM locations. "DisasmNeedReloc"
// will return "true", but we don't need to call it.
// Relocate it relative to "dat" not "cod" for simpler
// comparisons - just see if the read address matches
// instead of the true code address.
//
// val = val - (base + cod) + (cod - dat);
// val = val - base - cod + cod - dat;
// val = val - base - dat;
// val = val - (base + dat);
// base = base + dat;
// val = val - base;
//
// Only jumps that go forwards.
parseParam = DISASM_GET_OPERAND_INLINE(cip, 0) - gBase,
parseState = 0;
if (parseParam > cip) {
CodeScanAddJumpTarget(cip, parseParam, stk, hea, csState);
}
break;
}
case OP_JREL: {
// Add a jump target. Only jumps that go forwards.
parseParam = DISASM_GET_OPERAND_INLINE(cip, 0) + cip,
parseState = 0;
if (parseParam > cip) {
CodeScanAddJumpTarget(cip, parseParam, stk, hea, csState);
}
break;
}
case OP_SWITCH: {
// Add a jump target. These are always forwards.
CodeScanAddSwitchTarget(cip, stk, hea, csState),
parseState = cellmin;
break;
}
case OP_RETN: {
parseState = cellmin;
break;
}
default: {
parseState = 0;
break;
}
}
}
return
dctx[DisasmContext_opcode] = op,
dctx[DisasmContext_cip] = cip,
dctx[DisasmContext_nip] = cip + gAMXOpcodeBaseSizes[_:op],
csState[CodeScanMatch_stack] = stk,
csState[CodeScanMatch_heap] = hea,
true;
}
/// <library>amx_assembly codescan</library>
stock bool:CodeScanStep(dctx[DisasmContext], csState[CodeScanner]) {
new bool:ret = CodeScanStepInternal(dctx, csState, csState[CodeScanner_state], csState[CodeScanner_param]);
csState[CodeScanner_state] |= cellmin;
return ret;
}
/// <library>amx_assembly codescan</library>
static stock CodeScanCall(const cs[CodeScanMatcher], matcher__, csState[CodeScanner]) {
#emit LOAD.S.pri matcher__
#emit STOR.S.pri cs
// If I wrote way more assembly I could get away with not calling
// `CodeScanDeref(cur)` below, and not need to assign `param` to a variable
// before pushing it. But I'm not going to - it isn't worth the effort.
new
func = cs[CodeScanMatcher_func];
if (cs[CodeScanMatcher_flags] & SCANNER_HAS_USER_DATA) {
const cells0 = 2 * cellbytes;
const cells1 = 9 * cellbytes;
new
param = cs[CodeScanMatcher_user_data];
#emit PUSH.S param
#emit PUSH.S csState
#emit PUSH.C cells0
#emit LCTRL __cip
#emit ADD.C cells1
#emit LCTRL __jmp
#emit PUSH.pri
#emit LOAD.S.pri func
#emit SCTRL __cip
#emit STOR.S.pri func
} else {
const cells2 = 1 * cellbytes;
const cells3 = 9 * cellbytes;
#emit PUSH.S csState
#emit PUSH.C cells2
#emit LCTRL __cip
#emit ADD.C cells3
#emit LCTRL __jmp
#emit PUSH.pri
#emit LOAD.S.pri func
#emit SCTRL __cip
#emit STOR.S.pri func
}
return func;
}
/// <library>amx_assembly codescan</library>
static stock bool:CodeScanFindOneFastPattern3(const matcher[CodeScanMatcher], matcher__, addr, &cur) {
#emit LOAD.S.pri matcher__
#emit STOR.S.pri matcher
// Check if the current matcher has this exact function call in it as well.
cur = matcher[CodeScanMatcher_next];
for (new i = 0, j = matcher[CodeScanMatcher_len]; i != j; ++i) {
if (matcher[CodeScanMatcher_type][i] == OP_TYPE_OPCODE_ && Opcode:matcher[CodeScanMatcher_code][i] == OP_CALL && matcher[CodeScanMatcher_type][i + 1] == OP_TYPE_FUNCTION_ && matcher[CodeScanMatcher_code][i + 1] == addr) {
return true;
}
}
return false;
}
/// <library>amx_assembly codescan</library>
static stock bool:CodeScanFindOneFastPattern2(const matcher[CodeScanMatcher], matcher__, &addr) {
#emit LOAD.S.pri matcher__
#emit STOR.S.pri matcher
// Loop over all the function calls in the first matcher, and check that at least one exists in
// all the others. We only need to loop over the first, because it must exist in them all, so
// even if it is in all but the first it isn't good enough.
for (new i = 0, j = matcher[CodeScanMatcher_len]; i != j; ++i) {
if (matcher[CodeScanMatcher_type][i] == OP_TYPE_OPCODE_ && Opcode:matcher[CodeScanMatcher_code][i] == OP_CALL && matcher[CodeScanMatcher_type][i + 1] == OP_TYPE_FUNCTION_) {
// Found a candidate for the fast scan.
addr = matcher[CodeScanMatcher_code][i + 1];
new cur = matcher[CodeScanMatcher_next];
do {
if (cur == -1) {
// Ran out of matchers, so this function call will do.
return true;
}
// Check that all other matchers have the same function call.
} while (CodeScanFindOneFastPattern3(CodeScanDeref(cur), addr, cur));
}
}
return false;
}
forward bool:CodeScanRun(csState[CodeScanner]);
/// <library>amx_assembly codescan</library>
static stock CodeScanRunFastPrescanLocated(&proc, &nextaddr, const searchFuncAddr) {
// Do a fast code scan for functions containing something vaguely similar to the pattern. Once
// that's found we can reparse the function with the full analysis mode.
new Opcode:o = OP_NONE;
new addr = nextaddr;
while (addr < 0) {
switch (o = Opcode:ReadAmxMemory(addr)) {
case OP_PROC: {
proc = addr;
addr += cellbytes;
}
case OP_CASETBL: {
addr += ReadAmxMemory(addr + cellbytes) * (2 * cellbytes) + (3 * cellbytes);
}
case OP_CALL: {
if (ReadAmxMemory(addr + cellbytes) - gCodBase == searchFuncAddr) {
nextaddr = addr;
return true;
}
addr += 2 * cellbytes;
}
default: {
addr += CODE_SCAN_NOT_IN_RANGE(o, 0, sizeof (gAMXOpcodeBaseSizes)) ? (cellbytes) : (gAMXOpcodeBaseSizes[_:o]);
}
}
}
return false;
}
/// <library>amx_assembly codescan</library>
static stock CodeScanRunFastPrescanRelocate(&proc, &nextaddr, const searchFuncAddr) {
// Do a fast code scan for functions containing something vaguely similar to the pattern. Once
// that's found we can reparse the function with the full analysis mode.
new Opcode:o = OP_NONE;
new addr = nextaddr;
while (addr < 0) {
switch (o = UnrelocateOpcode(Opcode:ReadAmxMemory(addr))) {
case OP_PROC: {
proc = addr;
addr += cellbytes;
}
case OP_CASETBL: {
addr += ReadAmxMemory(addr + cellbytes) * (2 * cellbytes) + (3 * cellbytes);
}
case OP_CALL: {
if (ReadAmxMemory(addr + cellbytes) - gCodBase == searchFuncAddr) {
nextaddr = addr;
return true;
}
addr += 2 * cellbytes;
}
default: {
addr += CODE_SCAN_NOT_IN_RANGE(o, 0, sizeof (gAMXOpcodeBaseSizes)) ? (cellbytes) : (gAMXOpcodeBaseSizes[_:o]);
}
}
}
return false;
}