45 lines
1.5 KiB
Python
45 lines
1.5 KiB
Python
import struct
|
|
|
|
SHT_SYMTAB = 2
|
|
SHT_DYNSYM = 11
|
|
|
|
|
|
def _sections(buf):
|
|
if buf[:4] != b"\x7fELF" or buf[4] != 2:
|
|
raise ValueError("not an ELF64 file")
|
|
e_shoff, = struct.unpack_from("<Q", buf, 0x28)
|
|
e_shentsize, e_shnum, _ = struct.unpack_from("<HHH", buf, 0x3A)
|
|
secs = []
|
|
for i in range(e_shnum):
|
|
off = e_shoff + i * e_shentsize
|
|
name, typ, flags, addr, offset, size, link, info, align, entsize = \
|
|
struct.unpack_from("<IIQQQQIIQQ", buf, off)
|
|
secs.append({"type": typ, "offset": offset, "size": size,
|
|
"link": link, "entsize": entsize})
|
|
return secs
|
|
|
|
|
|
def symbol_offsets(path, names):
|
|
want = set(names)
|
|
with open(path, "rb") as fh:
|
|
buf = fh.read()
|
|
secs = _sections(buf)
|
|
found = {}
|
|
for sec in secs:
|
|
if sec["type"] not in (SHT_SYMTAB, SHT_DYNSYM) or not sec["entsize"]:
|
|
continue
|
|
strtab = secs[sec["link"]]
|
|
base, sbase = sec["offset"], strtab["offset"]
|
|
for i in range(sec["size"] // sec["entsize"]):
|
|
e = base + i * sec["entsize"]
|
|
st_name, st_info, st_other, st_shndx, st_value, st_size = \
|
|
struct.unpack_from("<IBBHQQ", buf, e)
|
|
if not st_name:
|
|
continue
|
|
end = buf.index(b"\x00", sbase + st_name)
|
|
nm = buf[sbase + st_name:end].decode("latin1")
|
|
if nm in want and st_value:
|
|
if nm not in found or st_value < found[nm]:
|
|
found[nm] = st_value
|
|
return {n: found.get(n) for n in names}
|