blob: 32479350c5fe61a758dbbf39e172f09b2e0db7c5 [file] [log] [blame]
Austin Schuh41baf202022-01-01 14:33:40 -08001#!/usr/bin/python
2
3# Written by Antonio Galea - 2010/11/18
4# Updated for DFU 1.1 by Sean Cross - 2020/03/31
5# Distributed under Gnu LGPL 3.0
6# see http://www.gnu.org/licenses/lgpl-3.0.txt
7
8import sys,struct,zlib,os
9from optparse import OptionParser
10
11DEFAULT_DEVICE="0x1209:0x5bf0"
12
13def named(tuple,names):
14 return dict(zip(names.split(),tuple))
15def consume(fmt,data,names):
16 n = struct.calcsize(fmt)
17 return named(struct.unpack(fmt,data[:n]),names),data[n:]
18def cstring(string):
19 return string.split('\0',1)[0]
20def compute_crc(data):
21 return 0xFFFFFFFF & -zlib.crc32(data) -1
22
23def parse(file,dump_images=False):
24 print ('File: "%s"' % file)
25 data = open(file,'rb').read()
26 crc = compute_crc(data[:-4])
27 data = data[len(data)-16:]
28 suffix = named(struct.unpack('<4H3sBI',data[:16]),'device product vendor dfu ufd len crc')
29 print ('usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x' % suffix)
30 if crc != suffix['crc']:
31 print ("CRC ERROR: computed crc32 is 0x%08x" % crc)
32 data = data[16:]
33 if data:
34 print ("PARSE ERROR")
35
36def build(file,data,device=DEFAULT_DEVICE):
37 # Parse the VID and PID from the `device` argument
38 v,d=map(lambda x: int(x,0) & 0xFFFF, device.split(':',1))
39
40 # Generate the DFU suffix, consisting of these fields:
41 # Field name | Length | Description
42 # ================+=========+================================
43 # bcdDevice | 2 | The release number of this firmware (0xffff - don't care)
44 # idProduct | 2 | PID of this device
45 # idVendor | 2 | VID of this device
46 # bcdDFU | 2 | Version of this DFU spec (0x01 0x00)
47 # ucDfuSignature | 3 | The characters 'DFU', printed in reverse order
48 # bLength | 1 | The length of this suffix (16 bytes)
49 # dwCRC | 4 | A CRC32 of the data, including this suffix
50 data += struct.pack('<4H3sB',0xffff,d,v,0x0100,b'UFD',16)
51 crc = compute_crc(data)
52 # Append the CRC32 of the entire block
53 data += struct.pack('<I',crc)
54 open(file,'wb').write(data)
55
56if __name__=="__main__":
57 usage = """
58%prog [-d|--dump] infile.dfu
59%prog {-b|--build} file.bin [{-D|--device}=vendor:device] outfile.dfu"""
60 parser = OptionParser(usage=usage)
61 parser.add_option("-b", "--build", action="store", dest="binfile",
62 help="build a DFU file from given BINFILE", metavar="BINFILE")
63 parser.add_option("-D", "--device", action="store", dest="device",
64 help="build for DEVICE, defaults to %s" % DEFAULT_DEVICE, metavar="DEVICE")
65 parser.add_option("-d", "--dump", action="store_true", dest="dump_images",
66 default=False, help="dump contained images to current directory")
67 (options, args) = parser.parse_args()
68
69 if options.binfile and len(args)==1:
70 binfile = options.binfile
71 if not os.path.isfile(binfile):
72 print ("Unreadable file '%s'." % binfile)
73 sys.exit(1)
74 target = open(binfile,'rb').read()
75 outfile = args[0]
76 device = DEFAULT_DEVICE
77 # If a device is specified, parse the pair into a VID:PID pair
78 # in order to validate them.
79 if options.device:
80 device=options.device
81 try:
82 v,d=map(lambda x: int(x,0) & 0xFFFF, device.split(':',1))
83 except:
84 print ("Invalid device '%s'." % device)
85 sys.exit(1)
86 build(outfile,target,device)
87 elif len(args)==1:
88 infile = args[0]
89 if not os.path.isfile(infile):
90 print ("Unreadable file '%s'." % infile)
91 sys.exit(1)
92 parse(infile, dump_images=options.dump_images)
93 else:
94 parser.print_help()
95 sys.exit(1)