aboutsummaryrefslogtreecommitdiff
path: root/circuitpython/tools/uf2/uf2tool/tool.c
blob: 9ec20a7ef3a750a9f8cc7d24df17f541e16c8433 (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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#ifdef WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <stdbool.h>
#include <pthread.h>
#include "hidapi.h"
#include "uf2hid.h"

#define EP_SIZE 64

typedef struct {
    hid_device *dev;
    uint16_t size;
    uint8_t serial;
    uint16_t seqNo;
    uint16_t pageSize;
    uint32_t flashSize;
    uint32_t msgSize;
    union {
        uint8_t buf[64 * 1024];
        HF2_Response resp;
    };
} HID_Dev;

uint64_t millis() {
    struct timeval tv;
    gettimeofday(&tv, 0);
    return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

void fatal(const char *msg) {
    fprintf(stderr, "Fatal error: %s\n", msg);
    exit(1);
}

void write16(uint8_t *ptr, uint16_t v) {
    ptr[0] = v;
    ptr[1] = v >> 8;
}

void write32(uint8_t *ptr, uint32_t v) {
    ptr[0] = v;
    ptr[1] = v >> 8;
    ptr[2] = v >> 16;
    ptr[3] = v >> 24;
}

uint32_t read32(uint8_t *ptr) { return ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24); }

uint32_t read16(uint8_t *ptr) { return ptr[0] | (ptr[1] << 8); }

int recv_hid(HID_Dev *pkt, int timeout) {
    uint8_t buf0[EP_SIZE + 1];
    uint8_t *buf;

    pkt->size = 0;
    memset(pkt->buf, 0, sizeof(pkt->buf));

    for (;;) {
        int sz = hid_read_timeout(pkt->dev, buf0, sizeof(buf0), timeout);
        if (sz <= 0) {
            if (timeout < 0)
                fatal("read error");
            return 0;
        }
        buf = buf0;
        if (!*buf)
            buf++; // skip report number if passed

        uint8_t tag = buf[0];
        if (pkt->size && (tag & HF2_FLAG_SERIAL_OUT))
            fatal("invalid serial transfer");
        uint32_t newsize = pkt->size + (tag & HF2_SIZE_MASK);
        if (newsize > sizeof(pkt->buf))
            fatal("too large packet");
        memcpy(pkt->buf + pkt->size, buf + 1, tag & HF2_SIZE_MASK);
        pkt->size = newsize;

        tag &= HF2_FLAG_MASK;
        if (tag != HF2_FLAG_CMDPKT_BODY) {
            pkt->serial = //
                tag == HF2_FLAG_SERIAL_OUT ? 1 : tag == HF2_FLAG_SERIAL_ERR ? 2 : 0;
            return 1;
        }

        timeout = -1; // next read is blocking
    }
}

void send_hid(hid_device *dev, const void *data, int size) {
    uint8_t buf[EP_SIZE + 1] = {0};
    const uint8_t *ptr = data;

    for (;;) {
        int s;
        if (size <= EP_SIZE - 1) {
            s = size;
            buf[1] = HF2_FLAG_CMDPKT_LAST | size;
        } else {
            s = EP_SIZE - 1;
            buf[1] = HF2_FLAG_CMDPKT_BODY | (EP_SIZE - 1);
        }
        memcpy(buf + 2, ptr, s);
        int sz = hid_write(dev, buf, EP_SIZE + 1);
        if (sz != EP_SIZE + 1)
            fatal("write error");
        ptr += s;
        size -= s;
        if (!size)
            break;
    }
}

void talk_hid(HID_Dev *pkt, int cmd, const void *data, uint32_t len) {
    if (len >= sizeof(pkt->buf) - 8)
        fatal("buffer overflow");
    if (data)
        memcpy(pkt->buf + 8, data, len);
    write32(pkt->buf, cmd);
    write16(pkt->buf + 4, ++pkt->seqNo);
    write16(pkt->buf + 6, 0);
    send_hid(pkt->dev, pkt->buf, 8 + len);

    if (cmd == HF2_CMD_RESET_INTO_APP)
        return; // no response expected

    recv_hid(pkt, -1);
    if (read16(pkt->buf) != pkt->seqNo)
        fatal("invalid sequence number");
    if (read16(pkt->buf + 2))
        fatal("invalid status");
}

uint8_t flashbuf[2 * 1024 * 1024];

unsigned short add_crc(char ptr, unsigned short crc) {
    unsigned short cmpt;
    crc = crc ^ (int)ptr << 8;
    for (cmpt = 0; cmpt < 8; cmpt++) {
        if (crc & 0x8000)
            crc = crc << 1 ^ 0x1021;
        else
            crc = crc << 1;
    }
    return (crc & 0xFFFF);
}

void verify(HID_Dev *cmd, uint8_t *buf, int size, int offset) {
    int maxSize = (cmd->pageSize / 2 - 12) * cmd->pageSize;
    while (size > maxSize) {
        verify(cmd, buf, maxSize, offset);
        buf += maxSize;
        offset += maxSize;
        size -= maxSize;
    }
    int numpages = size / cmd->pageSize;
    write32(cmd->buf + 8, offset);
    write32(cmd->buf + 12, numpages);
    talk_hid(cmd, HF2_CMD_CHKSUM_PAGES, 0, 8);
    for (int i = 0; i < numpages; ++i) {
        int sum = read16(cmd->buf + 4 + i * 2);
        uint16_t crc = 0;
        for (int j = 0; j < cmd->pageSize; ++j) {
            crc = add_crc(buf[j], crc);
        }
        if (sum != crc)
            fatal("verification failed");
        buf += cmd->pageSize;
    }
}

void *forward_stdin(void *cmd0) {
    uint8_t buf[EP_SIZE + 1];
    HID_Dev *cmd = cmd0;
    for (;;) {
        memset(buf, 0, sizeof(buf));
        int sz = read(0, buf + 2, EP_SIZE - 1);
        if (sz > 0) {
            buf[1] = HF2_FLAG_SERIAL_OUT | sz;
            hid_write(cmd->dev, buf, EP_SIZE + 1);
        }
        if (sz == 0)
            break;
    }
    return NULL;
}

void serial(HID_Dev *cmd) {
    pthread_t stdinFwd;
    pthread_create(&stdinFwd, NULL, forward_stdin, cmd);
    for (;;) {
        if (recv_hid(cmd, -1)) {
            if (cmd->serial)
                write(cmd->serial, cmd->buf, cmd->size);
        }
    }
}

int main(int argc, char *argv[]) {
    int res;
    HID_Dev cmd = {0};

    if (argc != 2) {
        printf("usage: %s COMMAND [ARGUMENTS...]\n", argv[0]);
        printf("Commands include:\n");
        printf("   serial           - run 'serial' port forwarding\n");
        printf("   list             - list devices\n");
        printf("   dmesg            - dump internal runtime logs from the device\n");
        printf("   info             - dump information about the device\n");
        printf("   FILE             - write specified BIN or UF2 file\n");
        printf("   random           - write randomly generated bin file\n");
        return 1;
    }

    const char *filename = argv[1];

    // Initialize the hidapi library
    res = hid_init();

    bool listMode = strcmp(filename, "list") == 0;

    struct hid_device_info *devs = hid_enumerate(0, 0);
    for (struct hid_device_info *p = devs; p; p = p->next) {
        int isOK = (p->release_number & 0xff00) == 0x4200;
        const char *path = strstr(p->path, "@1400");
        if (!path)
            path = p->path;
        if (listMode) {
            // exclude Apple devices
            if (p->vendor_id != 0x05ac)
                printf("%s: %04x:%04x %04x %s\n", isOK ? "HF2" : "...", p->vendor_id, p->product_id,
                       p->release_number, path);
        }
        if (isOK) {
            cmd.dev = hid_open_path(p->path);
        }
    }
    hid_free_enumeration(devs);
    if (listMode)
        return 0;
    if (!cmd.dev) {
        printf("no devices\n");
        return 1;
    }

    if (strcmp(filename, "serial") == 0) {
        serial(&cmd);
        return 0;
    }

    if (strcmp(filename, "dmesg") == 0) {
        talk_hid(&cmd, HF2_CMD_DMESG, 0, 0);
        printf("%s\n", cmd.buf + 4);
        return 0;
    }

    talk_hid(&cmd, HF2_CMD_INFO, 0, 0);
    printf("INFO: %s\n", cmd.buf + 4);

    talk_hid(&cmd, HF2_CMD_START_FLASH, 0, 0);

    talk_hid(&cmd, HF2_CMD_BININFO, 0, 0);
    if (cmd.buf[4] != HF2_MODE_BOOTLOADER)
        fatal("not bootloader");

    cmd.pageSize = read32(cmd.buf + 8);
    cmd.flashSize = read32(cmd.buf + 12) * cmd.pageSize;
    cmd.msgSize = read32(cmd.buf + 16);
    printf("page size: %d, total: %dkB\n", cmd.pageSize, cmd.flashSize / 1024);

    if (strcmp(filename, "info") == 0) {
        return 0;
    }

    int i;
    size_t filesize;
    int isUF2 = 0;

    if (strcmp(filename, "random") == 0) {
        srand(millis());
        filesize = 230 * 1024;
        for (i = 0; i < filesize; ++i)
            flashbuf[i] = rand();
    } else {
        FILE *f = fopen(filename, "rb");
        if (!f) {
            fatal("cannot open file");
        }
        int len = 1;
        filesize = 0;
        while (len) {
            len = fread(flashbuf + filesize, 1, sizeof(flashbuf) - filesize, f);
            filesize += len;
        }
        if (strncmp((const char *)flashbuf, "UF2\nWQ]\x9E", 8) == 0) {
            printf("detected UF2 file\n");
            if (cmd.pageSize != 256)
                fatal("wrong page size");
            isUF2 = 1;
        } else {
            filesize = (filesize + (cmd.pageSize - 1)) / cmd.pageSize * cmd.pageSize;
        }
        printf("read %ld bytes from %s\n", filesize, filename);
        fclose(f);
    }

    uint64_t start = millis();
    uint32_t addr = 0x2000;
    uint32_t blockSize = cmd.pageSize;

    if (isUF2)
        blockSize = 512;

    for (i = 0; i < filesize; i += blockSize) {
        if (isUF2) {
            addr = read32(flashbuf + i + 12);
            memcpy(cmd.buf + 12, flashbuf + i + 32, cmd.pageSize);
        } else {
            memcpy(cmd.buf + 12, flashbuf + i, cmd.pageSize);
        }
        write32(cmd.buf + 8, addr);
        talk_hid(&cmd, HF2_CMD_WRITE_FLASH_PAGE, 0, cmd.pageSize + 4);
        addr += cmd.pageSize;
    }

    printf("time: %d\n", (int)(millis() - start));
    start = millis();

#if 0
    for (i = 0; i < filesize; i += cmd.pageSize) {
        write32(cmd.buf + 8, i + 0x2000);
        write32(cmd.buf + 12, cmd.pageSize / 4);
        talk_hid(&cmd, HF2_CMD_MEM_READ_WORDS, 0, 8);
        if (memcmp(cmd.buf + 4, flashbuf + i, cmd.pageSize)) {
            printf("%d,%d,%d != %d?\n", cmd.buf[8], cmd.buf[9], cmd.buf[10], flashbuf[i]);
            fatal("verification failed");
        }
    }
#else
    if (!isUF2)
        verify(&cmd, flashbuf, filesize, 0x2000);
#endif

    printf("verify time: %d\n", (int)(millis() - start));

    talk_hid(&cmd, HF2_CMD_RESET_INTO_APP, 0, 0);

    printf("device reset.\n");

    // Finalize the hidapi library
    res = hid_exit();

    return 0;
}