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