add script to verify and write NXP LCP13xx firmware checksums

This commit is contained in:
King Kévin 2015-08-24 16:18:51 +02:00
parent 0c447df7b0
commit c0ee3dc8b9
1 changed files with 72 additions and 0 deletions

72
lpc-fw-crc.rb Executable file
View File

@ -0,0 +1,72 @@
#!/usr/bin/env ruby
# encoding: utf-8
# ruby: 1.9.3
=begin
this script verifies and writes the checksum for NXP LPC13xx firmwares.
for more information about how it is calculated refer to document UM10375 section 21.7 Criterion for Valid User Code
=end
def help
puts "usage: #{__FILE__} [operation] file"
puts "operations:"
puts "\t-v,--verify\tverify checksum (default)"
puts "\t-w,--write\twrite checksum"
puts "file: LPC13xx firmware"
end
puts "LPC13xx firmware checksum verifier and writer"
# should the checksum be written
write = false
file = nil
if ARGV.size==1 then
file = ARGV[0]
elsif ARGV.size==2 then
case ARGV[0]
when "-h","--help"
help
exit 0
when "-v","--verify"
# this is done per default
when "-w","--write"
write = true
else
help
exit 0
end
file = ARGV[1]
else
help
exit 0
end
raise "#{file} is not a file" unless File.file? file
raise "#{file} is too short" if File.size(file)<4*8
firmware = File.open(file,"r+") # open file
header = firmware.read(4*7).unpack("l*") # read the 7 first words (of 32 bits) to checksum
checksum = firmware.read(4).unpack("l*")[0]&0xffffffff # read the current checksum (8th word)
# calculate the correct checksum
sum = 0
header.each do |word|
sum += word
sum &= 0xffffffff
end
correct = ((~sum)+1)&0xffffffff # the 2's complement
puts "current checksum: 0x%08x" % checksum
puts "correct checksum: 0x%08x" % correct
if checksum==correct then
puts "checksum matches"
else
puts "checksum does not match"
if write then
firmware.seek(4*7,:SET)
firmware.write([correct].pack("l"))
puts "checksum written"
end
end
firmware.close