Last active
July 29, 2020 14:04
-
-
Save flyinprogrammer/8de3b6e795ae2d7e8ed7a8ea15e5eded to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
typedef uint32_t DWORD; | |
typedef uint16_t WORD; | |
int main(int argc, char *argv[]) { | |
char *filename = "firmware.bin"; | |
FILE *input_file; | |
if (argc > 1) | |
filename = argv[1]; | |
fprintf(stderr, "Opening file %s\n", filename); | |
input_file = fopen(filename, "r"); | |
DWORD dLength, dCheckSum, dExpectedCheckSum, dAddress, i, dImageBuf[512*1024]; | |
WORD wSignature; | |
fread(&wSignature,1,2,input_file); // read signature bytes | |
if (wSignature != 0x5943) // check ‘CY’ signature byte | |
{ | |
printf("Invalid image"); | |
return 1; | |
} | |
fread(&i, 2, 1, input_file); // skip 2 dummy bytes | |
dCheckSum = 0; | |
while (1) | |
{ | |
fread(&dLength,4,1,input_file); // read dLength | |
fread(&dAddress,4,1,input_file); // read dAddress | |
if (dLength==0) break; // done | |
// read sections | |
fread(dImageBuf, 4, dLength, input_file); | |
for (i=0; i<dLength; i++) dCheckSum += dImageBuf[i]; | |
} | |
printf("checksum: %#x\n", dCheckSum); | |
// read pre-computed checksum data | |
fread(&dExpectedCheckSum, 4, 1, input_file); | |
printf("expected checksum: %#x\n", dExpectedCheckSum); | |
if (dCheckSum != dExpectedCheckSum) | |
{ | |
printf("Fail to boot due to checksum error (calculated %#x != file %#x)\n", dCheckSum, dExpectedCheckSum); | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
yields:
https://stackoverflow.com/questions/35844586/can-i-assume-the-size-of-long-int-is-always-4-bytes/35844670
Lols, so don't I feel silly now. Thanks for your help @miek!