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