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