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