6e5010ec7cdbe01fbb1b8730070b64360c5899bf
[fw/openocd] / src / target / image.c
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2
3 /***************************************************************************
4  *   Copyright (C) 2007 by Dominic Rath                                    *
5  *   Dominic.Rath@gmx.de                                                   *
6  *                                                                         *
7  *   Copyright (C) 2007,2008 Ã˜yvind Harboe                                 *
8  *   oyvind.harboe@zylin.com                                               *
9  *                                                                         *
10  *   Copyright (C) 2008 by Spencer Oliver                                  *
11  *   spen@spen-soft.co.uk                                                  *
12  *                                                                         *
13  *   Copyright (C) 2009 by Franck Hereson                                  *
14  *   franck.hereson@secad.fr                                               *
15  *                                                                         *
16  *   Copyright (C) 2018 by Advantest                                       *
17  *   florian.meister@advantest.com                                         *
18  ***************************************************************************/
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include "image.h"
25 #include "target.h"
26 #include <helper/log.h>
27
28 /* convert ELF header field to host endianness */
29 #define field16(elf, field) \
30         ((elf->endianness == ELFDATA2LSB) ? \
31         le_to_h_u16((uint8_t *)&field) : be_to_h_u16((uint8_t *)&field))
32
33 #define field32(elf, field) \
34         ((elf->endianness == ELFDATA2LSB) ? \
35         le_to_h_u32((uint8_t *)&field) : be_to_h_u32((uint8_t *)&field))
36
37 #define field64(elf, field) \
38         ((elf->endianness == ELFDATA2LSB) ? \
39         le_to_h_u64((uint8_t *)&field) : be_to_h_u64((uint8_t *)&field))
40
41 static int autodetect_image_type(struct image *image, const char *url)
42 {
43         int retval;
44         struct fileio *fileio;
45         size_t read_bytes;
46         uint8_t buffer[9];
47
48         /* read the first 9 bytes of image */
49         retval = fileio_open(&fileio, url, FILEIO_READ, FILEIO_BINARY);
50         if (retval != ERROR_OK)
51                 return retval;
52         retval = fileio_read(fileio, 9, buffer, &read_bytes);
53
54         if (retval == ERROR_OK) {
55                 if (read_bytes != 9)
56                         retval = ERROR_FILEIO_OPERATION_FAILED;
57         }
58         fileio_close(fileio);
59
60         if (retval != ERROR_OK)
61                 return retval;
62
63         /* check header against known signatures */
64         if (strncmp((char *)buffer, ELFMAG, SELFMAG) == 0) {
65                 LOG_DEBUG("ELF image detected.");
66                 image->type = IMAGE_ELF;
67         } else if ((buffer[0] == ':')   /* record start byte */
68                 && (isxdigit(buffer[1]))
69                 && (isxdigit(buffer[2]))
70                 && (isxdigit(buffer[3]))
71                 && (isxdigit(buffer[4]))
72                 && (isxdigit(buffer[5]))
73                 && (isxdigit(buffer[6]))
74                 && (buffer[7] == '0')   /* record type : 00 -> 05 */
75                 && (buffer[8] >= '0') && (buffer[8] < '6')) {
76                 LOG_DEBUG("IHEX image detected.");
77                 image->type = IMAGE_IHEX;
78         } else if ((buffer[0] == 'S')   /* record start byte */
79                 && (isxdigit(buffer[1]))
80                 && (isxdigit(buffer[2]))
81                 && (isxdigit(buffer[3]))
82                 && (buffer[1] >= '0') && (buffer[1] < '9')) {
83                 LOG_DEBUG("S19 image detected.");
84                 image->type = IMAGE_SRECORD;
85         } else
86                 image->type = IMAGE_BINARY;
87
88         return ERROR_OK;
89 }
90
91 static int identify_image_type(struct image *image, const char *type_string, const char *url)
92 {
93         if (type_string) {
94                 if (!strcmp(type_string, "bin"))
95                         image->type = IMAGE_BINARY;
96                 else if (!strcmp(type_string, "ihex"))
97                         image->type = IMAGE_IHEX;
98                 else if (!strcmp(type_string, "elf"))
99                         image->type = IMAGE_ELF;
100                 else if (!strcmp(type_string, "mem"))
101                         image->type = IMAGE_MEMORY;
102                 else if (!strcmp(type_string, "s19"))
103                         image->type = IMAGE_SRECORD;
104                 else if (!strcmp(type_string, "build"))
105                         image->type = IMAGE_BUILDER;
106                 else
107                         return ERROR_IMAGE_TYPE_UNKNOWN;
108         } else
109                 return autodetect_image_type(image, url);
110
111         return ERROR_OK;
112 }
113
114 static int image_ihex_buffer_complete_inner(struct image *image,
115         char *lpsz_line,
116         struct imagesection *section)
117 {
118         struct image_ihex *ihex = image->type_private;
119         struct fileio *fileio = ihex->fileio;
120         uint32_t full_address;
121         uint32_t cooked_bytes;
122         bool end_rec = false;
123
124         /* we can't determine the number of sections that we'll have to create ahead of time,
125          * so we locally hold them until parsing is finished */
126
127         size_t filesize;
128         int retval;
129         retval = fileio_size(fileio, &filesize);
130         if (retval != ERROR_OK)
131                 return retval;
132
133         ihex->buffer = malloc(filesize >> 1);
134         cooked_bytes = 0x0;
135         image->num_sections = 0;
136
137         while (!fileio_feof(fileio)) {
138                 full_address = 0x0;
139                 section[image->num_sections].private = &ihex->buffer[cooked_bytes];
140                 section[image->num_sections].base_address = 0x0;
141                 section[image->num_sections].size = 0x0;
142                 section[image->num_sections].flags = 0;
143
144                 while (fileio_fgets(fileio, 1023, lpsz_line) == ERROR_OK) {
145                         uint32_t count;
146                         uint32_t address;
147                         uint32_t record_type;
148                         uint32_t checksum;
149                         uint8_t cal_checksum = 0;
150                         size_t bytes_read = 0;
151
152                         /* skip comments and blank lines */
153                         if ((lpsz_line[0] == '#') || (strlen(lpsz_line + strspn(lpsz_line, "\n\t\r ")) == 0))
154                                 continue;
155
156                         if (sscanf(&lpsz_line[bytes_read], ":%2" SCNx32 "%4" SCNx32 "%2" SCNx32, &count,
157                                 &address, &record_type) != 3)
158                                 return ERROR_IMAGE_FORMAT_ERROR;
159                         bytes_read += 9;
160
161                         cal_checksum += (uint8_t)count;
162                         cal_checksum += (uint8_t)(address >> 8);
163                         cal_checksum += (uint8_t)address;
164                         cal_checksum += (uint8_t)record_type;
165
166                         if (record_type == 0) { /* Data Record */
167                                 if ((full_address & 0xffff) != address) {
168                                         /* we encountered a nonconsecutive location, create a new section,
169                                          * unless the current section has zero size, in which case this specifies
170                                          * the current section's base address
171                                          */
172                                         if (section[image->num_sections].size != 0) {
173                                                 image->num_sections++;
174                                                 if (image->num_sections >= IMAGE_MAX_SECTIONS) {
175                                                         /* too many sections */
176                                                         LOG_ERROR("Too many sections found in IHEX file");
177                                                         return ERROR_IMAGE_FORMAT_ERROR;
178                                                 }
179                                                 section[image->num_sections].size = 0x0;
180                                                 section[image->num_sections].flags = 0;
181                                                 section[image->num_sections].private =
182                                                         &ihex->buffer[cooked_bytes];
183                                         }
184                                         section[image->num_sections].base_address =
185                                                 (full_address & 0xffff0000) | address;
186                                         full_address = (full_address & 0xffff0000) | address;
187                                 }
188
189                                 while (count-- > 0) {
190                                         unsigned value;
191                                         sscanf(&lpsz_line[bytes_read], "%2x", &value);
192                                         ihex->buffer[cooked_bytes] = (uint8_t)value;
193                                         cal_checksum += (uint8_t)ihex->buffer[cooked_bytes];
194                                         bytes_read += 2;
195                                         cooked_bytes += 1;
196                                         section[image->num_sections].size += 1;
197                                         full_address++;
198                                 }
199                         } else if (record_type == 1) {  /* End of File Record */
200                                 /* finish the current section */
201                                 image->num_sections++;
202
203                                 /* copy section information */
204                                 image->sections = malloc(sizeof(struct imagesection) * image->num_sections);
205                                 for (unsigned int i = 0; i < image->num_sections; i++) {
206                                         image->sections[i].private = section[i].private;
207                                         image->sections[i].base_address = section[i].base_address;
208                                         image->sections[i].size = section[i].size;
209                                         image->sections[i].flags = section[i].flags;
210                                 }
211
212                                 end_rec = true;
213                                 break;
214                         } else if (record_type == 2) {  /* Linear Address Record */
215                                 uint16_t upper_address;
216
217                                 sscanf(&lpsz_line[bytes_read], "%4hx", &upper_address);
218                                 cal_checksum += (uint8_t)(upper_address >> 8);
219                                 cal_checksum += (uint8_t)upper_address;
220                                 bytes_read += 4;
221
222                                 if ((full_address >> 4) != upper_address) {
223                                         /* we encountered a nonconsecutive location, create a new section,
224                                          * unless the current section has zero size, in which case this specifies
225                                          * the current section's base address
226                                          */
227                                         if (section[image->num_sections].size != 0) {
228                                                 image->num_sections++;
229                                                 if (image->num_sections >= IMAGE_MAX_SECTIONS) {
230                                                         /* too many sections */
231                                                         LOG_ERROR("Too many sections found in IHEX file");
232                                                         return ERROR_IMAGE_FORMAT_ERROR;
233                                                 }
234                                                 section[image->num_sections].size = 0x0;
235                                                 section[image->num_sections].flags = 0;
236                                                 section[image->num_sections].private =
237                                                         &ihex->buffer[cooked_bytes];
238                                         }
239                                         section[image->num_sections].base_address =
240                                                 (full_address & 0xffff) | (upper_address << 4);
241                                         full_address = (full_address & 0xffff) | (upper_address << 4);
242                                 }
243                         } else if (record_type == 3) {  /* Start Segment Address Record */
244                                 uint32_t dummy;
245
246                                 /* "Start Segment Address Record" will not be supported
247                                  * but we must consume it, and do not create an error.  */
248                                 while (count-- > 0) {
249                                         sscanf(&lpsz_line[bytes_read], "%2" SCNx32, &dummy);
250                                         cal_checksum += (uint8_t)dummy;
251                                         bytes_read += 2;
252                                 }
253                         } else if (record_type == 4) {  /* Extended Linear Address Record */
254                                 uint16_t upper_address;
255
256                                 sscanf(&lpsz_line[bytes_read], "%4hx", &upper_address);
257                                 cal_checksum += (uint8_t)(upper_address >> 8);
258                                 cal_checksum += (uint8_t)upper_address;
259                                 bytes_read += 4;
260
261                                 if ((full_address >> 16) != upper_address) {
262                                         /* we encountered a nonconsecutive location, create a new section,
263                                          * unless the current section has zero size, in which case this specifies
264                                          * the current section's base address
265                                          */
266                                         if (section[image->num_sections].size != 0) {
267                                                 image->num_sections++;
268                                                 if (image->num_sections >= IMAGE_MAX_SECTIONS) {
269                                                         /* too many sections */
270                                                         LOG_ERROR("Too many sections found in IHEX file");
271                                                         return ERROR_IMAGE_FORMAT_ERROR;
272                                                 }
273                                                 section[image->num_sections].size = 0x0;
274                                                 section[image->num_sections].flags = 0;
275                                                 section[image->num_sections].private =
276                                                         &ihex->buffer[cooked_bytes];
277                                         }
278                                         section[image->num_sections].base_address =
279                                                 (full_address & 0xffff) | (upper_address << 16);
280                                         full_address = (full_address & 0xffff) | (upper_address << 16);
281                                 }
282                         } else if (record_type == 5) {  /* Start Linear Address Record */
283                                 uint32_t start_address;
284
285                                 sscanf(&lpsz_line[bytes_read], "%8" SCNx32, &start_address);
286                                 cal_checksum += (uint8_t)(start_address >> 24);
287                                 cal_checksum += (uint8_t)(start_address >> 16);
288                                 cal_checksum += (uint8_t)(start_address >> 8);
289                                 cal_checksum += (uint8_t)start_address;
290                                 bytes_read += 8;
291
292                                 image->start_address_set = true;
293                                 image->start_address = be_to_h_u32((uint8_t *)&start_address);
294                         } else {
295                                 LOG_ERROR("unhandled IHEX record type: %i", (int)record_type);
296                                 return ERROR_IMAGE_FORMAT_ERROR;
297                         }
298
299                         sscanf(&lpsz_line[bytes_read], "%2" SCNx32, &checksum);
300
301                         if ((uint8_t)checksum != (uint8_t)(~cal_checksum + 1)) {
302                                 /* checksum failed */
303                                 LOG_ERROR("incorrect record checksum found in IHEX file");
304                                 return ERROR_IMAGE_CHECKSUM;
305                         }
306
307                         if (end_rec) {
308                                 end_rec = false;
309                                 LOG_WARNING("continuing after end-of-file record: %.40s", lpsz_line);
310                         }
311                 }
312         }
313
314         if (end_rec)
315                 return ERROR_OK;
316         else {
317                 LOG_ERROR("premature end of IHEX file, no matching end-of-file record found");
318                 return ERROR_IMAGE_FORMAT_ERROR;
319         }
320 }
321
322 /**
323  * Allocate memory dynamically instead of on the stack. This
324  * is important w/embedded hosts.
325  */
326 static int image_ihex_buffer_complete(struct image *image)
327 {
328         char *lpsz_line = malloc(1023);
329         if (!lpsz_line) {
330                 LOG_ERROR("Out of memory");
331                 return ERROR_FAIL;
332         }
333         struct imagesection *section = malloc(sizeof(struct imagesection) * IMAGE_MAX_SECTIONS);
334         if (!section) {
335                 free(lpsz_line);
336                 LOG_ERROR("Out of memory");
337                 return ERROR_FAIL;
338         }
339         int retval;
340
341         retval = image_ihex_buffer_complete_inner(image, lpsz_line, section);
342
343         free(section);
344         free(lpsz_line);
345
346         return retval;
347 }
348
349 static int image_elf32_read_headers(struct image *image)
350 {
351         struct image_elf *elf = image->type_private;
352         size_t read_bytes;
353         uint32_t i, j;
354         int retval;
355         uint32_t nload;
356         bool load_to_vaddr = false;
357
358         retval = fileio_seek(elf->fileio, 0);
359         if (retval != ERROR_OK) {
360                 LOG_ERROR("cannot seek to ELF file header, read failed");
361                 return retval;
362         }
363
364         elf->header32 = malloc(sizeof(Elf32_Ehdr));
365
366         if (!elf->header32) {
367                 LOG_ERROR("insufficient memory to perform operation");
368                 return ERROR_FILEIO_OPERATION_FAILED;
369         }
370
371         retval = fileio_read(elf->fileio, sizeof(Elf32_Ehdr), (uint8_t *)elf->header32, &read_bytes);
372         if (retval != ERROR_OK) {
373                 LOG_ERROR("cannot read ELF file header, read failed");
374                 return ERROR_FILEIO_OPERATION_FAILED;
375         }
376         if (read_bytes != sizeof(Elf32_Ehdr)) {
377                 LOG_ERROR("cannot read ELF file header, only partially read");
378                 return ERROR_FILEIO_OPERATION_FAILED;
379         }
380
381         elf->segment_count = field16(elf, elf->header32->e_phnum);
382         if (elf->segment_count == 0) {
383                 LOG_ERROR("invalid ELF file, no program headers");
384                 return ERROR_IMAGE_FORMAT_ERROR;
385         }
386
387         retval = fileio_seek(elf->fileio, field32(elf, elf->header32->e_phoff));
388         if (retval != ERROR_OK) {
389                 LOG_ERROR("cannot seek to ELF program header table, read failed");
390                 return retval;
391         }
392
393         elf->segments32 = malloc(elf->segment_count*sizeof(Elf32_Phdr));
394         if (!elf->segments32) {
395                 LOG_ERROR("insufficient memory to perform operation");
396                 return ERROR_FILEIO_OPERATION_FAILED;
397         }
398
399         retval = fileio_read(elf->fileio, elf->segment_count*sizeof(Elf32_Phdr),
400                         (uint8_t *)elf->segments32, &read_bytes);
401         if (retval != ERROR_OK) {
402                 LOG_ERROR("cannot read ELF segment headers, read failed");
403                 return retval;
404         }
405         if (read_bytes != elf->segment_count*sizeof(Elf32_Phdr)) {
406                 LOG_ERROR("cannot read ELF segment headers, only partially read");
407                 return ERROR_FILEIO_OPERATION_FAILED;
408         }
409
410         /* count useful segments (loadable), ignore BSS section */
411         image->num_sections = 0;
412         for (i = 0; i < elf->segment_count; i++)
413                 if ((field32(elf,
414                         elf->segments32[i].p_type) == PT_LOAD) &&
415                         (field32(elf, elf->segments32[i].p_filesz) != 0))
416                         image->num_sections++;
417
418         if (image->num_sections == 0) {
419                 LOG_ERROR("invalid ELF file, no loadable segments");
420                 return ERROR_IMAGE_FORMAT_ERROR;
421         }
422
423         /**
424          * some ELF linkers produce binaries with *all* the program header
425          * p_paddr fields zero (there can be however one loadable segment
426          * that has valid physical address 0x0).
427          * If we have such a binary with more than
428          * one PT_LOAD header, then use p_vaddr instead of p_paddr
429          * (ARM ELF standard demands p_paddr = 0 anyway, and BFD
430          * library uses this approach to workaround zero-initialized p_paddrs
431          * when obtaining lma - look at elf.c of BDF)
432          */
433         for (nload = 0, i = 0; i < elf->segment_count; i++)
434                 if (elf->segments32[i].p_paddr != 0)
435                         break;
436                 else if ((field32(elf,
437                         elf->segments32[i].p_type) == PT_LOAD) &&
438                         (field32(elf, elf->segments32[i].p_memsz) != 0))
439                         ++nload;
440
441         if (i >= elf->segment_count && nload > 1)
442                 load_to_vaddr = true;
443
444         /* alloc and fill sections array with loadable segments */
445         image->sections = malloc(image->num_sections * sizeof(struct imagesection));
446         if (!image->sections) {
447                 LOG_ERROR("insufficient memory to perform operation");
448                 return ERROR_FILEIO_OPERATION_FAILED;
449         }
450
451         for (i = 0, j = 0; i < elf->segment_count; i++) {
452                 if ((field32(elf,
453                         elf->segments32[i].p_type) == PT_LOAD) &&
454                         (field32(elf, elf->segments32[i].p_filesz) != 0)) {
455                         image->sections[j].size = field32(elf, elf->segments32[i].p_filesz);
456                         if (load_to_vaddr)
457                                 image->sections[j].base_address = field32(elf,
458                                                 elf->segments32[i].p_vaddr);
459                         else
460                                 image->sections[j].base_address = field32(elf,
461                                                 elf->segments32[i].p_paddr);
462                         image->sections[j].private = &elf->segments32[i];
463                         image->sections[j].flags = field32(elf, elf->segments32[i].p_flags);
464                         j++;
465                 }
466         }
467
468         image->start_address_set = true;
469         image->start_address = field32(elf, elf->header32->e_entry);
470
471         return ERROR_OK;
472 }
473
474 static int image_elf64_read_headers(struct image *image)
475 {
476         struct image_elf *elf = image->type_private;
477         size_t read_bytes;
478         uint32_t i, j;
479         int retval;
480         uint32_t nload;
481         bool load_to_vaddr = false;
482
483         retval = fileio_seek(elf->fileio, 0);
484         if (retval != ERROR_OK) {
485                 LOG_ERROR("cannot seek to ELF file header, read failed");
486                 return retval;
487         }
488
489         elf->header64 = malloc(sizeof(Elf64_Ehdr));
490
491         if (!elf->header64) {
492                 LOG_ERROR("insufficient memory to perform operation");
493                 return ERROR_FILEIO_OPERATION_FAILED;
494         }
495
496         retval = fileio_read(elf->fileio, sizeof(Elf64_Ehdr), (uint8_t *)elf->header64, &read_bytes);
497         if (retval != ERROR_OK) {
498                 LOG_ERROR("cannot read ELF file header, read failed");
499                 return ERROR_FILEIO_OPERATION_FAILED;
500         }
501         if (read_bytes != sizeof(Elf64_Ehdr)) {
502                 LOG_ERROR("cannot read ELF file header, only partially read");
503                 return ERROR_FILEIO_OPERATION_FAILED;
504         }
505
506         elf->segment_count = field16(elf, elf->header64->e_phnum);
507         if (elf->segment_count == 0) {
508                 LOG_ERROR("invalid ELF file, no program headers");
509                 return ERROR_IMAGE_FORMAT_ERROR;
510         }
511
512         retval = fileio_seek(elf->fileio, field64(elf, elf->header64->e_phoff));
513         if (retval != ERROR_OK) {
514                 LOG_ERROR("cannot seek to ELF program header table, read failed");
515                 return retval;
516         }
517
518         elf->segments64 = malloc(elf->segment_count*sizeof(Elf64_Phdr));
519         if (!elf->segments64) {
520                 LOG_ERROR("insufficient memory to perform operation");
521                 return ERROR_FILEIO_OPERATION_FAILED;
522         }
523
524         retval = fileio_read(elf->fileio, elf->segment_count*sizeof(Elf64_Phdr),
525                         (uint8_t *)elf->segments64, &read_bytes);
526         if (retval != ERROR_OK) {
527                 LOG_ERROR("cannot read ELF segment headers, read failed");
528                 return retval;
529         }
530         if (read_bytes != elf->segment_count*sizeof(Elf64_Phdr)) {
531                 LOG_ERROR("cannot read ELF segment headers, only partially read");
532                 return ERROR_FILEIO_OPERATION_FAILED;
533         }
534
535         /* count useful segments (loadable), ignore BSS section */
536         image->num_sections = 0;
537         for (i = 0; i < elf->segment_count; i++)
538                 if ((field32(elf,
539                         elf->segments64[i].p_type) == PT_LOAD) &&
540                         (field64(elf, elf->segments64[i].p_filesz) != 0))
541                         image->num_sections++;
542
543         if (image->num_sections == 0) {
544                 LOG_ERROR("invalid ELF file, no loadable segments");
545                 return ERROR_IMAGE_FORMAT_ERROR;
546         }
547
548         /**
549          * some ELF linkers produce binaries with *all* the program header
550          * p_paddr fields zero (there can be however one loadable segment
551          * that has valid physical address 0x0).
552          * If we have such a binary with more than
553          * one PT_LOAD header, then use p_vaddr instead of p_paddr
554          * (ARM ELF standard demands p_paddr = 0 anyway, and BFD
555          * library uses this approach to workaround zero-initialized p_paddrs
556          * when obtaining lma - look at elf.c of BDF)
557          */
558         for (nload = 0, i = 0; i < elf->segment_count; i++)
559                 if (elf->segments64[i].p_paddr != 0)
560                         break;
561                 else if ((field32(elf,
562                         elf->segments64[i].p_type) == PT_LOAD) &&
563                         (field64(elf, elf->segments64[i].p_memsz) != 0))
564                         ++nload;
565
566         if (i >= elf->segment_count && nload > 1)
567                 load_to_vaddr = true;
568
569         /* alloc and fill sections array with loadable segments */
570         image->sections = malloc(image->num_sections * sizeof(struct imagesection));
571         if (!image->sections) {
572                 LOG_ERROR("insufficient memory to perform operation");
573                 return ERROR_FILEIO_OPERATION_FAILED;
574         }
575
576         for (i = 0, j = 0; i < elf->segment_count; i++) {
577                 if ((field32(elf,
578                         elf->segments64[i].p_type) == PT_LOAD) &&
579                         (field64(elf, elf->segments64[i].p_filesz) != 0)) {
580                         image->sections[j].size = field64(elf, elf->segments64[i].p_filesz);
581                         if (load_to_vaddr)
582                                 image->sections[j].base_address = field64(elf,
583                                                 elf->segments64[i].p_vaddr);
584                         else
585                                 image->sections[j].base_address = field64(elf,
586                                                 elf->segments64[i].p_paddr);
587                         image->sections[j].private = &elf->segments64[i];
588                         image->sections[j].flags = field64(elf, elf->segments64[i].p_flags);
589                         j++;
590                 }
591         }
592
593         image->start_address_set = true;
594         image->start_address = field64(elf, elf->header64->e_entry);
595
596         return ERROR_OK;
597 }
598
599 static int image_elf_read_headers(struct image *image)
600 {
601         struct image_elf *elf = image->type_private;
602         size_t read_bytes;
603         unsigned char e_ident[EI_NIDENT];
604         int retval;
605
606         retval = fileio_read(elf->fileio, EI_NIDENT, e_ident, &read_bytes);
607         if (retval != ERROR_OK) {
608                 LOG_ERROR("cannot read ELF file header, read failed");
609                 return ERROR_FILEIO_OPERATION_FAILED;
610         }
611         if (read_bytes != EI_NIDENT) {
612                 LOG_ERROR("cannot read ELF file header, only partially read");
613                 return ERROR_FILEIO_OPERATION_FAILED;
614         }
615
616         if (strncmp((char *)e_ident, ELFMAG, SELFMAG) != 0) {
617                 LOG_ERROR("invalid ELF file, bad magic number");
618                 return ERROR_IMAGE_FORMAT_ERROR;
619         }
620
621         elf->endianness = e_ident[EI_DATA];
622         if ((elf->endianness != ELFDATA2LSB)
623                 && (elf->endianness != ELFDATA2MSB)) {
624                 LOG_ERROR("invalid ELF file, unknown endianness setting");
625                 return ERROR_IMAGE_FORMAT_ERROR;
626         }
627
628         switch (e_ident[EI_CLASS]) {
629         case ELFCLASS32:
630                 LOG_DEBUG("ELF32 image detected.");
631                 elf->is_64_bit = false;
632                 return image_elf32_read_headers(image);
633
634         case ELFCLASS64:
635                 LOG_DEBUG("ELF64 image detected.");
636                 elf->is_64_bit = true;
637                 return image_elf64_read_headers(image);
638
639         default:
640                 LOG_ERROR("invalid ELF file, only 32/64 bit ELF files are supported");
641                 return ERROR_IMAGE_FORMAT_ERROR;
642         }
643 }
644
645 static int image_elf32_read_section(struct image *image,
646         int section,
647         target_addr_t offset,
648         uint32_t size,
649         uint8_t *buffer,
650         size_t *size_read)
651 {
652         struct image_elf *elf = image->type_private;
653         Elf32_Phdr *segment = (Elf32_Phdr *)image->sections[section].private;
654         size_t read_size, really_read;
655         int retval;
656
657         *size_read = 0;
658
659         LOG_DEBUG("load segment %d at 0x%" TARGET_PRIxADDR " (sz = 0x%" PRIx32 ")", section, offset, size);
660
661         /* read initialized data in current segment if any */
662         if (offset < field32(elf, segment->p_filesz)) {
663                 /* maximal size present in file for the current segment */
664                 read_size = MIN(size, field32(elf, segment->p_filesz) - offset);
665                 LOG_DEBUG("read elf: size = 0x%zx at 0x%" TARGET_PRIxADDR "", read_size,
666                         field32(elf, segment->p_offset) + offset);
667                 /* read initialized area of the segment */
668                 retval = fileio_seek(elf->fileio, field32(elf, segment->p_offset) + offset);
669                 if (retval != ERROR_OK) {
670                         LOG_ERROR("cannot find ELF segment content, seek failed");
671                         return retval;
672                 }
673                 retval = fileio_read(elf->fileio, read_size, buffer, &really_read);
674                 if (retval != ERROR_OK) {
675                         LOG_ERROR("cannot read ELF segment content, read failed");
676                         return retval;
677                 }
678                 size -= read_size;
679                 *size_read += read_size;
680                 /* need more data ? */
681                 if (!size)
682                         return ERROR_OK;
683         }
684
685         return ERROR_OK;
686 }
687
688 static int image_elf64_read_section(struct image *image,
689         int section,
690         target_addr_t offset,
691         uint32_t size,
692         uint8_t *buffer,
693         size_t *size_read)
694 {
695         struct image_elf *elf = image->type_private;
696         Elf64_Phdr *segment = (Elf64_Phdr *)image->sections[section].private;
697         size_t read_size, really_read;
698         int retval;
699
700         *size_read = 0;
701
702         LOG_DEBUG("load segment %d at 0x%" TARGET_PRIxADDR " (sz = 0x%" PRIx32 ")", section, offset, size);
703
704         /* read initialized data in current segment if any */
705         if (offset < field64(elf, segment->p_filesz)) {
706                 /* maximal size present in file for the current segment */
707                 read_size = MIN(size, field64(elf, segment->p_filesz) - offset);
708                 LOG_DEBUG("read elf: size = 0x%zx at 0x%" TARGET_PRIxADDR "", read_size,
709                         field64(elf, segment->p_offset) + offset);
710                 /* read initialized area of the segment */
711                 retval = fileio_seek(elf->fileio, field64(elf, segment->p_offset) + offset);
712                 if (retval != ERROR_OK) {
713                         LOG_ERROR("cannot find ELF segment content, seek failed");
714                         return retval;
715                 }
716                 retval = fileio_read(elf->fileio, read_size, buffer, &really_read);
717                 if (retval != ERROR_OK) {
718                         LOG_ERROR("cannot read ELF segment content, read failed");
719                         return retval;
720                 }
721                 size -= read_size;
722                 *size_read += read_size;
723                 /* need more data ? */
724                 if (!size)
725                         return ERROR_OK;
726         }
727
728         return ERROR_OK;
729 }
730
731 static int image_elf_read_section(struct image *image,
732         int section,
733         target_addr_t offset,
734         uint32_t size,
735         uint8_t *buffer,
736         size_t *size_read)
737 {
738         struct image_elf *elf = image->type_private;
739
740         if (elf->is_64_bit)
741                 return image_elf64_read_section(image, section, offset, size, buffer, size_read);
742         else
743                 return image_elf32_read_section(image, section, offset, size, buffer, size_read);
744 }
745
746 static int image_mot_buffer_complete_inner(struct image *image,
747         char *lpsz_line,
748         struct imagesection *section)
749 {
750         struct image_mot *mot = image->type_private;
751         struct fileio *fileio = mot->fileio;
752         uint32_t full_address;
753         uint32_t cooked_bytes;
754         bool end_rec = false;
755
756         /* we can't determine the number of sections that we'll have to create ahead of time,
757          * so we locally hold them until parsing is finished */
758
759         int retval;
760         size_t filesize;
761         retval = fileio_size(fileio, &filesize);
762         if (retval != ERROR_OK)
763                 return retval;
764
765         mot->buffer = malloc(filesize >> 1);
766         cooked_bytes = 0x0;
767         image->num_sections = 0;
768
769         while (!fileio_feof(fileio)) {
770                 full_address = 0x0;
771                 section[image->num_sections].private = &mot->buffer[cooked_bytes];
772                 section[image->num_sections].base_address = 0x0;
773                 section[image->num_sections].size = 0x0;
774                 section[image->num_sections].flags = 0;
775
776                 while (fileio_fgets(fileio, 1023, lpsz_line) == ERROR_OK) {
777                         uint32_t count;
778                         uint32_t address;
779                         uint32_t record_type;
780                         uint32_t checksum;
781                         uint8_t cal_checksum = 0;
782                         uint32_t bytes_read = 0;
783
784                         /* skip comments and blank lines */
785                         if ((lpsz_line[0] == '#') || (strlen(lpsz_line + strspn(lpsz_line, "\n\t\r ")) == 0))
786                                 continue;
787
788                         /* get record type and record length */
789                         if (sscanf(&lpsz_line[bytes_read], "S%1" SCNx32 "%2" SCNx32, &record_type,
790                                 &count) != 2)
791                                 return ERROR_IMAGE_FORMAT_ERROR;
792
793                         bytes_read += 4;
794                         cal_checksum += (uint8_t)count;
795
796                         /* skip checksum byte */
797                         count -= 1;
798
799                         if (record_type == 0) {
800                                 /* S0 - starting record (optional) */
801                                 int value;
802
803                                 while (count-- > 0) {
804                                         sscanf(&lpsz_line[bytes_read], "%2x", &value);
805                                         cal_checksum += (uint8_t)value;
806                                         bytes_read += 2;
807                                 }
808                         } else if (record_type >= 1 && record_type <= 3) {
809                                 switch (record_type) {
810                                         case 1:
811                                                 /* S1 - 16 bit address data record */
812                                                 sscanf(&lpsz_line[bytes_read], "%4" SCNx32, &address);
813                                                 cal_checksum += (uint8_t)(address >> 8);
814                                                 cal_checksum += (uint8_t)address;
815                                                 bytes_read += 4;
816                                                 count -= 2;
817                                                 break;
818
819                                         case 2:
820                                                 /* S2 - 24 bit address data record */
821                                                 sscanf(&lpsz_line[bytes_read], "%6" SCNx32, &address);
822                                                 cal_checksum += (uint8_t)(address >> 16);
823                                                 cal_checksum += (uint8_t)(address >> 8);
824                                                 cal_checksum += (uint8_t)address;
825                                                 bytes_read += 6;
826                                                 count -= 3;
827                                                 break;
828
829                                         case 3:
830                                                 /* S3 - 32 bit address data record */
831                                                 sscanf(&lpsz_line[bytes_read], "%8" SCNx32, &address);
832                                                 cal_checksum += (uint8_t)(address >> 24);
833                                                 cal_checksum += (uint8_t)(address >> 16);
834                                                 cal_checksum += (uint8_t)(address >> 8);
835                                                 cal_checksum += (uint8_t)address;
836                                                 bytes_read += 8;
837                                                 count -= 4;
838                                                 break;
839
840                                 }
841
842                                 if (full_address != address) {
843                                         /* we encountered a nonconsecutive location, create a new section,
844                                          * unless the current section has zero size, in which case this specifies
845                                          * the current section's base address
846                                          */
847                                         if (section[image->num_sections].size != 0) {
848                                                 image->num_sections++;
849                                                 section[image->num_sections].size = 0x0;
850                                                 section[image->num_sections].flags = 0;
851                                                 section[image->num_sections].private =
852                                                         &mot->buffer[cooked_bytes];
853                                         }
854                                         section[image->num_sections].base_address = address;
855                                         full_address = address;
856                                 }
857
858                                 while (count-- > 0) {
859                                         unsigned value;
860                                         sscanf(&lpsz_line[bytes_read], "%2x", &value);
861                                         mot->buffer[cooked_bytes] = (uint8_t)value;
862                                         cal_checksum += (uint8_t)mot->buffer[cooked_bytes];
863                                         bytes_read += 2;
864                                         cooked_bytes += 1;
865                                         section[image->num_sections].size += 1;
866                                         full_address++;
867                                 }
868                         } else if (record_type == 5 || record_type == 6) {
869                                 /* S5 and S6 are the data count records, we ignore them */
870                                 uint32_t dummy;
871
872                                 while (count-- > 0) {
873                                         sscanf(&lpsz_line[bytes_read], "%2" SCNx32, &dummy);
874                                         cal_checksum += (uint8_t)dummy;
875                                         bytes_read += 2;
876                                 }
877                         } else if (record_type >= 7 && record_type <= 9) {
878                                 /* S7, S8, S9 - ending records for 32, 24 and 16bit */
879                                 image->num_sections++;
880
881                                 /* copy section information */
882                                 image->sections = malloc(sizeof(struct imagesection) * image->num_sections);
883                                 for (unsigned int i = 0; i < image->num_sections; i++) {
884                                         image->sections[i].private = section[i].private;
885                                         image->sections[i].base_address = section[i].base_address;
886                                         image->sections[i].size = section[i].size;
887                                         image->sections[i].flags = section[i].flags;
888                                 }
889
890                                 end_rec = true;
891                                 break;
892                         } else {
893                                 LOG_ERROR("unhandled S19 record type: %i", (int)(record_type));
894                                 return ERROR_IMAGE_FORMAT_ERROR;
895                         }
896
897                         /* account for checksum, will always be 0xFF */
898                         sscanf(&lpsz_line[bytes_read], "%2" SCNx32, &checksum);
899                         cal_checksum += (uint8_t)checksum;
900
901                         if (cal_checksum != 0xFF) {
902                                 /* checksum failed */
903                                 LOG_ERROR("incorrect record checksum found in S19 file");
904                                 return ERROR_IMAGE_CHECKSUM;
905                         }
906
907                         if (end_rec) {
908                                 end_rec = false;
909                                 LOG_WARNING("continuing after end-of-file record: %.40s", lpsz_line);
910                         }
911                 }
912         }
913
914         if (end_rec)
915                 return ERROR_OK;
916         else {
917                 LOG_ERROR("premature end of S19 file, no matching end-of-file record found");
918                 return ERROR_IMAGE_FORMAT_ERROR;
919         }
920 }
921
922 /**
923  * Allocate memory dynamically instead of on the stack. This
924  * is important w/embedded hosts.
925  */
926 static int image_mot_buffer_complete(struct image *image)
927 {
928         char *lpsz_line = malloc(1023);
929         if (!lpsz_line) {
930                 LOG_ERROR("Out of memory");
931                 return ERROR_FAIL;
932         }
933         struct imagesection *section = malloc(sizeof(struct imagesection) * IMAGE_MAX_SECTIONS);
934         if (!section) {
935                 free(lpsz_line);
936                 LOG_ERROR("Out of memory");
937                 return ERROR_FAIL;
938         }
939         int retval;
940
941         retval = image_mot_buffer_complete_inner(image, lpsz_line, section);
942
943         free(section);
944         free(lpsz_line);
945
946         return retval;
947 }
948
949 int image_open(struct image *image, const char *url, const char *type_string)
950 {
951         int retval = ERROR_OK;
952
953         retval = identify_image_type(image, type_string, url);
954         if (retval != ERROR_OK)
955                 return retval;
956
957         if (image->type == IMAGE_BINARY) {
958                 struct image_binary *image_binary;
959
960                 image_binary = image->type_private = malloc(sizeof(struct image_binary));
961
962                 retval = fileio_open(&image_binary->fileio, url, FILEIO_READ, FILEIO_BINARY);
963                 if (retval != ERROR_OK)
964                         return retval;
965                 size_t filesize;
966                 retval = fileio_size(image_binary->fileio, &filesize);
967                 if (retval != ERROR_OK) {
968                         fileio_close(image_binary->fileio);
969                         return retval;
970                 }
971
972                 image->num_sections = 1;
973                 image->sections = malloc(sizeof(struct imagesection));
974                 image->sections[0].base_address = 0x0;
975                 image->sections[0].size = filesize;
976                 image->sections[0].flags = 0;
977         } else if (image->type == IMAGE_IHEX) {
978                 struct image_ihex *image_ihex;
979
980                 image_ihex = image->type_private = malloc(sizeof(struct image_ihex));
981
982                 retval = fileio_open(&image_ihex->fileio, url, FILEIO_READ, FILEIO_TEXT);
983                 if (retval != ERROR_OK)
984                         return retval;
985
986                 retval = image_ihex_buffer_complete(image);
987                 if (retval != ERROR_OK) {
988                         LOG_ERROR(
989                                 "failed buffering IHEX image, check server output for additional information");
990                         fileio_close(image_ihex->fileio);
991                         return retval;
992                 }
993         } else if (image->type == IMAGE_ELF) {
994                 struct image_elf *image_elf;
995
996                 image_elf = image->type_private = malloc(sizeof(struct image_elf));
997
998                 retval = fileio_open(&image_elf->fileio, url, FILEIO_READ, FILEIO_BINARY);
999                 if (retval != ERROR_OK)
1000                         return retval;
1001
1002                 retval = image_elf_read_headers(image);
1003                 if (retval != ERROR_OK) {
1004                         fileio_close(image_elf->fileio);
1005                         return retval;
1006                 }
1007         } else if (image->type == IMAGE_MEMORY) {
1008                 struct target *target = get_target(url);
1009
1010                 if (!target) {
1011                         LOG_ERROR("target '%s' not defined", url);
1012                         return ERROR_FAIL;
1013                 }
1014
1015                 struct image_memory *image_memory;
1016
1017                 image->num_sections = 1;
1018                 image->sections = malloc(sizeof(struct imagesection));
1019                 image->sections[0].base_address = 0x0;
1020                 image->sections[0].size = 0xffffffff;
1021                 image->sections[0].flags = 0;
1022
1023                 image_memory = image->type_private = malloc(sizeof(struct image_memory));
1024
1025                 image_memory->target = target;
1026                 image_memory->cache = NULL;
1027                 image_memory->cache_address = 0x0;
1028         } else if (image->type == IMAGE_SRECORD) {
1029                 struct image_mot *image_mot;
1030
1031                 image_mot = image->type_private = malloc(sizeof(struct image_mot));
1032
1033                 retval = fileio_open(&image_mot->fileio, url, FILEIO_READ, FILEIO_TEXT);
1034                 if (retval != ERROR_OK)
1035                         return retval;
1036
1037                 retval = image_mot_buffer_complete(image);
1038                 if (retval != ERROR_OK) {
1039                         LOG_ERROR(
1040                                 "failed buffering S19 image, check server output for additional information");
1041                         fileio_close(image_mot->fileio);
1042                         return retval;
1043                 }
1044         } else if (image->type == IMAGE_BUILDER) {
1045                 image->num_sections = 0;
1046                 image->base_address_set = false;
1047                 image->sections = NULL;
1048                 image->type_private = NULL;
1049         }
1050
1051         if (image->base_address_set) {
1052                 /* relocate */
1053                 for (unsigned int section = 0; section < image->num_sections; section++)
1054                         image->sections[section].base_address += image->base_address;
1055                                                                                         /* we're done relocating. The two statements below are mainly
1056                                                                                         * for documentation purposes: stop anyone from empirically
1057                                                                                         * thinking they should use these values henceforth. */
1058                 image->base_address = 0;
1059                 image->base_address_set = false;
1060         }
1061
1062         return retval;
1063 };
1064
1065 int image_read_section(struct image *image,
1066         int section,
1067         target_addr_t offset,
1068         uint32_t size,
1069         uint8_t *buffer,
1070         size_t *size_read)
1071 {
1072         int retval;
1073
1074         /* don't read past the end of a section */
1075         if (offset + size > image->sections[section].size) {
1076                 LOG_DEBUG(
1077                         "read past end of section: 0x%8.8" TARGET_PRIxADDR " + 0x%8.8" PRIx32 " > 0x%8.8" PRIx32 "",
1078                         offset,
1079                         size,
1080                         image->sections[section].size);
1081                 return ERROR_COMMAND_SYNTAX_ERROR;
1082         }
1083
1084         if (image->type == IMAGE_BINARY) {
1085                 struct image_binary *image_binary = image->type_private;
1086
1087                 /* only one section in a plain binary */
1088                 if (section != 0)
1089                         return ERROR_COMMAND_SYNTAX_ERROR;
1090
1091                 /* seek to offset */
1092                 retval = fileio_seek(image_binary->fileio, offset);
1093                 if (retval != ERROR_OK)
1094                         return retval;
1095
1096                 /* return requested bytes */
1097                 retval = fileio_read(image_binary->fileio, size, buffer, size_read);
1098                 if (retval != ERROR_OK)
1099                         return retval;
1100         } else if (image->type == IMAGE_IHEX) {
1101                 memcpy(buffer, (uint8_t *)image->sections[section].private + offset, size);
1102                 *size_read = size;
1103
1104                 return ERROR_OK;
1105         } else if (image->type == IMAGE_ELF) {
1106                 return image_elf_read_section(image, section, offset, size, buffer, size_read);
1107         } else if (image->type == IMAGE_MEMORY) {
1108                 struct image_memory *image_memory = image->type_private;
1109                 uint32_t address = image->sections[section].base_address + offset;
1110
1111                 *size_read = 0;
1112
1113                 while ((size - *size_read) > 0) {
1114                         uint32_t size_in_cache;
1115
1116                         if (!image_memory->cache
1117                                 || (address < image_memory->cache_address)
1118                                 || (address >=
1119                                 (image_memory->cache_address + IMAGE_MEMORY_CACHE_SIZE))) {
1120                                 if (!image_memory->cache)
1121                                         image_memory->cache = malloc(IMAGE_MEMORY_CACHE_SIZE);
1122
1123                                 if (target_read_buffer(image_memory->target, address &
1124                                         ~(IMAGE_MEMORY_CACHE_SIZE - 1),
1125                                         IMAGE_MEMORY_CACHE_SIZE, image_memory->cache) != ERROR_OK) {
1126                                         free(image_memory->cache);
1127                                         image_memory->cache = NULL;
1128                                         return ERROR_IMAGE_TEMPORARILY_UNAVAILABLE;
1129                                 }
1130                                 image_memory->cache_address = address &
1131                                         ~(IMAGE_MEMORY_CACHE_SIZE - 1);
1132                         }
1133
1134                         size_in_cache =
1135                                 (image_memory->cache_address + IMAGE_MEMORY_CACHE_SIZE) - address;
1136
1137                         memcpy(buffer + *size_read,
1138                                 image_memory->cache + (address - image_memory->cache_address),
1139                                 (size_in_cache > size) ? size : size_in_cache
1140                                 );
1141
1142                         *size_read += (size_in_cache > size) ? size : size_in_cache;
1143                         address += (size_in_cache > size) ? size : size_in_cache;
1144                 }
1145         } else if (image->type == IMAGE_SRECORD) {
1146                 memcpy(buffer, (uint8_t *)image->sections[section].private + offset, size);
1147                 *size_read = size;
1148
1149                 return ERROR_OK;
1150         } else if (image->type == IMAGE_BUILDER) {
1151                 memcpy(buffer, (uint8_t *)image->sections[section].private + offset, size);
1152                 *size_read = size;
1153
1154                 return ERROR_OK;
1155         }
1156
1157         return ERROR_OK;
1158 }
1159
1160 int image_add_section(struct image *image, target_addr_t base, uint32_t size, uint64_t flags, uint8_t const *data)
1161 {
1162         struct imagesection *section;
1163
1164         /* only image builder supports adding sections */
1165         if (image->type != IMAGE_BUILDER)
1166                 return ERROR_COMMAND_SYNTAX_ERROR;
1167
1168         /* see if there's a previous section */
1169         if (image->num_sections) {
1170                 section = &image->sections[image->num_sections - 1];
1171
1172                 /* see if it's enough to extend the last section,
1173                  * adding data to previous sections or merging is not supported */
1174                 if (((section->base_address + section->size) == base) &&
1175                         (section->flags == flags)) {
1176                         section->private = realloc(section->private, section->size + size);
1177                         memcpy((uint8_t *)section->private + section->size, data, size);
1178                         section->size += size;
1179                         return ERROR_OK;
1180                 }
1181         }
1182
1183         /* allocate new section */
1184         image->num_sections++;
1185         image->sections =
1186                 realloc(image->sections, sizeof(struct imagesection) * image->num_sections);
1187         section = &image->sections[image->num_sections - 1];
1188         section->base_address = base;
1189         section->size = size;
1190         section->flags = flags;
1191         section->private = malloc(sizeof(uint8_t) * size);
1192         memcpy((uint8_t *)section->private, data, size);
1193
1194         return ERROR_OK;
1195 }
1196
1197 void image_close(struct image *image)
1198 {
1199         if (image->type == IMAGE_BINARY) {
1200                 struct image_binary *image_binary = image->type_private;
1201
1202                 fileio_close(image_binary->fileio);
1203         } else if (image->type == IMAGE_IHEX) {
1204                 struct image_ihex *image_ihex = image->type_private;
1205
1206                 fileio_close(image_ihex->fileio);
1207
1208                 free(image_ihex->buffer);
1209                 image_ihex->buffer = NULL;
1210         } else if (image->type == IMAGE_ELF) {
1211                 struct image_elf *image_elf = image->type_private;
1212
1213                 fileio_close(image_elf->fileio);
1214
1215                 if (image_elf->is_64_bit) {
1216                         free(image_elf->header64);
1217                         image_elf->header64 = NULL;
1218
1219                         free(image_elf->segments64);
1220                         image_elf->segments64 = NULL;
1221                 } else {
1222                         free(image_elf->header32);
1223                         image_elf->header32 = NULL;
1224
1225                         free(image_elf->segments32);
1226                         image_elf->segments32 = NULL;
1227                 }
1228         } else if (image->type == IMAGE_MEMORY) {
1229                 struct image_memory *image_memory = image->type_private;
1230
1231                 free(image_memory->cache);
1232                 image_memory->cache = NULL;
1233         } else if (image->type == IMAGE_SRECORD) {
1234                 struct image_mot *image_mot = image->type_private;
1235
1236                 fileio_close(image_mot->fileio);
1237
1238                 free(image_mot->buffer);
1239                 image_mot->buffer = NULL;
1240         } else if (image->type == IMAGE_BUILDER) {
1241                 for (unsigned int i = 0; i < image->num_sections; i++) {
1242                         free(image->sections[i].private);
1243                         image->sections[i].private = NULL;
1244                 }
1245         }
1246
1247         free(image->type_private);
1248         image->type_private = NULL;
1249
1250         free(image->sections);
1251         image->sections = NULL;
1252 }
1253
1254 int image_calculate_checksum(const uint8_t *buffer, uint32_t nbytes, uint32_t *checksum)
1255 {
1256         uint32_t crc = 0xffffffff;
1257         LOG_DEBUG("Calculating checksum");
1258
1259         static uint32_t crc32_table[256];
1260
1261         static bool first_init;
1262         if (!first_init) {
1263                 /* Initialize the CRC table and the decoding table.  */
1264                 unsigned int i, j, c;
1265                 for (i = 0; i < 256; i++) {
1266                         /* as per gdb */
1267                         for (c = i << 24, j = 8; j > 0; --j)
1268                                 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
1269                         crc32_table[i] = c;
1270                 }
1271
1272                 first_init = true;
1273         }
1274
1275         while (nbytes > 0) {
1276                 int run = nbytes;
1277                 if (run > 32768)
1278                         run = 32768;
1279                 nbytes -= run;
1280                 while (run--) {
1281                         /* as per gdb */
1282                         crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buffer++) & 255];
1283                 }
1284                 keep_alive();
1285         }
1286
1287         LOG_DEBUG("Calculating checksum done; checksum=0x%" PRIx32, crc);
1288
1289         *checksum = crc;
1290         return ERROR_OK;
1291 }