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