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