Merge pull request #376 from gtalusan/master
[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     DLOG("init watchpoints\n");
492
493     // set trcena in debug command to turn on dwt unit
494     stlink_write_debug32(sl, 0xE000EDFC,
495             stlink_read_debug32(sl, 0xE000EDFC) | (1<<24));
496
497     // make sure all watchpoints are cleared
498     for(int i = 0; i < DATA_WATCH_NUM; i++) {
499         data_watches[i].fun = WATCHDISABLED;
500         stlink_write_debug32(sl, 0xe0001028 + i * 16, 0);
501     }
502 }
503
504 static int add_data_watchpoint(stlink_t *sl, enum watchfun wf,
505                                stm32_addr_t addr, unsigned int len) {
506     int i = 0;
507     uint32_t mask;
508
509     // computer mask
510     // find a free watchpoint
511     // configure
512
513     mask = -1;
514     i = len;
515     while(i) {
516         i >>= 1;
517         mask++;
518     }
519
520     if((mask != (uint32_t)-1) && (mask < 16)) {
521         for(i = 0; i < DATA_WATCH_NUM; i++) {
522             // is this an empty slot ?
523             if(data_watches[i].fun == WATCHDISABLED) {
524                 DLOG("insert watchpoint %d addr %x wf %u mask %u len %d\n", i, addr, wf, mask, len);
525
526                 data_watches[i].fun = wf;
527                 data_watches[i].addr = addr;
528                 data_watches[i].mask = mask;
529
530                 // insert comparator address
531                 stlink_write_debug32(sl, 0xE0001020 + i * 16, addr);
532
533                 // insert mask
534                 stlink_write_debug32(sl, 0xE0001024 + i * 16, mask);
535
536                 // insert function
537                 stlink_write_debug32(sl, 0xE0001028 + i * 16, wf);
538
539                 // just to make sure the matched bit is clear !
540                 stlink_read_debug32(sl,  0xE0001028 + i * 16);
541                 return 0;
542             }
543         }
544     }
545
546     DLOG("failure: add watchpoints addr %x wf %u len %u\n", addr, wf, len);
547     return -1;
548 }
549
550 static int delete_data_watchpoint(stlink_t *sl, stm32_addr_t addr)
551 {
552     int i;
553
554     for(i = 0 ; i < DATA_WATCH_NUM; i++) {
555         if((data_watches[i].addr == addr) && (data_watches[i].fun != WATCHDISABLED)) {
556             DLOG("delete watchpoint %d addr %x\n", i, addr);
557
558             data_watches[i].fun = WATCHDISABLED;
559             stlink_write_debug32(sl, 0xe0001028 + i * 16, 0);
560
561             return 0;
562         }
563     }
564
565     DLOG("failure: delete watchpoint addr %x\n", addr);
566
567     return -1;
568 }
569
570 int code_break_num;
571 int code_lit_num;
572 #define CODE_BREAK_NUM_MAX      15
573 #define CODE_BREAK_LOW  0x01
574 #define CODE_BREAK_HIGH 0x02
575
576 struct code_hw_breakpoint {
577     stm32_addr_t addr;
578     int          type;
579 };
580
581 struct code_hw_breakpoint code_breaks[CODE_BREAK_NUM_MAX];
582
583 static void init_code_breakpoints(stlink_t *sl) {
584     memset(sl->q_buf, 0, 4);
585     stlink_write_debug32(sl, CM3_REG_FP_CTRL, 0x03 /*KEY | ENABLE4*/);
586     unsigned int val = stlink_read_debug32(sl, CM3_REG_FP_CTRL);
587     code_break_num = ((val >> 4) & 0xf);
588     code_lit_num = ((val >> 8) & 0xf);
589
590     ILOG("Found %i hw breakpoint registers\n", code_break_num);
591
592     for(int i = 0; i < code_break_num; i++) {
593         code_breaks[i].type = 0;
594         stlink_write_debug32(sl, CM3_REG_FP_COMP0 + i * 4, 0);
595     }
596 }
597
598 static int update_code_breakpoint(stlink_t *sl, stm32_addr_t addr, int set) {
599     stm32_addr_t fpb_addr;
600     uint32_t mask;
601     int type = (addr & 0x2) ? CODE_BREAK_HIGH : CODE_BREAK_LOW;
602
603     if(addr & 1) {
604         ELOG("update_code_breakpoint: unaligned address %08x\n", addr);
605         return -1;
606     }
607
608         if (sl->chip_id==STM32_CHIPID_F7) {
609                 fpb_addr = addr;
610         } else {
611                 fpb_addr = addr & ~0x3;
612         }
613
614     int id = -1;
615     for(int i = 0; i < code_break_num; i++) {
616         if(fpb_addr == code_breaks[i].addr ||
617                 (set && code_breaks[i].type == 0)) {
618             id = i;
619             break;
620         }
621     }
622
623     if(id == -1) {
624         if(set) return -1; // Free slot not found
625         else    return 0;  // Breakpoint is already removed
626     }
627
628     struct code_hw_breakpoint* brk = &code_breaks[id];
629
630     brk->addr = fpb_addr;
631
632         if (sl->chip_id==STM32_CHIPID_F7) {
633                 if(set) brk->type = type;
634                 else    brk->type = 0;
635
636                 mask = (brk->addr) | 1;
637         } else {
638                 if(set) brk->type |= type;
639                 else    brk->type &= ~type;
640
641                 mask = (brk->addr) | 1 | (brk->type << 30);
642         }
643
644     if(brk->type == 0) {
645         DLOG("clearing hw break %d\n", id);
646
647         stlink_write_debug32(sl, 0xe0002008 + id * 4, 0);
648     } else {
649         DLOG("setting hw break %d at %08x (%d)\n",
650                     id, brk->addr, brk->type);
651         DLOG("reg %08x \n",
652                     mask);
653
654         stlink_write_debug32(sl, 0xe0002008 + id * 4, mask);
655     }
656
657     return 0;
658 }
659
660
661 struct flash_block {
662     stm32_addr_t addr;
663     unsigned     length;
664     uint8_t*     data;
665
666     struct flash_block* next;
667 };
668
669 static struct flash_block* flash_root;
670
671 static int flash_add_block(stm32_addr_t addr, unsigned length, stlink_t *sl) {
672
673     if(addr < FLASH_BASE || addr + length > FLASH_BASE + sl->flash_size) {
674         ELOG("flash_add_block: incorrect bounds\n");
675         return -1;
676     }
677
678     stlink_calculate_pagesize(sl, addr);
679     if(addr % FLASH_PAGE != 0 || length % FLASH_PAGE != 0) {
680         ELOG("flash_add_block: unaligned block\n");
681         return -1;
682     }
683
684     struct flash_block* new = malloc(sizeof(struct flash_block));
685     new->next = flash_root;
686
687     new->addr   = addr;
688     new->length = length;
689     new->data   = calloc(length, 1);
690
691     flash_root = new;
692
693     return 0;
694 }
695
696 static int flash_populate(stm32_addr_t addr, uint8_t* data, unsigned length) {
697     unsigned int fit_blocks = 0, fit_length = 0;
698
699     for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
700         /* Block: ------X------Y--------
701          * Data:            a-----b
702          *                a--b
703          *            a-----------b
704          * Block intersects with data, if:
705          *  a < Y && b > x
706          */
707
708         unsigned X = fb->addr, Y = fb->addr + fb->length;
709         unsigned a = addr, b = addr + length;
710         if(a < Y && b > X) {
711             // from start of the block
712             unsigned start = (a > X ? a : X) - X;
713             unsigned end   = (b > Y ? Y : b) - X;
714
715             memcpy(fb->data + start, data, end - start);
716
717             fit_blocks++;
718             fit_length += end - start;
719         }
720     }
721
722     if(fit_blocks == 0) {
723         ELOG("Unfit data block %08x -> %04x\n", addr, length);
724         return -1;
725     }
726
727     if(fit_length != length) {
728         WLOG("data block %08x -> %04x truncated to %04x\n",
729                 addr, length, fit_length);
730         WLOG("(this is not an error, just a GDB glitch)\n");
731     }
732
733     return 0;
734 }
735
736 static int flash_go(stlink_t *sl) {
737     int error = -1;
738
739     // Some kinds of clock settings do not allow writing to flash.
740     stlink_reset(sl);
741     stlink_force_debug(sl);
742
743     for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
744         DLOG("flash_do: block %08x -> %04x\n", fb->addr, fb->length);
745
746         for(stm32_addr_t page = fb->addr; page < fb->addr + fb->length; page += FLASH_PAGE) {
747             unsigned length = fb->length - (page - fb->addr);
748
749             //Update FLASH_PAGE
750             stlink_calculate_pagesize(sl, page);
751
752             DLOG("flash_do: page %08x\n", page);
753             unsigned send = length > FLASH_PAGE ? FLASH_PAGE : length;
754             if(stlink_write_flash(sl, page, fb->data + (page - fb->addr),
755                         send) < 0)
756                 goto error;
757             length -= send;
758             
759         }
760     }
761
762     stlink_reset(sl);
763
764     error = 0;
765
766 error:
767     for(struct flash_block* fb = flash_root, *next; fb; fb = next) {
768         next = fb->next;
769         free(fb->data);
770         free(fb);
771     }
772
773     flash_root = NULL;
774
775     return error;
776 }
777
778 #define CLIDR   0xE000ED78
779 #define CTR     0xE000ED7C
780 #define CCSIDR  0xE000ED80
781 #define CSSELR  0xE000ED84
782 #define CCR     0xE000ED14
783 #define CCR_DC  (1 << 16)
784 #define CCR_IC  (1 << 17)
785 #define DCCSW   0xE000EF6C
786 #define ICIALLU 0xE000EF50
787
788 struct cache_level_desc
789 {
790   unsigned int nsets;
791   unsigned int nways;
792   unsigned int log2_nways;
793   unsigned int width;
794 };
795
796 struct cache_desc_t
797 {
798   /* Minimal line size in bytes.  */
799   unsigned int dminline;
800   unsigned int iminline;
801
802   /* Last level of unification (uniprocessor).  */
803   unsigned int louu;
804
805   struct cache_level_desc icache[7];
806   struct cache_level_desc dcache[7];
807 };
808
809 static struct cache_desc_t cache_desc;
810
811 /* Return the smallest R so that V <= (1 << R).  Not performance critical.  */
812 static unsigned ceil_log2(unsigned v)
813 {
814   unsigned res;
815   for (res = 0; (1U << res) < v; res++)
816     ;
817   return res;
818 }
819
820 static void read_cache_level_desc(stlink_t *sl, struct cache_level_desc *desc)
821 {
822   unsigned int ccsidr;
823   unsigned int log2_nsets;
824   ccsidr = stlink_read_debug32(sl, CCSIDR);
825   desc->nsets = ((ccsidr >> 13) & 0x3fff) + 1;
826   desc->nways = ((ccsidr >> 3) & 0x1ff) + 1;
827   desc->log2_nways = ceil_log2 (desc->nways);
828   log2_nsets = ceil_log2 (desc->nsets);
829   desc->width = 4 + (ccsidr & 7) + log2_nsets;
830   ILOG("%08x LineSize: %u, ways: %u, sets: %u (width: %u)\n",
831        ccsidr, 4 << (ccsidr & 7), desc->nways, desc->nsets, desc->width);
832 }
833
834 static void init_cache (stlink_t *sl) {
835   unsigned int clidr;
836   unsigned int ccr;
837   unsigned int ctr;
838   int i;
839
840   /* Assume only F7 has a cache.  */
841   if(sl->chip_id!=STM32_CHIPID_F7)
842     return;
843
844   clidr = stlink_read_debug32(sl, CLIDR);
845   ccr = stlink_read_debug32(sl, CCR);
846   ctr = stlink_read_debug32(sl, CTR);
847   cache_desc.dminline = 4 << ((ctr >> 16) & 0x0f);
848   cache_desc.iminline = 4 << (ctr & 0x0f);
849   cache_desc.louu = (clidr >> 27) & 7;
850
851   ILOG("Chip clidr: %08x, I-Cache: %s, D-Cache: %s\n",
852        clidr, ccr & CCR_IC ? "on" : "off", ccr & CCR_DC ? "on" : "off");
853   ILOG(" cache: LoUU: %u, LoC: %u, LoUIS: %u\n",
854        (clidr >> 27) & 7, (clidr >> 24) & 7, (clidr >> 21) & 7);
855   ILOG(" cache: ctr: %08x, DminLine: %u bytes, IminLine: %u bytes\n", ctr,
856        cache_desc.dminline, cache_desc.iminline);
857   for(i = 0; i < 7; i++)
858     {
859       unsigned int ct = (clidr >> (3 * i)) & 0x07;
860
861       cache_desc.dcache[i].width = 0;
862       cache_desc.icache[i].width = 0;
863
864       if(ct == 2 || ct == 3 || ct == 4)
865         {
866           /* Data.  */
867           stlink_write_debug32(sl, CSSELR, i << 1);
868           ILOG("D-Cache L%d: ", i);
869           read_cache_level_desc(sl, &cache_desc.dcache[i]);
870         }
871
872       if(ct == 1 || ct == 3)
873         {
874           /* Instruction.  */
875           stlink_write_debug32(sl, CSSELR, (i << 1) | 1);
876           ILOG("I-Cache L%d: ", i);
877           read_cache_level_desc(sl, &cache_desc.icache[i]);
878         }
879     }
880 }
881
882 static void cache_flush(stlink_t *sl, unsigned ccr) {
883   int level;
884
885   if (ccr & CCR_DC)
886     for (level = cache_desc.louu - 1; level >= 0; level--)
887       {
888         struct cache_level_desc *desc = &cache_desc.dcache[level];
889         unsigned addr;
890         unsigned max_addr = 1 << desc->width;
891         unsigned way_sh = 32 - desc->log2_nways;
892
893         /* D-cache clean by set-ways.  */
894         for (addr = (level << 1); addr < max_addr; addr += cache_desc.dminline)
895           {
896             unsigned int way;
897
898             for (way = 0; way < desc->nways; way++)
899               stlink_write_debug32(sl, DCCSW, addr | (way << way_sh));
900           }
901       }
902
903   /* Invalidate all I-cache to oPU.  */
904   if (ccr & CCR_IC)
905     stlink_write_debug32(sl, ICIALLU, 0);
906 }
907
908 static int cache_modified;
909
910 static void cache_change(stm32_addr_t start, unsigned count)
911 {
912   if (count == 0)
913     return;
914   (void)start;
915   cache_modified = 1;
916 }
917
918 static void cache_sync(stlink_t *sl)
919 {
920   unsigned ccr;
921
922   if(sl->chip_id!=STM32_CHIPID_F7)
923     return;
924   if (!cache_modified)
925     return;
926   cache_modified = 0;
927
928   ccr = stlink_read_debug32(sl, CCR);
929   if (ccr & (CCR_IC | CCR_DC))
930     cache_flush(sl, ccr);
931 }
932
933 int serve(stlink_t *sl, st_state_t *st) {
934     int sock = socket(AF_INET, SOCK_STREAM, 0);
935     if(sock < 0) {
936         perror("socket");
937         return 1;
938     }
939
940     unsigned int val = 1;
941     setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
942
943     struct sockaddr_in serv_addr;
944     memset(&serv_addr,0,sizeof(struct sockaddr_in));
945     serv_addr.sin_family = AF_INET;
946     serv_addr.sin_addr.s_addr = INADDR_ANY;
947     serv_addr.sin_port = htons(st->listen_port);
948
949     if(bind(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
950         perror("bind");
951         return 1;
952     }
953
954     if(listen(sock, 5) < 0) {
955         perror("listen");
956         return 1;
957     }
958
959     ILOG("Listening at *:%d...\n", st->listen_port);
960
961     int client = accept(sock, NULL, NULL);
962     //signal (SIGINT, SIG_DFL);
963     if(client < 0) {
964         perror("accept");
965         return 1;
966     }
967
968     close(sock);
969
970     stlink_force_debug(sl);
971     if (st->reset) {
972         stlink_reset(sl);
973     }
974     init_code_breakpoints(sl);
975     init_data_watchpoints(sl);
976
977     ILOG("GDB connected.\n");
978
979     /*
980      * To allow resetting the chip from GDB it is required to
981      * emulate attaching and detaching to target.
982      */
983     unsigned int attached = 1;
984
985     while(1) {
986         char* packet;
987
988         int status = gdb_recv_packet(client, &packet);
989         if(status < 0) {
990             ELOG("cannot recv: %d\n", status);
991 #ifdef __MINGW32__
992             win32_close_socket(sock);
993 #endif
994             return 1;
995         }
996
997         DLOG("recv: %s\n", packet);
998
999         char* reply = NULL;
1000         reg regp;
1001
1002         switch(packet[0]) {
1003             case 'q': {
1004                 if(packet[1] == 'P' || packet[1] == 'C' || packet[1] == 'L') {
1005                     reply = strdup("");
1006                     break;
1007                 }
1008
1009                 char *separator = strstr(packet, ":"), *params = "";
1010                 if(separator == NULL) {
1011                     separator = packet + strlen(packet);
1012                 } else {
1013                     params = separator + 1;
1014                 }
1015
1016                 unsigned queryNameLength = (separator - &packet[1]);
1017                 char* queryName = calloc(queryNameLength + 1, 1);
1018                 strncpy(queryName, &packet[1], queryNameLength);
1019
1020                 DLOG("query: %s;%s\n", queryName, params);
1021
1022                 if(!strcmp(queryName, "Supported")) {
1023                     if(sl->chip_id==STM32_CHIPID_F4
1024                        || sl->chip_id==STM32_CHIPID_F4_HD
1025                        || sl->chip_id==STM32_CHIPID_F7) {
1026                         reply = strdup("PacketSize=3fff;qXfer:memory-map:read+;qXfer:features:read+");
1027                     }
1028                     else {
1029                         reply = strdup("PacketSize=3fff;qXfer:memory-map:read+");
1030                     }
1031                 } else if(!strcmp(queryName, "Xfer")) {
1032                     char *type, *op, *__s_addr, *s_length;
1033                     char *tok = params;
1034                     char *annex __attribute__((unused));
1035
1036                     type     = strsep(&tok, ":");
1037                     op       = strsep(&tok, ":");
1038                     annex    = strsep(&tok, ":");
1039                     __s_addr   = strsep(&tok, ",");
1040                     s_length = tok;
1041
1042                     unsigned addr = strtoul(__s_addr, NULL, 16),
1043                              length = strtoul(s_length, NULL, 16);
1044
1045                     DLOG("Xfer: type:%s;op:%s;annex:%s;addr:%d;length:%d\n",
1046                                 type, op, annex, addr, length);
1047
1048                     const char* data = NULL;
1049
1050                     if(!strcmp(type, "memory-map") && !strcmp(op, "read"))
1051                         data = current_memory_map;
1052
1053                     if(!strcmp(type, "features") && !strcmp(op, "read"))
1054                         data = target_description_F4;
1055
1056                     if(data) {
1057                         unsigned data_length = strlen(data);
1058                         if(addr + length > data_length)
1059                             length = data_length - addr;
1060
1061                         if(length == 0) {
1062                             reply = strdup("l");
1063                         } else {
1064                             reply = calloc(length + 2, 1);
1065                             reply[0] = 'm';
1066                             strncpy(&reply[1], data, length);
1067                         }
1068                     }
1069                 } else if(!strncmp(queryName, "Rcmd,",4)) {
1070                     // Rcmd uses the wrong separator
1071                     char *separator = strstr(packet, ","), *params = "";
1072                     if(separator == NULL) {
1073                         separator = packet + strlen(packet);
1074                     } else {
1075                         params = separator + 1;
1076                     }
1077
1078
1079                     if (!strncmp(params,"726573756d65",12)) {// resume
1080                         DLOG("Rcmd: resume\n");
1081                         cache_sync(sl);
1082                         stlink_run(sl);
1083
1084                         reply = strdup("OK");
1085                     } else if (!strncmp(params,"68616c74",8)) { //halt
1086                         reply = strdup("OK");
1087
1088                         stlink_force_debug(sl);
1089
1090                         DLOG("Rcmd: halt\n");
1091                     } else if (!strncmp(params,"6a7461675f7265736574",20)) { //jtag_reset
1092                         reply = strdup("OK");
1093
1094                         stlink_jtag_reset(sl, 0);
1095                         stlink_jtag_reset(sl, 1);
1096                         stlink_force_debug(sl);
1097
1098                         DLOG("Rcmd: jtag_reset\n");
1099                     } else if (!strncmp(params,"7265736574",10)) { //reset
1100                         reply = strdup("OK");
1101
1102                         stlink_force_debug(sl);
1103                         stlink_reset(sl);
1104                         init_code_breakpoints(sl);
1105                         init_data_watchpoints(sl);
1106
1107                         DLOG("Rcmd: reset\n");
1108                     } else {
1109                         DLOG("Rcmd: %s\n", params);
1110                     }
1111
1112                 }
1113
1114                 if(reply == NULL)
1115                     reply = strdup("");
1116
1117                 free(queryName);
1118
1119                 break;
1120             }
1121
1122             case 'v': {
1123                 char *params = NULL;
1124                 char *cmdName = strtok_r(packet, ":;", &params);
1125
1126                 cmdName++; // vCommand -> Command
1127
1128                 if(!strcmp(cmdName, "FlashErase")) {
1129                     char *__s_addr, *s_length;
1130                     char *tok = params;
1131
1132                     __s_addr   = strsep(&tok, ",");
1133                     s_length = tok;
1134
1135                     unsigned addr = strtoul(__s_addr, NULL, 16),
1136                              length = strtoul(s_length, NULL, 16);
1137
1138                     DLOG("FlashErase: addr:%08x,len:%04x\n",
1139                                 addr, length);
1140
1141                     if(flash_add_block(addr, length, sl) < 0) {
1142                         reply = strdup("E00");
1143                     } else {
1144                         reply = strdup("OK");
1145                     }
1146                 } else if(!strcmp(cmdName, "FlashWrite")) {
1147                     char *__s_addr, *data;
1148                     char *tok = params;
1149
1150                     __s_addr = strsep(&tok, ":");
1151                     data   = tok;
1152
1153                     unsigned addr = strtoul(__s_addr, NULL, 16);
1154                     unsigned data_length = status - (data - packet);
1155
1156                     // Length of decoded data cannot be more than
1157                     // encoded, as escapes are removed.
1158                     // Additional byte is reserved for alignment fix.
1159                     uint8_t *decoded = calloc(data_length + 1, 1);
1160                     unsigned dec_index = 0;
1161                     for(unsigned int i = 0; i < data_length; i++) {
1162                         if(data[i] == 0x7d) {
1163                             i++;
1164                             decoded[dec_index++] = data[i] ^ 0x20;
1165                         } else {
1166                             decoded[dec_index++] = data[i];
1167                         }
1168                     }
1169
1170                     // Fix alignment
1171                     if(dec_index % 2 != 0)
1172                         dec_index++;
1173
1174                     DLOG("binary packet %d -> %d\n", data_length, dec_index);
1175
1176                     if(flash_populate(addr, decoded, dec_index) < 0) {
1177                         reply = strdup("E00");
1178                     } else {
1179                         reply = strdup("OK");
1180                     }
1181                 } else if(!strcmp(cmdName, "FlashDone")) {
1182                     if(flash_go(sl) < 0) {
1183                         reply = strdup("E00");
1184                     } else {
1185                         reply = strdup("OK");
1186                     }
1187                 } else if(!strcmp(cmdName, "Kill")) {
1188                     attached = 0;
1189
1190                     reply = strdup("OK");
1191                 }
1192
1193                 if(reply == NULL)
1194                     reply = strdup("");
1195
1196                 break;
1197             }
1198
1199             case 'c':
1200                 cache_sync(sl);
1201                 stlink_run(sl);
1202
1203                 while(1) {
1204                     int status = gdb_check_for_interrupt(client);
1205                     if(status < 0) {
1206                         ELOG("cannot check for int: %d\n", status);
1207 #ifdef __MINGW32__
1208                         win32_close_socket(sock);
1209 #endif
1210                         return 1;
1211                     }
1212
1213                     if(status == 1) {
1214                         stlink_force_debug(sl);
1215                         break;
1216                     }
1217
1218                     stlink_status(sl);
1219                     if(sl->core_stat == STLINK_CORE_HALTED) {
1220                         break;
1221                     }
1222
1223                     usleep(100000);
1224                 }
1225
1226                 reply = strdup("S05"); // TRAP
1227                 break;
1228
1229             case 's':
1230                 cache_sync(sl);
1231                 stlink_step(sl);
1232
1233                 reply = strdup("S05"); // TRAP
1234                 break;
1235
1236             case '?':
1237                 if(attached) {
1238                     reply = strdup("S05"); // TRAP
1239                 } else {
1240                     /* Stub shall reply OK if not attached. */
1241                     reply = strdup("OK");
1242                 }
1243                 break;
1244
1245             case 'g':
1246                 stlink_read_all_regs(sl, &regp);
1247
1248                 reply = calloc(8 * 16 + 1, 1);
1249                 for(int i = 0; i < 16; i++)
1250                     sprintf(&reply[i * 8], "%08x", htonl(regp.r[i]));
1251
1252                 break;
1253
1254             case 'p': {
1255                 unsigned id = strtoul(&packet[1], NULL, 16);
1256                 unsigned myreg = 0xDEADDEAD;
1257
1258                 if(id < 16) {
1259                     stlink_read_reg(sl, id, &regp);
1260                     myreg = htonl(regp.r[id]);
1261                 } else if(id == 0x19) {
1262                     stlink_read_reg(sl, 16, &regp);
1263                     myreg = htonl(regp.xpsr);
1264                 } else if(id == 0x1A) {
1265                     stlink_read_reg(sl, 17, &regp);
1266                     myreg = htonl(regp.main_sp);
1267                 } else if(id == 0x1B) {
1268                     stlink_read_reg(sl, 18, &regp);
1269                     myreg = htonl(regp.process_sp);
1270                 } else if(id == 0x1C) {
1271                     stlink_read_unsupported_reg(sl, id, &regp);
1272                     myreg = htonl(regp.control);
1273                 } else if(id == 0x1D) {
1274                     stlink_read_unsupported_reg(sl, id, &regp);
1275                     myreg = htonl(regp.faultmask);
1276                 } else if(id == 0x1E) {
1277                     stlink_read_unsupported_reg(sl, id, &regp);
1278                     myreg = htonl(regp.basepri);
1279                 } else if(id == 0x1F) {
1280                     stlink_read_unsupported_reg(sl, id, &regp);
1281                     myreg = htonl(regp.primask);
1282                 } else if(id >= 0x20 && id < 0x40) {
1283                     stlink_read_unsupported_reg(sl, id, &regp);
1284                     myreg = htonl(regp.s[id-0x20]);
1285                 } else if(id == 0x40) {
1286                     stlink_read_unsupported_reg(sl, id, &regp);
1287                     myreg = htonl(regp.fpscr);
1288                 } else {
1289                     reply = strdup("E00");
1290                 }
1291
1292                 reply = calloc(8 + 1, 1);
1293                 sprintf(reply, "%08x", myreg);
1294
1295                 break;
1296             }
1297
1298             case 'P': {
1299                 char* s_reg = &packet[1];
1300                 char* s_value = strstr(&packet[1], "=") + 1;
1301
1302                 unsigned reg   = strtoul(s_reg,   NULL, 16);
1303                 unsigned value = strtoul(s_value, NULL, 16);
1304
1305                 if(reg < 16) {
1306                     stlink_write_reg(sl, ntohl(value), reg);
1307                 } else if(reg == 0x19) {
1308                     stlink_write_reg(sl, ntohl(value), 16);
1309                 } else if(reg == 0x1A) {
1310                     stlink_write_reg(sl, ntohl(value), 17);
1311                 } else if(reg == 0x1B) {
1312                     stlink_write_reg(sl, ntohl(value), 18);
1313                 } else if(reg == 0x1C) {
1314                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1315                 } else if(reg == 0x1D) {
1316                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1317                 } else if(reg == 0x1E) {
1318                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1319                 } else if(reg == 0x1F) {
1320                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1321                 } else if(reg >= 0x20 && reg < 0x40) {
1322                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1323                 } else if(reg == 0x40) {
1324                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1325                 } else {
1326                     reply = strdup("E00");
1327                 }
1328
1329                 if(!reply) {
1330                     reply = strdup("OK");
1331                 }
1332
1333                 break;
1334             }
1335
1336             case 'G':
1337                 for(int i = 0; i < 16; i++) {
1338                     char str[9] = {0};
1339                     strncpy(str, &packet[1 + i * 8], 8);
1340                     uint32_t reg = strtoul(str, NULL, 16);
1341                     stlink_write_reg(sl, ntohl(reg), i);
1342                 }
1343
1344                 reply = strdup("OK");
1345                 break;
1346
1347             case 'm': {
1348                 char* s_start = &packet[1];
1349                 char* s_count = strstr(&packet[1], ",") + 1;
1350
1351                 stm32_addr_t start = strtoul(s_start, NULL, 16);
1352                 unsigned     count = strtoul(s_count, NULL, 16);
1353
1354                 unsigned adj_start = start % 4;
1355                 unsigned count_rnd = (count + adj_start + 4 - 1) / 4 * 4;
1356                 if (count_rnd > sl->flash_pgsz)
1357                     count_rnd = sl->flash_pgsz;
1358                 if (count_rnd > 0x1800)
1359                     count_rnd = 0x1800;
1360                 if (count_rnd < count)
1361                     count = count_rnd;
1362
1363                 stlink_read_mem32(sl, start - adj_start, count_rnd);
1364
1365                 reply = calloc(count * 2 + 1, 1);
1366                 for(unsigned int i = 0; i < count; i++) {
1367                     reply[i * 2 + 0] = hex[sl->q_buf[i + adj_start] >> 4];
1368                     reply[i * 2 + 1] = hex[sl->q_buf[i + adj_start] & 0xf];
1369                 }
1370
1371                 break;
1372             }
1373
1374             case 'M': {
1375                 char* s_start = &packet[1];
1376                 char* s_count = strstr(&packet[1], ",") + 1;
1377                 char* hexdata = strstr(packet, ":") + 1;
1378
1379                 stm32_addr_t start = strtoul(s_start, NULL, 16);
1380                 unsigned     count = strtoul(s_count, NULL, 16);
1381
1382                 if(start % 4) {
1383                     unsigned align_count = 4 - start % 4;
1384                     if (align_count > count) align_count = count;
1385                     for(unsigned int i = 0; i < align_count; i ++) {
1386                         char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1387                         uint8_t byte = strtoul(hex, NULL, 16);
1388                         sl->q_buf[i] = byte;
1389                     }
1390                     stlink_write_mem8(sl, start, align_count);
1391                     cache_change(start, align_count);
1392                     start += align_count;
1393                     count -= align_count;
1394                     hexdata += 2*align_count;
1395                 }
1396
1397                 if(count - count % 4) {
1398                     unsigned aligned_count = count - count % 4;
1399
1400                     for(unsigned int i = 0; i < aligned_count; i ++) {
1401                         char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1402                         uint8_t byte = strtoul(hex, NULL, 16);
1403                         sl->q_buf[i] = byte;
1404                     }
1405                     stlink_write_mem32(sl, start, aligned_count);
1406                     cache_change(start, aligned_count);
1407                     count -= aligned_count;
1408                     start += aligned_count;
1409                     hexdata += 2*aligned_count;
1410                 }
1411
1412                 if(count) {
1413                     for(unsigned int i = 0; i < count; i ++) {
1414                         char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1415                         uint8_t byte = strtoul(hex, NULL, 16);
1416                         sl->q_buf[i] = byte;
1417                     }
1418                     stlink_write_mem8(sl, start, count);
1419                     cache_change(start, count);
1420                 }
1421                 reply = strdup("OK");
1422                 break;
1423             }
1424
1425             case 'Z': {
1426                 char *endptr;
1427                 stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
1428                 stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
1429
1430                 switch (packet[1]) {
1431                     case '1':
1432                         if(update_code_breakpoint(sl, addr, 1) < 0) {
1433                             reply = strdup("E00");
1434                         } else {
1435                             reply = strdup("OK");
1436                         }
1437                         break;
1438
1439                     case '2':   // insert write watchpoint
1440                     case '3':   // insert read  watchpoint
1441                     case '4': { // insert access watchpoint
1442                         enum watchfun wf;
1443                         if(packet[1] == '2') {
1444                             wf = WATCHWRITE;
1445                         } else if(packet[1] == '3') {
1446                             wf = WATCHREAD;
1447                         } else {
1448                             wf = WATCHACCESS;
1449                         }
1450
1451                         if(add_data_watchpoint(sl, wf, addr, len) < 0) {
1452                             reply = strdup("E00");
1453                         } else {
1454                             reply = strdup("OK");
1455                             break;
1456                         }
1457                     }
1458
1459                     default:
1460                         reply = strdup("");
1461                 }
1462                 break;
1463             }
1464             case 'z': {
1465                 char *endptr;
1466                 stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
1467                 //stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
1468
1469                 switch (packet[1]) {
1470                     case '1': // remove breakpoint
1471                         update_code_breakpoint(sl, addr, 0);
1472                         reply = strdup("OK");
1473                         break;
1474
1475                     case '2' : // remove write watchpoint
1476                     case '3' : // remove read watchpoint
1477                     case '4' : // remove access watchpoint
1478                         if(delete_data_watchpoint(sl, addr) < 0) {
1479                             reply = strdup("E00");
1480                         } else {
1481                             reply = strdup("OK");
1482                             break;
1483                         }
1484
1485                     default:
1486                         reply = strdup("");
1487                 }
1488                 break;
1489             }
1490
1491             case '!': {
1492                 /*
1493                  * Enter extended mode which allows restarting.
1494                  * We do support that always.
1495                  */
1496
1497                 /*
1498                  * Also, set to persistent mode
1499                  * to allow GDB disconnect.
1500                  */
1501                 st->persistent = 1;
1502
1503                 reply = strdup("OK");
1504
1505                 break;
1506             }
1507
1508             case 'R': {
1509                 /* Reset the core. */
1510
1511                 stlink_reset(sl);
1512                 init_code_breakpoints(sl);
1513                 init_data_watchpoints(sl);
1514
1515                 attached = 1;
1516
1517                 reply = strdup("OK");
1518
1519                 break;
1520             }
1521
1522             default:
1523                 reply = strdup("");
1524         }
1525
1526         if(reply) {
1527             DLOG("send: %s\n", reply);
1528
1529             int result = gdb_send_packet(client, reply);
1530             if(result != 0) {
1531                 ELOG("cannot send: %d\n", result);
1532                 free(reply);
1533                 free(packet);
1534 #ifdef __MINGW32__
1535                 win32_close_socket(sock);
1536 #endif
1537                 return 1;
1538             }
1539
1540             free(reply);
1541         }
1542
1543         free(packet);
1544     }
1545
1546 #ifdef __MINGW32__
1547     win32_close_socket(sock);
1548 #endif
1549
1550     return 0;
1551 }