2022-02-07 23:01:38 +00:00
|
|
|
#!/usr/bin/env python3
|
2011-02-04 07:25:12 +00:00
|
|
|
#
|
|
|
|
# gdb.py: Python module for low level GDB protocol implementation
|
|
|
|
# Copyright (C) 2009 Black Sphere Technologies
|
|
|
|
# Written by Gareth McMullin <gareth@blacksphere.co.nz>
|
2020-05-11 06:51:06 +00:00
|
|
|
#
|
2011-02-04 07:25:12 +00:00
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
|
|
|
|
# Used to parse XML memory map from target
|
|
|
|
from xml.dom.minidom import parseString
|
|
|
|
import struct
|
|
|
|
import time
|
|
|
|
|
|
|
|
def hexify(s):
|
2020-05-11 06:51:06 +00:00
|
|
|
"""Convert a bytes object into hex bytes representation"""
|
|
|
|
return s.hex().encode()
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def unhexify(s):
|
2020-05-11 06:51:06 +00:00
|
|
|
"""Convert a hex-encoded bytes into bytes object"""
|
|
|
|
return bytes.fromhex(s.decode())
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
class FakeSocket:
|
|
|
|
"""Emulate socket functions send and recv on a file object"""
|
|
|
|
def __init__(self, file):
|
|
|
|
self.file = file
|
2020-05-11 06:51:06 +00:00
|
|
|
|
2011-02-04 07:25:12 +00:00
|
|
|
def send(self, data):
|
|
|
|
self.file.write(data)
|
|
|
|
|
|
|
|
def recv(self, bufsize):
|
|
|
|
return self.file.read(bufsize)
|
|
|
|
|
|
|
|
class Target:
|
|
|
|
def __init__(self, sock):
|
|
|
|
if "send" in dir(sock):
|
|
|
|
self.sock = sock
|
2020-05-11 06:51:06 +00:00
|
|
|
else:
|
2011-02-04 07:25:12 +00:00
|
|
|
self.sock = FakeSocket(sock)
|
|
|
|
|
2020-05-11 06:51:06 +00:00
|
|
|
self.PacketSize=0x100 # default
|
|
|
|
|
2011-02-04 07:25:12 +00:00
|
|
|
def getpacket(self):
|
|
|
|
"""Return the first correctly received packet from GDB target"""
|
|
|
|
while True:
|
2020-05-11 06:51:06 +00:00
|
|
|
while self.sock.recv(1) != b'$':
|
|
|
|
pass
|
|
|
|
|
2011-02-04 07:25:12 +00:00
|
|
|
csum = 0
|
2020-05-11 06:51:06 +00:00
|
|
|
packet = [] # list-of-small-int
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
while True:
|
2020-05-11 06:51:06 +00:00
|
|
|
c, = self.sock.recv(1)
|
|
|
|
if c == ord('#'):
|
|
|
|
break
|
2011-02-04 07:25:12 +00:00
|
|
|
|
2020-05-11 06:51:06 +00:00
|
|
|
if c == ord('$'):
|
|
|
|
packet = []
|
2011-02-04 07:25:12 +00:00
|
|
|
csum = 0
|
|
|
|
continue
|
|
|
|
|
2020-05-11 06:51:06 +00:00
|
|
|
if c == ord('}'):
|
|
|
|
c, = self.sock.recv(1)
|
|
|
|
csum += c + ord('}')
|
|
|
|
packet.append(c ^ 0x20)
|
|
|
|
continue
|
2011-02-04 07:25:12 +00:00
|
|
|
|
2020-05-11 06:51:06 +00:00
|
|
|
packet.append(c)
|
|
|
|
csum += c
|
2011-02-04 07:25:12 +00:00
|
|
|
|
2020-05-11 06:51:06 +00:00
|
|
|
if (csum & 0xFF) == int(self.sock.recv(2),16):
|
|
|
|
break
|
2011-02-04 07:25:12 +00:00
|
|
|
|
2020-05-11 06:51:06 +00:00
|
|
|
self.sock.send(b'-')
|
2011-02-04 07:25:12 +00:00
|
|
|
|
2020-05-11 06:51:06 +00:00
|
|
|
self.sock.send(b'+')
|
|
|
|
return bytes(packet)
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def putpacket(self, packet):
|
2020-05-11 06:51:06 +00:00
|
|
|
"""Send packet to GDB target and wait for acknowledge
|
|
|
|
packet is bytes or string"""
|
|
|
|
|
|
|
|
if type(packet) == str:
|
|
|
|
packet = packet.encode()
|
|
|
|
|
2011-02-04 07:25:12 +00:00
|
|
|
while True:
|
2020-05-11 06:51:06 +00:00
|
|
|
out = []
|
|
|
|
|
2011-02-04 07:25:12 +00:00
|
|
|
for c in packet:
|
2020-05-11 06:51:06 +00:00
|
|
|
if (c in b'$#}'):
|
|
|
|
out.append(ord('}'))
|
|
|
|
out.append(c ^ 0x20)
|
2011-02-04 07:25:12 +00:00
|
|
|
else:
|
2020-05-11 06:51:06 +00:00
|
|
|
out.append(c)
|
|
|
|
|
|
|
|
csum = sum(out)
|
|
|
|
outb = b'$'+bytes(out)+b'#%02X' % (csum & 0xff)
|
|
|
|
|
|
|
|
self.sock.send(outb)
|
|
|
|
if self.sock.recv(1) == b'+':
|
|
|
|
break
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def monitor(self, cmd):
|
|
|
|
"""Send gdb "monitor" command to target"""
|
2020-05-11 06:51:06 +00:00
|
|
|
if type(cmd) == str:
|
|
|
|
cmd = cmd.encode()
|
|
|
|
|
2011-02-04 07:25:12 +00:00
|
|
|
ret = []
|
2020-05-11 06:51:06 +00:00
|
|
|
self.putpacket(b"qRcmd," + hexify(cmd))
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
while True:
|
|
|
|
s = self.getpacket()
|
2020-05-11 06:51:06 +00:00
|
|
|
|
|
|
|
if s == b'':
|
|
|
|
return None
|
|
|
|
if s == b'OK':
|
|
|
|
return ret
|
|
|
|
if s.startswith(b'O'):
|
|
|
|
ret.append(unhexify(s[1:]))
|
2011-02-04 07:25:12 +00:00
|
|
|
else:
|
2020-05-11 06:51:06 +00:00
|
|
|
raise Exception('Invalid GDB stub response %r'%s.decode())
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def attach(self, pid):
|
|
|
|
"""Attach to target process (gdb "attach" command)"""
|
2020-05-11 06:51:06 +00:00
|
|
|
self.putpacket(b"vAttach;%08X" % pid)
|
2011-02-04 07:25:12 +00:00
|
|
|
reply = self.getpacket()
|
2020-05-11 06:51:06 +00:00
|
|
|
if (reply == b'') or (reply[:1] == b'E'):
|
2011-02-04 07:25:12 +00:00
|
|
|
raise Exception('Failed to attach to remote pid %d' % pid)
|
|
|
|
|
|
|
|
def detach(self):
|
|
|
|
"""Detach from target process (gdb "detach" command)"""
|
2020-05-11 06:51:06 +00:00
|
|
|
self.putpacket(b"D")
|
|
|
|
if self.getpacket() != b'OK':
|
2011-02-04 07:25:12 +00:00
|
|
|
raise Exception("Failed to detach from remote process")
|
|
|
|
|
|
|
|
def reset(self):
|
|
|
|
"""Reset the target system"""
|
2020-05-11 06:51:06 +00:00
|
|
|
self.putpacket(b"r")
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def read_mem(self, addr, length):
|
|
|
|
"""Read length bytes from target at address addr"""
|
2020-05-11 06:51:06 +00:00
|
|
|
ret = b''
|
|
|
|
while length:
|
2022-02-07 23:01:38 +00:00
|
|
|
# print("Read")
|
2020-05-11 06:51:06 +00:00
|
|
|
packlen = min(length,self.PacketSize//2)
|
|
|
|
self.putpacket(b"m%08X,%08X" % (addr, packlen))
|
|
|
|
reply = self.getpacket()
|
|
|
|
if (reply == b'') or (reply[:1] == b'E'):
|
|
|
|
raise Exception('Error reading memory at 0x%08X' % addr)
|
|
|
|
try:
|
|
|
|
data = unhexify(reply)
|
|
|
|
except Exception:
|
|
|
|
raise Exception('Invalid response to memory read packet: %r' % reply)
|
|
|
|
ret += data
|
|
|
|
length -= packlen
|
|
|
|
addr += packlen
|
|
|
|
|
|
|
|
return ret
|
|
|
|
|
2011-02-04 07:25:12 +00:00
|
|
|
def write_mem(self, addr, data):
|
|
|
|
"""Write data to target at address addr"""
|
2020-05-11 06:51:06 +00:00
|
|
|
data = bytes(data)
|
|
|
|
|
|
|
|
while data:
|
|
|
|
d = data[:self.PacketSize-44]
|
|
|
|
data = data[len(d):]
|
|
|
|
#print("Writing %d bytes at 0x%X" % (len(d), addr))
|
|
|
|
pack = b"X%08X,%08X:%s" % (addr, len(d), d)
|
|
|
|
self.putpacket(pack)
|
|
|
|
|
|
|
|
if self.getpacket() != b'OK':
|
|
|
|
raise Exception('Error writing to memory at 0x%08X' % addr)
|
|
|
|
addr += len(d)
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def read_regs(self):
|
|
|
|
"""Read target core registers"""
|
2020-05-11 06:51:06 +00:00
|
|
|
self.putpacket(b"g")
|
2011-02-04 07:25:12 +00:00
|
|
|
reply = self.getpacket()
|
2020-05-11 06:51:06 +00:00
|
|
|
if (reply == b'') or (reply[:1] == b'E'):
|
2022-02-13 16:17:05 +00:00
|
|
|
raise Exception('Error reading target core registers')
|
2011-02-04 07:25:12 +00:00
|
|
|
try:
|
|
|
|
data = unhexify(reply)
|
2020-05-11 06:51:06 +00:00
|
|
|
except Exception:
|
2022-02-13 16:17:05 +00:00
|
|
|
raise Exception('Invalid response to registers read packet: %r' % reply)
|
2020-05-11 06:51:06 +00:00
|
|
|
ret = array.array('I',data)
|
|
|
|
return ret
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def write_regs(self, *regs):
|
|
|
|
"""Write target core registers"""
|
2011-11-12 00:47:50 +00:00
|
|
|
data = struct.pack("=%dL" % len(regs), *regs)
|
2020-05-11 06:51:06 +00:00
|
|
|
self.putpacket(b"G" + hexify(data))
|
|
|
|
if self.getpacket() != b'OK':
|
2011-02-04 07:25:12 +00:00
|
|
|
raise Exception('Error writing to target core registers')
|
|
|
|
|
|
|
|
def memmap_read(self):
|
|
|
|
"""Read the XML memory map from target"""
|
|
|
|
offset = 0
|
2020-05-11 06:51:06 +00:00
|
|
|
ret = b''
|
2011-02-04 07:25:12 +00:00
|
|
|
while True:
|
2020-05-11 06:51:06 +00:00
|
|
|
self.putpacket(b"qXfer:memory-map:read::%08X,%08X" % (offset, 512))
|
2011-02-04 07:25:12 +00:00
|
|
|
reply = self.getpacket()
|
2020-05-11 06:51:06 +00:00
|
|
|
if (reply[0] in b'ml'):
|
2011-02-04 07:25:12 +00:00
|
|
|
offset += len(reply) - 1
|
|
|
|
ret += reply[1:]
|
|
|
|
else:
|
2020-05-11 06:51:06 +00:00
|
|
|
raise Exception('Invalid GDB stub response %r'%reply)
|
|
|
|
|
|
|
|
if reply[:1] == b'l':
|
|
|
|
return ret
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def resume(self):
|
|
|
|
"""Resume target execution"""
|
2020-05-11 06:51:06 +00:00
|
|
|
self.putpacket(b'c')
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def interrupt(self):
|
|
|
|
"""Interrupt target execution"""
|
2020-05-11 06:51:06 +00:00
|
|
|
self.sock.send(b'\x03')
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def run_stub(self, stub, address, *args):
|
|
|
|
"""Execute a binary stub at address, passing args in core registers."""
|
|
|
|
self.reset() # Ensure processor is in sane state
|
|
|
|
time.sleep(0.1)
|
|
|
|
self.write_mem(address, stub)
|
|
|
|
regs = list(self.read_regs())
|
|
|
|
regs[:len(args)] = args
|
|
|
|
regs[15] = address
|
|
|
|
self.write_regs(*regs)
|
|
|
|
self.resume()
|
2020-05-11 06:51:06 +00:00
|
|
|
reply = None
|
2011-02-04 07:25:12 +00:00
|
|
|
while not reply:
|
|
|
|
reply = self.getpacket()
|
2020-05-11 06:51:06 +00:00
|
|
|
if not reply.startswith(b"T05"):
|
|
|
|
message = "Invalid stop response: %r" % reply
|
|
|
|
try:
|
|
|
|
message += {'T02':' (SIGINT)',
|
|
|
|
'T05':' (SIGTRAP)',
|
|
|
|
'T0B':' (SIGSEGV)',
|
|
|
|
'T1D':' (SIGLOST)'}[reply]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
raise Exception(message)
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
class FlashMemory:
|
|
|
|
def __init__(self, target, offset, length, blocksize):
|
|
|
|
self.target = target
|
|
|
|
self.offset = offset
|
|
|
|
self.length = length
|
|
|
|
self.blocksize = blocksize
|
2020-05-11 06:51:06 +00:00
|
|
|
self.blocks = list(None for i in range(length // blocksize))
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def prog(self, offset, data):
|
2020-05-11 06:51:06 +00:00
|
|
|
assert type(data)==bytes
|
|
|
|
|
|
|
|
assert ((offset >= self.offset) and
|
2011-02-04 07:25:12 +00:00
|
|
|
(offset + len(data) <= self.offset + self.length))
|
|
|
|
|
|
|
|
while data:
|
2020-05-11 06:51:06 +00:00
|
|
|
index = (offset - self.offset) // self.blocksize
|
2011-02-04 07:25:12 +00:00
|
|
|
bloffset = (offset - self.offset) % self.blocksize
|
|
|
|
bldata = data[:self.blocksize-bloffset]
|
|
|
|
data = data[len(bldata):]; offset += len(bldata)
|
|
|
|
if self.blocks[index] is None: # Initialize a clear block
|
2020-05-11 06:51:06 +00:00
|
|
|
self.blocks[index] = bytes(0xff for i in range(self.blocksize))
|
|
|
|
self.blocks[index] = (self.blocks[index][:bloffset] + bldata +
|
2011-02-04 07:25:12 +00:00
|
|
|
self.blocks[index][bloffset+len(bldata):])
|
|
|
|
|
|
|
|
def commit(self, progress_cb=None):
|
|
|
|
totalblocks = 0
|
|
|
|
for b in self.blocks:
|
2020-05-11 06:51:06 +00:00
|
|
|
if b is not None:
|
|
|
|
totalblocks += 1
|
|
|
|
|
2011-02-04 07:25:12 +00:00
|
|
|
block = 0
|
|
|
|
for i in range(len(self.blocks)):
|
|
|
|
block += 1
|
2018-03-11 19:35:38 +00:00
|
|
|
if callable(progress_cb) and totalblocks > 0:
|
2011-02-04 07:25:12 +00:00
|
|
|
progress_cb(block*100/totalblocks)
|
|
|
|
|
|
|
|
# Erase the block
|
|
|
|
data = self.blocks[i]
|
|
|
|
addr = self.offset + self.blocksize * i
|
2020-05-11 06:51:06 +00:00
|
|
|
if data is None:
|
|
|
|
continue
|
2022-02-07 23:01:38 +00:00
|
|
|
#print("Erasing flash at 0x%X" % (self.offset + self.blocksize*i))
|
2020-05-11 06:51:06 +00:00
|
|
|
self.target.putpacket(b"vFlashErase:%08X,%08X" %
|
2011-02-04 07:25:12 +00:00
|
|
|
(self.offset + self.blocksize*i, self.blocksize))
|
2020-05-11 06:51:06 +00:00
|
|
|
if self.target.getpacket() != b'OK':
|
2011-02-04 07:25:12 +00:00
|
|
|
raise Exception("Failed to erase flash")
|
|
|
|
|
|
|
|
while data:
|
|
|
|
d = data[0:980]
|
|
|
|
data = data[len(d):]
|
2022-02-07 23:01:38 +00:00
|
|
|
#print("Writing %d bytes at 0x%X" % (len(d), addr))
|
2020-05-11 06:51:06 +00:00
|
|
|
self.target.putpacket(b"vFlashWrite:%08X:%s" % (addr, d))
|
2011-02-04 07:25:12 +00:00
|
|
|
addr += len(d)
|
2020-05-11 06:51:06 +00:00
|
|
|
if self.target.getpacket() != b'OK':
|
2011-02-04 07:25:12 +00:00
|
|
|
raise Exception("Failed to write flash")
|
2020-05-11 06:51:06 +00:00
|
|
|
|
|
|
|
self.target.putpacket(b"vFlashDone")
|
|
|
|
if self.target.getpacket() != b'OK':
|
2011-02-04 07:25:12 +00:00
|
|
|
raise Exception("Failed to commit")
|
2020-05-11 06:51:06 +00:00
|
|
|
|
|
|
|
self.blocks = list(None for i in range(self.length // self.blocksize))
|
|
|
|
|
2011-02-04 07:25:12 +00:00
|
|
|
|
|
|
|
def flash_probe(self):
|
|
|
|
self.mem = []
|
|
|
|
xmldom = parseString(self.memmap_read())
|
2020-05-11 06:51:06 +00:00
|
|
|
|
2011-02-04 07:25:12 +00:00
|
|
|
for memrange in xmldom.getElementsByTagName("memory"):
|
2020-05-11 06:51:06 +00:00
|
|
|
if memrange.getAttribute("type") != "flash":
|
|
|
|
continue
|
2011-02-04 07:25:12 +00:00
|
|
|
offset = eval(memrange.getAttribute("start"))
|
|
|
|
length = eval(memrange.getAttribute("length"))
|
|
|
|
for property in memrange.getElementsByTagName("property"):
|
|
|
|
if property.getAttribute("name") == "blocksize":
|
|
|
|
blocksize = eval(property.firstChild.data)
|
|
|
|
break
|
|
|
|
mem = Target.FlashMemory(self, offset, length, blocksize)
|
|
|
|
self.mem.append(mem)
|
|
|
|
|
|
|
|
xmldom.unlink()
|
|
|
|
|
|
|
|
return self.mem
|
|
|
|
|
|
|
|
def flash_write_prepare(self, address, data):
|
|
|
|
for m in self.mem:
|
2015-06-30 13:29:27 +00:00
|
|
|
if (address >= m.offset) and (address + len(data) <= m.offset + m.length):
|
2011-02-04 07:25:12 +00:00
|
|
|
m.prog(address, data)
|
|
|
|
|
|
|
|
def flash_commit(self, progress_cb=None):
|
|
|
|
for m in self.mem:
|
|
|
|
m.commit(progress_cb)
|