Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012 #include <stdio.h>
00013 #include <ctype.h>
00014 #include <malloc.h>
00015 #include <stdlib.h>
00016 #include <string.h>
00017 #include "hexfile.h"
00018
00019 static int read_hex_line(char *line, unsigned char *buf, unsigned bufSize, unsigned *lowAddr, unsigned *highAddr)
00020 {
00021 unsigned long addr;
00022 unsigned nbytes, tmp, csum, i;
00023
00024 while (isspace(*line))
00025 line++;
00026 if (sscanf(line, ":%02X%04lX%02X", &nbytes, &addr, &tmp) != 3)
00027 return ERR_FMT;
00028 line = &line[9];
00029 csum = (nbytes & 0xff) + (addr & 0xff) + ((addr >> 8) & 0xff) + (tmp & 0xff);
00030 switch(tmp)
00031 {
00032 case 0:
00033 for (i=0;i<nbytes;i++)
00034 {
00035 sscanf(line, "%02X", &tmp);
00036 if (addr >= bufSize)
00037 {
00038 return ERR_ADDR;
00039 }
00040 if (addr > *highAddr)
00041 *highAddr = addr;
00042 if (addr < *lowAddr)
00043 *lowAddr = addr;
00044 buf[addr] = (unsigned char)tmp;
00045 csum += tmp;
00046 line = &line[2];
00047 addr++;
00048 }
00049 break;
00050
00051 case 2:
00052 return ERR_FMT;
00053
00054 case 3:
00055 for (i=0;i<nbytes;i++)
00056 {
00057 sscanf(line, "%02X", &tmp);
00058 csum += tmp;
00059 line = &line[2];
00060 }
00061 break;
00062
00063 case 1:
00064 default:
00065 break;
00066 }
00067 sscanf(line, "%02X", &tmp);
00068 csum = (~csum+1) & 0xff;
00069 if (csum != tmp)
00070 return ERR_CRC;
00071 return NO_ERR;
00072 }
00073
00074 int read_hex_file(FILE *fp, int crc, unsigned char *buf, unsigned buf_size, unsigned *low_addr, unsigned *high_addr)
00075 {
00076 int res, lcount, err;
00077 char line[1000];
00078 lcount = 0;
00079 err = 0;
00080 while (!feof(fp) && !ferror(fp))
00081 {
00082 fgets(line, 1000, fp);
00083 lcount++;
00084 if ((res = read_hex_line(line, buf, buf_size, low_addr, high_addr)) != NO_ERR)
00085 {
00086 switch(res)
00087 {
00088 case ERR_CRC:
00089 if (crc == 1)
00090 {
00091 fprintf(stderr, "ERROR: Checksum error on line %d\n", lcount);
00092 err = res;;
00093 }
00094 break;
00095
00096 case ERR_ADDR:
00097 fprintf(stderr, "ERROR: Hex file contents does not fit into flash\n");
00098 return res;
00099
00100 case ERR_FMT:
00101 fprintf(stderr, "ERROR: Invalid Intel hex format on line %d\n", lcount);
00102 return res;
00103 }
00104 }
00105 }
00106 return err;
00107 }