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