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