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