]> git.sur5r.net Git - openocd/blob - src/target/image.c
b1b7e3a6af723eeeb330d0526bafb4e7ae3827ed
[openocd] / src / target / image.c
1 /***************************************************************************
2  *   Copyright (C) 2007 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007,2008 Ã˜yvind Harboe                                 *
6  *   oyvind.harboe@zylin.com                                               *
7  *                                                                         *
8  *   Copyright (C) 2008 by Spencer Oliver                                  *
9  *   spen@spen-soft.co.uk                                                  *
10  *                                                                         *
11  *   Copyright (C) 2009 by Franck Hereson                                  *
12  *   franck.hereson@secad.fr                                               *
13  *                                                                         *
14  *   This program is free software; you can redistribute it and/or modify  *
15  *   it under the terms of the GNU General Public License as published by  *
16  *   the Free Software Foundation; either version 2 of the License, or     *
17  *   (at your option) any later version.                                   *
18  *                                                                         *
19  *   This program is distributed in the hope that it will be useful,       *
20  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
21  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
22  *   GNU General Public License for more details.                          *
23  *                                                                         *
24  *   You should have received a copy of the GNU General Public License     *
25  *   along with this program; if not, write to the                         *
26  *   Free Software Foundation, Inc.,                                       *
27  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
28  ***************************************************************************/
29
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif
33
34 #include "image.h"
35 #include "target.h"
36 #include <helper/log.h>
37
38 /* convert ELF header field to host endianness */
39 #define field16(elf, field) \
40         ((elf->endianness == ELFDATA2LSB) ? \
41         le_to_h_u16((uint8_t *)&field) : be_to_h_u16((uint8_t *)&field))
42
43 #define field32(elf, field) \
44         ((elf->endianness == ELFDATA2LSB) ? \
45         le_to_h_u32((uint8_t *)&field) : be_to_h_u32((uint8_t *)&field))
46
47 static int autodetect_image_type(struct image *image, const char *url)
48 {
49         int retval;
50         struct fileio fileio;
51         size_t read_bytes;
52         uint8_t buffer[9];
53
54         /* read the first 4 bytes of image */
55         retval = fileio_open(&fileio, url, FILEIO_READ, FILEIO_BINARY);
56         if (retval != ERROR_OK)
57                 return retval;
58         retval = fileio_read(&fileio, 9, buffer, &read_bytes);
59
60         if (retval == ERROR_OK) {
61                 if (read_bytes != 9)
62                         retval = ERROR_FILEIO_OPERATION_FAILED;
63         }
64         fileio_close(&fileio);
65
66         if (retval != ERROR_OK)
67                 return retval;
68
69         /* check header against known signatures */
70         if (strncmp((char *)buffer, ELFMAG, SELFMAG) == 0) {
71                 LOG_DEBUG("ELF image detected.");
72                 image->type = IMAGE_ELF;
73         } else if ((buffer[0] == ':')   /* record start byte */
74                 && (isxdigit(buffer[1]))
75                 && (isxdigit(buffer[2]))
76                 && (isxdigit(buffer[3]))
77                 && (isxdigit(buffer[4]))
78                 && (isxdigit(buffer[5]))
79                 && (isxdigit(buffer[6]))
80                 && (buffer[7] == '0')   /* record type : 00 -> 05 */
81                 && (buffer[8] >= '0') && (buffer[8] < '6')) {
82                 LOG_DEBUG("IHEX image detected.");
83                 image->type = IMAGE_IHEX;
84         } else if ((buffer[0] == 'S')   /* record start byte */
85                 && (isxdigit(buffer[1]))
86                 && (isxdigit(buffer[2]))
87                 && (isxdigit(buffer[3]))
88                 && (buffer[1] >= '0') && (buffer[1] < '9')) {
89                 LOG_DEBUG("S19 image detected.");
90                 image->type = IMAGE_SRECORD;
91         } else
92                 image->type = IMAGE_BINARY;
93
94         return ERROR_OK;
95 }
96
97 static int identify_image_type(struct image *image, const char *type_string, const char *url)
98 {
99         if (type_string) {
100                 if (!strcmp(type_string, "bin"))
101                         image->type = IMAGE_BINARY;
102                 else if (!strcmp(type_string, "ihex"))
103                         image->type = IMAGE_IHEX;
104                 else if (!strcmp(type_string, "elf"))
105                         image->type = IMAGE_ELF;
106                 else if (!strcmp(type_string, "mem"))
107                         image->type = IMAGE_MEMORY;
108                 else if (!strcmp(type_string, "s19"))
109                         image->type = IMAGE_SRECORD;
110                 else if (!strcmp(type_string, "build"))
111                         image->type = IMAGE_BUILDER;
112                 else
113                         return ERROR_IMAGE_TYPE_UNKNOWN;
114         } else
115                 return autodetect_image_type(image, url);
116
117         return ERROR_OK;
118 }
119
120 static int image_ihex_buffer_complete_inner(struct image *image,
121         char *lpszLine,
122         struct imagesection *section)
123 {
124         struct image_ihex *ihex = image->type_private;
125         struct fileio *fileio = &ihex->fileio;
126         uint32_t full_address = 0x0;
127         uint32_t cooked_bytes;
128         int i;
129
130         /* we can't determine the number of sections that we'll have to create ahead of time,
131          * so we locally hold them until parsing is finished */
132
133         int filesize;
134         int retval;
135         retval = fileio_size(fileio, &filesize);
136         if (retval != ERROR_OK)
137                 return retval;
138
139         ihex->buffer = malloc(filesize >> 1);
140         cooked_bytes = 0x0;
141         image->num_sections = 0;
142         section[image->num_sections].private = &ihex->buffer[cooked_bytes];
143         section[image->num_sections].base_address = 0x0;
144         section[image->num_sections].size = 0x0;
145         section[image->num_sections].flags = 0;
146
147         while (fileio_fgets(fileio, 1023, lpszLine) == ERROR_OK) {
148                 uint32_t count;
149                 uint32_t address;
150                 uint32_t record_type;
151                 uint32_t checksum;
152                 uint8_t cal_checksum = 0;
153                 size_t bytes_read = 0;
154
155                 if (lpszLine[0] == '#')
156                         continue;
157
158                 if (sscanf(&lpszLine[bytes_read], ":%2" SCNx32 "%4" SCNx32 "%2" SCNx32, &count,
159                         &address, &record_type) != 3)
160                         return ERROR_IMAGE_FORMAT_ERROR;
161                 bytes_read += 9;
162
163                 cal_checksum += (uint8_t)count;
164                 cal_checksum += (uint8_t)(address >> 8);
165                 cal_checksum += (uint8_t)address;
166                 cal_checksum += (uint8_t)record_type;
167
168                 if (record_type == 0) { /* Data Record */
169                         if ((full_address & 0xffff) != address) {
170                                 /* we encountered a nonconsecutive location, create a new section,
171                                  * unless the current section has zero size, in which case this specifies
172                                  * the current section's base address
173                                  */
174                                 if (section[image->num_sections].size != 0) {
175                                         image->num_sections++;
176                                         if (image->num_sections >= IMAGE_MAX_SECTIONS) {
177                                                 /* too many sections */
178                                                 LOG_ERROR("Too many sections found in IHEX file");
179                                                 return ERROR_IMAGE_FORMAT_ERROR;
180                                         }
181                                         section[image->num_sections].size = 0x0;
182                                         section[image->num_sections].flags = 0;
183                                         section[image->num_sections].private =
184                                                 &ihex->buffer[cooked_bytes];
185                                 }
186                                 section[image->num_sections].base_address =
187                                         (full_address & 0xffff0000) | address;
188                                 full_address = (full_address & 0xffff0000) | address;
189                         }
190
191                         while (count-- > 0) {
192                                 unsigned value;
193                                 sscanf(&lpszLine[bytes_read], "%2x", &value);
194                                 ihex->buffer[cooked_bytes] = (uint8_t)value;
195                                 cal_checksum += (uint8_t)ihex->buffer[cooked_bytes];
196                                 bytes_read += 2;
197                                 cooked_bytes += 1;
198                                 section[image->num_sections].size += 1;
199                                 full_address++;
200                         }
201                 } else if (record_type == 1) {  /* End of File Record */
202                         /* finish the current section */
203                         image->num_sections++;
204
205                         /* copy section information */
206                         image->sections = malloc(sizeof(struct imagesection) * image->num_sections);
207                         for (i = 0; i < image->num_sections; i++) {
208                                 image->sections[i].private = section[i].private;
209                                 image->sections[i].base_address = section[i].base_address;
210                                 image->sections[i].size = section[i].size;
211                                 image->sections[i].flags = section[i].flags;
212                         }
213
214                         return ERROR_OK;
215                 } else if (record_type == 2) {  /* Linear Address Record */
216                         uint16_t upper_address;
217
218                         sscanf(&lpszLine[bytes_read], "%4hx", &upper_address);
219                         cal_checksum += (uint8_t)(upper_address >> 8);
220                         cal_checksum += (uint8_t)upper_address;
221                         bytes_read += 4;
222
223                         if ((full_address >> 4) != upper_address) {
224                                 /* we encountered a nonconsecutive location, create a new section,
225                                  * unless the current section has zero size, in which case this specifies
226                                  * the current section's base address
227                                  */
228                                 if (section[image->num_sections].size != 0) {
229                                         image->num_sections++;
230                                         if (image->num_sections >= IMAGE_MAX_SECTIONS) {
231                                                 /* too many sections */
232                                                 LOG_ERROR("Too many sections found in IHEX file");
233                                                 return ERROR_IMAGE_FORMAT_ERROR;
234                                         }
235                                         section[image->num_sections].size = 0x0;
236                                         section[image->num_sections].flags = 0;
237                                         section[image->num_sections].private =
238                                                 &ihex->buffer[cooked_bytes];
239                                 }
240                                 section[image->num_sections].base_address =
241                                         (full_address & 0xffff) | (upper_address << 4);
242                                 full_address = (full_address & 0xffff) | (upper_address << 4);
243                         }
244                 } else if (record_type == 3) {  /* Start Segment Address Record */
245                         uint32_t dummy;
246
247                         /* "Start Segment Address Record" will not be supported
248                          * but we must consume it, and do not create an error.  */
249                         while (count-- > 0) {
250                                 sscanf(&lpszLine[bytes_read], "%2" SCNx32, &dummy);
251                                 cal_checksum += (uint8_t)dummy;
252                                 bytes_read += 2;
253                         }
254                 } else if (record_type == 4) {  /* Extended Linear Address Record */
255                         uint16_t upper_address;
256
257                         sscanf(&lpszLine[bytes_read], "%4hx", &upper_address);
258                         cal_checksum += (uint8_t)(upper_address >> 8);
259                         cal_checksum += (uint8_t)upper_address;
260                         bytes_read += 4;
261
262                         if ((full_address >> 16) != upper_address) {
263                                 /* we encountered a nonconsecutive location, create a new section,
264                                  * unless the current section has zero size, in which case this specifies
265                                  * the current section's base address
266                                  */
267                                 if (section[image->num_sections].size != 0) {
268                                         image->num_sections++;
269                                         if (image->num_sections >= IMAGE_MAX_SECTIONS) {
270                                                 /* too many sections */
271                                                 LOG_ERROR("Too many sections found in IHEX file");
272                                                 return ERROR_IMAGE_FORMAT_ERROR;
273                                         }
274                                         section[image->num_sections].size = 0x0;
275                                         section[image->num_sections].flags = 0;
276                                         section[image->num_sections].private =
277                                                 &ihex->buffer[cooked_bytes];
278                                 }
279                                 section[image->num_sections].base_address =
280                                         (full_address & 0xffff) | (upper_address << 16);
281                                 full_address = (full_address & 0xffff) | (upper_address << 16);
282                         }
283                 } else if (record_type == 5) {  /* Start Linear Address Record */
284                         uint32_t start_address;
285
286                         sscanf(&lpszLine[bytes_read], "%8" SCNx32, &start_address);
287                         cal_checksum += (uint8_t)(start_address >> 24);
288                         cal_checksum += (uint8_t)(start_address >> 16);
289                         cal_checksum += (uint8_t)(start_address >> 8);
290                         cal_checksum += (uint8_t)start_address;
291                         bytes_read += 8;
292
293                         image->start_address_set = 1;
294                         image->start_address = be_to_h_u32((uint8_t *)&start_address);
295                 } else {
296                         LOG_ERROR("unhandled IHEX record type: %i", (int)record_type);
297                         return ERROR_IMAGE_FORMAT_ERROR;
298                 }
299
300                 sscanf(&lpszLine[bytes_read], "%2" SCNx32, &checksum);
301
302                 if ((uint8_t)checksum != (uint8_t)(~cal_checksum + 1)) {
303                         /* checksum failed */
304                         LOG_ERROR("incorrect record checksum found in IHEX file");
305                         return ERROR_IMAGE_CHECKSUM;
306                 }
307         }
308
309         LOG_ERROR("premature end of IHEX file, no end-of-file record found");
310         return ERROR_IMAGE_FORMAT_ERROR;
311 }
312
313 /**
314  * Allocate memory dynamically instead of on the stack. This
315  * is important w/embedded hosts.
316  */
317 static int image_ihex_buffer_complete(struct image *image)
318 {
319         char *lpszLine = malloc(1023);
320         if (lpszLine == NULL) {
321                 LOG_ERROR("Out of memory");
322                 return ERROR_FAIL;
323         }
324         struct imagesection *section = malloc(sizeof(struct imagesection) * IMAGE_MAX_SECTIONS);
325         if (section == NULL) {
326                 free(lpszLine);
327                 LOG_ERROR("Out of memory");
328                 return ERROR_FAIL;
329         }
330         int retval;
331
332         retval = image_ihex_buffer_complete_inner(image, lpszLine, section);
333
334         free(section);
335         free(lpszLine);
336
337         return retval;
338 }
339
340 static int image_elf_read_headers(struct image *image)
341 {
342         struct image_elf *elf = image->type_private;
343         size_t read_bytes;
344         uint32_t i, j;
345         int retval;
346         uint32_t nload, load_to_vaddr = 0;
347
348         elf->header = malloc(sizeof(Elf32_Ehdr));
349
350         if (elf->header == NULL) {
351                 LOG_ERROR("insufficient memory to perform operation ");
352                 return ERROR_FILEIO_OPERATION_FAILED;
353         }
354
355         retval = fileio_read(&elf->fileio, sizeof(Elf32_Ehdr), (uint8_t *)elf->header, &read_bytes);
356         if (retval != ERROR_OK) {
357                 LOG_ERROR("cannot read ELF file header, read failed");
358                 return ERROR_FILEIO_OPERATION_FAILED;
359         }
360         if (read_bytes != sizeof(Elf32_Ehdr)) {
361                 LOG_ERROR("cannot read ELF file header, only partially read");
362                 return ERROR_FILEIO_OPERATION_FAILED;
363         }
364
365         if (strncmp((char *)elf->header->e_ident, ELFMAG, SELFMAG) != 0) {
366                 LOG_ERROR("invalid ELF file, bad magic number");
367                 return ERROR_IMAGE_FORMAT_ERROR;
368         }
369         if (elf->header->e_ident[EI_CLASS] != ELFCLASS32) {
370                 LOG_ERROR("invalid ELF file, only 32bits files are supported");
371                 return ERROR_IMAGE_FORMAT_ERROR;
372         }
373
374         elf->endianness = elf->header->e_ident[EI_DATA];
375         if ((elf->endianness != ELFDATA2LSB)
376                 && (elf->endianness != ELFDATA2MSB)) {
377                 LOG_ERROR("invalid ELF file, unknown endianness setting");
378                 return ERROR_IMAGE_FORMAT_ERROR;
379         }
380
381         elf->segment_count = field16(elf, elf->header->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->header->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->segments = malloc(elf->segment_count*sizeof(Elf32_Phdr));
394         if (elf->segments == NULL) {
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->segments, &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->segments[i].p_type) == PT_LOAD) &&
415                         (field32(elf, elf->segments[i].p_filesz) != 0))
416                         image->num_sections++;
417
418         assert(image->num_sections > 0);
419
420         /**
421          * some ELF linkers produce binaries with *all* the program header
422          * p_paddr fields zero (there can be however one loadable segment
423          * that has valid physical address 0x0).
424          * If we have such a binary with more than
425          * one PT_LOAD header, then use p_vaddr instead of p_paddr
426          * (ARM ELF standard demands p_paddr = 0 anyway, and BFD
427          * library uses this approach to workaround zero-initialized p_paddrs
428          * when obtaining lma - look at elf.c of BDF)
429          */
430         for (nload = 0, i = 0; i < elf->segment_count; i++)
431                 if (elf->segments[i].p_paddr != 0)
432                         break;
433                 else if ((field32(elf,
434                         elf->segments[i].p_type) == PT_LOAD) &&
435                         (field32(elf, elf->segments[i].p_memsz) != 0))
436                         ++nload;
437
438         if (i >= elf->segment_count && nload > 1)
439                 load_to_vaddr = 1;
440
441         /* alloc and fill sections array with loadable segments */
442         image->sections = malloc(image->num_sections * sizeof(struct imagesection));
443         for (i = 0, j = 0; i < elf->segment_count; i++) {
444                 if ((field32(elf,
445                         elf->segments[i].p_type) == PT_LOAD) &&
446                         (field32(elf, elf->segments[i].p_filesz) != 0)) {
447                         image->sections[j].size = field32(elf, elf->segments[i].p_filesz);
448                         if (load_to_vaddr)
449                                 image->sections[j].base_address = field32(elf,
450                                                 elf->segments[i].p_vaddr);
451                         else
452                                 image->sections[j].base_address = field32(elf,
453                                                 elf->segments[i].p_paddr);
454                         image->sections[j].private = &elf->segments[i];
455                         image->sections[j].flags = field32(elf, elf->segments[i].p_flags);
456                         j++;
457                 }
458         }
459
460         image->start_address_set = 1;
461         image->start_address = field32(elf, elf->header->e_entry);
462
463         return ERROR_OK;
464 }
465
466 static int image_elf_read_section(struct image *image,
467         int section,
468         uint32_t offset,
469         uint32_t size,
470         uint8_t *buffer,
471         size_t *size_read)
472 {
473         struct image_elf *elf = image->type_private;
474         Elf32_Phdr *segment = (Elf32_Phdr *)image->sections[section].private;
475         size_t read_size, really_read;
476         int retval;
477
478         *size_read = 0;
479
480         LOG_DEBUG("load segment %d at 0x%" PRIx32 " (sz = 0x%" PRIx32 ")", section, offset, size);
481
482         /* read initialized data in current segment if any */
483         if (offset < field32(elf, segment->p_filesz)) {
484                 /* maximal size present in file for the current segment */
485                 read_size = MIN(size, field32(elf, segment->p_filesz) - offset);
486                 LOG_DEBUG("read elf: size = 0x%zu at 0x%" PRIx32 "", read_size,
487                         field32(elf, segment->p_offset) + offset);
488                 /* read initialized area of the segment */
489                 retval = fileio_seek(&elf->fileio, field32(elf, segment->p_offset) + offset);
490                 if (retval != ERROR_OK) {
491                         LOG_ERROR("cannot find ELF segment content, seek failed");
492                         return retval;
493                 }
494                 retval = fileio_read(&elf->fileio, read_size, buffer, &really_read);
495                 if (retval != ERROR_OK) {
496                         LOG_ERROR("cannot read ELF segment content, read failed");
497                         return retval;
498                 }
499                 size -= read_size;
500                 *size_read += read_size;
501                 /* need more data ? */
502                 if (!size)
503                         return ERROR_OK;
504         }
505
506         return ERROR_OK;
507 }
508
509 static int image_mot_buffer_complete_inner(struct image *image,
510         char *lpszLine,
511         struct imagesection *section)
512 {
513         struct image_mot *mot = image->type_private;
514         struct fileio *fileio = &mot->fileio;
515         uint32_t full_address = 0x0;
516         uint32_t cooked_bytes;
517         int i;
518
519         /* we can't determine the number of sections that we'll have to create ahead of time,
520          * so we locally hold them until parsing is finished */
521
522         int retval;
523         int filesize;
524         retval = fileio_size(fileio, &filesize);
525         if (retval != ERROR_OK)
526                 return retval;
527
528         mot->buffer = malloc(filesize >> 1);
529         cooked_bytes = 0x0;
530         image->num_sections = 0;
531         section[image->num_sections].private = &mot->buffer[cooked_bytes];
532         section[image->num_sections].base_address = 0x0;
533         section[image->num_sections].size = 0x0;
534         section[image->num_sections].flags = 0;
535
536         while (fileio_fgets(fileio, 1023, lpszLine) == ERROR_OK) {
537                 uint32_t count;
538                 uint32_t address;
539                 uint32_t record_type;
540                 uint32_t checksum;
541                 uint8_t cal_checksum = 0;
542                 uint32_t bytes_read = 0;
543
544                 /* get record type and record length */
545                 if (sscanf(&lpszLine[bytes_read], "S%1" SCNx32 "%2" SCNx32, &record_type,
546                         &count) != 2)
547                         return ERROR_IMAGE_FORMAT_ERROR;
548
549                 bytes_read += 4;
550                 cal_checksum += (uint8_t)count;
551
552                 /* skip checksum byte */
553                 count -= 1;
554
555                 if (record_type == 0) {
556                         /* S0 - starting record (optional) */
557                         int iValue;
558
559                         while (count-- > 0) {
560                                 sscanf(&lpszLine[bytes_read], "%2x", &iValue);
561                                 cal_checksum += (uint8_t)iValue;
562                                 bytes_read += 2;
563                         }
564                 } else if (record_type >= 1 && record_type <= 3) {
565                         switch (record_type) {
566                                 case 1:
567                                         /* S1 - 16 bit address data record */
568                                         sscanf(&lpszLine[bytes_read], "%4" SCNx32, &address);
569                                         cal_checksum += (uint8_t)(address >> 8);
570                                         cal_checksum += (uint8_t)address;
571                                         bytes_read += 4;
572                                         count -= 2;
573                                         break;
574
575                                 case 2:
576                                         /* S2 - 24 bit address data record */
577                                         sscanf(&lpszLine[bytes_read], "%6" SCNx32, &address);
578                                         cal_checksum += (uint8_t)(address >> 16);
579                                         cal_checksum += (uint8_t)(address >> 8);
580                                         cal_checksum += (uint8_t)address;
581                                         bytes_read += 6;
582                                         count -= 3;
583                                         break;
584
585                                 case 3:
586                                         /* S3 - 32 bit address data record */
587                                         sscanf(&lpszLine[bytes_read], "%8" SCNx32, &address);
588                                         cal_checksum += (uint8_t)(address >> 24);
589                                         cal_checksum += (uint8_t)(address >> 16);
590                                         cal_checksum += (uint8_t)(address >> 8);
591                                         cal_checksum += (uint8_t)address;
592                                         bytes_read += 8;
593                                         count -= 4;
594                                         break;
595
596                         }
597
598                         if (full_address != address) {
599                                 /* we encountered a nonconsecutive location, create a new section,
600                                  * unless the current section has zero size, in which case this specifies
601                                  * the current section's base address
602                                  */
603                                 if (section[image->num_sections].size != 0) {
604                                         image->num_sections++;
605                                         section[image->num_sections].size = 0x0;
606                                         section[image->num_sections].flags = 0;
607                                         section[image->num_sections].private =
608                                                 &mot->buffer[cooked_bytes];
609                                 }
610                                 section[image->num_sections].base_address = address;
611                                 full_address = address;
612                         }
613
614                         while (count-- > 0) {
615                                 unsigned value;
616                                 sscanf(&lpszLine[bytes_read], "%2x", &value);
617                                 mot->buffer[cooked_bytes] = (uint8_t)value;
618                                 cal_checksum += (uint8_t)mot->buffer[cooked_bytes];
619                                 bytes_read += 2;
620                                 cooked_bytes += 1;
621                                 section[image->num_sections].size += 1;
622                                 full_address++;
623                         }
624                 } else if (record_type == 5) {
625                         /* S5 is the data count record, we ignore it */
626                         uint32_t dummy;
627
628                         while (count-- > 0) {
629                                 sscanf(&lpszLine[bytes_read], "%2" SCNx32, &dummy);
630                                 cal_checksum += (uint8_t)dummy;
631                                 bytes_read += 2;
632                         }
633                 } else if (record_type >= 7 && record_type <= 9) {
634                         /* S7, S8, S9 - ending records for 32, 24 and 16bit */
635                         image->num_sections++;
636
637                         /* copy section information */
638                         image->sections = malloc(sizeof(struct imagesection) * image->num_sections);
639                         for (i = 0; i < image->num_sections; i++) {
640                                 image->sections[i].private = section[i].private;
641                                 image->sections[i].base_address = section[i].base_address;
642                                 image->sections[i].size = section[i].size;
643                                 image->sections[i].flags = section[i].flags;
644                         }
645
646                         return ERROR_OK;
647                 } else {
648                         LOG_ERROR("unhandled S19 record type: %i", (int)(record_type));
649                         return ERROR_IMAGE_FORMAT_ERROR;
650                 }
651
652                 /* account for checksum, will always be 0xFF */
653                 sscanf(&lpszLine[bytes_read], "%2" SCNx32, &checksum);
654                 cal_checksum += (uint8_t)checksum;
655
656                 if (cal_checksum != 0xFF) {
657                         /* checksum failed */
658                         LOG_ERROR("incorrect record checksum found in S19 file");
659                         return ERROR_IMAGE_CHECKSUM;
660                 }
661         }
662
663         LOG_ERROR("premature end of S19 file, no end-of-file record found");
664         return ERROR_IMAGE_FORMAT_ERROR;
665 }
666
667 /**
668  * Allocate memory dynamically instead of on the stack. This
669  * is important w/embedded hosts.
670  */
671 static int image_mot_buffer_complete(struct image *image)
672 {
673         char *lpszLine = malloc(1023);
674         if (lpszLine == NULL) {
675                 LOG_ERROR("Out of memory");
676                 return ERROR_FAIL;
677         }
678         struct imagesection *section = malloc(sizeof(struct imagesection) * IMAGE_MAX_SECTIONS);
679         if (section == NULL) {
680                 free(lpszLine);
681                 LOG_ERROR("Out of memory");
682                 return ERROR_FAIL;
683         }
684         int retval;
685
686         retval = image_mot_buffer_complete_inner(image, lpszLine, section);
687
688         free(section);
689         free(lpszLine);
690
691         return retval;
692 }
693
694 int image_open(struct image *image, const char *url, const char *type_string)
695 {
696         int retval = ERROR_OK;
697
698         retval = identify_image_type(image, type_string, url);
699         if (retval != ERROR_OK)
700                 return retval;
701
702         if (image->type == IMAGE_BINARY) {
703                 struct image_binary *image_binary;
704
705                 image_binary = image->type_private = malloc(sizeof(struct image_binary));
706
707                 retval = fileio_open(&image_binary->fileio, url, FILEIO_READ, FILEIO_BINARY);
708                 if (retval != ERROR_OK)
709                         return retval;
710                 int filesize;
711                 retval = fileio_size(&image_binary->fileio, &filesize);
712                 if (retval != ERROR_OK) {
713                         fileio_close(&image_binary->fileio);
714                         return retval;
715                 }
716
717                 image->num_sections = 1;
718                 image->sections = malloc(sizeof(struct imagesection));
719                 image->sections[0].base_address = 0x0;
720                 image->sections[0].size = filesize;
721                 image->sections[0].flags = 0;
722         } else if (image->type == IMAGE_IHEX) {
723                 struct image_ihex *image_ihex;
724
725                 image_ihex = image->type_private = malloc(sizeof(struct image_ihex));
726
727                 retval = fileio_open(&image_ihex->fileio, url, FILEIO_READ, FILEIO_TEXT);
728                 if (retval != ERROR_OK)
729                         return retval;
730
731                 retval = image_ihex_buffer_complete(image);
732                 if (retval != ERROR_OK) {
733                         LOG_ERROR(
734                                 "failed buffering IHEX image, check daemon output for additional information");
735                         fileio_close(&image_ihex->fileio);
736                         return retval;
737                 }
738         } else if (image->type == IMAGE_ELF) {
739                 struct image_elf *image_elf;
740
741                 image_elf = image->type_private = malloc(sizeof(struct image_elf));
742
743                 retval = fileio_open(&image_elf->fileio, url, FILEIO_READ, FILEIO_BINARY);
744                 if (retval != ERROR_OK)
745                         return retval;
746
747                 retval = image_elf_read_headers(image);
748                 if (retval != ERROR_OK) {
749                         fileio_close(&image_elf->fileio);
750                         return retval;
751                 }
752         } else if (image->type == IMAGE_MEMORY) {
753                 struct target *target = get_target(url);
754
755                 if (target == NULL) {
756                         LOG_ERROR("target '%s' not defined", url);
757                         return ERROR_FAIL;
758                 }
759
760                 struct image_memory *image_memory;
761
762                 image->num_sections = 1;
763                 image->sections = malloc(sizeof(struct imagesection));
764                 image->sections[0].base_address = 0x0;
765                 image->sections[0].size = 0xffffffff;
766                 image->sections[0].flags = 0;
767
768                 image_memory = image->type_private = malloc(sizeof(struct image_memory));
769
770                 image_memory->target = target;
771                 image_memory->cache = NULL;
772                 image_memory->cache_address = 0x0;
773         } else if (image->type == IMAGE_SRECORD) {
774                 struct image_mot *image_mot;
775
776                 image_mot = image->type_private = malloc(sizeof(struct image_mot));
777
778                 retval = fileio_open(&image_mot->fileio, url, FILEIO_READ, FILEIO_TEXT);
779                 if (retval != ERROR_OK)
780                         return retval;
781
782                 retval = image_mot_buffer_complete(image);
783                 if (retval != ERROR_OK) {
784                         LOG_ERROR(
785                                 "failed buffering S19 image, check daemon output for additional information");
786                         fileio_close(&image_mot->fileio);
787                         return retval;
788                 }
789         } else if (image->type == IMAGE_BUILDER) {
790                 image->num_sections = 0;
791                 image->base_address_set = 0;
792                 image->sections = NULL;
793                 image->type_private = NULL;
794         }
795
796         if (image->base_address_set) {
797                 /* relocate */
798                 int section;
799                 for (section = 0; section < image->num_sections; section++)
800                         image->sections[section].base_address += image->base_address;
801                                                                                         /* we're done relocating. The two statements below are mainly
802                                                                                         * for documenation purposes: stop anyone from empirically
803                                                                                         * thinking they should use these values henceforth. */
804                 image->base_address = 0;
805                 image->base_address_set = 0;
806         }
807
808         return retval;
809 };
810
811 int image_read_section(struct image *image,
812         int section,
813         uint32_t offset,
814         uint32_t size,
815         uint8_t *buffer,
816         size_t *size_read)
817 {
818         int retval;
819
820         /* don't read past the end of a section */
821         if (offset + size > image->sections[section].size) {
822                 LOG_DEBUG(
823                         "read past end of section: 0x%8.8" PRIx32 " + 0x%8.8" PRIx32 " > 0x%8.8" PRIx32 "",
824                         offset,
825                         size,
826                         image->sections[section].size);
827                 return ERROR_COMMAND_SYNTAX_ERROR;
828         }
829
830         if (image->type == IMAGE_BINARY) {
831                 struct image_binary *image_binary = image->type_private;
832
833                 /* only one section in a plain binary */
834                 if (section != 0)
835                         return ERROR_COMMAND_SYNTAX_ERROR;
836
837                 /* seek to offset */
838                 retval = fileio_seek(&image_binary->fileio, offset);
839                 if (retval != ERROR_OK)
840                         return retval;
841
842                 /* return requested bytes */
843                 retval = fileio_read(&image_binary->fileio, size, buffer, size_read);
844                 if (retval != ERROR_OK)
845                         return retval;
846         } else if (image->type == IMAGE_IHEX) {
847                 memcpy(buffer, (uint8_t *)image->sections[section].private + offset, size);
848                 *size_read = size;
849
850                 return ERROR_OK;
851         } else if (image->type == IMAGE_ELF)
852                 return image_elf_read_section(image, section, offset, size, buffer, size_read);
853         else if (image->type == IMAGE_MEMORY) {
854                 struct image_memory *image_memory = image->type_private;
855                 uint32_t address = image->sections[section].base_address + offset;
856
857                 *size_read = 0;
858
859                 while ((size - *size_read) > 0) {
860                         uint32_t size_in_cache;
861
862                         if (!image_memory->cache
863                                 || (address < image_memory->cache_address)
864                                 || (address >=
865                                 (image_memory->cache_address + IMAGE_MEMORY_CACHE_SIZE))) {
866                                 if (!image_memory->cache)
867                                         image_memory->cache = malloc(IMAGE_MEMORY_CACHE_SIZE);
868
869                                 if (target_read_buffer(image_memory->target, address &
870                                         ~(IMAGE_MEMORY_CACHE_SIZE - 1),
871                                         IMAGE_MEMORY_CACHE_SIZE, image_memory->cache) != ERROR_OK) {
872                                         free(image_memory->cache);
873                                         image_memory->cache = NULL;
874                                         return ERROR_IMAGE_TEMPORARILY_UNAVAILABLE;
875                                 }
876                                 image_memory->cache_address = address &
877                                         ~(IMAGE_MEMORY_CACHE_SIZE - 1);
878                         }
879
880                         size_in_cache =
881                                 (image_memory->cache_address + IMAGE_MEMORY_CACHE_SIZE) - address;
882
883                         memcpy(buffer + *size_read,
884                                 image_memory->cache + (address - image_memory->cache_address),
885                                 (size_in_cache > size) ? size : size_in_cache
886                                 );
887
888                         *size_read += (size_in_cache > size) ? size : size_in_cache;
889                         address += (size_in_cache > size) ? size : size_in_cache;
890                 }
891         } else if (image->type == IMAGE_SRECORD) {
892                 memcpy(buffer, (uint8_t *)image->sections[section].private + offset, size);
893                 *size_read = size;
894
895                 return ERROR_OK;
896         } else if (image->type == IMAGE_BUILDER) {
897                 memcpy(buffer, (uint8_t *)image->sections[section].private + offset, size);
898                 *size_read = size;
899
900                 return ERROR_OK;
901         }
902
903         return ERROR_OK;
904 }
905
906 int image_add_section(struct image *image, uint32_t base, uint32_t size, int flags, uint8_t const *data)
907 {
908         struct imagesection *section;
909
910         /* only image builder supports adding sections */
911         if (image->type != IMAGE_BUILDER)
912                 return ERROR_COMMAND_SYNTAX_ERROR;
913
914         /* see if there's a previous section */
915         if (image->num_sections) {
916                 section = &image->sections[image->num_sections - 1];
917
918                 /* see if it's enough to extend the last section,
919                  * adding data to previous sections or merging is not supported */
920                 if (((section->base_address + section->size) == base) &&
921                         (section->flags == flags)) {
922                         section->private = realloc(section->private, section->size + size);
923                         memcpy((uint8_t *)section->private + section->size, data, size);
924                         section->size += size;
925                         return ERROR_OK;
926                 }
927         }
928
929         /* allocate new section */
930         image->num_sections++;
931         image->sections =
932                 realloc(image->sections, sizeof(struct imagesection) * image->num_sections);
933         section = &image->sections[image->num_sections - 1];
934         section->base_address = base;
935         section->size = size;
936         section->flags = flags;
937         section->private = malloc(sizeof(uint8_t) * size);
938         memcpy((uint8_t *)section->private, data, size);
939
940         return ERROR_OK;
941 }
942
943 void image_close(struct image *image)
944 {
945         if (image->type == IMAGE_BINARY) {
946                 struct image_binary *image_binary = image->type_private;
947
948                 fileio_close(&image_binary->fileio);
949         } else if (image->type == IMAGE_IHEX) {
950                 struct image_ihex *image_ihex = image->type_private;
951
952                 fileio_close(&image_ihex->fileio);
953
954                 if (image_ihex->buffer) {
955                         free(image_ihex->buffer);
956                         image_ihex->buffer = NULL;
957                 }
958         } else if (image->type == IMAGE_ELF) {
959                 struct image_elf *image_elf = image->type_private;
960
961                 fileio_close(&image_elf->fileio);
962
963                 if (image_elf->header) {
964                         free(image_elf->header);
965                         image_elf->header = NULL;
966                 }
967
968                 if (image_elf->segments) {
969                         free(image_elf->segments);
970                         image_elf->segments = NULL;
971                 }
972         } else if (image->type == IMAGE_MEMORY) {
973                 struct image_memory *image_memory = image->type_private;
974
975                 if (image_memory->cache) {
976                         free(image_memory->cache);
977                         image_memory->cache = NULL;
978                 }
979         } else if (image->type == IMAGE_SRECORD) {
980                 struct image_mot *image_mot = image->type_private;
981
982                 fileio_close(&image_mot->fileio);
983
984                 if (image_mot->buffer) {
985                         free(image_mot->buffer);
986                         image_mot->buffer = NULL;
987                 }
988         } else if (image->type == IMAGE_BUILDER) {
989                 int i;
990
991                 for (i = 0; i < image->num_sections; i++) {
992                         free(image->sections[i].private);
993                         image->sections[i].private = NULL;
994                 }
995         }
996
997         if (image->type_private) {
998                 free(image->type_private);
999                 image->type_private = NULL;
1000         }
1001
1002         if (image->sections) {
1003                 free(image->sections);
1004                 image->sections = NULL;
1005         }
1006 }
1007
1008 int image_calculate_checksum(uint8_t *buffer, uint32_t nbytes, uint32_t *checksum)
1009 {
1010         uint32_t crc = 0xffffffff;
1011         LOG_DEBUG("Calculating checksum");
1012
1013         static uint32_t crc32_table[256];
1014
1015         static bool first_init;
1016         if (!first_init) {
1017                 /* Initialize the CRC table and the decoding table.  */
1018                 int i, j;
1019                 unsigned int c;
1020                 for (i = 0; i < 256; i++) {
1021                         /* as per gdb */
1022                         for (c = i << 24, j = 8; j > 0; --j)
1023                                 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
1024                         crc32_table[i] = c;
1025                 }
1026
1027                 first_init = true;
1028         }
1029
1030         while (nbytes > 0) {
1031                 int run = nbytes;
1032                 if (run > 32768)
1033                         run = 32768;
1034                 nbytes -= run;
1035                 while (run--) {
1036                         /* as per gdb */
1037                         crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buffer++) & 255];
1038                 }
1039                 keep_alive();
1040         }
1041
1042         LOG_DEBUG("Calculating checksum done");
1043
1044         *checksum = crc;
1045         return ERROR_OK;
1046 }