blob: 75ffe0f0892c7f6654b0913ad4e0109d496b1f01 [file] [log] [blame]
Doug Zongker512536a2010-02-17 16:11:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <errno.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070018#include <fcntl.h>
Doug Zongker512536a2010-02-17 16:11:44 -080019#include <libgen.h>
20#include <stdio.h>
21#include <stdlib.h>
22#include <string.h>
23#include <sys/stat.h>
24#include <sys/statfs.h>
25#include <sys/types.h>
Doug Zongker512536a2010-02-17 16:11:44 -080026#include <unistd.h>
27
Elliott Hughes4b166f02015-12-04 15:30:20 -080028#include <android-base/strings.h>
Tao Baoaca8e892015-07-17 11:47:44 -070029
Sen Jiangc48cb5e2016-02-04 16:23:21 +080030#include "openssl/sha.h"
Doug Zongker512536a2010-02-17 16:11:44 -080031#include "applypatch.h"
32#include "mtdutils/mtdutils.h"
Doug Zongkerc4351c72010-02-22 14:46:32 -080033#include "edify/expr.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070034#include "print_sha1.h"
Doug Zongker512536a2010-02-17 16:11:44 -080035
Doug Zongkerf291d852010-07-07 13:55:25 -070036static int LoadPartitionContents(const char* filename, FileContents* file);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070037static ssize_t FileSink(const unsigned char* data, ssize_t len, void* token);
Doug Zongker1c43c972012-02-28 11:07:09 -080038static int GenerateTarget(FileContents* source_file,
39 const Value* source_patch_value,
40 FileContents* copy_file,
41 const Value* copy_patch_value,
42 const char* source_filename,
43 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +080044 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -070045 size_t target_size,
46 const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080047
Tao Baoaca8e892015-07-17 11:47:44 -070048static bool mtd_partitions_scanned = false;
Doug Zongker512536a2010-02-17 16:11:44 -080049
Doug Zongkera1bc1482014-02-13 15:18:19 -080050// Read a file into memory; store the file contents and associated
Hristo Bojinovdb314d62010-08-02 10:29:49 -070051// metadata in *file.
52//
53// Return 0 on success.
Doug Zongkera1bc1482014-02-13 15:18:19 -080054int LoadFileContents(const char* filename, FileContents* file) {
Doug Zongker512536a2010-02-17 16:11:44 -080055 file->data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -080056
Doug Zongkerf291d852010-07-07 13:55:25 -070057 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
58 // load the contents of a partition.
59 if (strncmp(filename, "MTD:", 4) == 0 ||
60 strncmp(filename, "EMMC:", 5) == 0) {
61 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080062 }
Doug Zongker512536a2010-02-17 16:11:44 -080063
Doug Zongkerc4351c72010-02-22 14:46:32 -080064 if (stat(filename, &file->st) != 0) {
65 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
66 return -1;
67 }
68
69 file->size = file->st.st_size;
Tao Baoba9a42a2015-06-23 23:23:33 -070070 file->data = reinterpret_cast<unsigned char*>(malloc(file->size));
Doug Zongkerc4351c72010-02-22 14:46:32 -080071
72 FILE* f = fopen(filename, "rb");
73 if (f == NULL) {
74 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
75 free(file->data);
76 file->data = NULL;
77 return -1;
78 }
79
Tao Baoba9a42a2015-06-23 23:23:33 -070080 size_t bytes_read = fread(file->data, 1, file->size, f);
81 if (bytes_read != static_cast<size_t>(file->size)) {
82 printf("short read of \"%s\" (%zu bytes of %zd)\n", filename, bytes_read, file->size);
Doug Zongkerc4351c72010-02-22 14:46:32 -080083 free(file->data);
84 file->data = NULL;
85 return -1;
86 }
87 fclose(f);
88
Sen Jiangc48cb5e2016-02-04 16:23:21 +080089 SHA1(file->data, file->size, file->sha1);
Doug Zongkerc4351c72010-02-22 14:46:32 -080090 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080091}
92
Doug Zongkerf291d852010-07-07 13:55:25 -070093// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -080094// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -070095// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
96// "EMMC:<partition_device>:..."). The smallest size_n bytes for
97// which that prefix of the partition contents has the corresponding
98// sha1 hash will be loaded. It is acceptable for a size value to be
99// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -0800100//
101// This complexity is needed because if an OTA installation is
102// interrupted, the partition might contain either the source or the
103// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700104// the length in order to read from a partition (there is no
105// "end-of-file" marker), so the caller must specify the possible
106// lengths and the hash of the data, and we'll do the load expecting
107// to find one of those hashes.
108enum PartitionType { MTD, EMMC };
109
110static int LoadPartitionContents(const char* filename, FileContents* file) {
Tao Baoaca8e892015-07-17 11:47:44 -0700111 std::string copy(filename);
112 std::vector<std::string> pieces = android::base::Split(copy, ":");
113 if (pieces.size() < 4 || pieces.size() % 2 != 0) {
114 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
115 return -1;
116 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700117
118 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700119 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700120 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700121 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700122 type = EMMC;
123 } else {
Tao Baoba9a42a2015-06-23 23:23:33 -0700124 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800125 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800126 }
Tao Baoaca8e892015-07-17 11:47:44 -0700127 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800128
Tao Baoaca8e892015-07-17 11:47:44 -0700129 size_t pairs = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
130 std::vector<size_t> index(pairs);
131 std::vector<size_t> size(pairs);
132 std::vector<std::string> sha1sum(pairs);
Doug Zongker512536a2010-02-17 16:11:44 -0800133
Tao Baoaca8e892015-07-17 11:47:44 -0700134 for (size_t i = 0; i < pairs; ++i) {
135 size[i] = strtol(pieces[i*2+2].c_str(), NULL, 10);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800136 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700137 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800138 return -1;
139 }
Tao Baoaca8e892015-07-17 11:47:44 -0700140 sha1sum[i] = pieces[i*2+3].c_str();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800141 index[i] = i;
142 }
Doug Zongker512536a2010-02-17 16:11:44 -0800143
Tao Baoaca8e892015-07-17 11:47:44 -0700144 // Sort the index[] array so it indexes the pairs in order of increasing size.
145 sort(index.begin(), index.end(),
146 [&](const size_t& i, const size_t& j) {
147 return (size[i] < size[j]);
148 }
149 );
Doug Zongker512536a2010-02-17 16:11:44 -0800150
Doug Zongkerf291d852010-07-07 13:55:25 -0700151 MtdReadContext* ctx = NULL;
152 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800153
Doug Zongkerf291d852010-07-07 13:55:25 -0700154 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700155 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700156 if (!mtd_partitions_scanned) {
157 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700158 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700159 }
Doug Zongker512536a2010-02-17 16:11:44 -0800160
Doug Zongkerf291d852010-07-07 13:55:25 -0700161 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
162 if (mtd == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700163 printf("mtd partition \"%s\" not found (loading %s)\n", partition, filename);
Doug Zongkerf291d852010-07-07 13:55:25 -0700164 return -1;
165 }
166
167 ctx = mtd_read_partition(mtd);
168 if (ctx == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700169 printf("failed to initialize read of mtd partition \"%s\"\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700170 return -1;
171 }
172 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700173 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700174
175 case EMMC:
176 dev = fopen(partition, "rb");
177 if (dev == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700178 printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700179 return -1;
180 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800181 }
Doug Zongker512536a2010-02-17 16:11:44 -0800182
Doug Zongkerc4351c72010-02-22 14:46:32 -0800183 SHA_CTX sha_ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800184 SHA1_Init(&sha_ctx);
185 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800186
Tao Baoaca8e892015-07-17 11:47:44 -0700187 // Allocate enough memory to hold the largest size.
Tao Baoba9a42a2015-06-23 23:23:33 -0700188 file->data = reinterpret_cast<unsigned char*>(malloc(size[index[pairs-1]]));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800189 char* p = (char*)file->data;
190 file->size = 0; // # bytes read so far
Tao Baoaca8e892015-07-17 11:47:44 -0700191 bool found = false;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800192
Tao Baoaca8e892015-07-17 11:47:44 -0700193 for (size_t i = 0; i < pairs; ++i) {
194 // Read enough additional bytes to get us up to the next size. (Again,
195 // we're trying the possibilities in order of increasing size).
Doug Zongkerc4351c72010-02-22 14:46:32 -0800196 size_t next = size[index[i]] - file->size;
197 size_t read = 0;
198 if (next > 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700199 switch (type) {
200 case MTD:
201 read = mtd_read_data(ctx, p, next);
202 break;
203
204 case EMMC:
205 read = fread(p, 1, next, dev);
206 break;
207 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800208 if (next != read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700209 printf("short read (%zu bytes of %zu) for partition \"%s\"\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800210 read, next, partition);
211 free(file->data);
212 file->data = NULL;
213 return -1;
214 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800215 SHA1_Update(&sha_ctx, p, read);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800216 file->size += read;
217 }
218
219 // Duplicate the SHA context and finalize the duplicate so we can
220 // check it against this pair's expected hash.
221 SHA_CTX temp_ctx;
222 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800223 uint8_t sha_so_far[SHA_DIGEST_LENGTH];
224 SHA1_Final(sha_so_far, &temp_ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800225
Tao Baoaca8e892015-07-17 11:47:44 -0700226 if (ParseSha1(sha1sum[index[i]].c_str(), parsed_sha) != 0) {
227 printf("failed to parse sha1 %s in %s\n", sha1sum[index[i]].c_str(), filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800228 free(file->data);
229 file->data = NULL;
230 return -1;
231 }
232
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800233 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800234 // we have a match. stop reading the partition; we'll return
235 // the data we've read so far.
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700236 printf("partition read matched size %zu sha %s\n",
Tao Baoaca8e892015-07-17 11:47:44 -0700237 size[index[i]], sha1sum[index[i]].c_str());
238 found = true;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800239 break;
240 }
241
242 p += read;
243 }
244
Doug Zongkerf291d852010-07-07 13:55:25 -0700245 switch (type) {
246 case MTD:
247 mtd_read_close(ctx);
248 break;
249
250 case EMMC:
251 fclose(dev);
252 break;
253 }
254
Doug Zongkerc4351c72010-02-22 14:46:32 -0800255
Tao Baoaca8e892015-07-17 11:47:44 -0700256 if (!found) {
257 // Ran off the end of the list of (size,sha1) pairs without finding a match.
Tao Baoba9a42a2015-06-23 23:23:33 -0700258 printf("contents of partition \"%s\" didn't match %s\n", partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800259 free(file->data);
260 file->data = NULL;
261 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800262 }
263
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800264 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800265
Doug Zongkerc4351c72010-02-22 14:46:32 -0800266 // Fake some stat() info.
267 file->st.st_mode = 0644;
268 file->st.st_uid = 0;
269 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800270
Doug Zongkerc4351c72010-02-22 14:46:32 -0800271 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800272}
273
274
275// Save the contents of the given FileContents object under the given
276// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800277int SaveFileContents(const char* filename, const FileContents* file) {
Michael Rungebe81e512014-10-29 12:42:15 -0700278 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800279 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700280 printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800281 return -1;
282 }
Doug Zongker512536a2010-02-17 16:11:44 -0800283
Doug Zongker1c43c972012-02-28 11:07:09 -0800284 ssize_t bytes_written = FileSink(file->data, file->size, &fd);
285 if (bytes_written != file->size) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700286 printf("short write of \"%s\" (%zd bytes of %zd) (%s)\n",
287 filename, bytes_written, file->size, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800288 close(fd);
289 return -1;
290 }
Michael Rungebe81e512014-10-29 12:42:15 -0700291 if (fsync(fd) != 0) {
292 printf("fsync of \"%s\" failed: %s\n", filename, strerror(errno));
293 return -1;
294 }
295 if (close(fd) != 0) {
296 printf("close of \"%s\" failed: %s\n", filename, strerror(errno));
297 return -1;
298 }
Doug Zongker512536a2010-02-17 16:11:44 -0800299
Doug Zongker1c43c972012-02-28 11:07:09 -0800300 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800301 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
302 return -1;
303 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800304 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800305 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
306 return -1;
307 }
Doug Zongker512536a2010-02-17 16:11:44 -0800308
Doug Zongkerc4351c72010-02-22 14:46:32 -0800309 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800310}
311
Doug Zongkerf291d852010-07-07 13:55:25 -0700312// Write a memory buffer to 'target' partition, a string of the form
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700313// "MTD:<partition>[:...]" or "EMMC:<partition_device>[:...]". The target name
314// might contain multiple colons, but WriteToPartition() only uses the first
315// two and ignores the rest. Return 0 on success.
Tao Baoba9a42a2015-06-23 23:23:33 -0700316int WriteToPartition(unsigned char* data, size_t len, const char* target) {
Tao Baoaca8e892015-07-17 11:47:44 -0700317 std::string copy(target);
318 std::vector<std::string> pieces = android::base::Split(copy, ":");
319
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700320 if (pieces.size() < 2) {
Tao Baoaca8e892015-07-17 11:47:44 -0700321 printf("WriteToPartition called with bad target (%s)\n", target);
322 return -1;
323 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700324
325 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700326 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700327 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700328 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700329 type = EMMC;
330 } else {
331 printf("WriteToPartition called with bad target (%s)\n", target);
332 return -1;
333 }
Tao Baoaca8e892015-07-17 11:47:44 -0700334 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800335
Doug Zongkerf291d852010-07-07 13:55:25 -0700336 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700337 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700338 if (!mtd_partitions_scanned) {
339 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700340 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700341 }
342
343 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
344 if (mtd == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700345 printf("mtd partition \"%s\" not found for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700346 return -1;
347 }
348
349 MtdWriteContext* ctx = mtd_write_partition(mtd);
350 if (ctx == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700351 printf("failed to init mtd partition \"%s\" for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700352 return -1;
353 }
354
Tao Baoba9a42a2015-06-23 23:23:33 -0700355 size_t written = mtd_write_data(ctx, reinterpret_cast<char*>(data), len);
Doug Zongkerf291d852010-07-07 13:55:25 -0700356 if (written != len) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700357 printf("only wrote %zu of %zu bytes to MTD %s\n", written, len, partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700358 mtd_write_close(ctx);
359 return -1;
360 }
361
362 if (mtd_erase_blocks(ctx, -1) < 0) {
363 printf("error finishing mtd write of %s\n", partition);
364 mtd_write_close(ctx);
365 return -1;
366 }
367
368 if (mtd_write_close(ctx)) {
369 printf("error closing mtd write of %s\n", partition);
370 return -1;
371 }
372 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700373 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700374
Tao Baoba9a42a2015-06-23 23:23:33 -0700375 case EMMC: {
Doug Zongker044a0b42013-07-08 09:42:54 -0700376 size_t start = 0;
Tao Baoba9a42a2015-06-23 23:23:33 -0700377 bool success = false;
Michael Rungebe81e512014-10-29 12:42:15 -0700378 int fd = open(partition, O_RDWR | O_SYNC);
Doug Zongkerc870a992013-07-09 10:34:46 -0700379 if (fd < 0) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700380 printf("failed to open %s: %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700381 return -1;
382 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700383
Tao Baoaca8e892015-07-17 11:47:44 -0700384 for (size_t attempt = 0; attempt < 2; ++attempt) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700385 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700386 printf("failed seek on %s: %s\n", partition, strerror(errno));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700387 return -1;
388 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700389 while (start < len) {
390 size_t to_write = len - start;
Doug Zongker168724c2013-12-19 15:16:57 -0800391 if (to_write > 1<<20) to_write = 1<<20;
Doug Zongker044a0b42013-07-08 09:42:54 -0700392
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700393 ssize_t written = TEMP_FAILURE_RETRY(write(fd, data+start, to_write));
394 if (written == -1) {
395 printf("failed write writing to %s: %s\n", partition, strerror(errno));
396 return -1;
Doug Zongker044a0b42013-07-08 09:42:54 -0700397 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700398 start += written;
Doug Zongker044a0b42013-07-08 09:42:54 -0700399 }
Michael Rungebe81e512014-10-29 12:42:15 -0700400 if (fsync(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700401 printf("failed to sync to %s (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700402 return -1;
403 }
404 if (close(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700405 printf("failed to close %s (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700406 return -1;
407 }
408 fd = open(partition, O_RDONLY);
409 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700410 printf("failed to reopen %s for verify (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700411 return -1;
412 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700413
Tao Baoba9a42a2015-06-23 23:23:33 -0700414 // Drop caches so our subsequent verification read
Doug Zongker044a0b42013-07-08 09:42:54 -0700415 // won't just be reading the cache.
416 sync();
Doug Zongkerc870a992013-07-09 10:34:46 -0700417 int dc = open("/proc/sys/vm/drop_caches", O_WRONLY);
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700418 if (TEMP_FAILURE_RETRY(write(dc, "3\n", 2)) == -1) {
419 printf("write to /proc/sys/vm/drop_caches failed: %s\n", strerror(errno));
420 } else {
421 printf(" caches dropped\n");
422 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700423 close(dc);
Doug Zongker044a0b42013-07-08 09:42:54 -0700424 sleep(1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700425
426 // verify
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700427 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
428 printf("failed to seek back to beginning of %s: %s\n",
429 partition, strerror(errno));
430 return -1;
431 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700432 unsigned char buffer[4096];
433 start = len;
Tao Baoba9a42a2015-06-23 23:23:33 -0700434 for (size_t p = 0; p < len; p += sizeof(buffer)) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700435 size_t to_read = len - p;
Tao Baoba9a42a2015-06-23 23:23:33 -0700436 if (to_read > sizeof(buffer)) {
437 to_read = sizeof(buffer);
438 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700439
Doug Zongkerc870a992013-07-09 10:34:46 -0700440 size_t so_far = 0;
441 while (so_far < to_read) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700442 ssize_t read_count =
443 TEMP_FAILURE_RETRY(read(fd, buffer+so_far, to_read-so_far));
444 if (read_count == -1) {
445 printf("verify read error %s at %zu: %s\n",
446 partition, p, strerror(errno));
447 return -1;
Doug Zongkerc870a992013-07-09 10:34:46 -0700448 }
Tao Baoba9a42a2015-06-23 23:23:33 -0700449 if (static_cast<size_t>(read_count) < to_read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700450 printf("short verify read %s at %zu: %zd %zu %s\n",
Doug Zongkerc870a992013-07-09 10:34:46 -0700451 partition, p, read_count, to_read, strerror(errno));
452 }
453 so_far += read_count;
Doug Zongker044a0b42013-07-08 09:42:54 -0700454 }
455
Tao Baoba9a42a2015-06-23 23:23:33 -0700456 if (memcmp(buffer, data+p, to_read) != 0) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700457 printf("verification failed starting at %zu\n", p);
Doug Zongker044a0b42013-07-08 09:42:54 -0700458 start = p;
459 break;
460 }
461 }
462
463 if (start == len) {
Tao Baoabba55b2015-07-17 18:11:12 -0700464 printf("verification read succeeded (attempt %zu)\n", attempt+1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700465 success = true;
466 break;
467 }
468 }
469
470 if (!success) {
471 printf("failed to verify after all attempts\n");
472 return -1;
473 }
474
Doug Zongkerc870a992013-07-09 10:34:46 -0700475 if (close(fd) != 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700476 printf("error closing %s (%s)\n", partition, strerror(errno));
477 return -1;
478 }
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700479 sync();
Doug Zongkerf291d852010-07-07 13:55:25 -0700480 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700481 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800482 }
Doug Zongker512536a2010-02-17 16:11:44 -0800483
Doug Zongkerc4351c72010-02-22 14:46:32 -0800484 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800485}
486
487
488// Take a string 'str' of 40 hex digits and parse it into the 20
489// byte array 'digest'. 'str' may contain only the digest or be of
490// the form "<digest>:<anything>". Return 0 on success, -1 on any
491// error.
492int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800493 const char* ps = str;
494 uint8_t* pd = digest;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800495 for (int i = 0; i < SHA_DIGEST_LENGTH * 2; ++i, ++ps) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800496 int digit;
497 if (*ps >= '0' && *ps <= '9') {
498 digit = *ps - '0';
499 } else if (*ps >= 'a' && *ps <= 'f') {
500 digit = *ps - 'a' + 10;
501 } else if (*ps >= 'A' && *ps <= 'F') {
502 digit = *ps - 'A' + 10;
503 } else {
504 return -1;
505 }
506 if (i % 2 == 0) {
507 *pd = digit << 4;
508 } else {
509 *pd |= digit;
510 ++pd;
511 }
Doug Zongker512536a2010-02-17 16:11:44 -0800512 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800513 if (*ps != '\0') return -1;
514 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800515}
516
Doug Zongkerc4351c72010-02-22 14:46:32 -0800517// Search an array of sha1 strings for one matching the given sha1.
518// Return the index of the match on success, or -1 if no match is
519// found.
Doug Zongker044a0b42013-07-08 09:42:54 -0700520int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800521 int num_patches) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800522 uint8_t patch_sha1[SHA_DIGEST_LENGTH];
Tao Baoba9a42a2015-06-23 23:23:33 -0700523 for (int i = 0; i < num_patches; ++i) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800524 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800525 memcmp(patch_sha1, sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800526 return i;
527 }
Doug Zongker512536a2010-02-17 16:11:44 -0800528 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800529 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800530}
531
532// Returns 0 if the contents of the file (argv[2]) or the cached file
533// match any of the sha1's on the command line (argv[3:]). Returns
534// nonzero otherwise.
Tao Baoba9a42a2015-06-23 23:23:33 -0700535int applypatch_check(const char* filename, int num_patches,
536 char** const patch_sha1_str) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800537 FileContents file;
538 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800539
Doug Zongkerc4351c72010-02-22 14:46:32 -0800540 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700541 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800542 // partitions, where the filename encodes the sha1s; no need to
543 // check them twice.)
Doug Zongkera1bc1482014-02-13 15:18:19 -0800544 if (LoadFileContents(filename, &file) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800545 (num_patches > 0 &&
546 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
547 printf("file \"%s\" doesn't have any of expected "
548 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800549
Doug Zongkerc4351c72010-02-22 14:46:32 -0800550 free(file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800551 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800552
Doug Zongkerc4351c72010-02-22 14:46:32 -0800553 // If the source file is missing or corrupted, it might be because
554 // we were killed in the middle of patching it. A copy of it
555 // should have been made in CACHE_TEMP_SOURCE. If that file
556 // exists and matches the sha1 we're looking for, the check still
557 // passes.
558
Doug Zongkera1bc1482014-02-13 15:18:19 -0800559 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800560 printf("failed to load cache file\n");
561 return 1;
562 }
563
564 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
565 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
566 free(file.data);
567 return 1;
568 }
569 }
Doug Zongker512536a2010-02-17 16:11:44 -0800570
571 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800572 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800573}
574
575int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800576 ShowBSDiffLicense();
577 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800578}
579
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700580ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700581 int fd = *reinterpret_cast<int *>(token);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800582 ssize_t done = 0;
583 ssize_t wrote;
Tao Baoba9a42a2015-06-23 23:23:33 -0700584 while (done < len) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700585 wrote = TEMP_FAILURE_RETRY(write(fd, data+done, len-done));
586 if (wrote == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700587 printf("error writing %zd bytes: %s\n", (len-done), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800588 return done;
589 }
590 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800591 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800592 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800593}
594
595typedef struct {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800596 unsigned char* buffer;
597 ssize_t size;
598 ssize_t pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800599} MemorySinkInfo;
600
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700601ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700602 MemorySinkInfo* msi = reinterpret_cast<MemorySinkInfo*>(token);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800603 if (msi->size - msi->pos < len) {
604 return -1;
605 }
606 memcpy(msi->buffer + msi->pos, data, len);
607 msi->pos += len;
608 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800609}
610
611// Return the amount of free space (in bytes) on the filesystem
612// containing filename. filename must exist. Return -1 on error.
613size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800614 struct statfs sf;
615 if (statfs(filename, &sf) != 0) {
616 printf("failed to statfs %s: %s\n", filename, strerror(errno));
617 return -1;
618 }
caozhiyuan3b497762015-05-19 17:21:00 +0800619 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800620}
621
Doug Zongkerc4351c72010-02-22 14:46:32 -0800622int CacheSizeCheck(size_t bytes) {
623 if (MakeFreeSpaceOnCache(bytes) < 0) {
624 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
625 return 1;
626 } else {
627 return 0;
628 }
629}
630
Doug Zongkerc4351c72010-02-22 14:46:32 -0800631// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800632// (the original file is not touched until we have the desired
633// replacement for it) and idempotent (it's okay to run this program
634// multiple times).
635//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800636// - if the sha1 hash of <target_filename> is <target_sha1_string>,
637// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800638//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800639// - otherwise, if the sha1 hash of <source_filename> is one of the
640// entries in <patch_sha1_str>, the corresponding patch from
641// <patch_data> (which must be a VAL_BLOB) is applied to produce a
642// new file (the type of patch is automatically detected from the
Tao Baoabba55b2015-07-17 18:11:12 -0700643// blob data). If that new file has sha1 hash <target_sha1_str>,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800644// moves it to replace <target_filename>, and exits successfully.
645// Note that if <source_filename> and <target_filename> are not the
646// same, <source_filename> is NOT deleted on success.
647// <target_filename> may be the string "-" to mean "the same as
648// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800649//
650// - otherwise, or if any error is encountered, exits with non-zero
651// status.
652//
Doug Zongkerf291d852010-07-07 13:55:25 -0700653// <source_filename> may refer to a partition to read the source data.
Tao Baoabba55b2015-07-17 18:11:12 -0700654// See the comments for the LoadPartitionContents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800655// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800656
Doug Zongkerc4351c72010-02-22 14:46:32 -0800657int applypatch(const char* source_filename,
658 const char* target_filename,
659 const char* target_sha1_str,
660 size_t target_size,
661 int num_patches,
662 char** const patch_sha1_str,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700663 Value** patch_data,
664 Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700665 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800666
Tao Baoba9a42a2015-06-23 23:23:33 -0700667 if (target_filename[0] == '-' && target_filename[1] == '\0') {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800668 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800669 }
670
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800671 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800672 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
673 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800674 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800675 }
Doug Zongker512536a2010-02-17 16:11:44 -0800676
Doug Zongkerc4351c72010-02-22 14:46:32 -0800677 FileContents copy_file;
678 FileContents source_file;
Doug Zongker1c43c972012-02-28 11:07:09 -0800679 copy_file.data = NULL;
680 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800681 const Value* source_patch_value = NULL;
682 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800683
Doug Zongkerc4351c72010-02-22 14:46:32 -0800684 // We try to load the target file into the source_file object.
Doug Zongkera1bc1482014-02-13 15:18:19 -0800685 if (LoadFileContents(target_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800686 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800687 // The early-exit case: the patch was already applied, this file
688 // has the desired hash, nothing for us to do.
Tao Baoabba55b2015-07-17 18:11:12 -0700689 printf("already %s\n", short_sha1(target_sha1).c_str());
Doug Zongker1c43c972012-02-28 11:07:09 -0800690 free(source_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800691 return 0;
692 }
693 }
Doug Zongker512536a2010-02-17 16:11:44 -0800694
Doug Zongkerc4351c72010-02-22 14:46:32 -0800695 if (source_file.data == NULL ||
696 (target_filename != source_filename &&
697 strcmp(target_filename, source_filename) != 0)) {
698 // Need to load the source file: either we failed to load the
699 // target file, or we did but it's different from the source file.
700 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800701 source_file.data = NULL;
Doug Zongkera1bc1482014-02-13 15:18:19 -0800702 LoadFileContents(source_filename, &source_file);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800703 }
704
705 if (source_file.data != NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700706 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1_str, num_patches);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800707 if (to_use >= 0) {
708 source_patch_value = patch_data[to_use];
709 }
710 }
711
712 if (source_patch_value == NULL) {
713 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800714 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800715 printf("source file is bad; trying copy\n");
716
Doug Zongkera1bc1482014-02-13 15:18:19 -0800717 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800718 // fail.
719 printf("failed to read copy file\n");
720 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800721 }
722
Tao Baoba9a42a2015-06-23 23:23:33 -0700723 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700724 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800725 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800726 }
727
Doug Zongkerc4351c72010-02-22 14:46:32 -0800728 if (copy_patch_value == NULL) {
729 // fail.
730 printf("copy file doesn't match source SHA-1s either\n");
Doug Zongker1c43c972012-02-28 11:07:09 -0800731 free(copy_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800732 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800733 }
Doug Zongker512536a2010-02-17 16:11:44 -0800734 }
735
Doug Zongker1c43c972012-02-28 11:07:09 -0800736 int result = GenerateTarget(&source_file, source_patch_value,
737 &copy_file, copy_patch_value,
738 source_filename, target_filename,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700739 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800740 free(source_file.data);
741 free(copy_file.data);
742
743 return result;
744}
745
Tao Baoabba55b2015-07-17 18:11:12 -0700746/*
747 * This function flashes a given image to the target partition. It verifies
748 * the target cheksum first, and will return if target has the desired hash.
749 * It checks the checksum of the given source image before flashing, and
750 * verifies the target partition afterwards. The function is idempotent.
751 * Returns zero on success.
752 */
753int applypatch_flash(const char* source_filename, const char* target_filename,
754 const char* target_sha1_str, size_t target_size) {
755 printf("flash %s: ", target_filename);
756
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800757 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Tao Baoabba55b2015-07-17 18:11:12 -0700758 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
759 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
760 return 1;
761 }
762
763 FileContents source_file;
764 source_file.data = NULL;
765 std::string target_str(target_filename);
766
767 std::vector<std::string> pieces = android::base::Split(target_str, ":");
768 if (pieces.size() != 2 || (pieces[0] != "MTD" && pieces[0] != "EMMC")) {
769 printf("invalid target name \"%s\"", target_filename);
770 return 1;
771 }
772
773 // Load the target into the source_file object to see if already applied.
774 pieces.push_back(std::to_string(target_size));
775 pieces.push_back(target_sha1_str);
776 std::string fullname = android::base::Join(pieces, ':');
777 if (LoadPartitionContents(fullname.c_str(), &source_file) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800778 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700779 // The early-exit case: the image was already applied, this partition
780 // has the desired hash, nothing for us to do.
781 printf("already %s\n", short_sha1(target_sha1).c_str());
782 free(source_file.data);
783 return 0;
784 }
785
786 if (LoadFileContents(source_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800787 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700788 // The source doesn't have desired checksum.
789 printf("source \"%s\" doesn't have expected sha1 sum\n", source_filename);
790 printf("expected: %s, found: %s\n", short_sha1(target_sha1).c_str(),
791 short_sha1(source_file.sha1).c_str());
792 free(source_file.data);
793 return 1;
794 }
795 }
796
797 if (WriteToPartition(source_file.data, target_size, target_filename) != 0) {
798 printf("write of copied data to %s failed\n", target_filename);
799 free(source_file.data);
800 return 1;
801 }
802
803 free(source_file.data);
804 return 0;
805}
806
Doug Zongker1c43c972012-02-28 11:07:09 -0800807static int GenerateTarget(FileContents* source_file,
808 const Value* source_patch_value,
809 FileContents* copy_file,
810 const Value* copy_patch_value,
811 const char* source_filename,
812 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800813 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700814 size_t target_size,
815 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800816 int retry = 1;
817 SHA_CTX ctx;
818 int output;
819 MemorySinkInfo msi;
820 FileContents* source_to_use;
821 char* outname;
Doug Zongker1c43c972012-02-28 11:07:09 -0800822 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800823
824 // assume that target_filename (eg "/system/app/Foo.apk") is located
825 // on the same filesystem as its top-level directory ("/system").
826 // We need something that exists for calling statfs().
827 char target_fs[strlen(target_filename)+1];
828 char* slash = strchr(target_filename+1, '/');
829 if (slash != NULL) {
830 int count = slash - target_filename;
831 strncpy(target_fs, target_filename, count);
832 target_fs[count] = '\0';
Doug Zongker512536a2010-02-17 16:11:44 -0800833 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800834 strcpy(target_fs, target_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800835 }
836
Doug Zongkerc4351c72010-02-22 14:46:32 -0800837 do {
838 // Is there enough room in the target filesystem to hold the patched
839 // file?
840
Doug Zongkerf291d852010-07-07 13:55:25 -0700841 if (strncmp(target_filename, "MTD:", 4) == 0 ||
842 strncmp(target_filename, "EMMC:", 5) == 0) {
843 // If the target is a partition, we're actually going to
844 // write the output to /tmp and then copy it to the
845 // partition. statfs() always returns 0 blocks free for
846 // /tmp, so instead we'll just assume that /tmp has enough
847 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800848
Doug Zongkerf291d852010-07-07 13:55:25 -0700849 // We still write the original source to cache, in case
850 // the partition write is interrupted.
Doug Zongker1c43c972012-02-28 11:07:09 -0800851 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800852 printf("not enough free space on /cache\n");
853 return 1;
854 }
855 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
856 printf("failed to back up source file\n");
857 return 1;
858 }
859 made_copy = 1;
860 retry = 0;
861 } else {
862 int enough_space = 0;
863 if (retry > 0) {
864 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongker201cd462010-08-13 09:41:21 -0700865 enough_space =
866 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800867 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700868 if (!enough_space) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700869 printf("target %zu bytes; free space %zu bytes; retry %d; enough %d\n",
870 target_size, free_space, retry, enough_space);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700871 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800872 }
873
874 if (!enough_space) {
875 retry = 0;
876 }
877
878 if (!enough_space && source_patch_value != NULL) {
879 // Using the original source, but not enough free space. First
880 // copy the source file to cache, then delete it from the original
881 // location.
882
Doug Zongkerf291d852010-07-07 13:55:25 -0700883 if (strncmp(source_filename, "MTD:", 4) == 0 ||
884 strncmp(source_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800885 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700886 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800887 // we're ever in a state where we need to do this, fail.
Tao Baoba9a42a2015-06-23 23:23:33 -0700888 printf("not enough free space for target but source is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800889 return 1;
890 }
891
Doug Zongker1c43c972012-02-28 11:07:09 -0800892 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800893 printf("not enough free space on /cache\n");
894 return 1;
895 }
896
897 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
898 printf("failed to back up source file\n");
899 return 1;
900 }
901 made_copy = 1;
902 unlink(source_filename);
903
904 size_t free_space = FreeSpaceForFile(target_fs);
Tao Baoba9a42a2015-06-23 23:23:33 -0700905 printf("(now %zu bytes free for target) ", free_space);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800906 }
907 }
908
909 const Value* patch;
910 if (source_patch_value != NULL) {
Doug Zongker1c43c972012-02-28 11:07:09 -0800911 source_to_use = source_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800912 patch = source_patch_value;
913 } else {
Doug Zongker1c43c972012-02-28 11:07:09 -0800914 source_to_use = copy_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800915 patch = copy_patch_value;
916 }
917
918 if (patch->type != VAL_BLOB) {
919 printf("patch is not a blob\n");
920 return 1;
921 }
922
923 SinkFn sink = NULL;
924 void* token = NULL;
925 output = -1;
926 outname = NULL;
Doug Zongkerf291d852010-07-07 13:55:25 -0700927 if (strncmp(target_filename, "MTD:", 4) == 0 ||
928 strncmp(target_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800929 // We store the decoded output in memory.
Tao Baoba9a42a2015-06-23 23:23:33 -0700930 msi.buffer = reinterpret_cast<unsigned char*>(malloc(target_size));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800931 if (msi.buffer == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700932 printf("failed to alloc %zu bytes for output\n", target_size);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800933 return 1;
934 }
935 msi.pos = 0;
936 msi.size = target_size;
937 sink = MemorySink;
938 token = &msi;
939 } else {
940 // We write the decoded output to "<tgt-file>.patch".
Tao Baoba9a42a2015-06-23 23:23:33 -0700941 outname = reinterpret_cast<char*>(malloc(strlen(target_filename) + 10));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800942 strcpy(outname, target_filename);
943 strcat(outname, ".patch");
944
Tao Baoba9a42a2015-06-23 23:23:33 -0700945 output = open(outname, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800946 if (output < 0) {
947 printf("failed to open output file %s: %s\n",
948 outname, strerror(errno));
949 return 1;
950 }
951 sink = FileSink;
952 token = &output;
953 }
954
955 char* header = patch->data;
956 ssize_t header_bytes_read = patch->size;
957
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800958 SHA1_Init(&ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800959
960 int result;
961
962 if (header_bytes_read >= 8 &&
963 memcmp(header, "BSDIFF40", 8) == 0) {
964 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
965 patch, 0, sink, token, &ctx);
966 } else if (header_bytes_read >= 8 &&
967 memcmp(header, "IMGDIFF2", 8) == 0) {
968 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700969 patch, sink, token, &ctx, bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800970 } else {
971 printf("Unknown patch file format\n");
972 return 1;
973 }
974
975 if (output >= 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700976 if (fsync(output) != 0) {
977 printf("failed to fsync file \"%s\" (%s)\n", outname, strerror(errno));
978 result = 1;
979 }
980 if (close(output) != 0) {
981 printf("failed to close file \"%s\" (%s)\n", outname, strerror(errno));
982 result = 1;
983 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800984 }
985
986 if (result != 0) {
987 if (retry == 0) {
988 printf("applying patch failed\n");
989 return result != 0;
990 } else {
991 printf("applying patch failed; retrying\n");
992 }
993 if (outname != NULL) {
994 unlink(outname);
995 }
996 } else {
997 // succeeded; no need to retry
998 break;
999 }
1000 } while (retry-- > 0);
1001
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001002 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
1003 SHA1_Final(current_target_sha1, &ctx);
1004 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001005 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -08001006 return 1;
Doug Zongkerbf80f492012-10-19 12:24:26 -07001007 } else {
Tao Baoabba55b2015-07-17 18:11:12 -07001008 printf("now %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -08001009 }
1010
1011 if (output < 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -07001012 // Copy the temp file to the partition.
1013 if (WriteToPartition(msi.buffer, msi.pos, target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001014 printf("write of patched data to %s failed\n", target_filename);
1015 return 1;
1016 }
1017 free(msi.buffer);
Doug Zongker512536a2010-02-17 16:11:44 -08001018 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001019 // Give the .patch file the same owner, group, and mode of the
1020 // original source file.
1021 if (chmod(outname, source_to_use->st.st_mode) != 0) {
1022 printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
1023 return 1;
1024 }
Tao Baoba9a42a2015-06-23 23:23:33 -07001025 if (chown(outname, source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001026 printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
1027 return 1;
1028 }
Doug Zongker512536a2010-02-17 16:11:44 -08001029
Doug Zongkerc4351c72010-02-22 14:46:32 -08001030 // Finally, rename the .patch file to replace the target file.
1031 if (rename(outname, target_filename) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001032 printf("rename of .patch to \"%s\" failed: %s\n", target_filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -08001033 return 1;
1034 }
Doug Zongker512536a2010-02-17 16:11:44 -08001035 }
1036
Doug Zongkerc4351c72010-02-22 14:46:32 -08001037 // If this run of applypatch created the copy, and we're here, we
1038 // can delete it.
Tao Baoba9a42a2015-06-23 23:23:33 -07001039 if (made_copy) {
1040 unlink(CACHE_TEMP_SOURCE);
1041 }
Doug Zongker512536a2010-02-17 16:11:44 -08001042
Doug Zongkerc4351c72010-02-22 14:46:32 -08001043 // Success!
1044 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001045}