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