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