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