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
|
#!/usr/bin/env python3
"""List SVC #0x74 candidates and driver-ID property TLVs in signed ELFs.
The SVC scan is limited to halfword-aligned executable ELF segments but is
NOT a CFG disassembly: Thumb-2 second halfwords and data can collide. Validate
every hit in disassembly before attributing service slots. Property TLVs are
matched by the exact short header (length/type/name length/value length).
"""
from __future__ import annotations
import argparse
import struct
from pathlib import Path
SVC74 = b'\x74\xdf'
DRIVER_PROP = b'amd.dr.driverID\0'
DRIVER_HEADER = bytes((4 + len(DRIVER_PROP) + 4, 1, len(DRIVER_PROP), 4))
def load_spans(path: Path):
image = path.read_bytes()
if len(image) < 52 or image[:5] != b'\x7fELF\x01' or image[5] != 1:
return []
phoff = struct.unpack_from('<I', image, 28)[0]
entsize, count = struct.unpack_from('<HH', image, 42)
spans = []
for i in range(count):
pos = phoff + entsize * i
if pos + 32 > len(image):
break
kind, offset, va, _, filesz, _, flags, _ = struct.unpack_from('<8I', image, pos)
if kind != 1 or not flags & 1 or offset + filesz > len(image):
continue
spans.append((va, offset, image[offset:offset + filesz]))
return spans
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('paths', type=Path, nargs='+', help='ELF files or trees')
args = ap.parse_args()
paths = sorted({f for p in args.paths for f in ([p] if p.is_file() else p.rglob('*.elf'))})
for path in paths:
image = path.read_bytes()
for va, file_off, data in load_spans(path):
for i in range((-va) & 1, len(data) - 1, 2):
if data[i:i+2] == SVC74:
print(f'{path}\tsvc74-candidate va=0x{va+i:x}\tfile_off=0x{file_off+i:x}')
pos = image.find(DRIVER_PROP)
while pos >= 0:
end = pos + len(DRIVER_PROP)
if image[pos-4:pos] == DRIVER_HEADER and end + 4 <= len(image):
value = struct.unpack_from('<I', image, end)[0]
print(f'{path}\tdriver-id={value}\tfile_off=0x{pos:x}')
pos = image.find(DRIVER_PROP, pos + 1)
return 0
if __name__ == '__main__':
raise SystemExit(main())
|