What's new? | Help | Directory | Sign in
Google
             
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
/*
amoxiflash -- NAND Flash chip programmer utility, using the Infectus 1 / 2 chip
Copyright (C) 2008 bushing

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

For more information, contact bushing@gmail.com, or see http://code.google.com/p/amoxiflash
*/

#define VERSION "0.4"

#include <stdio.h>
#include <math.h>
#include <inttypes.h>
#include <usb.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <sys/time.h>
#include "amoxiflash.h"

#ifdef __MINGW32__
#define fseeko fseeko64
#define ftello ftello64
#define usleep(x) _sleep((x)/1000)
#endif

#define ENDPOINT_READ 0x81
#define ENDPOINT_WRITE 1

#define INFECTUS_NAND_CMD 0x4e
#define INFECTUS_NAND_SEND 0x1
#define INFECTUS_NAND_RECV 0x2

#define NAND_RESET 0xff
#define NAND_CHIPID 0x90
#define NAND_GETSTATUS 0x70
#define NAND_ERASE_PRE 0x60
#define NAND_ERASE_POST 0xd0
#define NAND_READ_PRE 0x00
#define NAND_READ_POST 0x30
#define NAND_WRITE_PRE 0x80
#define NAND_WRITE_POST 0x10

#define PAGEBUF_SIZE 4096

usb_dev_handle *locate_infectus(void);

struct usb_dev_handle *h;
struct timeval tv1, tv2;
char *progname;

int run_fast = 0;
int subpage_size = 0x2c0;
int page_size = 2048;
int spare_size = 64;
int num_blocks = 4096;
int pages_per_block = 64;
int verify_after_write = 1;
int chip_select = 0;
int force = 0;
int debug_mode = 0;
int test_mode = 0;
int check_status = 0;
int start_block = 0;
int quick_check = 0;

u32 start_time = 0;
u32 blocks_done = 0;

char *spinner_chars="/-\\|";
int spin = 0;

void draw_spin(void) {
printf("\b%c", spinner_chars[spin++]);
fflush(stdout);
if(!spinner_chars[spin]) spin=0;
}

static const char *pld_ids[] = {
"O2MOD",
"Globe Hitachi",
"Globe Samsung",
"Infectus 78",
"NAND Programmer",
"2 NAND Programmer",
"SPI Programmer",
"XDowngrader"
};


void timer_start(void) {
gettimeofday(&tv1, NULL);
}

unsigned long long timer_end(void) {
unsigned long long retval;
gettimeofday(&tv2, NULL);
retval = (tv2.tv_sec - tv1.tv_sec) * 1000000ULL;
retval += tv2.tv_usec - tv1.tv_usec;
return retval;
}

char ascii(char s) {
if(s < 0x20) return '.';
if(s > 0x7E) return '.';
return s;
}

void hexdump(void *d, int len) {
u8 *data;
int i, off;
data = (u8*)d;
for (off=0; off<len; off += 16) {
printf("%08x ",off);
for(i=0; i<16; i++)
if((i+off)>=len) printf(" ");
else printf("%02x ",data[off+i]);

printf(" ");
for(i=0; i<16; i++)
if((i+off)>=len) printf(" ");
else printf("%c",ascii(data[off+i]));
printf("\n");
}
}

int infectus_sendcommand(u8 *buf, int len, int maxsize) {
if (debug_mode) {
printf("> "); hexdump(buf, len);
}

int ret = 0;
start:
while (ret < len) {
ret = usb_bulk_write(h, ENDPOINT_WRITE, (char *)buf, len, 500);
if (ret < 0) {
printf("Error %d sending command: %s\n", ret, usb_strerror());
return ret;
}
if (ret != len) {
printf("Error: short write (%d < %d)\n", ret, len);
}
}

ret=usb_bulk_read(h, ENDPOINT_READ, (char *)buf, maxsize, 500);
if(ret < 0) {
printf("Error reading reply: %d\n", ret);
return ret;
}

if (debug_mode) {
printf("< ");
hexdump(buf, ret);
}

if(buf[0] != 0xFF) {
printf("Reply began with %02x, expected ff\n", buf[0]);
goto start;
}
buf++; // skip initial FF

if (debug_mode && ret > 0) hexdump(buf, ret);
// usleep(1000);
return ret;
}

int infectus_nand_command(u8 *command, unsigned int len, ...) {
int i;
va_list ap;
va_start(ap, len);
memset(command, 0, len+9);
command[0]=INFECTUS_NAND_CMD;
command[7]=len;
for(i=0; i<=len; i++) {
command[i+8]=va_arg(ap,int) & 0xff;
}
va_end(ap);
return len+9;
}

int infectus_nand_receive(u8 *buf, int len) {
memset(buf, 0, 8);
buf[0] = INFECTUS_NAND_CMD;
buf[1] = INFECTUS_NAND_RECV;
buf[6] = (len >> 8) & 0xff;
buf[7] = len & 0xff;
return infectus_sendcommand(buf, 8, len+3);
}

int infectus_nand_send(u8 *buf, int len) {
u8 temp_buf[PAGEBUF_SIZE];
memset(temp_buf, 0, sizeof temp_buf);

memcpy(temp_buf, "\x4e\x01\x00\x00\x00\x00", 8);
temp_buf[6] = len/256;
temp_buf[7] = len%256;
memcpy(temp_buf+8, buf, len);

int retval = infectus_sendcommand(temp_buf, len+8, PAGEBUF_SIZE);
if (retval < 0) return retval;
if (retval > len) retval = len - 1;
memcpy(buf, temp_buf, retval);
return retval;
}

int infectus_reset(void) {
u8 buf[128];
int ret;

ret = usb_set_configuration(h,1);
if (ret) printf("conf_stat=%d\n",ret);

if (ret == -1) {
printf("Unable to set USB device configuration; are you running as root?\n");
exit(0);
}

/* Initialize "USB stuff" */
ret = usb_claim_interface(h,0);
if (ret) printf("claim_stat=%d\n",ret);

ret = usb_set_altinterface(h,0);
if (ret) printf("alt_stat=%d\n",ret);

ret = usb_clear_halt(h, ENDPOINT_READ);
if (ret) printf("usb_clear_halt(%x)=%d (%s)\n", ENDPOINT_READ, ret, usb_strerror());

/* What does this do? */
ret = usb_control_msg(h, USB_TYPE_VENDOR + USB_RECIP_DEVICE,
2, 2, 0, (char *)buf, 0, 1000);
if (ret) printf("usb_control_msg(2)=%d\n", ret);

/* Send Infectus reset command */
ret = 0;
while(ret == 0) {
memcpy(buf, "\x45\x15\x00\x00\x00\x00\x00\x00", 8);
ret = infectus_sendcommand(buf, 8, 128);
}
return 0;
}

/* Version part 1: ? */
int infectus_get_version(void) {
u8 buf[128];
int ret;
memcpy(buf, "\x45\x13\x01\x00\x00\x00\x00\x00", 8);

ret=infectus_sendcommand(buf, 8, 128);
printf("Infectus version (?) = %hhx\n", buf[1]);
// hexdump(buf, ret);
return 0;
}

/* Version part 2: loader version */
int infectus_get_loader_version(void) {
u8 buf[128];
int ret;
memcpy(buf, "\x4c\x07\x00\x00\x00\x00\x00\x00", 8);

ret = infectus_sendcommand(buf, 8, 128);
printf("Infectus Loader version = %hhu.%hhu\n", buf[1], buf[2]);
// hexdump(buf, ret);
return 0;
}

int infectus_check_pld_id(void) {
u8 buf[128];
int ret;
memcpy(buf, "\x4c\x15\x00\x00\x00\x00\x00\x00", 8);

ret = infectus_sendcommand(buf, 8, 128);
if (ret < 0) return ret;
if (buf[1] > (sizeof pld_ids)/4) {
fprintf(stderr, "Unknown PLD ID %d\n", buf[1]);
} else {
printf("PLD ID: %s\n", pld_ids[buf[1]]);
}
/* if (buf[1] != 7 && buf[1] != 4) {
fprintf(stderr, "WARNING: If you experience problems, please try reprogramming the Infectus\n");
fprintf(stderr, "chip with the 'NAND Programmer' or 'XDowngrader' firmwares and try again.\n");
} */
return 0;
}

/* In a dual-NAND configuration, select one of the chips (generally 0 or 1) */
int infectus_selectflash(int which) {
u8 buf[128];
memcpy(buf, "\x45\x14\x00\x00\x00\x00\x00\x00", 8);
buf[2] = which;

infectus_sendcommand(buf, 8, 128);
return 0;
}

/* Get NAND flash chip status */
int infectus_getstatus(void) {
u8 buf[128];
int ret,len;

len=infectus_nand_command(buf, 0, NAND_GETSTATUS);
ret=infectus_sendcommand(buf, len, 128);

infectus_nand_receive(buf, 1);

return buf[1];
}

/* Wait for NAND flash to be ready */
void wait_flash(void) {
int status=0;
while (status != 0xc0) {
status = infectus_getstatus();
if(status != 0xc0) printf("Status = %x\n", status);
}
}

/* Query the first two bytes of the NAND flash chip ID.
Eventually, this should be used to select the appropriate parameters
to be used when talking to this chip. */

int infectus_getflashid(void) {
u8 buf[128];
int ret,len;

len=infectus_nand_command(buf, 0, NAND_RESET);
ret=infectus_sendcommand(buf, len, 128);

len=infectus_nand_command(buf, 1, NAND_CHIPID, 0);
ret=infectus_sendcommand(buf, len, 128);

infectus_nand_receive(buf, 2);

return buf[1] << 8 | buf[2];
}

/* Erase a block of flash memory. */
int infectus_eraseblock(unsigned int blockno) {
u8 buf[128];
unsigned int pageno = blockno * pages_per_block;
int ret, len;

if (test_mode) return 0;

len=infectus_nand_command(buf, 3, NAND_ERASE_PRE, pageno, pageno >> 8, pageno >> 16);
ret = infectus_sendcommand(buf, len, 128);
if (ret!=1) printf("Erase command returned %d\n", ret);

len=infectus_nand_command(buf, 0, NAND_ERASE_POST);
ret = infectus_sendcommand(buf, len, 128);

if (check_status) wait_flash();
return ret;
}


int infectus_readflashpage(u8 *dstbuf, unsigned int pageno) {
u8 buf[128];
u8 flash_buf[PAGEBUF_SIZE];
int ret, len, subpage;

len=infectus_nand_command(buf, 5, NAND_READ_PRE, 0,
0, pageno, pageno >> 8, pageno >> 16);
ret = infectus_sendcommand(buf, len, 128);

len=infectus_nand_command(buf, 0, NAND_READ_POST);
ret = infectus_sendcommand(buf, len, 128);

len = 0;
for(subpage = 0; subpage < ceil((float)(page_size + spare_size) / subpage_size); subpage++) {
ret = infectus_nand_receive(flash_buf, subpage_size);
if (ret!= (subpage_size+1)) printf("Readpage returned %d\n", ret);
memcpy(dstbuf + subpage*subpage_size, flash_buf+1, subpage_size);
len += ret-1;
}
return len;
}

int file_readflashpage(FILE *fp, u8 *dstbuf, unsigned int pageno) {
fseeko(fp, pageno * (page_size + spare_size), SEEK_SET);
return fread(dstbuf, 1, page_size + spare_size, fp);
}

int file_writeflashpage(FILE *fp, u8 *dstbuf, unsigned int pageno) {
fseeko(fp, pageno * (page_size + spare_size), SEEK_SET);
return fwrite(dstbuf, 1, (page_size + spare_size), fp);
}

int mem_compare(u8 *buf1, u8 *buf2, int size) {
int i;
for(i=0; i<size; i++) if(buf1[i] != buf2[i]) break;
return i;
}

int flash_compare(FILE *fp, unsigned int pageno) {
u8 buf1[PAGEBUF_SIZE], buf2[PAGEBUF_SIZE];
// u8 buf3[PAGEBUF_SIZE];
int x;
file_readflashpage(fp, buf1, pageno);
if (check_ecc(buf1)==ECC_WRONG) {
printf("warning, invalid ECC on disk for page %d\n", pageno);
}

infectus_readflashpage(buf2, pageno);
if (check_ecc(buf2)==ECC_WRONG) {
printf("warning, invalid ECC in flash for page %d\n", pageno);
}

if((x = memcmp(buf1, buf2, page_size + spare_size))) {
// printf("miscompare on page %d: \n", pageno);
// infectus_readflashpage(buf3, pageno);
// if(memcmp(buf2, buf3, sizeof buf3)) {
// printf("chip is on crack\n");
// }
}
return x;
}

int flash_isFF(u8 *buf, int len) {
unsigned int *p = (unsigned int *)buf;
int i;
len/=4;
for(i=0;i<len;i++) if(p[i]!=0xFFFFFFFF) return 0;
return 1;
}

int infectus_writeflashpage(u8 *dstbuf, unsigned int pageno) {
u8 buf[128];
int ret, len, subpage;

if (test_mode) return 0;

for(subpage = 0; subpage < ceil((float)(page_size + spare_size)/subpage_size); subpage++) {
len=infectus_nand_command(buf, 5, NAND_WRITE_PRE, subpage * subpage_size,
(subpage * subpage_size) >> 8 , pageno, pageno >> 8, pageno >> 16);
ret = infectus_sendcommand(buf, len, 128);

infectus_nand_send(dstbuf + subpage * subpage_size, subpage_size);

len=infectus_nand_command(buf, 0, NAND_WRITE_POST);
ret = infectus_sendcommand(buf, len, 128);

if (check_status) wait_flash();
}
return 0;
}

int flash_program_block(FILE *fp, unsigned int blockno) {
u8 buf[PAGEBUF_SIZE];
unsigned long long usec;
int pageno, p, miscompares=0;
printf("\r ");
printf("\r%04x", blockno); fflush(stdout);
timer_start();
for(pageno = run_fast?2:0; pageno < pages_per_block; pageno += (run_fast?0x4:1)) {
p = blockno*pages_per_block + pageno;
if (flash_compare(fp, p)) {
putchar('x');
miscompares++;
// if (run_fast) break; I can't think of a reason not to do this, so ...
break;
} else putchar('=');
fflush(stdout);
}
usec = timer_end();
float rate = (float)blocks_done / (time(NULL) - start_time);
int secs_remaining = (num_blocks - blockno) / rate;
if (blocks_done > 2) {
printf ("%04.1f%% ",blockno * 100.0 / num_blocks);
if (secs_remaining > 180) {
printf("%dm\r", secs_remaining/60);
} else {
printf("%ds\r", secs_remaining);
}
} else putchar('\r');
if (debug_mode) fprintf(stderr, "Read(%.3f)", usec / 1000000.0f);
putchar('\r');
if (miscompares > 0) {
// printf(" %d miscompares in block\n", miscompares);
printf("Erasing...");
infectus_eraseblock(blockno);
printf("\nProg: ");
timer_start();
for(pageno = 0; pageno < pages_per_block; pageno++) {
p = blockno*pages_per_block + pageno;
if (file_readflashpage(fp, buf, p)==(page_size + spare_size)) {
if(flash_isFF(buf, (page_size + spare_size))) {
putchar('F');
continue;
}
infectus_writeflashpage(buf, p);
if (verify_after_write) {
if (flash_compare(fp, p)) {
putchar('!');
} else putchar('.');
fflush(stdout);
}
}
}
usec = timer_end();
if (debug_mode) fprintf(stderr,"Write(%.3f)", usec / 1000000.0f);
putchar('\r');

}
blocks_done++;
return 0;
}

int flash_dump_block(FILE *fp, unsigned int blockno) {
u8 buf[PAGEBUF_SIZE];
int pageno, p, ret;
printf("\r ");
printf("\r%04x", blockno); fflush(stdout);

for(pageno = 0; pageno < pages_per_block; pageno++) {
p = blockno*pages_per_block + pageno;
ret = infectus_readflashpage(buf, p);
if (ret==(page_size + spare_size)) {
/* if (check_ecc(buf)==ECC_WRONG) {
printf("warning, invalid ECC for page %d\n", pageno);
} */
file_writeflashpage(fp, buf, p);
putchar('.');
fflush(stdout);
} else {
printf("error, short read: %d < %d\n", ret, page_size + spare_size);
}
}
float rate = (float)blocks_done / (time(NULL) - start_time);
int secs_remaining = (num_blocks - blockno) / rate;
if (blocks_done > 2) {
printf ("%04.1f%% ",blockno * 100.0 / num_blocks);
if (secs_remaining > 180) {
printf("%dm\r", secs_remaining/60);
} else {
printf("%ds\r", secs_remaining);
}
} else putchar('\r');
fflush(stdout);
blocks_done++;
return 0;
}

void usage(void) {
fprintf(stderr, "Usage: %s command -[tvwdf] [-b blocksize] filename\n", progname);
fprintf(stderr, " -t test mode -- do not erase or write\n");
fprintf(stderr, " -v verify every byte of written data\n");
fprintf(stderr, " -w wait for status after programming\n");
fprintf(stderr, " -x {0,1} on a dual NAND programmer, choose chip\n");
fprintf(stderr, " -f force: ignore safety checks. Dangerous!\n");
fprintf(stderr, " -d debug (enable debugging output)\n");
fprintf(stderr, " -b blocksize set blocksize; see docs for more info. Default: 0x%x\n", subpage_size);
fprintf(stderr, " -s blockno start block -- skip this number of blocks\n");
fprintf(stderr, " before proceeding\n");
fprintf(stderr, "\nValid commands are:\n");
fprintf(stderr, " check check ECC data in file\n");
fprintf(stderr, " strip strip ECC data from file\n");
fprintf(stderr, " sums calculate simple checksum for each page of a file\n");
fprintf(stderr, " dump read from flash chip and dump to file\n");
fprintf(stderr, " program compare file to flash contents, reprogram flash\n");
fprintf(stderr, " to match file\n");
fprintf(stderr, " erase erase the entire flash chip\n");

exit(1);
}

int strip_file_ecc(char *filename) {
u32 pageno;
if (!filename) {
fprintf(stderr, "Error: you must specify a filename to strip\n");
usage();
}

char *output_filename=malloc(strlen(filename)+5);
sprintf(output_filename, "%s.raw", filename);

FILE *fp = fopen(filename, "rb");
if(!fp) {
perror("Couldn't open input file: ");
exit(1);
}
fseek(fp, 0, SEEK_END);
off_t file_length = ftello(fp);
fseek(fp, 0, SEEK_SET);

if ((file_length % (page_size + spare_size)) && !force) {
printf("Error: File length is not a multiple of %d bytes. Are you sure\n",
page_size + spare_size);
printf("you want to do this? Pass -f to force.\n");
exit(1);
}

printf("Stripping ECC data from %s into %s\n", filename, output_filename);
FILE *fp_out = fopen(output_filename, "wb");
if(!fp_out) {
perror("Couldn't open output file: ");
exit(1);
}

u64 num_pages = file_length / (page_size + spare_size);
printf("File size: %"PRIu64" bytes / %"PRIu64" pages / %"PRIu64" blocks\n",
file_length, num_pages, num_pages / pages_per_block);

for (pageno=0; (pageno < num_pages) && !feof(fp); pageno++) {
u8 buf[PAGEBUF_SIZE];
if ((pageno % 2048)==0) {
printf ("\r%04.1f%% ", pageno * 100.0 / num_pages);
draw_spin();
}
fread(buf, 1, page_size + spare_size, fp);
fwrite(buf, 1, page_size, fp_out);
}
fclose(fp_out);
fclose(fp);
return 0;
}

int check_file_ecc(char *filename) {
u32 pageno;
u32 count_invalid=0, count_wrong=0, count_blank=0, count_ok=0;

if (!filename) {
fprintf(stderr, "Error: you must specify a filename to check\n");
usage();
}
printf("Checking ECC for file %s\n", filename);
start_time = time(NULL);
FILE *fp = fopen(filename, "rb");
if(!fp) {
perror("Couldn't open file: ");
exit(1);
}
fseek(fp, 0, SEEK_END);
off_t file_length = ftello(fp);
fseek(fp, 0, SEEK_SET);
u64 num_pages = file_length / (page_size + spare_size);
printf("File size: %"PRIu64" bytes / %"PRIu64" pages / %"PRIu64" blocks\n",
file_length, num_pages, num_pages / pages_per_block);
for (pageno = 0; pageno < num_pages && !feof(fp); pageno++) {
u8 buf[PAGEBUF_SIZE];
file_readflashpage(fp, buf, pageno);
if ((pageno % 2048)==0) {
printf ("\r%04.1f%% ", pageno * 100.0 / num_pages);
draw_spin();
}
switch (check_ecc(buf)) {
case ECC_OK:
count_ok++;
break;
case ECC_WRONG:
count_wrong++;
printf("%d: ecc WRONG\n", pageno);
printf("Stored ECC: "); hexdump(buf+page_size+48, 16);
printf("Calc ECC: "); hexdump(calc_page_ecc(buf), 16);
break;
case ECC_INVALID:
count_invalid++;
break;
case ECC_BLANK:
count_blank++;
break;
default: break;
}
}
fclose(fp);
printf("\nTotals: %u pages OK, %u pages WRONG, %u pages blank, %u pages unreadable\n",
count_ok, count_wrong, count_blank, count_invalid);
exit(0);
return 1;
}

/* Precomputed bitcount uses a precomputed array that stores the number of ones
in each char. */
static int bits_in_char [256] ;

/* Iterated bitcount iterates over each bit. The while condition sometimes helps
terminates the loop earlier */
int iterated_bitcount (unsigned int n)
{
int count=0;
while (n)
{
count += n & 0x1u ;
n >>= 1 ;
}
return count ;
}
void compute_bits_in_char (void)
{
unsigned int i ;
for (i = 0; i < 256; i++)
bits_in_char [i] = iterated_bitcount (i) ;
return ;
}

int generate_checksums(char *filename) {
u32 pageno;
char output_filename[1024];
compute_bits_in_char();

if (!filename) {
fprintf(stderr, "Error: you must specify a filename to check\n");
usage();
}
sprintf(output_filename, "%s.out", filename);
printf("Generating sums for file %s, outputting to %s\n", filename, output_filename);
start_time = time(NULL);
FILE *fp = fopen(filename, "rb");
if(!fp) {
perror("Couldn't open file: ");
exit(1);
}
fseek(fp, 0, SEEK_END);
off_t file_length = ftello(fp);
fseek(fp, 0, SEEK_SET);
u64 num_pages = file_length / (page_size + spare_size);
printf("File size: %"PRIu64" bytes / %"PRIu64" pages / %"PRIu64" blocks\n",
file_length, num_pages, num_pages / pages_per_block);

FILE *out_fp = fopen(output_filename, "w");
if(!fp) {
perror("Couldn't open output file: ");
exit(1);
}
for (pageno = 0; pageno < num_pages && !feof(fp); pageno++) {
u8 buf[PAGEBUF_SIZE];
int i;
unsigned int sum=0;
file_readflashpage(fp, buf, pageno);
for (i=0; i<page_size; i++) sum += bits_in_char[buf[i]];
fprintf(out_fp, "%x %x\n", pageno, sum);
if ((pageno % 2048)==0) {
printf ("\r%04.1f%% ", pageno * 100.0 / num_pages);
draw_spin();
}

}
fclose(fp);
fclose(out_fp);
exit(0);
return 1;
}


void usb_exit_handler(void) {
usb_close(h);
}

int check_file_validity(FILE *fp) {
u64 original_offset;
u64 file_size;
u8 header_magic[4];

original_offset = ftello(fp);
fseeko(fp, 0, SEEK_END);
file_size = ftello(fp);

if (file_size % (page_size + spare_size)) {
printf("WARNING: This file does not seem to be a valid dump file,\n");
printf(" because its filesize (%"PRIu64") is not a multiple of %d\n",
file_size, page_size + spare_size);
}

fseeko(fp, 0, SEEK_SET);
fread(header_magic, 1, 4, fp);

if (memcmp(header_magic, "\x27\xAE\x8C\x9C", 4)) {
printf("WARNING: This file does not seem to be a Wii firmware dump.\n");
}
fseeko(fp, original_offset, SEEK_SET);
return 0;
}

int main (int argc,char **argv)
{
int retval;
char ch;
char *filename = NULL;

progname = argv[0];
printf("amoxiflash version %s, (c) 2008 bushing\n", VERSION);

if (argc < 2) usage();
char *command = argv[1];
if (argc > 2) filename = argv[2];
optind = 2; // skip over command

while ((ch = getopt(argc, argv, "b:tvwx:df:s:q")) != -1) {
switch (ch) {
case 'b': subpage_size = strtol(optarg, NULL, 0); break;
case 't': test_mode = 1; break;
case 'v': verify_after_write = 1; break;
case 'w': check_status = 1; break;
case 'x': chip_select = strtol(optarg, NULL, 0);
if (chip_select != 0 && chip_select != 1) {
fprintf(stderr, "Invalid chip number -- must be 0 or 1\n");
usage();
}
break;
case 'd': debug_mode = 1; break;
case 'f': force = 1; break;
case 's': start_block = strtol(optarg, NULL, 0); break;
case 'q': quick_check = 1; break;
case '?':
default:
usage();
}
}
argc -= optind;
argv += optind;

if (!strcmp(command, "check")) {
if (!filename) {
fprintf(stderr, "Error: check requires a filename\n");
usage();
}

retval = check_file_ecc(filename);
exit(retval);
}

if (!strcmp(command, "strip")) {
if (!filename) {
fprintf(stderr, "Error: strip requires a filename\n");
usage();
}

retval = strip_file_ecc(filename);
exit(retval);
}

if (!strcmp(command, "sums")) {
if (!filename) {
fprintf(stderr, "Error: sums requires a filename\n");
usage();
}

retval = generate_checksums(filename);
exit(retval);
}
usb_init();
atexit(usb_exit_handler);
// usb_set_debug(2);
if ((h = locate_infectus())==0)
{
printf("Could not open the infectus device\n");
exit(1);
}

u32 flashid = 0;
infectus_reset();
infectus_get_version();
infectus_get_loader_version();
infectus_check_pld_id();
infectus_selectflash(chip_select);
usleep(1000);
flashid = infectus_getflashid();