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