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