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