reorder.c 1.65 KB
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define OCTBYTE_SIZE 512

int convert_8_to_9(unsigned char dst[9], unsigned char src[8])
{
	int i, v, bits;

	for (i=v=bits=0; i<8; i++) {
		v <<= 9;    /* Add 0 and next bytes */
		bits++;
		v |= src[i];
		
		dst[i] = (v >> bits) & 0xff;
	}
	dst[8] = src[7];

	return 0;
}

int reorder_file(char *in_file, char *out_file, int start)
{
	FILE *fIn, *fOut;
	unsigned char *memory, out[9], line[256];
	unsigned long d1, d2, addr, i, j;

	memory = (unsigned char *) malloc(8 * OCTBYTE_SIZE);
	if (memory == NULL) {
		fprintf(stderr, "Cannot alloc memory for reorder %d\n", start);
		return -1;
    }

	fIn = fopen(in_file, "rb");
	fOut = fopen(out_file, "wb");
    if (fIn == NULL ||  fOut == NULL) {
		fprintf(stderr, "Cannot open file %x %x %d", fIn, fOut, start);
		free(memory);
		if (fIn) fclose(fIn);
		if (fOut) fclose(fOut);
		return -2;
	}

	memset(memory, 0, 8 * OCTBYTE_SIZE);
	while (fgets(line, 256, fIn)) {
 		if (line[0] != '@') continue;
		
		sscanf(line, "@%x %x_%x", &addr, &d1, &d2);
		if (addr < OCTBYTE_SIZE) {
			addr <<= 3;   /* byte position */
			for (i=0; i<4; i++) {
				memory[addr+i] = (d2 >> (i<<3)) & 0xff;
				memory[addr+i+4] = (d1 >> (i<<3)) & 0xff;
			}
		}
	}

	for (i=0; i<OCTBYTE_SIZE; i++) {
		convert_8_to_9(out, memory+(i<<3));
		fprintf(fOut, "@%8.8x ", start+i);
		for (j=0; j<9; j++) fprintf(fOut, "%2.2x", out[j]);
		fprintf(fOut, "\n");
	}

	fclose(fIn);
	fclose(fOut);
	free(memory);
	return 0;
}

int main()
{
	int ret1, ret2;

	ret1 = reorder_file("rdram.DMEM", "dmem_reordered.data", 0);
	ret2 = reorder_file("rdram.IMEM", "imem_reordered.data", 512);

	return (ret1<<16) | ret2; 
}