[ update ] bind gdb server on INADDR_ANY, as requested by thomas@popp.ws
[fw/stlink] / gdbserver / gdb-server.c
1 /* -*- tab-width:8 -*- */
2 #define DEBUG 0
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 #ifdef __MINGW32__
16 #include "mingw.h"
17 #else
18 #include <sys/socket.h>
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
21 #include <signal.h>
22 #endif
23
24 #include <stlink-common.h>
25
26 #include "gdb-remote.h"
27
28 #define DEFAULT_LOGGING_LEVEL 50
29 #define DEFAULT_GDB_LISTEN_PORT 4242
30
31 #define STRINGIFY_inner(name) #name
32 #define STRINGIFY(name) STRINGIFY_inner(name)
33
34 #define FLASH_BASE 0x08000000
35
36 //Allways update the FLASH_PAGE before each use, by calling stlink_calculate_pagesize
37 #define FLASH_PAGE (sl->flash_pgsz)
38
39 stlink_t *connected_stlink = NULL;
40
41 static const char hex[] = "0123456789abcdef";
42
43 static const char* current_memory_map = NULL;
44
45 typedef struct _st_state_t {
46     // things from command line, bleh
47     int stlink_version;
48     // "/dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTE531X6-if00-port0" is only 58 chars
49     char devicename[100];
50     int logging_level;
51         int listen_port;
52     int persistent;
53 } st_state_t;
54
55
56 int serve(stlink_t *sl, st_state_t *st);
57 char* make_memory_map(stlink_t *sl);
58
59 static void cleanup(int signal __attribute__((unused))) {
60     if (connected_stlink) {
61         /* Switch back to mass storage mode before closing. */
62         stlink_run(connected_stlink);
63         stlink_exit_debug_mode(connected_stlink);
64         stlink_close(connected_stlink);
65     }
66
67     exit(1);
68 }
69
70 int parse_options(int argc, char** argv, st_state_t *st) {
71     static struct option long_options[] = {
72         {"help", no_argument, NULL, 'h'},
73         {"verbose", optional_argument, NULL, 'v'},
74         {"device", required_argument, NULL, 'd'},
75         {"stlink_version", required_argument, NULL, 's'},
76         {"stlinkv1", no_argument, NULL, '1'},
77                 {"listen_port", required_argument, NULL, 'p'},
78                 {"multi", optional_argument, NULL, 'm'},
79         {0, 0, 0, 0},
80     };
81         const char * help_str = "%s - usage:\n\n"
82         "  -h, --help\t\tPrint this help\n"
83         "  -vXX, --verbose=XX\tspecify a specific verbosity level (0..99)\n"
84         "  -v, --verbose\tspecify generally verbose logging\n"
85         "  -d <device>, --device=/dev/stlink2_1\n"
86         "\t\t\tWhere is your stlink device connected?\n"
87         "  -s X, --stlink_version=X\n"
88         "\t\t\tChoose what version of stlink to use, (defaults to 2)\n"
89         "  -1, --stlinkv1\tForce stlink version 1\n"
90         "  -p 4242, --listen_port=1234\n"
91         "\t\t\tSet the gdb server listen port. "
92         "(default port: " STRINGIFY(DEFAULT_GDB_LISTEN_PORT) ")\n"
93     "  -m, --multi\n"
94     "\t\t\tSet gdb server to extended mode.\n"
95     "\t\t\tst-util will continue listening for connections after disconnect.\n"
96         ;
97
98
99     int option_index = 0;
100     int c;
101     int q;
102     while ((c = getopt_long(argc, argv, "hv::d:s:1p:m", long_options, &option_index)) != -1) {
103         switch (c) {
104         case 0:
105             printf("XXXXX Shouldn't really normally come here, only if there's no corresponding option\n");
106             printf("option %s", long_options[option_index].name);
107             if (optarg) {
108                 printf(" with arg %s", optarg);
109             }
110             printf("\n");
111             break;
112         case 'h':
113             printf(help_str, argv[0]);
114             exit(EXIT_SUCCESS);
115             break;
116         case 'v':
117             if (optarg) {
118                 st->logging_level = atoi(optarg);
119             } else {
120                 st->logging_level = DEFAULT_LOGGING_LEVEL;
121             }
122             break;
123         case 'd':
124             if (strlen(optarg) > sizeof (st->devicename)) {
125                 fprintf(stderr, "device name too long: %zd\n", strlen(optarg));
126             } else {
127                 strcpy(st->devicename, optarg);
128             }
129             break;
130                 case '1':
131                         st->stlink_version = 1;
132                         break;
133                 case 's':
134                         sscanf(optarg, "%i", &q);
135                         if (q < 0 || q > 2) {
136                                 fprintf(stderr, "stlink version %d unknown!\n", q);
137                                 exit(EXIT_FAILURE);
138                         }
139                         st->stlink_version = q;
140                         break;
141                 case 'p':
142                         sscanf(optarg, "%i", &q);
143                         if (q < 0) {
144                                 fprintf(stderr, "Can't use a negative port to listen on: %d\n", q);
145                                 exit(EXIT_FAILURE);
146                         }
147                         st->listen_port = q;
148                         break;
149                 case 'm':
150                         st->persistent = 1;
151                         break;
152         }
153     }
154
155     if (optind < argc) {
156         printf("non-option ARGV-elements: ");
157         while (optind < argc)
158             printf("%s ", argv[optind++]);
159         printf("\n");
160     }
161     return 0;
162 }
163
164
165 int main(int argc, char** argv) {
166
167         stlink_t *sl = NULL;
168
169         st_state_t state;
170         memset(&state, 0, sizeof(state));
171         // set defaults...
172         state.stlink_version = 2;
173         state.logging_level = DEFAULT_LOGGING_LEVEL;
174         state.listen_port = DEFAULT_GDB_LISTEN_PORT;
175         parse_options(argc, argv, &state);
176         switch (state.stlink_version) {
177         case 2:
178                 sl = stlink_open_usb(state.logging_level);
179                 if(sl == NULL) return 1;
180                 break;
181         case 1:
182                 sl = stlink_v1_open(state.logging_level);
183                 if(sl == NULL) return 1;
184                 break;
185     }
186
187     connected_stlink = sl;
188     signal(SIGINT, &cleanup);
189
190         printf("Chip ID is %08x, Core ID is  %08x.\n", sl->chip_id, sl->core_id);
191
192         sl->verbose=0;
193
194         current_memory_map = make_memory_map(sl);
195
196 #ifdef __MINGW32__
197         WSADATA wsadata;
198         if (WSAStartup(MAKEWORD(2,2),&wsadata) !=0 ) {
199                 goto winsock_error;
200         }
201 #endif
202
203         do {
204                 serve(sl, &state);
205         } while (state.persistent);
206
207 #ifdef __MINGW32__
208 winsock_error:
209         WSACleanup();
210 #endif
211
212         /* Switch back to mass storage mode before closing. */
213         stlink_run(sl);
214         stlink_exit_debug_mode(sl);
215         stlink_close(sl);
216
217         return 0;
218 }
219
220 static const char* const target_description_F4 =
221     "<?xml version=\"1.0\"?>"
222     "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
223     "<target version=\"1.0\">"
224     "   <architecture>arm</architecture>"
225     "   <feature name=\"org.gnu.gdb.arm.m-profile\">"
226     "       <reg name=\"r0\" bitsize=\"32\"/>"
227     "       <reg name=\"r1\" bitsize=\"32\"/>"
228     "       <reg name=\"r2\" bitsize=\"32\"/>"
229     "       <reg name=\"r3\" bitsize=\"32\"/>"
230     "       <reg name=\"r4\" bitsize=\"32\"/>"
231     "       <reg name=\"r5\" bitsize=\"32\"/>"
232     "       <reg name=\"r6\" bitsize=\"32\"/>"
233     "       <reg name=\"r7\" bitsize=\"32\"/>"
234     "       <reg name=\"r8\" bitsize=\"32\"/>"
235     "       <reg name=\"r9\" bitsize=\"32\"/>"
236     "       <reg name=\"r10\" bitsize=\"32\"/>"
237     "       <reg name=\"r11\" bitsize=\"32\"/>"
238     "       <reg name=\"r12\" bitsize=\"32\"/>"
239     "       <reg name=\"sp\" bitsize=\"32\" type=\"data_ptr\"/>"
240     "       <reg name=\"lr\" bitsize=\"32\"/>"
241     "       <reg name=\"pc\" bitsize=\"32\" type=\"code_ptr\"/>"
242     "       <reg name=\"xpsr\" bitsize=\"32\" regnum=\"25\"/>"
243     "       <reg name=\"msp\" bitsize=\"32\" regnum=\"26\" type=\"data_ptr\" group=\"general\" />"
244     "       <reg name=\"psp\" bitsize=\"32\" regnum=\"27\" type=\"data_ptr\" group=\"general\" />"
245     "       <reg name=\"control\" bitsize=\"8\" regnum=\"28\" type=\"int\" group=\"general\" />"
246     "       <reg name=\"faultmask\" bitsize=\"8\" regnum=\"29\" type=\"int\" group=\"general\" />"
247     "       <reg name=\"basepri\" bitsize=\"8\" regnum=\"30\" type=\"int\" group=\"general\" />"
248     "       <reg name=\"primask\" bitsize=\"8\" regnum=\"31\" type=\"int\" group=\"general\" />"
249     "       <reg name=\"s0\" bitsize=\"32\" regnum=\"32\" type=\"float\" group=\"float\" />"
250     "       <reg name=\"s1\" bitsize=\"32\" type=\"float\" group=\"float\" />"
251     "       <reg name=\"s2\" bitsize=\"32\" type=\"float\" group=\"float\" />"
252     "       <reg name=\"s3\" bitsize=\"32\" type=\"float\" group=\"float\" />"
253     "       <reg name=\"s4\" bitsize=\"32\" type=\"float\" group=\"float\" />"
254     "       <reg name=\"s5\" bitsize=\"32\" type=\"float\" group=\"float\" />"
255     "       <reg name=\"s6\" bitsize=\"32\" type=\"float\" group=\"float\" />"
256     "       <reg name=\"s7\" bitsize=\"32\" type=\"float\" group=\"float\" />"
257     "       <reg name=\"s8\" bitsize=\"32\" type=\"float\" group=\"float\" />"
258     "       <reg name=\"s9\" bitsize=\"32\" type=\"float\" group=\"float\" />"
259     "       <reg name=\"s10\" bitsize=\"32\" type=\"float\" group=\"float\" />"
260     "       <reg name=\"s11\" bitsize=\"32\" type=\"float\" group=\"float\" />"
261     "       <reg name=\"s12\" bitsize=\"32\" type=\"float\" group=\"float\" />"
262     "       <reg name=\"s13\" bitsize=\"32\" type=\"float\" group=\"float\" />"
263     "       <reg name=\"s14\" bitsize=\"32\" type=\"float\" group=\"float\" />"
264     "       <reg name=\"s15\" bitsize=\"32\" type=\"float\" group=\"float\" />"
265     "       <reg name=\"s16\" bitsize=\"32\" type=\"float\" group=\"float\" />"
266     "       <reg name=\"s17\" bitsize=\"32\" type=\"float\" group=\"float\" />"
267     "       <reg name=\"s18\" bitsize=\"32\" type=\"float\" group=\"float\" />"
268     "       <reg name=\"s19\" bitsize=\"32\" type=\"float\" group=\"float\" />"
269     "       <reg name=\"s20\" bitsize=\"32\" type=\"float\" group=\"float\" />"
270     "       <reg name=\"s21\" bitsize=\"32\" type=\"float\" group=\"float\" />"
271     "       <reg name=\"s22\" bitsize=\"32\" type=\"float\" group=\"float\" />"
272     "       <reg name=\"s23\" bitsize=\"32\" type=\"float\" group=\"float\" />"
273     "       <reg name=\"s24\" bitsize=\"32\" type=\"float\" group=\"float\" />"
274     "       <reg name=\"s25\" bitsize=\"32\" type=\"float\" group=\"float\" />"
275     "       <reg name=\"s26\" bitsize=\"32\" type=\"float\" group=\"float\" />"
276     "       <reg name=\"s27\" bitsize=\"32\" type=\"float\" group=\"float\" />"
277     "       <reg name=\"s28\" bitsize=\"32\" type=\"float\" group=\"float\" />"
278     "       <reg name=\"s29\" bitsize=\"32\" type=\"float\" group=\"float\" />"
279     "       <reg name=\"s30\" bitsize=\"32\" type=\"float\" group=\"float\" />"
280     "       <reg name=\"s31\" bitsize=\"32\" type=\"float\" group=\"float\" />"
281     "       <reg name=\"fpscr\" bitsize=\"32\" type=\"int\" group=\"float\" />"
282     "   </feature>"
283     "</target>";
284
285 static const char* const memory_map_template_F4 =
286   "<?xml version=\"1.0\"?>"
287   "<!DOCTYPE memory-map PUBLIC \"+//IDN gnu.org//DTD GDB Memory Map V1.0//EN\""
288   "     \"http://sourceware.org/gdb/gdb-memory-map.dtd\">"
289   "<memory-map>"
290   "  <memory type=\"rom\" start=\"0x00000000\" length=\"0x100000\"/>"       // code = sram, bootrom or flash; flash is bigger
291   "  <memory type=\"ram\" start=\"0x10000000\" length=\"0x10000\"/>"        // ccm ram
292   "  <memory type=\"ram\" start=\"0x20000000\" length=\"0x20000\"/>"        // sram
293   "  <memory type=\"flash\" start=\"0x08000000\" length=\"0x10000\">"           //Sectors 0..3
294   "    <property name=\"blocksize\">0x4000</property>"                                          //16kB
295   "  </memory>"
296   "  <memory type=\"flash\" start=\"0x08010000\" length=\"0x10000\">"           //Sector 4
297   "    <property name=\"blocksize\">0x10000</property>"                                         //64kB
298   "  </memory>"
299   "  <memory type=\"flash\" start=\"0x08020000\" length=\"0x70000\">"           //Sectors 5..11
300   "    <property name=\"blocksize\">0x20000</property>"                                         //128kB
301   "  </memory>"
302   "  <memory type=\"ram\" start=\"0x40000000\" length=\"0x1fffffff\"/>"         // peripheral regs
303   "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>"         // cortex regs
304   "  <memory type=\"rom\" start=\"0x1fff0000\" length=\"0x7800\"/>"         // bootrom
305   "  <memory type=\"rom\" start=\"0x1fffc000\" length=\"0x10\"/>"               // option byte area
306   "</memory-map>";
307
308 static const char* const memory_map_template =
309   "<?xml version=\"1.0\"?>"
310   "<!DOCTYPE memory-map PUBLIC \"+//IDN gnu.org//DTD GDB Memory Map V1.0//EN\""
311   "     \"http://sourceware.org/gdb/gdb-memory-map.dtd\">"
312   "<memory-map>"
313   "  <memory type=\"rom\" start=\"0x00000000\" length=\"0x%zx\"/>"       // code = sram, bootrom or flash; flash is bigger
314   "  <memory type=\"ram\" start=\"0x20000000\" length=\"0x%zx\"/>"       // sram 8k
315   "  <memory type=\"flash\" start=\"0x08000000\" length=\"0x%zx\">"
316   "    <property name=\"blocksize\">0x%zx</property>"
317   "  </memory>"
318   "  <memory type=\"ram\" start=\"0x40000000\" length=\"0x1fffffff\"/>" // peripheral regs
319   "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>" // cortex regs
320   "  <memory type=\"rom\" start=\"0x%08x\" length=\"0x%zx\"/>"           // bootrom
321   "  <memory type=\"rom\" start=\"0x1ffff800\" length=\"0x10\"/>"        // option byte area
322   "</memory-map>";
323
324 char* make_memory_map(stlink_t *sl) {
325         /* This will be freed in serve() */
326         char* map = malloc(4096);
327         map[0] = '\0';
328
329         if(sl->chip_id==STM32_CHIPID_F4) {
330         strcpy(map, memory_map_template_F4);
331     } else {
332         snprintf(map, 4096, memory_map_template,
333                         sl->flash_size,
334                         sl->sram_size,
335                         sl->flash_size, sl->flash_pgsz,
336                         sl->sys_base, sl->sys_size);
337     }
338         return map;
339 }
340
341
342 /*
343  * DWT_COMP0     0xE0001020
344  * DWT_MASK0     0xE0001024
345  * DWT_FUNCTION0 0xE0001028
346  * DWT_COMP1     0xE0001030
347  * DWT_MASK1     0xE0001034
348  * DWT_FUNCTION1 0xE0001038
349  * DWT_COMP2     0xE0001040
350  * DWT_MASK2     0xE0001044
351  * DWT_FUNCTION2 0xE0001048
352  * DWT_COMP3     0xE0001050
353  * DWT_MASK3     0xE0001054
354  * DWT_FUNCTION3 0xE0001058
355  */
356
357 #define DATA_WATCH_NUM 4
358
359 enum watchfun { WATCHDISABLED = 0, WATCHREAD = 5, WATCHWRITE = 6, WATCHACCESS = 7 };
360
361 struct code_hw_watchpoint {
362         stm32_addr_t addr;
363         uint8_t mask;
364         enum watchfun fun;
365 };
366
367 struct code_hw_watchpoint data_watches[DATA_WATCH_NUM];
368
369 static void init_data_watchpoints(stlink_t *sl) {
370         #ifdef DEBUG
371         printf("init watchpoints\n");
372         #endif
373
374         // set trcena in debug command to turn on dwt unit
375         stlink_write_debug32(sl, 0xE000EDFC,
376                              stlink_read_debug32(sl, 0xE000EDFC) | (1<<24));
377
378         // make sure all watchpoints are cleared
379         for(int i = 0; i < DATA_WATCH_NUM; i++) {
380                 data_watches[i].fun = WATCHDISABLED;
381                 stlink_write_debug32(sl, 0xe0001028 + i * 16, 0);
382         }
383 }
384
385 static int add_data_watchpoint(stlink_t *sl, enum watchfun wf, stm32_addr_t addr, unsigned int len)
386 {
387         int i = 0;
388         uint32_t mask;
389
390         // computer mask
391         // find a free watchpoint
392         // configure
393
394         mask = -1;
395         i = len;
396         while(i) {
397                 i >>= 1;
398                 mask++;
399         }
400
401         if((mask != (uint32_t)-1) && (mask < 16)) {
402                 for(i = 0; i < DATA_WATCH_NUM; i++) {
403                         // is this an empty slot ?
404                         if(data_watches[i].fun == WATCHDISABLED) {
405                                 #ifdef DEBUG
406                                 printf("insert watchpoint %d addr %x wf %u mask %u len %d\n", i, addr, wf, mask, len);
407                                 #endif
408
409                                 data_watches[i].fun = wf;
410                                 data_watches[i].addr = addr;
411                                 data_watches[i].mask = mask;
412
413                                 // insert comparator address
414                                 stlink_write_debug32(sl, 0xE0001020 + i * 16, addr);
415
416                                 // insert mask
417                                 stlink_write_debug32(sl, 0xE0001024 + i * 16, mask);
418
419                                 // insert function
420                                 stlink_write_debug32(sl, 0xE0001028 + i * 16, wf);
421
422                                 // just to make sure the matched bit is clear !
423                                 stlink_read_debug32(sl,  0xE0001028 + i * 16);
424                                 return 0;
425                         }
426                 }
427         }
428
429         #ifdef DEBUG
430         printf("failure: add watchpoints addr %x wf %u len %u\n", addr, wf, len);
431         #endif
432         return -1;
433 }
434
435 static int delete_data_watchpoint(stlink_t *sl, stm32_addr_t addr)
436 {
437         int i;
438
439         for(i = 0 ; i < DATA_WATCH_NUM; i++) {
440                 if((data_watches[i].addr == addr) && (data_watches[i].fun != WATCHDISABLED)) {
441                         #ifdef DEBUG
442                         printf("delete watchpoint %d addr %x\n", i, addr);
443                         #endif
444
445                         data_watches[i].fun = WATCHDISABLED;
446                         stlink_write_debug32(sl, 0xe0001028 + i * 16, 0);
447
448                         return 0;
449                 }
450         }
451
452         #ifdef DEBUG
453         printf("failure: delete watchpoint addr %x\n", addr);
454         #endif
455
456         return -1;
457 }
458
459 #define CODE_BREAK_NUM  6
460 #define CODE_BREAK_LOW  0x01
461 #define CODE_BREAK_HIGH 0x02
462
463 struct code_hw_breakpoint {
464         stm32_addr_t addr;
465         int          type;
466 };
467
468 struct code_hw_breakpoint code_breaks[CODE_BREAK_NUM];
469
470 static void init_code_breakpoints(stlink_t *sl) {
471         memset(sl->q_buf, 0, 4);
472         stlink_write_debug32(sl, CM3_REG_FP_CTRL, 0x03 /*KEY | ENABLE4*/);
473         printf("KARL - should read back as 0x03, not 60 02 00 00\n");
474         stlink_read_debug32(sl, CM3_REG_FP_CTRL);
475
476         for(int i = 0; i < CODE_BREAK_NUM; i++) {
477                 code_breaks[i].type = 0;
478                 stlink_write_debug32(sl, CM3_REG_FP_COMP0 + i * 4, 0);
479         }
480 }
481
482 static int update_code_breakpoint(stlink_t *sl, stm32_addr_t addr, int set) {
483         stm32_addr_t fpb_addr = addr & ~0x3;
484         int type = addr & 0x2 ? CODE_BREAK_HIGH : CODE_BREAK_LOW;
485
486         if(addr & 1) {
487                 fprintf(stderr, "update_code_breakpoint: unaligned address %08x\n", addr);
488                 return -1;
489         }
490
491         int id = -1;
492         for(int i = 0; i < CODE_BREAK_NUM; i++) {
493                 if(fpb_addr == code_breaks[i].addr ||
494                         (set && code_breaks[i].type == 0)) {
495                         id = i;
496                         break;
497                 }
498         }
499
500         if(id == -1) {
501                 if(set) return -1; // Free slot not found
502                 else    return 0;  // Breakpoint is already removed
503         }
504
505         struct code_hw_breakpoint* brk = &code_breaks[id];
506
507         brk->addr = fpb_addr;
508
509         if(set) brk->type |= type;
510         else    brk->type &= ~type;
511
512         if(brk->type == 0) {
513                 #ifdef DEBUG
514                 printf("clearing hw break %d\n", id);
515                 #endif
516
517                 stlink_write_debug32(sl, 0xe0002008 + id * 4, 0);
518         } else {
519                 uint32_t mask = (brk->addr) | 1 | (brk->type << 30);
520
521                 #ifdef DEBUG
522                 printf("setting hw break %d at %08x (%d)\n",
523                         id, brk->addr, brk->type);
524                 printf("reg %08x \n",
525                         mask);
526                 #endif
527
528                 stlink_write_debug32(sl, 0xe0002008 + id * 4, mask);
529         }
530
531         return 0;
532 }
533
534
535 struct flash_block {
536         stm32_addr_t addr;
537         unsigned     length;
538         uint8_t*     data;
539
540         struct flash_block* next;
541 };
542
543 static struct flash_block* flash_root;
544
545 static int flash_add_block(stm32_addr_t addr, unsigned length, stlink_t *sl) {
546
547         if(addr < FLASH_BASE || addr + length > FLASH_BASE + sl->flash_size) {
548                 fprintf(stderr, "flash_add_block: incorrect bounds\n");
549                 return -1;
550         }
551
552         stlink_calculate_pagesize(sl, addr);
553         if(addr % FLASH_PAGE != 0 || length % FLASH_PAGE != 0) {
554                 fprintf(stderr, "flash_add_block: unaligned block\n");
555                 return -1;
556         }
557
558         struct flash_block* new = malloc(sizeof(struct flash_block));
559         new->next = flash_root;
560
561         new->addr   = addr;
562         new->length = length;
563         new->data   = calloc(length, 1);
564
565         flash_root = new;
566
567         return 0;
568 }
569
570 static int flash_populate(stm32_addr_t addr, uint8_t* data, unsigned length) {
571         unsigned int fit_blocks = 0, fit_length = 0;
572
573         for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
574                 /* Block: ------X------Y--------
575                  * Data:            a-----b
576                  *                a--b
577                  *            a-----------b
578                  * Block intersects with data, if:
579                  *  a < Y && b > x
580                  */
581
582                 unsigned X = fb->addr, Y = fb->addr + fb->length;
583                 unsigned a = addr, b = addr + length;
584                 if(a < Y && b > X) {
585                         // from start of the block
586                         unsigned start = (a > X ? a : X) - X;
587                         unsigned end   = (b > Y ? Y : b) - X;
588
589                         memcpy(fb->data + start, data, end - start);
590
591                         fit_blocks++;
592                         fit_length += end - start;
593                 }
594         }
595
596         if(fit_blocks == 0) {
597                 fprintf(stderr, "Unfit data block %08x -> %04x\n", addr, length);
598                 return -1;
599         }
600
601         if(fit_length != length) {
602                 fprintf(stderr, "warning: data block %08x -> %04x truncated to %04x\n",
603                         addr, length, fit_length);
604                 fprintf(stderr, "(this is not an error, just a GDB glitch)\n");
605         }
606
607         return 0;
608 }
609
610 static int flash_go(stlink_t *sl) {
611         int error = -1;
612
613         // Some kinds of clock settings do not allow writing to flash.
614         stlink_reset(sl);
615
616         for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
617                 #ifdef DEBUG
618                 printf("flash_do: block %08x -> %04x\n", fb->addr, fb->length);
619                 #endif
620
621                 unsigned length = fb->length;
622                 for(stm32_addr_t page = fb->addr; page < fb->addr + fb->length; page += FLASH_PAGE) {
623
624                         //Update FLASH_PAGE
625                         stlink_calculate_pagesize(sl, page);
626
627                         #ifdef DEBUG
628                         printf("flash_do: page %08x\n", page);
629                         #endif
630
631                         if(stlink_write_flash(sl, page, fb->data + (page - fb->addr),
632                                         length > FLASH_PAGE ? FLASH_PAGE : length) < 0)
633                                 goto error;
634                         }
635         }
636
637         stlink_reset(sl);
638
639         error = 0;
640
641 error:
642         for(struct flash_block* fb = flash_root, *next; fb; fb = next) {
643                 next = fb->next;
644                 free(fb->data);
645                 free(fb);
646         }
647
648         flash_root = NULL;
649
650         return error;
651 }
652
653 int serve(stlink_t *sl, st_state_t *st) {
654         int sock = socket(AF_INET, SOCK_STREAM, 0);
655         if(sock < 0) {
656                 perror("socket");
657                 return 1;
658         }
659
660         unsigned int val = 1;
661         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
662
663         struct sockaddr_in serv_addr;
664         memset(&serv_addr,0,sizeof(struct sockaddr_in));
665         serv_addr.sin_family = AF_INET;
666         serv_addr.sin_addr.s_addr = INADDR_ANY;
667         serv_addr.sin_port = htons(st->listen_port);
668
669         if(bind(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
670                 perror("bind");
671                 return 1;
672         }
673
674         if(listen(sock, 5) < 0) {
675                 perror("listen");
676                 return 1;
677         }
678
679         stlink_force_debug(sl);
680         stlink_reset(sl);
681         init_code_breakpoints(sl);
682         init_data_watchpoints(sl);
683
684         printf("Listening at *:%d...\n", st->listen_port);
685
686         int client = accept(sock, NULL, NULL);
687         //signal (SIGINT, SIG_DFL);
688         if(client < 0) {
689                 perror("accept");
690                 return 1;
691         }
692
693         close(sock);
694
695         printf("GDB connected.\n");
696
697         /*
698          * To allow resetting the chip from GDB it is required to
699          * emulate attaching and detaching to target.
700          */
701         unsigned int attached = 1;
702
703         while(1) {
704                 char* packet;
705
706                 int status = gdb_recv_packet(client, &packet);
707                 if(status < 0) {
708                         fprintf(stderr, "cannot recv: %d\n", status);
709                         return 1;
710                 }
711
712                 #ifdef DEBUG
713                 printf("recv: %s\n", packet);
714                 #endif
715
716                 char* reply = NULL;
717                 reg regp;
718
719                 switch(packet[0]) {
720                 case 'q': {
721                         if(packet[1] == 'P' || packet[1] == 'C' || packet[1] == 'L') {
722                                 reply = strdup("");
723                                 break;
724                         }
725
726                         char *separator = strstr(packet, ":"), *params = "";
727                         if(separator == NULL) {
728                                 separator = packet + strlen(packet);
729                         } else {
730                                 params = separator + 1;
731                         }
732
733                         unsigned queryNameLength = (separator - &packet[1]);
734                         char* queryName = calloc(queryNameLength + 1, 1);
735                         strncpy(queryName, &packet[1], queryNameLength);
736
737                         #ifdef DEBUG
738                         printf("query: %s;%s\n", queryName, params);
739                         #endif
740
741                         if(!strcmp(queryName, "Supported")) {
742                 if(sl->chip_id==STM32_CHIPID_F4) {
743                     reply = strdup("PacketSize=3fff;qXfer:memory-map:read+;qXfer:features:read+");
744                 }
745                 else {
746                     reply = strdup("PacketSize=3fff;qXfer:memory-map:read+");
747                 }
748                         } else if(!strcmp(queryName, "Xfer")) {
749                                 char *type, *op, *__s_addr, *s_length;
750                                 char *tok = params;
751                                 char *annex __attribute__((unused));
752
753                                 type     = strsep(&tok, ":");
754                                 op       = strsep(&tok, ":");
755                                 annex    = strsep(&tok, ":");
756                                 __s_addr   = strsep(&tok, ",");
757                                 s_length = tok;
758
759                                 unsigned addr = strtoul(__s_addr, NULL, 16),
760                                        length = strtoul(s_length, NULL, 16);
761
762                                 #ifdef DEBUG
763                                 printf("Xfer: type:%s;op:%s;annex:%s;addr:%d;length:%d\n",
764                                         type, op, annex, addr, length);
765                                 #endif
766
767                                 const char* data = NULL;
768
769                                 if(!strcmp(type, "memory-map") && !strcmp(op, "read"))
770                                         data = current_memory_map;
771
772                                 if(!strcmp(type, "features") && !strcmp(op, "read"))
773                                         data = target_description_F4;
774
775                                 if(data) {
776                                         unsigned data_length = strlen(data);
777                                         if(addr + length > data_length)
778                                                 length = data_length - addr;
779
780                                         if(length == 0) {
781                                                 reply = strdup("l");
782                                         } else {
783                                                 reply = calloc(length + 2, 1);
784                                                 reply[0] = 'm';
785                                                 strncpy(&reply[1], data, length);
786                                         }
787                                 }
788                         } else if(!strncmp(queryName, "Rcmd,",4)) {
789                                 // Rcmd uses the wrong separator
790                                 char *separator = strstr(packet, ","), *params = "";
791                                 if(separator == NULL) {
792                                         separator = packet + strlen(packet);
793                                 } else {
794                                         params = separator + 1;
795                                 }
796
797
798                                 if (!strncmp(params,"726573756d65",12)) {// resume
799 #ifdef DEBUG
800                                         printf("Rcmd: resume\n");
801 #endif
802                                         stlink_run(sl);
803
804                                         reply = strdup("OK");
805                 } else if (!strncmp(params,"68616c74",8)) { //halt
806                                         reply = strdup("OK");
807
808                                         stlink_force_debug(sl);
809
810 #ifdef DEBUG
811                                         printf("Rcmd: halt\n");
812 #endif
813                 } else if (!strncmp(params,"6a7461675f7265736574",20)) { //jtag_reset
814                                         reply = strdup("OK");
815
816                                         stlink_jtag_reset(sl, 1);
817                                         stlink_jtag_reset(sl, 0);
818                                         stlink_force_debug(sl);
819
820 #ifdef DEBUG
821                                         printf("Rcmd: jtag_reset\n");
822 #endif
823                 } else if (!strncmp(params,"7265736574",10)) { //reset
824                                         reply = strdup("OK");
825
826                                         stlink_force_debug(sl);
827                                         stlink_reset(sl);
828                                         init_code_breakpoints(sl);
829                                         init_data_watchpoints(sl);
830
831 #ifdef DEBUG
832                                         printf("Rcmd: reset\n");
833 #endif
834                                 } else {
835 #ifdef DEBUG
836                                         printf("Rcmd: %s\n", params);
837 #endif
838
839                                 }
840
841                         }
842
843                         if(reply == NULL)
844                                 reply = strdup("");
845
846                         free(queryName);
847
848                         break;
849                 }
850
851                 case 'v': {
852                         char *params = NULL;
853                         char *cmdName = strtok_r(packet, ":;", &params);
854
855                         cmdName++; // vCommand -> Command
856
857                         if(!strcmp(cmdName, "FlashErase")) {
858                                 char *__s_addr, *s_length;
859                                 char *tok = params;
860
861                                 __s_addr   = strsep(&tok, ",");
862                                 s_length = tok;
863
864                                 unsigned addr = strtoul(__s_addr, NULL, 16),
865                                        length = strtoul(s_length, NULL, 16);
866
867                                 #ifdef DEBUG
868                                 printf("FlashErase: addr:%08x,len:%04x\n",
869                                         addr, length);
870                                 #endif
871
872                                 if(flash_add_block(addr, length, sl) < 0) {
873                                         reply = strdup("E00");
874                                 } else {
875                                         reply = strdup("OK");
876                                 }
877                         } else if(!strcmp(cmdName, "FlashWrite")) {
878                                 char *__s_addr, *data;
879                                 char *tok = params;
880
881                                 __s_addr = strsep(&tok, ":");
882                                 data   = tok;
883
884                                 unsigned addr = strtoul(__s_addr, NULL, 16);
885                                 unsigned data_length = status - (data - packet);
886
887                                 // Length of decoded data cannot be more than
888                                 // encoded, as escapes are removed.
889                                 // Additional byte is reserved for alignment fix.
890                                 uint8_t *decoded = calloc(data_length + 1, 1);
891                                 unsigned dec_index = 0;
892                                 for(unsigned int i = 0; i < data_length; i++) {
893                                         if(data[i] == 0x7d) {
894                                                 i++;
895                                                 decoded[dec_index++] = data[i] ^ 0x20;
896                                         } else {
897                                                 decoded[dec_index++] = data[i];
898                                         }
899                                 }
900
901                                 // Fix alignment
902                                 if(dec_index % 2 != 0)
903                                         dec_index++;
904
905                                 #ifdef DEBUG
906                                 printf("binary packet %d -> %d\n", data_length, dec_index);
907                                 #endif
908
909                                 if(flash_populate(addr, decoded, dec_index) < 0) {
910                                         reply = strdup("E00");
911                                 } else {
912                                         reply = strdup("OK");
913                                 }
914                         } else if(!strcmp(cmdName, "FlashDone")) {
915                                 if(flash_go(sl) < 0) {
916                                         reply = strdup("E00");
917                                 } else {
918                                         reply = strdup("OK");
919                                 }
920                         } else if(!strcmp(cmdName, "Kill")) {
921                                 attached = 0;
922
923                                 reply = strdup("OK");
924                         }
925
926                         if(reply == NULL)
927                                 reply = strdup("");
928
929                         break;
930                 }
931
932                 case 'c':
933                         stlink_run(sl);
934
935                         while(1) {
936                                 int status = gdb_check_for_interrupt(client);
937                                 if(status < 0) {
938                                         fprintf(stderr, "cannot check for int: %d\n", status);
939                                         return 1;
940                                 }
941
942                                 if(status == 1) {
943                                         stlink_force_debug(sl);
944                                         break;
945                                 }
946
947                                 stlink_status(sl);
948                                 if(sl->core_stat == STLINK_CORE_HALTED) {
949                                         break;
950                                 }
951
952                                 usleep(100000);
953                         }
954
955                         reply = strdup("S05"); // TRAP
956                         break;
957
958                 case 's':
959                         stlink_step(sl);
960
961                         reply = strdup("S05"); // TRAP
962                         break;
963
964                 case '?':
965                         if(attached) {
966                                 reply = strdup("S05"); // TRAP
967                         } else {
968                                 /* Stub shall reply OK if not attached. */
969                                 reply = strdup("OK");
970                         }
971                         break;
972
973                 case 'g':
974                         stlink_read_all_regs(sl, &regp);
975
976                         reply = calloc(8 * 16 + 1, 1);
977                         for(int i = 0; i < 16; i++)
978                                 sprintf(&reply[i * 8], "%08x", htonl(regp.r[i]));
979
980                         break;
981
982                 case 'p': {
983                         unsigned id = strtoul(&packet[1], NULL, 16);
984                         unsigned myreg = 0xDEADDEAD;
985
986                         if(id < 16) {
987                                 stlink_read_reg(sl, id, &regp);
988                                 myreg = htonl(regp.r[id]);
989                         } else if(id == 0x19) {
990                                 stlink_read_reg(sl, 16, &regp);
991                                 myreg = htonl(regp.xpsr);
992                         } else if(id == 0x1A) {
993                                 stlink_read_reg(sl, 17, &regp);
994                                 myreg = htonl(regp.main_sp);
995                         } else if(id == 0x1B) {
996                                 stlink_read_reg(sl, 18, &regp);
997                                 myreg = htonl(regp.process_sp);
998                         } else if(id == 0x1C) {
999                                 stlink_read_unsupported_reg(sl, id, &regp);
1000                                 myreg = htonl(regp.control);
1001                         } else if(id == 0x1D) {
1002                                 stlink_read_unsupported_reg(sl, id, &regp);
1003                                 myreg = htonl(regp.faultmask);
1004                         } else if(id == 0x1E) {
1005                                 stlink_read_unsupported_reg(sl, id, &regp);
1006                                 myreg = htonl(regp.basepri);
1007                         } else if(id == 0x1F) {
1008                                 stlink_read_unsupported_reg(sl, id, &regp);
1009                                 myreg = htonl(regp.primask);
1010             } else if(id >= 0x20 && id < 0x40) {
1011                 stlink_read_unsupported_reg(sl, id, &regp);
1012                 myreg = htonl(regp.s[id-0x20]);
1013                         } else if(id == 0x40) {
1014                 stlink_read_unsupported_reg(sl, id, &regp);
1015                 myreg = htonl(regp.fpscr);
1016                         } else {
1017                                 reply = strdup("E00");
1018                         }
1019
1020                         reply = calloc(8 + 1, 1);
1021                         sprintf(reply, "%08x", myreg);
1022
1023                         break;
1024                 }
1025
1026                 case 'P': {
1027                         char* s_reg = &packet[1];
1028                         char* s_value = strstr(&packet[1], "=") + 1;
1029
1030                         unsigned reg   = strtoul(s_reg,   NULL, 16);
1031                         unsigned value = strtoul(s_value, NULL, 16);
1032
1033                         if(reg < 16) {
1034                                 stlink_write_reg(sl, ntohl(value), reg);
1035                         } else if(reg == 0x19) {
1036                                 stlink_write_reg(sl, ntohl(value), 16);
1037                         } else if(reg == 0x1A) {
1038                                 stlink_write_reg(sl, ntohl(value), 17);
1039                         } else if(reg == 0x1B) {
1040                                 stlink_write_reg(sl, ntohl(value), 18);
1041                         } else if(reg == 0x1C) {
1042                                 stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1043                         } else if(reg == 0x1D) {
1044                                 stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1045                         } else if(reg == 0x1E) {
1046                                 stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1047                         } else if(reg == 0x1F) {
1048                                 stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1049             } else if(reg >= 0x20 && reg < 0x40) {
1050                 stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1051                         } else if(reg == 0x40) {
1052                 stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1053                         } else {
1054                                 reply = strdup("E00");
1055                         }
1056
1057                         if(!reply) {
1058                                 reply = strdup("OK");
1059                         }
1060
1061                         break;
1062                 }
1063
1064                 case 'G':
1065                         for(int i = 0; i < 16; i++) {
1066                                 char str[9] = {0};
1067                                 strncpy(str, &packet[1 + i * 8], 8);
1068                                 uint32_t reg = strtoul(str, NULL, 16);
1069                                 stlink_write_reg(sl, ntohl(reg), i);
1070                         }
1071
1072                         reply = strdup("OK");
1073                         break;
1074
1075                 case 'm': {
1076                         char* s_start = &packet[1];
1077                         char* s_count = strstr(&packet[1], ",") + 1;
1078
1079                         stm32_addr_t start = strtoul(s_start, NULL, 16);
1080                         unsigned     count = strtoul(s_count, NULL, 16);
1081
1082                         unsigned adj_start = start % 4;
1083                         unsigned count_rnd = (count + adj_start + 4 - 1) / 4 * 4;
1084
1085                         stlink_read_mem32(sl, start - adj_start, count_rnd);
1086
1087                         reply = calloc(count * 2 + 1, 1);
1088                         for(unsigned int i = 0; i < count; i++) {
1089                                 reply[i * 2 + 0] = hex[sl->q_buf[i + adj_start] >> 4];
1090                                 reply[i * 2 + 1] = hex[sl->q_buf[i + adj_start] & 0xf];
1091                         }
1092
1093                         break;
1094                 }
1095
1096                 case 'M': {
1097                         char* s_start = &packet[1];
1098                         char* s_count = strstr(&packet[1], ",") + 1;
1099                         char* hexdata = strstr(packet, ":") + 1;
1100
1101                         stm32_addr_t start = strtoul(s_start, NULL, 16);
1102                         unsigned     count = strtoul(s_count, NULL, 16);
1103
1104                         if(start % 4) {
1105                           unsigned align_count = 4 - start % 4;
1106                           if (align_count > count) align_count = count;
1107                           for(unsigned int i = 0; i < align_count; i ++) {
1108                                 char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1109                                 uint8_t byte = strtoul(hex, NULL, 16);
1110                                 sl->q_buf[i] = byte;
1111                           }
1112                           stlink_write_mem8(sl, start, align_count);
1113                           start += align_count;
1114                           count -= align_count;
1115                           hexdata += 2*align_count;
1116                         }
1117
1118                         if(count - count % 4) {
1119                           unsigned aligned_count = count - count % 4;
1120
1121                           for(unsigned int i = 0; i < aligned_count; i ++) {
1122                             char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1123                             uint8_t byte = strtoul(hex, NULL, 16);
1124                             sl->q_buf[i] = byte;
1125                           }
1126                           stlink_write_mem32(sl, start, aligned_count);
1127                           count -= aligned_count;
1128                           start += aligned_count;
1129                           hexdata += 2*aligned_count;
1130                         }
1131
1132                         if(count) {
1133                           for(unsigned int i = 0; i < count; i ++) {
1134                             char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1135                             uint8_t byte = strtoul(hex, NULL, 16);
1136                             sl->q_buf[i] = byte;
1137                           }
1138                           stlink_write_mem8(sl, start, count);
1139                         }
1140                         reply = strdup("OK");
1141                         break;
1142                 }
1143
1144                 case 'Z': {
1145                         char *endptr;
1146                         stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
1147                         stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
1148
1149                         switch (packet[1]) {
1150                                 case '1':
1151                                 if(update_code_breakpoint(sl, addr, 1) < 0) {
1152                                         reply = strdup("E00");
1153                                 } else {
1154                                         reply = strdup("OK");
1155                                 }
1156                                 break;
1157
1158                                 case '2':   // insert write watchpoint
1159                                 case '3':   // insert read  watchpoint
1160                                 case '4':   // insert access watchpoint
1161                                 {
1162                                         enum watchfun wf;
1163                                         if(packet[1] == '2') {
1164                                                 wf = WATCHWRITE;
1165                                         } else if(packet[1] == '3') {
1166                                                 wf = WATCHREAD;
1167                                         } else {
1168                                                 wf = WATCHACCESS;
1169                                         }
1170
1171                     if(add_data_watchpoint(sl, wf, addr, len) < 0) {
1172                         reply = strdup("E00");
1173                     } else {
1174                         reply = strdup("OK");
1175                         break;
1176                     }
1177                                 }
1178
1179                                 default:
1180                                 reply = strdup("");
1181                         }
1182                         break;
1183                 }
1184                 case 'z': {
1185                         char *endptr;
1186                         stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
1187                         //stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
1188
1189                         switch (packet[1]) {
1190                                 case '1': // remove breakpoint
1191                                 update_code_breakpoint(sl, addr, 0);
1192                                 reply = strdup("OK");
1193                                 break;
1194
1195                                 case '2' : // remove write watchpoint
1196                                 case '3' : // remove read watchpoint
1197                                 case '4' : // remove access watchpoint
1198                                 if(delete_data_watchpoint(sl, addr) < 0) {
1199                                         reply = strdup("E00");
1200                                 } else {
1201                                         reply = strdup("OK");
1202                                         break;
1203                                 }
1204
1205                                 default:
1206                                 reply = strdup("");
1207                         }
1208                         break;
1209                 }
1210
1211                 case '!': {
1212                         /*
1213                          * Enter extended mode which allows restarting.
1214                          * We do support that always.
1215                          */
1216
1217                         /*
1218                          * Also, set to persistent mode
1219                          * to allow GDB disconnect.
1220                          */
1221                         st->persistent = 1;
1222
1223                         reply = strdup("OK");
1224
1225                         break;
1226                 }
1227
1228                 case 'R': {
1229                         /* Reset the core. */
1230
1231                         stlink_reset(sl);
1232                         init_code_breakpoints(sl);
1233                         init_data_watchpoints(sl);
1234
1235                         attached = 1;
1236
1237                         reply = strdup("OK");
1238
1239                         break;
1240                 }
1241
1242                 default:
1243                         reply = strdup("");
1244                 }
1245
1246                 if(reply) {
1247                         #ifdef DEBUG
1248                         printf("send: %s\n", reply);
1249                         #endif
1250
1251                         int result = gdb_send_packet(client, reply);
1252                         if(result != 0) {
1253                                 fprintf(stderr, "cannot send: %d\n", result);
1254                                 free(reply);
1255                                 free(packet);
1256                                 return 1;
1257                         }
1258
1259                         free(reply);
1260                 }
1261
1262                 free(packet);
1263         }
1264
1265         return 0;
1266 }