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