-
Notifications
You must be signed in to change notification settings - Fork 43
/
newflasher.c
5415 lines (4632 loc) · 129 KB
/
newflasher.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
/*
* Copyright (C) 2017 Munjeni
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "version.h"
#if (!defined(_WIN32)) && (!defined(WIN32))
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64 1
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64 1
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE 1
#endif
#ifndef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 64
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#ifdef _WIN32
#define __USE_MINGW_ANSI_STDIO 1
#include <windows.h>
#include <setupapi.h>
#include <initguid.h>
#include "GordonGate.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#ifdef HAS_STDINT_H
#include <stdint.h>
#endif
#include <stdbool.h>
#ifdef unix
#include <unistd.h>
#include <sys/types.h>
#endif
#ifdef _WIN32
#include <direct.h>
#include <io.h>
#endif
#if defined(USE_FILE32API)
#define fopen64 fopen
#define ftello64 ftell
#define fseeko64 fseek
#else
#ifdef __FreeBSD__
#define fopen64 fopen
#define ftello64 ftello
#define fseeko64 fseeko
#endif
/*#ifdef __ANDROID__
#define fopen64 fopen
#define ftello64 ftello
#define fseeko64 fseeko
#endif*/
#ifdef _MSC_VER
#define fopen64 fopen
#if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC)))
#define ftello64 _ftelli64
#define fseeko64 _fseeki64
#else /* old msc */
#define ftello64 ftell
#define fseeko64 fseek
#endif
#endif
#endif
#include <ctype.h>
#include <sys/stat.h>
#include <limits.h>
#include <time.h>
#include <dirent.h>
#include <assert.h>
#if !defined(_WIN32) && !defined(__APPLE__)
#include <linux/usbdevice_fs.h>
#include <linux/usb/ch9.h>
#include <asm/byteorder.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <ctype.h>
#endif
#ifdef __APPLE__
#include <unistd.h>
//#include <CoreFoundation/CoreFoundation.h>
//#include <IOKit/IOKitLib.h>
//#include <IOKit/IOCFPlugIn.h>
//#include <IOKit/usb/IOUSBLib.h>
//#include <mach/mach.h>
#include "libusb.h"
#define fseeko64 fseeko
#define ftello64 ftello
#define fopen64 fopen
#endif
#include "expat.h"
#include "zlib.h"
#ifdef XML_LARGE_SIZE
#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
#define XML_FMT_INT_MOD "I64"
#else
#define XML_FMT_INT_MOD "ll"
#endif
#else
#define XML_FMT_INT_MOD "l"
#endif
#ifdef _WIN32
#define sleep Sleep
#define ONESEC 1000
#else
#define ONESEC 1
#endif
#define ENABLE_DEBUG 1
#if ENABLE_DEBUG
#define LOG printf
#else
#define LOG(...)
#endif
#define BUFF_MAX 0x800000
#define MAX_UNIT_LINE_LEN 0x80000
static char tmp[4096];
static char tmp_reply[BUFF_MAX];
static unsigned long get_reply_len;
static bool okay_replied = false;
static char product[12];
static char version[64];
static char version_bootloader[64];
static char version_baseband[64];
static char serialno[64];
static char secure[32];
static unsigned int sector_size = 0;
static unsigned int max_download_size = 0;
static char loader_version[64];
static char phone_id[64];
static char device_id[64];
static char rooting_status[32];
static char ufs_info[64];
static char emmc_info[64];
static bool have_ufs = false;
static char default_security[16];
static char platform_id[64];
static unsigned int keystore_counter = 0;
static char security_state[128];
static char s1_root[64];
static char sake_root[16];
static char get_root_key_hash[0x41];
static char slot_count[2];
static char current_slot[2];
static char remember_current_slot[2];
static unsigned int something_flashed = 0;
static bool is_2021_device = false;
static unsigned int battery_level = 0;
int is_big_endian(void)
{
union {
unsigned int i;
char c[4];
} e = { 0x01000000 };
return e.c[0];
}
unsigned int swap_uint32(unsigned int val)
{
if (is_big_endian())
return val;
val = ((val << 8) & 0xFF00FF00 ) | ((val >> 8) & 0xFF00FF);
return ((val << 16) | (val >> 16)) & 0xffffffff;
}
unsigned long long swap_uint64(unsigned long long val)
{
if (is_big_endian())
return val;
val = ((val << 8) & 0xFF00FF00FF00FF00ULL) | ((val >> 8) & 0x00FF00FF00FF00FFULL);
val = ((val << 16) & 0xFFFF0000FFFF0000ULL) | ((val >> 16) & 0x0000FFFF0000FFFFULL);
return ((val << 32) | (val >> 32)) & 0xffffffffffffffffULL;
}
void fread_unus_res(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t in;
in = fread(ptr, size, nmemb, stream);
if (in) {
/* satisfy warn unused result */
}
}
unsigned int file_size(char *filename) {
unsigned int size;
FILE *fp = fopen(filename, "rb");
if (fp == NULL) {
return 0;
}
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
fclose(fp);
return size;
}
static int file_exist(char *file) {
int ret;
FILE *f = NULL;
if ((f = fopen64(file, "rb")) == NULL) {
ret = 0;
} else {
fclose(f);
ret = 1;
}
return ret;
}
static void remove_file_exist(char *file) {
if (file_exist(file)) {
remove(file);
}
}
static char *basenamee(char *in) {
char *ssc;
int p = 0;
ssc = strstr(in, "/");
if (ssc == NULL) {
ssc = strstr(in, "\\");
if(ssc == NULL) {
return in;
}
}
do {
p = strlen(ssc) + 1;
in = &in[strlen(in)-p+2];
ssc = strstr(in, "/");
if (ssc == NULL)
ssc = strstr(in, "\\");
} while(ssc);
return in;
}
static ssize_t g_getline(char **lineptr, size_t *n, FILE *stream) {
char *cur_pos, *new_lineptr;
int c;
size_t new_lineptr_len;
if (lineptr == NULL || n == NULL || stream == NULL) {
errno = EINVAL;
printf("Error: EINVAL!\n");
return -1;
}
if (*lineptr == NULL) {
*n = MAX_UNIT_LINE_LEN;
if ((*lineptr = (char *)malloc(*n)) == NULL) {
errno = ENOMEM;
printf("Error: MAX_UNIT_LINE_LEN reached!\n");
return -1;
}
}
cur_pos = *lineptr;
for (;;) {
c = getc(stream);
if (ferror(stream) || (c == EOF && cur_pos == *lineptr))
return -1;
if (c == EOF)
break;
if ((*lineptr + *n - cur_pos) < 2) {
if (SSIZE_MAX / 2 < *n) {
#ifdef EOVERFLOW
errno = EOVERFLOW;
#else
errno = ERANGE; /* no EOVERFLOW defined */
#endif
printf("Error: EOVERFLOW!\n");
return -1;
}
new_lineptr_len = *n * 2;
if ((new_lineptr = (char *)realloc(*lineptr, new_lineptr_len)) == NULL) {
errno = ENOMEM;
printf("Error: ENOMEM for realloc!\n");
return -1;
}
*lineptr = new_lineptr;
*n = new_lineptr_len;
}
*cur_pos++ = c;
if (c == '\r' || c == '\n')
break;
}
*cur_pos = '\0';
return (ssize_t)(cur_pos - *lineptr);
}
static void trim(char *ptr) {
int i = 0;
int j = 0;
while(ptr[j] != '\0') {
if(ptr[j] == 0x20 || ptr[j] == 0x09 || ptr[j] == '\n' || ptr[j] == '\r') {
++j;
ptr[i] = ptr[j];
} else {
ptr[i] = ptr[j];
++i;
++j;
}
}
ptr[i] = '\0';
}
// 2 minute
#define USB_TIMEOUT 120000
#ifndef _WIN32
static char *TEXT(char *what) {
return what;
}
void DisplayError(char *title)
{
printf("%s\n%s\n", title, strerror(errno));
}
#else
#define StringCchPrintf(str, n, format, ...) snprintf((char *)str, n, (char const *)format, __VA_ARGS__)
void DisplayError(LPTSTR lpszFunction)
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL );
lpDisplayBuf =
(LPVOID)LocalAlloc( LMEM_ZEROINIT,
( lstrlen((LPCTSTR)lpMsgBuf)
+ lstrlen((LPCTSTR)lpszFunction)
+ 40) /* account for format string */
* sizeof(TCHAR) );
if (FAILED( StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error code %lu as follows:\n%s"),
lpszFunction,
dw,
(char *)lpMsgBuf)))
{
printf("FATAL ERROR: Unable to output error code.\n");
}
printf("ERROR: %s\n", (LPCTSTR)lpDisplayBuf);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
#endif
#ifdef _WIN32
static char *uint16_to_vidpidstring(unsigned short VID, unsigned short PID)
{
static char temp[18];
snprintf(temp, sizeof(temp), "vid_%x%x%x%x&pid_%x%x%x%x",
(VID>>12)&0xf, (VID>>8)&0xf, (VID>>4)&0xf, VID&0xf,
(PID>>12)&0xf, (PID>>8)&0xf, (PID>>4)&0xf, PID&0xf);
return temp;
}
#endif
static void to_ascii(char *dest, const char *text) {
unsigned long int ch;
for(; sscanf((const char *)text, "%02lx", &ch)==1; text+=2)
*dest++ = ch;
*dest = 0;
}
static void to_uppercase(char *ptr) {
for ( ; *ptr; ++ptr) *ptr = toupper(*ptr);
}
static void display_buffer_hex_ascii(char *message, char *buffer, unsigned int size) {
unsigned int i, j, k;
LOG("%s[0x%X]:\n", message, size);
for (i=0; i<size; i+=16) {
LOG("\n %08X ", i);
for(j=0,k=0; k<16; j++,k++) {
if (i+j < size) {
LOG("%02X", buffer[i+j] & 0xff);
} else {
LOG(" ");
}
LOG(" ");
}
LOG(" ");
for(j=0,k=0; k<16; j++,k++) {
if (i+j < size) {
if ((buffer[i+j] < 32) || (buffer[i+j] > 126)) {
LOG(".");
} else {
LOG("%c", buffer[i+j]);
}
}
}
}
LOG("\n\n" );
}
#define EP_IN 0
#define EP_OUT 1
#ifdef _WIN32
static GUID GUID_DEVINTERFACE_USB_DEVICE = {0xA5DCBF10L, 0x6530, 0x11D2, {0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED}};
HDEVINFO hDevInfo;
#else
#ifdef __APPLE__
typedef struct libusb_device_handle *HANDLE;
#define CloseHandle libusb_close
#define SetupDiDestroyDeviceInfoList(...)
int32_t OSAtomicDecrement32Barrier(volatile int32_t *__theValue) { return 0; }
int32_t OSAtomicIncrement32Barrier(volatile int32_t *__theValue) { return 0; }
int endpoint_in = 0x81, endpoint_out = 0x01; // default IN and OUT endpoints
#else
#define SetupDiDestroyDeviceInfoList(...)
/* The max bulk size for linux is 16384 which is defined
* in drivers/usb/core/devio.c.
*/
#define MAX_USBFS_BULK_SIZE 4096
/*(16 * 1024)*/
struct usb_handle
{
char fname[64];
int desc;
unsigned char ep_in;
unsigned char ep_out;
};
typedef struct usb_handle *HANDLE;
static inline int badname(const char *name)
{
while (*name) {
if (!isdigit(*name++))
return 1;
}
return 0;
}
static int get_vidpid(int fd, unsigned short VID, unsigned short PID)
{
struct usb_device_descriptor *dev;
char desc[1024];
int n;
if ((n = read(fd, desc, sizeof(desc))) == 0)
return 0;
dev = (void *)desc;
/*printf("found vid: %04x\n", dev->idVendor);
printf("found pid: %04x\n", dev->idProduct);*/
if (dev->idVendor != VID || dev->idProduct != PID)
return 0;
return 1;
}
struct usb_handle *get_flashmode(unsigned short VID, unsigned short PID)
{
char busname[64], devname[64];
DIR *busdir, *devdir;
struct dirent *de;
int fd;
int found_usb = 0;
int n;
int ifc;
struct usb_handle *usb = NULL;
busdir = opendir("/dev/bus/usb");
if (busdir == NULL) {
printf("Error, no /dev/bus/usb ! Please connect device first in flash mode!\n");
return usb;
}
/*printf("busdir: %p\n", busdir);*/
while ((de = readdir(busdir)) && (found_usb == 0)) {
/*printf("dirent: %p\n", de);*/
if (badname(de->d_name))
continue;
snprintf(busname, sizeof(busname), "%s/%s", "/dev/bus/usb", de->d_name);
/*printf("busname: %s\n", busname);*/
devdir = opendir(busname);
while ((de = readdir(devdir)) && (found_usb == 0)) {
if (badname(de->d_name))
continue;
snprintf(devname, sizeof(devname), "%s/%s", busname, de->d_name);
/*printf("devname: %s\n", devname);*/
if ((fd = open(devname, O_RDWR)) < 1) {
printf("cannot open %s for writing\n", devname);
continue;
}
if (get_vidpid(fd, VID, PID)) {
printf("found device with vid:0x%04x pid:0x%04x.\n", VID, PID);
usb = calloc(1, sizeof(struct usb_handle));
usb->ep_in = 0x81;
usb->ep_out = 0x01;
usb->desc = fd;
ifc = 0;
if ((n = ioctl(fd, USBDEVFS_CLAIMINTERFACE, &ifc)) != 0) {
printf("ERROR: n = %d, errno = %d (%s)\n",
n, errno, strerror(errno));
closedir(devdir);
closedir(busdir);
return NULL;
}
found_usb = 1;
}
}
closedir(devdir);
}
closedir(busdir);
return usb;
}
int usb_close(struct usb_handle *h)
{
int fd;
fd = h->desc;
h->desc = -1;
if (fd >= 0) {
close(fd);
/*printf("usb closed %d\n", fd);*/
}
return 0;
}
#define CloseHandle usb_close
#endif
#endif
#ifdef _WIN32
static char *open_dev(unsigned short VID, unsigned short PID)
{
SP_DEVICE_INTERFACE_DATA DevIntfData;
PSP_DEVICE_INTERFACE_DETAIL_DATA DevIntfDetailData;
SP_DEVINFO_DATA DevData;
unsigned long dwSize, dwMemberIdx;
static char devicePath[MAX_PATH];
char szDescription[MAX_PATH];
int ret = 1;
char *vidpid = uint16_to_vidpidstring(VID, PID);
memset(devicePath, 0, sizeof(devicePath));
hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, NULL, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (hDevInfo != INVALID_HANDLE_VALUE)
{
DevIntfData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
dwMemberIdx = 0;
SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &GUID_DEVINTERFACE_USB_DEVICE, dwMemberIdx, &DevIntfData);
while(GetLastError() != ERROR_NO_MORE_ITEMS)
{
DevData.cbSize = sizeof(DevData);
SetupDiGetDeviceInterfaceDetail(hDevInfo, &DevIntfData, NULL, 0, &dwSize, NULL);
DevIntfDetailData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize);
DevIntfDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &DevIntfData, DevIntfDetailData, dwSize, &dwSize, &DevData))
{
if (strstr(DevIntfDetailData->DevicePath, vidpid) != NULL)
{
strncpy(devicePath, DevIntfDetailData->DevicePath, strlen(DevIntfDetailData->DevicePath));
printf("Device path: %s\n", devicePath);
memset(szDescription, 0, MAX_PATH);
SetupDiGetClassDescription(&DevData.ClassGuid, szDescription, MAX_PATH, &dwSize);
printf("Class Description: %s\n", szDescription);
memset(szDescription, 0, MAX_PATH);
SetupDiGetDeviceInstanceId(hDevInfo, &DevData, szDescription, MAX_PATH, 0);
printf("Device Instance Id: %s\n\n", szDescription);
ret = 0;
}
}
HeapFree(GetProcessHeap(), 0, DevIntfDetailData);
/* Continue looping */
SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &GUID_DEVINTERFACE_USB_DEVICE, ++dwMemberIdx, &DevIntfData);
if (ret == 0)
break;
}
if (ret)
SetupDiDestroyDeviceInfoList(hDevInfo);
}
return devicePath;
}
static unsigned long transfer_bulk_async(HANDLE dev, int ep, char *bytes, unsigned long size, int timeout, int exact)
{
static unsigned long nBytesRead = 0;
BOOL bResult;
unsigned char progress = 0;
time_t start = time(NULL);
OVERLAPPED gOverLapped_in = {
.Internal = 0,
.InternalHigh = 0,
.Offset = 0,
.OffsetHigh = 0
};
OVERLAPPED gOverLapped_out = {
.Internal = 0,
.InternalHigh = 0,
.Offset = 0,
.OffsetHigh = 0
};
if (ep == EP_IN)
{
nBytesRead = 0;
gOverLapped_in.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (NULL == gOverLapped_in.hEvent)
{
DisplayError(TEXT("Error creating overlaped_in hEvent!"));
return 0;
}
else
{
bResult = ReadFile(dev, bytes, size, NULL, &gOverLapped_in);
if (!bResult)
{
switch(GetLastError())
{
case ERROR_HANDLE_EOF:
{
/* we have reached the end of the file during the call to ReadFile */
DisplayError(TEXT("HANDLE_EOF:"));
break;
}
case ERROR_IO_PENDING:
{
/* asynchronous i/o is still in progress */
switch(WaitForSingleObject(gOverLapped_in.hEvent, timeout))
{
case WAIT_OBJECT_0:
/* check on the results of the asynchronous read and update the nBytesRead... */
do
{
// https://docs.microsoft.com/en-us/windows/win32/api/ioapiset/nf-ioapiset-getoverlappedresult
bResult = GetOverlappedResult(dev, &gOverLapped_in, &nBytesRead, FALSE);
if (time(NULL)-start > 5)
{
start = time(NULL);
progress += 1;
printf(".");
if (progress == 60)
{
progress = 0;
printf("\n");
}
}
}
while(!bResult && ERROR_IO_INCOMPLETE == GetLastError());
if (!bResult)
DisplayError(TEXT("GetOverlapped_in_Result:"));
break;
case WAIT_TIMEOUT:
DisplayError(TEXT("TIMEOUT:"));
CancelIo(dev);
break;
default:
DisplayError(TEXT("ERROR_IO_PENDING OTHER:"));
CancelIo(dev);
break;
}
}
case ERROR_SUCCESS:
{
//printf("io read succed.\n");
CancelIo(dev);
break;
}
default:
{
DisplayError(TEXT("IO_OTHER:"));
CancelIo(dev);
break;
}
}
}
ResetEvent(gOverLapped_in.hEvent);
CloseHandle(gOverLapped_in.hEvent);
}
}
if (ep == EP_OUT)
{
nBytesRead = 0;
gOverLapped_out.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (NULL == gOverLapped_out.hEvent) {
DisplayError(TEXT("Error creating overlaped_in hEvent!"));
return 0;
}
else
{
bResult = WriteFile(dev, bytes, size, NULL, &gOverLapped_out);
if(!bResult)
{
switch (GetLastError())
{
case ERROR_HANDLE_EOF:
{
/* we have reached the end of the file during the call to ReadFile */
DisplayError(TEXT("HANDLE_EOF:"));
break;
}
case ERROR_IO_PENDING:
{
/* asynchronous i/o is still in progress */
switch(WaitForSingleObject(gOverLapped_out.hEvent, timeout))
{
case WAIT_OBJECT_0:
/* check on the results of the asynchronous read and update the nBytesRead... */
do
{
// https://docs.microsoft.com/en-us/windows/win32/api/ioapiset/nf-ioapiset-getoverlappedresult
bResult = GetOverlappedResult(dev, &gOverLapped_out, &nBytesRead, FALSE);
if (time(NULL)-start > 5)
{
start = time(NULL);
progress += 1;
printf(".");
if (progress == 60)
{
progress = 0;
printf("\n");
}
}
}
while(!bResult && ERROR_IO_INCOMPLETE == GetLastError());
if (!bResult)
DisplayError(TEXT("GetOverLapped_out_Result:"));
break;
case WAIT_TIMEOUT:
DisplayError(TEXT("TIMEOUT:"));
CancelIo(dev);
break;
default:
DisplayError(TEXT("ERROR_IO_PENDING OTHER:"));
CancelIo(dev);
break;
}
}
case ERROR_SUCCESS:
{
//printf("io write succed.\n");
CancelIo(dev);
break;
}
default:
{
DisplayError(TEXT("IO_OTHER:"));
CancelIo(dev);
break;
}
}
}
ResetEvent(gOverLapped_out.hEvent);
CloseHandle(gOverLapped_out.hEvent);
}
}
if (exact) {
if (nBytesRead != size) {
printf(" - Error %s! Need nBytes: 0x%lx but done: 0x%lx\n", (ep == EP_IN) ? "read" : "write", size, nBytesRead);
display_buffer_hex_ascii("nBytes", bytes, nBytesRead);
return 0;
}
}
#if 0
if (ep == EP_IN && nBytesRead) {
printf(" - Successfully read 0x%lx bytes from handle.\n", nBytesRead);
display_buffer_hex_ascii("Raw input ", bytes, nBytesRead);
}
if (ep == EP_OUT && nBytesRead) {
printf(" - Successfully write 0x%lx bytes to handle.\n", nBytesRead);
//display_buffer_hex_ascii("Raw output ", bytes, nBytesRead);
}
#endif
return nBytesRead;
}
#else
#ifdef __APPLE__
static unsigned long transfer_bulk_async(HANDLE dev, int ep, char *bytes, unsigned long size, int timeout, int exact)
{
int res = 0;
int try = 0;
int actual_length = 0;
if (ep == EP_IN)
{
do {
res = libusb_bulk_transfer(dev, endpoint_in, (unsigned char *)bytes, size, &actual_length, timeout);
if (res == LIBUSB_ERROR_PIPE)
{
int halt = libusb_clear_halt(dev, endpoint_in);
if (halt != LIBUSB_SUCCESS)
{
printf("clear halt (in): %s\n", libusb_error_name(halt));
}
else
{
printf("halt clear after: %d\n", try);
}
}
try++;
} while ((res == LIBUSB_ERROR_PIPE) && (try < 3));
if (res != LIBUSB_SUCCESS)
{
printf("bulk transfer (in): %s\n", libusb_error_name(res));
return 0;
}
}
if (ep == EP_OUT)
{
do {
res = libusb_bulk_transfer(dev, endpoint_out, (unsigned char *)bytes, size, &actual_length, timeout);
if (res == LIBUSB_ERROR_PIPE)
{
int halt = libusb_clear_halt(dev, endpoint_out);
if (halt != LIBUSB_SUCCESS)
{
printf("clear halt (out): %s\n", libusb_error_name(halt));
}
else
{
printf("halt clear after: %d\n", try);
}
}
try++;
} while ((res == LIBUSB_ERROR_PIPE) && (try < 3));
if (res != LIBUSB_SUCCESS)
{
printf("bulk transfer (out): %s\n", libusb_error_name(res));
return 0;
}
}
if (exact)
{
if ((unsigned long)actual_length != size)
{
printf(" - Error %s! Need nBytes: 0x%lx but done: 0x%lx\n", (ep == EP_IN) ? "read" : "write", size, (unsigned long)actual_length);
display_buffer_hex_ascii("nBytes", bytes, actual_length);
return 0;
}
}
return (unsigned long)actual_length;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#else
static unsigned long transfer_bulk_async(struct usb_handle *h, int ep, const void *_bytes, unsigned long size, int timeout, int exact)
{
char *bytes = (char *)_bytes;
unsigned long count = 0;
unsigned long size_tot = size;
struct usbdevfs_bulktransfer bulk;
int n = 0;
if (ep == EP_IN)