Now you can halt/continue from gdb.
[riscv-isa-sim.git] / riscv / gdbserver.cc
1 #include <arpa/inet.h>
2 #include <errno.h>
3 #include <fcntl.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <sys/socket.h>
7 #include <sys/types.h>
8 #include <unistd.h>
9
10 #include <algorithm>
11 #include <cassert>
12 #include <cstdio>
13 #include <vector>
14
15 #include "disasm.h"
16 #include "sim.h"
17 #include "gdbserver.h"
18
19 template <typename T>
20 unsigned int circular_buffer_t<T>::size() const
21 {
22 if (end >= start)
23 return end - start;
24 else
25 return end + capacity - start;
26 }
27
28 template <typename T>
29 void circular_buffer_t<T>::consume(unsigned int bytes)
30 {
31 start = (start + bytes) % capacity;
32 }
33
34 template <typename T>
35 unsigned int circular_buffer_t<T>::contiguous_empty_size() const
36 {
37 if (end >= start)
38 if (start == 0)
39 return capacity - end - 1;
40 else
41 return capacity - end;
42 else
43 return start - end - 1;
44 }
45
46 template <typename T>
47 unsigned int circular_buffer_t<T>::contiguous_data_size() const
48 {
49 if (end >= start)
50 return end - start;
51 else
52 return capacity - start;
53 }
54
55 template <typename T>
56 void circular_buffer_t<T>::data_added(unsigned int bytes)
57 {
58 end += bytes;
59 assert(end <= capacity);
60 if (end == capacity)
61 end = 0;
62 }
63
64 template <typename T>
65 void circular_buffer_t<T>::reset()
66 {
67 start = 0;
68 end = 0;
69 }
70
71 template <typename T>
72 void circular_buffer_t<T>::append(const T *src, unsigned int count)
73 {
74 unsigned int copy = std::min(count, contiguous_empty_size());
75 memcpy(contiguous_empty(), src, copy * sizeof(T));
76 data_added(copy);
77 count -= copy;
78 if (count > 0) {
79 assert(count < contiguous_empty_size());
80 memcpy(contiguous_empty(), src, count * sizeof(T));
81 data_added(count);
82 }
83 }
84
85 // Code inspired by/copied from OpenOCD server/server.c.
86
87 gdbserver_t::gdbserver_t(uint16_t port, sim_t *sim) :
88 sim(sim),
89 client_fd(0),
90 recv_buf(64 * 1024), send_buf(64 * 1024)
91 {
92 socket_fd = socket(AF_INET, SOCK_STREAM, 0);
93 if (socket_fd == -1) {
94 fprintf(stderr, "error creating socket: %s\n", strerror(errno));
95 abort();
96 }
97
98 int so_reuseaddr_option = 1;
99 setsockopt(socket_fd,
100 SOL_SOCKET,
101 SO_REUSEADDR,
102 (void *)&so_reuseaddr_option,
103 sizeof(int));
104
105 int oldopts = fcntl(socket_fd, F_GETFL, 0);
106 fcntl(socket_fd, F_SETFL, oldopts | O_NONBLOCK);
107
108 struct sockaddr_in sin;
109 memset(&sin, 0, sizeof(sin));
110 sin.sin_family = AF_INET;
111 sin.sin_addr.s_addr = INADDR_ANY;
112 sin.sin_port = htons(port);
113
114 if (bind(socket_fd, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
115 fprintf(stderr, "couldn't bind to socket: %s\n", strerror(errno));
116 abort();
117 }
118
119 /* These setsockopt()s must happen before the listen() */
120 int window_size = 128 * 1024;
121 setsockopt(socket_fd, SOL_SOCKET, SO_SNDBUF,
122 (char *)&window_size, sizeof(window_size));
123 setsockopt(socket_fd, SOL_SOCKET, SO_RCVBUF,
124 (char *)&window_size, sizeof(window_size));
125
126 if (listen(socket_fd, 1) == -1) {
127 fprintf(stderr, "couldn't listen on socket: %s\n", strerror(errno));
128 abort();
129 }
130 }
131
132 void gdbserver_t::accept()
133 {
134 struct sockaddr client_addr;
135 socklen_t address_size = sizeof(client_addr);
136 client_fd = ::accept(socket_fd, &client_addr, &address_size);
137 if (client_fd == -1) {
138 if (errno == EAGAIN) {
139 // We'll try again in the next call.
140 } else {
141 fprintf(stderr, "failed to accept on socket: %s (%d)\n", strerror(errno), errno);
142 abort();
143 }
144 } else {
145 int oldopts = fcntl(client_fd, F_GETFL, 0);
146 fcntl(client_fd, F_SETFL, oldopts | O_NONBLOCK);
147 expect_ack = false;
148
149 // gdb wants the core to be halted when it attaches.
150 processor_t *p = sim->get_core(0);
151 p->set_halted(true);
152 }
153 }
154
155 void gdbserver_t::read()
156 {
157 // Reading from a non-blocking socket still blocks if there is no data
158 // available.
159
160 size_t count = recv_buf.contiguous_empty_size();
161 assert(count > 0);
162 ssize_t bytes = ::read(client_fd, recv_buf.contiguous_empty(), count);
163 if (bytes == -1) {
164 if (errno == EAGAIN) {
165 // We'll try again the next call.
166 } else {
167 fprintf(stderr, "failed to read on socket: %s (%d)\n", strerror(errno), errno);
168 abort();
169 }
170 } else if (bytes == 0) {
171 // The remote disconnected.
172 client_fd = 0;
173 recv_buf.reset();
174 send_buf.reset();
175 } else {
176 recv_buf.data_added(bytes);
177 printf("Read %d bytes.\n", bytes);
178 }
179 }
180
181 void gdbserver_t::write()
182 {
183 if (send_buf.empty())
184 return;
185
186 while (!send_buf.empty()) {
187 unsigned int count = send_buf.contiguous_data_size();
188 assert(count > 0);
189 ssize_t bytes = ::write(client_fd, send_buf.contiguous_data(), count);
190 if (bytes == -1) {
191 fprintf(stderr, "failed to write to socket: %s (%d)\n", strerror(errno), errno);
192 abort();
193 } else if (bytes == 0) {
194 // Client can't take any more data right now.
195 break;
196 } else {
197 printf("wrote %ld bytes: ", bytes);
198 for (unsigned int i = 0; i < bytes; i++) {
199 printf("%c", send_buf[i]);
200 }
201 printf("\n");
202 send_buf.consume(bytes);
203 }
204 }
205 }
206
207 void print_packet(const std::vector<uint8_t> &packet)
208 {
209 for (uint8_t c : packet) {
210 if (c >= ' ' and c <= '~')
211 fprintf(stderr, "%c", c);
212 else
213 fprintf(stderr, "\\x%x", c);
214 }
215 fprintf(stderr, "\n");
216 }
217
218 uint8_t compute_checksum(const std::vector<uint8_t> &packet)
219 {
220 uint8_t checksum = 0;
221 for (auto i = packet.begin() + 1; i != packet.end() - 3; i++ ) {
222 checksum += *i;
223 }
224 return checksum;
225 }
226
227 uint8_t character_hex_value(uint8_t character)
228 {
229 if (character >= '0' && character <= '9')
230 return character - '0';
231 if (character >= 'a' && character <= 'f')
232 return 10 + character - 'a';
233 if (character >= 'A' && character <= 'F')
234 return 10 + character - 'A';
235 return 0xff;
236 }
237
238 uint8_t extract_checksum(const std::vector<uint8_t> &packet)
239 {
240 return character_hex_value(*(packet.end() - 1)) +
241 16 * character_hex_value(*(packet.end() - 2));
242 }
243
244 void gdbserver_t::process_requests()
245 {
246 // See https://sourceware.org/gdb/onlinedocs/gdb/Remote-Protocol.html
247
248 while (!recv_buf.empty()) {
249 std::vector<uint8_t> packet;
250 for (unsigned int i = 0; i < recv_buf.size(); i++) {
251 uint8_t b = recv_buf[i];
252
253 if (packet.empty() && expect_ack && b == '+') {
254 fprintf(stderr, "Received ack\n");
255 recv_buf.consume(1);
256 break;
257 }
258
259 if (packet.empty() && b == 3) {
260 fprintf(stderr, "Received interrupt\n");
261 recv_buf.consume(1);
262 handle_interrupt();
263 break;
264 }
265
266 if (b == '$') {
267 // Start of new packet.
268 if (!packet.empty()) {
269 fprintf(stderr, "Received malformed %ld-byte packet from debug client: ", packet.size());
270 print_packet(packet);
271 recv_buf.consume(i);
272 break;
273 }
274 }
275
276 packet.push_back(b);
277
278 // Packets consist of $<packet-data>#<checksum>
279 // where <checksum> is
280 if (packet.size() >= 4 &&
281 packet[packet.size()-3] == '#') {
282 handle_packet(packet);
283 recv_buf.consume(i+1);
284 break;
285 }
286 }
287 // There's a partial packet in the buffer. Wait until we get more data to
288 // process it.
289 if (packet.size()) {
290 fprintf(stderr, "Partial packet: ");
291 print_packet(packet);
292 break;
293 }
294 }
295 }
296
297 void gdbserver_t::handle_halt_reason(const std::vector<uint8_t> &packet)
298 {
299 send_packet("S00");
300 }
301
302 void gdbserver_t::handle_read_general_registers(const std::vector<uint8_t> &packet)
303 {
304 // Register order that gdb expects is:
305 // "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7",
306 // "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15",
307 // "x16", "x17", "x18", "x19", "x20", "x21", "x22", "x23",
308 // "x24", "x25", "x26", "x27", "x28", "x29", "x30", "x31",
309 // "pc",
310 // "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
311 // "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
312 // "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
313 // "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
314
315 // Each byte of register data is described by two hex digits. The bytes with
316 // the register are transmitted in target byte order. The size of each
317 // register and their position within the ‘g’ packet are determined by the
318 // gdb internal gdbarch functions DEPRECATED_REGISTER_RAW_SIZE and
319 // gdbarch_register_name.
320
321 send("$");
322 running_checksum = 0;
323 processor_t *p = sim->get_core(0);
324 for (int r = 0; r < 32; r++) {
325 send(p->state.XPR[r]);
326 }
327 send_running_checksum();
328 expect_ack = true;
329 }
330
331 uint64_t consume_hex_number(std::vector<uint8_t>::const_iterator &iter,
332 std::vector<uint8_t>::const_iterator end)
333 {
334 uint64_t value = 0;
335
336 while (iter != end) {
337 uint8_t c = *iter;
338 uint64_t c_value = character_hex_value(c);
339 if (c_value > 15)
340 break;
341 iter++;
342 value <<= 4;
343 value += c_value;
344 }
345 return value;
346 }
347
348 void gdbserver_t::handle_read_register(const std::vector<uint8_t> &packet)
349 {
350 // p n
351
352 // Register order that gdb expects is:
353 // "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7",
354 // "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15",
355 // "x16", "x17", "x18", "x19", "x20", "x21", "x22", "x23",
356 // "x24", "x25", "x26", "x27", "x28", "x29", "x30", "x31",
357 // "pc",
358 // "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
359 // "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
360 // "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
361 // "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
362
363 std::vector<uint8_t>::const_iterator iter = packet.begin() + 2;
364 unsigned int n = consume_hex_number(iter, packet.end());
365 if (*iter != '#')
366 return send_packet("E16"); // EINVAL
367
368 processor_t *p = sim->get_core(0);
369 send("$");
370 running_checksum = 0;
371 if (n < 32) {
372 send(p->state.XPR[n]);
373 } else if (n == 0x20) {
374 send(p->state.pc);
375 } else {
376 send("E16"); // EINVAL
377 }
378
379 send_running_checksum();
380 expect_ack = true;
381 }
382
383 void gdbserver_t::handle_read_memory(const std::vector<uint8_t> &packet)
384 {
385 // m addr,length
386 std::vector<uint8_t>::const_iterator iter = packet.begin() + 2;
387 reg_t address = consume_hex_number(iter, packet.end());
388 printf("address=%lx %c\n", address, *iter);
389 if (*iter != ',')
390 return send_packet("E16"); // EINVAL
391 iter++;
392 reg_t length = consume_hex_number(iter, packet.end());
393 printf("length=%lx %c\n", length, *iter);
394 if (*iter != '#')
395 return send_packet("E16"); // EINVAL
396
397 send("$");
398 running_checksum = 0;
399 char buffer[3];
400 processor_t *p = sim->get_core(0);
401 mmu_t* mmu = sim->debug_mmu;
402
403 for (reg_t i = 0; i < length; i++) {
404 sprintf(buffer, "%02x", mmu->load_uint8(address + i));
405 send(buffer);
406 }
407 send_running_checksum();
408 }
409
410 void gdbserver_t::handle_packet(const std::vector<uint8_t> &packet)
411 {
412 if (compute_checksum(packet) != extract_checksum(packet)) {
413 fprintf(stderr, "Received %ld-byte packet with invalid checksum\n", packet.size());
414 fprintf(stderr, "Computed checksum: %x\n", compute_checksum(packet));
415 print_packet(packet);
416 send("-");
417 return;
418 }
419
420 fprintf(stderr, "Received %ld-byte packet from debug client: ", packet.size());
421 print_packet(packet);
422 send("+");
423
424 switch (packet[1]) {
425 case '?':
426 return handle_halt_reason(packet);
427 case 'g':
428 return handle_read_general_registers(packet);
429 case 'm':
430 return handle_read_memory(packet);
431 case 'p':
432 return handle_read_register(packet);
433 case 'c':
434 return handle_continue(packet);
435 }
436
437 // Not supported.
438 send_packet("");
439 }
440
441 void gdbserver_t::handle_interrupt()
442 {
443 processor_t *p = sim->get_core(0);
444 p->set_halted(true);
445 send_packet("S02"); // Pretend program received SIGINT.
446 }
447
448 void gdbserver_t::handle_continue(const std::vector<uint8_t> &packet)
449 {
450 // c [addr]
451 processor_t *p = sim->get_core(0);
452 if (packet[2] != '#') {
453 std::vector<uint8_t>::const_iterator iter = packet.begin() + 2;
454 p->state.pc = consume_hex_number(iter, packet.end());
455 if (*iter != '#')
456 return send_packet("E16"); // EINVAL
457 }
458
459 p->set_halted(false);
460 }
461
462 void gdbserver_t::handle()
463 {
464 if (client_fd > 0) {
465 this->read();
466 this->write();
467
468 } else {
469 this->accept();
470 }
471
472 this->process_requests();
473 }
474
475 void gdbserver_t::send(const char* msg)
476 {
477 unsigned int length = strlen(msg);
478 for (const char *c = msg; *c; c++)
479 running_checksum += *c;
480 send_buf.append((const uint8_t *) msg, length);
481 }
482
483 void gdbserver_t::send(uint64_t value)
484 {
485 char buffer[3];
486 for (unsigned int i = 0; i < 8; i++) {
487 sprintf(buffer, "%02x", value & 0xff);
488 send(buffer);
489 value >>= 8;
490 }
491 }
492
493 void gdbserver_t::send(uint32_t value)
494 {
495 char buffer[3];
496 for (unsigned int i = 0; i < 4; i++) {
497 sprintf(buffer, "%02x", value & 0xff);
498 send(buffer);
499 value >>= 8;
500 }
501 }
502
503 void gdbserver_t::send_packet(const char* data)
504 {
505 send("$");
506 running_checksum = 0;
507 send(data);
508 send_running_checksum();
509 expect_ack = true;
510 }
511
512 void gdbserver_t::send_running_checksum()
513 {
514 char checksum_string[4];
515 sprintf(checksum_string, "#%02x", running_checksum);
516 send(checksum_string);
517 }