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