blob: 75d77372ead6b9b782f18865bf5471bed2e2bac0 [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
Yabin Cuid483c202016-02-03 17:08:52 -080028#include <memory>
29#include <string>
30
Elliott Hughes4b166f02015-12-04 15:30:20 -080031#include <android-base/strings.h>
Tao Baoaca8e892015-07-17 11:47:44 -070032
Sen Jiangc48cb5e2016-02-04 16:23:21 +080033#include "openssl/sha.h"
Doug Zongker512536a2010-02-17 16:11:44 -080034#include "applypatch.h"
35#include "mtdutils/mtdutils.h"
Doug Zongkerc4351c72010-02-22 14:46:32 -080036#include "edify/expr.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include "print_sha1.h"
Doug Zongker512536a2010-02-17 16:11:44 -080038
Doug Zongkerf291d852010-07-07 13:55:25 -070039static int LoadPartitionContents(const char* filename, FileContents* file);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070040static ssize_t FileSink(const unsigned char* data, ssize_t len, void* token);
Doug Zongker1c43c972012-02-28 11:07:09 -080041static int GenerateTarget(FileContents* source_file,
42 const Value* source_patch_value,
43 FileContents* copy_file,
44 const Value* copy_patch_value,
45 const char* source_filename,
46 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +080047 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -070048 size_t target_size,
49 const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080050
Tao Baoaca8e892015-07-17 11:47:44 -070051static bool mtd_partitions_scanned = false;
Doug Zongker512536a2010-02-17 16:11:44 -080052
Doug Zongkera1bc1482014-02-13 15:18:19 -080053// Read a file into memory; store the file contents and associated
Hristo Bojinovdb314d62010-08-02 10:29:49 -070054// metadata in *file.
55//
56// Return 0 on success.
Doug Zongkera1bc1482014-02-13 15:18:19 -080057int LoadFileContents(const char* filename, FileContents* file) {
Doug Zongker512536a2010-02-17 16:11:44 -080058 file->data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -080059
Doug Zongkerf291d852010-07-07 13:55:25 -070060 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
61 // load the contents of a partition.
62 if (strncmp(filename, "MTD:", 4) == 0 ||
63 strncmp(filename, "EMMC:", 5) == 0) {
64 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080065 }
Doug Zongker512536a2010-02-17 16:11:44 -080066
Doug Zongkerc4351c72010-02-22 14:46:32 -080067 if (stat(filename, &file->st) != 0) {
68 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
69 return -1;
70 }
71
72 file->size = file->st.st_size;
Yabin Cuid483c202016-02-03 17:08:52 -080073 file->data = nullptr;
74
75 std::unique_ptr<unsigned char, decltype(&free)> data(
76 static_cast<unsigned char*>(malloc(file->size)), free);
77 if (data == nullptr) {
78 printf("failed to allocate memory: %s\n", strerror(errno));
79 return -1;
80 }
Doug Zongkerc4351c72010-02-22 14:46:32 -080081
82 FILE* f = fopen(filename, "rb");
83 if (f == NULL) {
84 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -080085 return -1;
86 }
87
Yabin Cuid483c202016-02-03 17:08:52 -080088 size_t bytes_read = fread(data.get(), 1, file->size, f);
Tao Baoba9a42a2015-06-23 23:23:33 -070089 if (bytes_read != static_cast<size_t>(file->size)) {
90 printf("short read of \"%s\" (%zu bytes of %zd)\n", filename, bytes_read, file->size);
Yabin Cuid483c202016-02-03 17:08:52 -080091 fclose(f);
Doug Zongkerc4351c72010-02-22 14:46:32 -080092 return -1;
93 }
94 fclose(f);
Yabin Cuid483c202016-02-03 17:08:52 -080095 file->data = data.release();
Sen Jiangc48cb5e2016-02-04 16:23:21 +080096 SHA1(file->data, file->size, file->sha1);
Doug Zongkerc4351c72010-02-22 14:46:32 -080097 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080098}
99
Doug Zongkerf291d852010-07-07 13:55:25 -0700100// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -0800101// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -0700102// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
103// "EMMC:<partition_device>:..."). The smallest size_n bytes for
104// which that prefix of the partition contents has the corresponding
105// sha1 hash will be loaded. It is acceptable for a size value to be
106// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -0800107//
108// This complexity is needed because if an OTA installation is
109// interrupted, the partition might contain either the source or the
110// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700111// the length in order to read from a partition (there is no
112// "end-of-file" marker), so the caller must specify the possible
113// lengths and the hash of the data, and we'll do the load expecting
114// to find one of those hashes.
115enum PartitionType { MTD, EMMC };
116
117static int LoadPartitionContents(const char* filename, FileContents* file) {
Tao Baoaca8e892015-07-17 11:47:44 -0700118 std::string copy(filename);
119 std::vector<std::string> pieces = android::base::Split(copy, ":");
120 if (pieces.size() < 4 || pieces.size() % 2 != 0) {
121 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
122 return -1;
123 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700124
125 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700126 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700127 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700128 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700129 type = EMMC;
130 } else {
Tao Baoba9a42a2015-06-23 23:23:33 -0700131 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800132 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800133 }
Tao Baoaca8e892015-07-17 11:47:44 -0700134 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800135
Tao Baoaca8e892015-07-17 11:47:44 -0700136 size_t pairs = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
137 std::vector<size_t> index(pairs);
138 std::vector<size_t> size(pairs);
139 std::vector<std::string> sha1sum(pairs);
Doug Zongker512536a2010-02-17 16:11:44 -0800140
Tao Baoaca8e892015-07-17 11:47:44 -0700141 for (size_t i = 0; i < pairs; ++i) {
142 size[i] = strtol(pieces[i*2+2].c_str(), NULL, 10);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800143 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700144 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800145 return -1;
146 }
Tao Baoaca8e892015-07-17 11:47:44 -0700147 sha1sum[i] = pieces[i*2+3].c_str();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800148 index[i] = i;
149 }
Doug Zongker512536a2010-02-17 16:11:44 -0800150
Tao Baoaca8e892015-07-17 11:47:44 -0700151 // Sort the index[] array so it indexes the pairs in order of increasing size.
152 sort(index.begin(), index.end(),
153 [&](const size_t& i, const size_t& j) {
154 return (size[i] < size[j]);
155 }
156 );
Doug Zongker512536a2010-02-17 16:11:44 -0800157
Doug Zongkerf291d852010-07-07 13:55:25 -0700158 MtdReadContext* ctx = NULL;
159 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800160
Doug Zongkerf291d852010-07-07 13:55:25 -0700161 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700162 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700163 if (!mtd_partitions_scanned) {
164 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700165 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700166 }
Doug Zongker512536a2010-02-17 16:11:44 -0800167
Doug Zongkerf291d852010-07-07 13:55:25 -0700168 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
169 if (mtd == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700170 printf("mtd partition \"%s\" not found (loading %s)\n", partition, filename);
Doug Zongkerf291d852010-07-07 13:55:25 -0700171 return -1;
172 }
173
174 ctx = mtd_read_partition(mtd);
175 if (ctx == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700176 printf("failed to initialize read of mtd partition \"%s\"\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700177 return -1;
178 }
179 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700180 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700181
182 case EMMC:
183 dev = fopen(partition, "rb");
184 if (dev == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700185 printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700186 return -1;
187 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800188 }
Doug Zongker512536a2010-02-17 16:11:44 -0800189
Doug Zongkerc4351c72010-02-22 14:46:32 -0800190 SHA_CTX sha_ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800191 SHA1_Init(&sha_ctx);
192 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800193
Tao Baoaca8e892015-07-17 11:47:44 -0700194 // Allocate enough memory to hold the largest size.
Yabin Cuid483c202016-02-03 17:08:52 -0800195 file->data = static_cast<unsigned char*>(malloc(size[index[pairs-1]]));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800196 char* p = (char*)file->data;
197 file->size = 0; // # bytes read so far
Tao Baoaca8e892015-07-17 11:47:44 -0700198 bool found = false;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800199
Tao Baoaca8e892015-07-17 11:47:44 -0700200 for (size_t i = 0; i < pairs; ++i) {
201 // Read enough additional bytes to get us up to the next size. (Again,
202 // we're trying the possibilities in order of increasing size).
Doug Zongkerc4351c72010-02-22 14:46:32 -0800203 size_t next = size[index[i]] - file->size;
204 size_t read = 0;
205 if (next > 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700206 switch (type) {
207 case MTD:
208 read = mtd_read_data(ctx, p, next);
209 break;
210
211 case EMMC:
212 read = fread(p, 1, next, dev);
213 break;
214 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800215 if (next != read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700216 printf("short read (%zu bytes of %zu) for partition \"%s\"\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800217 read, next, partition);
218 free(file->data);
219 file->data = NULL;
220 return -1;
221 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800222 SHA1_Update(&sha_ctx, p, read);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800223 file->size += read;
224 }
225
226 // Duplicate the SHA context and finalize the duplicate so we can
227 // check it against this pair's expected hash.
228 SHA_CTX temp_ctx;
229 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800230 uint8_t sha_so_far[SHA_DIGEST_LENGTH];
231 SHA1_Final(sha_so_far, &temp_ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800232
Tao Baoaca8e892015-07-17 11:47:44 -0700233 if (ParseSha1(sha1sum[index[i]].c_str(), parsed_sha) != 0) {
234 printf("failed to parse sha1 %s in %s\n", sha1sum[index[i]].c_str(), filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800235 free(file->data);
236 file->data = NULL;
237 return -1;
238 }
239
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800240 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800241 // we have a match. stop reading the partition; we'll return
242 // the data we've read so far.
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700243 printf("partition read matched size %zu sha %s\n",
Tao Baoaca8e892015-07-17 11:47:44 -0700244 size[index[i]], sha1sum[index[i]].c_str());
245 found = true;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800246 break;
247 }
248
249 p += read;
250 }
251
Doug Zongkerf291d852010-07-07 13:55:25 -0700252 switch (type) {
253 case MTD:
254 mtd_read_close(ctx);
255 break;
256
257 case EMMC:
258 fclose(dev);
259 break;
260 }
261
Doug Zongkerc4351c72010-02-22 14:46:32 -0800262
Tao Baoaca8e892015-07-17 11:47:44 -0700263 if (!found) {
264 // Ran off the end of the list of (size,sha1) pairs without finding a match.
Tao Baoba9a42a2015-06-23 23:23:33 -0700265 printf("contents of partition \"%s\" didn't match %s\n", partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800266 free(file->data);
267 file->data = NULL;
268 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800269 }
270
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800271 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800272
Doug Zongkerc4351c72010-02-22 14:46:32 -0800273 // Fake some stat() info.
274 file->st.st_mode = 0644;
275 file->st.st_uid = 0;
276 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800277
Doug Zongkerc4351c72010-02-22 14:46:32 -0800278 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800279}
280
281
282// Save the contents of the given FileContents object under the given
283// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800284int SaveFileContents(const char* filename, const FileContents* file) {
Michael Rungebe81e512014-10-29 12:42:15 -0700285 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800286 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700287 printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800288 return -1;
289 }
Doug Zongker512536a2010-02-17 16:11:44 -0800290
Doug Zongker1c43c972012-02-28 11:07:09 -0800291 ssize_t bytes_written = FileSink(file->data, file->size, &fd);
292 if (bytes_written != file->size) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700293 printf("short write of \"%s\" (%zd bytes of %zd) (%s)\n",
294 filename, bytes_written, file->size, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800295 close(fd);
296 return -1;
297 }
Michael Rungebe81e512014-10-29 12:42:15 -0700298 if (fsync(fd) != 0) {
299 printf("fsync of \"%s\" failed: %s\n", filename, strerror(errno));
300 return -1;
301 }
302 if (close(fd) != 0) {
303 printf("close of \"%s\" failed: %s\n", filename, strerror(errno));
304 return -1;
305 }
Doug Zongker512536a2010-02-17 16:11:44 -0800306
Doug Zongker1c43c972012-02-28 11:07:09 -0800307 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800308 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
309 return -1;
310 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800311 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800312 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
313 return -1;
314 }
Doug Zongker512536a2010-02-17 16:11:44 -0800315
Doug Zongkerc4351c72010-02-22 14:46:32 -0800316 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800317}
318
Doug Zongkerf291d852010-07-07 13:55:25 -0700319// Write a memory buffer to 'target' partition, a string of the form
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700320// "MTD:<partition>[:...]" or "EMMC:<partition_device>[:...]". The target name
321// might contain multiple colons, but WriteToPartition() only uses the first
322// two and ignores the rest. Return 0 on success.
Yabin Cuid483c202016-02-03 17:08:52 -0800323int WriteToPartition(const unsigned char* data, size_t len, const char* target) {
Tao Baoaca8e892015-07-17 11:47:44 -0700324 std::string copy(target);
325 std::vector<std::string> pieces = android::base::Split(copy, ":");
326
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700327 if (pieces.size() < 2) {
Tao Baoaca8e892015-07-17 11:47:44 -0700328 printf("WriteToPartition called with bad target (%s)\n", target);
329 return -1;
330 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700331
332 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700333 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700334 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700335 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700336 type = EMMC;
337 } else {
338 printf("WriteToPartition called with bad target (%s)\n", target);
339 return -1;
340 }
Tao Baoaca8e892015-07-17 11:47:44 -0700341 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800342
Doug Zongkerf291d852010-07-07 13:55:25 -0700343 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700344 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700345 if (!mtd_partitions_scanned) {
346 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700347 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700348 }
349
350 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
351 if (mtd == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700352 printf("mtd partition \"%s\" not found for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700353 return -1;
354 }
355
356 MtdWriteContext* ctx = mtd_write_partition(mtd);
357 if (ctx == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700358 printf("failed to init mtd partition \"%s\" for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700359 return -1;
360 }
361
Yabin Cuid483c202016-02-03 17:08:52 -0800362 size_t written = mtd_write_data(ctx, reinterpret_cast<const char*>(data), len);
Doug Zongkerf291d852010-07-07 13:55:25 -0700363 if (written != len) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700364 printf("only wrote %zu of %zu bytes to MTD %s\n", written, len, partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700365 mtd_write_close(ctx);
366 return -1;
367 }
368
369 if (mtd_erase_blocks(ctx, -1) < 0) {
370 printf("error finishing mtd write of %s\n", partition);
371 mtd_write_close(ctx);
372 return -1;
373 }
374
375 if (mtd_write_close(ctx)) {
376 printf("error closing mtd write of %s\n", partition);
377 return -1;
378 }
379 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700380 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700381
Tao Baoba9a42a2015-06-23 23:23:33 -0700382 case EMMC: {
Doug Zongker044a0b42013-07-08 09:42:54 -0700383 size_t start = 0;
Tao Baoba9a42a2015-06-23 23:23:33 -0700384 bool success = false;
Michael Rungebe81e512014-10-29 12:42:15 -0700385 int fd = open(partition, O_RDWR | O_SYNC);
Doug Zongkerc870a992013-07-09 10:34:46 -0700386 if (fd < 0) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700387 printf("failed to open %s: %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700388 return -1;
389 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700390
Tao Baoaca8e892015-07-17 11:47:44 -0700391 for (size_t attempt = 0; attempt < 2; ++attempt) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700392 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700393 printf("failed seek on %s: %s\n", partition, strerror(errno));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700394 return -1;
395 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700396 while (start < len) {
397 size_t to_write = len - start;
Doug Zongker168724c2013-12-19 15:16:57 -0800398 if (to_write > 1<<20) to_write = 1<<20;
Doug Zongker044a0b42013-07-08 09:42:54 -0700399
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700400 ssize_t written = TEMP_FAILURE_RETRY(write(fd, data+start, to_write));
401 if (written == -1) {
402 printf("failed write writing to %s: %s\n", partition, strerror(errno));
403 return -1;
Doug Zongker044a0b42013-07-08 09:42:54 -0700404 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700405 start += written;
Doug Zongker044a0b42013-07-08 09:42:54 -0700406 }
Michael Rungebe81e512014-10-29 12:42:15 -0700407 if (fsync(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700408 printf("failed to sync to %s (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700409 return -1;
410 }
411 if (close(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700412 printf("failed to close %s (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700413 return -1;
414 }
415 fd = open(partition, O_RDONLY);
416 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700417 printf("failed to reopen %s for verify (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700418 return -1;
419 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700420
Tao Baoba9a42a2015-06-23 23:23:33 -0700421 // Drop caches so our subsequent verification read
Doug Zongker044a0b42013-07-08 09:42:54 -0700422 // won't just be reading the cache.
423 sync();
Doug Zongkerc870a992013-07-09 10:34:46 -0700424 int dc = open("/proc/sys/vm/drop_caches", O_WRONLY);
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700425 if (TEMP_FAILURE_RETRY(write(dc, "3\n", 2)) == -1) {
426 printf("write to /proc/sys/vm/drop_caches failed: %s\n", strerror(errno));
427 } else {
428 printf(" caches dropped\n");
429 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700430 close(dc);
Doug Zongker044a0b42013-07-08 09:42:54 -0700431 sleep(1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700432
433 // verify
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700434 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
435 printf("failed to seek back to beginning of %s: %s\n",
436 partition, strerror(errno));
437 return -1;
438 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700439 unsigned char buffer[4096];
440 start = len;
Tao Baoba9a42a2015-06-23 23:23:33 -0700441 for (size_t p = 0; p < len; p += sizeof(buffer)) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700442 size_t to_read = len - p;
Tao Baoba9a42a2015-06-23 23:23:33 -0700443 if (to_read > sizeof(buffer)) {
444 to_read = sizeof(buffer);
445 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700446
Doug Zongkerc870a992013-07-09 10:34:46 -0700447 size_t so_far = 0;
448 while (so_far < to_read) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700449 ssize_t read_count =
450 TEMP_FAILURE_RETRY(read(fd, buffer+so_far, to_read-so_far));
451 if (read_count == -1) {
452 printf("verify read error %s at %zu: %s\n",
453 partition, p, strerror(errno));
454 return -1;
Doug Zongkerc870a992013-07-09 10:34:46 -0700455 }
Tao Baoba9a42a2015-06-23 23:23:33 -0700456 if (static_cast<size_t>(read_count) < to_read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700457 printf("short verify read %s at %zu: %zd %zu %s\n",
Doug Zongkerc870a992013-07-09 10:34:46 -0700458 partition, p, read_count, to_read, strerror(errno));
459 }
460 so_far += read_count;
Doug Zongker044a0b42013-07-08 09:42:54 -0700461 }
462
Tao Baoba9a42a2015-06-23 23:23:33 -0700463 if (memcmp(buffer, data+p, to_read) != 0) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700464 printf("verification failed starting at %zu\n", p);
Doug Zongker044a0b42013-07-08 09:42:54 -0700465 start = p;
466 break;
467 }
468 }
469
470 if (start == len) {
Tao Baoabba55b2015-07-17 18:11:12 -0700471 printf("verification read succeeded (attempt %zu)\n", attempt+1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700472 success = true;
473 break;
474 }
475 }
476
477 if (!success) {
478 printf("failed to verify after all attempts\n");
479 return -1;
480 }
481
Doug Zongkerc870a992013-07-09 10:34:46 -0700482 if (close(fd) != 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700483 printf("error closing %s (%s)\n", partition, strerror(errno));
484 return -1;
485 }
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700486 sync();
Doug Zongkerf291d852010-07-07 13:55:25 -0700487 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700488 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800489 }
Doug Zongker512536a2010-02-17 16:11:44 -0800490
Doug Zongkerc4351c72010-02-22 14:46:32 -0800491 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800492}
493
494
495// Take a string 'str' of 40 hex digits and parse it into the 20
496// byte array 'digest'. 'str' may contain only the digest or be of
497// the form "<digest>:<anything>". Return 0 on success, -1 on any
498// error.
499int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800500 const char* ps = str;
501 uint8_t* pd = digest;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800502 for (int i = 0; i < SHA_DIGEST_LENGTH * 2; ++i, ++ps) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800503 int digit;
504 if (*ps >= '0' && *ps <= '9') {
505 digit = *ps - '0';
506 } else if (*ps >= 'a' && *ps <= 'f') {
507 digit = *ps - 'a' + 10;
508 } else if (*ps >= 'A' && *ps <= 'F') {
509 digit = *ps - 'A' + 10;
510 } else {
511 return -1;
512 }
513 if (i % 2 == 0) {
514 *pd = digit << 4;
515 } else {
516 *pd |= digit;
517 ++pd;
518 }
Doug Zongker512536a2010-02-17 16:11:44 -0800519 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800520 if (*ps != '\0') return -1;
521 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800522}
523
Doug Zongkerc4351c72010-02-22 14:46:32 -0800524// Search an array of sha1 strings for one matching the given sha1.
525// Return the index of the match on success, or -1 if no match is
526// found.
Doug Zongker044a0b42013-07-08 09:42:54 -0700527int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800528 int num_patches) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800529 uint8_t patch_sha1[SHA_DIGEST_LENGTH];
Tao Baoba9a42a2015-06-23 23:23:33 -0700530 for (int i = 0; i < num_patches; ++i) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800531 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800532 memcmp(patch_sha1, sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800533 return i;
534 }
Doug Zongker512536a2010-02-17 16:11:44 -0800535 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800536 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800537}
538
539// Returns 0 if the contents of the file (argv[2]) or the cached file
540// match any of the sha1's on the command line (argv[3:]). Returns
541// nonzero otherwise.
Tao Baoba9a42a2015-06-23 23:23:33 -0700542int applypatch_check(const char* filename, int num_patches,
543 char** const patch_sha1_str) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800544 FileContents file;
545 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800546
Doug Zongkerc4351c72010-02-22 14:46:32 -0800547 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700548 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800549 // partitions, where the filename encodes the sha1s; no need to
550 // check them twice.)
Doug Zongkera1bc1482014-02-13 15:18:19 -0800551 if (LoadFileContents(filename, &file) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800552 (num_patches > 0 &&
553 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
554 printf("file \"%s\" doesn't have any of expected "
555 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800556
Doug Zongkerc4351c72010-02-22 14:46:32 -0800557 free(file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800558 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800559
Doug Zongkerc4351c72010-02-22 14:46:32 -0800560 // If the source file is missing or corrupted, it might be because
561 // we were killed in the middle of patching it. A copy of it
562 // should have been made in CACHE_TEMP_SOURCE. If that file
563 // exists and matches the sha1 we're looking for, the check still
564 // passes.
565
Doug Zongkera1bc1482014-02-13 15:18:19 -0800566 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800567 printf("failed to load cache file\n");
568 return 1;
569 }
570
571 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
572 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
573 free(file.data);
574 return 1;
575 }
576 }
Doug Zongker512536a2010-02-17 16:11:44 -0800577
578 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800579 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800580}
581
582int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800583 ShowBSDiffLicense();
584 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800585}
586
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700587ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800588 int fd = *static_cast<int*>(token);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800589 ssize_t done = 0;
590 ssize_t wrote;
Tao Baoba9a42a2015-06-23 23:23:33 -0700591 while (done < len) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700592 wrote = TEMP_FAILURE_RETRY(write(fd, data+done, len-done));
593 if (wrote == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700594 printf("error writing %zd bytes: %s\n", (len-done), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800595 return done;
596 }
597 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800598 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800599 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800600}
601
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700602ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800603 std::string* s = static_cast<std::string*>(token);
604 s->append(reinterpret_cast<const char*>(data), len);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800605 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800606}
607
608// Return the amount of free space (in bytes) on the filesystem
609// containing filename. filename must exist. Return -1 on error.
610size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800611 struct statfs sf;
612 if (statfs(filename, &sf) != 0) {
613 printf("failed to statfs %s: %s\n", filename, strerror(errno));
614 return -1;
615 }
caozhiyuan3b497762015-05-19 17:21:00 +0800616 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800617}
618
Doug Zongkerc4351c72010-02-22 14:46:32 -0800619int CacheSizeCheck(size_t bytes) {
620 if (MakeFreeSpaceOnCache(bytes) < 0) {
621 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
622 return 1;
623 } else {
624 return 0;
625 }
626}
627
Doug Zongkerc4351c72010-02-22 14:46:32 -0800628// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800629// (the original file is not touched until we have the desired
630// replacement for it) and idempotent (it's okay to run this program
631// multiple times).
632//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800633// - if the sha1 hash of <target_filename> is <target_sha1_string>,
634// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800635//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800636// - otherwise, if the sha1 hash of <source_filename> is one of the
637// entries in <patch_sha1_str>, the corresponding patch from
638// <patch_data> (which must be a VAL_BLOB) is applied to produce a
639// new file (the type of patch is automatically detected from the
Tao Baoabba55b2015-07-17 18:11:12 -0700640// blob data). If that new file has sha1 hash <target_sha1_str>,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800641// moves it to replace <target_filename>, and exits successfully.
642// Note that if <source_filename> and <target_filename> are not the
643// same, <source_filename> is NOT deleted on success.
644// <target_filename> may be the string "-" to mean "the same as
645// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800646//
647// - otherwise, or if any error is encountered, exits with non-zero
648// status.
649//
Doug Zongkerf291d852010-07-07 13:55:25 -0700650// <source_filename> may refer to a partition to read the source data.
Tao Baoabba55b2015-07-17 18:11:12 -0700651// See the comments for the LoadPartitionContents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800652// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800653
Doug Zongkerc4351c72010-02-22 14:46:32 -0800654int applypatch(const char* source_filename,
655 const char* target_filename,
656 const char* target_sha1_str,
657 size_t target_size,
658 int num_patches,
659 char** const patch_sha1_str,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700660 Value** patch_data,
661 Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700662 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800663
Tao Baoba9a42a2015-06-23 23:23:33 -0700664 if (target_filename[0] == '-' && target_filename[1] == '\0') {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800665 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800666 }
667
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800668 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800669 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
670 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800671 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800672 }
Doug Zongker512536a2010-02-17 16:11:44 -0800673
Doug Zongkerc4351c72010-02-22 14:46:32 -0800674 FileContents copy_file;
675 FileContents source_file;
Doug Zongker1c43c972012-02-28 11:07:09 -0800676 copy_file.data = NULL;
677 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800678 const Value* source_patch_value = NULL;
679 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800680
Doug Zongkerc4351c72010-02-22 14:46:32 -0800681 // We try to load the target file into the source_file object.
Doug Zongkera1bc1482014-02-13 15:18:19 -0800682 if (LoadFileContents(target_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800683 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800684 // The early-exit case: the patch was already applied, this file
685 // has the desired hash, nothing for us to do.
Tao Baoabba55b2015-07-17 18:11:12 -0700686 printf("already %s\n", short_sha1(target_sha1).c_str());
Doug Zongker1c43c972012-02-28 11:07:09 -0800687 free(source_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800688 return 0;
689 }
690 }
Doug Zongker512536a2010-02-17 16:11:44 -0800691
Doug Zongkerc4351c72010-02-22 14:46:32 -0800692 if (source_file.data == NULL ||
693 (target_filename != source_filename &&
694 strcmp(target_filename, source_filename) != 0)) {
695 // Need to load the source file: either we failed to load the
696 // target file, or we did but it's different from the source file.
697 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800698 source_file.data = NULL;
Doug Zongkera1bc1482014-02-13 15:18:19 -0800699 LoadFileContents(source_filename, &source_file);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800700 }
701
702 if (source_file.data != NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700703 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1_str, num_patches);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800704 if (to_use >= 0) {
705 source_patch_value = patch_data[to_use];
706 }
707 }
708
709 if (source_patch_value == NULL) {
710 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800711 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800712 printf("source file is bad; trying copy\n");
713
Doug Zongkera1bc1482014-02-13 15:18:19 -0800714 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800715 // fail.
716 printf("failed to read copy file\n");
717 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800718 }
719
Tao Baoba9a42a2015-06-23 23:23:33 -0700720 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700721 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800722 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800723 }
724
Doug Zongkerc4351c72010-02-22 14:46:32 -0800725 if (copy_patch_value == NULL) {
726 // fail.
727 printf("copy file doesn't match source SHA-1s either\n");
Doug Zongker1c43c972012-02-28 11:07:09 -0800728 free(copy_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800729 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800730 }
Doug Zongker512536a2010-02-17 16:11:44 -0800731 }
732
Doug Zongker1c43c972012-02-28 11:07:09 -0800733 int result = GenerateTarget(&source_file, source_patch_value,
734 &copy_file, copy_patch_value,
735 source_filename, target_filename,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700736 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800737 free(source_file.data);
738 free(copy_file.data);
739
740 return result;
741}
742
Tao Baoabba55b2015-07-17 18:11:12 -0700743/*
744 * This function flashes a given image to the target partition. It verifies
745 * the target cheksum first, and will return if target has the desired hash.
746 * It checks the checksum of the given source image before flashing, and
747 * verifies the target partition afterwards. The function is idempotent.
748 * Returns zero on success.
749 */
750int applypatch_flash(const char* source_filename, const char* target_filename,
751 const char* target_sha1_str, size_t target_size) {
752 printf("flash %s: ", target_filename);
753
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800754 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Tao Baoabba55b2015-07-17 18:11:12 -0700755 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
756 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
757 return 1;
758 }
759
760 FileContents source_file;
761 source_file.data = NULL;
762 std::string target_str(target_filename);
763
764 std::vector<std::string> pieces = android::base::Split(target_str, ":");
765 if (pieces.size() != 2 || (pieces[0] != "MTD" && pieces[0] != "EMMC")) {
766 printf("invalid target name \"%s\"", target_filename);
767 return 1;
768 }
769
770 // Load the target into the source_file object to see if already applied.
771 pieces.push_back(std::to_string(target_size));
772 pieces.push_back(target_sha1_str);
773 std::string fullname = android::base::Join(pieces, ':');
774 if (LoadPartitionContents(fullname.c_str(), &source_file) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800775 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700776 // The early-exit case: the image was already applied, this partition
777 // has the desired hash, nothing for us to do.
778 printf("already %s\n", short_sha1(target_sha1).c_str());
779 free(source_file.data);
780 return 0;
781 }
782
783 if (LoadFileContents(source_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800784 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700785 // The source doesn't have desired checksum.
786 printf("source \"%s\" doesn't have expected sha1 sum\n", source_filename);
787 printf("expected: %s, found: %s\n", short_sha1(target_sha1).c_str(),
788 short_sha1(source_file.sha1).c_str());
789 free(source_file.data);
790 return 1;
791 }
792 }
793
794 if (WriteToPartition(source_file.data, target_size, target_filename) != 0) {
795 printf("write of copied data to %s failed\n", target_filename);
796 free(source_file.data);
797 return 1;
798 }
799
800 free(source_file.data);
801 return 0;
802}
803
Doug Zongker1c43c972012-02-28 11:07:09 -0800804static int GenerateTarget(FileContents* source_file,
805 const Value* source_patch_value,
806 FileContents* copy_file,
807 const Value* copy_patch_value,
808 const char* source_filename,
809 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800810 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700811 size_t target_size,
812 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800813 int retry = 1;
814 SHA_CTX ctx;
Yabin Cuid483c202016-02-03 17:08:52 -0800815 std::string memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800816 FileContents* source_to_use;
Doug Zongker1c43c972012-02-28 11:07:09 -0800817 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800818
Yabin Cuid483c202016-02-03 17:08:52 -0800819 bool target_is_partition = (strncmp(target_filename, "MTD:", 4) == 0 ||
820 strncmp(target_filename, "EMMC:", 5) == 0);
821 const std::string tmp_target_filename = std::string(target_filename) + ".patch";
822
Doug Zongkerc4351c72010-02-22 14:46:32 -0800823 // assume that target_filename (eg "/system/app/Foo.apk") is located
824 // on the same filesystem as its top-level directory ("/system").
825 // We need something that exists for calling statfs().
Yabin Cuid483c202016-02-03 17:08:52 -0800826 std::string target_fs = target_filename;
827 auto slash_pos = target_fs.find('/', 1);
828 if (slash_pos != std::string::npos) {
829 target_fs.resize(slash_pos);
830 }
831
832 const Value* patch;
833 if (source_patch_value != NULL) {
834 source_to_use = source_file;
835 patch = source_patch_value;
Doug Zongker512536a2010-02-17 16:11:44 -0800836 } else {
Yabin Cuid483c202016-02-03 17:08:52 -0800837 source_to_use = copy_file;
838 patch = copy_patch_value;
839 }
840 if (patch->type != VAL_BLOB) {
841 printf("patch is not a blob\n");
842 return 1;
843 }
844 char* header = patch->data;
845 ssize_t header_bytes_read = patch->size;
846 bool use_bsdiff = false;
847 if (header_bytes_read >= 8 && memcmp(header, "BSDIFF40", 8) == 0) {
848 use_bsdiff = true;
849 } else if (header_bytes_read >= 8 && memcmp(header, "IMGDIFF2", 8) == 0) {
850 use_bsdiff = false;
851 } else {
852 printf("Unknown patch file format\n");
853 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800854 }
855
Doug Zongkerc4351c72010-02-22 14:46:32 -0800856 do {
857 // Is there enough room in the target filesystem to hold the patched
858 // file?
859
Yabin Cuid483c202016-02-03 17:08:52 -0800860 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700861 // If the target is a partition, we're actually going to
862 // write the output to /tmp and then copy it to the
863 // partition. statfs() always returns 0 blocks free for
864 // /tmp, so instead we'll just assume that /tmp has enough
865 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800866
Doug Zongkerf291d852010-07-07 13:55:25 -0700867 // We still write the original source to cache, in case
868 // the partition write is interrupted.
Doug Zongker1c43c972012-02-28 11:07:09 -0800869 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800870 printf("not enough free space on /cache\n");
871 return 1;
872 }
873 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
874 printf("failed to back up source file\n");
875 return 1;
876 }
877 made_copy = 1;
878 retry = 0;
879 } else {
880 int enough_space = 0;
881 if (retry > 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800882 size_t free_space = FreeSpaceForFile(target_fs.c_str());
Doug Zongker201cd462010-08-13 09:41:21 -0700883 enough_space =
884 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800885 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700886 if (!enough_space) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700887 printf("target %zu bytes; free space %zu bytes; retry %d; enough %d\n",
888 target_size, free_space, retry, enough_space);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700889 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800890 }
891
892 if (!enough_space) {
893 retry = 0;
894 }
895
896 if (!enough_space && source_patch_value != NULL) {
897 // Using the original source, but not enough free space. First
898 // copy the source file to cache, then delete it from the original
899 // location.
900
Doug Zongkerf291d852010-07-07 13:55:25 -0700901 if (strncmp(source_filename, "MTD:", 4) == 0 ||
902 strncmp(source_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800903 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700904 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800905 // we're ever in a state where we need to do this, fail.
Tao Baoba9a42a2015-06-23 23:23:33 -0700906 printf("not enough free space for target but source is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800907 return 1;
908 }
909
Doug Zongker1c43c972012-02-28 11:07:09 -0800910 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800911 printf("not enough free space on /cache\n");
912 return 1;
913 }
914
915 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
916 printf("failed to back up source file\n");
917 return 1;
918 }
919 made_copy = 1;
920 unlink(source_filename);
921
Yabin Cuid483c202016-02-03 17:08:52 -0800922 size_t free_space = FreeSpaceForFile(target_fs.c_str());
Tao Baoba9a42a2015-06-23 23:23:33 -0700923 printf("(now %zu bytes free for target) ", free_space);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800924 }
925 }
926
Doug Zongkerc4351c72010-02-22 14:46:32 -0800927
928 SinkFn sink = NULL;
929 void* token = NULL;
Yabin Cuid483c202016-02-03 17:08:52 -0800930 int output_fd = -1;
931 if (target_is_partition) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800932 // We store the decoded output in memory.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800933 sink = MemorySink;
Yabin Cuid483c202016-02-03 17:08:52 -0800934 token = &memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800935 } else {
936 // We write the decoded output to "<tgt-file>.patch".
Yabin Cuid483c202016-02-03 17:08:52 -0800937 output_fd = open(tmp_target_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_SYNC,
938 S_IRUSR | S_IWUSR);
939 if (output_fd < 0) {
940 printf("failed to open output file %s: %s\n", tmp_target_filename.c_str(),
941 strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800942 return 1;
943 }
944 sink = FileSink;
Yabin Cuid483c202016-02-03 17:08:52 -0800945 token = &output_fd;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800946 }
947
Doug Zongkerc4351c72010-02-22 14:46:32 -0800948
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800949 SHA1_Init(&ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800950
951 int result;
Yabin Cuid483c202016-02-03 17:08:52 -0800952 if (use_bsdiff) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800953 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
954 patch, 0, sink, token, &ctx);
Yabin Cuid483c202016-02-03 17:08:52 -0800955 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800956 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700957 patch, sink, token, &ctx, bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800958 }
959
Yabin Cuid483c202016-02-03 17:08:52 -0800960 if (!target_is_partition) {
961 if (fsync(output_fd) != 0) {
962 printf("failed to fsync file \"%s\" (%s)\n", tmp_target_filename.c_str(),
963 strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700964 result = 1;
965 }
Yabin Cuid483c202016-02-03 17:08:52 -0800966 if (close(output_fd) != 0) {
967 printf("failed to close file \"%s\" (%s)\n", tmp_target_filename.c_str(),
968 strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700969 result = 1;
970 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800971 }
972
973 if (result != 0) {
974 if (retry == 0) {
975 printf("applying patch failed\n");
976 return result != 0;
977 } else {
978 printf("applying patch failed; retrying\n");
979 }
Yabin Cuid483c202016-02-03 17:08:52 -0800980 if (!target_is_partition) {
981 unlink(tmp_target_filename.c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800982 }
983 } else {
984 // succeeded; no need to retry
985 break;
986 }
987 } while (retry-- > 0);
988
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800989 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
990 SHA1_Final(current_target_sha1, &ctx);
991 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800992 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800993 return 1;
Doug Zongkerbf80f492012-10-19 12:24:26 -0700994 } else {
Tao Baoabba55b2015-07-17 18:11:12 -0700995 printf("now %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800996 }
997
Yabin Cuid483c202016-02-03 17:08:52 -0800998 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700999 // Copy the temp file to the partition.
Yabin Cuid483c202016-02-03 17:08:52 -08001000 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
1001 memory_sink_str.size(), target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001002 printf("write of patched data to %s failed\n", target_filename);
1003 return 1;
1004 }
Doug Zongker512536a2010-02-17 16:11:44 -08001005 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001006 // Give the .patch file the same owner, group, and mode of the
1007 // original source file.
Yabin Cuid483c202016-02-03 17:08:52 -08001008 if (chmod(tmp_target_filename.c_str(), source_to_use->st.st_mode) != 0) {
1009 printf("chmod of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -08001010 return 1;
1011 }
Yabin Cuid483c202016-02-03 17:08:52 -08001012 if (chown(tmp_target_filename.c_str(), source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
1013 printf("chown of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -08001014 return 1;
1015 }
Doug Zongker512536a2010-02-17 16:11:44 -08001016
Doug Zongkerc4351c72010-02-22 14:46:32 -08001017 // Finally, rename the .patch file to replace the target file.
Yabin Cuid483c202016-02-03 17:08:52 -08001018 if (rename(tmp_target_filename.c_str(), target_filename) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001019 printf("rename of .patch to \"%s\" failed: %s\n", target_filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -08001020 return 1;
1021 }
Doug Zongker512536a2010-02-17 16:11:44 -08001022 }
1023
Doug Zongkerc4351c72010-02-22 14:46:32 -08001024 // If this run of applypatch created the copy, and we're here, we
1025 // can delete it.
Tao Baoba9a42a2015-06-23 23:23:33 -07001026 if (made_copy) {
1027 unlink(CACHE_TEMP_SOURCE);
1028 }
Doug Zongker512536a2010-02-17 16:11:44 -08001029
Doug Zongkerc4351c72010-02-22 14:46:32 -08001030 // Success!
1031 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001032}