Align loader to 32-bit boundary
[fw/stlink] / gdbserver / gdb-server.c
1 /*
2  * Copyright (C)  2011 Peter Zotov <whitequark@whitequark.org>
3  * Use of this source code is governed by a BSD-style
4  * license that can be found in the LICENSE file.
5  */
6
7 #include <getopt.h>
8 #include <signal.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <sys/types.h>
14 #ifdef __MINGW32__
15 #include "mingw.h"
16 #else
17 #include <sys/socket.h>
18 #include <netinet/in.h>
19 #include <arpa/inet.h>
20 #endif
21
22 #include <stlink-common.h>
23 #include <uglylogging.h>
24
25 #include "gdb-remote.h"
26 #include "gdb-server.h"
27
28 #define FLASH_BASE 0x08000000
29
30 //Allways update the FLASH_PAGE before each use, by calling stlink_calculate_pagesize
31 #define FLASH_PAGE (sl->flash_pgsz)
32
33 stlink_t *connected_stlink = NULL;
34
35 static const char hex[] = "0123456789abcdef";
36
37 static const char* current_memory_map = NULL;
38
39 typedef struct _st_state_t {
40     // things from command line, bleh
41     int stlink_version;
42     int logging_level;
43     int listen_port;
44     int persistent;
45     int reset;
46 } st_state_t;
47
48
49 int serve(stlink_t *sl, st_state_t *st);
50 char* make_memory_map(stlink_t *sl);
51 static void init_cache (stlink_t *sl);
52
53 static void cleanup(int signal __attribute__((unused))) {
54     if (connected_stlink) {
55         /* Switch back to mass storage mode before closing. */
56         stlink_run(connected_stlink);
57         stlink_exit_debug_mode(connected_stlink);
58         stlink_close(connected_stlink);
59     }
60
61     exit(1);
62 }
63
64
65
66 int parse_options(int argc, char** argv, st_state_t *st) {
67     static struct option long_options[] = {
68         {"help", no_argument, NULL, 'h'},
69         {"verbose", optional_argument, NULL, 'v'},
70         {"stlink_version", required_argument, NULL, 's'},
71         {"stlinkv1", no_argument, NULL, '1'},
72         {"listen_port", required_argument, NULL, 'p'},
73         {"multi", optional_argument, NULL, 'm'},
74         {"no-reset", optional_argument, NULL, 'n'},
75         {0, 0, 0, 0},
76     };
77     const char * help_str = "%s - usage:\n\n"
78         "  -h, --help\t\tPrint this help\n"
79         "  -vXX, --verbose=XX\tSpecify a specific verbosity level (0..99)\n"
80         "  -v, --verbose\t\tSpecify generally verbose logging\n"
81         "  -s X, --stlink_version=X\n"
82         "\t\t\tChoose what version of stlink to use, (defaults to 2)\n"
83         "  -1, --stlinkv1\tForce stlink version 1\n"
84         "  -p 4242, --listen_port=1234\n"
85         "\t\t\tSet the gdb server listen port. "
86         "(default port: " STRINGIFY(DEFAULT_GDB_LISTEN_PORT) ")\n"
87         "  -m, --multi\n"
88         "\t\t\tSet gdb server to extended mode.\n"
89         "\t\t\tst-util will continue listening for connections after disconnect.\n"
90         "  -n, --no-reset\n"
91         "\t\t\tDo not reset board on connection.\n"
92         "\n"
93         "The STLINKv2 device to use can be specified in the environment\n"
94         "variable STLINK_DEVICE on the format <USB_BUS>:<USB_ADDR>.\n"
95         "\n"
96         ;
97
98
99     int option_index = 0;
100     int c;
101     int q;
102     while ((c = getopt_long(argc, argv, "hv::s:1p:mn", long_options, &option_index)) != -1) {
103         switch (c) {
104             case 0:
105                 printf("XXXXX Shouldn't really normally come here, only if there's no corresponding option\n");
106                 printf("option %s", long_options[option_index].name);
107                 if (optarg) {
108                     printf(" with arg %s", optarg);
109                 }
110                 printf("\n");
111                 break;
112             case 'h':
113                 printf(help_str, argv[0]);
114                 exit(EXIT_SUCCESS);
115                 break;
116             case 'v':
117                 if (optarg) {
118                     st->logging_level = atoi(optarg);
119                 } else {
120                     st->logging_level = DEFAULT_LOGGING_LEVEL;
121                 }
122                 break;
123             case '1':
124                 st->stlink_version = 1;
125                 break;
126             case 's':
127                 sscanf(optarg, "%i", &q);
128                 if (q < 0 || q > 2) {
129                     fprintf(stderr, "stlink version %d unknown!\n", q);
130                     exit(EXIT_FAILURE);
131                 }
132                 st->stlink_version = q;
133                 break;
134             case 'p':
135                 sscanf(optarg, "%i", &q);
136                 if (q < 0) {
137                     fprintf(stderr, "Can't use a negative port to listen on: %d\n", q);
138                     exit(EXIT_FAILURE);
139                 }
140                 st->listen_port = q;
141                 break;
142             case 'm':
143                 st->persistent = 1;
144                 break;
145             case 'n':
146                 st->reset = 0;
147                 break;
148         }
149     }
150
151     if (optind < argc) {
152         printf("non-option ARGV-elements: ");
153         while (optind < argc)
154             printf("%s ", argv[optind++]);
155         printf("\n");
156     }
157     return 0;
158 }
159
160
161 int main(int argc, char** argv) {
162     int32_t voltage;
163
164     stlink_t *sl = NULL;
165
166     st_state_t state;
167     memset(&state, 0, sizeof(state));
168     // set defaults...
169     state.stlink_version = 2;
170     state.logging_level = DEFAULT_LOGGING_LEVEL;
171     state.listen_port = DEFAULT_GDB_LISTEN_PORT;
172     state.reset = 1;    /* By default, reset board */
173     parse_options(argc, argv, &state);
174     switch (state.stlink_version) {
175         case 2:
176             sl = stlink_open_usb(state.logging_level, state.reset, NULL);
177             if(sl == NULL) return 1;
178             break;
179         case 1:
180             sl = stlink_v1_open(state.logging_level, state.reset);
181             if(sl == NULL) return 1;
182             break;
183     }
184
185     connected_stlink = sl;
186     signal(SIGINT, &cleanup);
187     signal(SIGTERM, &cleanup);
188     signal(SIGSEGV, &cleanup);
189
190     if (state.reset) {
191         stlink_reset(sl);
192     }
193
194     ILOG("Chip ID is %08x, Core ID is  %08x.\n", sl->chip_id, sl->core_id);
195
196     voltage = stlink_target_voltage(sl);
197     if (voltage != -1) {
198         ILOG("Target voltage is %d mV.\n", voltage);
199     }
200
201     sl->verbose=0;
202
203     current_memory_map = make_memory_map(sl);
204
205 #ifdef __MINGW32__
206     WSADATA     wsadata;
207     if (WSAStartup(MAKEWORD(2,2),&wsadata) !=0 ) {
208         goto winsock_error;
209     }
210 #endif
211
212     init_cache(sl);
213
214     do {
215         if (serve(sl, &state)) {
216           sleep (1); // don't go bezurk if serve returns with error
217         }
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=\"0xE0000\">"     //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=\"0x60000000\" length=\"0x7fffffff\"/>"   // AHB3 Peripherals
319     "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>"   // cortex regs
320     "  <memory type=\"rom\" start=\"0x1fff0000\" length=\"0x7800\"/>"       // bootrom
321     "  <memory type=\"rom\" start=\"0x1fffc000\" length=\"0x10\"/>"         // option byte area
322     "</memory-map>";
323
324 static const char* const memory_map_template_F4_HD =
325     "<?xml version=\"1.0\"?>"
326     "<!DOCTYPE memory-map PUBLIC \"+//IDN gnu.org//DTD GDB Memory Map V1.0//EN\""
327     "     \"http://sourceware.org/gdb/gdb-memory-map.dtd\">"
328     "<memory-map>"
329     "  <memory type=\"rom\" start=\"0x00000000\" length=\"0x100000\"/>"     // code = sram, bootrom or flash; flash is bigger
330     "  <memory type=\"ram\" start=\"0x10000000\" length=\"0x10000\"/>"      // ccm ram
331     "  <memory type=\"ram\" start=\"0x20000000\" length=\"0x40000\"/>"      // sram
332     "  <memory type=\"ram\" start=\"0x60000000\" length=\"0x10000000\"/>"   // fmc bank 1 (nor/psram/sram)
333     "  <memory type=\"ram\" start=\"0x70000000\" length=\"0x20000000\"/>"   // fmc bank 2 & 3 (nand flash)
334     "  <memory type=\"ram\" start=\"0x90000000\" length=\"0x10000000\"/>"   // fmc bank 4 (pc card)
335     "  <memory type=\"ram\" start=\"0xC0000000\" length=\"0x20000000\"/>"   // fmc sdram bank 1 & 2
336     "  <memory type=\"flash\" start=\"0x08000000\" length=\"0x10000\">"     //Sectors 0..3
337     "    <property name=\"blocksize\">0x4000</property>"                    //16kB
338     "  </memory>"
339     "  <memory type=\"flash\" start=\"0x08010000\" length=\"0x10000\">"     //Sector 4
340     "    <property name=\"blocksize\">0x10000</property>"                   //64kB
341     "  </memory>"
342     "  <memory type=\"flash\" start=\"0x08020000\" length=\"0xE0000\">"     //Sectors 5..11
343     "    <property name=\"blocksize\">0x20000</property>"                   //128kB
344     "  </memory>"
345     "  <memory type=\"ram\" start=\"0x40000000\" length=\"0x1fffffff\"/>"   // peripheral regs
346     "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>"   // cortex regs
347     "  <memory type=\"rom\" start=\"0x1fff0000\" length=\"0x7800\"/>"       // bootrom
348     "  <memory type=\"rom\" start=\"0x1fffc000\" length=\"0x10\"/>"         // option byte area
349     "</memory-map>";
350
351 static const char* const memory_map_template_F2 =
352     "<?xml version=\"1.0\"?>"
353     "<!DOCTYPE memory-map PUBLIC \"+//IDN gnu.org//DTD GDB Memory Map V1.0//EN\""
354     "     \"http://sourceware.org/gdb/gdb-memory-map.dtd\">"
355     "<memory-map>"
356     "  <memory type=\"rom\" start=\"0x00000000\" length=\"0x%zx\"/>"        // code = sram, bootrom or flash; flash is bigger
357     "  <memory type=\"ram\" start=\"0x20000000\" length=\"0x%zx\"/>"        // sram
358     "  <memory type=\"flash\" start=\"0x08000000\" length=\"0x10000\">"     //Sectors 0..3
359     "    <property name=\"blocksize\">0x4000</property>"                    //16kB
360     "  </memory>"
361     "  <memory type=\"flash\" start=\"0x08010000\" length=\"0x10000\">"     //Sector 4
362     "    <property name=\"blocksize\">0x10000</property>"                   //64kB
363     "  </memory>"
364     "  <memory type=\"flash\" start=\"0x08020000\" length=\"0x%zx\">"       //Sectors 5..
365     "    <property name=\"blocksize\">0x20000</property>"                   //128kB
366     "  </memory>"
367     "  <memory type=\"ram\" start=\"0x40000000\" length=\"0x1fffffff\"/>"   // peripheral regs
368     "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>"   // cortex regs
369     "  <memory type=\"rom\" start=\"0x%08x\" length=\"0x%zx\"/>"            // bootrom
370     "  <memory type=\"rom\" start=\"0x1fffc000\" length=\"0x10\"/>"         // option byte area
371     "</memory-map>";
372
373 static const char* const memory_map_template_L4 =
374     "<?xml version=\"1.0\"?>"
375     "<!DOCTYPE memory-map PUBLIC \"+//IDN gnu.org//DTD GDB Memory Map V1.0//EN\""
376     "     \"http://sourceware.org/gdb/gdb-memory-map.dtd\">"
377     "<memory-map>"
378     "  <memory type=\"rom\" start=\"0x00000000\" length=\"0x%zx\"/>"        // code = sram, bootrom or flash; flash is bigger
379     "  <memory type=\"ram\" start=\"0x10000000\" length=\"0x8000\"/>"       // SRAM2 (32 KB)
380     "  <memory type=\"ram\" start=\"0x20000000\" length=\"0x18000\"/>"      // SRAM1 (96 KB)
381     "  <memory type=\"flash\" start=\"0x08000000\" length=\"0x%zx\">"
382     "    <property name=\"blocksize\">0x800</property>"
383     "  </memory>"
384     "  <memory type=\"ram\" start=\"0x40000000\" length=\"0x1fffffff\"/>"   // peripheral regs
385     "  <memory type=\"ram\" start=\"0x60000000\" length=\"0x7fffffff\"/>"   // AHB3 Peripherals
386     "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>"   // cortex regs
387     "  <memory type=\"rom\" start=\"0x1fff0000\" length=\"0x7000\"/>"       // bootrom
388     "  <memory type=\"rom\" start=\"0x1fff7800\" length=\"0x10\"/>"         // option byte area
389     "  <memory type=\"rom\" start=\"0x1ffff800\" length=\"0x10\"/>"         // option byte area
390     "</memory-map>";
391
392 static const char* const memory_map_template =
393     "<?xml version=\"1.0\"?>"
394     "<!DOCTYPE memory-map PUBLIC \"+//IDN gnu.org//DTD GDB Memory Map V1.0//EN\""
395     "     \"http://sourceware.org/gdb/gdb-memory-map.dtd\">"
396     "<memory-map>"
397     "  <memory type=\"rom\" start=\"0x00000000\" length=\"0x%zx\"/>"        // code = sram, bootrom or flash; flash is bigger
398     "  <memory type=\"ram\" start=\"0x20000000\" length=\"0x%zx\"/>"        // sram 8k
399     "  <memory type=\"flash\" start=\"0x08000000\" length=\"0x%zx\">"
400     "    <property name=\"blocksize\">0x%zx</property>"
401     "  </memory>"
402     "  <memory type=\"ram\" start=\"0x40000000\" length=\"0x1fffffff\"/>"   // peripheral regs
403     "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>"   // cortex regs
404     "  <memory type=\"rom\" start=\"0x%08x\" length=\"0x%zx\"/>"            // bootrom
405     "  <memory type=\"rom\" start=\"0x1ffff800\" length=\"0x10\"/>"         // option byte area
406     "</memory-map>";
407
408 static const char* const memory_map_template_F7 =
409     "<?xml version=\"1.0\"?>"
410     "<!DOCTYPE memory-map PUBLIC \"+//IDN gnu.org//DTD GDB Memory Map V1.0//EN\""
411     "     \"http://sourceware.org/gdb/gdb-memory-map.dtd\">"
412     "<memory-map>"
413     "  <memory type=\"ram\" start=\"0x00000000\" length=\"0x4000\"/>"       // ITCM ram 16kB
414     "  <memory type=\"rom\" start=\"0x00200000\" length=\"0x100000\"/>"     // ITCM flash
415     "  <memory type=\"ram\" start=\"0x20000000\" length=\"0x50000\"/>"      // sram
416     "  <memory type=\"flash\" start=\"0x08000000\" length=\"0x20000\">"     // Sectors 0..3
417     "    <property name=\"blocksize\">0x8000</property>"                    // 32kB
418     "  </memory>"
419     "  <memory type=\"flash\" start=\"0x08020000\" length=\"0x20000\">"     // Sector 4
420     "    <property name=\"blocksize\">0x20000</property>"                   // 128kB
421     "  </memory>"
422     "  <memory type=\"flash\" start=\"0x08040000\" length=\"0xC0000\">"     // Sectors 5..7
423     "    <property name=\"blocksize\">0x40000</property>"                   // 128kB
424     "  </memory>"
425     "  <memory type=\"ram\" start=\"0x40000000\" length=\"0x1fffffff\"/>"   // peripheral regs
426     "  <memory type=\"ram\" start=\"0x60000000\" length=\"0x7fffffff\"/>"   // AHB3 Peripherals
427     "  <memory type=\"ram\" start=\"0xe0000000\" length=\"0x1fffffff\"/>"   // cortex regs
428     "  <memory type=\"rom\" start=\"0x00100000\" length=\"0xEDC0\"/>"       // bootrom
429     "  <memory type=\"rom\" start=\"0x1fff0000\" length=\"0x20\"/>"         // option byte area
430     "</memory-map>";
431
432 char* make_memory_map(stlink_t *sl) {
433     /* This will be freed in serve() */
434     char* map = malloc(4096);
435     map[0] = '\0';
436
437     if(sl->chip_id==STM32_CHIPID_F4 || sl->chip_id==STM32_CHIPID_F446) {
438         strcpy(map, memory_map_template_F4);
439     } else if(sl->chip_id==STM32_CHIPID_F4 || sl->chip_id==STM32_CHIPID_F7) {
440         strcpy(map, memory_map_template_F7);
441     } else if(sl->chip_id==STM32_CHIPID_F4_HD) {
442         strcpy(map, memory_map_template_F4_HD);
443     } else if(sl->chip_id==STM32_CHIPID_F2) {
444         snprintf(map, 4096, memory_map_template_F2,
445                 sl->flash_size,
446                 sl->sram_size,
447                 sl->flash_size - 0x20000,
448                 sl->sys_base, sl->sys_size);
449     } else if(sl->chip_id==STM32_CHIPID_L4) {
450         snprintf(map, 4096, memory_map_template_L4,
451                 sl->flash_size, sl->flash_size);
452     } else {
453         snprintf(map, 4096, memory_map_template,
454                 sl->flash_size,
455                 sl->sram_size,
456                 sl->flash_size, sl->flash_pgsz,
457                 sl->sys_base, sl->sys_size);
458     }
459     return map;
460 }
461
462
463 /*
464  * DWT_COMP0     0xE0001020
465  * DWT_MASK0     0xE0001024
466  * DWT_FUNCTION0 0xE0001028
467  * DWT_COMP1     0xE0001030
468  * DWT_MASK1     0xE0001034
469  * DWT_FUNCTION1 0xE0001038
470  * DWT_COMP2     0xE0001040
471  * DWT_MASK2     0xE0001044
472  * DWT_FUNCTION2 0xE0001048
473  * DWT_COMP3     0xE0001050
474  * DWT_MASK3     0xE0001054
475  * DWT_FUNCTION3 0xE0001058
476  */
477
478 #define DATA_WATCH_NUM 4
479
480 enum watchfun { WATCHDISABLED = 0, WATCHREAD = 5, WATCHWRITE = 6, WATCHACCESS = 7 };
481
482 struct code_hw_watchpoint {
483     stm32_addr_t addr;
484     uint8_t mask;
485     enum watchfun fun;
486 };
487
488 struct code_hw_watchpoint data_watches[DATA_WATCH_NUM];
489
490 static void init_data_watchpoints(stlink_t *sl) {
491     uint32_t data;
492     DLOG("init watchpoints\n");
493
494     stlink_read_debug32(sl, 0xE000EDFC, &data);
495     data |= 1<<24;
496     // set trcena in debug command to turn on dwt unit
497     stlink_write_debug32(sl, 0xE000EDFC, data);
498
499     // make sure all watchpoints are cleared
500     for(int i = 0; i < DATA_WATCH_NUM; i++) {
501         data_watches[i].fun = WATCHDISABLED;
502         stlink_write_debug32(sl, 0xe0001028 + i * 16, 0);
503     }
504 }
505
506 static int add_data_watchpoint(stlink_t *sl, enum watchfun wf,
507                                stm32_addr_t addr, unsigned int len) {
508     int i = 0;
509     uint32_t mask, dummy;
510
511     // computer mask
512     // find a free watchpoint
513     // configure
514
515     mask = -1;
516     i = len;
517     while(i) {
518         i >>= 1;
519         mask++;
520     }
521
522     if((mask != (uint32_t)-1) && (mask < 16)) {
523         for(i = 0; i < DATA_WATCH_NUM; i++) {
524             // is this an empty slot ?
525             if(data_watches[i].fun == WATCHDISABLED) {
526                 DLOG("insert watchpoint %d addr %x wf %u mask %u len %d\n", i, addr, wf, mask, len);
527
528                 data_watches[i].fun = wf;
529                 data_watches[i].addr = addr;
530                 data_watches[i].mask = mask;
531
532                 // insert comparator address
533                 stlink_write_debug32(sl, 0xE0001020 + i * 16, addr);
534
535                 // insert mask
536                 stlink_write_debug32(sl, 0xE0001024 + i * 16, mask);
537
538                 // insert function
539                 stlink_write_debug32(sl, 0xE0001028 + i * 16, wf);
540
541                 // just to make sure the matched bit is clear !
542                 stlink_read_debug32(sl,  0xE0001028 + i * 16, &dummy);
543                 return 0;
544             }
545         }
546     }
547
548     DLOG("failure: add watchpoints addr %x wf %u len %u\n", addr, wf, len);
549     return -1;
550 }
551
552 static int delete_data_watchpoint(stlink_t *sl, stm32_addr_t addr)
553 {
554     int i;
555
556     for(i = 0 ; i < DATA_WATCH_NUM; i++) {
557         if((data_watches[i].addr == addr) && (data_watches[i].fun != WATCHDISABLED)) {
558             DLOG("delete watchpoint %d addr %x\n", i, addr);
559
560             data_watches[i].fun = WATCHDISABLED;
561             stlink_write_debug32(sl, 0xe0001028 + i * 16, 0);
562
563             return 0;
564         }
565     }
566
567     DLOG("failure: delete watchpoint addr %x\n", addr);
568
569     return -1;
570 }
571
572 int code_break_num;
573 int code_lit_num;
574 #define CODE_BREAK_NUM_MAX      15
575 #define CODE_BREAK_LOW  0x01
576 #define CODE_BREAK_HIGH 0x02
577
578 struct code_hw_breakpoint {
579     stm32_addr_t addr;
580     int          type;
581 };
582
583 struct code_hw_breakpoint code_breaks[CODE_BREAK_NUM_MAX];
584
585 static void init_code_breakpoints(stlink_t *sl) {
586     unsigned int val;
587     memset(sl->q_buf, 0, 4);
588     stlink_write_debug32(sl, CM3_REG_FP_CTRL, 0x03 /*KEY | ENABLE4*/);
589     stlink_read_debug32(sl, CM3_REG_FP_CTRL, &val);
590     code_break_num = ((val >> 4) & 0xf);
591     code_lit_num = ((val >> 8) & 0xf);
592
593     ILOG("Found %i hw breakpoint registers\n", code_break_num);
594
595     for(int i = 0; i < code_break_num; i++) {
596         code_breaks[i].type = 0;
597         stlink_write_debug32(sl, CM3_REG_FP_COMP0 + i * 4, 0);
598     }
599 }
600
601 static int update_code_breakpoint(stlink_t *sl, stm32_addr_t addr, int set) {
602     stm32_addr_t fpb_addr;
603     uint32_t mask;
604     int type = (addr & 0x2) ? CODE_BREAK_HIGH : CODE_BREAK_LOW;
605
606     if(addr & 1) {
607         ELOG("update_code_breakpoint: unaligned address %08x\n", addr);
608         return -1;
609     }
610
611         if (sl->chip_id==STM32_CHIPID_F7) {
612                 fpb_addr = addr;
613         } else {
614                 fpb_addr = addr & ~0x3;
615         }
616
617     int id = -1;
618     for(int i = 0; i < code_break_num; i++) {
619         if(fpb_addr == code_breaks[i].addr ||
620                 (set && code_breaks[i].type == 0)) {
621             id = i;
622             break;
623         }
624     }
625
626     if(id == -1) {
627         if(set) return -1; // Free slot not found
628         else    return 0;  // Breakpoint is already removed
629     }
630
631     struct code_hw_breakpoint* brk = &code_breaks[id];
632
633     brk->addr = fpb_addr;
634
635         if (sl->chip_id==STM32_CHIPID_F7) {
636                 if(set) brk->type = type;
637                 else    brk->type = 0;
638
639                 mask = (brk->addr) | 1;
640         } else {
641                 if(set) brk->type |= type;
642                 else    brk->type &= ~type;
643
644                 mask = (brk->addr) | 1 | (brk->type << 30);
645         }
646
647     if(brk->type == 0) {
648         DLOG("clearing hw break %d\n", id);
649
650         stlink_write_debug32(sl, 0xe0002008 + id * 4, 0);
651     } else {
652         DLOG("setting hw break %d at %08x (%d)\n",
653                     id, brk->addr, brk->type);
654         DLOG("reg %08x \n",
655                     mask);
656
657         stlink_write_debug32(sl, 0xe0002008 + id * 4, mask);
658     }
659
660     return 0;
661 }
662
663
664 struct flash_block {
665     stm32_addr_t addr;
666     unsigned     length;
667     uint8_t*     data;
668
669     struct flash_block* next;
670 };
671
672 static struct flash_block* flash_root;
673
674 static int flash_add_block(stm32_addr_t addr, unsigned length, stlink_t *sl) {
675
676     if(addr < FLASH_BASE || addr + length > FLASH_BASE + sl->flash_size) {
677         ELOG("flash_add_block: incorrect bounds\n");
678         return -1;
679     }
680
681     stlink_calculate_pagesize(sl, addr);
682     if(addr % FLASH_PAGE != 0 || length % FLASH_PAGE != 0) {
683         ELOG("flash_add_block: unaligned block\n");
684         return -1;
685     }
686
687     struct flash_block* new = malloc(sizeof(struct flash_block));
688     new->next = flash_root;
689
690     new->addr   = addr;
691     new->length = length;
692     new->data   = calloc(length, 1);
693
694     flash_root = new;
695
696     return 0;
697 }
698
699 static int flash_populate(stm32_addr_t addr, uint8_t* data, unsigned length) {
700     unsigned int fit_blocks = 0, fit_length = 0;
701
702     for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
703         /* Block: ------X------Y--------
704          * Data:            a-----b
705          *                a--b
706          *            a-----------b
707          * Block intersects with data, if:
708          *  a < Y && b > x
709          */
710
711         unsigned X = fb->addr, Y = fb->addr + fb->length;
712         unsigned a = addr, b = addr + length;
713         if(a < Y && b > X) {
714             // from start of the block
715             unsigned start = (a > X ? a : X) - X;
716             unsigned end   = (b > Y ? Y : b) - X;
717
718             memcpy(fb->data + start, data, end - start);
719
720             fit_blocks++;
721             fit_length += end - start;
722         }
723     }
724
725     if(fit_blocks == 0) {
726         ELOG("Unfit data block %08x -> %04x\n", addr, length);
727         return -1;
728     }
729
730     if(fit_length != length) {
731         WLOG("data block %08x -> %04x truncated to %04x\n",
732                 addr, length, fit_length);
733         WLOG("(this is not an error, just a GDB glitch)\n");
734     }
735
736     return 0;
737 }
738
739 static int flash_go(stlink_t *sl) {
740     int error = -1;
741
742     // Some kinds of clock settings do not allow writing to flash.
743     stlink_reset(sl);
744     stlink_force_debug(sl);
745
746     for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
747         DLOG("flash_do: block %08x -> %04x\n", fb->addr, fb->length);
748
749         for(stm32_addr_t page = fb->addr; page < fb->addr + fb->length; page += FLASH_PAGE) {
750             unsigned length = fb->length - (page - fb->addr);
751
752             //Update FLASH_PAGE
753             stlink_calculate_pagesize(sl, page);
754
755             DLOG("flash_do: page %08x\n", page);
756             unsigned send = length > FLASH_PAGE ? FLASH_PAGE : length;
757             if(stlink_write_flash(sl, page, fb->data + (page - fb->addr),
758                         send, 0) < 0)
759                 goto error;
760             length -= send;
761             
762         }
763     }
764
765     stlink_reset(sl);
766
767     error = 0;
768
769 error:
770     for(struct flash_block* fb = flash_root, *next; fb; fb = next) {
771         next = fb->next;
772         free(fb->data);
773         free(fb);
774     }
775
776     flash_root = NULL;
777
778     return error;
779 }
780
781 #define CLIDR   0xE000ED78
782 #define CTR     0xE000ED7C
783 #define CCSIDR  0xE000ED80
784 #define CSSELR  0xE000ED84
785 #define CCR     0xE000ED14
786 #define CCR_DC  (1 << 16)
787 #define CCR_IC  (1 << 17)
788 #define DCCSW   0xE000EF6C
789 #define ICIALLU 0xE000EF50
790
791 struct cache_level_desc
792 {
793   unsigned int nsets;
794   unsigned int nways;
795   unsigned int log2_nways;
796   unsigned int width;
797 };
798
799 struct cache_desc_t
800 {
801   /* Minimal line size in bytes.  */
802   unsigned int dminline;
803   unsigned int iminline;
804
805   /* Last level of unification (uniprocessor).  */
806   unsigned int louu;
807
808   struct cache_level_desc icache[7];
809   struct cache_level_desc dcache[7];
810 };
811
812 static struct cache_desc_t cache_desc;
813
814 /* Return the smallest R so that V <= (1 << R).  Not performance critical.  */
815 static unsigned ceil_log2(unsigned v)
816 {
817   unsigned res;
818   for (res = 0; (1U << res) < v; res++)
819     ;
820   return res;
821 }
822
823 static void read_cache_level_desc(stlink_t *sl, struct cache_level_desc *desc)
824 {
825   unsigned int ccsidr;
826   unsigned int log2_nsets;
827
828   stlink_read_debug32(sl, CCSIDR, &ccsidr);
829   desc->nsets = ((ccsidr >> 13) & 0x3fff) + 1;
830   desc->nways = ((ccsidr >> 3) & 0x1ff) + 1;
831   desc->log2_nways = ceil_log2 (desc->nways);
832   log2_nsets = ceil_log2 (desc->nsets);
833   desc->width = 4 + (ccsidr & 7) + log2_nsets;
834   ILOG("%08x LineSize: %u, ways: %u, sets: %u (width: %u)\n",
835        ccsidr, 4 << (ccsidr & 7), desc->nways, desc->nsets, desc->width);
836 }
837
838 static void init_cache (stlink_t *sl) {
839   unsigned int clidr;
840   unsigned int ccr;
841   unsigned int ctr;
842   int i;
843
844   /* Assume only F7 has a cache.  */
845   if(sl->chip_id!=STM32_CHIPID_F7)
846     return;
847
848   stlink_read_debug32(sl, CLIDR, &clidr);
849   stlink_read_debug32(sl, CCR, &ccr);
850   stlink_read_debug32(sl, CTR, &ctr);
851   cache_desc.dminline = 4 << ((ctr >> 16) & 0x0f);
852   cache_desc.iminline = 4 << (ctr & 0x0f);
853   cache_desc.louu = (clidr >> 27) & 7;
854
855   ILOG("Chip clidr: %08x, I-Cache: %s, D-Cache: %s\n",
856        clidr, ccr & CCR_IC ? "on" : "off", ccr & CCR_DC ? "on" : "off");
857   ILOG(" cache: LoUU: %u, LoC: %u, LoUIS: %u\n",
858        (clidr >> 27) & 7, (clidr >> 24) & 7, (clidr >> 21) & 7);
859   ILOG(" cache: ctr: %08x, DminLine: %u bytes, IminLine: %u bytes\n", ctr,
860        cache_desc.dminline, cache_desc.iminline);
861   for(i = 0; i < 7; i++)
862     {
863       unsigned int ct = (clidr >> (3 * i)) & 0x07;
864
865       cache_desc.dcache[i].width = 0;
866       cache_desc.icache[i].width = 0;
867
868       if(ct == 2 || ct == 3 || ct == 4)
869         {
870           /* Data.  */
871           stlink_write_debug32(sl, CSSELR, i << 1);
872           ILOG("D-Cache L%d: ", i);
873           read_cache_level_desc(sl, &cache_desc.dcache[i]);
874         }
875
876       if(ct == 1 || ct == 3)
877         {
878           /* Instruction.  */
879           stlink_write_debug32(sl, CSSELR, (i << 1) | 1);
880           ILOG("I-Cache L%d: ", i);
881           read_cache_level_desc(sl, &cache_desc.icache[i]);
882         }
883     }
884 }
885
886 static void cache_flush(stlink_t *sl, unsigned ccr) {
887   int level;
888
889   if (ccr & CCR_DC)
890     for (level = cache_desc.louu - 1; level >= 0; level--)
891       {
892         struct cache_level_desc *desc = &cache_desc.dcache[level];
893         unsigned addr;
894         unsigned max_addr = 1 << desc->width;
895         unsigned way_sh = 32 - desc->log2_nways;
896
897         /* D-cache clean by set-ways.  */
898         for (addr = (level << 1); addr < max_addr; addr += cache_desc.dminline)
899           {
900             unsigned int way;
901
902             for (way = 0; way < desc->nways; way++)
903               stlink_write_debug32(sl, DCCSW, addr | (way << way_sh));
904           }
905       }
906
907   /* Invalidate all I-cache to oPU.  */
908   if (ccr & CCR_IC)
909     stlink_write_debug32(sl, ICIALLU, 0);
910 }
911
912 static int cache_modified;
913
914 static void cache_change(stm32_addr_t start, unsigned count)
915 {
916   if (count == 0)
917     return;
918   (void)start;
919   cache_modified = 1;
920 }
921
922 static void cache_sync(stlink_t *sl)
923 {
924   unsigned ccr;
925
926   if(sl->chip_id!=STM32_CHIPID_F7)
927     return;
928   if (!cache_modified)
929     return;
930   cache_modified = 0;
931
932   stlink_read_debug32(sl, CCR, &ccr);
933   if (ccr & (CCR_IC | CCR_DC))
934     cache_flush(sl, ccr);
935 }
936
937 int serve(stlink_t *sl, st_state_t *st) {
938     int sock = socket(AF_INET, SOCK_STREAM, 0);
939     if(sock < 0) {
940         perror("socket");
941         return 1;
942     }
943
944     unsigned int val = 1;
945     setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
946
947     struct sockaddr_in serv_addr;
948     memset(&serv_addr,0,sizeof(struct sockaddr_in));
949     serv_addr.sin_family = AF_INET;
950     serv_addr.sin_addr.s_addr = INADDR_ANY;
951     serv_addr.sin_port = htons(st->listen_port);
952
953     if(bind(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
954         perror("bind");
955         return 1;
956     }
957
958     if(listen(sock, 5) < 0) {
959         perror("listen");
960         return 1;
961     }
962
963     ILOG("Listening at *:%d...\n", st->listen_port);
964
965     int client = accept(sock, NULL, NULL);
966     //signal (SIGINT, SIG_DFL);
967     if(client < 0) {
968         perror("accept");
969         return 1;
970     }
971
972     close(sock);
973
974     stlink_force_debug(sl);
975     if (st->reset) {
976         stlink_reset(sl);
977     }
978     init_code_breakpoints(sl);
979     init_data_watchpoints(sl);
980
981     ILOG("GDB connected.\n");
982
983     /*
984      * To allow resetting the chip from GDB it is required to
985      * emulate attaching and detaching to target.
986      */
987     unsigned int attached = 1;
988
989     while(1) {
990         char* packet;
991
992         int status = gdb_recv_packet(client, &packet);
993         if(status < 0) {
994             ELOG("cannot recv: %d\n", status);
995 #ifdef __MINGW32__
996             win32_close_socket(sock);
997 #endif
998             return 1;
999         }
1000
1001         DLOG("recv: %s\n", packet);
1002
1003         char* reply = NULL;
1004         reg regp;
1005
1006         switch(packet[0]) {
1007             case 'q': {
1008                 if(packet[1] == 'P' || packet[1] == 'C' || packet[1] == 'L') {
1009                     reply = strdup("");
1010                     break;
1011                 }
1012
1013                 char *separator = strstr(packet, ":"), *params = "";
1014                 if(separator == NULL) {
1015                     separator = packet + strlen(packet);
1016                 } else {
1017                     params = separator + 1;
1018                 }
1019
1020                 unsigned queryNameLength = (separator - &packet[1]);
1021                 char* queryName = calloc(queryNameLength + 1, 1);
1022                 strncpy(queryName, &packet[1], queryNameLength);
1023
1024                 DLOG("query: %s;%s\n", queryName, params);
1025
1026                 if(!strcmp(queryName, "Supported")) {
1027                     if(sl->chip_id==STM32_CHIPID_F4
1028                        || sl->chip_id==STM32_CHIPID_F4_HD
1029                        || sl->chip_id==STM32_CHIPID_F7) {
1030                         reply = strdup("PacketSize=3fff;qXfer:memory-map:read+;qXfer:features:read+");
1031                     }
1032                     else {
1033                         reply = strdup("PacketSize=3fff;qXfer:memory-map:read+");
1034                     }
1035                 } else if(!strcmp(queryName, "Xfer")) {
1036                     char *type, *op, *__s_addr, *s_length;
1037                     char *tok = params;
1038                     char *annex __attribute__((unused));
1039
1040                     type     = strsep(&tok, ":");
1041                     op       = strsep(&tok, ":");
1042                     annex    = strsep(&tok, ":");
1043                     __s_addr   = strsep(&tok, ",");
1044                     s_length = tok;
1045
1046                     unsigned addr = strtoul(__s_addr, NULL, 16),
1047                              length = strtoul(s_length, NULL, 16);
1048
1049                     DLOG("Xfer: type:%s;op:%s;annex:%s;addr:%d;length:%d\n",
1050                                 type, op, annex, addr, length);
1051
1052                     const char* data = NULL;
1053
1054                     if(!strcmp(type, "memory-map") && !strcmp(op, "read"))
1055                         data = current_memory_map;
1056
1057                     if(!strcmp(type, "features") && !strcmp(op, "read"))
1058                         data = target_description_F4;
1059
1060                     if(data) {
1061                         unsigned data_length = strlen(data);
1062                         if(addr + length > data_length)
1063                             length = data_length - addr;
1064
1065                         if(length == 0) {
1066                             reply = strdup("l");
1067                         } else {
1068                             reply = calloc(length + 2, 1);
1069                             reply[0] = 'm';
1070                             strncpy(&reply[1], data, length);
1071                         }
1072                     }
1073                 } else if(!strncmp(queryName, "Rcmd,",4)) {
1074                     // Rcmd uses the wrong separator
1075                     char *separator = strstr(packet, ","), *params = "";
1076                     if(separator == NULL) {
1077                         separator = packet + strlen(packet);
1078                     } else {
1079                         params = separator + 1;
1080                     }
1081
1082
1083                     if (!strncmp(params,"726573756d65",12)) {// resume
1084                         DLOG("Rcmd: resume\n");
1085                         cache_sync(sl);
1086                         stlink_run(sl);
1087
1088                         reply = strdup("OK");
1089                     } else if (!strncmp(params,"68616c74",8)) { //halt
1090                         reply = strdup("OK");
1091
1092                         stlink_force_debug(sl);
1093
1094                         DLOG("Rcmd: halt\n");
1095                     } else if (!strncmp(params,"6a7461675f7265736574",20)) { //jtag_reset
1096                         reply = strdup("OK");
1097
1098                         stlink_jtag_reset(sl, 0);
1099                         stlink_jtag_reset(sl, 1);
1100                         stlink_force_debug(sl);
1101
1102                         DLOG("Rcmd: jtag_reset\n");
1103                     } else if (!strncmp(params,"7265736574",10)) { //reset
1104                         reply = strdup("OK");
1105
1106                         stlink_force_debug(sl);
1107                         stlink_reset(sl);
1108                         init_code_breakpoints(sl);
1109                         init_data_watchpoints(sl);
1110
1111                         DLOG("Rcmd: reset\n");
1112                     } else {
1113                         DLOG("Rcmd: %s\n", params);
1114                     }
1115
1116                 }
1117
1118                 if(reply == NULL)
1119                     reply = strdup("");
1120
1121                 free(queryName);
1122
1123                 break;
1124             }
1125
1126             case 'v': {
1127                 char *params = NULL;
1128                 char *cmdName = strtok_r(packet, ":;", &params);
1129
1130                 cmdName++; // vCommand -> Command
1131
1132                 if(!strcmp(cmdName, "FlashErase")) {
1133                     char *__s_addr, *s_length;
1134                     char *tok = params;
1135
1136                     __s_addr   = strsep(&tok, ",");
1137                     s_length = tok;
1138
1139                     unsigned addr = strtoul(__s_addr, NULL, 16),
1140                              length = strtoul(s_length, NULL, 16);
1141
1142                     DLOG("FlashErase: addr:%08x,len:%04x\n",
1143                                 addr, length);
1144
1145                     if(flash_add_block(addr, length, sl) < 0) {
1146                         reply = strdup("E00");
1147                     } else {
1148                         reply = strdup("OK");
1149                     }
1150                 } else if(!strcmp(cmdName, "FlashWrite")) {
1151                     char *__s_addr, *data;
1152                     char *tok = params;
1153
1154                     __s_addr = strsep(&tok, ":");
1155                     data   = tok;
1156
1157                     unsigned addr = strtoul(__s_addr, NULL, 16);
1158                     unsigned data_length = status - (data - packet);
1159
1160                     // Length of decoded data cannot be more than
1161                     // encoded, as escapes are removed.
1162                     // Additional byte is reserved for alignment fix.
1163                     uint8_t *decoded = calloc(data_length + 1, 1);
1164                     unsigned dec_index = 0;
1165                     for(unsigned int i = 0; i < data_length; i++) {
1166                         if(data[i] == 0x7d) {
1167                             i++;
1168                             decoded[dec_index++] = data[i] ^ 0x20;
1169                         } else {
1170                             decoded[dec_index++] = data[i];
1171                         }
1172                     }
1173
1174                     // Fix alignment
1175                     if(dec_index % 2 != 0)
1176                         dec_index++;
1177
1178                     DLOG("binary packet %d -> %d\n", data_length, dec_index);
1179
1180                     if(flash_populate(addr, decoded, dec_index) < 0) {
1181                         reply = strdup("E00");
1182                     } else {
1183                         reply = strdup("OK");
1184                     }
1185                 } else if(!strcmp(cmdName, "FlashDone")) {
1186                     if(flash_go(sl) < 0) {
1187                         reply = strdup("E00");
1188                     } else {
1189                         reply = strdup("OK");
1190                     }
1191                 } else if(!strcmp(cmdName, "Kill")) {
1192                     attached = 0;
1193
1194                     reply = strdup("OK");
1195                 }
1196
1197                 if(reply == NULL)
1198                     reply = strdup("");
1199
1200                 break;
1201             }
1202
1203             case 'c':
1204                 cache_sync(sl);
1205                 stlink_run(sl);
1206
1207                 while(1) {
1208                     int status = gdb_check_for_interrupt(client);
1209                     if(status < 0) {
1210                         ELOG("cannot check for int: %d\n", status);
1211 #ifdef __MINGW32__
1212                         win32_close_socket(sock);
1213 #endif
1214                         return 1;
1215                     }
1216
1217                     if(status == 1) {
1218                         stlink_force_debug(sl);
1219                         break;
1220                     }
1221
1222                     stlink_status(sl);
1223                     if(sl->core_stat == STLINK_CORE_HALTED) {
1224                         break;
1225                     }
1226
1227                     usleep(100000);
1228                 }
1229
1230                 reply = strdup("S05"); // TRAP
1231                 break;
1232
1233             case 's':
1234                 cache_sync(sl);
1235                 stlink_step(sl);
1236
1237                 reply = strdup("S05"); // TRAP
1238                 break;
1239
1240             case '?':
1241                 if(attached) {
1242                     reply = strdup("S05"); // TRAP
1243                 } else {
1244                     /* Stub shall reply OK if not attached. */
1245                     reply = strdup("OK");
1246                 }
1247                 break;
1248
1249             case 'g':
1250                 stlink_read_all_regs(sl, &regp);
1251
1252                 reply = calloc(8 * 16 + 1, 1);
1253                 for(int i = 0; i < 16; i++)
1254                     sprintf(&reply[i * 8], "%08x", htonl(regp.r[i]));
1255
1256                 break;
1257
1258             case 'p': {
1259                 unsigned id = strtoul(&packet[1], NULL, 16);
1260                 unsigned myreg = 0xDEADDEAD;
1261
1262                 if(id < 16) {
1263                     stlink_read_reg(sl, id, &regp);
1264                     myreg = htonl(regp.r[id]);
1265                 } else if(id == 0x19) {
1266                     stlink_read_reg(sl, 16, &regp);
1267                     myreg = htonl(regp.xpsr);
1268                 } else if(id == 0x1A) {
1269                     stlink_read_reg(sl, 17, &regp);
1270                     myreg = htonl(regp.main_sp);
1271                 } else if(id == 0x1B) {
1272                     stlink_read_reg(sl, 18, &regp);
1273                     myreg = htonl(regp.process_sp);
1274                 } else if(id == 0x1C) {
1275                     stlink_read_unsupported_reg(sl, id, &regp);
1276                     myreg = htonl(regp.control);
1277                 } else if(id == 0x1D) {
1278                     stlink_read_unsupported_reg(sl, id, &regp);
1279                     myreg = htonl(regp.faultmask);
1280                 } else if(id == 0x1E) {
1281                     stlink_read_unsupported_reg(sl, id, &regp);
1282                     myreg = htonl(regp.basepri);
1283                 } else if(id == 0x1F) {
1284                     stlink_read_unsupported_reg(sl, id, &regp);
1285                     myreg = htonl(regp.primask);
1286                 } else if(id >= 0x20 && id < 0x40) {
1287                     stlink_read_unsupported_reg(sl, id, &regp);
1288                     myreg = htonl(regp.s[id-0x20]);
1289                 } else if(id == 0x40) {
1290                     stlink_read_unsupported_reg(sl, id, &regp);
1291                     myreg = htonl(regp.fpscr);
1292                 } else {
1293                     reply = strdup("E00");
1294                 }
1295
1296                 reply = calloc(8 + 1, 1);
1297                 sprintf(reply, "%08x", myreg);
1298
1299                 break;
1300             }
1301
1302             case 'P': {
1303                 char* s_reg = &packet[1];
1304                 char* s_value = strstr(&packet[1], "=") + 1;
1305
1306                 unsigned reg   = strtoul(s_reg,   NULL, 16);
1307                 unsigned value = strtoul(s_value, NULL, 16);
1308
1309                 if(reg < 16) {
1310                     stlink_write_reg(sl, ntohl(value), reg);
1311                 } else if(reg == 0x19) {
1312                     stlink_write_reg(sl, ntohl(value), 16);
1313                 } else if(reg == 0x1A) {
1314                     stlink_write_reg(sl, ntohl(value), 17);
1315                 } else if(reg == 0x1B) {
1316                     stlink_write_reg(sl, ntohl(value), 18);
1317                 } else if(reg == 0x1C) {
1318                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1319                 } else if(reg == 0x1D) {
1320                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1321                 } else if(reg == 0x1E) {
1322                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1323                 } else if(reg == 0x1F) {
1324                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1325                 } else if(reg >= 0x20 && reg < 0x40) {
1326                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1327                 } else if(reg == 0x40) {
1328                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1329                 } else {
1330                     reply = strdup("E00");
1331                 }
1332
1333                 if(!reply) {
1334                     reply = strdup("OK");
1335                 }
1336
1337                 break;
1338             }
1339
1340             case 'G':
1341                 for(int i = 0; i < 16; i++) {
1342                     char str[9] = {0};
1343                     strncpy(str, &packet[1 + i * 8], 8);
1344                     uint32_t reg = strtoul(str, NULL, 16);
1345                     stlink_write_reg(sl, ntohl(reg), i);
1346                 }
1347
1348                 reply = strdup("OK");
1349                 break;
1350
1351             case 'm': {
1352                 char* s_start = &packet[1];
1353                 char* s_count = strstr(&packet[1], ",") + 1;
1354
1355                 stm32_addr_t start = strtoul(s_start, NULL, 16);
1356                 unsigned     count = strtoul(s_count, NULL, 16);
1357
1358                 unsigned adj_start = start % 4;
1359                 unsigned count_rnd = (count + adj_start + 4 - 1) / 4 * 4;
1360                 if (count_rnd > sl->flash_pgsz)
1361                     count_rnd = sl->flash_pgsz;
1362                 if (count_rnd > 0x1800)
1363                     count_rnd = 0x1800;
1364                 if (count_rnd < count)
1365                     count = count_rnd;
1366
1367                 stlink_read_mem32(sl, start - adj_start, count_rnd);
1368
1369                 reply = calloc(count * 2 + 1, 1);
1370                 for(unsigned int i = 0; i < count; i++) {
1371                     reply[i * 2 + 0] = hex[sl->q_buf[i + adj_start] >> 4];
1372                     reply[i * 2 + 1] = hex[sl->q_buf[i + adj_start] & 0xf];
1373                 }
1374
1375                 break;
1376             }
1377
1378             case 'M': {
1379                 char* s_start = &packet[1];
1380                 char* s_count = strstr(&packet[1], ",") + 1;
1381                 char* hexdata = strstr(packet, ":") + 1;
1382
1383                 stm32_addr_t start = strtoul(s_start, NULL, 16);
1384                 unsigned     count = strtoul(s_count, NULL, 16);
1385
1386                 if(start % 4) {
1387                     unsigned align_count = 4 - start % 4;
1388                     if (align_count > count) align_count = count;
1389                     for(unsigned int i = 0; i < align_count; i ++) {
1390                         char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1391                         uint8_t byte = strtoul(hex, NULL, 16);
1392                         sl->q_buf[i] = byte;
1393                     }
1394                     stlink_write_mem8(sl, start, align_count);
1395                     cache_change(start, align_count);
1396                     start += align_count;
1397                     count -= align_count;
1398                     hexdata += 2*align_count;
1399                 }
1400
1401                 if(count - count % 4) {
1402                     unsigned aligned_count = count - count % 4;
1403
1404                     for(unsigned int i = 0; i < aligned_count; i ++) {
1405                         char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1406                         uint8_t byte = strtoul(hex, NULL, 16);
1407                         sl->q_buf[i] = byte;
1408                     }
1409                     stlink_write_mem32(sl, start, aligned_count);
1410                     cache_change(start, aligned_count);
1411                     count -= aligned_count;
1412                     start += aligned_count;
1413                     hexdata += 2*aligned_count;
1414                 }
1415
1416                 if(count) {
1417                     for(unsigned int i = 0; i < count; i ++) {
1418                         char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1419                         uint8_t byte = strtoul(hex, NULL, 16);
1420                         sl->q_buf[i] = byte;
1421                     }
1422                     stlink_write_mem8(sl, start, count);
1423                     cache_change(start, count);
1424                 }
1425                 reply = strdup("OK");
1426                 break;
1427             }
1428
1429             case 'Z': {
1430                 char *endptr;
1431                 stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
1432                 stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
1433
1434                 switch (packet[1]) {
1435                     case '1':
1436                         if(update_code_breakpoint(sl, addr, 1) < 0) {
1437                             reply = strdup("E00");
1438                         } else {
1439                             reply = strdup("OK");
1440                         }
1441                         break;
1442
1443                     case '2':   // insert write watchpoint
1444                     case '3':   // insert read  watchpoint
1445                     case '4': { // insert access watchpoint
1446                         enum watchfun wf;
1447                         if(packet[1] == '2') {
1448                             wf = WATCHWRITE;
1449                         } else if(packet[1] == '3') {
1450                             wf = WATCHREAD;
1451                         } else {
1452                             wf = WATCHACCESS;
1453                         }
1454
1455                         if(add_data_watchpoint(sl, wf, addr, len) < 0) {
1456                             reply = strdup("E00");
1457                         } else {
1458                             reply = strdup("OK");
1459                             break;
1460                         }
1461                     }
1462
1463                     default:
1464                         reply = strdup("");
1465                 }
1466                 break;
1467             }
1468             case 'z': {
1469                 char *endptr;
1470                 stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
1471                 //stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
1472
1473                 switch (packet[1]) {
1474                     case '1': // remove breakpoint
1475                         update_code_breakpoint(sl, addr, 0);
1476                         reply = strdup("OK");
1477                         break;
1478
1479                     case '2' : // remove write watchpoint
1480                     case '3' : // remove read watchpoint
1481                     case '4' : // remove access watchpoint
1482                         if(delete_data_watchpoint(sl, addr) < 0) {
1483                             reply = strdup("E00");
1484                         } else {
1485                             reply = strdup("OK");
1486                             break;
1487                         }
1488
1489                     default:
1490                         reply = strdup("");
1491                 }
1492                 break;
1493             }
1494
1495             case '!': {
1496                 /*
1497                  * Enter extended mode which allows restarting.
1498                  * We do support that always.
1499                  */
1500
1501                 /*
1502                  * Also, set to persistent mode
1503                  * to allow GDB disconnect.
1504                  */
1505                 st->persistent = 1;
1506
1507                 reply = strdup("OK");
1508
1509                 break;
1510             }
1511
1512             case 'R': {
1513                 /* Reset the core. */
1514
1515                 stlink_reset(sl);
1516                 init_code_breakpoints(sl);
1517                 init_data_watchpoints(sl);
1518
1519                 attached = 1;
1520
1521                 reply = strdup("OK");
1522
1523                 break;
1524             }
1525
1526             default:
1527                 reply = strdup("");
1528         }
1529
1530         if(reply) {
1531             DLOG("send: %s\n", reply);
1532
1533             int result = gdb_send_packet(client, reply);
1534             if(result != 0) {
1535                 ELOG("cannot send: %d\n", result);
1536                 free(reply);
1537                 free(packet);
1538 #ifdef __MINGW32__
1539                 win32_close_socket(sock);
1540 #endif
1541                 return 1;
1542             }
1543
1544             free(reply);
1545         }
1546
1547         free(packet);
1548     }
1549
1550 #ifdef __MINGW32__
1551     win32_close_socket(sock);
1552 #endif
1553
1554     return 0;
1555 }