dfu.py 3.5 KB

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