Merge pull request #313 from schodet/f2-memory
[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 char* make_memory_map(stlink_t *sl) {
387     /* This will be freed in serve() */
388     char* map = malloc(4096);
389     map[0] = '\0';
390
391     if(sl->chip_id==STM32_CHIPID_F4) {
392         strcpy(map, memory_map_template_F4);
393     } else if(sl->chip_id==STM32_CHIPID_F4_HD) {
394         strcpy(map, memory_map_template_F4_HD);
395     } else if(sl->chip_id==STM32_CHIPID_F2) {
396         snprintf(map, 4096, memory_map_template_F2,
397                 sl->flash_size,
398                 sl->sram_size,
399                 sl->flash_size - 0x20000,
400                 sl->sys_base, sl->sys_size);
401     } else {
402         snprintf(map, 4096, memory_map_template,
403                 sl->flash_size,
404                 sl->sram_size,
405                 sl->flash_size, sl->flash_pgsz,
406                 sl->sys_base, sl->sys_size);
407     }
408     return map;
409 }
410
411
412 /*
413  * DWT_COMP0     0xE0001020
414  * DWT_MASK0     0xE0001024
415  * DWT_FUNCTION0 0xE0001028
416  * DWT_COMP1     0xE0001030
417  * DWT_MASK1     0xE0001034
418  * DWT_FUNCTION1 0xE0001038
419  * DWT_COMP2     0xE0001040
420  * DWT_MASK2     0xE0001044
421  * DWT_FUNCTION2 0xE0001048
422  * DWT_COMP3     0xE0001050
423  * DWT_MASK3     0xE0001054
424  * DWT_FUNCTION3 0xE0001058
425  */
426
427 #define DATA_WATCH_NUM 4
428
429 enum watchfun { WATCHDISABLED = 0, WATCHREAD = 5, WATCHWRITE = 6, WATCHACCESS = 7 };
430
431 struct code_hw_watchpoint {
432     stm32_addr_t addr;
433     uint8_t mask;
434     enum watchfun fun;
435 };
436
437 struct code_hw_watchpoint data_watches[DATA_WATCH_NUM];
438
439 static void init_data_watchpoints(stlink_t *sl) {
440     DLOG("init watchpoints\n");
441
442     // set trcena in debug command to turn on dwt unit
443     stlink_write_debug32(sl, 0xE000EDFC,
444             stlink_read_debug32(sl, 0xE000EDFC) | (1<<24));
445
446     // make sure all watchpoints are cleared
447     for(int i = 0; i < DATA_WATCH_NUM; i++) {
448         data_watches[i].fun = WATCHDISABLED;
449         stlink_write_debug32(sl, 0xe0001028 + i * 16, 0);
450     }
451 }
452
453 static int add_data_watchpoint(stlink_t *sl, enum watchfun wf,
454                                stm32_addr_t addr, unsigned int len) {
455     int i = 0;
456     uint32_t mask;
457
458     // computer mask
459     // find a free watchpoint
460     // configure
461
462     mask = -1;
463     i = len;
464     while(i) {
465         i >>= 1;
466         mask++;
467     }
468
469     if((mask != (uint32_t)-1) && (mask < 16)) {
470         for(i = 0; i < DATA_WATCH_NUM; i++) {
471             // is this an empty slot ?
472             if(data_watches[i].fun == WATCHDISABLED) {
473                 DLOG("insert watchpoint %d addr %x wf %u mask %u len %d\n", i, addr, wf, mask, len);
474
475                 data_watches[i].fun = wf;
476                 data_watches[i].addr = addr;
477                 data_watches[i].mask = mask;
478
479                 // insert comparator address
480                 stlink_write_debug32(sl, 0xE0001020 + i * 16, addr);
481
482                 // insert mask
483                 stlink_write_debug32(sl, 0xE0001024 + i * 16, mask);
484
485                 // insert function
486                 stlink_write_debug32(sl, 0xE0001028 + i * 16, wf);
487
488                 // just to make sure the matched bit is clear !
489                 stlink_read_debug32(sl,  0xE0001028 + i * 16);
490                 return 0;
491             }
492         }
493     }
494
495     DLOG("failure: add watchpoints addr %x wf %u len %u\n", addr, wf, len);
496     return -1;
497 }
498
499 static int delete_data_watchpoint(stlink_t *sl, stm32_addr_t addr)
500 {
501     int i;
502
503     for(i = 0 ; i < DATA_WATCH_NUM; i++) {
504         if((data_watches[i].addr == addr) && (data_watches[i].fun != WATCHDISABLED)) {
505             DLOG("delete watchpoint %d addr %x\n", i, addr);
506
507             data_watches[i].fun = WATCHDISABLED;
508             stlink_write_debug32(sl, 0xe0001028 + i * 16, 0);
509
510             return 0;
511         }
512     }
513
514     DLOG("failure: delete watchpoint addr %x\n", addr);
515
516     return -1;
517 }
518
519 #define CODE_BREAK_NUM  6
520 #define CODE_LIT_NUM    2
521 #define CODE_BREAK_LOW  0x01
522 #define CODE_BREAK_HIGH 0x02
523
524 struct code_hw_breakpoint {
525     stm32_addr_t addr;
526     int          type;
527 };
528
529 struct code_hw_breakpoint code_breaks[CODE_BREAK_NUM];
530
531 static void init_code_breakpoints(stlink_t *sl) {
532     memset(sl->q_buf, 0, 4);
533     stlink_write_debug32(sl, CM3_REG_FP_CTRL, 0x03 /*KEY | ENABLE4*/);
534     unsigned int val = stlink_read_debug32(sl, CM3_REG_FP_CTRL);
535     if (((val & 3) != 1) ||
536             ((((val >> 8) & 0x70) | ((val >> 4) & 0xf)) != CODE_BREAK_NUM) ||
537             (((val >> 8) & 0xf) != CODE_LIT_NUM)){
538         ELOG("[FP_CTRL] = 0x%08x expecting 0x%08x\n", val,
539                 ((CODE_BREAK_NUM & 0x70) << 8) | (CODE_LIT_NUM << 8) |  ((CODE_BREAK_NUM & 0xf) << 4) | 1);
540     }
541
542
543     for(int i = 0; i < CODE_BREAK_NUM; i++) {
544         code_breaks[i].type = 0;
545         stlink_write_debug32(sl, CM3_REG_FP_COMP0 + i * 4, 0);
546     }
547 }
548
549 static int update_code_breakpoint(stlink_t *sl, stm32_addr_t addr, int set) {
550     stm32_addr_t fpb_addr = addr & ~0x3;
551     int type = addr & 0x2 ? CODE_BREAK_HIGH : CODE_BREAK_LOW;
552
553     if(addr & 1) {
554         ELOG("update_code_breakpoint: unaligned address %08x\n", addr);
555         return -1;
556     }
557
558     int id = -1;
559     for(int i = 0; i < CODE_BREAK_NUM; i++) {
560         if(fpb_addr == code_breaks[i].addr ||
561                 (set && code_breaks[i].type == 0)) {
562             id = i;
563             break;
564         }
565     }
566
567     if(id == -1) {
568         if(set) return -1; // Free slot not found
569         else    return 0;  // Breakpoint is already removed
570     }
571
572     struct code_hw_breakpoint* brk = &code_breaks[id];
573
574     brk->addr = fpb_addr;
575
576     if(set) brk->type |= type;
577     else        brk->type &= ~type;
578
579     if(brk->type == 0) {
580         DLOG("clearing hw break %d\n", id);
581
582         stlink_write_debug32(sl, 0xe0002008 + id * 4, 0);
583     } else {
584         uint32_t mask = (brk->addr) | 1 | (brk->type << 30);
585
586         DLOG("setting hw break %d at %08x (%d)\n",
587                     id, brk->addr, brk->type);
588         DLOG("reg %08x \n",
589                     mask);
590
591         stlink_write_debug32(sl, 0xe0002008 + id * 4, mask);
592     }
593
594     return 0;
595 }
596
597
598 struct flash_block {
599     stm32_addr_t addr;
600     unsigned     length;
601     uint8_t*     data;
602
603     struct flash_block* next;
604 };
605
606 static struct flash_block* flash_root;
607
608 static int flash_add_block(stm32_addr_t addr, unsigned length, stlink_t *sl) {
609
610     if(addr < FLASH_BASE || addr + length > FLASH_BASE + sl->flash_size) {
611         ELOG("flash_add_block: incorrect bounds\n");
612         return -1;
613     }
614
615     stlink_calculate_pagesize(sl, addr);
616     if(addr % FLASH_PAGE != 0 || length % FLASH_PAGE != 0) {
617         ELOG("flash_add_block: unaligned block\n");
618         return -1;
619     }
620
621     struct flash_block* new = malloc(sizeof(struct flash_block));
622     new->next = flash_root;
623
624     new->addr   = addr;
625     new->length = length;
626     new->data   = calloc(length, 1);
627
628     flash_root = new;
629
630     return 0;
631 }
632
633 static int flash_populate(stm32_addr_t addr, uint8_t* data, unsigned length) {
634     unsigned int fit_blocks = 0, fit_length = 0;
635
636     for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
637         /* Block: ------X------Y--------
638          * Data:            a-----b
639          *                a--b
640          *            a-----------b
641          * Block intersects with data, if:
642          *  a < Y && b > x
643          */
644
645         unsigned X = fb->addr, Y = fb->addr + fb->length;
646         unsigned a = addr, b = addr + length;
647         if(a < Y && b > X) {
648             // from start of the block
649             unsigned start = (a > X ? a : X) - X;
650             unsigned end   = (b > Y ? Y : b) - X;
651
652             memcpy(fb->data + start, data, end - start);
653
654             fit_blocks++;
655             fit_length += end - start;
656         }
657     }
658
659     if(fit_blocks == 0) {
660         ELOG("Unfit data block %08x -> %04x\n", addr, length);
661         return -1;
662     }
663
664     if(fit_length != length) {
665         WLOG("data block %08x -> %04x truncated to %04x\n",
666                 addr, length, fit_length);
667         WLOG("(this is not an error, just a GDB glitch)\n");
668     }
669
670     return 0;
671 }
672
673 static int flash_go(stlink_t *sl) {
674     int error = -1;
675
676     // Some kinds of clock settings do not allow writing to flash.
677     stlink_reset(sl);
678
679     for(struct flash_block* fb = flash_root; fb; fb = fb->next) {
680         DLOG("flash_do: block %08x -> %04x\n", fb->addr, fb->length);
681
682         unsigned length = fb->length;
683         for(stm32_addr_t page = fb->addr; page < fb->addr + fb->length; page += FLASH_PAGE) {
684
685             //Update FLASH_PAGE
686             stlink_calculate_pagesize(sl, page);
687
688             DLOG("flash_do: page %08x\n", page);
689
690             if(stlink_write_flash(sl, page, fb->data + (page - fb->addr),
691                         length > FLASH_PAGE ? FLASH_PAGE : length) < 0)
692                 goto error;
693         }
694     }
695
696     stlink_reset(sl);
697
698     error = 0;
699
700 error:
701     for(struct flash_block* fb = flash_root, *next; fb; fb = next) {
702         next = fb->next;
703         free(fb->data);
704         free(fb);
705     }
706
707     flash_root = NULL;
708
709     return error;
710 }
711
712 int serve(stlink_t *sl, st_state_t *st) {
713     int sock = socket(AF_INET, SOCK_STREAM, 0);
714     if(sock < 0) {
715         perror("socket");
716         return 1;
717     }
718
719     unsigned int val = 1;
720     setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
721
722     struct sockaddr_in serv_addr;
723     memset(&serv_addr,0,sizeof(struct sockaddr_in));
724     serv_addr.sin_family = AF_INET;
725     serv_addr.sin_addr.s_addr = INADDR_ANY;
726     serv_addr.sin_port = htons(st->listen_port);
727
728     if(bind(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
729         perror("bind");
730         return 1;
731     }
732
733     if(listen(sock, 5) < 0) {
734         perror("listen");
735         return 1;
736     }
737
738     ILOG("Listening at *:%d...\n", st->listen_port);
739
740     int client = accept(sock, NULL, NULL);
741     //signal (SIGINT, SIG_DFL);
742     if(client < 0) {
743         perror("accept");
744         return 1;
745     }
746
747     close(sock);
748
749     stlink_force_debug(sl);
750     if (st->reset) {
751         stlink_reset(sl);
752     }
753     init_code_breakpoints(sl);
754     init_data_watchpoints(sl);
755
756     ILOG("GDB connected.\n");
757
758     /*
759      * To allow resetting the chip from GDB it is required to
760      * emulate attaching and detaching to target.
761      */
762     unsigned int attached = 1;
763
764     while(1) {
765         char* packet;
766
767         int status = gdb_recv_packet(client, &packet);
768         if(status < 0) {
769             ELOG("cannot recv: %d\n", status);
770 #ifdef __MINGW32__
771             win32_close_socket(sock);
772 #endif
773             return 1;
774         }
775
776         DLOG("recv: %s\n", packet);
777
778         char* reply = NULL;
779         reg regp;
780
781         switch(packet[0]) {
782             case 'q': {
783                 if(packet[1] == 'P' || packet[1] == 'C' || packet[1] == 'L') {
784                     reply = strdup("");
785                     break;
786                 }
787
788                 char *separator = strstr(packet, ":"), *params = "";
789                 if(separator == NULL) {
790                     separator = packet + strlen(packet);
791                 } else {
792                     params = separator + 1;
793                 }
794
795                 unsigned queryNameLength = (separator - &packet[1]);
796                 char* queryName = calloc(queryNameLength + 1, 1);
797                 strncpy(queryName, &packet[1], queryNameLength);
798
799                 DLOG("query: %s;%s\n", queryName, params);
800
801                 if(!strcmp(queryName, "Supported")) {
802                     if(sl->chip_id==STM32_CHIPID_F4 || sl->chip_id==STM32_CHIPID_F4_HD) {
803                         reply = strdup("PacketSize=3fff;qXfer:memory-map:read+;qXfer:features:read+");
804                     }
805                     else {
806                         reply = strdup("PacketSize=3fff;qXfer:memory-map:read+");
807                     }
808                 } else if(!strcmp(queryName, "Xfer")) {
809                     char *type, *op, *__s_addr, *s_length;
810                     char *tok = params;
811                     char *annex __attribute__((unused));
812
813                     type     = strsep(&tok, ":");
814                     op       = strsep(&tok, ":");
815                     annex    = strsep(&tok, ":");
816                     __s_addr   = strsep(&tok, ",");
817                     s_length = tok;
818
819                     unsigned addr = strtoul(__s_addr, NULL, 16),
820                              length = strtoul(s_length, NULL, 16);
821
822                     DLOG("Xfer: type:%s;op:%s;annex:%s;addr:%d;length:%d\n",
823                                 type, op, annex, addr, length);
824
825                     const char* data = NULL;
826
827                     if(!strcmp(type, "memory-map") && !strcmp(op, "read"))
828                         data = current_memory_map;
829
830                     if(!strcmp(type, "features") && !strcmp(op, "read"))
831                         data = target_description_F4;
832
833                     if(data) {
834                         unsigned data_length = strlen(data);
835                         if(addr + length > data_length)
836                             length = data_length - addr;
837
838                         if(length == 0) {
839                             reply = strdup("l");
840                         } else {
841                             reply = calloc(length + 2, 1);
842                             reply[0] = 'm';
843                             strncpy(&reply[1], data, length);
844                         }
845                     }
846                 } else if(!strncmp(queryName, "Rcmd,",4)) {
847                     // Rcmd uses the wrong separator
848                     char *separator = strstr(packet, ","), *params = "";
849                     if(separator == NULL) {
850                         separator = packet + strlen(packet);
851                     } else {
852                         params = separator + 1;
853                     }
854
855
856                     if (!strncmp(params,"726573756d65",12)) {// resume
857                         DLOG("Rcmd: resume\n");
858                         stlink_run(sl);
859
860                         reply = strdup("OK");
861                     } else if (!strncmp(params,"68616c74",8)) { //halt
862                         reply = strdup("OK");
863
864                         stlink_force_debug(sl);
865
866                         DLOG("Rcmd: halt\n");
867                     } else if (!strncmp(params,"6a7461675f7265736574",20)) { //jtag_reset
868                         reply = strdup("OK");
869
870                         stlink_jtag_reset(sl, 0);
871                         stlink_jtag_reset(sl, 1);
872                         stlink_force_debug(sl);
873
874                         DLOG("Rcmd: jtag_reset\n");
875                     } else if (!strncmp(params,"7265736574",10)) { //reset
876                         reply = strdup("OK");
877
878                         stlink_force_debug(sl);
879                         stlink_reset(sl);
880                         init_code_breakpoints(sl);
881                         init_data_watchpoints(sl);
882
883                         DLOG("Rcmd: reset\n");
884                     } else {
885                         DLOG("Rcmd: %s\n", params);
886                     }
887
888                 }
889
890                 if(reply == NULL)
891                     reply = strdup("");
892
893                 free(queryName);
894
895                 break;
896             }
897
898             case 'v': {
899                 char *params = NULL;
900                 char *cmdName = strtok_r(packet, ":;", &params);
901
902                 cmdName++; // vCommand -> Command
903
904                 if(!strcmp(cmdName, "FlashErase")) {
905                     char *__s_addr, *s_length;
906                     char *tok = params;
907
908                     __s_addr   = strsep(&tok, ",");
909                     s_length = tok;
910
911                     unsigned addr = strtoul(__s_addr, NULL, 16),
912                              length = strtoul(s_length, NULL, 16);
913
914                     DLOG("FlashErase: addr:%08x,len:%04x\n",
915                                 addr, length);
916
917                     if(flash_add_block(addr, length, sl) < 0) {
918                         reply = strdup("E00");
919                     } else {
920                         reply = strdup("OK");
921                     }
922                 } else if(!strcmp(cmdName, "FlashWrite")) {
923                     char *__s_addr, *data;
924                     char *tok = params;
925
926                     __s_addr = strsep(&tok, ":");
927                     data   = tok;
928
929                     unsigned addr = strtoul(__s_addr, NULL, 16);
930                     unsigned data_length = status - (data - packet);
931
932                     // Length of decoded data cannot be more than
933                     // encoded, as escapes are removed.
934                     // Additional byte is reserved for alignment fix.
935                     uint8_t *decoded = calloc(data_length + 1, 1);
936                     unsigned dec_index = 0;
937                     for(unsigned int i = 0; i < data_length; i++) {
938                         if(data[i] == 0x7d) {
939                             i++;
940                             decoded[dec_index++] = data[i] ^ 0x20;
941                         } else {
942                             decoded[dec_index++] = data[i];
943                         }
944                     }
945
946                     // Fix alignment
947                     if(dec_index % 2 != 0)
948                         dec_index++;
949
950                     DLOG("binary packet %d -> %d\n", data_length, dec_index);
951
952                     if(flash_populate(addr, decoded, dec_index) < 0) {
953                         reply = strdup("E00");
954                     } else {
955                         reply = strdup("OK");
956                     }
957                 } else if(!strcmp(cmdName, "FlashDone")) {
958                     if(flash_go(sl) < 0) {
959                         reply = strdup("E00");
960                     } else {
961                         reply = strdup("OK");
962                     }
963                 } else if(!strcmp(cmdName, "Kill")) {
964                     attached = 0;
965
966                     reply = strdup("OK");
967                 }
968
969                 if(reply == NULL)
970                     reply = strdup("");
971
972                 break;
973             }
974
975             case 'c':
976                 stlink_run(sl);
977
978                 while(1) {
979                     int status = gdb_check_for_interrupt(client);
980                     if(status < 0) {
981                         ELOG("cannot check for int: %d\n", status);
982 #ifdef __MINGW32__
983                         win32_close_socket(sock);
984 #endif
985                         return 1;
986                     }
987
988                     if(status == 1) {
989                         stlink_force_debug(sl);
990                         break;
991                     }
992
993                     stlink_status(sl);
994                     if(sl->core_stat == STLINK_CORE_HALTED) {
995                         break;
996                     }
997
998                     usleep(100000);
999                 }
1000
1001                 reply = strdup("S05"); // TRAP
1002                 break;
1003
1004             case 's':
1005                 stlink_step(sl);
1006
1007                 reply = strdup("S05"); // TRAP
1008                 break;
1009
1010             case '?':
1011                 if(attached) {
1012                     reply = strdup("S05"); // TRAP
1013                 } else {
1014                     /* Stub shall reply OK if not attached. */
1015                     reply = strdup("OK");
1016                 }
1017                 break;
1018
1019             case 'g':
1020                 stlink_read_all_regs(sl, &regp);
1021
1022                 reply = calloc(8 * 16 + 1, 1);
1023                 for(int i = 0; i < 16; i++)
1024                     sprintf(&reply[i * 8], "%08x", htonl(regp.r[i]));
1025
1026                 break;
1027
1028             case 'p': {
1029                 unsigned id = strtoul(&packet[1], NULL, 16);
1030                 unsigned myreg = 0xDEADDEAD;
1031
1032                 if(id < 16) {
1033                     stlink_read_reg(sl, id, &regp);
1034                     myreg = htonl(regp.r[id]);
1035                 } else if(id == 0x19) {
1036                     stlink_read_reg(sl, 16, &regp);
1037                     myreg = htonl(regp.xpsr);
1038                 } else if(id == 0x1A) {
1039                     stlink_read_reg(sl, 17, &regp);
1040                     myreg = htonl(regp.main_sp);
1041                 } else if(id == 0x1B) {
1042                     stlink_read_reg(sl, 18, &regp);
1043                     myreg = htonl(regp.process_sp);
1044                 } else if(id == 0x1C) {
1045                     stlink_read_unsupported_reg(sl, id, &regp);
1046                     myreg = htonl(regp.control);
1047                 } else if(id == 0x1D) {
1048                     stlink_read_unsupported_reg(sl, id, &regp);
1049                     myreg = htonl(regp.faultmask);
1050                 } else if(id == 0x1E) {
1051                     stlink_read_unsupported_reg(sl, id, &regp);
1052                     myreg = htonl(regp.basepri);
1053                 } else if(id == 0x1F) {
1054                     stlink_read_unsupported_reg(sl, id, &regp);
1055                     myreg = htonl(regp.primask);
1056                 } else if(id >= 0x20 && id < 0x40) {
1057                     stlink_read_unsupported_reg(sl, id, &regp);
1058                     myreg = htonl(regp.s[id-0x20]);
1059                 } else if(id == 0x40) {
1060                     stlink_read_unsupported_reg(sl, id, &regp);
1061                     myreg = htonl(regp.fpscr);
1062                 } else {
1063                     reply = strdup("E00");
1064                 }
1065
1066                 reply = calloc(8 + 1, 1);
1067                 sprintf(reply, "%08x", myreg);
1068
1069                 break;
1070             }
1071
1072             case 'P': {
1073                 char* s_reg = &packet[1];
1074                 char* s_value = strstr(&packet[1], "=") + 1;
1075
1076                 unsigned reg   = strtoul(s_reg,   NULL, 16);
1077                 unsigned value = strtoul(s_value, NULL, 16);
1078
1079                 if(reg < 16) {
1080                     stlink_write_reg(sl, ntohl(value), reg);
1081                 } else if(reg == 0x19) {
1082                     stlink_write_reg(sl, ntohl(value), 16);
1083                 } else if(reg == 0x1A) {
1084                     stlink_write_reg(sl, ntohl(value), 17);
1085                 } else if(reg == 0x1B) {
1086                     stlink_write_reg(sl, ntohl(value), 18);
1087                 } else if(reg == 0x1C) {
1088                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1089                 } else if(reg == 0x1D) {
1090                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1091                 } else if(reg == 0x1E) {
1092                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1093                 } else if(reg == 0x1F) {
1094                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1095                 } else if(reg >= 0x20 && reg < 0x40) {
1096                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1097                 } else if(reg == 0x40) {
1098                     stlink_write_unsupported_reg(sl, ntohl(value), reg, &regp);
1099                 } else {
1100                     reply = strdup("E00");
1101                 }
1102
1103                 if(!reply) {
1104                     reply = strdup("OK");
1105                 }
1106
1107                 break;
1108             }
1109
1110             case 'G':
1111                 for(int i = 0; i < 16; i++) {
1112                     char str[9] = {0};
1113                     strncpy(str, &packet[1 + i * 8], 8);
1114                     uint32_t reg = strtoul(str, NULL, 16);
1115                     stlink_write_reg(sl, ntohl(reg), i);
1116                 }
1117
1118                 reply = strdup("OK");
1119                 break;
1120
1121             case 'm': {
1122                 char* s_start = &packet[1];
1123                 char* s_count = strstr(&packet[1], ",") + 1;
1124
1125                 stm32_addr_t start = strtoul(s_start, NULL, 16);
1126                 unsigned     count = strtoul(s_count, NULL, 16);
1127
1128                 unsigned adj_start = start % 4;
1129                 unsigned count_rnd = (count + adj_start + 4 - 1) / 4 * 4;
1130
1131                 stlink_read_mem32(sl, start - adj_start, count_rnd);
1132
1133                 reply = calloc(count * 2 + 1, 1);
1134                 for(unsigned int i = 0; i < count; i++) {
1135                     reply[i * 2 + 0] = hex[sl->q_buf[i + adj_start] >> 4];
1136                     reply[i * 2 + 1] = hex[sl->q_buf[i + adj_start] & 0xf];
1137                 }
1138
1139                 break;
1140             }
1141
1142             case 'M': {
1143                 char* s_start = &packet[1];
1144                 char* s_count = strstr(&packet[1], ",") + 1;
1145                 char* hexdata = strstr(packet, ":") + 1;
1146
1147                 stm32_addr_t start = strtoul(s_start, NULL, 16);
1148                 unsigned     count = strtoul(s_count, NULL, 16);
1149
1150                 if(start % 4) {
1151                     unsigned align_count = 4 - start % 4;
1152                     if (align_count > count) align_count = count;
1153                     for(unsigned int i = 0; i < align_count; i ++) {
1154                         char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1155                         uint8_t byte = strtoul(hex, NULL, 16);
1156                         sl->q_buf[i] = byte;
1157                     }
1158                     stlink_write_mem8(sl, start, align_count);
1159                     start += align_count;
1160                     count -= align_count;
1161                     hexdata += 2*align_count;
1162                 }
1163
1164                 if(count - count % 4) {
1165                     unsigned aligned_count = count - count % 4;
1166
1167                     for(unsigned int i = 0; i < aligned_count; i ++) {
1168                         char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1169                         uint8_t byte = strtoul(hex, NULL, 16);
1170                         sl->q_buf[i] = byte;
1171                     }
1172                     stlink_write_mem32(sl, start, aligned_count);
1173                     count -= aligned_count;
1174                     start += aligned_count;
1175                     hexdata += 2*aligned_count;
1176                 }
1177
1178                 if(count) {
1179                     for(unsigned int i = 0; i < count; i ++) {
1180                         char hex[3] = { hexdata[i*2], hexdata[i*2+1], 0 };
1181                         uint8_t byte = strtoul(hex, NULL, 16);
1182                         sl->q_buf[i] = byte;
1183                     }
1184                     stlink_write_mem8(sl, start, count);
1185                 }
1186                 reply = strdup("OK");
1187                 break;
1188             }
1189
1190             case 'Z': {
1191                 char *endptr;
1192                 stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
1193                 stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
1194
1195                 switch (packet[1]) {
1196                     case '1':
1197                         if(update_code_breakpoint(sl, addr, 1) < 0) {
1198                             reply = strdup("E00");
1199                         } else {
1200                             reply = strdup("OK");
1201                         }
1202                         break;
1203
1204                     case '2':   // insert write watchpoint
1205                     case '3':   // insert read  watchpoint
1206                     case '4': { // insert access watchpoint
1207                         enum watchfun wf;
1208                         if(packet[1] == '2') {
1209                             wf = WATCHWRITE;
1210                         } else if(packet[1] == '3') {
1211                             wf = WATCHREAD;
1212                         } else {
1213                             wf = WATCHACCESS;
1214                         }
1215
1216                         if(add_data_watchpoint(sl, wf, addr, len) < 0) {
1217                             reply = strdup("E00");
1218                         } else {
1219                             reply = strdup("OK");
1220                             break;
1221                         }
1222                     }
1223
1224                     default:
1225                         reply = strdup("");
1226                 }
1227                 break;
1228             }
1229             case 'z': {
1230                 char *endptr;
1231                 stm32_addr_t addr = strtoul(&packet[3], &endptr, 16);
1232                 //stm32_addr_t len  = strtoul(&endptr[1], NULL, 16);
1233
1234                 switch (packet[1]) {
1235                     case '1': // remove breakpoint
1236                         update_code_breakpoint(sl, addr, 0);
1237                         reply = strdup("OK");
1238                         break;
1239
1240                     case '2' : // remove write watchpoint
1241                     case '3' : // remove read watchpoint
1242                     case '4' : // remove access watchpoint
1243                         if(delete_data_watchpoint(sl, addr) < 0) {
1244                             reply = strdup("E00");
1245                         } else {
1246                             reply = strdup("OK");
1247                             break;
1248                         }
1249
1250                     default:
1251                         reply = strdup("");
1252                 }
1253                 break;
1254             }
1255
1256             case '!': {
1257                 /*
1258                  * Enter extended mode which allows restarting.
1259                  * We do support that always.
1260                  */
1261
1262                 /*
1263                  * Also, set to persistent mode
1264                  * to allow GDB disconnect.
1265                  */
1266                 st->persistent = 1;
1267
1268                 reply = strdup("OK");
1269
1270                 break;
1271             }
1272
1273             case 'R': {
1274                 /* Reset the core. */
1275
1276                 stlink_reset(sl);
1277                 init_code_breakpoints(sl);
1278                 init_data_watchpoints(sl);
1279
1280                 attached = 1;
1281
1282                 reply = strdup("OK");
1283
1284                 break;
1285             }
1286
1287             default:
1288                 reply = strdup("");
1289         }
1290
1291         if(reply) {
1292             DLOG("send: %s\n", reply);
1293
1294             int result = gdb_send_packet(client, reply);
1295             if(result != 0) {
1296                 ELOG("cannot send: %d\n", result);
1297                 free(reply);
1298                 free(packet);
1299 #ifdef __MINGW32__
1300                 win32_close_socket(sock);
1301 #endif
1302                 return 1;
1303             }
1304
1305             free(reply);
1306         }
1307
1308         free(packet);
1309     }
1310
1311 #ifdef __MINGW32__
1312     win32_close_socket(sock);
1313 #endif
1314
1315     return 0;
1316 }