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