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