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