Initial import
[experiments/ACPI.git] / acpi_table_checksum.py
1 #!/usr/bin/env python
2 #
3 # acpi_table_checksum - verify and calculate the checksum of ACPI tables
4 #
5 # Copyright (C) 2015  Antonio Ospite <ao2@ao2.it>
6 #
7 # This program is free software. It comes without any warranty, to
8 # the extent permitted by applicable law. You can redistribute it
9 # and/or modify it under the terms of the Do What The Fuck You Want
10 # To Public License, Version 2, as published by Sam Hocevar. See
11 # http://sam.zoy.org/wtfpl/COPYING for more details.
12
13 import sys
14
15 CHECKSUM_OFFSET = 9
16
17
18 # Two's complement byte checksum:
19 def acpi_table_checksum(buf, length):
20     checksum = 0
21
22     for i in range(0, length):
23         checksum = (checksum + buf[i]) & 0xff
24
25     return (0x100 - checksum) & 0xff
26
27
28 def calc_new_checksum(data):
29     data_copy = data[:]
30     data_copy[CHECKSUM_OFFSET] = 0
31     return acpi_table_checksum(data_copy, len(data_copy))
32
33
34 def verify_checksum(data):
35     return (acpi_table_checksum(data, len(data)) == 0)
36
37
38 def usage():
39     print "%s <ACPI_TABLE>" % sys.argv[0]
40
41
42 if __name__ == "__main__":
43     if len(sys.argv) != 2:
44         usage()
45         sys.exit(1)
46
47     table = sys.argv[1]
48
49     with open(table, 'rb') as f:
50         data = bytearray(f.read())
51
52         checksum_is_valid = verify_checksum(data)
53
54         if checksum_is_valid:
55             print "Checksum valid (0x%02x)." % data[CHECKSUM_OFFSET]
56         else:
57             print "Checksum not valid, calculating a new one..."
58             new_checksum = calc_new_checksum(data)
59             print "New checksum 0x%02x" % new_checksum
60             data[CHECKSUM_OFFSET] = new_checksum
61             print "Checksum vaiid %d" % verify_checksum(data)