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