summaryrefslogtreecommitdiff
path: root/util/spdtool/spdtool.py
blob: be75e665195c2886742cf28f74ebf0c08b1f12d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#!/usr/bin/env python
# spdtool - Tool for partial deblobbing of UEFI firmware images
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
#
# Parse a blob and search for SPD files.
# First it is searched for a possible SPD header.
#
# For each candidate the function verify_match is invoked to check
# additional fields (known bits, reserved bits, CRC, ...)
#
# Dumps the found SPDs into the current folder.
#
# Implemented:
#  DDR4 SPDs
#

import argparse
import crc16
import struct


class Parser(object):
    def __init__(self, blob, verbose=False, ignorecrc=False):
        self.blob = blob
        self.ignorecrc = ignorecrc
        self.verbose = verbose

    @staticmethod
    def get_matches():
        """Return the first byte to look for"""
        raise Exception("Function not implemented")

    def verify_match(self, header, offset):
        """Return true if it looks like a SPD"""
        raise Exception("Function not implemented")

    def get_len(self, header, offset):
        """Return the length of the SPD"""
        raise Exception("Function not implemented")

    def get_part_number(self, offset):
        """Return the part number in SPD"""
        return ""

    def get_manufacturer_id(self, offset):
        """Return the manufacturer ID in SPD"""
        return 0xffff

    def get_mtransfers(self, offset):
        """Return the number of MT/s"""
        return 0

    def get_manufacturer(self, offset):
        """Return manufacturer as string"""
        id = self.get_manufacturer_id(offset)
        if id == 0xffff:
            return "Unknown"
        ids = {
            0x2c80: "Crucial/Micron",
            0x4304: "Ramaxel",
            0x4f01: "Transcend",
            0x9801: "Kingston",
            0x987f: "Hynix",
            0x9e02: "Corsair",
            0xb004: "OCZ",
            0xad80: "Hynix/Hyundai",
            0xb502: "SuperTalent",
            0xcd04: "GSkill",
            0xce80: "Samsung",
            0xfe02: "Elpida",
            0xff2c: "Micron",
        }
        if id in ids:
            return ids[id]
        return "Unknown"

    def blob_as_ord(self, offset):
        """Helper for python2/python3 compatibility"""
        return self.blob[offset] if type(self.blob[offset]) is int \
            else ord(self.blob[offset])

    def search(self, start):
        """Search for SPD at start. Returns -1 on error or offset
           if found.
        """
        for i in self.get_matches():
            for offset in range(start, len(self.blob)):
                if self.blob_as_ord(offset) == i and \
                    self.verify_match(i, offset):
                    return offset, self.get_len(i, offset)
        return -1, 0


class SPD4Parser(Parser):
    @staticmethod
    def get_matches():
        """Return DDR4 possible header candidates"""
        ret = []
        for i in [1, 2, 3, 4]:
            for j in [1, 2]:
                ret.append(i + j * 16)
        return ret

    def verify_match(self, header, offset):
        """Verify DDR4 specific bit fields."""
        # offset 0 is a candidate, no need to validate
        if self.blob_as_ord(offset + 1) == 0xff:
            return False
        if self.blob_as_ord(offset + 2) != 0x0c:
            return False
        if self.blob_as_ord(offset + 5) & 0xc0 > 0:
            return False
        if self.blob_as_ord(offset + 6) & 0xc > 0:
            return False
        if self.blob_as_ord(offset + 7) & 0xc0 > 0:
            return False
        if self.blob_as_ord(offset + 8) != 0:
            return False
        if self.blob_as_ord(offset + 9) & 0xf > 0:
            return False
        if self.verbose:
            print("%x: Looks like DDR4 SPD" % offset)

        crc = crc16.crc16xmodem(self.blob[offset:offset + 0x7d + 1])
        # Vendors ignore the endianness...
        crc_spd1 = self.blob_as_ord(offset + 0x7f)
        crc_spd1 |= (self.blob_as_ord(offset + 0x7e) << 8)
        crc_spd2 = self.blob_as_ord(offset + 0x7e)
        crc_spd2 |= (self.blob_as_ord(offset + 0x7f) << 8)
        if crc != crc_spd1 and crc != crc_spd2:
            if self.verbose:
                print("%x: CRC16 doesn't match" % offset)
            if not self.ignorecrc:
                return False

        return True

    def get_len(self, header, offset):
        """Return the length of the SPD found."""
        if (header >> 4) & 7 == 1:
            return 256
        if (header >> 4) & 7 == 2:
            return 512
        return 0

    def get_part_number(self, offset):
        """Return part number as string"""
        if offset + 0x15c >= len(self.blob):
            return ""
        tmp = self.blob[offset + 0x149:offset + 0x15c + 1]
        return tmp.decode('utf-8').rstrip()

    def get_manufacturer_id(self, offset):
        """Return manufacturer ID"""
        if offset + 0x141 >= len(self.blob):
            return 0xffff
        tmp = self.blob[offset + 0x140:offset + 0x141 + 1]
        return struct.unpack('H', tmp)[0]

    def get_mtransfers(self, offset):
        """Return MT/s as specified by MTB and FTB"""
        if offset + 0x7d >= len(self.blob):
            return 0

        if self.blob_as_ord(offset + 0x11) != 0:
            return 0
        mtb = 8.0
        ftb = 1000.0
        tmp = self.blob[offset + 0x12:offset + 0x12 + 1]
        tckm = struct.unpack('B', tmp)[0]
        tmp = self.blob[offset + 0x7d:offset + 0x7d + 1]
        tckf = struct.unpack('b', tmp)[0]
        return int(2000 / (tckm / mtb + tckf / ftb))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='SPD rom dumper')
    parser.add_argument('--blob', required=True,
                        help='The ROM to search SPDs in.')
    parser.add_argument('--spd4', action='store_true', default=False,
                        help='Search for DDR4 SPDs.')
    parser.add_argument('--hex', action='store_true', default=False,
                        help='Store SPD in hex format otherwise binary.')
    parser.add_argument('-v', '--verbose', help='increase output verbosity',
                        action='store_true')
    parser.add_argument('--ignorecrc', help='Ignore CRC mismatch',
                        action='store_true', default=False)
    args = parser.parse_args()

    blob = open(args.blob, "rb").read()

    if args.spd4:
        p = SPD4Parser(blob, args.verbose, args.ignorecrc)
    else:
        raise Exception("Must specify one of the following arguments:\n--spd4")

    offset = 0
    cnt = 0
    while True:
        offset, length = p.search(offset)
        if length == 0:
            break
        print("Found SPD at 0x%x" % offset)
        print(" '%s', size %d, manufacturer %s (0x%04x) %d MT/s\n" %
              (p.get_part_number(offset), length, p.get_manufacturer(offset),
               p.get_manufacturer_id(offset), p.get_mtransfers(offset)))
        filename = "spd-%d-%s-%s.bin" % (cnt, p.get_part_number(offset),
            p.get_manufacturer(offset))
        filename = filename.replace("/", "_")
        filename = "".join([c for c in filename if c.isalpha() or c.isdigit()
                    or c == '-' or c == '.' or c == '_']).rstrip()
        if not args.hex:
            open(filename, "wb").write(blob[offset:offset + length])
        else:
            filename += ".hex"
            with open(filename, "w") as fn:
                j = 0
                for i in blob[offset:offset + length]:
                    fn.write("%02X" % struct.unpack('B', i)[0])
                    fn.write(" " if j < 15 else "\n")
                    j = (j + 1) % 16
        offset += 1
        cnt += 1