/
autoassembler.pas
2988 lines (2380 loc) · 92.7 KB
/
autoassembler.pas
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
unit autoassembler;
{$MODE Delphi}
interface
uses jwawindows, windows, Assemblerunit, classes, LCLIntf,symbolhandler,
sysutils,dialogs,controls, CEFuncProc, NewKernelHandler ,plugin,
ProcessHandlerUnit, lua, lualib, lauxlib;
function getenableanddisablepos(code:tstrings;var enablepos,disablepos: integer): boolean;
function autoassemble(code: tstrings;popupmessages: boolean):boolean; overload;
function autoassemble(code: Tstrings; popupmessages,enable,syntaxcheckonly, targetself: boolean):boolean; overload;
function autoassemble(code: Tstrings; popupmessages,enable,syntaxcheckonly, targetself: boolean;var CEAllocarray: TCEAllocArray; registeredsymbols: tstringlist=nil): boolean; overload;
type TAutoAssemblerPrologue=procedure(code: TStrings; syntaxcheckonly: boolean) of object;
type TAutoAssemblerCallback=function(parameters: string; syntaxcheckonly: boolean): string of object;
type TRegisteredAutoAssemblerCommand=class
command: string;
callback: TAutoAssemblerCallback;
end;
procedure RegisterAutoAssemblerCommand(command: string; callback: TAutoAssemblerCallback);
procedure UnregisterAutoAssemblerCommand(command: string);
function registerAutoAssemblerPrologue(m: TAutoAssemblerPrologue): integer;
procedure unregisterAutoAssemblerPrologue(id: integer);
implementation
uses simpleaobscanner, StrUtils, LuaHandler, memscan, disassembler, networkInterface,
networkInterfaceApi, fgl, LuaCaller, SynHighlighterAA;
resourcestring
rsForwardJumpWithNoLabelDefined = 'Forward jump with no label defined';
rsThereIsCodeDefinedWithoutSpecifyingTheAddressItBel = 'There is code defined without specifying the address it belongs to';
rsIsNotAValidBytestring = '%s is not a valid bytestring';
rsTheBytesAtAreNotWhatWasExpected = 'The bytes at %s are not what was expected';
rsTheMemoryAtCanNotBeRead = 'The memory at +%s can not be read';
rsWrongSyntaxASSERTAddress1122335566 = 'Wrong syntax. ASSERT(address,11 22 33 ** 55 66)';
rsIsNotAValidSize = '%s is not a valid size';
rsWrongSyntaxGLOBALALLOCNameSize = 'Wrong syntax. GLOBALALLOC(name,size)';
rsCouldNotBeFound = '%s could not be found';
rsWrongSyntaxIncludeFilenameCea = 'Wrong syntax. Include(filename.cea)';
rsWrongSyntaxCreateThreadAddress = 'Wrong syntax. CreateThread(address)';
rsCouldNotBeInjected = '%s could not be injected';
rsWrongSyntaxLoadLibraryFilename = 'Wrong syntax. LoadLibrary(filename)';
rsWrongSyntaxLuaCall = 'Wrong Syntax. LuaCall(luacommand)';
rsInvalidAddressForReadMem = 'Invalid address for ReadMem';
rsInvalidSizeForReadMem = 'Invalid size for ReadMem';
rsTheMemoryAtCouldNotBeFullyRead = 'The memory at %s could not be fully read';
rsWrongSyntaxReadMemAddressSize = 'Wrong syntax. ReadMem(address,size)';
rsTheFileDoesNotExist = 'The file %s does not exist';
rsWrongSyntaxLoadBinaryAddressFilename = 'Wrong syntax. LoadBinary(address,filename)';
rsWrongSyntaxReAssemble = 'Wrong syntax. Reassemble(address)';
rsSyntaxError = 'Syntax error';
rsTheArrayOfByteCouldNotBeFound = 'The array of byte ''%s'' could not be found';
rsWrongSyntaxAOBSCANName11223355 = 'Wrong syntax. AOBSCAN(name,11 22 33 ** 55)';
rsWrongSyntaxAOBSCANMODULEName11223355 = 'Wrong syntax. AOBSCANMODULE(name, module, 11 22 33 ** 55)';
rsDefineAlreadyDefined = 'Define %s already defined';
rsWrongSyntaxDEFINENameWhatever = 'Wrong syntax. DEFINE(name,whatever)';
rsSyntaxErrorFullAccessAddressSize = 'Syntax error. FullAccess(address,size)';
rsIsNotAValidIdentifier = '%s is not a valid identifier';
rsIsBeingRedeclared = '%s is being redeclared';
rsLabelIsBeingDefinedMoreThanOnce = 'label %s is being defined more than once';
rsLabelIsNotDefinedInTheScript = 'label %s is not defined in the script';
rsTheIdentifierHasAlreadyBeenDeclared = 'The identifier %s has already been declared';
rsWrongSyntaxALLOCIdentifierSizeinbytes = 'Wrong syntax. ALLOC(identifier,sizeinbytes)';
rsNeedToUseKernelmodeReadWriteprocessmemory = 'You need to use kernelmode read/writeprocessmemory if you want to use KALLOC';
rsSorryButWithoutTheDriverKALLOCWillNotFunction = 'Sorry, but without the driver KALLOC will not function';
rsWrongSyntaxKallocIdentifierSizeinbytes = 'Wrong syntax. kalloc(identifier,sizeinbytes)';
rsThisAddressSpecifierIsNotValid = 'This address specifier is not valid';
rsThisInstructionCanTBeCompiled = 'This instruction can''t be compiled';
rsErrorInLine = 'Error in line %s (%s) :%s';
rsWasSupposedToBeAddedToTheSymbollistButItIsnTDeclar = '%s was supposed to be added to the symbollist, but it isn''t declared';
rsTheAddressInCreatethreadIsNotValid = 'The address in createthread(%s) is not valid';
rsTheAddressInLoadbinaryIsNotValid = 'The address in loadbinary(%s,%s) is not valid';
rsThisCodeCanBeInjectedAreYouSure = 'This code can be injected. Are you sure?';
rsFailureToAllocateMemory = 'Failure to allocate memory';
rsNotAllInstructionsCouldBeInjected = 'Not all instructions could be injected';
rsTheFollowingKernelAddressesWhereAllocated = 'The following kernel addresses where allocated';
rsTheCodeInjectionWasSuccessfull = 'The code injection was successfull';
rsYouCanOnlyHaveOneEnableSection = 'You can only have one enable section';
rsYouCanOnlyHaveOneDisableSection = 'You can only have one disable section';
rsYouHavnTSpecifiedAEnableSection = 'You havn''t specified a enable section';
rsYouHavnTSpecifiedADisableSection = 'You havn''t specified a disable section';
rsWrongSyntaxSHAREDALLOCNameSize = 'Wrong syntax. SHAREDALLOC(name,size)';
type
TregisteredAutoAssemblerCommands = TFPGList<TRegisteredAutoAssemblerCommand>;
var
registeredAutoAssemblerCommands: TregisteredAutoAssemblerCommands;
AutoAssemblerPrologues: array of TAutoAssemblerPrologue;
function registerAutoAssemblerPrologue(m: TAutoAssemblerPrologue): integer;
var i: integer;
begin
for i:=0 to length(AutoAssemblerPrologues)-1 do
begin
if assigned(AutoAssemblerPrologues[i])=false then
begin
AutoAssemblerPrologues[i]:=m;
result:=i;
exit;
end
end;
result:=length(AutoAssemblerPrologues);
setlength(AutoAssemblerPrologues, result+1);
AutoAssemblerPrologues[result]:=m;
end;
procedure unregisterAutoAssemblerPrologue(id: integer);
begin
if id<length(AutoAssemblerPrologues) then
AutoAssemblerPrologues[id]:=nil;
end;
procedure RegisterAutoAssemblerCommand(command: string; callback: TAutoAssemblerCallback);
var i: integer;
c:TRegisteredAutoAssemblerCommand;
begin
if registeredAutoAssemblerCommands=nil then
registeredAutoAssemblerCommands:=TregisteredAutoAssemblerCommands.Create;
command:=uppercase(command);
for i:=0 to registeredAutoAssemblerCommands.Count-1 do
if registeredAutoAssemblerCommands[i].command=command then
begin
//update
CleanupLuaCall(tmethod(registeredAutoAssemblerCommands[i].callback));
registeredAutoAssemblerCommands[i].callback:=nil;//TAutoAssemblerCallback(callback);
exit;
end;
c:=TRegisteredAutoAssemblerCommand.create;
c.command:=command;
c.callback:=callback;
registeredAutoAssemblerCommands.Add(c);
aa_AddExtraCommand(pchar(command));
end;
procedure UnregisterAutoAssemblerCommand(command: string);
var i,j: integer;
c:TRegisteredAutoAssemblerCommand;
begin
command:=uppercase(command);
i:=0;
while i<registeredAutoAssemblerCommands.count do
begin
if registeredAutoAssemblerCommands[i].command=command then
begin
c:=registeredAutoAssemblerCommands[i];
CleanupLuaCall(tmethod(c.callback));
registeredAutoAssemblerCommands.Delete(i);
c.free;
end
else
inc(i);
end;
aa_RemoveExtraCommand(pchar(command));
end;
procedure tokenize(input: string; tokens: tstringlist);
var i: integer;
a: integer;
begin
tokens.clear;
a:=-1;
for i:=1 to length(input) do
begin
case input[i] of
'a'..'z','A'..'Z','0'..'9','.', '_','#','@': if a=-1 then a:=i;
else
begin
if a<>-1 then
tokens.AddObject(copy(input,a,i-a),tobject(a));
a:=-1;
end;
end;
end;
if a<>-1 then
tokens.AddObject(copy(input,a,length(input)),tobject(a));
end;
function tokencheck(input,token:string):boolean;
var tokens: tstringlist;
i: integer;
begin
tokens:=tstringlist.Create;
try
tokenize(input,tokens);
result:=false;
for i:=0 to tokens.Count-1 do
if tokens[i]=token then
begin
result:=true;
break;
end;
finally
tokens.free;
end;
end;
function replacetoken(input: string;token:string;replacewith:string):string;
var tokens: tstringlist;
i,j: integer;
begin
result:=input;
tokens:=tstringlist.Create;
try
tokenize(input,tokens);
for i:=0 to tokens.Count-1 do
if tokens[i]=token then
begin
j:=integer(tokens.Objects[i]);
result:=copy(input,1,j-1)+replacewith+copy(input,j+length(token),length(input));
end;
finally
tokens.free;
end;
end;
procedure tokenizeStruct(input: string; tokens: tstringlist);
//a version of tokenize using strutils to split up the strings. (I don't want to replace it yet since it is slightly different, probably better, but let's be safe for now till it's fully tested)
var delims: TSysCharSet;
i: integer;
begin
delims:=[' '];
tokens.clear;
for i:=1 to WordCount(input, delims) do
tokens.add(ExtractWord(i, input, delims));
end;
procedure replaceStructWithDefines(code: Tstrings; linenr: integer);
{
parses the structure starting at the given line number.
removes the structure definition from the code
writes a define(xxxx,xxxxx) inplace starting from the linenumber
precondition: linenr is valid and code[linenr] is indeed a STRUCT name line
Structure format:
struct name
db ? db ? db ? db ?
db ? ? ?
dw ?
dd ?
dq ?
resb 4 resb 4
resw 4
resd 2
resq 1
elementname1:
db ?
resw 1
dw ?
elementname2: dw ?
endstruct
Res is an alternate to the usual "d* ?" but is specifically for no fill (Res stands for reserve)
Usage res* # where # is the number of copies. This is better suited for strings which can not be defined with db ?
when done the name.elementname1 and just elementname1 will be defined at the spot the structure was placed. Subsequent structure definitions can override these defines. Elements may NOT have reserved words as they will get replaced. (like assembler commands)
}
var
currentOffset: integer;
structname: string;
elementname: string;
i,j,k: integer;
tokens: Tstringlist;
elements: tstringlist;
starttoken: integer;
bytesize: integer;
endfound: boolean;
lastlinenr: integer;
procedure structError(reason: string='');
var error: string;
begin
error:='Error in the structure definition of '+structname+' at line '+inttostr(lastlinenr+1);
if reason<>'' then
error:=error+' :'+reason
else
error:=error+'.';
raise exception.create(error);
end;
begin
lastlinenr:=linenr;
endfound:=false;
structname:=trim(copy(code[linenr], 7, length(code[linenr])));
currentOffset:=0;
tokens:=tstringlist.create;
elements:=tstringlist.create;
for i:=linenr+1 to code.count-1 do
begin
lastlinenr:=i;
tokenizeStruct(code[i], tokens);
j:=0;
if tokens.count>0 then
begin
//first check if it's a label definition
if tokens[0][length(tokens[0])]=':' then
begin
elementname:=copy(tokens[0], 1, Length(tokens[0])-1);
if GetOpcodesIndex(elementname)<>-1 then
structError(elementname+' is a reserved word');
elements.AddObject(elementname, tobject(currentOffset));
j:=1;
end;
//then check if it's the end of the struct
if (uppercase(tokens[0])='ENDSTRUCT') or (uppercase(tokens[0])='ENDS') then
begin
endfound:=true;
break; //all done
end;
end;
//if it's neither a label or structure end then it's a size defining token
while j < tokens.count do
begin
tokens[j]:=uppercase(tokens[j]);
case tokens[j][1] of
'R':
begin
//could be res*
if (length(tokens[j])=4) and (copy(tokens[j],1,3)='RES') then
begin
case tokens[j][4] of
'B': bytesize:=1;
'W': bytesize:=2;
'D': bytesize:=4;
'Q': bytesize:=8;
else
StructError;
end;
//now get the count
inc(j);
if j>=tokens.count then
structError;
try
inc(currentOffset, bytesize*StrToInt(tokens[j]));
except
structerror;
end;
end else structerror;
end;
'D':
begin
//could be d* ?
if length(tokens[j])=2 then
begin
case tokens[j][2] of
'B': bytesize:=1;
'W': bytesize:=2;
'D': bytesize:=4;
'Q': bytesize:=8;
else
StructError;
end;
inc(j);
if j>=tokens.count then
structError;
inc(currentOffset, bytesize);
//check if there are more ?'s after this (in case of dw ? ? ?)
while j<tokens.count-1 do
begin
if tokens[j+1]='?' then //check from the spot in front
begin
inc(currentOffset, bytesize);
inc(j);
end
else
break; //nope
end;
end else structerror;
end;
else
structError('No idea what '+tokens[j]+' is'); //we already dealth with labels, so this is wrong
end;
inc(j); //next token
end;
end;
if endfound=false then
structerror('No end found');
//the elements have been filled in, delete the structure (between linenr and lastlinenr) and inject define(element,offset) and define(structname.element,offset)
for i:=lastlinenr downto linenr do
code.Delete(i);
for i:=0 to elements.count-1 do
begin
code.Insert(linenr,'define('+elements[i]+','+inttohex(ptruint(elements.objects[i]),1)+')');
code.Insert(linenr,'define('+structname+'.'+elements[i]+','+inttohex(ptruint(elements.objects[i]),1)+')');
end;
code.insert(linenr, 'define('+structname+'_size,'+inttohex(currentOffset,1)+')');
tokens.Free;
elements.free;
end;
procedure removecomments(code: tstrings);
var i,j: integer;
currentline: string;
instring: boolean;
incomment: boolean;
begin
//remove comments
instring:=false;
incomment:=false;
for i:=0 to code.count-1 do
begin
currentline:=code[i];
for j:=1 to length(currentline) do
begin
if incomment then
begin
//inside a comment, remove everything till a } is encountered
if ((currentline[j]='}') and (processhandler.SystemArchitecture<>archArm)) or
((currentline[j]='*') and (j<length(currentline)) and (currentline[j+1]='/')) then
begin
incomment:=false; //and continue parsing the code...
if ((currentline[j]='*') and (j<length(currentline)) and (currentline[j+1]='/')) then
currentline[j+1]:=' ';
end;
currentline[j]:=' ';
end
else
begin
if currentline[j]='''' then instring:=not instring;
if currentline[j]=#9 then currentline[j]:=' '; //tabs are basicly comments
if not instring then
begin
//not inside a string, so comment markers need to be dealt with
if (currentline[j]='/') and (j<length(currentline)) and (currentline[j+1]='/') then //- comment (only the rest of the line)
begin
//cut off till the end of the line (and might as well jump out now)
currentline:=copy(currentline,1,j-1);
break;
end;
if ((currentline[j]='{') and (processhandler.SystemArchitecture<>archArm)) or
((currentline[j]='/') and (j<length(currentline)) and (currentline[j+1]='*')) then
begin
incomment:=true;
currentline[j]:=' '; //replace from here till the first } with spaces, this goes on for multiple lines
end;
end;
end;
end;
code[i]:=trim(currentline);
end;
end;
procedure unlabeledlabels(code: tstrings);
var i,j: integer;
lastseenlabel: integer;
labels: array of string; //sorted in order of definition
currentline: string;
begin
//unlabeled label support
//For those reading the source, PLEASE , try not to code scripts like that
//the scripts you make look like crap, and are hard to read. (like using goto in a c app)
//this is just to make one guy happy
setlength(labels,0);
i:=0;
while i<code.count do
begin
currentline:=code[i];
if length(currentline)>1 then
begin
if currentline='@@:' then
begin
currentline:='RandomLabel'+chr(ord('A')+random(26))+
chr(ord('A')+random(26))+
chr(ord('A')+random(26))+
chr(ord('A')+random(26))+
chr(ord('A')+random(26))+
chr(ord('A')+random(26))+
chr(ord('A')+random(26))+
chr(ord('A')+random(26))+
chr(ord('A')+random(26))+
':';
code[i]:=currentline;
code.Insert(0,'label('+copy(currentline,1,length(currentline)-1)+')');
inc(i);
setlength(labels,length(labels)+1);
labels[length(labels)-1]:=copy(currentline,1,length(currentline)-1);
end else
if currentline[length(currentline)]=':' then
begin
setlength(labels,length(labels)+1);
labels[length(labels)-1]:=copy(currentline,1,length(currentline)-1);
end;
end;
inc(i);
end;
//all label definitions have been filled in
//now change @F (forward) and @B (back) to the labels in front and behind
lastseenlabel:=-1;
for i:=0 to code.Count-1 do
begin
currentline:=code[i];
if length(currentline)>1 then
begin
if currentline[length(currentline)]=':' then
begin
//find this in the array
currentline:=copy(currentline,1,length(currentline)-1);
for j:=(lastseenlabel+1) to length(labels)-1 do //lastseenlabel+1 since it is ordered in definition
begin
if uppercase(currentline)=uppercase(labels[j]) then
begin
lastseenlabel:=j;
break;
end;
end;
currentline:=currentline+':';
//lastseenlabel is now updated to the current pos
end else
if pos('@f',lowercase(currentline))>0 then //forward
begin
//forward label, so labels[lastseenlabel+1]
if lastseenlabel+1 >= length(labels) then
raise exception.Create(rsForwardJumpWithNoLabelDefined);
currentline:=replacetoken(currentline,'@f',labels[lastseenlabel+1]);
currentline:=replacetoken(currentline,'@F',labels[lastseenlabel+1]);
end else
if pos('@b',lowercase(currentline))>0 then //back
begin
//forward label, so labels[lastseenlabel]
if lastseenlabel=-1 then
raise exception.Create(rsThereIsCodeDefinedWithoutSpecifyingTheAddressItBel);
currentline:=replacetoken(currentline,'@b',labels[lastseenlabel]);
currentline:=replacetoken(currentline,'@B',labels[lastseenlabel]);
end;
end;
code[i]:=currentline;
end;
end;
procedure aobscans(code: tstrings; syntaxcheckonly: boolean);
//Replaces all AOBSCAN lines with DEFINE(NAME,ADDRESS)
type
TAOBEntry = record
name: string;
aobstring: string;
linenumber: integer;
end;
PAOBEntry=^TAOBEntry;
var i,j,k, m: integer;
aobscanmodules: array of record
name: string;
entries: array of TAOBEntry;
minaddress, maxaddress: ptruint;
memscan: TMemScan;
end;
a,b,c,d: integer;
currentline: string;
s1,s2, s3: string;
testptr: ptruint;
cpucount: integer;
threads: integer;
mi: TModuleInfo;
aobstrings: string;
error: boolean;
errorstring: string;
aob1, aob2: dword;
procedure finished(f: integer);
//cleanup a memscan and fill in the results
var i,j: integer;
results: TAddresses;
aoblist: string;
begin
setlength(results,0);
if length(aobscanmodules[f].entries)=1 then
begin
//if only 1 entry a normal aobscan was done, so use GetOnlyOneResult instead
if aobscanmodules[f].memscan.GetOnlyOneResult(testptr) then
begin
setlength(results,1);
results[0]:=testptr;
end;
end
else
aobscanmodules[f].memscan.GetOnlyOneResults(results);
if length(results)=length(aobscanmodules[f].entries) then
begin
for i:=0 to length(aobscanmodules[f].entries)-1 do
begin
if results[i]=0 then
begin
error:=true;
errorstring:='The array of byte named '+aobscanmodules[f].entries[i].name+' could not be found';
end
else
code[aobscanmodules[f].entries[i].linenumber]:='DEFINE('+aobscanmodules[f].entries[i].name+', '+inttohex(results[i],8)+')';
end;
end
else
begin
error:=true;
aoblist:='';
for i:=0 to length(aobscanmodules[f].entries)-1 do
aoblist:=aoblist+aobscanmodules[f].entries[i].name+' ';
errorstring:='Error while scanning for AOB''s : '+aoblist+#13#10#13#10+'Error: '+aobscanmodules[f].memscan.GetErrorString;
end;
aobscanmodules[f].memscan.Free;
aobscanmodules[f].memscan:=nil;
dec(threads);
end;
begin
error:=false;
setlength(aobscanmodules,0);
cpucount:=GetCPUCount;
threads:=0;
for i:=0 to code.Count-1 do
begin
//AOBSCAN(variable,aobtring) (works like define)
currentline:=code[i];
if uppercase(copy(currentline,1,8))='AOBSCAN(' then
begin
//convert this line from AOBSCAN(varname,bytestring) to DEFINE(varname,address)
a:=pos('(',currentline);
b:=pos(',',currentline);
c:=pos(')',currentline);
if (a>0) and (b>0) and (c>0) then
begin
s1:=trim(copy(currentline,a+1,b-a-1));
s2:=trim(copy(currentline,b+1,c-b-1));
//s1=varname
//s2=AOBstring
testPtr:=0;
if (not syntaxcheckonly) then
begin
//find the '' module
m:=-1;
for j:=0 to length(aobscanmodules)-1 do
if aobscanmodules[j].name='' then
begin
m:=j;
break;
end;
if m=-1 then
begin
setlength(aobscanmodules, length(aobscanmodules)+1);
m:=length(aobscanmodules)-1;
aobscanmodules[m].name:='';
aobscanmodules[m].minaddress:=0;
{$ifdef cpu64}
if processhandler.is64Bit then
aobscanmodules[m].maxaddress:=qword($7fffffffffffffff)
else
{$endif}
begin
if Is64bitOS then
aobscanmodules[m].maxaddress:=$ffffffff
else
aobscanmodules[m].maxaddress:=$7fffffff;
end;
aobscanmodules[m].maxaddress:=$ffffffffffffffff;
setlength(aobscanmodules[m].entries,0); //shouldn't be needed, but do it anyhow
end;
j:=length(aobscanmodules[m].entries);
setlength(aobscanmodules[m].entries, j+1);
aobscanmodules[m].entries[j].name:=s1;
aobscanmodules[m].entries[j].aobstring:=s2;
aobscanmodules[m].entries[j].linenumber:=i;
end
else
code[i]:='DEFINE('+s1+', 00000000)';
end else raise exception.Create(rsWrongSyntaxAOBSCANName11223355);
end;
if uppercase(copy(currentline,1,14))='AOBSCANMODULE(' then //AOBSCANMODULE(varname, modulename, bytestring)
begin
a:=pos('(',currentline);
b:=pos(',',currentline);
c:=PosEx(',',currentline,b+1);
d:=pos(')',currentline);
if d<=a then raise exception.create(rsWrongSyntaxAOBSCANMODULEName11223355);
if (a>0) and (b>0) and (c>0) then
begin
s1:=trim(copy(currentline,a+1,b-a-1));
s2:=uppercase(trim(copy(currentline,b+1,c-b-1)));
s3:=trim(copy(currentline,c+1,d-c-1));
//s1=varname
//s2=MODULE
//s3=aob
testPtr:=0;
if (not syntaxcheckonly) then
begin
//find the s2 module
m:=-1;
for j:=0 to length(aobscanmodules)-1 do
if aobscanmodules[j].name=s2 then
begin
m:=j;
break;
end;
if m=-1 then
begin
setlength(aobscanmodules, length(aobscanmodules)+1);
m:=length(aobscanmodules)-1;
aobscanmodules[m].name:=s2;
if symhandler.getmodulebyname(s2, mi) then
begin
aobscanmodules[m].minaddress:=mi.baseaddress;
aobscanmodules[m].maxaddress:=mi.baseaddress+mi.basesize;
end
else
raise exception.create('module not found:'+s2);
setlength(aobscanmodules[m].entries,0);
end;
j:=length(aobscanmodules[m].entries);
setlength(aobscanmodules[m].entries, j+1);
aobscanmodules[m].entries[j].name:=s1;
aobscanmodules[m].entries[j].aobstring:=s3;
aobscanmodules[m].entries[j].linenumber:=i;
end
else
code[i]:='DEFINE('+s1+', 00000000)';
end else raise exception.Create(rsWrongSyntaxAOBSCANMODULEName11223355);
end;
end;
//do simultaneous scans for the selected modules
for i:=0 to length(aobscanmodules)-1 do
begin
//wait for one to finish
j:=0;
while threads>=cpucount do
begin
if (aobscanmodules[j].memscan<>nil) and (aobscanmodules[j].memscan.waittilldone(50)) then
begin
finished(j);
break;
end;
j:=(j+1) mod i;
end;
inc(threads);
aobscanmodules[i].memscan:=TMemScan.create(nil);
aobscanmodules[i].memscan.OnlyOne:=true;
aobstrings:='';
for j:=0 to length(aobscanmodules[i].entries)-1 do
aobstrings:=aobstrings+'('+aobscanmodules[i].entries[j].aobstring+')';
if length(aobscanmodules[i].entries)=1 then //bytearrays is slightly slower, so only use it if more than one entry is to be scanned
aobscanmodules[i].memscan.firstscan(soExactValue, vtByteArray, rtRounded, aobscanmodules[i].entries[0].aobstring, '', aobscanmodules[i].minaddress, aobscanmodules[i].maxaddress, true, false, false, false, fsmNotAligned)
else
aobscanmodules[i].memscan.firstscan(soExactValue, vtByteArrays, rtRounded, aobstrings, '', aobscanmodules[i].minaddress, aobscanmodules[i].maxaddress, true, false, false, false, fsmNotAligned);
end;
//now wait till all are finished
for i:=0 to length(aobscanmodules)-1 do
if aobscanmodules[i].memscan<>nil then
begin
aobscanmodules[i].memscan.waittilldone;
finished(i);
end;
if error then raise exception.create(errorstring);
end;
procedure luacode(code: TStrings; syntaxcheckonly: boolean);
{
Find and execute the LUA parts:
function (syntaxcheck)
<code>
end
If the functions return a string, substitute the code with the given string
}
var
i,j,k: integer;
s: tstringlist;
stack: integer;
str: string;
error: boolean;
begin
i:=0;
while i<code.Count do
begin
//search for {$LUA}
str:=uppercase(TrimRight(code[i]));
if str='{$LUA}' then
begin
//search for {$ASM} or the end
j:=i+1;
while j<=code.count do
begin
if (j=code.count) or (uppercase(TrimRight(code[j]))='{$ASM}') then
begin
s:=TStringList.create;
s.add('local syntaxcheck=...');
code[i]:='';
for k:=i+1 to j-1 do
begin
s.Add(code[k]);
code[k]:=''; //empty
end;
if j<>code.count then
code[j]:='';
LUACS.Enter;
try
stack:=lua_Gettop(luavm);
error:=false;
luaL_loadstring(luavm, pchar(s.text));
if lua_isfunction(luavm, -1) then
begin
lua_pushboolean(luavm, syntaxcheckonly);
if lua.lua_pcall(luavm, 1, 1, 0)=0 then
begin
if lua_isstring(luavm,-1) then
begin
str:=Lua_ToString(luavm, -1);
s:=tstringlist.create;
s.text:=str;
for k:=0 to s.count-1 do
code.Insert(i+k, s[k]);
s.free;
end;
end
else
error:=true;
end
else
error:=true;
if error then
begin
if lua_isstring(luavm, -1) then
raise exception.create('Lua error in the script at line '+inttostr(integer(code.Objects[i]))+':'+lua_tostring(luavm, -1))
else
raise exception.create('Lua error in the script at line '+inttostr(integer(code.Objects[i])));
end;
finally
lua_settop(Luavm, stack);
LUACS.Leave;
end;
break;
end;
inc(j);
end;
end
else
inc(i);
end;
//one more time getting rid of {$ASM} lines that have been added while they shouldn't be required
for i:=0 to code.count-1 do
if uppercase(TrimRight(code[i]))='{$ASM}' then
code[i]:='';
end;
function autoassemble2(code: tstrings;popupmessages: boolean;syntaxcheckonly:boolean; targetself: boolean ;var ceallocarray:TCEAllocArray; registeredsymbols: tstringlist=nil):boolean;
{
registeredsymbols is a stringlist that is initialized by the caller as case insensitive and no duplicates
}
type tassembled=record