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