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