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