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