forked from ilyakurdyukov/spreadtrum_flash
-
Notifications
You must be signed in to change notification settings - Fork 19
/
common.c
2038 lines (1868 loc) · 57.2 KB
/
common.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "common.h"
#if !USE_LIBUSB
DWORD curPort = 0;
DWORD* ports = NULL;
DWORD FindPort(const char* USB_DL)
{
const GUID GUID_DEVCLASS_PORTS = { 0x4d36e978, 0xe325, 0x11ce,{0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18} };
HDEVINFO DeviceInfoSet;
SP_DEVINFO_DATA DeviceInfoData;
DWORD dwIndex = 0;
DWORD count = 0;
DeviceInfoSet = SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS, NULL, NULL, DIGCF_PRESENT);
if (DeviceInfoSet == INVALID_HANDLE_VALUE) {
DBG_LOG("Failed to get device information set. Error code: %ld\n", GetLastError());
return 0;
}
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
while (SetupDiEnumDeviceInfo(DeviceInfoSet, dwIndex, &DeviceInfoData)) {
char friendlyName[MAX_PATH];
DWORD dataType = 0;
DWORD dataSize = sizeof(friendlyName);
SetupDiGetDeviceRegistryPropertyA(DeviceInfoSet, &DeviceInfoData, SPDRP_FRIENDLYNAME, &dataType, (BYTE*)friendlyName, dataSize, &dataSize);
char* result = strstr(friendlyName, USB_DL);
if (result != NULL) {
char portNum_str[4];
strncpy(portNum_str, result + strlen(USB_DL) + 5, 3);
portNum_str[3] = 0;
DWORD portNum = strtoul(portNum_str, NULL, 0);
DWORD* temp = (DWORD*)realloc(ports, (count + 2) * sizeof(DWORD));
if (temp == NULL) {
DBG_LOG("Memory allocation failed.\n");
SetupDiDestroyDeviceInfoList(DeviceInfoSet);
free(ports);
ports = NULL;
return 0;
}
ports = temp;
ports[count] = portNum;
count++;
}
++dwIndex;
}
SetupDiDestroyDeviceInfoList(DeviceInfoSet);
if (count > 0) {
ports[count] = 0;
return ports[0];
}
return 0;
}
void usleep(unsigned int us)
{
Sleep(us / 1000);
}
#endif
extern int m_bOpened;
void print_mem(FILE* f, uint8_t* buf, size_t len) {
size_t i; int a, j, n;
for (i = 0; i < len; i += 16) {
n = len - i;
if (n > 16) n = 16;
for (j = 0; j < n; j++) fprintf(f, "%02x ", buf[i + j]);
for (; j < 16; j++) fprintf(f, " ");
fprintf(f, " |");
for (j = 0; j < n; j++) {
a = buf[i + j];
fprintf(f, "%c", a > 0x20 && a < 0x7f ? a : '.');
}
fprintf(f, "|\n");
}
}
void print_string(FILE* f, const void* src, size_t n) {
size_t i; int a, b = 0;
const uint8_t* buf = (const uint8_t*)src;
fprintf(f, "\"");
for (i = 0; i < n; i++) {
a = buf[i]; b = 0;
switch (a) {
case '"': case '\\': b = a; break;
case 0: b = '0'; break;
case '\b': b = 'b'; break;
case '\t': b = 't'; break;
case '\n': b = 'n'; break;
case '\f': b = 'f'; break;
case '\r': b = 'r'; break;
}
if (b) fprintf(f, "\\%c", b);
else if (a >= 32 && a < 127) fprintf(f, "%c", a);
else fprintf(f, "\\x%02x", a);
}
fprintf(f, "\"\n");
}
#if USE_LIBUSB
void find_endpoints(libusb_device_handle* dev_handle, int result[2]) {
int endp_in = -1, endp_out = -1;
int i, k, err;
//struct libusb_device_descriptor desc;
struct libusb_config_descriptor* config;
libusb_device* device = libusb_get_device(dev_handle);
if (!device)
ERR_EXIT("libusb_get_device failed\n");
//if (libusb_get_device_descriptor(device, &desc) < 0)
// ERR_EXIT("libusb_get_device_descriptor failed");
err = libusb_get_config_descriptor(device, 0, &config);
if (err < 0)
ERR_EXIT("libusb_get_config_descriptor failed : %s\n", libusb_error_name(err));
for (k = 0; k < config->bNumInterfaces; k++) {
const struct libusb_interface* interface;
const struct libusb_interface_descriptor* interface_desc;
int claim = 0;
interface = config->interface + k;
if (interface->num_altsetting < 1) continue;
interface_desc = interface->altsetting + 0;
for (i = 0; i < interface_desc->bNumEndpoints; i++) {
const struct libusb_endpoint_descriptor* endpoint;
endpoint = interface_desc->endpoint + i;
if (endpoint->bmAttributes == 2) {
int addr = endpoint->bEndpointAddress;
err = 0;
if (addr & 0x80) {
if (endp_in >= 0) ERR_EXIT("more than one endp_in\n");
endp_in = addr;
claim = 1;
}
else {
if (endp_out >= 0) ERR_EXIT("more than one endp_out\n");
endp_out = addr;
claim = 1;
}
}
}
if (claim) {
i = interface_desc->bInterfaceNumber;
#if LIBUSB_DETACH
err = libusb_kernel_driver_active(dev_handle, i);
if (err > 0) {
DBG_LOG("kernel driver is active, trying to detach\n");
err = libusb_detach_kernel_driver(dev_handle, i);
if (err < 0)
ERR_EXIT("libusb_detach_kernel_driver failed : %s\n", libusb_error_name(err));
}
#endif
err = libusb_claim_interface(dev_handle, i);
if (err < 0)
ERR_EXIT("libusb_claim_interface failed : %s\n", libusb_error_name(err));
break;
}
}
if (endp_in < 0) ERR_EXIT("endp_in not found\n");
if (endp_out < 0) ERR_EXIT("endp_out not found\n");
libusb_free_config_descriptor(config);
//DBG_LOG("USB endp_in=%02x, endp_out=%02x\n", endp_in, endp_out);
result[0] = endp_in;
result[1] = endp_out;
}
#endif
#define RECV_BUF_LEN (0x8000)
char savepath[ARGV_LEN] = { 0 };
DA_INFO_T Da_Info;
spdio_t* spdio_init(int flags) {
uint8_t* p; spdio_t* io;
p = (uint8_t*)malloc(sizeof(spdio_t) + RECV_BUF_LEN + (4 + 0x10000 + 2) * 3 + 2);
io = (spdio_t*)p;
if (!p) ERR_EXIT("malloc failed\n");
memset(io, 0, sizeof(spdio_t));
p += sizeof(spdio_t);
io->flags = flags;
io->recv_len = 0;
io->recv_pos = 0;
io->recv_buf = p; p += RECV_BUF_LEN;
io->temp_buf = p + 4;
io->raw_buf = p; p += 4 + 0x10000 + 2;
io->enc_buf = p;
io->verbose = 0;
io->timeout = 1000;
memset(io->recv_buf, 0, 8);
return io;
}
void spdio_free(spdio_t* io) {
if (!io) return;
#if _WIN32
PostThreadMessage(io->iThread, THRD_MESSAGE_EXIT, 0, 0);
WaitForSingleObject(io->hThread, INFINITE);
CloseHandle(io->hThread);
#endif
#if USE_LIBUSB
libusb_close(io->dev_handle);
libusb_exit(NULL);
#else
call_DisconnectChannel(io->handle);
call_Uninitialize(io->handle);
destroyClass(io->handle);
#endif
free(io);
}
int spd_transcode(uint8_t* dst, uint8_t* src, int len) {
int i, a, n = 0;
for (i = 0; i < len; i++) {
a = src[i];
if (a == HDLC_HEADER || a == HDLC_ESCAPE) {
if (dst) dst[n] = HDLC_ESCAPE;
n++;
a ^= 0x20;
}
if (dst) dst[n] = a;
n++;
}
return n;
}
int spd_transcode_max(uint8_t* src, int len, int n) {
int i, a;
for (i = 0; i < len; i++) {
a = src[i];
a = a == HDLC_HEADER || a == HDLC_ESCAPE ? 2 : 1;
if (n < a) break;
n -= a;
}
return i;
}
unsigned spd_crc16(unsigned crc, const void* src, unsigned len) {
uint8_t* s = (uint8_t*)src; int i;
crc &= 0xffff;
while (len--) {
crc ^= *s++ << 8;
for (i = 0; i < 8; i++)
crc = crc << 1 ^ ((0 - (crc >> 15)) & 0x11021);
}
return crc;
}
#define CHK_FIXZERO 1
#define CHK_ORIG 2
unsigned spd_checksum(unsigned crc, const void* src, int len, int final) {
uint8_t* s = (uint8_t*)src;
while (len > 1) {
crc += s[1] << 8 | s[0]; s += 2;
len -= 2;
}
if (len) crc += *s;
if (final) {
crc = (crc >> 16) + (crc & 0xffff);
crc += crc >> 16;
crc = ~crc & 0xffff;
if (len < final)
crc = crc >> 8 | (crc & 0xff) << 8;
}
return crc;
}
void encode_msg(spdio_t* io, int type, const void* data, size_t len) {
uint8_t* p, * p0; unsigned chk;
if (len > 0xffff)
ERR_EXIT("message too long\n");
if (type == BSL_CMD_CHECK_BAUD) {
memset(io->enc_buf, HDLC_HEADER, len);
io->enc_len = len;
*(uint8_t*)(io->raw_buf) = HDLC_HEADER;
return;
}
p = p0 = io->raw_buf;
WRITE16_BE(p, type); p += 2;
WRITE16_BE(p, len); p += 2;
memcpy(p, data, len); p += len;
len = p - p0;
if (io->flags & FLAGS_CRC16)
chk = spd_crc16(0, p0, len);
else {
// if (len & 1) *p++ = 0;
chk = spd_checksum(0, p0, len, CHK_FIXZERO);
}
WRITE16_BE(p, chk); p += 2;
io->raw_len = len = p - p0;
p = io->enc_buf;
*p++ = HDLC_HEADER;
if (io->flags & FLAGS_TRANSCODE)
len = spd_transcode(p, p0, len);
else memcpy(p, p0, len);
p[len] = HDLC_HEADER;
io->enc_len = len + 2;
}
int send_msg(spdio_t* io) {
int ret;
if (!io->enc_len)
ERR_EXIT("empty message\n");
#if _WIN32
if (m_bOpened == -1) {
spdio_free(io);
ERR_EXIT("device removed, exiting...\n");
}
#endif
if (io->verbose >= 2) {
DBG_LOG("send (%d):\n", io->enc_len);
print_mem(stderr, io->enc_buf, io->enc_len);
}
else if (io->verbose >= 1) {
if (io->raw_buf[0] == HDLC_HEADER)
DBG_LOG("send: check baud\n");
else if (io->raw_len >= 4) {
DBG_LOG("send: type = 0x%02x, size = %d\n",
READ16_BE(io->raw_buf), READ16_BE(io->raw_buf + 2));
}
else DBG_LOG("send: unknown message\n");
}
#if USE_LIBUSB
{
int err = libusb_bulk_transfer(io->dev_handle,
io->endp_out, io->enc_buf, io->enc_len, &ret, io->timeout);
if (err < 0)
ERR_EXIT("usb_send failed : %s\n", libusb_error_name(err));
}
#else
ret = call_Write(io->handle, io->enc_buf, io->enc_len);
#endif
if (ret != io->enc_len)
ERR_EXIT("usb_send failed (%d / %d)\n", ret, io->enc_len);
return ret;
}
extern int fdl1_loaded;
int recv_msg_orig(spdio_t* io) {
int a, pos, len, chk;
int esc = 0, nread = 0, head_found = 0, plen = 6;
len = io->recv_len;
pos = io->recv_pos;
memset(io->recv_buf, 0, 8);
for (;;) {
if (pos >= len) {
#if _WIN32
if (m_bOpened == -1) {
spdio_free(io);
ERR_EXIT("device removed, exiting...\n");
}
#endif
#if USE_LIBUSB
int err = libusb_bulk_transfer(io->dev_handle, io->endp_in, io->recv_buf, RECV_BUF_LEN, &len, io->timeout);
if (err == LIBUSB_ERROR_NO_DEVICE)
ERR_EXIT("connection closed\n");
else if (err < 0)
{ DBG_LOG("usb_recv failed : %s\n", libusb_error_name(err)); return 0; }
#else
len = call_Read(io->handle, io->recv_buf, RECV_BUF_LEN, io->timeout);
#endif
if (len < 0)
{ DBG_LOG("usb_recv failed, ret = %d\n", len); return 0; }
if (io->verbose >= 2) {
DBG_LOG("recv (%d):\n", len);
print_mem(stderr, io->recv_buf, len);
}
pos = 0;
if (!len) break;
}
a = io->recv_buf[pos++];
if (io->flags & FLAGS_TRANSCODE) {
if (esc && a != (HDLC_HEADER ^ 0x20) &&
a != (HDLC_ESCAPE ^ 0x20))
{ DBG_LOG("unexpected escaped byte (0x%02x)\n", a); return 0; }
if (a == HDLC_HEADER) {
if (!head_found) head_found = 1;
else if (!nread) continue;
else if (nread < plen)
{ DBG_LOG("recieved message too short\n"); return 0; }
else break;
}
else if (a == HDLC_ESCAPE) {
esc = 0x20;
}
else {
if (!head_found) continue;
if (nread >= plen)
{ DBG_LOG("recieved message too long\n"); return 0; }
io->raw_buf[nread++] = a ^ esc;
esc = 0;
}
}
else {
if (!head_found && a == HDLC_HEADER) {
head_found = 1;
continue;
}
if (nread == plen) {
if (a != HDLC_HEADER)
{ DBG_LOG("expected end of message\n"); return 0; }
break;
}
io->raw_buf[nread++] = a;
}
if (nread == 4) {
a = READ16_BE(io->raw_buf + 2); // len
plen = a + 6;
}
}
io->recv_len = len;
io->recv_pos = pos;
io->raw_len = nread;
if (!nread) return 0;
if (nread < 6)
{ DBG_LOG("recieved message too short\n"); return 0; }
if (nread != plen)
{ DBG_LOG("bad length (%d, expected %d)\n", nread, plen); return 0; }
a = READ16_BE(io->raw_buf + plen - 2);
if (fdl1_loaded == 0 && !(io->flags & FLAGS_CRC16))
{
int chk1, chk2;
chk1 = spd_crc16(0, io->raw_buf, plen - 2);
if (a == chk1) io->flags |= FLAGS_CRC16;
else
{
chk2 = spd_checksum(0, io->raw_buf, plen - 2, CHK_ORIG);
if (a == chk2) fdl1_loaded = 1;
else
{
DBG_LOG("bad checksum (0x%04x, expected 0x%04x or 0x%04x)\n", a, chk1, chk2);
return 0;
}
}
}
else
{
if (io->flags & FLAGS_CRC16)
chk = spd_crc16(0, io->raw_buf, plen - 2);
else
chk = spd_checksum(0, io->raw_buf, plen - 2, CHK_ORIG);
if (a != chk)
{
DBG_LOG("bad checksum (0x%04x, expected 0x%04x)\n", a, chk);
return 0;
}
}
if (io->verbose == 1)
DBG_LOG("recv: type = 0x%02x, size = %d\n",
READ16_BE(io->raw_buf), READ16_BE(io->raw_buf + 2));
return nread;
}
extern int fdl2_executed;
int recv_msg(spdio_t* io) {
int ret;
for (;;) {
ret = recv_msg_orig(io);
// only retry in fdl2 stage
if (!ret) {
if (fdl2_executed) {
#if !USE_LIBUSB
if (io->raw_len) call_Clear(io->handle); //io->raw_len = nread in recv_msg_orig()
#endif
send_msg(io);
ret = recv_msg_orig(io);
if (!ret) break;
}
else break;
}
if (recv_type(io) != BSL_REP_LOG) break;
DBG_LOG("BSL_REP_LOG: ");
print_string(stderr, io->raw_buf + 4, READ16_BE(io->raw_buf + 2));
}
return ret;
}
int recv_msg_timeout(spdio_t* io, int timeout) {
int old = io->timeout, ret;
io->timeout = old > timeout ? old : timeout;
ret = recv_msg(io);
io->timeout = old;
return ret;
}
unsigned recv_type(spdio_t* io) {
//if (io->raw_len < 6) return -1;
return READ16_BE(io->raw_buf);
}
int send_and_check(spdio_t* io) {
int ret;
send_msg(io);
ret = recv_msg(io);
if (!ret) ERR_EXIT("timeout reached\n");
ret = recv_type(io);
if (ret != BSL_REP_ACK) {
DBG_LOG("unexpected response (0x%04x)\n", ret);
return -1;
}
return 0;
}
int check_confirm(const char* name) {
char c;
DBG_LOG("Answer \"y\" to confirm the \"%s\" command: ", name);
fflush(stdout);
if (scanf(" %c", &c) != 1) return 0;
while (getchar() != '\n');
if (tolower(c) == 'y') return 1;
return 0;
}
uint8_t* loadfile(const char* fn, size_t* num, size_t extra) {
size_t n, j = 0; uint8_t* buf = 0;
FILE* fi = fopen(fn, "rb");
if (fi) {
fseek(fi, 0, SEEK_END);
n = ftell(fi);
if (n) {
fseek(fi, 0, SEEK_SET);
buf = (uint8_t*)malloc(n + extra);
if (buf) j = fread(buf, 1, n, fi);
}
fclose(fi);
}
if (num) *num = j;
return buf;
}
void send_file(spdio_t* io, const char* fn,
uint32_t start_addr, int end_data, unsigned step) {
uint8_t* mem; size_t size = 0;
uint32_t data[2], i, n;
mem = loadfile(fn, &size, 0);
if (!mem) ERR_EXIT("loadfile(\"%s\") failed\n", fn);
if ((uint64_t)size >> 32) ERR_EXIT("file too big\n");
WRITE32_BE(data, start_addr);
WRITE32_BE(data + 1, size);
encode_msg(io, BSL_CMD_START_DATA, data, 4 * 2);
if (send_and_check(io)) { free(mem); return; }
for (i = 0; i < size; i += n) {
n = size - i;
// n = spd_transcode_max(mem + i, size - i, 2048 - 2 - 6);
if (n > step) n = step;
encode_msg(io, BSL_CMD_MIDST_DATA, mem + i, n);
if (send_and_check(io)) { free(mem); return; }
}
free(mem);
if (end_data) {
encode_msg(io, BSL_CMD_END_DATA, NULL, 0);
send_and_check(io);
}
DBG_LOG("SEND %s to 0x%x\n", fn, start_addr);
}
unsigned dump_flash(spdio_t* io,
uint32_t addr, uint32_t start, uint32_t len,
const char* fn, unsigned step) {
uint32_t n, offset, nread;
int ret;
FILE* fo;
if (savepath[0]) {
char fix_fn[1024];
sprintf(fix_fn, "%s/%s", savepath, fn);
fo = fopen(fix_fn, "wb");
}
else fo = fopen(fn, "wb");
if (!fo) ERR_EXIT("fopen(dump) failed\n");
for (offset = start; offset < start + len; ) {
uint32_t data[3];
n = start + len - offset;
if (n > step) n = step;
WRITE32_BE(data, addr);
WRITE32_BE(data + 1, n);
WRITE32_BE(data + 2, offset);
encode_msg(io, BSL_CMD_READ_FLASH, data, 4 * 3);
send_msg(io);
ret = recv_msg(io);
if (!ret) ERR_EXIT("timeout reached\n");
if ((ret = recv_type(io)) != BSL_REP_READ_FLASH) {
DBG_LOG("unexpected response (0x%04x)\n", ret);
break;
}
nread = READ16_BE(io->raw_buf + 2);
if (n < nread)
ERR_EXIT("unexpected length\n");
if (fwrite(io->raw_buf + 4, 1, nread, fo) != nread)
ERR_EXIT("fwrite(dump) failed\n");
offset += nread;
if (n != nread) break;
}
DBG_LOG("Read Flash Done: 0x%08x+0x%x, target: 0x%x, read: 0x%x\n", addr, start, len, offset - start);
fclose(fo);
return offset;
}
unsigned dump_mem(spdio_t* io,
uint32_t start, uint32_t len, const char* fn, unsigned step) {
uint32_t n, offset, nread;
int ret;
FILE* fo;
if (savepath[0]) {
char fix_fn[2048];
sprintf(fix_fn, "%s/%s", savepath, fn);
fo = fopen(fix_fn, "wb");
}
else fo = fopen(fn, "wb");
if (!fo) ERR_EXIT("fopen(dump) failed\n");
for (offset = start; offset < start + len; ) {
uint32_t data[3];
n = start + len - offset;
if (n > step) n = step;
WRITE32_BE(data, offset);
WRITE32_BE(data + 1, n);
WRITE32_BE(data + 2, 0); // unused
encode_msg(io, BSL_CMD_READ_FLASH, data, sizeof(data));
send_msg(io);
ret = recv_msg(io);
if (!ret) ERR_EXIT("timeout reached\n");
if ((ret = recv_type(io)) != BSL_REP_READ_FLASH) {
DBG_LOG("unexpected response (0x%04x)\n", ret);
break;
}
nread = READ16_BE(io->raw_buf + 2);
if (n < nread)
ERR_EXIT("unexpected length\n");
if (fwrite(io->raw_buf + 4, 1, nread, fo) != nread)
ERR_EXIT("fwrite(dump) failed\n");
offset += nread;
if (n != nread) break;
}
DBG_LOG("Read Mem Done: 0x%08x, target: 0x%x, read: 0x%x\n", start, len, offset - start);
fclose(fo);
return offset;
}
int copy_to_wstr(uint16_t* d, size_t n, const char* s) {
size_t i; int a = -1;
for (i = 0; a && i < n; i++) { a = s[i]; WRITE16_LE(d + i, a); }
return a;
}
int copy_from_wstr(char* d, size_t n, const uint16_t* s) {
size_t i; int a = -1;
for (i = 0; a && i < n; i++) { d[i] = a = s[i]; if (a >> 8) break; }
return a;
}
void select_partition(spdio_t* io, const char* name,
uint64_t size, int mode64, int cmd) {
uint32_t t32; uint64_t n64;
struct {
uint16_t name[36];
uint32_t size, size_hi; uint64_t dummy;
} pkt = { 0 };
int ret;
ret = copy_to_wstr(pkt.name, sizeof(pkt.name) / 2, name);
if (ret) ERR_EXIT("name too long\n");
n64 = size;
WRITE32_LE(&pkt.size, n64);
if (mode64) {
t32 = n64 >> 32;
WRITE32_LE(&pkt.size_hi, t32);
}
encode_msg(io, cmd, &pkt,
sizeof(pkt.name) + (mode64 ? 16 : 4));
}
#define PROGRESS_BAR_WIDTH 40
void print_progress_bar(float progress) {
static int completed0 = 0;
if (completed0 == PROGRESS_BAR_WIDTH) completed0 = 0;
int completed = (int)(PROGRESS_BAR_WIDTH * progress);
int remaining;
if (completed != completed0)
{
remaining = PROGRESS_BAR_WIDTH - completed;
DBG_LOG("[");
for (int i = 0; i < completed; i++) {
DBG_LOG("=");
}
for (int i = 0; i < remaining; i++) {
DBG_LOG(" ");
}
DBG_LOG("] %.1f%%\n", 100 * progress);
}
completed0 = completed;
}
uint64_t dump_partition(spdio_t* io,
const char* name, uint64_t start, uint64_t len,
const char* fn, unsigned step) {
uint32_t n, nread, t32; uint64_t offset, n64;
int ret, mode64 = (start + len) >> 32;
FILE* fo;
if (!memcmp(name, "userdata", 8)) { if (!check_confirm("read userdata")) return 0; }
else if (strstr(name, "nv1") || strstr(name, "nv2"))
{
char* name_tmp = malloc(strlen(name) + 1);
if (name_tmp == NULL) return 0;
sprintf(name_tmp, "%s", name);
char* dot = strrchr(name_tmp, '1');
if (dot != NULL) *dot = '2';
select_partition(io, name_tmp, 8, 0, BSL_CMD_READ_START);
free(name_tmp);
if (send_and_check(io)) return 0;
uint32_t data[2] = { 8,0 };
encode_msg(io, BSL_CMD_READ_MIDST, data, 8);
send_msg(io);
ret = recv_msg(io);
if (!ret) ERR_EXIT("timeout reached\n");
if (recv_type(io) != BSL_REP_READ_FLASH) return 0;
if (*(uint32_t*)(io->raw_buf + 4) == 0x00004e56)
{
if (dot != NULL) len = *(uint32_t*)(io->raw_buf + 8);
else len = 0x200 + *(uint32_t*)(io->raw_buf + 8);
DBG_LOG("nv length: 0x%llx\n", (long long)len);
}
encode_msg(io, BSL_CMD_READ_END, NULL, 0);
send_and_check(io);
}
select_partition(io, name, start + len, mode64, BSL_CMD_READ_START);
if (send_and_check(io)) return 0;
if (savepath[0]) {
char fix_fn[2048];
sprintf(fix_fn, "%s/%s", savepath, fn);
fo = fopen(fix_fn, "wb");
}
else fo = fopen(fn, "wb");
if (!fo) ERR_EXIT("fopen(dump) failed\n");
for (offset = start; (n64 = start + len - offset); ) {
uint32_t data[3];
n = (uint32_t)(n64 > step ? step : n64);
WRITE32_LE(data, n);
WRITE32_LE(data + 1, offset);
t32 = offset >> 32;
WRITE32_LE(data + 2, t32);
encode_msg(io, BSL_CMD_READ_MIDST, data, mode64 ? 12 : 8);
send_msg(io);
ret = recv_msg(io);
if (!ret) ERR_EXIT("timeout reached\n");
if ((ret = recv_type(io)) != BSL_REP_READ_FLASH) {
DBG_LOG("unexpected response (0x%04x)\n", ret);
break;
}
nread = READ16_BE(io->raw_buf + 2);
if (n < nread)
ERR_EXIT("unexpected length\n");
if (fwrite(io->raw_buf + 4, 1, nread, fo) != nread)
ERR_EXIT("fwrite(dump) failed\n");
print_progress_bar((offset + nread - start) / (float)len);
offset += nread;
if (n != nread) break;
}
DBG_LOG("Read Part Done: %s+0x%llx, target: 0x%llx, read: 0x%llx\n",
name, (long long)start, (long long)len,
(long long)(offset - start));
fclose(fo);
encode_msg(io, BSL_CMD_READ_END, NULL, 0);
send_and_check(io);
return offset;
}
uint64_t read_pactime(spdio_t* io) {
uint32_t n, offset = 0x81400, len = 8;
int ret; uint32_t data[2];
unsigned long long time, unix;
select_partition(io, "miscdata", offset + len, 0, BSL_CMD_READ_START);
if (send_and_check(io)) return 0;
WRITE32_LE(data, len);
WRITE32_LE(data + 1, offset);
encode_msg(io, BSL_CMD_READ_MIDST, data, sizeof(data));
send_msg(io);
ret = recv_msg(io);
if (!ret) ERR_EXIT("timeout reached\n");
if ((ret = recv_type(io)) != BSL_REP_READ_FLASH)
ERR_EXIT("unexpected response (0x%04x)\n", ret);
n = READ16_BE(io->raw_buf + 2);
if (n != len) ERR_EXIT("unexpected length\n");
time = (uint32_t)READ32_LE(io->raw_buf + 4);
time |= (uint64_t)READ32_LE(io->raw_buf + 8) << 32;
unix = time ? time / 10000000 - 11644473600 : 0;
// $ date -d @unixtime
DBG_LOG("pactime = 0x%llx (unix = %llu)\n", time, unix);
encode_msg(io, BSL_CMD_READ_END, NULL, 0);
send_and_check(io);
return time;
}
int scan_xml_partitions(const char* fn, uint8_t* buf, size_t buf_size) {
const char* part1 = "Partitions>";
char* src, * p, name[36]; size_t size = 0;
int part1_len = strlen(part1), found = 0, stage = 0;
src = (char*)loadfile(fn, &size, 1);
if (!src) ERR_EXIT("loadfile failed\n");
src[size] = 0;
p = src;
for (;;) {
int i, a = *p++, n; char c; long long size;
if (a == ' ' || a == '\t' || a == '\n' || a == '\r') continue;
if (a != '<') {
if (!a) break;
if (stage != 1) continue;
ERR_EXIT("xml: unexpected symbol\n");
}
if (!memcmp(p, "!--", 3)) {
p = strstr(p + 3, "--");
if (!p || !((p[-1] - '!') | (p[-2] - '<')) || p[2] != '>')
ERR_EXIT("xml: unexpected syntax\n");
p += 3;
continue;
}
if (stage != 1) {
stage += !memcmp(p, part1, part1_len);
if (stage > 2)
ERR_EXIT("xml: more than one partition lists\n");
p = strchr(p, '>');
if (!p) ERR_EXIT("xml: unexpected syntax\n");
p++;
continue;
}
if (*p == '/' && !memcmp(p + 1, part1, part1_len)) {
p = p + 1 + part1_len;
stage++;
continue;
}
i = sscanf(p, "Partition id=\"%35[^\"]\" size=\"%lli\"/%n%c", name, &size, &n, &c);
if (i != 3 || c != '>')
ERR_EXIT("xml: unexpected syntax\n");
p += n + 1;
if (buf_size < 0x4c)
ERR_EXIT("xml: too many partitions\n");
buf_size -= 0x4c;
memset(buf, 0, 36 * 2);
for (i = 0; (a = name[i]); i++) buf[i * 2] = a;
if (!i) ERR_EXIT("empty partition name\n");
WRITE32_LE(buf + 0x48, size);
buf += 0x4c;
DBG_LOG("[%d] %s, %d\n", found, name, (int)size);
found++;
}
if (p - 1 != src + size) ERR_EXIT("xml: zero byte");
if (stage != 2) ERR_EXIT("xml: unexpected syntax\n");
free(src);
return found;
}
#define SECTOR_SIZE 512
#define MAX_SECTORS 32
extern int selected_ab;
int gpt_info(partition_t* ptable, const char* fn_xml, int* part_count_ptr) {
FILE* fp;
if (savepath[0]) {
char fix_fn[1024];
sprintf(fix_fn, "%s/pgpt.bin", savepath);
fp = fopen(fix_fn, "rb");
}
else fp = fopen("pgpt.bin", "rb");
if (fp == NULL) {
return -1;
}
efi_header header;
int bytes_read;
uint8_t buffer[SECTOR_SIZE];
int sector_index = 0;
int found = 0;
while (sector_index < MAX_SECTORS) {
bytes_read = fread(buffer, 1, SECTOR_SIZE, fp);
if (bytes_read != SECTOR_SIZE) {
fclose(fp);
return -1;
}
if (memcmp(buffer, "EFI PART", 8) == 0) {
memcpy(&header, buffer, sizeof(header));
found = 1;
break;
}
sector_index++;
}
if (found == 0) {
fclose(fp);
return -1;
}
else {
if (sector_index == 1) Da_Info.dwStorageType = 0x102;
else Da_Info.dwStorageType = 0x103;
}
int real_SECTOR_SIZE = SECTOR_SIZE * sector_index;
efi_entry* entries = malloc(header.number_of_partition_entries * sizeof(efi_entry));
if (entries == NULL) {
fclose(fp);
return -1;
}
fseek(fp, (long)header.partition_entry_lba * real_SECTOR_SIZE, SEEK_SET);
bytes_read = fread(entries, 1, header.number_of_partition_entries * sizeof(efi_entry), fp);
if (bytes_read != (int)(header.number_of_partition_entries * sizeof(efi_entry)))
DBG_LOG("only read %d/%d\n", bytes_read, (int)(header.number_of_partition_entries * sizeof(efi_entry)));
FILE* fo = NULL;
if (strcmp(fn_xml, "-")) {
fo = fopen(fn_xml, "wb");
if (!fo) ERR_EXIT("fopen failed\n");
fprintf(fo, "<Partitions>\n");
}
int n = 0;
for (int i = 0; i < header.number_of_partition_entries; i++) {
efi_entry entry = *(entries + i);
if (entry.starting_lba == 0 && entry.ending_lba == 0) {
n = i;
break;
}
}
DBG_LOG(" 0 %36s 256KB\n", "splloader");
for (int i = 0; i < n; i++) {
efi_entry entry = *(entries + i);
copy_from_wstr((*(ptable + i)).name, 36, (uint16_t*)entry.partition_name);
uint64_t lba_count = entry.ending_lba - entry.starting_lba + 1;
(*(ptable + i)).size = lba_count * real_SECTOR_SIZE;
DBG_LOG("%3d %36s %7lldMB\n", i + 1, (*(ptable + i)).name, ((*(ptable + i)).size >> 20));
if (fo) {
fprintf(fo, " <Partition id=\"%s\" size=\"", (*(ptable + i)).name);
if (i + 1 == n) fprintf(fo, "0x%x\"/>\n", ~0);
else fprintf(fo, "%lld\"/>\n", ((*(ptable + i)).size >> 20));
}
if (!selected_ab) {
size_t namelen = strlen((*(ptable + i)).name);
if (namelen > 2 && 0 == strcmp((*(ptable + i)).name + namelen - 2, "_a")) selected_ab = 1;
}
}
if (fo) {
fprintf(fo, "</Partitions>");
fclose(fo);
}
free(entries);
fclose(fp);
*part_count_ptr = n;
DBG_LOG("standard gpt table saved to pgpt.bin\n");
DBG_LOG("skip saving sprd partition list packet\n");
return 0;
}
extern int gpt_failed;
partition_t* partition_list(spdio_t* io, const char* fn, int* part_count_ptr) {
long size;
unsigned i, n = 0;
int ret; FILE* fo = NULL; uint8_t* p;
partition_t* ptable = malloc(128 * sizeof(partition_t));
if (ptable == NULL) return NULL;