Merge pull request #295 from simonjwright/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=\"0x60000000\" length=\"0x7fffffff\"/>"   // AHB3 Peripherals
314     "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>"   // cortex regs
315     "  <memory type=\"rom\" start=\"0x1fff0000\" length=\"0x7800\"/>"       // bootrom
316     "  <memory type=\"rom\" start=\"0x1fffc000\" length=\"0x10\"/>"         // option byte area
317     "</memory-map>";
318
319 static const char* const memory_map_template_F4_HD =
320     "<?xml version=\"1.0\"?>"
321     "<!DOCTYPE memory-map PUBLIC \"+//IDN gnu.org//DTD GDB Memory Map V1.0//EN\""
322     "     \"http://sourceware.org/gdb/gdb-memory-map.dtd\">"
323     "<memory-map>"
324     "  <memory type=\"rom\" start=\"0x00000000\" length=\"0x100000\"/>"     // code = sram, bootrom or flash; flash is bigger
325     "  <memory type=\"ram\" start=\"0x10000000\" length=\"0x10000\"/>"      // ccm ram
326     "  <memory type=\"ram\" start=\"0x20000000\" length=\"0x30000\"/>"      // sram
327     "  <memory type=\"flash\" start=\"0x08000000\" length=\"0x10000\">"     //Sectors 0..3
328     "    <property name=\"blocksize\">0x4000</property>"                    //16kB
329     "  </memory>"
330     "  <memory type=\"flash\" start=\"0x08010000\" length=\"0x10000\">"     //Sector 4
331     "    <property name=\"blocksize\">0x10000</property>"                   //64kB
332     "  </memory>"
333     "  <memory type=\"flash\" start=\"0x08020000\" length=\"0xE0000\">"     //Sectors 5..11
334     "    <property name=\"blocksize\">0x20000</property>"                   //128kB
335     "  </memory>"
336     "  <memory type=\"ram\" start=\"0x40000000\" length=\"0x1fffffff\"/>"   // peripheral regs
337     "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>"   // cortex regs
338     "  <memory type=\"rom\" start=\"0x1fff0000\" length=\"0x7800\"/>"       // bootrom
339     "  <memory type=\"rom\" start=\"0x1fffc000\" length=\"0x10\"/>"         // option byte area
340     "</memory-map>";
341
342 static const char* const memory_map_template =
343     "<?xml version=\"1.0\"?>"
344     "<!DOCTYPE memory-map PUBLIC \"+//IDN gnu.org//DTD GDB Memory Map V1.0//EN\""
345     "     \"http://sourceware.org/gdb/gdb-memory-map.dtd\">"
346     "<memory-map>"
347     "  <memory type=\"rom\" start=\"0x00000000\" length=\"0x%zx\"/>"        // code = sram, bootrom or flash; flash is bigger
348     "  <memory type=\"ram\" start=\"0x20000000\" length=\"0x%zx\"/>"        // sram 8k
349     "  <memory type=\"flash\" start=\"0x08000000\" length=\"0x%zx\">"
350     "    <property name=\"blocksize\">0x%zx</property>"
351     "  </memory>"
352     "  <memory type=\"ram\" start=\"0x40000000\" length=\"0x1fffffff\"/>"   // peripheral regs
353     "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>"   // cortex regs
354     "  <memory type=\"rom\" start=\"0x%08x\" length=\"0x%zx\"/>"            // bootrom
355     "  <memory type=\"rom\" start=\"0x1ffff800\" length=\"0x10\"/>"         // option byte area
356     "</memory-map>";
357
358 char* make_memory_map(stlink_t *sl) {
359     /* This will be freed in serve() */
360     char* map = malloc(4096);
361     map[0] = '\0';
362
363     if(sl->chip_id==STM32_CHIPID_F4) {
364         strcpy(map, memory_map_template_F4);
365     } else if(sl->chip_id==STM32_CHIPID_F4_HD) {
366         strcpy(map, memory_map_template_F4_HD);
367     } else {
368         snprintf(map, 4096, memory_map_template,
369                 sl->flash_size,
370                 sl->sram_size,
371                 sl->flash_size, sl->flash_pgsz,
372                 sl->sys_base, sl->sys_size);
373     }
374     return map;
375 }
376
377
378 /*
379  * DWT_COMP0     0xE0001020
380  * DWT_MASK0     0xE0001024
381  * DWT_FUNCTION0 0xE0001028
382  * DWT_COMP1     0xE0001030
383  * DWT_MASK1     0xE0001034
384  * DWT_FUNCTION1 0xE0001038
385  * DWT_COMP2     0xE0001040
386  * DWT_MASK2     0xE0001044
387  * DWT_FUNCTION2 0xE0001048
388  * DWT_COMP3     0xE0001050
389  * DWT_MASK3     0xE0001054
390  * DWT_FUNCTION3 0xE0001058
391  */
392
393 #define DATA_WATCH_NUM 4
394
395 enum watchfun { WATCHDISABLED = 0, WATCHREAD = 5, WATCHWRITE = 6, WATCHACCESS = 7 };
396
397 struct code_hw_watchpoint {
398     stm32_addr_t addr;
399     uint8_t mask;
400     enum watchfun fun;
401 };
402
403 struct code_hw_watchpoint data_watches[DATA_WATCH_NUM];
404
405 static void init_data_watchpoints(stlink_t *sl) {
406     DLOG("init watchpoints\n");
407
408     // set trcena in debug command to turn on dwt unit
409     stlink_write_debug32(sl, 0xE000EDFC,
410             stlink_read_debug32(sl, 0xE000EDFC) | (1<<24));
411
412     // make sure all watchpoints are cleared
413     for(int i = 0; i < DATA_WATCH_NUM; i++) {
414         data_watches[i].fun = WATCHDISABLED;
415         stlink_write_debug32(sl, 0xe0001028 + i * 16, 0);
416     }
417 }
418
419 static int add_data_watchpoint(stlink_t *sl, enum watchfun wf,
420                                stm32_addr_t addr, unsigned int len) {
421     int i = 0;
422     uint32_t mask;
423
424     // computer mask
425     // find a free watchpoint
426     // configure
427
428     mask = -1;
429     i = len;
430     while(i) {
431         i >>= 1;
432         mask++;
433     }
434
435     if((mask != (uint32_t)-1) && (mask < 16)) {
436         for(i = 0; i < DATA_WATCH_NUM; i++) {
437             // is this an empty slot ?
438             if(data_watches[i].fun == WATCHDISABLED) {
439                 DLOG("insert watchpoint %d addr %x wf %u mask %u len %d\n", i, addr, wf, mask, len);
440
441                 data_watches[i].fun = wf;
442                 data_watches[i].addr = addr;
443                 data_watches[i].mask = mask;
444
445                 // insert comparator address
446                 stlink_write_debug32(sl, 0xE0001020 + i * 16, addr);
447
448                 // insert mask
449                 stlink_write_debug32(sl, 0xE0001024 + i * 16, mask);
450
451                 // insert function
452                 stlink_write_debug32(sl, 0xE0001028 + i * 16, wf);
453
454                 // just to make sure the matched bit is clear !
455                 stlink_read_debug32(sl,  0xE0001028 + i * 16);
456                 return 0;
457             }
458         }
459     }
460
461     DLOG("failure: add watchpoints addr %x wf %u len %u\n", addr, wf, len);
462     return -1;
463 }
464
465 static int delete_data_watchpoint(stlink_t *sl, stm32_addr_t addr)
466 {
467     int i;
468
469     for(i = 0 ; i < DATA_WATCH_NUM; i++) {
470         if((data_watches[i].addr == addr) && (data_watches[i].fun != WATCHDISABLED)) {
471             DLOG("delete watchpoint %d addr %x\n", i, addr);
472
473             data_watches[i].fun = WATCHDISABLED;
474             stlink_write_debug32(sl, 0xe0001028 + i * 16, 0);
475
476             return 0;
477         }
478     }
479
480     DLOG("failure: delete watchpoint addr %x\n", addr);
481
482     return -1;
483 }
484
485 #define CODE_BREAK_NUM  6
486 #define CODE_LIT_NUM    2
487 #define CODE_BREAK_LOW  0x01
488 #define CODE_BREAK_HIGH 0x02
489
490 struct code_hw_breakpoint {
491     stm32_addr_t addr;
492     int          type;
493 };
494
495 struct code_hw_breakpoint code_breaks[CODE_BREAK_NUM];
496
497 static void init_code_breakpoints(stlink_t *sl) {
498     memset(sl->q_buf, 0, 4);
499     stlink_write_debug32(sl, CM3_REG_FP_CTRL, 0x03 /*KEY | ENABLE4*/);
500     unsigned int val = stlink_read_debug32(sl, CM3_REG_FP_CTRL);
501     if (((val & 3) != 1) ||
502             ((((val >> 8) & 0x70) | ((val >> 4) & 0xf)) != CODE_BREAK_NUM) ||
503             (((val >> 8) & 0xf) != CODE_LIT_NUM)){
504         ELOG("[FP_CTRL] = 0x%08x expecting 0x%08x\n", val,
505                 ((CODE_BREAK_NUM & 0x70) << 8) | (CODE_LIT_NUM << 8) |  ((CODE_BREAK_NUM & 0xf) << 4) | 1);
506     }
507
508
509     for(int i = 0; i < CODE_BREAK_NUM; i++) {
510         code_breaks[i].type = 0;
511         stlink_write_debug32(sl, CM3_REG_FP_COMP0 + i * 4, 0);
512     }
513 }
514
515 static int update_code_breakpoint(stlink_t *sl, stm32_addr_t addr, int set) {
516     stm32_addr_t fpb_addr = addr & ~0x3;
517     int type = addr & 0x2 ? CODE_BREAK_HIGH : CODE_BREAK_LOW;
518
519     if(addr & 1) {
520         ELOG("update_code_breakpoint: unaligned address %08x\n", addr);
521         return -1;
522     }
523
524     int id = -1;
525     for(int i = 0; i < CODE_BREAK_NUM; i++) {
526         if(fpb_addr == code_breaks[i].addr ||
527                 (set && code_breaks[i].type == 0)) {
528             id = i;
529             break;
530         }
531     }
532
533     if(id == -1) {
534         if(set) return -1; // Free slot not found
535         else    return 0;  // Breakpoint is already removed
536     }
537
538     struct code_hw_breakpoint* brk = &code_breaks[id];
539
540     brk->addr = fpb_addr;
541
542     if(set) brk->type |= type;
543     else        brk->type &= ~type;
544
545     if(brk->type == 0) {
546         DLOG("clearing hw break %d\n", id);
547
548         stlink_write_debug32(sl, 0xe0002008 + id * 4, 0);
549     } else {
550         uint32_t mask = (brk->addr) | 1 | (brk->type << 30);
551
552         DLOG("setting hw break %d at %08x (%d)\n",
553                     id, brk->addr, brk->type);
554         DLOG("reg %08x \n",
555                     mask);
556
557         stlink_write_debug32(sl, 0xe0002008 + id * 4, mask);
558     }
559
560     return 0;
561 }
562
563
564 struct flash_block {
565     stm32_addr_t addr;
566     unsigned     length;
567     uint8_t*     data;
568
569     struct flash_block* next;
570 };
571
572 static struct flash_block* flash_root;
573
574 static int flash_add_block(stm32_addr_t addr, unsigned length, stlink_t *sl) {
575
576     if(addr < FLASH_BASE || addr + length > FLASH_BASE + sl->flash_size) {
577         ELOG("flash_add_block: incorrect bounds\n");
578         return -1;
579     }
580
581     stlink_calculate_pagesize(sl, addr);
582     if(addr % FLASH_PAGE != 0 || length % FLASH_PAGE != 0) {
583         ELOG("flash_add_block: unaligned block\n");
584         return -1;
585     }
586
587     struct flash_block* new = malloc(sizeof(struct flash_block));
588     new->next = flash_root;
589
590     new->addr   = addr;
591     new->length = length;
592     new->data   = calloc(length, 1);
593
594     flash_root = new;
595
596     return 0;
597 }
598
599 static int flash_populate(stm32_addr_t addr, uint8_t* data, unsigned length) {
600     unsigned int fit_blocks = 0, fit_length = 0;
601
602     for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
603         /* Block: ------X------Y--------
604          * Data:            a-----b
605          *                a--b
606          *            a-----------b
607          * Block intersects with data, if:
608          *  a < Y && b > x
609          */
610
611         unsigned X = fb->addr, Y = fb->addr + fb->length;
612         unsigned a = addr, b = addr + length;
613         if(a < Y && b > X) {
614             // from start of the block
615             unsigned start = (a > X ? a : X) - X;
616             unsigned end   = (b > Y ? Y : b) - X;
617
618             memcpy(fb->data + start, data, end - start);
619
620             fit_blocks++;
621             fit_length += end - start;
622         }
623     }
624
625     if(fit_blocks == 0) {
626         ELOG("Unfit data block %08x -> %04x\n", addr, length);
627         return -1;
628     }
629
630     if(fit_length != length) {
631         WLOG("data block %08x -> %04x truncated to %04x\n",
632                 addr, length, fit_length);
633         WLOG("(this is not an error, just a GDB glitch)\n");
634     }
635
636     return 0;
637 }
638
639 static int flash_go(stlink_t *sl) {
640     int error = -1;
641
642     // Some kinds of clock settings do not allow writing to flash.
643     stlink_reset(sl);
644
645     for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
646         DLOG("flash_do: block %08x -> %04x\n", fb->addr, fb->length);
647
648         unsigned length = fb->length;
649         for(stm32_addr_t page = fb->addr; page < fb->addr + fb->length; page += FLASH_PAGE) {
650
651             //Update FLASH_PAGE
652             stlink_calculate_pagesize(sl, page);
653
654             DLOG("flash_do: page %08x\n", page);
655
656             if(stlink_write_flash(sl, page, fb->data + (page - fb->addr),
657                         length > FLASH_PAGE ? FLASH_PAGE : length) < 0)
658                 goto error;
659         }
660     }
661
662     stlink_reset(sl);
663
664     error = 0;
665
666 error:
667     for(struct flash_block* fb = flash_root, *next; fb; fb = next) {
668         next = fb->next;
669         free(fb->data);
670         free(fb);
671     }
672
673     flash_root = NULL;
674
675     return error;
676 }
677
678 int serve(stlink_t *sl, st_state_t *st) {
679     int sock = socket(AF_INET, SOCK_STREAM, 0);
680     if(sock < 0) {
681         perror("socket");
682         return 1;
683     }
684
685     unsigned int val = 1;
686     setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
687
688     struct sockaddr_in serv_addr;
689     memset(&serv_addr,0,sizeof(struct sockaddr_in));
690     serv_addr.sin_family = AF_INET;
691     serv_addr.sin_addr.s_addr = INADDR_ANY;
692     serv_addr.sin_port = htons(st->listen_port);
693
694     if(bind(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
695         perror("bind");
696         return 1;
697     }
698
699     if(listen(sock, 5) < 0) {
700         perror("listen");
701         return 1;
702     }
703
704     ILOG("Listening at *:%d...\n", st->listen_port);
705
706     int client = accept(sock, NULL, NULL);
707     //signal (SIGINT, SIG_DFL);
708     if(client < 0) {
709         perror("accept");
710         return 1;
711     }
712
713     close(sock);
714
715     stlink_force_debug(sl);
716     if (st->reset) {
717         stlink_reset(sl);
718     }
719     init_code_breakpoints(sl);
720     init_data_watchpoints(sl);
721
722     ILOG("GDB connected.\n");
723
724     /*
725      * To allow resetting the chip from GDB it is required to
726      * emulate attaching and detaching to target.
727      */
728     unsigned int attached = 1;
729
730     while(1) {
731         char* packet;
732
733         int status = gdb_recv_packet(client, &packet);
734         if(status < 0) {
735             ELOG("cannot recv: %d\n", status);
736             return 1;
737         }
738
739         DLOG("recv: %s\n", packet);
740
741         char* reply = NULL;
742         reg regp;
743
744         switch(packet[0]) {
745             case 'q': {
746                 if(packet[1] == 'P' || packet[1] == 'C' || packet[1] == 'L') {
747                     reply = strdup("");
748                     break;
749                 }
750
751                 char *separator = strstr(packet, ":"), *params = "";
752                 if(separator == NULL) {
753                     separator = packet + strlen(packet);
754                 } else {
755                     params = separator + 1;
756                 }
757
758                 unsigned queryNameLength = (separator - &packet[1]);
759                 char* queryName = calloc(queryNameLength + 1, 1);
760                 strncpy(queryName, &packet[1], queryNameLength);
761
762                 DLOG("query: %s;%s\n", queryName, params);
763
764                 if(!strcmp(queryName, "Supported")) {
765                     if(sl->chip_id==STM32_CHIPID_F4 || sl->chip_id==STM32_CHIPID_F4_HD) {
766                         reply = strdup("PacketSize=3fff;qXfer:memory-map:read+;qXfer:features:read+");
767                     }
768                     else {
769                         reply = strdup("PacketSize=3fff;qXfer:memory-map:read+");
770                     }
771                 } else if(!strcmp(queryName, "Xfer")) {
772                     char *type, *op, *__s_addr, *s_length;
773                     char *tok = params;
774                     char *annex __attribute__((unused));
775
776                     type     = strsep(&tok, ":");
777                     op       = strsep(&tok, ":");
778                     annex    = strsep(&tok, ":");
779                     __s_addr   = strsep(&tok, ",");
780                     s_length = tok;
781
782                     unsigned addr = strtoul(__s_addr, NULL, 16),
783                              length = strtoul(s_length, NULL, 16);
784
785                     DLOG("Xfer: type:%s;op:%s;annex:%s;addr:%d;length:%d\n",
786                                 type, op, annex, addr, length);
787
788                     const char* data = NULL;
789
790                     if(!strcmp(type, "memory-map") && !strcmp(op, "read"))
791                         data = current_memory_map;
792
793                     if(!strcmp(type, "features") && !strcmp(op, "read"))
794                         data = target_description_F4;
795
796                     if(data) {
797                         unsigned data_length = strlen(data);
798                         if(addr + length > data_length)
799                             length = data_length - addr;
800
801                         if(length == 0) {
802                             reply = strdup("l");
803                         } else {
804                             reply = calloc(length + 2, 1);
805                             reply[0] = 'm';
806                             strncpy(&reply[1], data, length);
807                         }
808                     }
809                 } else if(!strncmp(queryName, "Rcmd,",4)) {
810                     // Rcmd uses the wrong separator
811                     char *separator = strstr(packet, ","), *params = "";
812                     if(separator == NULL) {
813                         separator = packet + strlen(packet);
814                     } else {
815                         params = separator + 1;
816                     }
817
818
819                     if (!strncmp(params,"726573756d65",12)) {// resume
820                         DLOG("Rcmd: resume\n");
821                         stlink_run(sl);
822
823                         reply = strdup("OK");
824                     } else if (!strncmp(params,"68616c74",8)) { //halt
825                         reply = strdup("OK");
826
827                         stlink_force_debug(sl);
828
829                         DLOG("Rcmd: halt\n");
830                     } else if (!strncmp(params,"6a7461675f7265736574",20)) { //jtag_reset
831                         reply = strdup("OK");
832
833                         stlink_jtag_reset(sl, 0);
834                         stlink_jtag_reset(sl, 1);
835                         stlink_force_debug(sl);
836
837                         DLOG("Rcmd: jtag_reset\n");
838                     } else if (!strncmp(params,"7265736574",10)) { //reset
839                         reply = strdup("OK");
840
841                         stlink_force_debug(sl);
842                         stlink_reset(sl);
843                         init_code_breakpoints(sl);
844                         init_data_watchpoints(sl);
845
846                         DLOG("Rcmd: reset\n");
847                     } else {
848                         DLOG("Rcmd: %s\n", params);
849                     }
850
851                 }
852
853                 if(reply == NULL)
854                     reply = strdup("");
855
856                 free(queryName);
857
858                 break;
859             }
860
861             case 'v': {
862                 char *params = NULL;
863                 char *cmdName = strtok_r(packet, ":;", &params);
864
865                 cmdName++; // vCommand -> Command
866
867                 if(!strcmp(cmdName, "FlashErase")) {
868                     char *__s_addr, *s_length;
869                     char *tok = params;
870
871                     __s_addr   = strsep(&tok, ",");
872                     s_length = tok;
873
874                     unsigned addr = strtoul(__s_addr, NULL, 16),
875                              length = strtoul(s_length, NULL, 16);
876
877                     DLOG("FlashErase: addr:%08x,len:%04x\n",
878                                 addr, length);
879
880                     if(flash_add_block(addr, length, sl) < 0) {
881                         reply = strdup("E00");
882                     } else {
883                         reply = strdup("OK");
884                     }
885                 } else if(!strcmp(cmdName, "FlashWrite")) {
886                     char *__s_addr, *data;
887                     char *tok = params;
888
889                     __s_addr = strsep(&tok, ":");
890                     data   = tok;
891
892                     unsigned addr = strtoul(__s_addr, NULL, 16);
893                     unsigned data_length = status - (data - packet);
894
895                     // Length of decoded data cannot be more than
896                     // encoded, as escapes are removed.
897                     // Additional byte is reserved for alignment fix.
898                     uint8_t *decoded = calloc(data_length + 1, 1);
899                     unsigned dec_index = 0;
900                     for(unsigned int i = 0; i < data_length; i++) {
901                         if(data[i] == 0x7d) {
902                             i++;
903                             decoded[dec_index++] = data[i] ^ 0x20;
904                         } else {
905                             decoded[dec_index++] = data[i];
906                         }
907                     }
908
909                     // Fix alignment
910                     if(dec_index % 2 != 0)
911                         dec_index++;
912
913                     DLOG("binary packet %d -> %d\n", data_length, dec_index);
914
915                     if(flash_populate(addr, decoded, dec_index) < 0) {
916                         reply = strdup("E00");
917                     } else {
918                         reply = strdup("OK");
919                     }
920                 } else if(!strcmp(cmdName, "FlashDone")) {
921                     if(flash_go(sl) < 0) {
922                         reply = strdup("E00");
923                     } else {
924                         reply = strdup("OK");
925                     }
926                 } else if(!strcmp(cmdName, "Kill")) {
927                     attached = 0;
928
929                     reply = strdup("OK");
930                 }
931
932                 if(reply == NULL)
933                     reply = strdup("");
934
935                 break;
936             }
937
938             case 'c':
939                 stlink_run(sl);
940
941                 while(1) {
942                     int status = gdb_check_for_interrupt(client);
943                     if(status < 0) {
944                         ELOG("cannot check for int: %d\n", status);
945                         return 1;
946                     }
947
948                     if(status == 1) {
949                         stlink_force_debug(sl);
950                         break;
951                     }
952
953                     stlink_status(sl);
954                     if(sl->core_stat == STLINK_CORE_HALTED) {
955                         break;
956                     }
957
958                     usleep(100000);
959                 }
960
961                 reply = strdup("S05"); // TRAP
962                 break;
963
964             case 's':
965                 stlink_step(sl);
966
967                 reply = strdup("S05"); // TRAP
968                 break;
969
970             case '?':
971                 if(attached) {
972                     reply = strdup("S05"); // TRAP
973                 } else {
974                     /* Stub shall reply OK if not attached. */
975                     reply = strdup("OK");
976                 }
977                 break;
978
979             case 'g':
980                 stlink_read_all_regs(sl, &regp);
981
982                 reply = calloc(8 * 16 + 1, 1);
983                 for(int i = 0; i < 16; i++)
984                     sprintf(&reply[i * 8], "%08x", htonl(regp.r[i]));
985
986                 break;
987
988             case 'p': {
989                 unsigned id = strtoul(&packet[1], NULL, 16);
990                 unsigned myreg = 0xDEADDEAD;
991
992                 if(id < 16) {
993                     stlink_read_reg(sl, id, &regp);
994                     myreg = htonl(regp.r[id]);
995                 } else if(id == 0x19) {
996                     stlink_read_reg(sl, 16, &regp);
997                     myreg = htonl(regp.xpsr);
998                 } else if(id == 0x1A) {
999                     stlink_read_reg(sl, 17, &regp);
1000                     myreg = htonl(regp.main_sp);
1001                 } else if(id == 0x1B) {
1002                     stlink_read_reg(sl, 18, &regp);
1003                     myreg = htonl(regp.process_sp);
1004                 } else if(id == 0x1C) {
1005                     stlink_read_unsupported_reg(sl, id, &regp);
1006                     myreg = htonl(regp.control);
1007                 } else if(id == 0x1D) {
1008                     stlink_read_unsupported_reg(sl, id, &regp);
1009                     myreg = htonl(regp.faultmask);
1010                 } else if(id == 0x1E) {
1011                     stlink_read_unsupported_reg(sl, id, &regp);
1012                     myreg = htonl(regp.basepri);
1013                 } else if(id == 0x1F) {
1014                     stlink_read_unsupported_reg(sl, id, &regp);
1015                     myreg = htonl(regp.primask);
1016                 } else if(id >= 0x20 && id < 0x40) {
1017                     stlink_read_unsupported_reg(sl, id, &regp);
1018                     myreg = htonl(regp.s[id-0x20]);
1019                 } else if(id == 0x40) {
1020                     stlink_read_unsupported_reg(sl, id, &regp);
1021                     myreg = htonl(regp.fpscr);
1022                 } else {
1023                     reply = strdup("E00");
1024                 }
1025
1026                 reply = calloc(8 + 1, 1);
1027                 sprintf(reply, "%08x", myreg);
1028
1029                 break;
1030             }
1031
1032             case 'P': {
1033                 char* s_reg = &packet[1];
1034                 char* s_value = strstr(&packet[1], "=") + 1;
1035
1036                 unsigned reg   = strtoul(s_reg,   NULL, 16);
1037                 unsigned value = strtoul(s_value, NULL, 16);
1038
1039                 if(reg < 16) {
1040                     stlink_write_reg(sl, ntohl(value), reg);
1041                 } else if(reg == 0x19) {
1042                     stlink_write_reg(sl, ntohl(value), 16);
1043                 } else if(reg == 0x1A) {
1044                     stlink_write_reg(sl, ntohl(value), 17);
1045                 } else if(reg == 0x1B) {
1046                     stlink_write_reg(sl, ntohl(value), 18);
1047                 } else if(reg == 0x1C) {
1048                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1049                 } else if(reg == 0x1D) {
1050                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1051                 } else if(reg == 0x1E) {
1052                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1053                 } else if(reg == 0x1F) {
1054                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1055                 } else if(reg >= 0x20 && reg < 0x40) {
1056                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1057                 } else if(reg == 0x40) {
1058                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1059                 } else {
1060                     reply = strdup("E00");
1061                 }
1062
1063                 if(!reply) {
1064                     reply = strdup("OK");
1065                 }
1066
1067                 break;
1068             }
1069
1070             case 'G':
1071                 for(int i = 0; i < 16; i++) {
1072                     char str[9] = {0};
1073                     strncpy(str, &packet[1 + i * 8], 8);
1074                     uint32_t reg = strtoul(str, NULL, 16);
1075                     stlink_write_reg(sl, ntohl(reg), i);
1076                 }
1077
1078                 reply = strdup("OK");
1079                 break;
1080
1081             case 'm': {
1082                 char* s_start = &packet[1];
1083                 char* s_count = strstr(&packet[1], ",") + 1;
1084
1085                 stm32_addr_t start = strtoul(s_start, NULL, 16);
1086                 unsigned     count = strtoul(s_count, NULL, 16);
1087
1088                 unsigned adj_start = start % 4;
1089                 unsigned count_rnd = (count + adj_start + 4 - 1) / 4 * 4;
1090
1091                 stlink_read_mem32(sl, start - adj_start, count_rnd);
1092
1093                 reply = calloc(count * 2 + 1, 1);
1094                 for(unsigned int i = 0; i < count; i++) {
1095                     reply[i * 2 + 0] = hex[sl->q_buf[i + adj_start] >> 4];
1096                     reply[i * 2 + 1] = hex[sl->q_buf[i + adj_start] & 0xf];
1097                 }
1098
1099                 break;
1100             }
1101
1102             case 'M': {
1103                 char* s_start = &packet[1];
1104                 char* s_count = strstr(&packet[1], ",") + 1;
1105                 char* hexdata = strstr(packet, ":") + 1;
1106
1107                 stm32_addr_t start = strtoul(s_start, NULL, 16);
1108                 unsigned     count = strtoul(s_count, NULL, 16);
1109
1110                 if(start % 4) {
1111                     unsigned align_count = 4 - start % 4;
1112                     if (align_count > count) align_count = count;
1113                     for(unsigned int i = 0; i < align_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, align_count);
1119                     start += align_count;
1120                     count -= align_count;
1121                     hexdata += 2*align_count;
1122                 }
1123
1124                 if(count - count % 4) {
1125                     unsigned aligned_count = count - count % 4;
1126
1127                     for(unsigned int i = 0; i < aligned_count; i ++) {
1128                         char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1129                         uint8_t byte = strtoul(hex, NULL, 16);
1130                         sl->q_buf[i] = byte;
1131                     }
1132                     stlink_write_mem32(sl, start, aligned_count);
1133                     count -= aligned_count;
1134                     start += aligned_count;
1135                     hexdata += 2*aligned_count;
1136                 }
1137
1138                 if(count) {
1139                     for(unsigned int i = 0; i < count; i ++) {
1140                         char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1141                         uint8_t byte = strtoul(hex, NULL, 16);
1142                         sl->q_buf[i] = byte;
1143                     }
1144                     stlink_write_mem8(sl, start, count);
1145                 }
1146                 reply = strdup("OK");
1147                 break;
1148             }
1149
1150             case 'Z': {
1151                 char *endptr;
1152                 stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
1153                 stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
1154
1155                 switch (packet[1]) {
1156                     case '1':
1157                         if(update_code_breakpoint(sl, addr, 1) < 0) {
1158                             reply = strdup("E00");
1159                         } else {
1160                             reply = strdup("OK");
1161                         }
1162                         break;
1163
1164                     case '2':   // insert write watchpoint
1165                     case '3':   // insert read  watchpoint
1166                     case '4': { // insert access watchpoint
1167                         enum watchfun wf;
1168                         if(packet[1] == '2') {
1169                             wf = WATCHWRITE;
1170                         } else if(packet[1] == '3') {
1171                             wf = WATCHREAD;
1172                         } else {
1173                             wf = WATCHACCESS;
1174                         }
1175
1176                         if(add_data_watchpoint(sl, wf, addr, len) < 0) {
1177                             reply = strdup("E00");
1178                         } else {
1179                             reply = strdup("OK");
1180                             break;
1181                         }
1182                     }
1183
1184                     default:
1185                         reply = strdup("");
1186                 }
1187                 break;
1188             }
1189             case 'z': {
1190                 char *endptr;
1191                 stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
1192                 //stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
1193
1194                 switch (packet[1]) {
1195                     case '1': // remove breakpoint
1196                         update_code_breakpoint(sl, addr, 0);
1197                         reply = strdup("OK");
1198                         break;
1199
1200                     case '2' : // remove write watchpoint
1201                     case '3' : // remove read watchpoint
1202                     case '4' : // remove access watchpoint
1203                         if(delete_data_watchpoint(sl, addr) < 0) {
1204                             reply = strdup("E00");
1205                         } else {
1206                             reply = strdup("OK");
1207                             break;
1208                         }
1209
1210                     default:
1211                         reply = strdup("");
1212                 }
1213                 break;
1214             }
1215
1216             case '!': {
1217                 /*
1218                  * Enter extended mode which allows restarting.
1219                  * We do support that always.
1220                  */
1221
1222                 /*
1223                  * Also, set to persistent mode
1224                  * to allow GDB disconnect.
1225                  */
1226                 st->persistent = 1;
1227
1228                 reply = strdup("OK");
1229
1230                 break;
1231             }
1232
1233             case 'R': {
1234                 /* Reset the core. */
1235
1236                 stlink_reset(sl);
1237                 init_code_breakpoints(sl);
1238                 init_data_watchpoints(sl);
1239
1240                 attached = 1;
1241
1242                 reply = strdup("OK");
1243
1244                 break;
1245             }
1246
1247             default:
1248                 reply = strdup("");
1249         }
1250
1251         if(reply) {
1252             DLOG("send: %s\n", reply);
1253
1254             int result = gdb_send_packet(client, reply);
1255             if(result != 0) {
1256                 ELOG("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 }