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