1 import struct 2 import sys 3 4 def readU32(contents, offset): 5 wordBytes = contents[offset:offset + 4] 6 return struct.unpack('>I', wordBytes)[0] 7 8 def readU16(contents, offset): 9 wordBytes = contents[offset:offset + 2] 10 return struct.unpack('>H', wordBytes)[0] 11 12 def checkChecksum(infile): 13 contents = infile.read() 14 if len(contents) % 4: 15 print 'File length is not a multiple of 4' 16 17 sum = 0 18 for offset in range(0, len(contents), 4): 19 sum += readU32(contents, offset) 20 while sum >= 2**32: 21 sum -= 2**32 22 print 'Sum of whole file: %x' % sum 23 24 numTables = readU16(contents, 4) 25 26 for offset in range(12, 12 + numTables * 16, 16): 27 tag = contents[offset:offset + 4] 28 chksum = readU32(contents, offset + 4) 29 toffset = readU32(contents, offset + 8) 30 tlength = readU32(contents, offset + 12) 31 32 sum = 0 33 for offset2 in range(toffset, toffset + tlength, 4): 34 sum += readU32(contents, offset2) 35 while sum >= 2**32: 36 sum -= 2**32 37 if sum != chksum: 38 print 'Bad chksum: %s' % tag 39 40 if __name__ == '__main__': 41 if len(sys.argv) != 2: 42 print 'Usage: %s <ttf filename>' % sys.argv[0] 43 else: 44 checkChecksum(file(sys.argv[1], 'r')) 45