brcm80211fwconv: Add support for merging data back
[b43-tools.git] / disassembler / brcm80211fwconv
1 #!/usr/bin/env python
2 """
3 #   Copyright (C) 2010  Michael Buesch <mb@bu3sch.de>
4 #
5 #   This program is free software; you can redistribute it and/or modify
6 #   it under the terms of the GNU General Public License version 2
7 #   as published by the Free Software Foundation.
8 #
9 #   This program is distributed in the hope that it will be useful,
10 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 #   GNU General Public License for more details.
13 """
14
15 import sys
16 import getopt
17
18 def indexToName(index):
19         D11UCODE_NAMETAG_START          = 0
20         D11LCN0BSINITVALS24             = 1
21         D11LCN0INITVALS24               = 2
22         D11LCN1BSINITVALS24             = 3
23         D11LCN1INITVALS24               = 4
24         D11LCN2BSINITVALS24             = 5
25         D11LCN2INITVALS24               = 6
26         D11N0ABSINITVALS16              = 7
27         D11N0BSINITVALS16               = 8
28         D11N0INITVALS16                 = 9
29         D11UCODE_OVERSIGHT16_MIMO       = 10
30         D11UCODE_OVERSIGHT16_MIMOSZ     = 11
31         D11UCODE_OVERSIGHT24_LCN        = 12
32         D11UCODE_OVERSIGHT24_LCNSZ      = 13
33         D11UCODE_OVERSIGHT_BOMMAJOR     = 14
34         D11UCODE_OVERSIGHT_BOMMINOR     = 15
35
36         namemap = {
37                 D11UCODE_NAMETAG_START          : "start",
38                 D11LCN0BSINITVALS24             : "LCN0 bs initvals 24",
39                 D11LCN0INITVALS24               : "LCN0 initvals 24",
40                 D11LCN1BSINITVALS24             : "LCN1 bs initvals 24",
41                 D11LCN1INITVALS24               : "LCN1 initvals 24",
42                 D11LCN2BSINITVALS24             : "LCN2 bs initvals 24",
43                 D11LCN2INITVALS24               : "LCN2 initvals 24",
44                 D11N0ABSINITVALS16              : "N0A bs initvals 16",
45                 D11N0BSINITVALS16               : "N0 bs initvals 16",
46                 D11N0INITVALS16                 : "N0 initvals 16",
47                 D11UCODE_OVERSIGHT16_MIMO       : "microcode 16 MIMO",
48                 D11UCODE_OVERSIGHT16_MIMOSZ     : "microcode 16 MIMO size",
49                 D11UCODE_OVERSIGHT24_LCN        : "microcode 24 LCN",
50                 D11UCODE_OVERSIGHT24_LCNSZ      : "microcode 24 LCN size",
51                 D11UCODE_OVERSIGHT_BOMMAJOR     : "bom major",
52                 D11UCODE_OVERSIGHT_BOMMINOR     : "bom minor",
53         }
54         try:
55                 return namemap[index]
56         except KeyError:
57                 return "Unknown"
58
59 def parseHeader(hdr_data):
60         sections = []
61         for i in range(0, len(hdr_data), 3 * 4):
62                 offset = ord(hdr_data[i + 0]) | (ord(hdr_data[i + 1]) << 8) |\
63                         (ord(hdr_data[i + 2]) << 16) | (ord(hdr_data[i + 3]) << 24)
64                 length = ord(hdr_data[i + 4]) | (ord(hdr_data[i + 5]) << 8) |\
65                         (ord(hdr_data[i + 6]) << 16) | (ord(hdr_data[i + 7]) << 24)
66                 index = ord(hdr_data[i + 8]) | (ord(hdr_data[i + 9]) << 8) |\
67                         (ord(hdr_data[i + 10]) << 16) | (ord(hdr_data[i + 11]) << 24)
68
69                 sections.append( (offset, length, index) )
70         sections.sort(key = lambda x: x[2]) # Sort by index
71         return sections
72
73 def generateHeaderData(sections):
74         data = []
75         for section in sections:
76                 (offset, length, index) = section
77                 data.append(chr(offset & 0xFF))
78                 data.append(chr((offset >> 8) & 0xFF))
79                 data.append(chr((offset >> 16) & 0xFF))
80                 data.append(chr((offset >> 24) & 0xFF))
81                 data.append(chr(length & 0xFF))
82                 data.append(chr((length >> 8) & 0xFF))
83                 data.append(chr((length >> 16) & 0xFF))
84                 data.append(chr((length >> 24) & 0xFF))
85                 data.append(chr(index & 0xFF))
86                 data.append(chr((index >> 8) & 0xFF))
87                 data.append(chr((index >> 16) & 0xFF))
88                 data.append(chr((index >> 24) & 0xFF))
89         return "".join(data)
90
91 def getSectionByIndex(sections, searchIndex):
92         for section in sections:
93                 (offset, length, index) = section
94                 if searchIndex == index:
95                         return section
96         return None
97
98 def parseHeaderFile(hdr_filepath):
99         try:
100                 hdr_data = file(hdr_filepath, "rb").read()
101         except (IOError), e:
102                 print "Failed to read header file: %s" % e.strerror
103                 return None
104         if len(hdr_data) % (3 * 4) != 0:
105                 print "Invalid header file format"
106                 return None
107         return parseHeader(hdr_data)
108
109 def dumpInfo(hdr_filepath):
110         sections = parseHeaderFile(hdr_filepath)
111         if not sections:
112                 return 1
113         for section in sections:
114                 (offset, length, index) = section
115                 print "Index %2d   %24s    ==>  offset:0x%08X  length:0x%08X" %\
116                         (index, indexToName(index), offset, length)
117         return 0
118
119 def extractSection(hdr_filepath, bin_filepath, extractIndex, outfilePath):
120         sections = parseHeaderFile(hdr_filepath)
121         if not sections:
122                 return 1
123         section = getSectionByIndex(sections, extractIndex)
124         if not section:
125                 print "Did not find a section with index %d" % extractIndex
126                 return 1
127         (offset, length, index) = section
128         try:
129                 bin_data = file(bin_filepath, "rb").read()
130         except (IOError), e:
131                 print "Failed to read bin file: %s" % e.strerror
132                 return 1
133         try:
134                 outfile = file(outfilePath, "wb")
135                 outfile.write(bin_data[offset : offset + length])
136         except IndexError:
137                 print "Binfile index error."
138                 return 1
139         except (IOError), e:
140                 print "Failed to write output file: %s" % e.strerror
141                 return 1
142         return 0
143
144 def mergeSection(hdr_filepath, bin_filepath, mergeIndex, mergefilePath):
145         sections = parseHeaderFile(hdr_filepath)
146         if not sections:
147                 return 1
148         try:
149                 bin_data = file(bin_filepath, "rb").read()
150         except (IOError), e:
151                 print "Failed to read bin file: %s" % e.strerror
152                 return 1
153         try:
154                 merge_data = file(mergefilePath, "rb").read()
155         except (IOError), e:
156                 print "Failed to open merge output file: %s" % e.strerror
157                 return 1
158         newBin = []
159         newSections = []
160         newOffset = 0
161         for section in sections:
162                 (offset, length, index) = section
163                 if index == mergeIndex:
164                         # We overwrite this section
165                         newBin.append(merge_data)
166                         newSections.append( (newOffset, len(merge_data), index) )
167                         newOffset += len(merge_data)
168                 else:
169                         try:
170                                 newBin.append(bin_data[offset : offset + length])
171                         except IndexError:
172                                 print "Failed to read input data"
173                                 return 1
174                         newSections.append( (newOffset, length, index) )
175                         newOffset += length
176         newBin = "".join(newBin)
177         newHdr = generateHeaderData(newSections)
178         try:
179                 file(bin_filepath, "wb").write(newBin)
180                 file(hdr_filepath, "wb").write(newHdr)
181         except (IOError), e:
182                 print "Failed to write bin or header file: %s" % e.strerror
183                 return 1
184         return 0
185
186 def usage():
187         print "BRCM80211 firmware converter tool"
188         print ""
189         print "Usage: %s [OPTIONS]" % sys.argv[0]
190         print ""
191         print "  -H|--header FILE         Use FILE as header file"
192         print "  -B|--bin FILE            Use FILE as bin file"
193         print ""
194         print "Actions:"
195         print "  -d|--dump                Dump general information"
196         print "  -x|--extract INDEX:FILE  Extract the section with index INDEX to FILE"
197         print "  -m|--merge INDEX:FILE    Merges FILE into the bin file stream at INDEX"
198         print "                           A Merge modifies the files specified in -H and -B"
199         print ""
200         print "  -h|--help                Print this help text"
201
202 def main():
203         opt_header = None
204         opt_bin = None
205         opt_action = None
206         opt_index = None
207         opt_outfile = None
208         opt_mergefile = None
209
210         try:
211                 (opts, args) = getopt.getopt(sys.argv[1:],
212                         "hH:B:dx:m:",
213                         [ "help", "header=", "bin=", "dump", "extract=", "merge=", ])
214         except getopt.GetoptError:
215                 usage()
216                 return 1
217         for (o, v) in opts:
218                 if o in ("-h", "--help"):
219                         usage()
220                         return 0;
221                 if o in ("-H", "--header"):
222                         opt_header = v
223                 if o in ("-B", "--bin"):
224                         opt_bin = v
225                 if o in ("-d", "--dump"):
226                         opt_action = "dump"
227                 if o in ("-x", "--extract"):
228                         opt_action = "extract"
229                         try:
230                                 v = v.split(':')
231                                 opt_index = int(v[0])
232                                 opt_outfile = v[1]
233                         except IndexError, ValueError:
234                                 print "Invalid -x|--extract index number\n"
235                                 usage()
236                                 return 1
237                 if o in ("-m", "--merge"):
238                         opt_action = "merge"
239                         try:
240                                 v = v.split(':')
241                                 opt_index = int(v[0])
242                                 opt_mergefile = v[1]
243                         except IndexError, ValueError:
244                                 print "Invalid -m|--merge index and/or merge file name\n"
245                                 usage()
246                                 return 1
247         if not opt_action:
248                 print "No action specified\n"
249                 usage()
250                 return 1
251         if opt_action == "dump":
252                 if not opt_header:
253                         print "No header file specified\n"
254                         usage()
255                         return 1
256                 return dumpInfo(opt_header)
257         elif opt_action == "extract":
258                 if not opt_header or not opt_bin:
259                         print "No header or bin file specified\n"
260                         usage()
261                         return 1
262                 return extractSection(opt_header, opt_bin, opt_index, opt_outfile)
263         elif opt_action == "merge":
264                 if not opt_header or not opt_bin:
265                         print "No header or bin file specified\n"
266                         usage()
267                         return 1
268                 return mergeSection(opt_header, opt_bin, opt_index, opt_mergefile)
269         return 1
270
271 if __name__ == "__main__":
272         sys.exit(main())