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