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