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