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