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