1#!/usr/bin/env python3
2
3# The MIT License (MIT)
4# Copyright (c) Microsoft Corporation
5
6# All rights reserved.
7
8# Permission is hereby granted, free of charge, to any person obtaining a copy
9# of this software and associated documentation files (the "Software"), to deal
10# in the Software without restriction, including without limitation the rights
11# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12# copies of the Software, and to permit persons to whom the Software is
13# furnished to do so, subject to the following conditions:
14
15# The above copyright notice and this permission notice shall be included in all
16# copies or substantial portions of the Software.
17
18# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24# SOFTWARE.
25
26# taken from https://github.com/microsoft/uf2/blob/master/utils/uf2conv.py
27import sys
28import struct
29import subprocess
30import re
31import os
32import os.path
33import argparse
34
35
36UF2_MAGIC_START0 = 0x0A324655 # "UF2\n"
37UF2_MAGIC_START1 = 0x9E5D5157 # Randomly selected
38UF2_MAGIC_END    = 0x0AB16F30 # Ditto
39
40families = {
41    'SAMD21': 0x68ed2b88,
42    'SAML21': 0x1851780a,
43    'SAMD51': 0x55114460,
44    'NRF52': 0x1b57745f,
45    'STM32F0': 0x647824b6,
46    'STM32F1': 0x5ee21072,
47    'STM32F2': 0x5d1a0a2e,
48    'STM32F3': 0x6b846188,
49    'STM32F4': 0x57755a57,
50    'STM32F7': 0x53b80f00,
51    'STM32G0': 0x300f5633,
52    'STM32G4': 0x4c71240a,
53    'STM32H7': 0x6db66082,
54    'STM32L0': 0x202e3a91,
55    'STM32L1': 0x1e1f432d,
56    'STM32L4': 0x00ff6919,
57    'STM32L5': 0x04240bdf,
58    'STM32WB': 0x70d16653,
59    'STM32WL': 0x21460ff0,
60    'ATMEGA32': 0x16573617,
61    'MIMXRT10XX': 0x4FB2D5BD,
62    'LPC55': 0x2abc77ec,
63    'GD32F350': 0x31D228C6,
64    'ESP32S2': 0xbfdd4eee,
65    'RP2040': 0xe48bff56
66}
67
68INFO_FILE = "/INFO_UF2.TXT"
69
70appstartaddr = 0x2000
71familyid = 0x0
72
73
74def is_uf2(buf):
75    w = struct.unpack("<II", buf[0:8])
76    return w[0] == UF2_MAGIC_START0 and w[1] == UF2_MAGIC_START1
77
78def is_hex(buf):
79    try:
80        w = buf[0:30].decode("utf-8")
81    except UnicodeDecodeError:
82        return False
83    if w[0] == ':' and re.match(b"^[:0-9a-fA-F\r\n]+$", buf):
84        return True
85    return False
86
87def convert_from_uf2(buf):
88    global appstartaddr
89    numblocks = len(buf) // 512
90    curraddr = None
91    outp = []
92    for blockno in range(numblocks):
93        ptr = blockno * 512
94        block = buf[ptr:ptr + 512]
95        hd = struct.unpack(b"<IIIIIIII", block[0:32])
96        if hd[0] != UF2_MAGIC_START0 or hd[1] != UF2_MAGIC_START1:
97            print("Skipping block at " + ptr + "; bad magic")
98            continue
99        if hd[2] & 1:
100            # NO-flash flag set; skip block
101            continue
102        datalen = hd[4]
103        if datalen > 476:
104            assert False, "Invalid UF2 data size at " + ptr
105        newaddr = hd[3]
106        if curraddr == None:
107            appstartaddr = newaddr
108            curraddr = newaddr
109        padding = newaddr - curraddr
110        if padding < 0:
111            assert False, "Block out of order at " + ptr
112        if padding > 10*1024*1024:
113            assert False, "More than 10M of padding needed at " + ptr
114        if padding % 4 != 0:
115            assert False, "Non-word padding size at " + ptr
116        while padding > 0:
117            padding -= 4
118            outp += b"\x00\x00\x00\x00"
119        outp.append(block[32 : 32 + datalen])
120        curraddr = newaddr + datalen
121    return b"".join(outp)
122
123def convert_to_carray(file_content):
124    outp = "const unsigned long bindata_len = %d;\n" % len(file_content)
125    outp += "const unsigned char bindata[] __attribute__((aligned(16))) = {"
126    for i in range(len(file_content)):
127        if i % 16 == 0:
128            outp += "\n"
129        outp += "0x%02x, " % file_content[i]
130    outp += "\n};\n"
131    return bytes(outp, "utf-8")
132
133def convert_to_uf2(file_content):
134    global familyid
135    datapadding = b""
136    while len(datapadding) < 512 - 256 - 32 - 4:
137        datapadding += b"\x00\x00\x00\x00"
138    numblocks = (len(file_content) + 255) // 256
139    outp = []
140    for blockno in range(numblocks):
141        ptr = 256 * blockno
142        chunk = file_content[ptr:ptr + 256]
143        flags = 0x0
144        if familyid:
145            flags |= 0x2000
146        hd = struct.pack(b"<IIIIIIII",
147            UF2_MAGIC_START0, UF2_MAGIC_START1,
148            flags, ptr + appstartaddr, 256, blockno, numblocks, familyid)
149        while len(chunk) < 256:
150            chunk += b"\x00"
151        block = hd + chunk + datapadding + struct.pack(b"<I", UF2_MAGIC_END)
152        assert len(block) == 512
153        outp.append(block)
154    return b"".join(outp)
155
156class Block:
157    def __init__(self, addr):
158        self.addr = addr
159        self.bytes = bytearray(256)
160
161    def encode(self, blockno, numblocks):
162        global familyid
163        flags = 0x0
164        if familyid:
165            flags |= 0x2000
166        hd = struct.pack("<IIIIIIII",
167            UF2_MAGIC_START0, UF2_MAGIC_START1,
168            flags, self.addr, 256, blockno, numblocks, familyid)
169        hd += self.bytes[0:256]
170        while len(hd) < 512 - 4:
171            hd += b"\x00"
172        hd += struct.pack("<I", UF2_MAGIC_END)
173        return hd
174
175def convert_from_hex_to_uf2(buf):
176    global appstartaddr
177    appstartaddr = None
178    upper = 0
179    currblock = None
180    blocks = []
181    for line in buf.split('\n'):
182        if line[0] != ":":
183            continue
184        i = 1
185        rec = []
186        while i < len(line) - 1:
187            rec.append(int(line[i:i+2], 16))
188            i += 2
189        tp = rec[3]
190        if tp == 4:
191            upper = ((rec[4] << 8) | rec[5]) << 16
192        elif tp == 2:
193            upper = ((rec[4] << 8) | rec[5]) << 4
194            assert (upper & 0xffff) == 0
195        elif tp == 1:
196            break
197        elif tp == 0:
198            addr = upper | (rec[1] << 8) | rec[2]
199            if appstartaddr == None:
200                appstartaddr = addr
201            i = 4
202            while i < len(rec) - 1:
203                if not currblock or currblock.addr & ~0xff != addr & ~0xff:
204                    currblock = Block(addr & ~0xff)
205                    blocks.append(currblock)
206                currblock.bytes[addr & 0xff] = rec[i]
207                addr += 1
208                i += 1
209    numblocks = len(blocks)
210    resfile = b""
211    for i in range(0, numblocks):
212        resfile += blocks[i].encode(i, numblocks)
213    return resfile
214
215def to_str(b):
216    return b.decode("utf-8")
217
218def get_drives():
219    drives = []
220    if sys.platform == "win32":
221        r = subprocess.check_output(["wmic", "PATH", "Win32_LogicalDisk",
222                                     "get", "DeviceID,", "VolumeName,",
223                                     "FileSystem,", "DriveType"])
224        for line in to_str(r).split('\n'):
225            words = re.split('\s+', line)
226            if len(words) >= 3 and words[1] == "2" and words[2] == "FAT":
227                drives.append(words[0])
228    else:
229        rootpath = "/media"
230        if sys.platform == "darwin":
231            rootpath = "/Volumes"
232        elif sys.platform == "linux":
233            tmp = rootpath + "/" + os.environ["USER"]
234            if os.path.isdir(tmp):
235                rootpath = tmp
236        for d in os.listdir(rootpath):
237            drives.append(os.path.join(rootpath, d))
238
239
240    def has_info(d):
241        try:
242            return os.path.isfile(d + INFO_FILE)
243        except:
244            return False
245
246    return list(filter(has_info, drives))
247
248
249def board_id(path):
250    with open(path + INFO_FILE, mode='r') as file:
251        file_content = file.read()
252    return re.search("Board-ID: ([^\r\n]*)", file_content).group(1)
253
254
255def list_drives():
256    for d in get_drives():
257        print(d, board_id(d))
258
259
260def write_file(name, buf):
261    with open(name, "wb") as f:
262        f.write(buf)
263    print("Wrote %d bytes to %s" % (len(buf), name))
264
265
266def main():
267    global appstartaddr, familyid
268    def error(msg):
269        print(msg)
270        sys.exit(1)
271    parser = argparse.ArgumentParser(description='Convert to UF2 or flash directly.')
272    parser.add_argument('input', metavar='INPUT', type=str, nargs='?',
273                        help='input file (HEX, BIN or UF2)')
274    parser.add_argument('-b' , '--base', dest='base', type=str,
275                        default="0x2000",
276                        help='set base address of application for BIN format (default: 0x2000)')
277    parser.add_argument('-o' , '--output', metavar="FILE", dest='output', type=str,
278                        help='write output to named file; defaults to "flash.uf2" or "flash.bin" where sensible')
279    parser.add_argument('-d' , '--device', dest="device_path",
280                        help='select a device path to flash')
281    parser.add_argument('-l' , '--list', action='store_true',
282                        help='list connected devices')
283    parser.add_argument('-c' , '--convert', action='store_true',
284                        help='do not flash, just convert')
285    parser.add_argument('-D' , '--deploy', action='store_true',
286                        help='just flash, do not convert')
287    parser.add_argument('-f' , '--family', dest='family', type=str,
288                        default="0x0",
289                        help='specify familyID - number or name (default: 0x0)')
290    parser.add_argument('-C' , '--carray', action='store_true',
291                        help='convert binary file to a C array, not UF2')
292    args = parser.parse_args()
293    appstartaddr = int(args.base, 0)
294
295    if args.family.upper() in families:
296        familyid = families[args.family.upper()]
297    else:
298        try:
299            familyid = int(args.family, 0)
300        except ValueError:
301            error("Family ID needs to be a number or one of: " + ", ".join(families.keys()))
302
303    if args.list:
304        list_drives()
305    else:
306        if not args.input:
307            error("Need input file")
308        with open(args.input, mode='rb') as f:
309            inpbuf = f.read()
310        from_uf2 = is_uf2(inpbuf)
311        ext = "uf2"
312        if args.deploy:
313            outbuf = inpbuf
314        elif from_uf2:
315            outbuf = convert_from_uf2(inpbuf)
316            ext = "bin"
317        elif is_hex(inpbuf):
318            outbuf = convert_from_hex_to_uf2(inpbuf.decode("utf-8"))
319        elif args.carray:
320            outbuf = convert_to_carray(inpbuf)
321            ext = "h"
322        else:
323            outbuf = convert_to_uf2(inpbuf)
324        print("Converting to %s, output size: %d, start address: 0x%x" %
325              (ext, len(outbuf), appstartaddr))
326        if args.convert or ext != "uf2":
327            drives = []
328            if args.output == None:
329                args.output = "flash." + ext
330        else:
331            drives = get_drives()
332
333        if args.output:
334            write_file(args.output, outbuf)
335        else:
336            if len(drives) == 0:
337                error("No drive to deploy.")
338        for d in drives:
339            print("Flashing %s (%s)" % (d, board_id(d)))
340            write_file(d + "/NEW.UF2", outbuf)
341
342
343if __name__ == "__main__":
344    main()
345