-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsonixflasher.c
437 lines (363 loc) · 12.2 KB
/
sonixflasher.c
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <hidapi.h>
#define RESPONSE_LEN 64
#define MAX_FIRMWARE_SN32F260 (30 * 1024) //30k
#define MAX_FIRMWARE_SN32F240 (64 * 1024) //64k
#define QMK_OFFSET_DEFAULT 0x200
#define CMD_BASE 0x55AA0000
#define CMD_INIT (CMD_BASE + 0x100)
#define CMD_PREPARE (CMD_BASE + 0x500)
#define CMD_REBOOT (CMD_BASE + 0x700)
#define SONIX_VID 0x0c45
#define SN268_PID 0x7010
#define SN248B_PID 0x7040
#define SN248_PID 0x7900
#define EXPECTED_STATUS 0xFAFAFAFA
#define MAX_ATTEMPTS 5
long MAX_FIRMWARE = MAX_FIRMWARE_SN32F260;
static void print_usage(char *m_name)
{
fprintf(stderr,
"Usage: \n"
" %s <cmd> [options]\n"
"where <cmd> is one of:\n"
" --vidpid -v Set VID for device to flash\n"
" --offset -o Set flashing offset (default: 0)\n"
" --file -f Binary of the firmware to flash (*.bin extension) \n"
" --jumploader -j Define if we are flashing a jumploader \n"
"\n"
"Examples: \n"
". Flash jumploader to device w/ vid/pid 0x0c45/0x7040 \n"
" sonixflasher --vidpid 0c45/7040 --file fw.bin -j\n"
". Flash fw to device w/ vid/pid 0x0c45/0x7040 and offset 0x200\n"
" sonixflasher --vidpid 0c45/7040 --file fw.bin -o 0x200\n"
"\n"
""
"", m_name);
}
void clear_buffer(unsigned char *data, size_t lenght)
{
for(int i = 0; i < lenght; i++) data[i] = 0;
}
void print_buffer(unsigned char *data, size_t lenght)
{
printf("Sending Report...\n");
for(int i = 0; i < lenght; i++) printf("%02x", data[i]);
printf("\n");
}
bool read_response_32(unsigned char *data, uint32_t expected_result, uint32_t *resp)
{
uint32_t r = *resp;
memcpy(&r, data, 4);
*resp = r;
return r == expected_result;
}
void write_buffer_32(unsigned char *data, uint32_t cmd)
{
memcpy(data, &cmd, 4);
}
bool hid_set_feature(hid_device *dev, unsigned char *data, size_t length)
{
if(length > 65)
{
fprintf(stderr, "ERROR: Report cant be more than 65 bytes!!\n");
return false;
}
int res = hid_send_feature_report(dev, data, length);
if(res < 0)
{
fprintf(stderr, "ERROR: Error while writing!\n");
return false;
}
return true;
}
int hid_get_feature(hid_device *dev, unsigned char *data)
{
return hid_get_feature_report(dev, data, RESPONSE_LEN + 1);
}
bool flash(hid_device *dev, long offset, FILE *firmware, long fw_size, bool skip_size_check)
{
unsigned char buf[65];
int read_bytes;
uint32_t resp = 0;
uint32_t status = 0;
if(skip_size_check == false)
{
if(fw_size + offset > MAX_FIRMWARE)
{
printf("ERROR: Firmware is too large too flash.\n");
return false;
}
}
// 1) Initialize
printf("Initializing flash...\n");
clear_buffer(buf, 65);
write_buffer_32(buf, CMD_INIT);
hid_set_feature(dev, buf, 65);
clear_buffer(buf, 65);
read_bytes = hid_get_feature(dev, buf);
if(read_bytes != RESPONSE_LEN + 1)
{
fprintf(stderr, "ERROR: Failed to initialize: got response of length %d, expected %d.\n", read_bytes, RESPONSE_LEN);
return false;
}
if(!read_response_32(buf, CMD_INIT, &resp)) // Read cmd
{
fprintf(stderr, "ERROR: Failed to initialize: response cmd is 0x%08x, expected 0x%08x.\n", resp, CMD_INIT);
return false;
}
// // 2) Prepare for flash
printf("Preparing for flash...\n");
clear_buffer(buf, 65);
write_buffer_32(buf, CMD_PREPARE);
write_buffer_32(buf+5, (uint32_t)offset);
write_buffer_32(buf+9, (uint32_t)(fw_size/64));
hid_set_feature(dev, buf, 65);
clear_buffer(buf, 65);
read_bytes = hid_get_feature(dev, buf);
if(!read_response_32(buf, CMD_PREPARE, &resp)) // Read cmd
{
fprintf(stderr, "ERROR: Failed to initialize: response cmd is 0x%08x, expected 0x%08x.\n", resp, CMD_PREPARE);
return false;
}
if(!read_response_32(buf + 5, EXPECTED_STATUS, &status))// Read status
{
fprintf(stderr, "ERROR: Failed to initialize: response status is 0x%08x, expected 0x%08x.\n", status, EXPECTED_STATUS);
return false;
}
// // 3) Flash
printf("Flashing device, please wait...\n");
size_t bytes_read = 0;
clear_buffer(buf, 65);
while ((bytes_read = fread(buf+1, 1, 64, firmware)) > 0)
{
hid_set_feature(dev, buf, 65);
clear_buffer(buf, 65);
}
printf("Flashing done. Rebooting.\n");
// // 4) reboot
clear_buffer(buf, 65);
write_buffer_32(buf, CMD_REBOOT);
hid_set_feature(dev, buf, 65);
return true;
}
int str2buf(void* buffer, char* delim_str, char* string, int buflen, int bufelem_size)
{
char *s;
int pos = 0;
if( string==NULL ) return -1;
memset(buffer,0,buflen); // bzero() not defined on Win32?
while((s = strtok(string, delim_str)) != NULL && pos < buflen){
string = NULL;
switch(bufelem_size) {
case 1:
((uint8_t*)buffer)[pos++] = (uint8_t)strtol(s, NULL, 0); break;
case 2:
((int*)buffer)[pos++] = (int)strtol(s, NULL, 0); break;
}
}
return pos;
}
bool sanity_check_firmware(long fw_size, long offset)
{
if(fw_size + offset > MAX_FIRMWARE)
{
fprintf(stderr, "ERROR: Firmware is too large too flash: 0x%08lx max allowed is 0x%08lx.\n", fw_size, MAX_FIRMWARE - offset);
return false;
}
if(fw_size < 0x100)
{
fprintf(stderr, "ERROR: Firmware is too small.");
return false;
}
return true;
//TODO check pointer validity
}
bool sanity_check_jumploader_firmware(long fw_size)
{
if(fw_size > QMK_OFFSET_DEFAULT)
{
fprintf(stderr, "ERROR: Jumper loader is too large: 0x%08lx max allowed is 0x%08lx.\n", fw_size, MAX_FIRMWARE - QMK_OFFSET_DEFAULT);
return false;
}
return true;
}
int main(int argc, char* argv[])
{
int opt, opt_index, res;
hid_device *handle;
uint16_t vid = 0;
uint16_t pid = 0;
long offset = 0;
char* file_name = NULL;
bool flash_jumploader = false;
if(argc < 2)
{
print_usage("sonixflasher");
exit(1);
}
struct option longoptions[] =
{
{"help", no_argument, 0, 'h'},
{"vidpid", required_argument, NULL, 'v'},
{"offset", optional_argument, NULL, 'o'},
{"file", required_argument, NULL, 'f'},
{"jumploader", required_argument, NULL, 'j'},
{NULL,0,0,0}
};
while ((opt = getopt_long(argc, argv, "hv:o:f:j", longoptions, &opt_index)) != -1)
{
switch (opt)
{
case 0: // Show help
print_usage("sonixflasher");
break;
case 'v': // Set vid/pid
if( sscanf(optarg, "%4hx/%4hx", &vid,&pid) !=2 ) { // match "23FE/AB12"
if( !sscanf(optarg, "%4hx:%4hx", &vid,&pid) ) { // match "23FE:AB12"
// else try parsing standard dec/hex values
int wordbuf[4]; // a little extra space
str2buf(wordbuf, ":/, ", optarg, sizeof(wordbuf), 2);
vid = wordbuf[0]; pid = wordbuf[1];
}
}
break;
case 'f': // file name
file_name = optarg;
break;
case 'o': // offset
offset = strtol(optarg,NULL, 0);
break;
case 'j': // Jumploader
flash_jumploader = true;
break;
case '?':
default:
switch (optopt)
{
case 'f':
case 'v':
fprintf(stderr, "ERROR: option '-%c' requires a parameter.\n", optopt);
break;
case 0:
fprintf(stderr, "ERROR: invalid option.\n");
break;
default:
fprintf(stderr, "ERROR: invalid option '-%c'.\n", optopt);
break;
}
exit(1);
}
}
if (file_name == NULL)
{
fprintf(stderr, "ERROR: filename cannot be null.\n");
exit(1);
}
printf("Firmware to flash: %s with offset 0x%04lx, device: 0x%04x/0x%04x.\n", file_name, offset, vid, pid);
FILE* fp = fopen(file_name, "rb");
if(fp == NULL)
{
fprintf(stderr, "ERROR: Could not open file (Does the file exist?).\n");
fclose(fp);
exit(1);
}
// Get file size
fseek(fp, 0 , SEEK_END);
long file_size = ftell(fp);
fseek(fp, 0 , SEEK_SET);
// if jumploader is not 0x200 in length, add padded zeroes to file
if(flash_jumploader && file_size < QMK_OFFSET_DEFAULT)
{
printf("Warning: jumploader binary doesnt have a size of: 0x%04x bytes.\n", QMK_OFFSET_DEFAULT);
printf("Truncating jumploader binary to: 0x%04x.\n", QMK_OFFSET_DEFAULT);
// Close device before truncating it
fclose(fp);
if (truncate(file_name, QMK_OFFSET_DEFAULT) != 0)
{
fprintf(stderr, "ERROR: Could not truncate file.\n");
exit(1);
}
// Try open the file again.
fp = fopen(file_name, "rb");
if(fp == NULL)
{
fprintf(stderr, "ERROR: Could not open file.\n");
fclose(fp);
exit(1);
}
}
// Try to open the device
res = hid_init();
printf("Opening device...\n");
handle = hid_open(vid, pid, NULL);
uint8_t attempt_no = 1;
while(handle == NULL && attempt_no <= MAX_ATTEMPTS) // Try {MAX ATTEMPTS} to connect to device.
{
printf("Device failed to open, re-trying in 3 seconds. Attempt %d of %d...\n", attempt_no, MAX_ATTEMPTS);
sleep(3);
handle = hid_open(vid, pid, NULL);
attempt_no++;
}
if(handle)
{
printf("Device opened successfully...\n");
// Check VID/PID
if(vid != SONIX_VID || (pid != SN248_PID && pid != SN248B_PID && pid != SN268_PID))
{
printf("Warning: Flashing a non-sonix device, you are now on your own.\n");
// Set max firmware to 64k, useful when flashing a Sonix Board that isnt in BL mode (Redragons, Keychrons)
MAX_FIRMWARE = MAX_FIRMWARE_SN32F240; // Maybe add a param to override this (?)
}
// Set max fw size depending on VID/PID
if(vid == SONIX_VID)
{
switch (pid)
{
case SN248_PID:
case SN248B_PID:
MAX_FIRMWARE = MAX_FIRMWARE_SN32F240;
break;
case SN268_PID:
default:
MAX_FIRMWARE = MAX_FIRMWARE_SN32F260;
if(!flash_jumploader && offset == 0) // Failsafe when flashing a 268 w/o jumploader and offset
{
printf("Warning: Flashing 26X without offset.\n");
printf("Fail safing to offset 0x%04x\n", QMK_OFFSET_DEFAULT);
offset = QMK_OFFSET_DEFAULT;
}
break;
}
}
while (file_size % 64 != 0) file_size++; // Add padded zereos (if any) to file_size, since we are using a fixed 64 + 1 buffer, we need to take in consideration when the file doesnt fill the buffer.
if( ((flash_jumploader && sanity_check_jumploader_firmware(file_size)) ||
(!flash_jumploader && sanity_check_firmware(file_size, offset))) &&
(flash(handle, offset, fp, file_size, false)))
{
printf("Device succesfully flashed!\n");
}
else
{
fprintf(stderr, "ERROR: Could not flash the device. Try again.\n");
}
}
else
{
fprintf(stderr, "ERROR: Could not open the device (Is the device connected?).\n");
}
fclose(fp);
hid_close(handle);
res = hid_exit();
if(res < 0)
{
fprintf(stderr, "ERROR: Could not close the device.\n");
}
exit(0);
}