views:

170

answers:

1

Q. I have a hex code running on a machine. How do I calculate the checksum of the entire code at runtime?

+5  A: 

You need to have read access to the entire code segment. This probably involves getting symbols from the linker that reference the first and last addresses of the code. You can cast those addresses into a suitably sized data pointer, and run any common CRC or checksum algorithm you want over the code segment.

To verify the CRC, you need to know its authoritative value. This can be done after linking by computing the CRC and patching it into the initializer for a suitable variable.

In embedded systems where I've used a similar technique as an integrity check before replacing the firmware in a field upgrade, I usually arrange the memory map of the firmware's image to begin with a read-only data structure. It is easy to write a utility to compute the CRC of the image and fix up the structure. The embedded system's boot loader then can verify that CRC during boot to determine if valid firmware is present, and fall back to an update utility if not. Of course, the update utility uses that same CRC to validate a new image before flashing.

Edit: Some references on CRC, in case its helpful:

RBerteig