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