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