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