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