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