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