Update readme, as this is about to get messy!
[fw/stlink] / gdbserver / gdb-server.c
1 /* -*- tab-width:8 -*- */
2
3 /*
4  Copyright (C)  2011 Peter Zotov <whitequark@whitequark.org>
5  Use of this source code is governed by a BSD-style
6  license that can be found in the LICENSE file.
7 */
8
9 #include <getopt.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <sys/types.h>
15 #include <sys/socket.h>
16 #include <netinet/in.h>
17 #include <arpa/inet.h>
18 #include <signal.h>
19
20 #include <stlink-common.h>
21
22 #include "gdb-remote.h"
23
24 #define DEFAULT_LOGGING_LEVEL 100
25 #define DEFAULT_GDB_LISTEN_PORT 4242
26
27 #define STRINGIFY_inner(name) #name
28 #define STRINGIFY(name) STRINGIFY_inner(name)
29
30 #define FLASH_BASE 0x08000000
31 #define FLASH_PAGE (sl->flash_pgsz)
32 #define FLASH_PAGE_MASK (~((1 << 10) - 1))
33 #define FLASH_SIZE (FLASH_PAGE * 128)
34
35 static const char hex[] = "0123456789abcdef";
36
37 static const char* current_memory_map = NULL;
38
39 /*
40  * Chip IDs are explained in the appropriate programming manual for the
41  * DBGMCU_IDCODE register (0xE0042000)
42  */
43
44 #define CORE_M3_R1 0x1BA00477
45 #define CORE_M3_R2 0x4BA00477
46 #define CORE_M4_R0 0x2BA01477
47
48 typedef struct _st_state_t {
49     // things from command line, bleh
50     int stlink_version;
51     // "/dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTE531X6-if00-port0" is only 58 chars
52     char devicename[100];
53     int logging_level;
54         int listen_port;
55 } st_state_t;
56
57
58 int serve(stlink_t *sl, int port);
59 char* make_memory_map(stlink_t *sl);
60
61
62 int parse_options(int argc, char** argv, st_state_t *st) {
63     static struct option long_options[] = {
64         {"help", no_argument, NULL, 'h'},
65         {"verbose", optional_argument, NULL, 'v'},
66         {"device", required_argument, NULL, 'd'},
67         {"stlink_version", required_argument, NULL, 's'},
68         {"stlinkv1", no_argument, NULL, '1'},
69                 {"listen_port", required_argument, NULL, 'p'},
70         {0, 0, 0, 0},
71     };
72         const char * help_str = "%s - usage:\n\n"
73         "  -h, --help\t\tPrint this help\n"
74         "  -vXX, --verbose=XX\tspecify a specific verbosity level (0..99)\n"
75         "  -v, --verbose\tspecify generally verbose logging\n"
76         "  -d <device>, --device=/dev/stlink2_1\n"
77         "\t\t\tWhere is your stlink device connected?\n"
78         "  -s X, --stlink_version=X\n"
79         "\t\t\tChoose what version of stlink to use, (defaults to 2)\n"
80         "  -1, --stlinkv1\tForce stlink version 1\n"
81         "  -p 4242, --listen_port=1234\n"
82         "\t\t\tSet the gdb server listen port. "
83         "(default port: " STRINGIFY(DEFAULT_GDB_LISTEN_PORT) ")\n"
84         ;
85
86
87     int option_index = 0;
88     int c;
89     int q;
90     while ((c = getopt_long(argc, argv, "hv::d:s:1p:", long_options, &option_index)) != -1) {
91         switch (c) {
92         case 0:
93             printf("XXXXX Shouldn't really normally come here, only if there's no corresponding option\n");
94             printf("option %s", long_options[option_index].name);
95             if (optarg) {
96                 printf(" with arg %s", optarg);
97             }
98             printf("\n");
99             break;
100         case 'h':
101             printf(help_str, argv[0]);
102             exit(EXIT_SUCCESS);
103             break;
104         case 'v':
105             if (optarg) {
106                 st->logging_level = atoi(optarg);
107             } else {
108                 st->logging_level = DEFAULT_LOGGING_LEVEL;
109             }
110             break;
111         case 'd':
112             if (strlen(optarg) > sizeof (st->devicename)) {
113                 fprintf(stderr, "device name too long: %zd\n", strlen(optarg));
114             } else {
115                 strcpy(st->devicename, optarg);
116             }
117             break;
118                 case '1':
119                         st->stlink_version = 1;
120                         break;
121                 case 's':
122                         sscanf(optarg, "%i", &q);
123                         if (q < 0 || q > 2) {
124                                 fprintf(stderr, "stlink version %d unknown!\n", q);
125                                 exit(EXIT_FAILURE);
126                         }
127                         st->stlink_version = q;
128                         break;
129                 case 'p':
130                         sscanf(optarg, "%i", &q);
131                         if (q < 0) {
132                                 fprintf(stderr, "Can't use a negative port to listen on: %d\n", q);
133                                 exit(EXIT_FAILURE);
134                         }
135                         st->listen_port = q;
136                         break;
137         }
138     }
139
140     if (optind < argc) {
141         printf("non-option ARGV-elements: ");
142         while (optind < argc)
143             printf("%s ", argv[optind++]);
144         printf("\n");
145     }
146     return 0;
147 }
148
149
150 int main(int argc, char** argv) {
151
152         stlink_t *sl = NULL;
153
154         st_state_t state;
155         memset(&state, 0, sizeof(state));
156         // set defaults...
157         state.stlink_version = 2;
158         state.logging_level = DEFAULT_LOGGING_LEVEL;
159         state.listen_port = DEFAULT_GDB_LISTEN_PORT;
160         parse_options(argc, argv, &state);
161         switch (state.stlink_version) {
162         case 2:
163                 sl = stlink_open_usb(state.logging_level);
164                 if(sl == NULL) return 1;
165                 break;
166         case 1:
167                 sl = stlink_v1_open(state.logging_level);
168                 if(sl == NULL) return 1;
169                 break;
170     }
171     
172     // ALLLL of this should move into "stlink_open_xxx"
173
174     if (stlink_current_mode(sl) != STLINK_DEV_DEBUG_MODE) {
175         if (stlink_current_mode(sl) == STLINK_DEV_DFU_MODE) {
176             stlink_exit_dfu_mode(sl);
177         }
178         stlink_enter_swd_mode(sl);
179     }
180
181         uint32_t chip_id = stlink_chip_id(sl);
182         uint32_t core_id = stlink_core_id(sl);
183
184         /* Fix chip_id for F4 */
185         if (((chip_id & 0xFFF) == 0x411) && (core_id == CORE_M4_R0)) {
186           printf("Fixing wrong chip_id for STM32F4 Rev A errata\n");
187           chip_id = 0x413;
188         }
189
190         printf("Chip ID is %08x, Core ID is  %08x.\n", chip_id, core_id);
191
192         current_memory_map = make_memory_map(sl);
193
194         while(serve(sl, state.listen_port) == 0);
195
196         /* Switch back to mass storage mode before closing. */
197         stlink_run(sl);
198         stlink_exit_debug_mode(sl);
199         stlink_close(sl);
200
201         return 0;
202 }
203
204 static const char* const memory_map_template =
205   "<?xml version=\"1.0\"?>"
206   "<!DOCTYPE memory-map PUBLIC \"+//IDN gnu.org//DTD GDB Memory Map V1.0//EN\""
207   "     \"http://sourceware.org/gdb/gdb-memory-map.dtd\">"
208   "<memory-map>"
209   "  <memory type=\"rom\" start=\"0x00000000\" length=\"0x%x\"/>"       // code = sram, bootrom or flash; flash is bigger
210   "  <memory type=\"ram\" start=\"0x20000000\" length=\"0x%x\"/>"       // sram 8k
211   "  <memory type=\"flash\" start=\"0x08000000\" length=\"0x%x\">"
212   "    <property name=\"blocksize\">0x%x</property>"
213   "  </memory>"
214   "  <memory type=\"ram\" start=\"0x40000000\" length=\"0x1fffffff\"/>" // peripheral regs
215   "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>" // cortex regs
216   "  <memory type=\"rom\" start=\"0x%08x\" length=\"0x%x\"/>"           // bootrom
217   "  <memory type=\"rom\" start=\"0x1ffff800\" length=\"0x8\"/>"        // option byte area
218   "</memory-map>";
219
220 char* make_memory_map(stlink_t *sl) {
221         /* This will be freed in serve() */
222         char* map = malloc(4096);
223         map[0] = '\0';
224
225         snprintf(map, 4096, memory_map_template,
226                         sl->flash_size,
227                         sl->sram_size,
228                         sl->flash_size, sl->flash_pgsz,
229                         sl->sys_base, sl->sys_size);
230
231         return map;
232 }
233
234
235 /* 
236  * DWT_COMP0     0xE0001020
237  * DWT_MASK0     0xE0001024
238  * DWT_FUNCTION0 0xE0001028
239  * DWT_COMP1     0xE0001030
240  * DWT_MASK1     0xE0001034
241  * DWT_FUNCTION1 0xE0001038
242  * DWT_COMP2     0xE0001040
243  * DWT_MASK2     0xE0001044
244  * DWT_FUNCTION2 0xE0001048
245  * DWT_COMP3     0xE0001050
246  * DWT_MASK3     0xE0001054
247  * DWT_FUNCTION3 0xE0001058
248  */
249
250 #define DATA_WATCH_NUM 4
251
252 enum watchfun { WATCHDISABLED = 0, WATCHREAD = 5, WATCHWRITE = 6, WATCHACCESS = 7 };
253
254 struct code_hw_watchpoint {
255         stm32_addr_t addr;
256         uint8_t mask;
257         enum watchfun fun;
258 };
259
260 struct code_hw_watchpoint data_watches[DATA_WATCH_NUM];
261
262 static void init_data_watchpoints(stlink_t *sl) {
263         #ifdef DEBUG
264         printf("init watchpoints\n");
265         #endif
266
267         // set trcena in debug command to turn on dwt unit
268         stlink_read_mem32(sl, 0xE000EDFC, 4);
269         sl->q_buf[3] |= 1;
270         stlink_write_mem32(sl, 0xE000EDFC, 4);
271
272         // make sure all watchpoints are cleared
273         memset(sl->q_buf, 0, 4);
274         for(int i = 0; i < DATA_WATCH_NUM; i++) {
275                 data_watches[i].fun = WATCHDISABLED;
276                 stlink_write_mem32(sl, 0xe0001028 + i * 16, 4);
277         }
278 }
279
280 static int add_data_watchpoint(stlink_t *sl, enum watchfun wf, stm32_addr_t addr, unsigned int len)
281 {
282         int i = 0;
283         uint32_t mask;
284
285         // computer mask
286         // find a free watchpoint
287         // configure
288
289         mask = -1;
290         i = len;
291         while(i) {
292                 i >>= 1;
293                 mask++;
294         }
295
296         if((mask != -1) && (mask < 16)) {
297                 for(i = 0; i < DATA_WATCH_NUM; i++) {
298                         // is this an empty slot ?
299                         if(data_watches[i].fun == WATCHDISABLED) {
300                                 #ifdef DEBUG
301                                 printf("insert watchpoint %d addr %x wf %u mask %u len %d\n", i, addr, wf, mask, len);
302                                 #endif
303
304                                 data_watches[i].fun = wf;
305                                 data_watches[i].addr = addr;
306                                 data_watches[i].mask = mask;
307
308                                 // insert comparator address
309                                 sl->q_buf[0] = (addr & 0xff);
310                                 sl->q_buf[1] = ((addr >> 8) & 0xff);
311                                 sl->q_buf[2] = ((addr >> 16) & 0xff);
312                                 sl->q_buf[3] = ((addr >> 24)  & 0xff);
313
314                                 stlink_write_mem32(sl, 0xE0001020 + i * 16, 4);
315
316                                 // insert mask
317                                 memset(sl->q_buf, 0, 4);
318                                 sl->q_buf[0] = mask;
319                                 stlink_write_mem32(sl, 0xE0001024 + i * 16, 4);
320
321                                 // insert function
322                                 memset(sl->q_buf, 0, 4);
323                                 sl->q_buf[0] = wf;
324                                 stlink_write_mem32(sl, 0xE0001028 + i * 16, 4);
325
326                                 // just to make sure the matched bit is clear !
327                                 stlink_read_mem32(sl,  0xE0001028 + i * 16, 4);
328                                 return 0;
329                         }
330                 }
331         }
332
333         #ifdef DEBUG
334         printf("failure: add watchpoints addr %x wf %u len %u\n", addr, wf, len);
335         #endif
336         return -1;
337 }
338
339 static int delete_data_watchpoint(stlink_t *sl, stm32_addr_t addr)
340 {
341         int i;
342
343         for(i = 0 ; i < DATA_WATCH_NUM; i++) {
344                 if((data_watches[i].addr == addr) && (data_watches[i].fun != WATCHDISABLED)) {
345                         #ifdef DEBUG
346                         printf("delete watchpoint %d addr %x\n", i, addr);
347                         #endif
348
349                         memset(sl->q_buf, 0, 4);
350                         data_watches[i].fun = WATCHDISABLED;
351                         stlink_write_mem32(sl, 0xe0001028 + i * 16, 4);
352
353                         return 0;
354                 }
355         }
356
357         #ifdef DEBUG
358         printf("failure: delete watchpoint addr %x\n", addr);
359         #endif
360
361         return -1;
362 }
363
364 #define CODE_BREAK_NUM  6
365 #define CODE_BREAK_LOW  0x01
366 #define CODE_BREAK_HIGH 0x02
367
368 struct code_hw_breakpoint {
369         stm32_addr_t addr;
370         int          type;
371 };
372
373 struct code_hw_breakpoint code_breaks[CODE_BREAK_NUM];
374
375 static void init_code_breakpoints(stlink_t *sl) {
376         memset(sl->q_buf, 0, 4);
377         sl->q_buf[0] = 0x03; // KEY | ENABLE
378         stlink_write_mem32(sl, CM3_REG_FP_CTRL, 4);
379         printf("KARL - should read back as 0x03, not 60 02 00 00\n");
380         stlink_read_mem32(sl, CM3_REG_FP_CTRL, 4);
381
382         memset(sl->q_buf, 0, 4);
383         for(int i = 0; i < CODE_BREAK_NUM; i++) {
384                 code_breaks[i].type = 0;
385                 stlink_write_mem32(sl, CM3_REG_FP_COMP0 + i * 4, 4);
386         }
387 }
388
389 static int update_code_breakpoint(stlink_t *sl, stm32_addr_t addr, int set) {
390         stm32_addr_t fpb_addr = addr & ~0x3;
391         int type = addr & 0x2 ? CODE_BREAK_HIGH : CODE_BREAK_LOW;
392
393         if(addr & 1) {
394                 fprintf(stderr, "update_code_breakpoint: unaligned address %08x\n", addr);
395                 return -1;
396         }
397
398         int id = -1;
399         for(int i = 0; i < CODE_BREAK_NUM; i++) {
400                 if(fpb_addr == code_breaks[i].addr ||
401                         (set && code_breaks[i].type == 0)) {
402                         id = i;
403                         break;
404                 }
405         }
406
407         if(id == -1) {
408                 if(set) return -1; // Free slot not found
409                 else    return 0;  // Breakpoint is already removed
410         }
411
412         struct code_hw_breakpoint* brk = &code_breaks[id];
413
414         brk->addr = fpb_addr;
415
416         if(set) brk->type |= type;
417         else    brk->type &= ~type;
418
419         memset(sl->q_buf, 0, 4);
420
421         if(brk->type == 0) {
422                 #ifdef DEBUG
423                 printf("clearing hw break %d\n", id);
424                 #endif
425
426                 stlink_write_mem32(sl, 0xe0002008 + id * 4, 4);
427         } else {
428                 sl->q_buf[0] = ( brk->addr        & 0xff) | 1;
429                 sl->q_buf[1] = ((brk->addr >> 8)  & 0xff);
430                 sl->q_buf[2] = ((brk->addr >> 16) & 0xff);
431                 sl->q_buf[3] = ((brk->addr >> 24) & 0xff) | (brk->type << 6);
432
433                 #ifdef DEBUG
434                 printf("setting hw break %d at %08x (%d)\n",
435                         id, brk->addr, brk->type);
436                 printf("reg %02x %02x %02x %02x\n",
437                         sl->q_buf[3], sl->q_buf[2], sl->q_buf[1], sl->q_buf[0]);
438                 #endif
439
440                 stlink_write_mem32(sl, 0xe0002008 + id * 4, 4);
441         }
442
443         return 0;
444 }
445
446
447 struct flash_block {
448         stm32_addr_t addr;
449         unsigned     length;
450         uint8_t*     data;
451
452         struct flash_block* next;
453 };
454
455 static struct flash_block* flash_root;
456
457 static int flash_add_block(stm32_addr_t addr, unsigned length, 
458                            stlink_t *sl) {
459         if(addr < FLASH_BASE || addr + length > FLASH_BASE + FLASH_SIZE) {
460                 fprintf(stderr, "flash_add_block: incorrect bounds\n");
461                 return -1;
462         }
463
464         if(addr % FLASH_PAGE != 0 || length % FLASH_PAGE != 0) {
465                 fprintf(stderr, "flash_add_block: unaligned block\n");
466                 return -1;
467         }
468
469         struct flash_block* new = malloc(sizeof(struct flash_block));
470         new->next = flash_root;
471
472         new->addr   = addr;
473         new->length = length;
474         new->data   = calloc(length, 1);
475
476         flash_root = new;
477
478         return 0;
479 }
480
481 static int flash_populate(stm32_addr_t addr, uint8_t* data, unsigned length) {
482         int fit_blocks = 0, fit_length = 0;
483
484         for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
485                 /* Block: ------X------Y--------
486                  * Data:            a-----b
487                  *                a--b
488                  *            a-----------b
489                  * Block intersects with data, if:
490                  *  a < Y && b > x
491                  */
492
493                 unsigned X = fb->addr, Y = fb->addr + fb->length;
494                 unsigned a = addr, b = addr + length;
495                 if(a < Y && b > X) {
496                         // from start of the block
497                         unsigned start = (a > X ? a : X) - X;
498                         unsigned end   = (b > Y ? Y : b) - X;
499
500                         memcpy(fb->data + start, data, end - start);
501
502                         fit_blocks++;
503                         fit_length += end - start;
504                 }
505         }
506
507         if(fit_blocks == 0) {
508                 fprintf(stderr, "Unfit data block %08x -> %04x\n", addr, length);
509                 return -1;
510         }
511
512         if(fit_length != length) {
513                 fprintf(stderr, "warning: data block %08x -> %04x truncated to %04x\n",
514                         addr, length, fit_length);
515                 fprintf(stderr, "(this is not an error, just a GDB glitch)\n");
516         }
517
518         return 0;
519 }
520
521 static int flash_go(stlink_t *sl) {
522         int error = -1;
523
524         // Some kinds of clock settings do not allow writing to flash.
525         stlink_reset(sl);
526
527         for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
528                 #ifdef DEBUG
529                 printf("flash_do: block %08x -> %04x\n", fb->addr, fb->length);
530                 #endif
531
532                 unsigned length = fb->length;
533                 for(stm32_addr_t page = fb->addr; page < fb->addr + fb->length; page += FLASH_PAGE) {
534                         #ifdef DEBUG
535                         printf("flash_do: page %08x\n", page);
536                         #endif
537
538                         stlink_erase_flash_page(sl, page);
539
540                         if(stlink_write_flash(sl, page, fb->data + (page - fb->addr),
541                                         length > FLASH_PAGE ? FLASH_PAGE : length) < 0)
542                                 goto error;
543                 }
544
545         }
546
547         stlink_reset(sl);
548
549         error = 0;
550
551 error:
552         for(struct flash_block* fb = flash_root, *next; fb; fb = next) {
553                 next = fb->next;
554                 free(fb->data);
555                 free(fb);
556         }
557
558         flash_root = NULL;
559
560         return error;
561 }
562
563 int serve(stlink_t *sl, int port) {
564         int sock = socket(AF_INET, SOCK_STREAM, 0);
565         if(sock < 0) {
566                 perror("socket");
567                 return 1;
568         }
569
570         unsigned int val = 1;
571         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
572
573         struct sockaddr_in serv_addr = {0};
574         serv_addr.sin_family = AF_INET;
575         serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
576         serv_addr.sin_port = htons(port);
577
578         if(bind(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
579                 perror("bind");
580                 return 1;
581         }
582
583         if(listen(sock, 5) < 0) {
584                 perror("listen");
585                 return 1;
586         }
587
588         stlink_force_debug(sl);
589         stlink_reset(sl);
590         init_code_breakpoints(sl);
591         init_data_watchpoints(sl);
592
593         printf("Listening at *:%d...\n", port);
594
595         int client = accept(sock, NULL, NULL);
596         signal (SIGINT, SIG_DFL);
597         if(client < 0) {
598                 perror("accept");
599                 return 1;
600         }
601
602         close(sock);
603
604         printf("GDB connected.\n");
605
606         /*
607          * To allow resetting the chip from GDB it is required to
608          * emulate attaching and detaching to target.
609          */
610         unsigned int attached = 1;
611
612         while(1) {
613                 char* packet;
614
615                 int status = gdb_recv_packet(client, &packet);
616                 if(status < 0) {
617                         fprintf(stderr, "cannot recv: %d\n", status);
618                         return 1;
619                 }
620
621                 #ifdef DEBUG
622                 printf("recv: %s\n", packet);
623                 #endif
624
625                 char* reply = NULL;
626                 reg regp;
627
628                 switch(packet[0]) {
629                 case 'q': {
630                         if(packet[1] == 'P' || packet[1] == 'C' || packet[1] == 'L') {
631                                 reply = strdup("");
632                                 break;
633                         }
634
635                         char *separator = strstr(packet, ":"), *params = "";
636                         if(separator == NULL) {
637                                 separator = packet + strlen(packet);
638                         } else {
639                                 params = separator + 1;
640                         }
641
642                         unsigned queryNameLength = (separator - &packet[1]);
643                         char* queryName = calloc(queryNameLength + 1, 1);
644                         strncpy(queryName, &packet[1], queryNameLength);
645
646                         #ifdef DEBUG
647                         printf("query: %s;%s\n", queryName, params);
648                         #endif
649
650                         if(!strcmp(queryName, "Supported")) {
651                                 reply = strdup("PacketSize=3fff;qXfer:memory-map:read+");
652                         } else if(!strcmp(queryName, "Xfer")) {
653                                 char *type, *op, *s_addr, *s_length;
654                                 char *tok = params;
655                                 char *annex __attribute__((unused));
656
657                                 type     = strsep(&tok, ":");
658                                 op       = strsep(&tok, ":");
659                                 annex    = strsep(&tok, ":");
660                                 s_addr   = strsep(&tok, ",");
661                                 s_length = tok;
662
663                                 unsigned addr = strtoul(s_addr, NULL, 16),
664                                        length = strtoul(s_length, NULL, 16);
665
666                                 #ifdef DEBUG
667                                 printf("Xfer: type:%s;op:%s;annex:%s;addr:%d;length:%d\n",
668                                         type, op, annex, addr, length);
669                                 #endif
670
671                                 const char* data = NULL;
672
673                                 if(!strcmp(type, "memory-map") && !strcmp(op, "read"))
674                                         data = current_memory_map;
675
676                                 if(data) {
677                                         unsigned data_length = strlen(data);
678                                         if(addr + length > data_length)
679                                                 length = data_length - addr;
680
681                                         if(length == 0) {
682                                                 reply = strdup("l");
683                                         } else {
684                                                 reply = calloc(length + 2, 1);
685                                                 reply[0] = 'm';
686                                                 strncpy(&reply[1], data, length);
687                                         }
688                                 }
689                         }
690
691                         if(reply == NULL)
692                                 reply = strdup("");
693
694                         free(queryName);
695
696                         break;
697                 }
698
699                 case 'v': {
700                         char *params = NULL;
701                         char *cmdName = strtok_r(packet, ":;", &params);
702
703                         cmdName++; // vCommand -> Command
704
705                         if(!strcmp(cmdName, "FlashErase")) {
706                                 char *s_addr, *s_length;
707                                 char *tok = params;
708
709                                 s_addr   = strsep(&tok, ",");
710                                 s_length = tok;
711
712                                 unsigned addr = strtoul(s_addr, NULL, 16),
713                                        length = strtoul(s_length, NULL, 16);
714
715                                 #ifdef DEBUG
716                                 printf("FlashErase: addr:%08x,len:%04x\n",
717                                         addr, length);
718                                 #endif
719
720                                 if(flash_add_block(addr, length, sl) < 0) {
721                                         reply = strdup("E00");
722                                 } else {
723                                         reply = strdup("OK");
724                                 }
725                         } else if(!strcmp(cmdName, "FlashWrite")) {
726                                 char *s_addr, *data;
727                                 char *tok = params;
728
729                                 s_addr = strsep(&tok, ":");
730                                 data   = tok;
731
732                                 unsigned addr = strtoul(s_addr, NULL, 16);
733                                 unsigned data_length = status - (data - packet);
734
735                                 // Length of decoded data cannot be more than
736                                 // encoded, as escapes are removed.
737                                 // Additional byte is reserved for alignment fix.
738                                 uint8_t *decoded = calloc(data_length + 1, 1);
739                                 unsigned dec_index = 0;
740                                 for(int i = 0; i < data_length; i++) {
741                                         if(data[i] == 0x7d) {
742                                                 i++;
743                                                 decoded[dec_index++] = data[i] ^ 0x20;
744                                         } else {
745                                                 decoded[dec_index++] = data[i];
746                                         }
747                                 }
748
749                                 // Fix alignment
750                                 if(dec_index % 2 != 0)
751                                         dec_index++;
752
753                                 #ifdef DEBUG
754                                 printf("binary packet %d -> %d\n", data_length, dec_index);
755                                 #endif
756
757                                 if(flash_populate(addr, decoded, dec_index) < 0) {
758                                         reply = strdup("E00");
759                                 } else {
760                                         reply = strdup("OK");
761                                 }
762                         } else if(!strcmp(cmdName, "FlashDone")) {
763                                 if(flash_go(sl) < 0) {
764                                         reply = strdup("E00");
765                                 } else {
766                                         reply = strdup("OK");
767                                 }
768                         } else if(!strcmp(cmdName, "Kill")) {
769                                 attached = 0;
770
771                                 reply = strdup("OK");
772                         }
773
774                         if(reply == NULL)
775                                 reply = strdup("");
776
777                         break;
778                 }
779
780                 case 'c':
781                         stlink_run(sl);
782
783                         while(1) {
784                                 int status = gdb_check_for_interrupt(client);
785                                 if(status < 0) {
786                                         fprintf(stderr, "cannot check for int: %d\n", status);
787                                         return 1;
788                                 }
789
790                                 if(status == 1) {
791                                         stlink_force_debug(sl);
792                                         break;
793                                 }
794
795                                 stlink_status(sl);
796                                 if(sl->core_stat == STLINK_CORE_HALTED) {
797                                         break;
798                                 }
799
800                                 usleep(100000);
801                         }
802
803                         reply = strdup("S05"); // TRAP
804                         break;
805
806                 case 's':
807                         stlink_step(sl);
808
809                         reply = strdup("S05"); // TRAP
810                         break;
811
812                 case '?':
813                         if(attached) {
814                                 reply = strdup("S05"); // TRAP
815                         } else {
816                                 /* Stub shall reply OK if not attached. */
817                                 reply = strdup("OK");
818                         }
819                         break;
820
821                 case 'g':
822                         stlink_read_all_regs(sl, &regp);
823
824                         reply = calloc(8 * 16 + 1, 1);
825                         for(int i = 0; i < 16; i++)
826                                 sprintf(&reply[i * 8], "%08x", htonl(regp.r[i]));
827
828                         break;
829
830                 case 'p': {
831                         unsigned id = strtoul(&packet[1], NULL, 16);
832                         unsigned myreg = 0xDEADDEAD;
833
834                         if(id < 16) {
835                                 stlink_read_reg(sl, id, &regp);
836                                 myreg = htonl(regp.r[id]);
837                         } else if(id == 0x19) {
838                                 stlink_read_reg(sl, 16, &regp);
839                                 myreg = htonl(regp.xpsr);
840                         } else {
841                                 reply = strdup("E00");
842                         }
843
844                         reply = calloc(8 + 1, 1);
845                         sprintf(reply, "%08x", myreg);
846
847                         break;
848                 }
849
850                 case 'P': {
851                         char* s_reg = &packet[1];
852                         char* s_value = strstr(&packet[1], "=") + 1;
853
854                         unsigned reg   = strtoul(s_reg,   NULL, 16);
855                         unsigned value = strtoul(s_value, NULL, 16);
856
857                         if(reg < 16) {
858                                 stlink_write_reg(sl, ntohl(value), reg);
859                         } else if(reg == 0x19) {
860                                 stlink_write_reg(sl, ntohl(value), 16);
861                         } else {
862                                 reply = strdup("E00");
863                         }
864
865                         if(!reply) {
866                                 reply = strdup("OK");
867                         }
868
869                         break;
870                 }
871
872                 case 'G':
873                         for(int i = 0; i < 16; i++) {
874                                 char str[9] = {0};
875                                 strncpy(str, &packet[1 + i * 8], 8);
876                                 uint32_t reg = strtoul(str, NULL, 16);
877                                 stlink_write_reg(sl, ntohl(reg), i);
878                         }
879
880                         reply = strdup("OK");
881                         break;
882
883                 case 'm': {
884                         char* s_start = &packet[1];
885                         char* s_count = strstr(&packet[1], ",") + 1;
886
887                         stm32_addr_t start = strtoul(s_start, NULL, 16);
888                         unsigned     count = strtoul(s_count, NULL, 16);
889
890                         unsigned adj_start = start % 4;
891
892                         stlink_read_mem32(sl, start - adj_start, (count % 4 == 0) ?
893                                                 count : count + 4 - (count % 4));
894
895                         reply = calloc(count * 2 + 1, 1);
896                         for(int i = 0; i < count; i++) {
897                                 reply[i * 2 + 0] = hex[sl->q_buf[i + adj_start] >> 4];
898                                 reply[i * 2 + 1] = hex[sl->q_buf[i + adj_start] & 0xf];
899                         }
900
901                         break;
902                 }
903
904                 case 'M': {
905                         char* s_start = &packet[1];
906                         char* s_count = strstr(&packet[1], ",") + 1;
907                         char* hexdata = strstr(packet, ":") + 1;
908
909                         stm32_addr_t start = strtoul(s_start, NULL, 16);
910                         unsigned     count = strtoul(s_count, NULL, 16);
911
912                         for(int i = 0; i < count; i ++) {
913                                 char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
914                                 uint8_t byte = strtoul(hex, NULL, 16);
915                                 sl->q_buf[i] = byte;
916                         }
917
918                         if((count % 4) == 0 && (start % 4) == 0) {
919                                 stlink_write_mem32(sl, start, count);
920                         } else {
921                                 stlink_write_mem8(sl, start, count);
922                         }
923
924                         reply = strdup("OK");
925
926                         break;
927                 }
928
929                 case 'Z': {
930                         char *endptr;
931                         stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
932                         stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
933
934                         switch (packet[1]) {
935                                 case '1':
936                                 if(update_code_breakpoint(sl, addr, 1) < 0) {
937                                         reply = strdup("E00");
938                                 } else {
939                                         reply = strdup("OK");
940                                 }
941                                 break;
942
943                                 case '2':   // insert write watchpoint
944                                 case '3':   // insert read  watchpoint
945                                 case '4':   // insert access watchpoint
946                                 {
947                                         enum watchfun wf;
948                                         if(packet[1] == '2') {
949                                                 wf = WATCHWRITE;
950                                         } else if(packet[1] == '3') {
951                                                 wf = WATCHREAD;
952                                         } else {
953                                                 wf = WATCHACCESS;
954                                                 if(add_data_watchpoint(sl, wf, addr, len) < 0) {
955                                                         reply = strdup("E00");
956                                                 } else {
957                                                         reply = strdup("OK");
958                                                         break;
959                                                 }
960                                         }
961                                 }
962
963                                 default:
964                                 reply = strdup("");
965                         }
966                         break;
967                 }
968                 case 'z': {
969                         char *endptr;
970                         stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
971                         //stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
972
973                         switch (packet[1]) {
974                                 case '1': // remove breakpoint
975                                 update_code_breakpoint(sl, addr, 0);
976                                 reply = strdup("OK");
977                                 break;
978
979                                 case '2' : // remove write watchpoint
980                                 case '3' : // remove read watchpoint
981                                 case '4' : // remove access watchpoint
982                                 if(delete_data_watchpoint(sl, addr) < 0) {
983                                         reply = strdup("E00");
984                                 } else {
985                                         reply = strdup("OK");
986                                         break;
987                                 }
988
989                                 default:
990                                 reply = strdup("");
991                         }
992                         break;
993                 }
994
995                 case '!': {
996                         /*
997                          * Enter extended mode which allows restarting.
998                          * We do support that always.
999                          */
1000
1001                         reply = strdup("OK");
1002
1003                         break;
1004                 }
1005
1006                 case 'R': {
1007                         /* Reset the core. */
1008
1009                         stlink_reset(sl);
1010                         init_code_breakpoints(sl);
1011                         init_data_watchpoints(sl);
1012
1013                         attached = 1;
1014
1015                         reply = strdup("OK");
1016
1017                         break;
1018                 }
1019
1020                 default:
1021                         reply = strdup("");
1022                 }
1023
1024                 if(reply) {
1025                         #ifdef DEBUG
1026                         printf("send: %s\n", reply);
1027                         #endif
1028
1029                         int result = gdb_send_packet(client, reply);
1030                         if(result != 0) {
1031                                 fprintf(stderr, "cannot send: %d\n", result);
1032                                 return 1;
1033                         }
1034
1035                         free(reply);
1036                 }
1037
1038                 free(packet);
1039         }
1040
1041         return 0;
1042 }