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