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