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