mkflash.c 1.9 KB
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <getopt.h>

#include "ecc256.h"

/*
 * construct a flash image from a binary file
 */

#define PAGE_SIZE	512
#define OOB_SIZE	16
#define ECC0_OFF	525
#define ECC1_OFF	520

#define PAGES_PER_BLK   32

int
main(int argc, char* argv[]) {
    FILE* in = stdin, * out = stdout;
    char c;
    unsigned char buf[PAGE_SIZE+OOB_SIZE];
    int ascii = 0, checksum = 0, pagecnt;

    opterr = 0;
    while((c = getopt(argc, argv, "aco:")) != (char)-1) {
        switch(c) {
	case 'a':
	    ascii = 1; break;
	case 'c':
	    checksum = 1; break;
	case 'o':
	    if ((out = fopen(optarg, "w")) == NULL) {
		perror(optarg);
		return 1;
	    }
	    break;
	default:
	    fprintf(stderr, "Usage: mkflash file\n");
	    return 1;
	}
    }

    //if (optind >= argc) in = stdin
    if (optind < argc && (in = fopen(argv[optind], "r")) == NULL) {
	perror(argv[optind]);
	return 1;
    }

    memset(buf, 0xff, sizeof buf);
    pagecnt = 0;
    while(fread(buf, sizeof buf[0], PAGE_SIZE, in) > 0) {
	ecc256_calculate(buf, buf+ECC0_OFF);
	ecc256_calculate(buf+256, buf+ECC1_OFF);
	if (ascii) {
	    int i;
	    for(i = 0; i < PAGE_SIZE+OOB_SIZE; i++)
		fprintf(out, "%02x%c", buf[i], i % 16 == 15 ? '\n' : ' ');
	} else {
	    if (fwrite(buf, sizeof buf, 1, out) < 0) {
		perror("fwrite");
		return 1;
	    }
	}
	if (checksum) {
	    int i;
	    unsigned short sum = 0;
	    for(i = 0; i < PAGE_SIZE+OOB_SIZE; i++)
		sum += buf[i];
	    fprintf(stderr, "%04x\n", sum);
	}
        if((pagecnt)==0)
            pagecnt=PAGES_PER_BLK-1;
        else
            pagecnt--;

	memset(buf, 0xff, sizeof buf);
    }
    while(pagecnt--){
        if (ascii) {
	    int i;
	    for(i = 0; i < PAGE_SIZE+OOB_SIZE; i++)
		fprintf(out, "%02x%c", buf[i], i % 16 == 15 ? '\n' : ' ');
	} else {
	    if (fwrite(buf, sizeof buf, 1, out) < 0) {
		perror("fwrite");
		return -1;
	    }
	}
    }
    return 0;
}