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