-
Notifications
You must be signed in to change notification settings - Fork 11
/
gdbserver.rb
375 lines (340 loc) · 8.57 KB
/
gdbserver.rb
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
require 'socket'
$: << File.realpath('..', __FILE__)
require 'device'
require 'log'
class GDBServer
def initialize(target, *addr)
@target = target
@servsock = TCPServer.new(*addr)
end
def run_loop
while true
@sock = @servsock.accept
begin
handle_connection
rescue EOFError, Errno::EPIPE, Errno::ECONNRESET
Log(:gdb, 1){ "connection closed" }
end
@sock.close
end
end
def handle_connection
Log(:gdb, 1){ "accepted connection" }
@data = String.new # ASCII-8BIT
@sock.setsockopt(:TCP, :NODELAY, true)
@sock.set_encoding('binary')
attach
while @state != :detached
cmd = read_packet
repl = nil
begin
# default to "unknown command", but allow
# explicit nil (needed by R)
repl = catch (:gdbreply) do
dispatch(cmd) || ''
end
rescue EOFError, Errno::EPIPE, Errno::ECONNRESET
raise
rescue StandardError => e
Log(:gdb, 1){ ([e] + e.backtrace).join("\n") }
repl = 'E01'
end
reply repl if repl
end
# optionally wait for final '?' cmd
cmd = read_packet
reply ''
end
def read_packet
while !(m = /^(.*[$])([^#]*)[#]..(.*)/.match(@data))
Log(:gdb, 3){ "data length #{@data.length} no full packet, reading more" }
@data += @sock.readpartial(1024)
end
_, discard, pkt, @data = m.to_a
@sock.write('+') # ack
Log(:gdb, 2){ "received pkt #{pkt.gsub(/[^[:print:]]/, '.')}, discarded leading `#{discard}'" }
pkt
end
def reply(pkt)
csum = 0
pkt.each_byte{|b| csum += b}
csum = csum % 256
fullpkt = "$%s#%02x" % [pkt, csum]
Log(:gdb, 2){ "sending pkt #{fullpkt}" }
@sock.write(fullpkt)
# we just ignore the ack, because we're on TCP
end
def dispatch(pkt)
case pkt
when '!'
# extended mode
'OK'
when '?'
# get halt reason
wait_stop
when /^c([[:xdigit:]]+)?$/
# continue [addr]
continue($1)
when 'D'
# detach
detach
when 'g'
# read general registers
read_registers
when /^G([[:xdigit:]]+)$/
# write general registers
write_registers($1)
when /^m([[:xdigit:]]+),([[:xdigit:]]+)$/
# read addr,length memory
read_mem($1, $2)
when /^M([[:xdigit:]]+),([[:xdigit:]]+):([[:xdigit:]]+)$/
# write addr,length:data to memory
write_mem($1, $3)
when /^qAttached.*/
# we always attach to an existing process
'1'
when /^qRcmd,([[:xdigit:]]+)/
# monitor command
cmd = parse_hex_binary($1)
Log(:gdb, 1){ 'received command %s' % cmd}
when /^qSupported.*/
'PacketSize=4000;qXfer:features:read+;qXfer:memory-map:read+'
when /^qXfer:features:read:target.xml:([[:xdigit:]]+),([[:xdigit:]]+)$/
send_tdesc($1, $2)
when /^qXfer:memory-map:read::([[:xdigit:]]+),([[:xdigit:]]+)$/
send_mmap($1, $2)
when /^R..$/
# reset system
reset_system(false)
when /^s([[:xdigit:]]+)?$/
# single step [addr]
single_step($1)
when /^T([[:digit:]]+)$/
# Thread always alive
'OK'
when /^vAttach;.*$/
attach
when /^vFlashErase:([[:xdigit:]]+),([[:xdigit:]]+)$/
flash_prepare($1, $2)
when /^vFlashWrite:([[:xdigit:]]+):(.*)$/m
# flash to address $1 data $2
flash_write($1, $2)
when /^vFlashDone$/
flash_commit
when /^vKill;/
ret = reset_system(:ok)
@state = :killed
ret
when /^vRun;$/
@state = :resetting
reset_system(:stop)
when /^([zZ])([01234]),([[:xdigit:]]+),([[:xdigit:]]*).*/
# remove/insert breakpoint
breakpoint($1, $2, $3, $4)
else
# error
Log(:gdb, 1){ "invalid packet `#{pkt}'" }
''
end
end
def parse_int(str)
str.to_i(16)
end
def parse_hex_binary(data)
[data].pack('H*')
end
def code_hex_binary(data)
data.unpack('H*').first
end
def parse_raw_binary(data)
data.gsub(/\x7d./m){|m| (m[1].ord ^ 0x20).chr}
end
def attach
@target.enable_debug!
@target.catch_vector!(true)
@target.halt_core!
@target.enable_breakpoints!
@state = :running
wait_stop
end
def detach
@target.disable_breakpoints!
@target.disable_debug!
@target.continue!
@state = :detached
'OK'
end
def continue(addrstr)
if addrstr
@target.set_register!(:pc, parse_int(addrstr))
end
@target.continue!
wait_stop
end
def read_registers
code_hex_binary(@target.read_registers)
end
def write_registers(regstr)
@target.write_registers!(parse_hex_binary(regstr))
'OK'
end
def read_mem(addrstr, lenstr)
code_hex_binary(@target.read_mem(parse_int(addrstr), parse_int(lenstr)))
end
def write_mem(addrstr, datastr)
@target.write_mem(parse_int(addrstr), parse_hex_binary(datastr))
'OK'
end
def reset_system(send_reply)
@target.reset_system!
ret = wait_stop(send_reply)
if not send_reply
# this packet has no reply
throw :gdbreply, nil
else
ret
end
end
def single_step(addrstr)
if addrstr
@target.set_register!(:pc, parse_int(addrstr))
end
@target.single_step!
wait_stop
end
def wait_stop(send_reply=:stop)
while !@target.core_halted?
begin
@data += @sock.read_nonblock(1024)
# check for telnet BREAK sequence
if @data.include?([255, 243].pack('c*')) || @data.include?([3].pack('c'))
Log(:gdb, 1){ "received break - stopping core" }
@target.halt_core!
end
rescue IO::WaitReadable
end
sleep 0.1
end
return 'X01' if @state == :killed
aux = ""
halt_reason = @target.halt_reason
if Array === halt_reason
halt_reason, type, addr = halt_reason
typestr = case type
when :watch_write
"watch"
when :watch_read
"rwatch"
when :watch_access
"awatch"
end
aux = "%s:%x;" % [typestr, addr]
end
Log(:gdb, 2){ "halt reason #{halt_reason}#{aux}" }
case send_reply
when :stop
sig_num = Signal.list[halt_reason.to_s] || Signal.list["INT"]
pc_num = @target.reg_desc.index{|r| r[:name] == :pc}
cur_pc = @target.get_register(:pc, true)
'T%02x%02x:%s;thread:1;%s' % [sig_num, pc_num, code_hex_binary(cur_pc), aux]
when :ok
'OK'
when false
nil
else
raise RuntimeError, "invalid reply mode"
end
end
def breakpoint(insertstr, typestr, addrstr, kindstr)
type = case typestr
when '0'
:break_software
when '1'
:break_hardware
when '2'
:watch_write
when '3'
:watch_read
when '4'
:watch_access
end
kind = parse_int(kindstr)
addr = parse_int(addrstr)
case insertstr
when 'Z'
@target.add_breakpoint(type, addr, kind)
when 'z'
@target.remove_breakpoint(type, addr, kind)
end
'OK'
end
def send_mmap(addrstr, lenstr)
addr, len = parse_int(addrstr), parse_int(lenstr)
desc = @target.mmap[addr,len]
if desc.empty?
'l'
else
"m#{desc}"
end
end
def send_tdesc(addrstr, lenstr)
addr, len = parse_int(addrstr), parse_int(lenstr)
desc = @target.tdesc[addr,len]
if desc.empty?
'l'
else
"m#{desc}"
end
end
def flash_prepare(addrstr, lenstr)
addr, len = parse_int(addrstr), parse_int(lenstr)
@flashdata ||= {}
@flashdata[addr] = 0xff.chr * len
'OK'
end
def flash_write(addrstr, datastr)
addr, data = parse_int(addrstr), parse_raw_binary(datastr)
@flashdata.each do |fa, fd|
next if fa > addr || fa + fd.length < addr + data.length
fd[addr - fa, data.length] = data
return 'OK'
end
@flashdata = {}
raise RuntimeError, "memory region not prepared"
end
def flash_commit
sections = @flashdata.sort_by{|k,v| k}
@flashdata = {}
sections.each do |addr, data|
@target.program_section(addr, data)
end
reset_system(:ok)
end
end
if $0 == __FILE__
require 'backend-driver'
driver = ARGV[0]
if ARGV[1] == '--'
cmd = ARGV[2..-1]
end
bkend = BackendDriver.from_string(ARGV[0])
k = Device.detect(bkend)
if cmd
trap("INT", "IGNORE")
case pid = Process.fork
when nil
# child
g = GDBServer.new(k, 1234)
g.run_loop
$stderr.puts "GDB server exiting"
exit!
else
# parent
system(*cmd)
Process.kill("TERM", pid)
end
else
g = GDBServer.new(k, 1234)
g.run_loop
end
end