-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathprocess_asm.py
1500 lines (1335 loc) · 51.9 KB
/
process_asm.py
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
import hashlib
import json
from optparse import OptionParser
import os
import pathlib
import re
import time
parser = OptionParser()
parser.add_option("--show-hex-prefix", dest="show_hex_prefix",
help="show '0' prefix and 'h' suffix for hex numbers (yes, no)",
default="yes")
parser.add_option("--write-proc-dict", dest="write_proc_dict",
help="Write procedures dictionary to json file (yes, no)",
default="no")
parser.add_option("--force", dest="force",
help="Always do full asm conversion (yes, no)",
default="no")
(options, args) = parser.parse_args()
options.show_hex_prefix = (options.show_hex_prefix != 'no')
options.write_proc_dict = (options.write_proc_dict != 'no')
options.force = (options.force != 'no')
entry_point_regexp = re.compile('Entry\s+Point:\s+(?P<entryPoint>[\dABCDEF]+)')
export_regexp = re.compile('\*\s+Export:\s+(?P<export>\S+),\s+(?P<ordinal>\d+)')
num_regexp = re.compile('(?P<prefix>[^\w\?\.@$])(?P<number>[\dABCDEF]+)')
jump_cmds = 'jmp|je|jne|jb|jnb|jbe|jl|jnl|jle|jg|ja|js|jns|jp|jnp|jo|jno'
cmds = 'call|loop|loopnz|' + jump_cmds
direct_transfer = '^(?P<cmd>{})\s+(?P<target>[\dABCDEF]+)\W*$'
direct_transfer_regexp = re.compile(direct_transfer.format(cmds))
jump_regexp = re.compile(direct_transfer.format(jump_cmds))
external_ref_regexp = re.compile('(?P<extern>(?P<library>\w+)\.(?P<name>\S+))')
byteReg = 'al|cl|dl'
wordReg = 'ax|cx|dx'
dwordReg = 'edi|esi|eax|ecx|edx'
access = '\[.*\]'
regLeft = '((?P<byteLeft>{})|(?P<wordLeft>{})|(?P<dwordLeft>{}))'.format(byteReg, wordReg, dwordReg)
regRight = '((?P<byteRight>{})|(?P<wordRight>{})|(?P<dwordRight>{}))'.format(byteReg, wordReg, dwordReg)
accessLeft = '(?P<accessLeft>{})'.format(access)
accessRight = '(?P<accessRight>{})'.format(access)
byte_memory_access_regexp = re.compile(
r'^(mov|cmp|add|sub|imul|or|and|xor|test)\s+'
r'(({},\s+{})|({},\s+{}))$'.format(
regLeft, accessRight, accessLeft, regRight))
noFWAIT = {
'fstsw' : 'fnstsw',
}
fwait_regexp = re.compile('^(?P<cmd>{})'.format("|".join(noFWAIT.keys())))
imul_3_regexp = re.compile('^imul\s+(\w+,\s+){2}(?P<imm>[\dABCDEF]+)')
def toHex(n):
return format(n, '08X')
def fromHex(h):
return int(h, 16)
class ImageWriter:
def __init__(self, imageMap):
self._imageMap = imageMap
self._lines = []
self._printedComments = set()
self._items = []
def imageMap(self):
return self._imageMap
def label(self, addr):
for item in self._items:
if hasattr(item, 'labelAt') and item.labelAt(addr) != None:
return item.labelAt(addr)
return self._imageMap.label(addr)
def write(self, item):
if isinstance(item, str):
self._lines.append(item)
else:
self._items.append(item)
if not item.startAddress() in self._printedComments:
comments = self._imageMap.commentsToString(item.startAddress())
self._lines.append(comments)
self._printedComments.add(item.startAddress())
item.write(self)
self._items.pop()
def toString(self):
return ''.join(self._lines)
class CodeItem:
def adjustInstructions(self, imageMap):
pass
class Procedure(CodeItem):
def __init__(self, items, isUsed):
self._firstItem = items[0]
self._lastItem = items[-1]
self._items = {item.startAddress(): item for item in items}
self._isUsed = isUsed
def label(self):
return self._firstItem.label()
def startAddress(self):
return self._firstItem.startAddress()
def endAddress(self):
return self._lastItem.endAddress()
def adjustInstructions(self, imageMap):
for item in self._items.values():
if isinstance(item, CodeItem):
item.adjustInstructions(imageMap)
def labelAt(self, addr):
item = self._items.get(addr)
if item is not None:
return item.label()
return None
def _writeItems(self, writer):
for addr in sorted(self._items.keys()):
item = self._items[addr]
writer.write(item)
def write(self, writer):
if not self._isUsed:
self._writeItems(writer)
return
self._firstItem.hideLabel()
writer.write("{} PROC\n".format(self.label()))
self._writeItems(writer)
writer.write("{} ENDP\n".format(self.label()))
class ImportReference:
underscore_libs = {'python15'}
def __init__(self, addr, library, name):
is_underscore = library.lower() in self.underscore_libs
self._addr = addr
self._name = name
if is_underscore:
self._mangled_name = "_{}".format(name)
else:
self._mangled_name = name
def showLabel(self, name):
pass
def label(self):
return "__imp_{}".format(self._mangled_name)
def startAddress(self):
return self._addr
def endAddress(self):
return self._addr + self.length()
def length(self):
return 4
def demangleStdcall(self):
match = re.search('^_(?P<name>\w+)@(?P<size>\d+)$', self._name)
if match:
name = match.group('name')
size = int(match.group('size'))
return (name, size)
return (None, None)
def write(self, writer):
imageMap = writer.imageMap()
label = "g{}".format(toHex(self._addr))
data = "0{}h".format(imageMap.bytes(self._addr, self.endAddress()))
writer.write("{} dd {}; {}\n".format(label, data, self._name))
class DataItem:
_addr = None
_length = 0
def __init__(self, startAddr, endAddr):
self._addr = startAddr
self._length = endAddr - startAddr
self._ptrs = {}
self._messages = {}
def showLabel(self, name):
pass
def label(self):
return "g{}".format(toHex(self._addr))
def startAddress(self):
return self._addr
def endAddress(self):
return self._addr + self._length
def length(self):
return self._length
def applyRelocs(self, imageMap):
reloc = imageMap.relocations()
addr = self.startAddress()
while addr < self.endAddress():
if addr in reloc:
targetAddr = reloc[addr]
length = 4
addrStr = reverseBytes(imageMap.bytes(addr, addr + length))
if (
fromHex(addrStr) != targetAddr or
(addr + length > self.endAddress())
):
self._messages[addr] = "Failed to apply reloc."
else:
self._ptrs[addr] = targetAddr
imageMap.resolveAddress(targetAddr)
else:
length = 1
addr += length
def canRead32Bit(self, imageMap, addr):
length = 4
if addr + length > self.endAddress():
return False
for i in range(addr, addr + length):
if i in self._ptrs:
return False
if imageMap.isUninitialisedByte(i):
return False
return True
def zeroFilledDataLen(self, imageMap, startAddr):
curAddr = startAddr
while curAddr < self.endAddress():
if imageMap.bytes(curAddr, curAddr + 1) != "00":
break
if curAddr in self._ptrs:
break
curAddr += 1
return (curAddr - startAddr)
def uninitialisedDataLen(self, imageMap, startAddr):
curAddr = startAddr
while curAddr < self.endAddress():
if not imageMap.isUninitialisedByte(curAddr):
break
curAddr += 1
return (curAddr - startAddr)
def write(self, writer):
imageMap = writer.imageMap()
addr = self.startAddress()
while addr < self.endAddress():
error = ""
if addr in self._messages:
error = "; {}".format(self._messages[addr])
label = " " * 9
if addr == self.startAddress():
label = self.label()
if addr in self._ptrs:
length = 4
dataSize = "dd"
data = writer.label(self._ptrs[addr])
elif self.uninitialisedDataLen(imageMap, addr) > 0:
length = self.uninitialisedDataLen(imageMap, addr)
if length < 4:
dataSize = "db"
numElements = length
else:
dataSize = "dd"
numElements = length // 4
length = numElements * 4
data = "{} dup (?)".format(numElements)
elif self.zeroFilledDataLen(imageMap, addr) >= 8:
numElements = self.zeroFilledDataLen(imageMap, addr) // 4
length = numElements * 4
dataSize = "dd"
data = "{} dup (0)".format(numElements)
elif self.canRead32Bit(imageMap, addr):
length = 4
dataSize = "dd"
num = reverseBytes(imageMap.bytes(addr, addr + length))
data = "0{}h".format(num)
else:
length = 1
dataSize = "db"
data = "0{}h".format(imageMap.bytes(addr, addr + length))
writer.write("{} {} {}{}\n".format(label, dataSize, data, error))
addr += length
class AsmInstruction(CodeItem):
_addr = None
_instr = None
_length = 0
_showLabel = False
_name = None
_message = ""
def __init__(self, addr, instr, length):
self._addr = addr
self._instr = instr
self._length = length
self._pointers = []
self._parseJump()
def showLabel(self, name):
self._showLabel = True
self._name = name
def hideLabel(self):
self._showLabel = False
def hasLabel(self):
return self._showLabel
def label(self):
return self._name or "l{}".format(toHex(self._addr))
def startAddress(self):
return self._addr
def endAddress(self):
return self._addr + self._length
def length(self):
return self._length
def addHexPrefix(self, instr):
return num_regexp.sub('\g<prefix>0\g<number>h', instr)
def fixByteMemoryAccess(self):
match = re.search(byte_memory_access_regexp, self._instr)
if match:
access = match.group('accessLeft') or match.group('accessRight')
byte = match.group('byteLeft') or match.group('byteRight')
word = match.group('wordLeft') or match.group('wordRight')
dword = match.group('dwordLeft') or match.group('dwordRight')
size = None
size = 'byte ptr' if byte is not None else size
size = 'word ptr' if word is not None else size
size = 'dword ptr' if dword is not None else size
self._instr = self._instr.replace(access, '{} {}'.format(size, access))
def addNearJumpModifier(self, imageMap):
opcode = imageMap.bytes(self._addr, self._addr + 1)
if opcode == "E9":
self._instr = self._instr.replace('jmp', 'jmp near ptr')
def avoidEmittingOfFWAIT(self):
match = re.search(fwait_regexp, self._instr)
if match:
cmd = match.group('cmd')
self._instr = self._instr.replace(cmd, noFWAIT[cmd])
def fix_imul_3_args(self):
match = re.search(imul_3_regexp, self._instr)
if match:
immediate_str = match.group('imm')
immediate = fromHex(immediate_str)
if immediate >= 0x80000000 and immediate < 0xFFFFFF80:
# negative value
immediate = 0x100000000 - immediate
self._instr = self._instr.replace(
immediate_str, "-{}".format(toHex(immediate))
)
def applyRelocs(self, imageMap):
reloc = imageMap.relocations()
for a in range(self._addr, self._addr + self._length):
if a in reloc:
targetAddr = reloc[a]
if self._instr.find(toHex(targetAddr)) < 0:
self.printErrorMessage("Failed to apply reloc")
else:
imageMap.resolveAddress(targetAddr)
self._pointers.append(targetAddr)
def printErrorMessage(self, msg):
self._message += " {}.".format(msg)
def resolveDirectTransferAddress(self, imageMap):
match = re.search(direct_transfer_regexp, self._instr)
if match:
cmd = match.group('cmd')
targetAddr = fromHex(match.group('target'))
label = imageMap.label(targetAddr)
self._instr = "{} {}".format(cmd, label)
imageMap.resolveAddress(targetAddr)
def resolveExternalCalls(self, imageMap):
match = re.search(external_ref_regexp, self._instr)
if match:
externalSym = match.group('extern')
library = match.group('library')
symbolName = match.group('name')
(targetAddr, isDirectCall) = self.extractTargetAddress(imageMap)
if targetAddr is not None and not isDirectCall:
imageMap.addImportReference(targetAddr, library, symbolName)
self.printErrorMessage("[{}]".format(externalSym))
target = self.buildTargetOperand(targetAddr, isDirectCall)
self._instr = self._instr.replace(externalSym, target)
def buildTargetOperand(self, targetAddr, isDirectCall):
if targetAddr is None:
return 'external_symbol'
elif isDirectCall:
return toHex(targetAddr)
else:
return "[{}]".format(toHex(targetAddr))
def extractTargetAddress(self, imageMap):
bytes = imageMap.bytes(self.startAddress(), self.endAddress())
prefixes = [
'(?P<directCall>E8)', # call ptr
'FF15', # call [ptr]
'FF25', # jmp [ptr]
'A1', # mov eax, [ptr]
'8B0D', # mov ecx, [ptr]
'8B15', # mov edx, [ptr]
'3B05', # cmp eax, [ptr]
'3B0D', # cmp ecx, [ptr]
'3B15', # cmp edx, [ptr]
]
prefix = '|'.join(prefixes)
match = re.search('^({})(?P<addr>........)$'.format(prefix), bytes)
if match:
addr = reverseBytes(match.group('addr'))
if match.group('directCall'):
return (self.endAddress() + fromHex(addr), True)
else:
return (fromHex(addr), False)
return (None, False)
def replacePointers(self, writer):
instr = self._instr
for addr in self._pointers:
label = writer.label(addr)
if instr.find("[{}]".format(toHex(addr))) < 0:
label = "offset {}".format(label)
(instr, count) = re.subn(toHex(addr), label, instr, 1)
if count == 0:
self.printErrorMessage("Failed to replace number with label")
return instr
def isReturn(self):
return self._instr.startswith("ret")
def isUnconditionalJump(self):
return self._instr.startswith("jmp")
def isShortJump(self, imageMap):
if self.isUnconditionalJump():
opcode = imageMap.bytes(self._addr, self._addr + 1)
if opcode == "E9":
return False
return True
def _parseJump(self):
match = re.search(jump_regexp, self._instr)
if match:
self._isJump = True
self._jumpTarget = fromHex(match.group('target'))
else:
self._isJump = False
self._jumpTarget = None
def isJump(self):
return self._isJump or self.isUnconditionalJump()
def jumpTarget(self):
return self._jumpTarget
def write(self, writer):
label = "{}:".format(self.label())
if (not self._showLabel):
label = " "
msg = ""
if (self._message):
msg = "; {}".format(self._message.lstrip())
instr = self.replacePointers(writer)
if options.show_hex_prefix:
instr = self.addHexPrefix(instr)
writer.write("{} {}{}\n".format(label, instr, msg))
class CodeBlock(CodeItem):
def __init__(self, instructions):
self._instructions = instructions
def showLabel(self, name):
self._instructions[0].showLabel(name)
def hideLabel(self):
self._instructions[0].hideLabel()
def hasLabel(self):
return self._instructions[0].hasLabel()
def label(self):
return self._instructions[0].label()
def startAddress(self):
return self._instructions[0].startAddress()
def endAddress(self):
return self._instructions[-1].endAddress()
def length(self):
return self.endAddress() - self.startAddress()
def isReturn(self):
return self._instructions[-1].isReturn()
def isUnconditionalJump(self):
return self._instructions[-1].isUnconditionalJump()
def isShortJump(self, imageMap):
return self._instructions[-1].isShortJump(imageMap)
def jumpTarget(self):
return self._instructions[-1].jumpTarget()
def split(self, addr):
instructions1 = []
instructions2 = []
for instr in self._instructions:
if instr.startAddress() < addr:
instructions1.append(instr)
else:
instructions2.append(instr)
if (len(instructions2) == 0 or instructions2[0].startAddress() != addr):
return (None, None)
return (instructions1, instructions2)
def processData(self, imageMap):
for instr in self._instructions:
instr.resolveExternalCalls(imageMap)
instr.applyRelocs(imageMap)
instr.resolveDirectTransferAddress(imageMap)
def adjustInstructions(self, imageMap):
for instr in self._instructions:
instr.fixByteMemoryAccess()
instr.addNearJumpModifier(imageMap)
instr.avoidEmittingOfFWAIT()
instr.fix_imul_3_args()
def write(self, writer):
for instr in self._instructions:
writer.write(instr)
class ImageMap:
def __init__(self, mem):
self._mem = mem
self._items = {}
self._blocks = {}
self._importReferences = {}
self._exports = {}
self._unresolvedAddresses = set()
self._comments = {}
def itemsMap(self):
return self._items
def unresolvedAddresses(self):
return self._unresolvedAddresses
def relocations(self):
return self._mem.relocations()
def importReferences(self):
importReferences = []
for addr in sorted(self._items.keys()):
item = self._items[addr]
if (isinstance(item, ImportReference)):
importReferences.append(item)
return importReferences
def exports(self):
return self._exports
def label(self, addr):
if addr in self._items:
return self._items[addr].label()
return "l{}".format(toHex(addr))
def add(self, addr, item):
self._items[addr] = item
def addImportReference(self, addr, library, name):
self._importReferences[addr] = ImportReference(addr, library, name)
def addExport(self, addr, name):
self._exports[addr] = name
self.resolveAddress(addr)
def addComments(self, addr, comments):
if (len(comments) > 0):
self._comments[addr] = comments
def comments(self, addr):
return self._comments.get(addr)
def bytes(self, startAddress, endAddress):
return self._mem.bytes(startAddress, endAddress)
def isUninitialisedByte(self, address):
return self._mem.isUninitialisedByte(address)
def dasm(self, addr):
patterns = {
"55" : "push ebp",
"56" : "push esi",
"57" : "push edi",
"8BEC" : "mov ebp, esp",
"83EC4C" : "sub esp, 0000004C",
"81EC44040000" : "sub esp, 00000444",
}
length = 1
instruction = "invalid {}".format(self._mem.bytes(addr, addr + length))
for (pattern, instr) in patterns.items():
l = len(pattern) // 2
bytes = self._mem.bytes(addr, addr + l)
if (bytes == pattern):
instruction = instr
length = l
break
return AsmInstruction(addr, instruction, length)
def removeOverlappedItems(self):
prevItem = None
for addr in sorted(self._items.keys()):
item = self._items[addr]
if (prevItem is not None and prevItem.endAddress() > item.startAddress()):
self._items[prevItem.startAddress()] = DataItem(prevItem.startAddress(), item.startAddress())
prevItem = item
def isInvalidInstruction(self, item, relAddr):
relLength = 4
relStart = relAddr
relEnd = relAddr + relLength
return relAddr < item.startAddress() or relEnd > item.endAddress()
def removeInvalidInstructions(self):
invalidInstructions = set()
for addr in sorted(self._items.keys()):
item = self._items[addr]
if isinstance(item, AsmInstruction):
for relAddr in range(item.startAddress(), item.endAddress()):
if (relAddr in self.relocations()):
if self.isInvalidInstruction(item, relAddr):
invalidInstructions.add(item)
relLength = 4
for relAddr in sorted(self.relocations().keys()):
for addr in range(relAddr, relAddr + relLength):
item = self._items.get(addr)
if isinstance(item, AsmInstruction):
if self.isInvalidInstruction(item, relAddr):
invalidInstructions.add(item)
for item in invalidInstructions:
startAddr = item.startAddress()
endAddr = item.endAddress()
self._items[startAddr] = DataItem(startAddr, endAddr)
def endAddressOfAdjacentDataItems(self, addr):
item = self._items[addr]
if not isinstance(item, DataItem):
return item.startAddress()
nextItem = self._items.get(item.endAddress())
while isinstance(nextItem, DataItem):
item = nextItem
nextItem = self._items.get(item.endAddress())
return item.endAddress()
def mergeAdjacentDataItems(self):
endAddr = None
for addr in sorted(self._items.keys()):
if endAddr is not None and addr < endAddr:
del self._items[addr]
else:
endAddr = self.endAddressOfAdjacentDataItems(addr)
if (endAddr > self._items[addr].endAddress()):
self._items[addr] = DataItem(addr, endAddr)
def mergeUserData(self, userMap):
self._items = self._mergeUserData(self._items, userMap)
def _mergeUserData(self, imageMap, userMap):
result = dict()
nextAddr = 0
for addr in sorted(set(list(imageMap) + list(userMap))):
item = imageMap.get(addr)
usrItem = userMap.get(addr)
if (usrItem != None):
result[addr] = usrItem
nextAddr = usrItem.endAddress()
elif (item != None and item.endAddress() > nextAddr):
if addr >= nextAddr:
result[addr] = item
elif isinstance(item, AsmInstruction):
while nextAddr < item.endAddress():
result[nextAddr] = self.dasm(nextAddr)
nextAddr = result[nextAddr].endAddress()
return result
def splitDataItems(self):
unresolvedAddresses = self._unresolvedAddresses
importReferences = self._importReferences.values()
addresses = (
list(self._items) +
list(unresolvedAddresses) +
list(self.relocations().values()) +
list(map(lambda ref : ref.startAddress(), importReferences)) +
list(map(lambda ref : ref.endAddress(), importReferences))
)
curItem = None
for addr in sorted(set(addresses)):
item = self._items.get(addr)
if (item != None):
curItem = item
elif isinstance(curItem, DataItem) and addr < curItem.endAddress():
itemLeft = DataItem(curItem.startAddress(), addr)
itemRight = DataItem(addr, curItem.endAddress())
self._items[curItem.startAddress()] = itemLeft
self._items[addr] = itemRight
curItem = itemRight
for addr in sorted(self._items.keys()):
item = self._items[addr]
importRef = self._importReferences.get(addr)
if (importRef is not None and
isinstance(item, DataItem) and
item.endAddress() == importRef.endAddress()
):
self._items[addr] = importRef
self._unresolvedAddresses -= set(self._items)
def resolveAddress(self, addr, name = None):
if addr in self._items or self.splitBlock(addr):
self._items[addr].showLabel(name)
else:
self._unresolvedAddresses.add(addr)
def splitBlock(self, addr):
block = self._blocks.get(addr)
if block is None:
return False
(instrs1, instrs2) = block.split(addr)
if instrs1 is None or instrs2 is None:
return False
del self._items[block.startAddress()]
self._createBlock(instrs1)
self._createBlock(instrs2)
return True
def _createBlock(self, instructions):
block = CodeBlock(instructions)
self._items[block.startAddress()] = block
for instr in instructions:
self._blocks[instr.startAddress()] = block
def makeBlocks(self):
blockInstructions = []
for addr in sorted(self._items.keys()):
item = self._items[addr]
if (
len(blockInstructions) > 0 and
(
not isinstance(item, AsmInstruction) or
item.hasLabel() or
blockInstructions[-1].endAddress() != item.startAddress() or
blockInstructions[-1].isReturn() or
blockInstructions[-1].isJump())
):
for blockInstruction in blockInstructions:
del self._items[blockInstruction.startAddress()]
self._createBlock(blockInstructions)
blockInstructions = []
if isinstance(item, AsmInstruction):
blockInstructions.append(item)
def _tryMakeProcedure(self, addr, shortJumpsFrom, isUsed):
items = []
item = self._items[addr]
if item.isUnconditionalJump() and item.jumpTarget() is None:
return
while True:
items.append(item)
if not isinstance(item, CodeBlock):
return
if (item.isReturn()):
break;
item = self._items[item.endAddress()]
# add jump tables for switch statements
item = self._items.get(item.endAddress())
while isinstance(item, DataItem):
items.append(item)
item = self._items[item.endAddress()]
procStartAddress = items[0].startAddress()
procEndAddress = items[-1].endAddress()
for item in items:
if isinstance(item, CodeBlock) and item.jumpTarget() is not None:
if (item.jumpTarget() <= procStartAddress):
return
if (item.jumpTarget() >= procEndAddress):
return
addrsFrom = shortJumpsFrom.get(item.startAddress())
if addrsFrom is not None:
for addrFrom in addrsFrom:
if (addrFrom < procStartAddress):
return
if (addrFrom >= procEndAddress):
return
for item in items:
del self._items[item.startAddress()]
self._items[addr] = Procedure(items, isUsed)
def _isProcStartPattern(self, addr):
return self.bytes(addr, addr + 3) == "558BEC"
def makeProcedures(self):
shortJumpsFrom = {}
for addr in sorted(self._items.keys()):
item = self._items[addr]
if isinstance(item, CodeBlock) and item.jumpTarget() is not None:
if item.isShortJump(self):
if not item.jumpTarget() in shortJumpsFrom:
shortJumpsFrom[item.jumpTarget()] = set()
shortJumpsFrom[item.jumpTarget()].add(addr)
for addr in sorted(self._items.keys()):
item = self._items.get(addr)
if isinstance(item, CodeBlock):
isUsed = item.hasLabel()
if isUsed or self._isProcStartPattern(addr):
self._tryMakeProcedure(addr, shortJumpsFrom, isUsed)
def commentsToString(self, addr):
lines = []
comments = self.comments(addr)
if comments is not None:
for comment in comments:
lines.append(";{}".format(comment))
return ''.join(lines)
def toString(self, endDataAddress):
writer = ImageWriter(self)
for addr in sorted(self._items.keys()):
if addr >= endDataAddress:
break
item = self._items[addr]
writer.write(item)
return writer.toString()
class MemoryArea:
_addr = None
_bytes = None
_reloc = None
def __init__(self, reloc):
self._reloc = reloc
def relocations(self):
return self._reloc
def addBytes(self, addr, bytes):
if self._addr is None:
self._addr = addr
self._bytes = list(bytes)
else:
expectedSize = 2 * (addr - self._addr)
delta = expectedSize - len(self._bytes)
if (delta < 0):
del self._bytes[delta:]
for i in range(delta):
self._bytes.append(None)
self._bytes.extend(bytes)
def bytes(self, startAddress, endAddress):
curAddr = startAddress
bytes = []
while curAddr < endAddress:
index = 2 * (curAddr - self._addr)
if index < len(self._bytes):
bytes.append(self._bytes[index] or "?")
bytes.append(self._bytes[index + 1] or "?")
else:
bytes.append("?")
bytes.append("?")
curAddr += 1
return "".join(bytes)
def isUninitialisedByte(self, address):
index = 2 * (address - self._addr)
if index >= len(self._bytes):
return True
return self._bytes[index] is None and self._bytes[index + 1] is None
class SrcSymbols:
def __init__(self):
self.varNames = {}
self.implementedVariables = set()
self.mangledNames = {}
self.implementedProcedures = set()
@staticmethod
def ensure_symbols_for_module(symbols_dict, module):
symbols = symbols_dict.get(module)
if symbols is None:
symbols = SrcSymbols()
symbols_dict[module] = symbols
return symbols
@staticmethod
def create_symbols_dict(
varNames, implementedVariables, mangledNames, implementedProcedures
):
symbols_dict = {}
for (module, addr), var_name in varNames.items():
symbols = SrcSymbols.ensure_symbols_for_module(symbols_dict, module)
symbols.varNames[addr] = var_name
for module, addr in implementedVariables:
symbols = SrcSymbols.ensure_symbols_for_module(symbols_dict, module)
symbols.implementedVariables.add(addr)
for (module, addr), mangled_name in mangledNames.items():
symbols = SrcSymbols.ensure_symbols_for_module(symbols_dict, module)
symbols.mangledNames[addr] = mangled_name
for module, addr in implementedProcedures:
symbols = SrcSymbols.ensure_symbols_for_module(symbols_dict, module)
symbols.implementedProcedures.add(addr)
return symbols_dict
class AsmFiles:
def __init__(self, dir):
self._dir = dir
@property
def input_asm(self):
return os.path.join(self._dir, "raw.txt")
@property
def input_data(self):
return os.path.join(self._dir, "data.txt")
@property
def reloc(self):
return os.path.join(self._dir, "reloc.txt")
@property
def module(self):
return os.path.join(self._dir, "module.txt")
@property
def intermediate_asm(self):
return os.path.join(self._dir, "code.str")
@property
def intermediate_export(self):
return os.path.join(self._dir, "export_cmd.str")
@property
def intermediate_hash(self):
return os.path.join(self._dir, "hash.str")
@property
def output_asm(self):
return os.path.join(self._dir, "native.asm")
@property
def output_procedures(self):
return os.path.join(self._dir, "procedures.inc")
@property
def output_variables(self):
return os.path.join(self._dir, "variables.inc")
@property
def output_export(self):
return os.path.join(self._dir, "export_cmd.txt")
@property
def uninitialised(self):
return os.path.join(self._dir, "uninitialised.asm")
@property
def export_include(self):
return os.path.join(self._dir, "export.inc")
@property
def import_include(self):
return os.path.join(self._dir, "import.inc")
@property
def stdcall_defs(self):
return os.path.join(self._dir, "stdcallDefs.cpp")
@property
def procedures_dict_json(self):
return os.path.join(self._dir, "procedures_dict.json")
@property
def asm_main(self):
return os.path.join(self._dir, "../asmMain.asm")
def extractEntryPoint(line):
match = re.search(entry_point_regexp, line)
if match:
return fromHex(match.group('entryPoint'))
return None