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