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