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