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