-
Notifications
You must be signed in to change notification settings - Fork 0
/
fastboot.cpp
executable file
·1551 lines (1372 loc) · 51.6 KB
/
fastboot.cpp
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) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#define _LARGEFILE64_SOURCE
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <inttypes.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <functional>
#include <utility>
#include <vector>
#include <android-base/parseint.h>
#include <android-base/parsenetaddress.h>
#include <android-base/strings.h>
#include <sparse/sparse.h>
#include <ziparchive/zip_archive.h>
#include "bootimg_utils.h"
#include "diagnose_usb.h"
#include "fastboot.h"
#include "fs.h"
#include "tcp.h"
#include "transport.h"
#include "udp.h"
#include "usb.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
#define ARRAY_SIZE(a) (sizeof(a)/sizeof(*(a)))
char cur_product[FB_RESPONSE_SZ + 1];
static const char* serial = nullptr;
static const char* product = nullptr;
static const char* cmdline = nullptr;
static unsigned short vendor_id = 0;
static int long_listing = 0;
static int64_t sparse_limit = -1;
static int64_t target_sparse_limit = -1;
static unsigned page_size = 2048;
static unsigned base_addr = 0x10000000;
static unsigned kernel_offset = 0x00008000;
static unsigned ramdisk_offset = 0x01000000;
static unsigned second_offset = 0x00f00000;
static unsigned tags_offset = 0x00000100;
enum fb_buffer_type {
FB_BUFFER,
FB_BUFFER_SPARSE,
};
struct fastboot_buffer {
enum fb_buffer_type type;
void* data;
int64_t sz;
};
static struct {
char img_name[13];
char sig_name[13];
char part_name[9];
bool is_optional;
} images[] = {
{"boot.img", "boot.sig", "boot", false},
{"recovery.img", "recovery.sig", "recovery", true},
{"system.img", "system.sig", "system", false},
{"vendor.img", "vendor.sig", "vendor", true},
};
static char* find_item(const char* item, const char* product) {
char *dir;
const char *fn;
char path[PATH_MAX + 128];
if(!strcmp(item,"boot")) {
fn = "boot.img";
} else if(!strcmp(item,"recovery")) {
fn = "recovery.img";
} else if(!strcmp(item,"system")) {
fn = "system.img";
} else if(!strcmp(item,"vendor")) {
fn = "vendor.img";
} else if(!strcmp(item,"userdata")) {
fn = "userdata.img";
} else if(!strcmp(item,"cache")) {
fn = "cache.img";
} else if(!strcmp(item,"info")) {
fn = "android-info.txt";
} else {
fprintf(stderr,"unknown partition '%s'\n", item);
return 0;
}
if(product) {
get_my_path(path);
sprintf(path + strlen(path),
"../../../target/product/%s/%s", product, fn);
return strdup(path);
}
dir = getenv("ANDROID_PRODUCT_OUT");
if((dir == 0) || (dir[0] == 0)) {
die("neither -p product specified nor ANDROID_PRODUCT_OUT set");
return 0;
}
sprintf(path, "%s/%s", dir, fn);
return strdup(path);
}
static int64_t get_file_size(int fd) {
struct stat sb;
return fstat(fd, &sb) == -1 ? -1 : sb.st_size;
}
static void* load_fd(int fd, int64_t* sz) {
int errno_tmp;
char* data = nullptr;
*sz = get_file_size(fd);
if (*sz < 0) {
goto oops;
}
data = (char*) malloc(*sz);
if (data == nullptr) goto oops;
if(read(fd, data, *sz) != *sz) goto oops;
close(fd);
return data;
oops:
errno_tmp = errno;
close(fd);
if(data != 0) free(data);
errno = errno_tmp;
return 0;
}
static void* load_file(const char* fn, int64_t* sz) {
int fd = open(fn, O_RDONLY | O_BINARY);
if (fd == -1) return nullptr;
return load_fd(fd, sz);
}
static int match_fastboot_with_serial(usb_ifc_info* info, const char* local_serial) {
// Require a matching vendor id if the user specified one with -i.
if (vendor_id != 0 && info->dev_vendor != vendor_id) {
return -1;
}
if (info->ifc_class != 0xff || info->ifc_subclass != 0x42 || info->ifc_protocol != 0x03) {
return -1;
}
// require matching serial number or device path if requested
// at the command line with the -s option.
if (local_serial && (strcmp(local_serial, info->serial_number) != 0 &&
strcmp(local_serial, info->device_path) != 0)) return -1;
return 0;
}
static int match_fastboot(usb_ifc_info* info) {
return match_fastboot_with_serial(info, serial);
}
static int list_devices_callback(usb_ifc_info* info) {
if (match_fastboot_with_serial(info, nullptr) == 0) {
std::string serial = info->serial_number;
if (!info->writable) {
serial = UsbNoPermissionsShortHelpText();
}
if (!serial[0]) {
serial = "????????????";
}
// output compatible with "adb devices"
if (!long_listing) {
printf("%s\tfastboot", serial.c_str());
} else {
printf("%-22s fastboot", serial.c_str());
if (strlen(info->device_path) > 0) printf(" %s", info->device_path);
}
putchar('\n');
}
return -1;
}
// Opens a new Transport connected to a device. If |serial| is non-null it will be used to identify
// a specific device, otherwise the first USB device found will be used.
//
// If |serial| is non-null but invalid, this prints an error message to stderr and returns nullptr.
// Otherwise it blocks until the target is available.
//
// The returned Transport is a singleton, so multiple calls to this function will return the same
// object, and the caller should not attempt to delete the returned Transport.
static Transport* open_device() {
static Transport* transport = nullptr;
bool announce = true;
if (transport != nullptr) {
return transport;
}
Socket::Protocol protocol = Socket::Protocol::kTcp;
std::string host;
int port = 0;
if (serial != nullptr) {
const char* net_address = nullptr;
if (android::base::StartsWith(serial, "tcp:")) {
protocol = Socket::Protocol::kTcp;
port = tcp::kDefaultPort;
net_address = serial + strlen("tcp:");
} else if (android::base::StartsWith(serial, "udp:")) {
protocol = Socket::Protocol::kUdp;
port = udp::kDefaultPort;
net_address = serial + strlen("udp:");
}
if (net_address != nullptr) {
std::string error;
if (!android::base::ParseNetAddress(net_address, &host, &port, nullptr, &error)) {
fprintf(stderr, "error: Invalid network address '%s': %s\n", net_address,
error.c_str());
return nullptr;
}
}
}
while (true) {
if (!host.empty()) {
std::string error;
if (protocol == Socket::Protocol::kTcp) {
transport = tcp::Connect(host, port, &error).release();
} else if (protocol == Socket::Protocol::kUdp) {
transport = udp::Connect(host, port, &error).release();
}
if (transport == nullptr && announce) {
fprintf(stderr, "error: %s\n", error.c_str());
}
} else {
transport = usb_open(match_fastboot);
}
if (transport != nullptr) {
return transport;
}
if (announce) {
announce = false;
fprintf(stderr, "< waiting for %s >\n", serial ? serial : "any device");
}
usleep(1000);
}
}
static void list_devices() {
// We don't actually open a USB device here,
// just getting our callback called so we can
// list all the connected devices.
usb_open(list_devices_callback);
}
static void usage() {
fprintf(stderr,
/* 1234567890123456789012345678901234567890123456789012345678901234567890123456 */
"usage: fastboot [ <option> ] <command>\n"
"\n"
"commands:\n"
" update <filename> Reflash device from update.zip.\n"
" flashall Flash boot, system, vendor, and --\n"
" if found -- recovery.\n"
" flash <partition> [ <filename> ] Write a file to a flash partition.\n"
" flashing lock Locks the device. Prevents flashing.\n"
" flashing unlock Unlocks the device. Allows flashing\n"
" any partition except\n"
" bootloader-related partitions.\n"
" flashing lock_critical Prevents flashing bootloader-related\n"
" partitions.\n"
" flashing unlock_critical Enables flashing bootloader-related\n"
" partitions.\n"
" flashing get_unlock_ability Queries bootloader to see if the\n"
" device is unlocked.\n"
" flashing get_unlock_bootloader_nonce Queries the bootloader to get the\n"
" unlock nonce.\n"
" flashing unlock_bootloader <request> Issue unlock bootloader using request.\n"
" flashing lock_bootloader Locks the bootloader to prevent\n"
" bootloader version rollback.\n"
" erase <partition> Erase a flash partition.\n"
" format[:[<fs type>][:[<size>]] <partition>\n"
" Format a flash partition. Can\n"
" override the fs type and/or size\n"
" the bootloader reports.\n"
" getvar <variable> Display a bootloader variable.\n"
" set_active <suffix> Sets the active slot. If slots are\n"
" not supported, this does nothing.\n"
" boot <kernel> [ <ramdisk> [ <second> ] ] Download and boot kernel.\n"
" flash:raw boot <kernel> [ <ramdisk> [ <second> ] ]\n"
" Create bootimage and flash it.\n"
" devices [-l] List all connected devices [with\n"
" device paths].\n"
" continue Continue with autoboot.\n"
" reboot [bootloader] Reboot device [into bootloader].\n"
" reboot-bootloader Reboot device into bootloader.\n"
" help Show this help message.\n"
"\n"
"options:\n"
" -w Erase userdata and cache (and format\n"
" if supported by partition type).\n"
" -u Do not erase partition before\n"
" formatting.\n"
" -s <specific device> Specify a device. For USB, provide either\n"
" a serial number or path to device port.\n"
" For ethernet, provide an address in the"
" form <protocol>:<hostname>[:port] where"
" <protocol> is either tcp or udp.\n"
" -p <product> Specify product name.\n"
" -c <cmdline> Override kernel commandline.\n"
" -i <vendor id> Specify a custom USB vendor id.\n"
" -b, --base <base_addr> Specify a custom kernel base\n"
" address (default: 0x10000000).\n"
" --kernel-offset Specify a custom kernel offset.\n"
" (default: 0x00008000)\n"
" --ramdisk-offset Specify a custom ramdisk offset.\n"
" (default: 0x01000000)\n"
" --tags-offset Specify a custom tags offset.\n"
" (default: 0x00000100)\n"
" -n, --page-size <page size> Specify the nand page size\n"
" (default: 2048).\n"
" -S <size>[K|M|G] Automatically sparse files greater\n"
" than 'size'. 0 to disable.\n"
" --slot <suffix> Specify slot suffix to be used if the\n"
" device supports slots. This will be\n"
" added to all partition names that use\n"
" slots. 'all' can be given to refer\n"
" to all slots. 'other' can be given to\n"
" refer to a non-current slot. If this\n"
" flag is not used, slotted partitions\n"
" will default to the current active slot.\n"
" -a, --set-active[=<suffix>] Sets the active slot. If no suffix is\n"
" provided, this will default to the value\n"
" given by --slot. If slots are not\n"
" supported, this does nothing. This will\n"
" run after all non-reboot commands.\n"
" --unbuffered Do not buffer input or output.\n"
" --version Display version.\n"
" -h, --help show this message.\n"
);
}
static void* load_bootable_image(const char* kernel, const char* ramdisk,
const char* secondstage, int64_t* sz,
const char* cmdline) {
if (kernel == nullptr) {
fprintf(stderr, "no image specified\n");
return 0;
}
int64_t ksize;
void* kdata = load_file(kernel, &ksize);
if (kdata == nullptr) {
fprintf(stderr, "cannot load '%s': %s\n", kernel, strerror(errno));
return 0;
}
// Is this actually a boot image?
if(!memcmp(kdata, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
if (cmdline) bootimg_set_cmdline((boot_img_hdr*) kdata, cmdline);
if (ramdisk) {
fprintf(stderr, "cannot boot a boot.img *and* ramdisk\n");
return 0;
}
*sz = ksize;
return kdata;
}
void* rdata = nullptr;
int64_t rsize = 0;
if (ramdisk) {
rdata = load_file(ramdisk, &rsize);
if (rdata == nullptr) {
fprintf(stderr,"cannot load '%s': %s\n", ramdisk, strerror(errno));
return 0;
}
}
void* sdata = nullptr;
int64_t ssize = 0;
if (secondstage) {
sdata = load_file(secondstage, &ssize);
if (sdata == nullptr) {
fprintf(stderr,"cannot load '%s': %s\n", secondstage, strerror(errno));
return 0;
}
}
fprintf(stderr,"creating boot image...\n");
int64_t bsize = 0;
void* bdata = mkbootimg(kdata, ksize, kernel_offset,
rdata, rsize, ramdisk_offset,
sdata, ssize, second_offset,
page_size, base_addr, tags_offset, &bsize);
if (bdata == nullptr) {
fprintf(stderr,"failed to create boot.img\n");
return 0;
}
if (cmdline) bootimg_set_cmdline((boot_img_hdr*) bdata, cmdline);
fprintf(stderr, "creating boot image - %" PRId64 " bytes\n", bsize);
*sz = bsize;
return bdata;
}
static void* unzip_file(ZipArchiveHandle zip, const char* entry_name, int64_t* sz)
{
ZipString zip_entry_name(entry_name);
ZipEntry zip_entry;
if (FindEntry(zip, zip_entry_name, &zip_entry) != 0) {
fprintf(stderr, "archive does not contain '%s'\n", entry_name);
return 0;
}
*sz = zip_entry.uncompressed_length;
uint8_t* data = reinterpret_cast<uint8_t*>(malloc(zip_entry.uncompressed_length));
if (data == nullptr) {
fprintf(stderr, "failed to allocate %" PRId64 " bytes for '%s'\n", *sz, entry_name);
return 0;
}
int error = ExtractToMemory(zip, &zip_entry, data, zip_entry.uncompressed_length);
if (error != 0) {
fprintf(stderr, "failed to extract '%s': %s\n", entry_name, ErrorCodeString(error));
free(data);
return 0;
}
return data;
}
#if defined(_WIN32)
// TODO: move this to somewhere it can be shared.
#include <windows.h>
// Windows' tmpfile(3) requires administrator rights because
// it creates temporary files in the root directory.
static FILE* win32_tmpfile() {
char temp_path[PATH_MAX];
DWORD nchars = GetTempPath(sizeof(temp_path), temp_path);
if (nchars == 0 || nchars >= sizeof(temp_path)) {
fprintf(stderr, "GetTempPath failed, error %ld\n", GetLastError());
return nullptr;
}
char filename[PATH_MAX];
if (GetTempFileName(temp_path, "fastboot", 0, filename) == 0) {
fprintf(stderr, "GetTempFileName failed, error %ld\n", GetLastError());
return nullptr;
}
return fopen(filename, "w+bTD");
}
#define tmpfile win32_tmpfile
#endif
static int unzip_to_file(ZipArchiveHandle zip, char* entry_name) {
FILE* fp = tmpfile();
if (fp == nullptr) {
fprintf(stderr, "failed to create temporary file for '%s': %s\n",
entry_name, strerror(errno));
return -1;
}
ZipString zip_entry_name(entry_name);
ZipEntry zip_entry;
if (FindEntry(zip, zip_entry_name, &zip_entry) != 0) {
fprintf(stderr, "archive does not contain '%s'\n", entry_name);
return -1;
}
int fd = fileno(fp);
int error = ExtractEntryToFile(zip, &zip_entry, fd);
if (error != 0) {
fprintf(stderr, "failed to extract '%s': %s\n", entry_name, ErrorCodeString(error));
return -1;
}
lseek(fd, 0, SEEK_SET);
return fd;
}
static char *strip(char *s)
{
int n;
while(*s && isspace(*s)) s++;
n = strlen(s);
while(n-- > 0) {
if(!isspace(s[n])) break;
s[n] = 0;
}
return s;
}
#define MAX_OPTIONS 32
static int setup_requirement_line(char *name)
{
char *val[MAX_OPTIONS];
char *prod = nullptr;
unsigned n, count;
char *x;
int invert = 0;
if (!strncmp(name, "reject ", 7)) {
name += 7;
invert = 1;
} else if (!strncmp(name, "require ", 8)) {
name += 8;
invert = 0;
} else if (!strncmp(name, "require-for-product:", 20)) {
// Get the product and point name past it
prod = name + 20;
name = strchr(name, ' ');
if (!name) return -1;
*name = 0;
name += 1;
invert = 0;
}
x = strchr(name, '=');
if (x == 0) return 0;
*x = 0;
val[0] = x + 1;
for(count = 1; count < MAX_OPTIONS; count++) {
x = strchr(val[count - 1],'|');
if (x == 0) break;
*x = 0;
val[count] = x + 1;
}
name = strip(name);
for(n = 0; n < count; n++) val[n] = strip(val[n]);
name = strip(name);
if (name == 0) return -1;
const char* var = name;
// Work around an unfortunate name mismatch.
if (!strcmp(name,"board")) var = "product";
const char** out = reinterpret_cast<const char**>(malloc(sizeof(char*) * count));
if (out == 0) return -1;
for(n = 0; n < count; n++) {
out[n] = strdup(strip(val[n]));
if (out[n] == 0) {
for(size_t i = 0; i < n; ++i) {
free((char*) out[i]);
}
free(out);
return -1;
}
}
fb_queue_require(prod, var, invert, n, out);
return 0;
}
static void setup_requirements(char* data, int64_t sz) {
char* s = data;
while (sz-- > 0) {
if (*s == '\n') {
*s++ = 0;
if (setup_requirement_line(data)) {
die("out of memory");
}
data = s;
} else {
s++;
}
}
}
static void queue_info_dump() {
fb_queue_notice("--------------------------------------------");
fb_queue_display("version-bootloader", "Bootloader Version...");
fb_queue_display("version-baseband", "Baseband Version.....");
fb_queue_display("serialno", "Serial Number........");
fb_queue_notice("--------------------------------------------");
}
static struct sparse_file **load_sparse_files(int fd, int max_size)
{
struct sparse_file* s = sparse_file_import_auto(fd, false, true);
if (!s) {
die("cannot sparse read file\n");
}
int files = sparse_file_resparse(s, max_size, nullptr, 0);
if (files < 0) {
die("Failed to resparse\n");
}
sparse_file** out_s = reinterpret_cast<sparse_file**>(calloc(sizeof(struct sparse_file *), files + 1));
if (!out_s) {
die("Failed to allocate sparse file array\n");
}
files = sparse_file_resparse(s, max_size, out_s, files);
if (files < 0) {
die("Failed to resparse\n");
}
return out_s;
}
static int64_t get_target_sparse_limit(Transport* transport) {
std::string max_download_size;
if (!fb_getvar(transport, "max-download-size", &max_download_size) ||
max_download_size.empty()) {
fprintf(stderr, "target didn't report max-download-size\n");
return 0;
}
// Some bootloaders (angler, for example) send spurious whitespace too.
max_download_size = android::base::Trim(max_download_size);
uint64_t limit;
if (!android::base::ParseUint(max_download_size.c_str(), &limit)) {
fprintf(stderr, "couldn't parse max-download-size '%s'\n", max_download_size.c_str());
return 0;
}
if (limit > 0) {
fprintf(stderr, "target reported max download size of %" PRId64 " bytes\n", limit);
}
return limit;
}
static int64_t get_sparse_limit(Transport* transport, int64_t size) {
int64_t limit;
if (sparse_limit == 0) {
return 0;
} else if (sparse_limit > 0) {
limit = sparse_limit;
} else {
if (target_sparse_limit == -1) {
target_sparse_limit = get_target_sparse_limit(transport);
}
if (target_sparse_limit > 0) {
limit = target_sparse_limit;
} else {
return 0;
}
}
if (size > limit) {
return limit;
}
return 0;
}
// Until we get lazy inode table init working in make_ext4fs, we need to
// erase partitions of type ext4 before flashing a filesystem so no stale
// inodes are left lying around. Otherwise, e2fsck gets very upset.
static bool needs_erase(Transport* transport, const char* partition) {
std::string partition_type;
if (!fb_getvar(transport, std::string("partition-type:") + partition, &partition_type)) {
return false;
}
return partition_type == "ext4";
}
static int load_buf_fd(Transport* transport, int fd, struct fastboot_buffer* buf) {
int64_t sz = get_file_size(fd);
if (sz == -1) {
return -1;
}
lseek64(fd, 0, SEEK_SET);
int64_t limit = get_sparse_limit(transport, sz);
if (limit) {
sparse_file** s = load_sparse_files(fd, limit);
if (s == nullptr) {
return -1;
}
buf->type = FB_BUFFER_SPARSE;
buf->data = s;
} else {
void* data = load_fd(fd, &sz);
if (data == nullptr) return -1;
buf->type = FB_BUFFER;
buf->data = data;
buf->sz = sz;
}
return 0;
}
static int load_buf(Transport* transport, const char *fname, struct fastboot_buffer *buf)
{
int fd;
fd = open(fname, O_RDONLY | O_BINARY);
if (fd < 0) {
return -1;
}
return load_buf_fd(transport, fd, buf);
}
static void flash_buf(const char *pname, struct fastboot_buffer *buf)
{
sparse_file** s;
switch (buf->type) {
case FB_BUFFER_SPARSE: {
std::vector<std::pair<sparse_file*, int64_t>> sparse_files;
s = reinterpret_cast<sparse_file**>(buf->data);
while (*s) {
int64_t sz = sparse_file_len(*s, true, false);
sparse_files.emplace_back(*s, sz);
++s;
}
for (size_t i = 0; i < sparse_files.size(); ++i) {
const auto& pair = sparse_files[i];
fb_queue_flash_sparse(pname, pair.first, pair.second, i + 1, sparse_files.size());
}
break;
}
case FB_BUFFER:
fb_queue_flash(pname, buf->data, buf->sz);
break;
default:
die("unknown buffer type: %d", buf->type);
}
}
static std::vector<std::string> get_suffixes(Transport* transport) {
std::vector<std::string> suffixes;
std::string suffix_list;
if (!fb_getvar(transport, "slot-suffixes", &suffix_list)) {
die("Could not get suffixes.\n");
}
return android::base::Split(suffix_list, ",");
}
static std::string verify_slot(Transport* transport, const char *slot, bool allow_all) {
if (strcmp(slot, "all") == 0) {
if (allow_all) {
return "all";
} else {
std::vector<std::string> suffixes = get_suffixes(transport);
if (!suffixes.empty()) {
return suffixes[0];
} else {
die("No known slots.");
}
}
}
std::vector<std::string> suffixes = get_suffixes(transport);
if (strcmp(slot, "other") == 0) {
std::string current_slot;
if (!fb_getvar(transport, "current-slot", ¤t_slot)) {
die("Failed to identify current slot.");
}
if (!suffixes.empty()) {
for (size_t i = 0; i < suffixes.size(); i++) {
if (current_slot == suffixes[i])
return suffixes[(i+1)%suffixes.size()];
}
} else {
die("No known slots.");
}
}
for (const std::string &suffix : suffixes) {
if (suffix == slot)
return slot;
}
fprintf(stderr, "Slot %s does not exist. supported slots are:\n", slot);
for (const std::string &suffix : suffixes) {
fprintf(stderr, "%s\n", suffix.c_str());
}
exit(1);
}
static std::string verify_slot(Transport* transport, const char *slot) {
return verify_slot(transport, slot, true);
}
static void do_for_partition(Transport* transport, const char *part, const char *slot,
std::function<void(const std::string&)> func, bool force_slot) {
std::string has_slot;
std::string current_slot;
if (!fb_getvar(transport, std::string("has-slot:")+part, &has_slot)) {
/* If has-slot is not supported, the answer is no. */
has_slot = "no";
}
if (has_slot == "yes") {
if (!slot || slot[0] == 0) {
if (!fb_getvar(transport, "current-slot", ¤t_slot)) {
die("Failed to identify current slot.\n");
}
func(std::string(part) + current_slot);
} else {
func(std::string(part) + slot);
}
} else {
if (force_slot && slot && slot[0]) {
fprintf(stderr, "Warning: %s does not support slots, and slot %s was requested.\n",
part, slot);
}
func(part);
}
}
/* This function will find the real partition name given a base name, and a slot. If slot is NULL or
* empty, it will use the current slot. If slot is "all", it will return a list of all possible
* partition names. If force_slot is true, it will fail if a slot is specified, and the given
* partition does not support slots.
*/
static void do_for_partitions(Transport* transport, const char *part, const char *slot,
std::function<void(const std::string&)> func, bool force_slot) {
std::string has_slot;
if (slot && strcmp(slot, "all") == 0) {
if (!fb_getvar(transport, std::string("has-slot:") + part, &has_slot)) {
die("Could not check if partition %s has slot.", part);
}
if (has_slot == "yes") {
std::vector<std::string> suffixes = get_suffixes(transport);
for (std::string &suffix : suffixes) {
do_for_partition(transport, part, suffix.c_str(), func, force_slot);
}
} else {
do_for_partition(transport, part, "", func, force_slot);
}
} else {
do_for_partition(transport, part, slot, func, force_slot);
}
}
static void do_flash(Transport* transport, const char* pname, const char* fname) {
struct fastboot_buffer buf;
if (load_buf(transport, fname, &buf)) {
die("cannot load '%s'", fname);
}
flash_buf(pname, &buf);
}
static void do_update_signature(ZipArchiveHandle zip, char* fn) {
int64_t sz;
void* data = unzip_file(zip, fn, &sz);
if (data == nullptr) return;
fb_queue_download("signature", data, sz);
fb_queue_command("signature", "installing signature");
}
static void do_update(Transport* transport, const char* filename, const char* slot_override, bool erase_first) {
queue_info_dump();
fb_queue_query_save("product", cur_product, sizeof(cur_product));
ZipArchiveHandle zip;
int error = OpenArchive(filename, &zip);
if (error != 0) {
CloseArchive(zip);
die("failed to open zip file '%s': %s", filename, ErrorCodeString(error));
}
int64_t sz;
void* data = unzip_file(zip, "android-info.txt", &sz);
if (data == nullptr) {
CloseArchive(zip);
die("update package '%s' has no android-info.txt", filename);
}
setup_requirements(reinterpret_cast<char*>(data), sz);
for (size_t i = 0; i < ARRAY_SIZE(images); ++i) {
int fd = unzip_to_file(zip, images[i].img_name);
if (fd == -1) {
if (images[i].is_optional) {
continue;
}
CloseArchive(zip);
exit(1); // unzip_to_file already explained why.
}
fastboot_buffer buf;
int rc = load_buf_fd(transport, fd, &buf);
if (rc) die("cannot load %s from flash", images[i].img_name);
auto update = [&](const std::string &partition) {
do_update_signature(zip, images[i].sig_name);
//printf("zj update!\n");
if (erase_first && needs_erase(transport, partition.c_str())) {
fb_queue_erase(partition.c_str());
}
flash_buf(partition.c_str(), &buf);
/* not closing the fd here since the sparse code keeps the fd around
* but hasn't mmaped data yet. The tmpfile will get cleaned up when the
* program exits.
*/
};
printf("zj update!\n");
do_for_partitions(transport, images[i].part_name, slot_override, update, false);
}
CloseArchive(zip);
}
static void do_send_signature(char* fn) {
char* xtn = strrchr(fn, '.');
if (!xtn) return;
if (strcmp(xtn, ".img")) return;
strcpy(xtn, ".sig");
int64_t sz;
void* data = load_file(fn, &sz);
strcpy(xtn, ".img");
if (data == nullptr) return;
fb_queue_download("signature", data, sz);
fb_queue_command("signature", "installing signature");
}
static void do_flashall(Transport* transport, const char* slot_override, int erase_first) {
queue_info_dump();
fb_queue_query_save("product", cur_product, sizeof(cur_product));
char* fname = find_item("info", product);
if (fname == nullptr) die("cannot find android-info.txt");
int64_t sz;
void* data = load_file(fname, &sz);
if (data == nullptr) die("could not load android-info.txt: %s", strerror(errno));
setup_requirements(reinterpret_cast<char*>(data), sz);
for (size_t i = 0; i < ARRAY_SIZE(images); i++) {
fname = find_item(images[i].part_name, product);