2 * Copyright (C) 2011 Peter Zotov <whitequark@whitequark.org>
3 * Use of this source code is governed by a BSD-style
4 * license that can be found in the LICENSE file.
18 static const char hex[] = "0123456789abcdef";
20 int gdb_send_packet(int fd, char* data) {
21 unsigned int data_length = strlen(data);
22 int length = data_length + 4;
23 char* packet = malloc(length); /* '$' data (hex) '#' cksum (hex) */
25 memset(packet, 0, length);
30 for(unsigned int i = 0; i < data_length; i++) {
31 packet[i + 1] = data[i];
35 packet[length - 3] = '#';
36 packet[length - 2] = hex[cksum >> 4];
37 packet[length - 1] = hex[cksum & 0xf];
40 if(write(fd, packet, length) != length) {
46 if(read(fd, &ack, 1) != 1) {
58 #define ALLOC_STEP 1024
60 int gdb_recv_packet(int fd, char** buffer) {
61 unsigned packet_size = ALLOC_STEP + 1, packet_idx = 0;
63 char recv_cksum[3] = {0};
64 char* packet_buffer = malloc(packet_size);
79 if(read(fd, &c, 1) != 1) {
96 packet_buffer[packet_idx++] = c;
99 if(packet_idx == packet_size) {
100 packet_size += ALLOC_STEP;
101 packet_buffer = realloc(packet_buffer, packet_size);
118 uint8_t recv_cksum_int = strtoul(recv_cksum, NULL, 16);
119 if(recv_cksum_int != cksum) {
121 if(write(fd, &nack, 1) != 1) {
128 if(write(fd, &ack, 1) != 1) {
133 packet_buffer[packet_idx] = 0;
134 *buffer = packet_buffer;
139 // Here we skip any characters which are not \x03, GDB interrupt.
140 // As we use the mode with ACK, in a (very unlikely) situation of a packet
141 // lost because of this skipping, it will be resent anyway.
142 int gdb_check_for_interrupt(int fd) {
147 if(poll(&pfd, 1, 0) != 0) {
150 if(read(fd, &c, 1) != 1)
153 if(c == '\x03') // ^C