diff --git a/lpc-fw-crc.rb b/lpc-fw-crc.rb new file mode 100755 index 0000000..f6bf754 --- /dev/null +++ b/lpc-fw-crc.rb @@ -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 +