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