Skip to content

Commit d97e347

Browse files
committed
Add a post action that calculates and inserts checksum for binary files
Resolve #25
1 parent 419bab8 commit d97e347

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

builder/main.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,30 @@
1515
import sys
1616
from platform import system
1717
from os import makedirs
18-
from os.path import isdir, join
18+
from os.path import isdir, isfile, join
19+
from struct import unpack, pack
1920

2021
from SCons.Script import (ARGUMENTS, COMMAND_LINE_TARGETS, AlwaysBuild,
2122
Builder, Default, DefaultEnvironment)
2223

24+
25+
def add_image_checksum(source, target, env):
26+
# According to https://community.nxp.com/t5/LPCXpresso-IDE-FAQs/LPC-Image-Checksums/m-p/471035
27+
# NXP LPC parts use a word in the vector table of the processor to store a checksum
28+
# that is examined by the bootloader to identify a valid image.
29+
bin_path = target[0].path
30+
if isfile(bin_path):
31+
# From https://github.com/ARMmbed/mbed-os/blob/master/tools/targets/LPC.py
32+
with open(bin_path, "r+b") as fp:
33+
# Read entries 0 through 6 (Little Endian 32bits words)
34+
vector = [unpack("<I", fp.read(4))[0] for _ in range(7)]
35+
36+
# location 7 (offset 0x1C in the vector table) should contain the 2"s
37+
# complement of the check-sum of table entries 0 through 6
38+
fp.seek(0x1C)
39+
fp.write(pack("<I", (~sum(vector) + 1) & 0xFFFFFFFF))
40+
41+
2342
env = DefaultEnvironment()
2443
env.SConscript("compat.py", exports="env")
2544
platform = env.PioPlatform()
@@ -97,6 +116,8 @@
97116
else:
98117
target_elf = env.BuildProgram()
99118
target_firm = env.ElfToBin(join("$BUILD_DIR", "${PROGNAME}"), target_elf)
119+
env.AddPostAction(target_firm, env.VerboseAction(
120+
add_image_checksum, "Adding checksum to $TARGET"))
100121
env.Depends(target_firm, "checkprogsize")
101122

102123
AlwaysBuild(env.Alias("nobuild", target_firm))

0 commit comments

Comments
 (0)