blob: 5483a68da407ddf1c60ec728068918524a857c53 [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
Tao Bao8fce75a2016-11-10 12:33:41 -080017#include "applypatch/applypatch.h"
18
Doug Zongker512536a2010-02-17 16:11:44 -080019#include <errno.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070020#include <fcntl.h>
Doug Zongker512536a2010-02-17 16:11:44 -080021#include <libgen.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#include <sys/stat.h>
26#include <sys/statfs.h>
27#include <sys/types.h>
Doug Zongker512536a2010-02-17 16:11:44 -080028#include <unistd.h>
29
Yabin Cuid483c202016-02-03 17:08:52 -080030#include <memory>
31#include <string>
Tao Bao8fce75a2016-11-10 12:33:41 -080032#include <utility>
33#include <vector>
Yabin Cuid483c202016-02-03 17:08:52 -080034
Tao Bao8fce75a2016-11-10 12:33:41 -080035#include <android-base/parseint.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080036#include <android-base/strings.h>
Tao Bao8fce75a2016-11-10 12:33:41 -080037#include <openssl/sha.h>
Tao Baoaca8e892015-07-17 11:47:44 -070038
Doug Zongkerc4351c72010-02-22 14:46:32 -080039#include "edify/expr.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080040#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070041#include "print_sha1.h"
Doug Zongker512536a2010-02-17 16:11:44 -080042
Tao Bao8fce75a2016-11-10 12:33:41 -080043static int LoadPartitionContents(const std::string& filename, FileContents* file);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070044static ssize_t FileSink(const unsigned char* data, ssize_t len, void* token);
Doug Zongker1c43c972012-02-28 11:07:09 -080045static int GenerateTarget(FileContents* source_file,
46 const Value* source_patch_value,
47 FileContents* copy_file,
48 const Value* copy_patch_value,
49 const char* source_filename,
50 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +080051 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -070052 size_t target_size,
53 const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080054
Tao Bao8fce75a2016-11-10 12:33:41 -080055// Read a file into memory; store the file contents and associated metadata in *file.
Hristo Bojinovdb314d62010-08-02 10:29:49 -070056// Return 0 on success.
Doug Zongkera1bc1482014-02-13 15:18:19 -080057int LoadFileContents(const char* filename, FileContents* file) {
Tao Bao8fce75a2016-11-10 12:33:41 -080058 // A special 'filename' beginning with "EMMC:" means to load the contents of a partition.
59 if (strncmp(filename, "EMMC:", 5) == 0) {
60 return LoadPartitionContents(filename, file);
61 }
Doug Zongker512536a2010-02-17 16:11:44 -080062
Tao Bao8fce75a2016-11-10 12:33:41 -080063 if (stat(filename, &file->st) == -1) {
64 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
65 return -1;
66 }
Doug Zongkerc4351c72010-02-22 14:46:32 -080067
Tao Bao8fce75a2016-11-10 12:33:41 -080068 std::vector<unsigned char> data(file->st.st_size);
69 std::unique_ptr<FILE, decltype(&ota_fclose)> f(ota_fopen(filename, "rb"), ota_fclose);
70 if (!f) {
71 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
72 return -1;
73 }
Doug Zongkerc4351c72010-02-22 14:46:32 -080074
Tao Bao8fce75a2016-11-10 12:33:41 -080075 size_t bytes_read = ota_fread(data.data(), 1, data.size(), f.get());
76 if (bytes_read != data.size()) {
77 printf("short read of \"%s\" (%zu bytes of %zu)\n", filename, bytes_read, data.size());
78 return -1;
79 }
80 file->data = std::move(data);
81 SHA1(file->data.data(), file->data.size(), file->sha1);
82 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080083}
84
Elliott Hughes63a31922016-06-09 17:41:22 -070085// Load the contents of an EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -080086// FileContents. filename should be a string of the form
Elliott Hughes63a31922016-06-09 17:41:22 -070087// "EMMC:<partition_device>:...". The smallest size_n bytes for
Doug Zongkerf291d852010-07-07 13:55:25 -070088// which that prefix of the partition contents has the corresponding
89// sha1 hash will be loaded. It is acceptable for a size value to be
90// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -080091//
92// This complexity is needed because if an OTA installation is
93// interrupted, the partition might contain either the source or the
94// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -070095// the length in order to read from a partition (there is no
96// "end-of-file" marker), so the caller must specify the possible
97// lengths and the hash of the data, and we'll do the load expecting
98// to find one of those hashes.
Tao Bao8fce75a2016-11-10 12:33:41 -080099static int LoadPartitionContents(const std::string& filename, FileContents* file) {
100 std::vector<std::string> pieces = android::base::Split(filename, ":");
101 if (pieces.size() < 4 || pieces.size() % 2 != 0 || pieces[0] != "EMMC") {
102 printf("LoadPartitionContents called with bad filename \"%s\"\n", filename.c_str());
103 return -1;
104 }
105
106 size_t pair_count = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
107 std::vector<std::pair<size_t, std::string>> pairs;
108 for (size_t i = 0; i < pair_count; ++i) {
109 size_t size;
110 if (!android::base::ParseUint(pieces[i * 2 + 2], &size) || size == 0) {
111 printf("LoadPartitionContents called with bad size \"%s\"\n", pieces[i * 2 + 2].c_str());
112 return -1;
113 }
114 pairs.push_back({ size, pieces[i * 2 + 3] });
115 }
116
117 // Sort the pairs array so that they are in order of increasing size.
118 std::sort(pairs.begin(), pairs.end());
119
120 const char* partition = pieces[1].c_str();
121 std::unique_ptr<FILE, decltype(&ota_fclose)> dev(ota_fopen(partition, "rb"), ota_fclose);
122 if (!dev) {
123 printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
124 return -1;
125 }
126
127 SHA_CTX sha_ctx;
128 SHA1_Init(&sha_ctx);
129
130 // Allocate enough memory to hold the largest size.
131 std::vector<unsigned char> buffer(pairs[pair_count - 1].first);
132 unsigned char* buffer_ptr = buffer.data();
133 size_t buffer_size = 0; // # bytes read so far
134 bool found = false;
135
136 for (const auto& pair : pairs) {
137 size_t current_size = pair.first;
138 const std::string& current_sha1 = pair.second;
139
140 // Read enough additional bytes to get us up to the next size. (Again,
141 // we're trying the possibilities in order of increasing size).
142 size_t next = current_size - buffer_size;
143 if (next > 0) {
144 size_t read = ota_fread(buffer_ptr, 1, next, dev.get());
145 if (next != read) {
146 printf("short read (%zu bytes of %zu) for partition \"%s\"\n", read, next, partition);
Tao Baoaca8e892015-07-17 11:47:44 -0700147 return -1;
Tao Bao8fce75a2016-11-10 12:33:41 -0800148 }
149 SHA1_Update(&sha_ctx, buffer_ptr, read);
150 buffer_size += read;
151 buffer_ptr += read;
Tao Baoaca8e892015-07-17 11:47:44 -0700152 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700153
Tao Bao8fce75a2016-11-10 12:33:41 -0800154 // Duplicate the SHA context and finalize the duplicate so we can
155 // check it against this pair's expected hash.
156 SHA_CTX temp_ctx;
157 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
158 uint8_t sha_so_far[SHA_DIGEST_LENGTH];
159 SHA1_Final(sha_so_far, &temp_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800160
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800161 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Tao Bao8fce75a2016-11-10 12:33:41 -0800162 if (ParseSha1(current_sha1.c_str(), parsed_sha) != 0) {
163 printf("failed to parse SHA-1 %s in %s\n", current_sha1.c_str(), filename.c_str());
164 return -1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800165 }
166
Tao Bao8fce75a2016-11-10 12:33:41 -0800167 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
168 // We have a match. Stop reading the partition; we'll return the data we've read so far.
169 printf("partition read matched size %zu SHA-1 %s\n", current_size, current_sha1.c_str());
170 found = true;
171 break;
Doug Zongker512536a2010-02-17 16:11:44 -0800172 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800173 }
Doug Zongker512536a2010-02-17 16:11:44 -0800174
Tao Bao8fce75a2016-11-10 12:33:41 -0800175 if (!found) {
176 // Ran off the end of the list of (size, sha1) pairs without finding a match.
177 printf("contents of partition \"%s\" didn't match %s\n", partition, filename.c_str());
178 return -1;
179 }
Doug Zongker512536a2010-02-17 16:11:44 -0800180
Tao Bao8fce75a2016-11-10 12:33:41 -0800181 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800182
Tao Bao8fce75a2016-11-10 12:33:41 -0800183 buffer.resize(buffer_size);
184 file->data = std::move(buffer);
185 // Fake some stat() info.
186 file->st.st_mode = 0644;
187 file->st.st_uid = 0;
188 file->st.st_gid = 0;
189
190 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800191}
192
193
194// Save the contents of the given FileContents object under the given
195// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800196int SaveFileContents(const char* filename, const FileContents* file) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800197 int fd = ota_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800198 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700199 printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800200 return -1;
201 }
Doug Zongker512536a2010-02-17 16:11:44 -0800202
Yabin Cuid6c93af2016-02-10 16:41:10 -0800203 ssize_t bytes_written = FileSink(file->data.data(), file->data.size(), &fd);
204 if (bytes_written != static_cast<ssize_t>(file->data.size())) {
205 printf("short write of \"%s\" (%zd bytes of %zu) (%s)\n",
206 filename, bytes_written, file->data.size(), strerror(errno));
Jed Estepa7b9a462015-12-15 16:04:53 -0800207 ota_close(fd);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800208 return -1;
209 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800210 if (ota_fsync(fd) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700211 printf("fsync of \"%s\" failed: %s\n", filename, strerror(errno));
212 return -1;
213 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800214 if (ota_close(fd) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700215 printf("close of \"%s\" failed: %s\n", filename, strerror(errno));
216 return -1;
217 }
Doug Zongker512536a2010-02-17 16:11:44 -0800218
Doug Zongker1c43c972012-02-28 11:07:09 -0800219 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800220 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
221 return -1;
222 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800223 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800224 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
225 return -1;
226 }
Doug Zongker512536a2010-02-17 16:11:44 -0800227
Doug Zongkerc4351c72010-02-22 14:46:32 -0800228 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800229}
230
Doug Zongkerf291d852010-07-07 13:55:25 -0700231// Write a memory buffer to 'target' partition, a string of the form
Elliott Hughes63a31922016-06-09 17:41:22 -0700232// "EMMC:<partition_device>[:...]". The target name
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700233// might contain multiple colons, but WriteToPartition() only uses the first
234// two and ignores the rest. Return 0 on success.
Yabin Cuid483c202016-02-03 17:08:52 -0800235int WriteToPartition(const unsigned char* data, size_t len, const char* target) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800236 std::vector<std::string> pieces = android::base::Split(std::string(target), ":");
Tao Baoaca8e892015-07-17 11:47:44 -0700237
Tao Bao8fce75a2016-11-10 12:33:41 -0800238 if (pieces.size() < 2 || pieces[0] != "EMMC") {
239 printf("WriteToPartition called with bad target (%s)\n", target);
240 return -1;
241 }
242
243 const char* partition = pieces[1].c_str();
244
245 size_t start = 0;
246 bool success = false;
247 int fd = ota_open(partition, O_RDWR | O_SYNC);
248 if (fd < 0) {
249 printf("failed to open %s: %s\n", partition, strerror(errno));
250 return -1;
251 }
252
253 for (size_t attempt = 0; attempt < 2; ++attempt) {
254 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
255 printf("failed seek on %s: %s\n", partition, strerror(errno));
256 return -1;
257 }
258 while (start < len) {
259 size_t to_write = len - start;
260 if (to_write > 1 << 20) to_write = 1 << 20;
261
262 ssize_t written = TEMP_FAILURE_RETRY(ota_write(fd, data + start, to_write));
263 if (written == -1) {
264 printf("failed write writing to %s: %s\n", partition, strerror(errno));
Tao Baoaca8e892015-07-17 11:47:44 -0700265 return -1;
Tao Bao8fce75a2016-11-10 12:33:41 -0800266 }
267 start += written;
Tao Baoaca8e892015-07-17 11:47:44 -0700268 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700269
Tao Bao8fce75a2016-11-10 12:33:41 -0800270 if (ota_fsync(fd) != 0) {
271 printf("failed to sync to %s (%s)\n", partition, strerror(errno));
272 return -1;
Doug Zongkerf291d852010-07-07 13:55:25 -0700273 }
Elliott Hughes63a31922016-06-09 17:41:22 -0700274 if (ota_close(fd) != 0) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800275 printf("failed to close %s (%s)\n", partition, strerror(errno));
276 return -1;
Elliott Hughes63a31922016-06-09 17:41:22 -0700277 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800278
279 fd = ota_open(partition, O_RDONLY);
280 if (fd < 0) {
281 printf("failed to reopen %s for verify (%s)\n", partition, strerror(errno));
282 return -1;
283 }
284
285 // Drop caches so our subsequent verification read won't just be reading the cache.
Elliott Hughes63a31922016-06-09 17:41:22 -0700286 sync();
Tao Bao8fce75a2016-11-10 12:33:41 -0800287 int dc = ota_open("/proc/sys/vm/drop_caches", O_WRONLY);
288 if (TEMP_FAILURE_RETRY(ota_write(dc, "3\n", 2)) == -1) {
289 printf("write to /proc/sys/vm/drop_caches failed: %s\n", strerror(errno));
290 } else {
291 printf(" caches dropped\n");
292 }
293 ota_close(dc);
294 sleep(1);
Elliott Hughes63a31922016-06-09 17:41:22 -0700295
Tao Bao8fce75a2016-11-10 12:33:41 -0800296 // verify
297 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
298 printf("failed to seek back to beginning of %s: %s\n", partition, strerror(errno));
299 return -1;
300 }
301
302 unsigned char buffer[4096];
303 start = len;
304 for (size_t p = 0; p < len; p += sizeof(buffer)) {
305 size_t to_read = len - p;
306 if (to_read > sizeof(buffer)) {
307 to_read = sizeof(buffer);
308 }
309
310 size_t so_far = 0;
311 while (so_far < to_read) {
312 ssize_t read_count = TEMP_FAILURE_RETRY(ota_read(fd, buffer + so_far, to_read - so_far));
313 if (read_count == -1) {
314 printf("verify read error %s at %zu: %s\n", partition, p, strerror(errno));
315 return -1;
316 } else if (read_count == 0) {
317 printf("verify read reached unexpected EOF, %s at %zu\n", partition, p);
318 return -1;
319 }
320 if (static_cast<size_t>(read_count) < to_read) {
321 printf("short verify read %s at %zu: %zd %zu %s\n", partition, p, read_count, to_read,
322 strerror(errno));
323 }
324 so_far += read_count;
325 }
326
327 if (memcmp(buffer, data + p, to_read) != 0) {
328 printf("verification failed starting at %zu\n", p);
329 start = p;
330 break;
331 }
332 }
333
334 if (start == len) {
335 printf("verification read succeeded (attempt %zu)\n", attempt + 1);
336 success = true;
337 break;
338 }
339 }
340
341 if (!success) {
342 printf("failed to verify after all attempts\n");
343 return -1;
344 }
345
346 if (ota_close(fd) != 0) {
347 printf("error closing %s (%s)\n", partition, strerror(errno));
348 return -1;
349 }
350 sync();
351
352 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800353}
354
Doug Zongker512536a2010-02-17 16:11:44 -0800355// Take a string 'str' of 40 hex digits and parse it into the 20
356// byte array 'digest'. 'str' may contain only the digest or be of
357// the form "<digest>:<anything>". Return 0 on success, -1 on any
358// error.
359int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800360 const char* ps = str;
361 uint8_t* pd = digest;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800362 for (int i = 0; i < SHA_DIGEST_LENGTH * 2; ++i, ++ps) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800363 int digit;
364 if (*ps >= '0' && *ps <= '9') {
365 digit = *ps - '0';
366 } else if (*ps >= 'a' && *ps <= 'f') {
367 digit = *ps - 'a' + 10;
368 } else if (*ps >= 'A' && *ps <= 'F') {
369 digit = *ps - 'A' + 10;
370 } else {
371 return -1;
372 }
373 if (i % 2 == 0) {
374 *pd = digit << 4;
375 } else {
376 *pd |= digit;
377 ++pd;
378 }
Doug Zongker512536a2010-02-17 16:11:44 -0800379 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800380 if (*ps != '\0') return -1;
381 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800382}
383
Doug Zongkerc4351c72010-02-22 14:46:32 -0800384// Search an array of sha1 strings for one matching the given sha1.
385// Return the index of the match on success, or -1 if no match is
386// found.
Tianjie Xuaced5d92016-10-12 10:55:04 -0700387int FindMatchingPatch(uint8_t* sha1, const std::vector<std::string>& patch_sha1_str) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800388 for (size_t i = 0; i < patch_sha1_str.size(); ++i) {
389 uint8_t patch_sha1[SHA_DIGEST_LENGTH];
390 if (ParseSha1(patch_sha1_str[i].c_str(), patch_sha1) == 0 &&
391 memcmp(patch_sha1, sha1, SHA_DIGEST_LENGTH) == 0) {
392 return i;
Doug Zongker512536a2010-02-17 16:11:44 -0800393 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800394 }
395 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800396}
397
398// Returns 0 if the contents of the file (argv[2]) or the cached file
399// match any of the sha1's on the command line (argv[3:]). Returns
400// nonzero otherwise.
Tianjie Xuaced5d92016-10-12 10:55:04 -0700401int applypatch_check(const char* filename, const std::vector<std::string>& patch_sha1_str) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800402 FileContents file;
Doug Zongker512536a2010-02-17 16:11:44 -0800403
Tao Bao8fce75a2016-11-10 12:33:41 -0800404 // It's okay to specify no sha1s; the check will pass if the
405 // LoadFileContents is successful. (Useful for reading
406 // partitions, where the filename encodes the sha1s; no need to
407 // check them twice.)
408 if (LoadFileContents(filename, &file) != 0 ||
409 (!patch_sha1_str.empty() && FindMatchingPatch(file.sha1, patch_sha1_str) < 0)) {
410 printf("file \"%s\" doesn't have any of expected sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800411
Tao Bao8fce75a2016-11-10 12:33:41 -0800412 // If the source file is missing or corrupted, it might be because
413 // we were killed in the middle of patching it. A copy of it
414 // should have been made in CACHE_TEMP_SOURCE. If that file
415 // exists and matches the sha1 we're looking for, the check still
416 // passes.
417 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
418 printf("failed to load cache file\n");
419 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800420 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800421
422 if (FindMatchingPatch(file.sha1, patch_sha1_str) < 0) {
423 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
424 return 1;
425 }
426 }
427 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800428}
429
430int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800431 ShowBSDiffLicense();
432 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800433}
434
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700435ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800436 int fd = *static_cast<int*>(token);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800437 ssize_t done = 0;
438 ssize_t wrote;
Tao Baoba9a42a2015-06-23 23:23:33 -0700439 while (done < len) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800440 wrote = TEMP_FAILURE_RETRY(ota_write(fd, data+done, len-done));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700441 if (wrote == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700442 printf("error writing %zd bytes: %s\n", (len-done), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800443 return done;
444 }
445 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800446 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800447 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800448}
449
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700450ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800451 std::string* s = static_cast<std::string*>(token);
452 s->append(reinterpret_cast<const char*>(data), len);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800453 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800454}
455
456// Return the amount of free space (in bytes) on the filesystem
457// containing filename. filename must exist. Return -1 on error.
458size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800459 struct statfs sf;
460 if (statfs(filename, &sf) != 0) {
461 printf("failed to statfs %s: %s\n", filename, strerror(errno));
462 return -1;
463 }
caozhiyuan3b497762015-05-19 17:21:00 +0800464 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800465}
466
Doug Zongkerc4351c72010-02-22 14:46:32 -0800467int CacheSizeCheck(size_t bytes) {
468 if (MakeFreeSpaceOnCache(bytes) < 0) {
Chih-Hung Hsieh54a27472016-04-18 11:30:55 -0700469 printf("unable to make %zu bytes available on /cache\n", bytes);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800470 return 1;
471 } else {
472 return 0;
473 }
474}
475
Doug Zongkerc4351c72010-02-22 14:46:32 -0800476// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800477// (the original file is not touched until we have the desired
478// replacement for it) and idempotent (it's okay to run this program
479// multiple times).
480//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800481// - if the sha1 hash of <target_filename> is <target_sha1_string>,
482// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800483//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800484// - otherwise, if the sha1 hash of <source_filename> is one of the
485// entries in <patch_sha1_str>, the corresponding patch from
486// <patch_data> (which must be a VAL_BLOB) is applied to produce a
487// new file (the type of patch is automatically detected from the
Tao Baoabba55b2015-07-17 18:11:12 -0700488// blob data). If that new file has sha1 hash <target_sha1_str>,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800489// moves it to replace <target_filename>, and exits successfully.
490// Note that if <source_filename> and <target_filename> are not the
491// same, <source_filename> is NOT deleted on success.
492// <target_filename> may be the string "-" to mean "the same as
493// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800494//
495// - otherwise, or if any error is encountered, exits with non-zero
496// status.
497//
Doug Zongkerf291d852010-07-07 13:55:25 -0700498// <source_filename> may refer to a partition to read the source data.
Tao Baoabba55b2015-07-17 18:11:12 -0700499// See the comments for the LoadPartitionContents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800500// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800501
Doug Zongkerc4351c72010-02-22 14:46:32 -0800502int applypatch(const char* source_filename,
503 const char* target_filename,
504 const char* target_sha1_str,
505 size_t target_size,
Tianjie Xuaced5d92016-10-12 10:55:04 -0700506 const std::vector<std::string>& patch_sha1_str,
Tao Baofada91c2016-10-27 18:16:06 -0700507 const std::vector<std::unique_ptr<Value>>& patch_data,
508 const Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700509 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800510
Tao Baoba9a42a2015-06-23 23:23:33 -0700511 if (target_filename[0] == '-' && target_filename[1] == '\0') {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800512 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800513 }
514
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800515 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800516 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
517 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800518 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800519 }
Doug Zongker512536a2010-02-17 16:11:44 -0800520
Doug Zongkerc4351c72010-02-22 14:46:32 -0800521 FileContents source_file;
Tao Baofada91c2016-10-27 18:16:06 -0700522 const Value* source_patch_value = nullptr;
Doug Zongker512536a2010-02-17 16:11:44 -0800523
Doug Zongkerc4351c72010-02-22 14:46:32 -0800524 // We try to load the target file into the source_file object.
Doug Zongkera1bc1482014-02-13 15:18:19 -0800525 if (LoadFileContents(target_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800526 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800527 // The early-exit case: the patch was already applied, this file
528 // has the desired hash, nothing for us to do.
Tao Baoabba55b2015-07-17 18:11:12 -0700529 printf("already %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800530 return 0;
531 }
532 }
Doug Zongker512536a2010-02-17 16:11:44 -0800533
Yabin Cuid6c93af2016-02-10 16:41:10 -0800534 if (source_file.data.empty() ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800535 (target_filename != source_filename &&
536 strcmp(target_filename, source_filename) != 0)) {
537 // Need to load the source file: either we failed to load the
538 // target file, or we did but it's different from the source file.
Yabin Cuid6c93af2016-02-10 16:41:10 -0800539 source_file.data.clear();
Doug Zongkera1bc1482014-02-13 15:18:19 -0800540 LoadFileContents(source_filename, &source_file);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800541 }
542
Yabin Cuid6c93af2016-02-10 16:41:10 -0800543 if (!source_file.data.empty()) {
Tianjie Xuaced5d92016-10-12 10:55:04 -0700544 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1_str);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800545 if (to_use >= 0) {
Tao Baofada91c2016-10-27 18:16:06 -0700546 source_patch_value = patch_data[to_use].get();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800547 }
548 }
549
Tao Bao8fce75a2016-11-10 12:33:41 -0800550 FileContents copy_file;
551 const Value* copy_patch_value = nullptr;
Tao Baofada91c2016-10-27 18:16:06 -0700552 if (source_patch_value == nullptr) {
Yabin Cuid6c93af2016-02-10 16:41:10 -0800553 source_file.data.clear();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800554 printf("source file is bad; trying copy\n");
555
Doug Zongkera1bc1482014-02-13 15:18:19 -0800556 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800557 // fail.
558 printf("failed to read copy file\n");
559 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800560 }
561
Tianjie Xuaced5d92016-10-12 10:55:04 -0700562 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1_str);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700563 if (to_use >= 0) {
Tao Baofada91c2016-10-27 18:16:06 -0700564 copy_patch_value = patch_data[to_use].get();
Doug Zongker512536a2010-02-17 16:11:44 -0800565 }
566
Tao Baofada91c2016-10-27 18:16:06 -0700567 if (copy_patch_value == nullptr) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800568 // fail.
569 printf("copy file doesn't match source SHA-1s either\n");
570 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800571 }
Doug Zongker512536a2010-02-17 16:11:44 -0800572 }
573
Yabin Cuid6c93af2016-02-10 16:41:10 -0800574 return GenerateTarget(&source_file, source_patch_value,
575 &copy_file, copy_patch_value,
576 source_filename, target_filename,
577 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800578}
579
Tao Baoabba55b2015-07-17 18:11:12 -0700580/*
581 * This function flashes a given image to the target partition. It verifies
582 * the target cheksum first, and will return if target has the desired hash.
583 * It checks the checksum of the given source image before flashing, and
584 * verifies the target partition afterwards. The function is idempotent.
585 * Returns zero on success.
586 */
587int applypatch_flash(const char* source_filename, const char* target_filename,
588 const char* target_sha1_str, size_t target_size) {
589 printf("flash %s: ", target_filename);
590
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800591 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Tao Baoabba55b2015-07-17 18:11:12 -0700592 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
593 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
594 return 1;
595 }
596
Tao Baoabba55b2015-07-17 18:11:12 -0700597 std::string target_str(target_filename);
598
599 std::vector<std::string> pieces = android::base::Split(target_str, ":");
Elliott Hughes63a31922016-06-09 17:41:22 -0700600 if (pieces.size() != 2 || pieces[0] != "EMMC") {
Tao Baoabba55b2015-07-17 18:11:12 -0700601 printf("invalid target name \"%s\"", target_filename);
602 return 1;
603 }
604
605 // Load the target into the source_file object to see if already applied.
606 pieces.push_back(std::to_string(target_size));
607 pieces.push_back(target_sha1_str);
608 std::string fullname = android::base::Join(pieces, ':');
Tao Bao8fce75a2016-11-10 12:33:41 -0800609 FileContents source_file;
610 if (LoadPartitionContents(fullname, &source_file) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800611 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800612 // The early-exit case: the image was already applied, this partition
613 // has the desired hash, nothing for us to do.
614 printf("already %s\n", short_sha1(target_sha1).c_str());
615 return 0;
Tao Baoabba55b2015-07-17 18:11:12 -0700616 }
617
618 if (LoadFileContents(source_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800619 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700620 // The source doesn't have desired checksum.
621 printf("source \"%s\" doesn't have expected sha1 sum\n", source_filename);
622 printf("expected: %s, found: %s\n", short_sha1(target_sha1).c_str(),
623 short_sha1(source_file.sha1).c_str());
Tao Baoabba55b2015-07-17 18:11:12 -0700624 return 1;
625 }
626 }
627
Yabin Cuid6c93af2016-02-10 16:41:10 -0800628 if (WriteToPartition(source_file.data.data(), target_size, target_filename) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700629 printf("write of copied data to %s failed\n", target_filename);
Tao Baoabba55b2015-07-17 18:11:12 -0700630 return 1;
631 }
Tao Baoabba55b2015-07-17 18:11:12 -0700632 return 0;
633}
634
Doug Zongker1c43c972012-02-28 11:07:09 -0800635static int GenerateTarget(FileContents* source_file,
636 const Value* source_patch_value,
637 FileContents* copy_file,
638 const Value* copy_patch_value,
639 const char* source_filename,
640 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800641 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700642 size_t target_size,
643 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800644 int retry = 1;
645 SHA_CTX ctx;
Yabin Cuid483c202016-02-03 17:08:52 -0800646 std::string memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800647 FileContents* source_to_use;
Doug Zongker1c43c972012-02-28 11:07:09 -0800648 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800649
Elliott Hughes63a31922016-06-09 17:41:22 -0700650 bool target_is_partition = (strncmp(target_filename, "EMMC:", 5) == 0);
Yabin Cuid483c202016-02-03 17:08:52 -0800651 const std::string tmp_target_filename = std::string(target_filename) + ".patch";
652
Doug Zongkerc4351c72010-02-22 14:46:32 -0800653 // assume that target_filename (eg "/system/app/Foo.apk") is located
654 // on the same filesystem as its top-level directory ("/system").
655 // We need something that exists for calling statfs().
Yabin Cuid483c202016-02-03 17:08:52 -0800656 std::string target_fs = target_filename;
657 auto slash_pos = target_fs.find('/', 1);
658 if (slash_pos != std::string::npos) {
659 target_fs.resize(slash_pos);
660 }
661
662 const Value* patch;
663 if (source_patch_value != NULL) {
664 source_to_use = source_file;
665 patch = source_patch_value;
Doug Zongker512536a2010-02-17 16:11:44 -0800666 } else {
Yabin Cuid483c202016-02-03 17:08:52 -0800667 source_to_use = copy_file;
668 patch = copy_patch_value;
669 }
670 if (patch->type != VAL_BLOB) {
671 printf("patch is not a blob\n");
672 return 1;
673 }
Tianjie Xuaced5d92016-10-12 10:55:04 -0700674 const char* header = &patch->data[0];
675 size_t header_bytes_read = patch->data.size();
Yabin Cuid483c202016-02-03 17:08:52 -0800676 bool use_bsdiff = false;
677 if (header_bytes_read >= 8 && memcmp(header, "BSDIFF40", 8) == 0) {
678 use_bsdiff = true;
679 } else if (header_bytes_read >= 8 && memcmp(header, "IMGDIFF2", 8) == 0) {
680 use_bsdiff = false;
681 } else {
682 printf("Unknown patch file format\n");
683 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800684 }
685
Doug Zongkerc4351c72010-02-22 14:46:32 -0800686 do {
687 // Is there enough room in the target filesystem to hold the patched
688 // file?
689
Yabin Cuid483c202016-02-03 17:08:52 -0800690 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700691 // If the target is a partition, we're actually going to
692 // write the output to /tmp and then copy it to the
693 // partition. statfs() always returns 0 blocks free for
694 // /tmp, so instead we'll just assume that /tmp has enough
695 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800696
Doug Zongkerf291d852010-07-07 13:55:25 -0700697 // We still write the original source to cache, in case
698 // the partition write is interrupted.
Yabin Cuid6c93af2016-02-10 16:41:10 -0800699 if (MakeFreeSpaceOnCache(source_file->data.size()) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800700 printf("not enough free space on /cache\n");
701 return 1;
702 }
703 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
704 printf("failed to back up source file\n");
705 return 1;
706 }
707 made_copy = 1;
708 retry = 0;
709 } else {
710 int enough_space = 0;
711 if (retry > 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800712 size_t free_space = FreeSpaceForFile(target_fs.c_str());
Doug Zongker201cd462010-08-13 09:41:21 -0700713 enough_space =
714 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800715 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700716 if (!enough_space) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700717 printf("target %zu bytes; free space %zu bytes; retry %d; enough %d\n",
718 target_size, free_space, retry, enough_space);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700719 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800720 }
721
722 if (!enough_space) {
723 retry = 0;
724 }
725
726 if (!enough_space && source_patch_value != NULL) {
727 // Using the original source, but not enough free space. First
728 // copy the source file to cache, then delete it from the original
729 // location.
730
Elliott Hughes63a31922016-06-09 17:41:22 -0700731 if (strncmp(source_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800732 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700733 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800734 // we're ever in a state where we need to do this, fail.
Tao Baoba9a42a2015-06-23 23:23:33 -0700735 printf("not enough free space for target but source is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800736 return 1;
737 }
738
Yabin Cuid6c93af2016-02-10 16:41:10 -0800739 if (MakeFreeSpaceOnCache(source_file->data.size()) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800740 printf("not enough free space on /cache\n");
741 return 1;
742 }
743
744 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
745 printf("failed to back up source file\n");
746 return 1;
747 }
748 made_copy = 1;
749 unlink(source_filename);
750
Yabin Cuid483c202016-02-03 17:08:52 -0800751 size_t free_space = FreeSpaceForFile(target_fs.c_str());
Tao Baoba9a42a2015-06-23 23:23:33 -0700752 printf("(now %zu bytes free for target) ", free_space);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800753 }
754 }
755
Doug Zongkerc4351c72010-02-22 14:46:32 -0800756
757 SinkFn sink = NULL;
758 void* token = NULL;
Yabin Cuid483c202016-02-03 17:08:52 -0800759 int output_fd = -1;
760 if (target_is_partition) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800761 // We store the decoded output in memory.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800762 sink = MemorySink;
Yabin Cuid483c202016-02-03 17:08:52 -0800763 token = &memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800764 } else {
765 // We write the decoded output to "<tgt-file>.patch".
Jed Estepa7b9a462015-12-15 16:04:53 -0800766 output_fd = ota_open(tmp_target_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_SYNC,
767 S_IRUSR | S_IWUSR);
Yabin Cuid483c202016-02-03 17:08:52 -0800768 if (output_fd < 0) {
769 printf("failed to open output file %s: %s\n", tmp_target_filename.c_str(),
770 strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800771 return 1;
772 }
773 sink = FileSink;
Yabin Cuid483c202016-02-03 17:08:52 -0800774 token = &output_fd;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800775 }
776
Doug Zongkerc4351c72010-02-22 14:46:32 -0800777
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800778 SHA1_Init(&ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800779
780 int result;
Yabin Cuid483c202016-02-03 17:08:52 -0800781 if (use_bsdiff) {
Yabin Cuid6c93af2016-02-10 16:41:10 -0800782 result = ApplyBSDiffPatch(source_to_use->data.data(), source_to_use->data.size(),
Doug Zongkerc4351c72010-02-22 14:46:32 -0800783 patch, 0, sink, token, &ctx);
Yabin Cuid483c202016-02-03 17:08:52 -0800784 } else {
Yabin Cuid6c93af2016-02-10 16:41:10 -0800785 result = ApplyImagePatch(source_to_use->data.data(), source_to_use->data.size(),
Doug Zongkera3ccba62012-08-20 15:28:02 -0700786 patch, sink, token, &ctx, bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800787 }
788
Yabin Cuid483c202016-02-03 17:08:52 -0800789 if (!target_is_partition) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800790 if (ota_fsync(output_fd) != 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800791 printf("failed to fsync file \"%s\" (%s)\n", tmp_target_filename.c_str(),
792 strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700793 result = 1;
794 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800795 if (ota_close(output_fd) != 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800796 printf("failed to close file \"%s\" (%s)\n", tmp_target_filename.c_str(),
797 strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700798 result = 1;
799 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800800 }
801
802 if (result != 0) {
803 if (retry == 0) {
804 printf("applying patch failed\n");
805 return result != 0;
806 } else {
807 printf("applying patch failed; retrying\n");
808 }
Yabin Cuid483c202016-02-03 17:08:52 -0800809 if (!target_is_partition) {
810 unlink(tmp_target_filename.c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800811 }
812 } else {
813 // succeeded; no need to retry
814 break;
815 }
816 } while (retry-- > 0);
817
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800818 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
819 SHA1_Final(current_target_sha1, &ctx);
820 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800821 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800822 return 1;
Doug Zongkerbf80f492012-10-19 12:24:26 -0700823 } else {
Tao Baoabba55b2015-07-17 18:11:12 -0700824 printf("now %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800825 }
826
Yabin Cuid483c202016-02-03 17:08:52 -0800827 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700828 // Copy the temp file to the partition.
Yabin Cuid483c202016-02-03 17:08:52 -0800829 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
830 memory_sink_str.size(), target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800831 printf("write of patched data to %s failed\n", target_filename);
832 return 1;
833 }
Doug Zongker512536a2010-02-17 16:11:44 -0800834 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800835 // Give the .patch file the same owner, group, and mode of the
836 // original source file.
Yabin Cuid483c202016-02-03 17:08:52 -0800837 if (chmod(tmp_target_filename.c_str(), source_to_use->st.st_mode) != 0) {
838 printf("chmod of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800839 return 1;
840 }
Yabin Cuid483c202016-02-03 17:08:52 -0800841 if (chown(tmp_target_filename.c_str(), source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
842 printf("chown of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800843 return 1;
844 }
Doug Zongker512536a2010-02-17 16:11:44 -0800845
Doug Zongkerc4351c72010-02-22 14:46:32 -0800846 // Finally, rename the .patch file to replace the target file.
Yabin Cuid483c202016-02-03 17:08:52 -0800847 if (rename(tmp_target_filename.c_str(), target_filename) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700848 printf("rename of .patch to \"%s\" failed: %s\n", target_filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800849 return 1;
850 }
Doug Zongker512536a2010-02-17 16:11:44 -0800851 }
852
Doug Zongkerc4351c72010-02-22 14:46:32 -0800853 // If this run of applypatch created the copy, and we're here, we
854 // can delete it.
Tao Baoba9a42a2015-06-23 23:23:33 -0700855 if (made_copy) {
856 unlink(CACHE_TEMP_SOURCE);
857 }
Doug Zongker512536a2010-02-17 16:11:44 -0800858
Doug Zongkerc4351c72010-02-22 14:46:32 -0800859 // Success!
860 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800861}