se505-buildsystem/tools/gen_image.c

125 lines
2.5 KiB
C

/*
* creates LOAD/Flash images for Siemens SE505
*
* (c) 01/2005 Olaf Rempel <razzor at kopf minus tisch dot de>
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include "trxhdr.h"
extern u_int32_t chksum_crc32(unsigned char *block, unsigned int length);
extern void chksum_crc32gentab();
int main(int argc, char *argv[]) {
struct trx_header trx;
int i, cnt;
FILE *fp;
char *buf;
if (argc <= 1) {
printf("USAGE: gen_image file.trx file.trx ... > outfile\n");
exit(-1);
}
// this is.. ugly, but works :)
if ((buf = malloc(FILE_MAX_LEN)) == NULL) {
perror("malloc");
exit(-1);
}
// init main header
memset(&trx, 0, sizeof(struct trx_header));
trx.magic = FILE_MAGIC;
// copy header
memcpy(buf, &trx, sizeof(struct trx_header));
cnt = sizeof(struct trx_header);
for (i = 1; i < argc; i++) {
// open file
if ((fp = fopen(argv[i], "r")) < 0) {
perror(argv[i]);
free(buf);
exit(-1);
}
// read header
if ((cnt = fread(&trx, 1, sizeof(struct trx_header), fp)) < 0) {
perror(argv[i]);
fclose(fp);
free(buf);
exit(-1);
} else if (cnt < sizeof(struct trx_header)) {
fprintf(stderr, "Truncated file: %s\n", argv[i]);
fclose(fp);
free(buf);
exit(-1);
} else if (trx.magic == TRX_MAGIC) {
if (trx.len > TRX_MAX_LEN || trx.len < sizeof(struct trx_header)) {
fprintf(stderr, "Bad TRX Header: %s\n", argv[i]);
fclose(fp);
free(buf);
exit(-1);
}
} else if (trx.magic == PMON_MAGIC) {
if (trx.len > PMON_MAX_LEN || trx.len < sizeof(struct trx_header)) {
fprintf(stderr, "Bad PMON Header: %s\n", argv[i]);
fclose(fp);
free(buf);
exit(-1);
}
} else if (trx.magic == NVAR_MAGIC) {
if (trx.len > NVRAM_MAX_LEN || trx.len < sizeof(struct trx_header)) {
fprintf(stderr, "Bad NVRAM Header: %s\n", argv[i]);
fclose(fp);
free(buf);
exit(-1);
}
} else {
fprintf(stderr, "Unknown Header Type: %s\n", argv[i]);
fclose(fp);
free(buf);
exit(-1);
}
// copy header
memcpy(buf + cnt, &trx, sizeof(struct trx_header));
cnt += sizeof(struct trx_header);
// copy file to buffer
while (!feof(fp))
cnt += fread(buf + cnt, 1, 65536, fp);
// close file
fclose(fp);
}
chksum_crc32gentab();
// copy main header again
memcpy(&trx, buf, sizeof(struct trx_header));
trx.len = cnt;
// create chksum without first 3 fields
trx.crc32 = chksum_crc32(buf +12, cnt);
memcpy(buf, &trx, sizeof(struct trx_header));
// flush to output
write(1, buf, cnt);
free(buf);
return 0;
}