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