blob: 6227154e5a9341a8e74cc13c17b409d04dabb437 [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 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 <ctype.h>
18#include <errno.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000019#include <dirent.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070021#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070022#include <pthread.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000027#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070028#include <sys/types.h>
29#include <sys/wait.h>
30#include <sys/ioctl.h>
31#include <time.h>
32#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010033#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070034
Tao Baoec8272f2017-03-15 17:39:01 -070035#include <functional>
Tao Baoe6aa3322015-08-05 15:20:27 -070036#include <memory>
37#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070038#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070039#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070040
Tao Bao039f2da2016-11-22 16:29:50 -080041#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080042#include <android-base/parseint.h>
43#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070044#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080045#include <applypatch/applypatch.h>
46#include <openssl/sha.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070047#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070048
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070049#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070050#include "error_code.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070051#include "updater/install.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080052#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070053#include "print_sha1.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070054#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070055
Sami Tolvanene82fa182015-06-10 15:58:12 +000056// Set this to 0 to interpret 'erase' transfers to mean do a
57// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
58// erase to mean fill the region with zeroes.
59#define DEBUG_ERASE 0
60
Tao Bao51412212016-12-28 14:44:05 -080061static constexpr size_t BLOCKSIZE = 4096;
62static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
63static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
64static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000065
Tao Bao0940fe12015-08-27 16:41:21 -070066struct RangeSet {
Tao Baoc844c062016-12-28 15:15:55 -080067 size_t count; // Limit is INT_MAX.
68 size_t size;
69 std::vector<size_t> pos; // Actual limit is INT_MAX.
Tao Bao0940fe12015-08-27 16:41:21 -070070};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070071
Tianjie Xu16255832016-04-30 11:49:59 -070072static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070073static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070074static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070075
Tao Baoc844c062016-12-28 15:15:55 -080076static RangeSet parse_range(const std::string& range_text) {
77 RangeSet rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010078
Tao Baoc844c062016-12-28 15:15:55 -080079 std::vector<std::string> pieces = android::base::Split(range_text, ",");
80 if (pieces.size() < 3) {
81 goto err;
82 }
83
84 size_t num;
85 if (!android::base::ParseUint(pieces[0], &num, static_cast<size_t>(INT_MAX))) {
86 goto err;
87 }
88
89 if (num == 0 || num % 2) {
90 goto err; // must be even
91 } else if (num != pieces.size() - 1) {
92 goto err;
93 }
94
95 rs.pos.resize(num);
96 rs.count = num / 2;
97 rs.size = 0;
98
99 for (size_t i = 0; i < num; i += 2) {
100 if (!android::base::ParseUint(pieces[i + 1], &rs.pos[i], static_cast<size_t>(INT_MAX))) {
101 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100102 }
103
Tao Baoc844c062016-12-28 15:15:55 -0800104 if (!android::base::ParseUint(pieces[i + 2], &rs.pos[i + 1], static_cast<size_t>(INT_MAX))) {
105 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100106 }
107
Tao Baoc844c062016-12-28 15:15:55 -0800108 if (rs.pos[i] >= rs.pos[i + 1]) {
109 goto err; // empty or negative range
Tao Baob15fd222015-09-24 11:10:51 -0700110 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100111
Tao Baoc844c062016-12-28 15:15:55 -0800112 size_t sz = rs.pos[i + 1] - rs.pos[i];
113 if (rs.size > SIZE_MAX - sz) {
114 goto err; // overflow
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700115 }
116
Tao Baoc844c062016-12-28 15:15:55 -0800117 rs.size += sz;
118 }
119
120 return rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100121
122err:
Tao Baoc844c062016-12-28 15:15:55 -0800123 LOG(ERROR) << "failed to parse range '" << range_text << "'";
Tao Bao3da88012017-02-03 13:09:23 -0800124 exit(EXIT_FAILURE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700125}
126
Tao Baoe6aa3322015-08-05 15:20:27 -0700127static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Tao Baoc844c062016-12-28 15:15:55 -0800128 for (size_t i = 0; i < r1.count; ++i) {
129 size_t r1_0 = r1.pos[i * 2];
130 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000131
Tao Baoc844c062016-12-28 15:15:55 -0800132 for (size_t j = 0; j < r2.count; ++j) {
133 size_t r2_0 = r2.pos[j * 2];
134 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000135
Tao Baoc844c062016-12-28 15:15:55 -0800136 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
137 return true;
138 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000139 }
Tao Baoc844c062016-12-28 15:15:55 -0800140 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000141
Tao Baoc844c062016-12-28 15:15:55 -0800142 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000143}
144
145static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700146 size_t so_far = 0;
147 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800148 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700149 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700150 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800151 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000152 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700153 } else if (r == 0) {
154 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800155 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700156 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700157 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700158 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700159 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000160 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700161}
162
Tao Bao612336d2015-08-27 16:41:21 -0700163static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
164 return read_all(fd, buffer.data(), size);
165}
166
Sami Tolvanen90221202014-12-09 16:39:47 +0000167static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700168 size_t written = 0;
169 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800170 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700171 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700172 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800173 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000174 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700175 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700176 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700177 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000178
Sami Tolvanen90221202014-12-09 16:39:47 +0000179 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700180}
181
Tao Bao612336d2015-08-27 16:41:21 -0700182static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
183 return write_all(fd, buffer.data(), size);
184}
185
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700186static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
187 // Don't discard blocks unless the update is a retry run.
188 if (!is_retry) {
189 return true;
190 }
191
192 uint64_t args[2] = {static_cast<uint64_t>(offset), size};
193 int status = ioctl(fd, BLKDISCARD, &args);
194 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800195 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700196 return false;
197 }
198 return true;
199}
200
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700201static bool check_lseek(int fd, off64_t offset, int whence) {
202 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
203 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700204 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800205 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700206 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700207 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700208 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700209}
210
Tao Bao612336d2015-08-27 16:41:21 -0700211static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700212 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700213 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700214
Tao Bao612336d2015-08-27 16:41:21 -0700215 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700216}
217
Tao Bao0940fe12015-08-27 16:41:21 -0700218struct RangeSinkState {
Chih-Hung Hsieh49c5c792016-04-29 14:16:35 -0700219 explicit RangeSinkState(RangeSet& rs) : tgt(rs) { };
Tao Bao0940fe12015-08-27 16:41:21 -0700220
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700221 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700222 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530223 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700224 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700225};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700226
227static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700228 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700229
Tao Bao0940fe12015-08-27 16:41:21 -0700230 if (rss->p_remain == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800231 LOG(ERROR) << "range sink write overrun";
Sami Tolvanen90221202014-12-09 16:39:47 +0000232 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700233 }
234
235 ssize_t written = 0;
236 while (size > 0) {
237 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000238
239 if (rss->p_remain < write_now) {
240 write_now = rss->p_remain;
241 }
242
243 if (write_all(rss->fd, data, write_now) == -1) {
244 break;
245 }
246
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700247 data += write_now;
248 size -= write_now;
249
250 rss->p_remain -= write_now;
251 written += write_now;
252
253 if (rss->p_remain == 0) {
254 // move to the next block
255 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700256 if (rss->p_block < rss->tgt.count) {
257 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
258 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000259
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700260 off64_t offset = static_cast<off64_t>(rss->tgt.pos[rss->p_block*2]) * BLOCKSIZE;
261 if (!discard_blocks(rss->fd, offset, rss->p_remain)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000262 break;
263 }
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700264
265 if (!check_lseek(rss->fd, offset, SEEK_SET)) {
266 break;
267 }
268
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700269 } else {
270 // we can't write any more; return how many bytes have
271 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000272 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700273 }
274 }
275 }
276
277 return written;
278}
279
280// All of the data for all the 'new' transfers is contained in one
281// file in the update package, concatenated together in the order in
282// which transfers.list will need it. We want to stream it out of the
283// archive (it's compressed) without writing it to a temp file, but we
284// can't write each section until it's that transfer's turn to go.
285//
286// To achieve this, we expand the new data from the archive in a
287// background thread, and block that threads 'receive uncompressed
288// data' function until the main thread has reached a point where we
289// want some new data to be written. We signal the background thread
290// with the destination for the data and block the main thread,
291// waiting for the background thread to complete writing that section.
292// Then it signals the main thread to wake up and goes back to
293// blocking waiting for a transfer.
294//
295// NewThreadInfo is the struct used to pass information back and forth
296// between the two threads. When the main thread wants some data
297// written, it sets rss to the destination location and signals the
298// condition. When the background thread is done writing, it clears
299// rss and signals the condition again.
300
Tao Bao0940fe12015-08-27 16:41:21 -0700301struct NewThreadInfo {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700302 ZipArchiveHandle za;
303 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700304
305 RangeSinkState* rss;
306
307 pthread_mutex_t mu;
308 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700309};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700310
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700311static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700312 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700313
314 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700315 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700316 // data is wanted.
317 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700318 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700319 pthread_cond_wait(&nti->cv, &nti->mu);
320 }
321 pthread_mutex_unlock(&nti->mu);
322
323 // At this point nti->rss is set, and we own it. The main
324 // thread is waiting for it to disappear from nti.
325 ssize_t written = RangeSinkWrite(data, size, nti->rss);
326 data += written;
327 size -= written;
328
Tao Bao0940fe12015-08-27 16:41:21 -0700329 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700330 // we have written all the bytes desired by this rss.
331
332 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700333 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700334 pthread_cond_broadcast(&nti->cv);
335 pthread_mutex_unlock(&nti->mu);
336 }
337 }
338
339 return true;
340}
341
342static void* unzip_new_data(void* cookie) {
343 NewThreadInfo* nti = (NewThreadInfo*) cookie;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700344 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700345 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700346}
347
Tao Bao612336d2015-08-27 16:41:21 -0700348static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000349 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700350 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000351
Tao Bao0940fe12015-08-27 16:41:21 -0700352 for (size_t i = 0; i < src.count; ++i) {
353 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000354 return -1;
355 }
356
Tao Bao0940fe12015-08-27 16:41:21 -0700357 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000358
Tao Bao612336d2015-08-27 16:41:21 -0700359 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000360 return -1;
361 }
362
363 p += size;
364 }
365
366 return 0;
367}
368
Tao Bao612336d2015-08-27 16:41:21 -0700369static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
370 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000371
Tao Bao0940fe12015-08-27 16:41:21 -0700372 size_t p = 0;
373 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700374 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
375 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
376 if (!discard_blocks(fd, offset, size)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000377 return -1;
378 }
379
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700380 if (!check_lseek(fd, offset, SEEK_SET)) {
381 return -1;
382 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000383
Tao Bao612336d2015-08-27 16:41:21 -0700384 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000385 return -1;
386 }
387
388 p += size;
389 }
390
391 return 0;
392}
393
Tao Baobaad2d42015-12-06 16:56:27 -0800394// Parameters for transfer list command functions
395struct CommandParameters {
396 std::vector<std::string> tokens;
397 size_t cpos;
398 const char* cmdname;
399 const char* cmdline;
400 std::string freestash;
401 std::string stashbase;
402 bool canwrite;
403 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700404 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800405 bool foundwrites;
406 bool isunresumable;
407 int version;
408 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700409 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800410 NewThreadInfo nti;
411 pthread_t thread;
412 std::vector<uint8_t> buffer;
413 uint8_t* patch_start;
414};
415
Doug Zongker52ae67d2014-09-08 12:22:09 -0700416// Do a source/target load for move/bsdiff/imgdiff in version 1.
Tao Baobaad2d42015-12-06 16:56:27 -0800417// We expect to parse the remainder of the parameter tokens as:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700418//
419// <src_range> <tgt_range>
420//
421// The source range is loaded into the provided buffer, reallocating
Tao Bao34847b22015-09-08 11:05:49 -0700422// it to make it larger if necessary.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700423
Tao Baobaad2d42015-12-06 16:56:27 -0800424static int LoadSrcTgtVersion1(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700425 std::vector<uint8_t>& buffer, int fd) {
Tao Baobaad2d42015-12-06 16:56:27 -0800426
427 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800428 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -0800429 return -1;
430 }
431
Tao Bao612336d2015-08-27 16:41:21 -0700432 // <src_range>
Tao Baoc844c062016-12-28 15:15:55 -0800433 RangeSet src = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700434
Tao Bao612336d2015-08-27 16:41:21 -0700435 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -0800436 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700437
Tao Bao612336d2015-08-27 16:41:21 -0700438 allocate(src.size * BLOCKSIZE, buffer);
439 int rc = ReadBlocks(src, buffer, fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700440 src_blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000441
Sami Tolvanen90221202014-12-09 16:39:47 +0000442 return rc;
443}
444
Tao Bao612336d2015-08-27 16:41:21 -0700445static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700446 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800447 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700448 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000449
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800450 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000451
Tao Baoe6aa3322015-08-05 15:20:27 -0700452 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000453
Tao Bao0940fe12015-08-27 16:41:21 -0700454 if (hexdigest != expected) {
455 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800456 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
457 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700458 }
459 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000460 }
461
Tao Bao0940fe12015-08-27 16:41:21 -0700462 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000463}
464
Tao Bao0940fe12015-08-27 16:41:21 -0700465static std::string GetStashFileName(const std::string& base, const std::string& id,
466 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700467 if (base.empty()) {
468 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000469 }
470
Tao Baoe6aa3322015-08-05 15:20:27 -0700471 std::string fn(STASH_DIRECTORY_BASE);
472 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000473
474 return fn;
475}
476
Tao Baoec8272f2017-03-15 17:39:01 -0700477// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
478// directory and continues despite of errors. Calls the 'callback' function for each file.
479static void EnumerateStash(const std::string& dirname,
480 const std::function<void(const std::string&)>& callback) {
481 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000482
Tao Baoec8272f2017-03-15 17:39:01 -0700483 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000484
Tao Baoec8272f2017-03-15 17:39:01 -0700485 if (directory == nullptr) {
486 if (errno != ENOENT) {
487 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000488 }
Tao Bao51412212016-12-28 14:44:05 -0800489 return;
490 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700491
Tao Baoec8272f2017-03-15 17:39:01 -0700492 dirent* item;
493 while ((item = readdir(directory.get())) != nullptr) {
494 if (item->d_type != DT_REG) continue;
495 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800496 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000497}
498
499// Deletes the stash directory and all files in it. Assumes that it only
500// contains files. There is nothing we can do about unlikely, but possible
501// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700502static void DeleteFile(const std::string& fn) {
503 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000504
Tao Baoec8272f2017-03-15 17:39:01 -0700505 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000506
Tao Baoec8272f2017-03-15 17:39:01 -0700507 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
508 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
509 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000510}
511
Tao Baoe6aa3322015-08-05 15:20:27 -0700512static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700513 if (base.empty()) return;
514
515 LOG(INFO) << "deleting stash " << base;
516
517 std::string dirname = GetStashFileName(base, "", "");
518 EnumerateStash(dirname, DeleteFile);
519
520 if (rmdir(dirname.c_str()) == -1) {
521 if (errno != ENOENT && errno != ENOTDIR) {
522 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000523 }
Tao Baoec8272f2017-03-15 17:39:01 -0700524 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000525}
526
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700527static int LoadStash(CommandParameters& params, const std::string& base, const std::string& id,
528 bool verify, size_t* blocks, std::vector<uint8_t>& buffer, bool printnoent) {
529 // In verify mode, if source range_set was saved for the given hash,
530 // check contents in the source blocks first. If the check fails,
531 // search for the stashed files on /cache as usual.
532 if (!params.canwrite) {
533 if (stash_map.find(id) != stash_map.end()) {
534 const RangeSet& src = stash_map[id];
535 allocate(src.size * BLOCKSIZE, buffer);
536
537 if (ReadBlocks(src, buffer, params.fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800538 LOG(ERROR) << "failed to read source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700539 return -1;
540 }
541 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800542 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700543 return -1;
544 }
545 return 0;
546 }
547 }
548
Tao Bao612336d2015-08-27 16:41:21 -0700549 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700550 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000551 }
552
Tao Bao0940fe12015-08-27 16:41:21 -0700553 size_t blockcount = 0;
554
Sami Tolvanen90221202014-12-09 16:39:47 +0000555 if (!blocks) {
556 blocks = &blockcount;
557 }
558
Tao Bao0940fe12015-08-27 16:41:21 -0700559 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000560
Tao Bao0940fe12015-08-27 16:41:21 -0700561 struct stat sb;
562 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000563
564 if (res == -1) {
565 if (errno != ENOENT || printnoent) {
Tao Bao039f2da2016-11-22 16:29:50 -0800566 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000567 }
Tao Bao0940fe12015-08-27 16:41:21 -0700568 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000569 }
570
Tao Bao039f2da2016-11-22 16:29:50 -0800571 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000572
Tao Bao0940fe12015-08-27 16:41:21 -0700573 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800574 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
Tao Bao0940fe12015-08-27 16:41:21 -0700575 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000576 }
577
Elliott Hughesbcabd092016-03-22 20:19:22 -0700578 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000579 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800580 PLOG(ERROR) << "open \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700581 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000582 }
583
Tao Bao612336d2015-08-27 16:41:21 -0700584 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000585
Tao Bao612336d2015-08-27 16:41:21 -0700586 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700587 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000588 }
589
Tao Bao0940fe12015-08-27 16:41:21 -0700590 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000591
Tao Bao612336d2015-08-27 16:41:21 -0700592 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800593 LOG(ERROR) << "unexpected contents in " << fn;
Tao Baoec8272f2017-03-15 17:39:01 -0700594 DeleteFile(fn);
Tao Bao0940fe12015-08-27 16:41:21 -0700595 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000596 }
597
Tao Bao0940fe12015-08-27 16:41:21 -0700598 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000599}
600
Tao Bao612336d2015-08-27 16:41:21 -0700601static int WriteStash(const std::string& base, const std::string& id, int blocks,
602 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
603 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700604 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000605 }
606
607 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800608 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700609 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000610 }
611
Tao Bao0940fe12015-08-27 16:41:21 -0700612 std::string fn = GetStashFileName(base, id, ".partial");
613 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000614
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100615 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700616 struct stat sb;
617 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100618
619 if (res == 0) {
620 // The file already exists and since the name is the hash of the contents,
621 // it's safe to assume the contents are identical (accidental hash collisions
622 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800623 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700624 *exists = true;
625 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100626 }
627
Tao Bao0940fe12015-08-27 16:41:21 -0700628 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100629 }
630
Tao Bao039f2da2016-11-22 16:29:50 -0800631 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000632
Tao Bao039f2da2016-11-22 16:29:50 -0800633 android::base::unique_fd fd(
634 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000635 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800636 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700637 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000638 }
639
640 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700641 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000642 }
643
Jed Estepa7b9a462015-12-15 16:04:53 -0800644 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700645 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800646 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700647 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000648 }
649
Tao Baoe6aa3322015-08-05 15:20:27 -0700650 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800651 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700652 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000653 }
654
Tao Bao0940fe12015-08-27 16:41:21 -0700655 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700656 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
657 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700658 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700659 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800660 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700661 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700662 }
663
Jed Estepa7b9a462015-12-15 16:04:53 -0800664 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700665 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800666 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700667 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700668 }
669
Tao Bao0940fe12015-08-27 16:41:21 -0700670 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000671}
672
673// Creates a directory for storing stash files and checks if the /cache partition
674// hash enough space for the expected amount of blocks we need to store. Returns
675// >0 if we created the directory, zero if it existed already, and <0 of failure.
676
Tao Bao51412212016-12-28 14:44:05 -0800677static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
678 std::string& base) {
679 if (blockdev.empty()) {
680 return -1;
681 }
682
683 // Stash directory should be different for each partition to avoid conflicts
684 // when updating multiple partitions at the same time, so we use the hash of
685 // the block device name as the base directory
686 uint8_t digest[SHA_DIGEST_LENGTH];
687 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
688 base = print_sha1(digest);
689
690 std::string dirname = GetStashFileName(base, "", "");
691 struct stat sb;
692 int res = stat(dirname.c_str(), &sb);
693 size_t max_stash_size = maxblocks * BLOCKSIZE;
694
695 if (res == -1 && errno != ENOENT) {
696 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
697 strerror(errno));
698 return -1;
699 } else if (res != 0) {
700 LOG(INFO) << "creating stash " << dirname;
701 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
702
703 if (res != 0) {
704 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
705 strerror(errno));
706 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000707 }
708
Tao Bao51412212016-12-28 14:44:05 -0800709 if (CacheSizeCheck(max_stash_size) != 0) {
710 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
711 max_stash_size);
712 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000713 }
714
Tao Bao51412212016-12-28 14:44:05 -0800715 return 1; // Created directory
716 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000717
Tao Bao51412212016-12-28 14:44:05 -0800718 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000719
Tao Baoec8272f2017-03-15 17:39:01 -0700720 // If the directory already exists, calculate the space already allocated to stash files and check
721 // if there's enough for all required blocks. Delete any partially completed stash files first.
722 EnumerateStash(dirname, [](const std::string& fn) {
723 if (android::base::EndsWith(fn, ".partial")) {
724 DeleteFile(fn);
725 }
726 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000727
Tao Bao51412212016-12-28 14:44:05 -0800728 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700729 EnumerateStash(dirname, [&existing](const std::string& fn) {
730 if (fn.empty()) return;
731 struct stat sb;
732 if (stat(fn.c_str(), &sb) == -1) {
733 PLOG(ERROR) << "stat \"" << fn << "\" failed";
734 return;
735 }
736 existing += static_cast<size_t>(sb.st_size);
737 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000738
Tao Bao51412212016-12-28 14:44:05 -0800739 if (max_stash_size > existing) {
740 size_t needed = max_stash_size - existing;
741 if (CacheSizeCheck(needed) != 0) {
742 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
743 needed);
744 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000745 }
Tao Bao51412212016-12-28 14:44:05 -0800746 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000747
Tao Bao51412212016-12-28 14:44:05 -0800748 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000749}
750
Tao Baobaad2d42015-12-06 16:56:27 -0800751static int SaveStash(CommandParameters& params, const std::string& base,
752 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000753
Tao Baobaad2d42015-12-06 16:56:27 -0800754 // <stash_id> <src_range>
755 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800756 LOG(ERROR) << "missing id and/or src range fields in stash command";
Sami Tolvanen90221202014-12-09 16:39:47 +0000757 return -1;
758 }
Tao Baobaad2d42015-12-06 16:56:27 -0800759 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000760
Tao Bao0940fe12015-08-27 16:41:21 -0700761 size_t blocks = 0;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700762 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000763 // Stash file already exists and has expected contents. Do not
764 // read from source again, as the source may have been already
765 // overwritten during a previous attempt.
766 return 0;
767 }
768
Tao Baoc844c062016-12-28 15:15:55 -0800769 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao34847b22015-09-08 11:05:49 -0700770
Tao Bao612336d2015-08-27 16:41:21 -0700771 allocate(src.size * BLOCKSIZE, buffer);
772 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000773 return -1;
774 }
Tao Bao34847b22015-09-08 11:05:49 -0700775 blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000776
Tao Bao612336d2015-08-27 16:41:21 -0700777 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000778 // Source blocks have unexpected contents. If we actually need this
779 // data later, this is an unrecoverable error. However, the command
780 // that uses the data may have already completed previously, so the
781 // possible failure will occur during source block verification.
Tao Bao039f2da2016-11-22 16:29:50 -0800782 LOG(ERROR) << "failed to load source blocks for stash " << id;
Sami Tolvanen90221202014-12-09 16:39:47 +0000783 return 0;
784 }
785
Tao Bao90eff6a2017-03-15 09:56:03 -0700786 // In verify mode, save source range_set instead of stashing blocks.
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700787 if (!params.canwrite && usehash) {
Tao Bao90eff6a2017-03-15 09:56:03 -0700788 stash_map[id] = src;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700789 return 0;
790 }
791
Tao Bao039f2da2016-11-22 16:29:50 -0800792 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xudd874b12016-05-13 12:13:15 -0700793 params.stashed += blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700794 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000795}
796
Tao Baobaad2d42015-12-06 16:56:27 -0800797static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700798 if (base.empty() || id.empty()) {
799 return -1;
800 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000801
Tao Baoec8272f2017-03-15 17:39:01 -0700802 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000803
Tao Baoec8272f2017-03-15 17:39:01 -0700804 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700805}
806
Tao Bao612336d2015-08-27 16:41:21 -0700807static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
808 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700809 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700810 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700811 // may be the same buffer.
812
Tao Bao612336d2015-08-27 16:41:21 -0700813 const uint8_t* from = source.data();
814 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700815 size_t start = locs.size;
816 for (int i = locs.count-1; i >= 0; --i) {
817 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700818 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700819 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700820 blocks * BLOCKSIZE);
821 }
822}
823
824// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800825// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700826//
827// <tgt_range> <src_block_count> <src_range>
828// (loads data from source image only)
829//
830// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
831// (loads data from stashes only)
832//
833// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
834// (loads data from both source image and stashes)
835//
836// On return, buffer is filled with the loaded source data (rearranged
837// and combined with stashed data as necessary). buffer may be
838// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000839// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700840
Tao Baobaad2d42015-12-06 16:56:27 -0800841static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700842 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800843
844 // At least it needs to provide three parameters: <tgt_range>,
845 // <src_block_count> and "-"/<src_range>.
846 if (params.cpos + 2 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800847 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -0800848 return -1;
849 }
850
Tao Bao612336d2015-08-27 16:41:21 -0700851 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -0800852 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700853
Tao Bao612336d2015-08-27 16:41:21 -0700854 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800855 const std::string& token = params.tokens[params.cpos++];
856 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
Tao Bao039f2da2016-11-22 16:29:50 -0800857 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
Tao Baobaad2d42015-12-06 16:56:27 -0800858 return -1;
859 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700860
Tao Bao612336d2015-08-27 16:41:21 -0700861 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700862
Tao Bao612336d2015-08-27 16:41:21 -0700863 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800864 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700865 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800866 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700867 } else {
Tao Baoc844c062016-12-28 15:15:55 -0800868 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -0700869 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700870
Tao Bao34847b22015-09-08 11:05:49 -0700871 if (overlap) {
872 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700873 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000874
Sami Tolvanen90221202014-12-09 16:39:47 +0000875 if (res == -1) {
876 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700877 }
878
Tao Baobaad2d42015-12-06 16:56:27 -0800879 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000880 // no stashes, only source range
881 return 0;
882 }
883
Tao Baoc844c062016-12-28 15:15:55 -0800884 RangeSet locs = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -0700885 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700886 }
887
Tao Baobaad2d42015-12-06 16:56:27 -0800888 // <[stash_id:stash_range]>
889 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700890 // Each word is a an index into the stash table, a colon, and
891 // then a rangeset describing where in the source block that
892 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800893 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
894 if (tokens.size() != 2) {
Tao Bao039f2da2016-11-22 16:29:50 -0800895 LOG(ERROR) << "invalid parameter";
Tao Baobaad2d42015-12-06 16:56:27 -0800896 return -1;
897 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000898
Tao Bao612336d2015-08-27 16:41:21 -0700899 std::vector<uint8_t> stash;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700900 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000901
902 if (res == -1) {
903 // These source blocks will fail verification if used later, but we
904 // will let the caller decide if this is a fatal failure
Tao Bao039f2da2016-11-22 16:29:50 -0800905 LOG(ERROR) << "failed to load stash " << tokens[0];
Sami Tolvanen90221202014-12-09 16:39:47 +0000906 continue;
907 }
908
Tao Baoc844c062016-12-28 15:15:55 -0800909 RangeSet locs = parse_range(tokens[1]);
Sami Tolvanen90221202014-12-09 16:39:47 +0000910
Tao Bao612336d2015-08-27 16:41:21 -0700911 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000912 }
913
914 return 0;
915}
916
Sami Tolvanen90221202014-12-09 16:39:47 +0000917// Do a source/target load for move/bsdiff/imgdiff in version 3.
918//
919// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
920// tells the function whether to expect separate source and targe block hashes, or
921// if they are both the same and only one hash should be expected, and
922// 'isunresumable', which receives a non-zero value if block verification fails in
923// a way that the update cannot be resumed anymore.
924//
925// If the function is unable to load the necessary blocks or their contents don't
926// match the hashes, the return value is -1 and the command should be aborted.
927//
928// If the return value is 1, the command has already been completed according to
929// the contents of the target blocks, and should not be performed again.
930//
931// If the return value is 0, source blocks have expected content and the command
932// can be performed.
933
Tao Bao34847b22015-09-08 11:05:49 -0700934static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -0700935 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000936
Tao Baobaad2d42015-12-06 16:56:27 -0800937 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800938 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -0700939 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000940 }
941
Tao Baobaad2d42015-12-06 16:56:27 -0800942 std::string srchash = params.tokens[params.cpos++];
943 std::string tgthash;
944
Sami Tolvanen90221202014-12-09 16:39:47 +0000945 if (onehash) {
946 tgthash = srchash;
947 } else {
Tao Baobaad2d42015-12-06 16:56:27 -0800948 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800949 LOG(ERROR) << "missing target hash";
Tao Bao0940fe12015-08-27 16:41:21 -0700950 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000951 }
Tao Baobaad2d42015-12-06 16:56:27 -0800952 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000953 }
954
Elliott Hughesbcabd092016-03-22 20:19:22 -0700955 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd,
956 params.stashbase, &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700957 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000958 }
959
Tao Bao34847b22015-09-08 11:05:49 -0700960 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000961
Tao Bao612336d2015-08-27 16:41:21 -0700962 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700963 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000964 }
965
Tao Bao612336d2015-08-27 16:41:21 -0700966 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000967 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -0700968 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000969 }
970
Tao Bao0940fe12015-08-27 16:41:21 -0700971 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000972 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700973 // resume from possible write errors. In verify mode, we can skip stashing
974 // because the source blocks won't be overwritten.
975 if (overlap && params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -0800976 LOG(INFO) << "stashing " << src_blocks << " overlapping blocks to " << srchash;
Sami Tolvanen90221202014-12-09 16:39:47 +0000977
Tao Bao0940fe12015-08-27 16:41:21 -0700978 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -0700979 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -0700980 &stash_exists) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800981 LOG(ERROR) << "failed to stash overlapping source blocks";
Tao Bao0940fe12015-08-27 16:41:21 -0700982 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000983 }
984
Tianjie Xudd874b12016-05-13 12:13:15 -0700985 params.stashed += src_blocks;
Sami Tolvanen90221202014-12-09 16:39:47 +0000986 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100987 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700988 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100989 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000990 }
991
992 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -0700993 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000994 }
995
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700996 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
997 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100998 // Overlapping source blocks were previously stashed, command can proceed.
999 // We are recovering from an interrupted command, so we don't know if the
1000 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -07001001 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001002 }
1003
1004 // Valid source data not available, update cannot be resumed
Tao Bao039f2da2016-11-22 16:29:50 -08001005 LOG(ERROR) << "partition has unexpected contents";
Tao Bao0940fe12015-08-27 16:41:21 -07001006 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +00001007
Tao Bao0940fe12015-08-27 16:41:21 -07001008 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001009}
1010
Tao Bao0940fe12015-08-27 16:41:21 -07001011static int PerformCommandMove(CommandParameters& params) {
1012 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001013 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001014 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001015 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001016
Tao Bao0940fe12015-08-27 16:41:21 -07001017 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001018 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001019 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001020 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001021 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001022 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001023 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001024 }
1025
1026 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001027 LOG(ERROR) << "failed to read blocks for move";
Tao Bao0940fe12015-08-27 16:41:21 -07001028 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001029 }
1030
1031 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001032 params.foundwrites = true;
1033 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001034 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001035 }
1036
Tao Bao0940fe12015-08-27 16:41:21 -07001037 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001038 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001039 LOG(INFO) << " moving " << blocks << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001040
Tao Bao0940fe12015-08-27 16:41:21 -07001041 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1042 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001043 }
1044 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001045 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001046 }
1047
1048 }
1049
Tao Baobaad2d42015-12-06 16:56:27 -08001050 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001051 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001052 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001053 }
1054
Tao Bao0940fe12015-08-27 16:41:21 -07001055 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001056
Tao Bao0940fe12015-08-27 16:41:21 -07001057 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001058}
1059
Tao Bao0940fe12015-08-27 16:41:21 -07001060static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001061 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001062 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001063}
1064
Tao Bao0940fe12015-08-27 16:41:21 -07001065static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001066 // <stash_id>
1067 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001068 LOG(ERROR) << "missing stash id in free command";
Tao Baobaad2d42015-12-06 16:56:27 -08001069 return -1;
1070 }
1071
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001072 const std::string& id = params.tokens[params.cpos++];
1073
Tao Bao90eff6a2017-03-15 09:56:03 -07001074 if (!params.canwrite && stash_map.find(id) != stash_map.end()) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001075 stash_map.erase(id);
1076 return 0;
1077 }
1078
Tao Bao0940fe12015-08-27 16:41:21 -07001079 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001080 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001081 }
1082
1083 return 0;
1084}
1085
Tao Bao0940fe12015-08-27 16:41:21 -07001086static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001087
Tao Baobaad2d42015-12-06 16:56:27 -08001088 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001089 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001090 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001091 }
1092
Tao Baoc844c062016-12-28 15:15:55 -08001093 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001094
Tao Bao039f2da2016-11-22 16:29:50 -08001095 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001096
Tao Bao612336d2015-08-27 16:41:21 -07001097 allocate(BLOCKSIZE, params.buffer);
1098 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001099
Tao Bao0940fe12015-08-27 16:41:21 -07001100 if (params.canwrite) {
1101 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001102 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1103 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1104 if (!discard_blocks(params.fd, offset, size)) {
1105 return -1;
1106 }
1107
1108 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001109 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001110 }
1111
Tao Bao0940fe12015-08-27 16:41:21 -07001112 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1113 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1114 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001115 }
1116 }
1117 }
1118 }
1119
Tao Bao0940fe12015-08-27 16:41:21 -07001120 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001121 // Update only for the zero command, as the erase command will call
1122 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001123 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001124 }
1125
Tao Bao0940fe12015-08-27 16:41:21 -07001126 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001127}
1128
Tao Bao0940fe12015-08-27 16:41:21 -07001129static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001130
Tao Baobaad2d42015-12-06 16:56:27 -08001131 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001132 LOG(ERROR) << "missing target blocks for new";
Tao Bao0940fe12015-08-27 16:41:21 -07001133 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001134 }
1135
Tao Baoc844c062016-12-28 15:15:55 -08001136 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001137
Tao Bao0940fe12015-08-27 16:41:21 -07001138 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001139 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
Sami Tolvanen90221202014-12-09 16:39:47 +00001140
Tao Bao0940fe12015-08-27 16:41:21 -07001141 RangeSinkState rss(tgt);
1142 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001143 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001144 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001145
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001146 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1147 if (!discard_blocks(params.fd, offset, tgt.size * BLOCKSIZE)) {
1148 return -1;
1149 }
1150
1151 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001152 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001153 }
1154
Tao Bao0940fe12015-08-27 16:41:21 -07001155 pthread_mutex_lock(&params.nti.mu);
1156 params.nti.rss = &rss;
1157 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001158
Tao Bao0940fe12015-08-27 16:41:21 -07001159 while (params.nti.rss) {
1160 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001161 }
1162
Tao Bao0940fe12015-08-27 16:41:21 -07001163 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001164 }
1165
Tao Bao0940fe12015-08-27 16:41:21 -07001166 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001167
Tao Bao0940fe12015-08-27 16:41:21 -07001168 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001169}
1170
Tao Bao0940fe12015-08-27 16:41:21 -07001171static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001172
Tao Baobaad2d42015-12-06 16:56:27 -08001173 // <offset> <length>
1174 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001175 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
Tao Bao0940fe12015-08-27 16:41:21 -07001176 return -1;
1177 }
1178
Tao Baobaad2d42015-12-06 16:56:27 -08001179 size_t offset;
1180 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001181 LOG(ERROR) << "invalid patch offset";
Tao Bao0940fe12015-08-27 16:41:21 -07001182 return -1;
1183 }
1184
Tao Baobaad2d42015-12-06 16:56:27 -08001185 size_t len;
1186 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001187 LOG(ERROR) << "invalid patch len";
Tao Baobaad2d42015-12-06 16:56:27 -08001188 return -1;
1189 }
Tao Bao0940fe12015-08-27 16:41:21 -07001190
Tao Bao612336d2015-08-27 16:41:21 -07001191 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001192 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001193 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001194 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001195 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001196 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001197 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001198 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001199 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001200 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001201 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001202 }
1203
1204 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001205 LOG(ERROR) << "failed to read blocks for diff";
Tao Bao0940fe12015-08-27 16:41:21 -07001206 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001207 }
1208
1209 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001210 params.foundwrites = true;
1211 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001212 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001213 }
1214
Tao Bao0940fe12015-08-27 16:41:21 -07001215 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001216 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001217 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001218
Tianjie Xuaced5d92016-10-12 10:55:04 -07001219 Value patch_value(VAL_BLOB,
1220 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001221
Tao Bao0940fe12015-08-27 16:41:21 -07001222 RangeSinkState rss(tgt);
1223 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001224 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001225 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001226
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001227 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1228 if (!discard_blocks(params.fd, offset, rss.p_remain)) {
1229 return -1;
1230 }
1231
1232 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001233 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001234 }
1235
Tao Bao0940fe12015-08-27 16:41:21 -07001236 if (params.cmdname[0] == 'i') { // imgdiff
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001237 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1238 &RangeSinkWrite, &rss, nullptr, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001239 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001240 return -1;
1241 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001242 } else {
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001243 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1244 0, &RangeSinkWrite, &rss, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001245 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001246 return -1;
1247 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001248 }
1249
1250 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001251 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001252 LOG(ERROR) << "range sink underrun?";
Sami Tolvanen90221202014-12-09 16:39:47 +00001253 }
1254 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001255 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size
1256 << " [" << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001257 }
1258 }
1259
Tao Baobaad2d42015-12-06 16:56:27 -08001260 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001261 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001262 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001263 }
1264
Tao Bao0940fe12015-08-27 16:41:21 -07001265 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001266
Tao Bao0940fe12015-08-27 16:41:21 -07001267 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001268}
1269
Tao Bao0940fe12015-08-27 16:41:21 -07001270static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001271 if (DEBUG_ERASE) {
1272 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001273 }
1274
Tao Bao0940fe12015-08-27 16:41:21 -07001275 struct stat sb;
1276 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001277 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001278 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001279 }
1280
Tao Bao0940fe12015-08-27 16:41:21 -07001281 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001282 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001283 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001284 }
1285
Tao Baobaad2d42015-12-06 16:56:27 -08001286 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001287 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001288 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001289 }
1290
Tao Baoc844c062016-12-28 15:15:55 -08001291 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001292
Tao Bao0940fe12015-08-27 16:41:21 -07001293 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001294 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001295
Tao Bao0940fe12015-08-27 16:41:21 -07001296 for (size_t i = 0; i < tgt.count; ++i) {
1297 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001298 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001299 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001300 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001301 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001302
Tao Bao0940fe12015-08-27 16:41:21 -07001303 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001304 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001305 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001306 }
1307 }
1308 }
1309
Tao Bao0940fe12015-08-27 16:41:21 -07001310 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001311}
1312
1313// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001314typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001315
Tao Bao612336d2015-08-27 16:41:21 -07001316struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001317 const char* name;
1318 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001319};
Sami Tolvanen90221202014-12-09 16:39:47 +00001320
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001321// args:
1322// - block device (or file) to modify in-place
1323// - transfer list (blob)
1324// - new data stream (filename within package.zip)
1325// - patch stream (filename within package.zip, must be uncompressed)
1326
Tao Bao0940fe12015-08-27 16:41:21 -07001327static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1328 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao73064612016-04-26 17:14:32 -07001329 CommandParameters params = {};
Sami Tolvanen90221202014-12-09 16:39:47 +00001330 params.canwrite = !dryrun;
1331
Tao Bao5354f602016-12-14 11:31:18 -08001332 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001333 if (state->is_retry) {
1334 is_retry = true;
Tao Bao039f2da2016-11-22 16:29:50 -08001335 LOG(INFO) << "This update is a retry.";
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001336 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001337
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001338 std::vector<std::unique_ptr<Value>> args;
1339 if (!ReadValueArgs(state, 4, argv, &args)) {
1340 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001341 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001342
1343 const Value* blockdev_filename = args[0].get();
1344 const Value* transfer_list_value = args[1].get();
1345 const Value* new_data_fn = args[2].get();
1346 const Value* patch_data_fn = args[3].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001347
1348 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001349 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1350 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001351 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001352 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001353 if (transfer_list_value->type != VAL_BLOB) {
Tianjie Xu16255832016-04-30 11:49:59 -07001354 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001355 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001356 }
1357 if (new_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001358 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001359 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001360 }
1361 if (patch_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001362 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string",
1363 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001364 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001365 }
1366
Tao Bao51412212016-12-28 14:44:05 -08001367 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
Tao Bao0940fe12015-08-27 16:41:21 -07001368 if (ui == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001369 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001370 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001371
Tao Bao612336d2015-08-27 16:41:21 -07001372 FILE* cmd_pipe = ui->cmd_pipe;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001373 ZipArchiveHandle za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001374
Tao Bao0940fe12015-08-27 16:41:21 -07001375 if (cmd_pipe == nullptr || za == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001376 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001377 }
1378
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001379 ZipString path_data(patch_data_fn->data.c_str());
1380 ZipEntry patch_entry;
1381 if (FindEntry(za, path_data, &patch_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001382 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001383 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001384 }
1385
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001386 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1387 ZipString new_data(new_data_fn->data.c_str());
1388 ZipEntry new_entry;
1389 if (FindEntry(za, new_data, &new_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001390 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001391 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001392 }
1393
Tianjie Xuaced5d92016-10-12 10:55:04 -07001394 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001395 if (params.fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001396 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001397 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001398 }
1399
Sami Tolvanen90221202014-12-09 16:39:47 +00001400 if (params.canwrite) {
1401 params.nti.za = za;
1402 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001403
Tao Bao0940fe12015-08-27 16:41:21 -07001404 pthread_mutex_init(&params.nti.mu, nullptr);
1405 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001406 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001407 pthread_attr_init(&attr);
1408 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1409
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001410 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1411 if (error != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001412 PLOG(ERROR) << "pthread_create failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001413 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001414 }
1415 }
1416
Tianjie Xuaced5d92016-10-12 10:55:04 -07001417 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001418 if (lines.size() < 2) {
Tianjie Xu16255832016-04-30 11:49:59 -07001419 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1420 lines.size());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001421 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001422 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001423
Sami Tolvanen90221202014-12-09 16:39:47 +00001424 // First line in transfer list is the version number
Tao Bao51412212016-12-28 14:44:05 -08001425 if (!android::base::ParseInt(lines[0], &params.version, 1, 4)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001426 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001427 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001428 }
1429
Tao Bao039f2da2016-11-22 16:29:50 -08001430 LOG(INFO) << "blockimg version is " << params.version;
Sami Tolvanen90221202014-12-09 16:39:47 +00001431
1432 // Second line in transfer list is the total number of blocks we expect to write
Tao Bao51412212016-12-28 14:44:05 -08001433 size_t total_blocks;
1434 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001435 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001436 return StringValue("");
Tao Baob15fd222015-09-24 11:10:51 -07001437 }
1438
1439 if (total_blocks == 0) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001440 return StringValue("t");
Sami Tolvanen90221202014-12-09 16:39:47 +00001441 }
1442
Tao Bao612336d2015-08-27 16:41:21 -07001443 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001444 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001445 if (lines.size() < 4) {
Tao Bao51412212016-12-28 14:44:05 -08001446 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1447 lines.size());
1448 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001449 }
1450
Sami Tolvanen90221202014-12-09 16:39:47 +00001451 // Third line is how many stash entries are needed simultaneously
Tao Bao039f2da2016-11-22 16:29:50 -08001452 LOG(INFO) << "maximum stash entries " << lines[2];
Doug Zongker52ae67d2014-09-08 12:22:09 -07001453
Sami Tolvanen90221202014-12-09 16:39:47 +00001454 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Bao51412212016-12-28 14:44:05 -08001455 size_t stash_max_blocks;
1456 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001457 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1458 lines[3].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001459 return StringValue("");
Doug Zongker52ae67d2014-09-08 12:22:09 -07001460 }
1461
Tao Bao51412212016-12-28 14:44:05 -08001462 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001463 if (res == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001464 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001465 }
Tao Bao612336d2015-08-27 16:41:21 -07001466
Tao Baob15fd222015-09-24 11:10:51 -07001467 params.createdstash = res;
1468
Tao Bao612336d2015-08-27 16:41:21 -07001469 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001470 }
1471
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001472 // Build a map of the available commands
1473 std::unordered_map<std::string, const Command*> cmd_map;
Tao Bao0940fe12015-08-27 16:41:21 -07001474 for (size_t i = 0; i < cmdcount; ++i) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001475 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001476 LOG(ERROR) << "Error: command [" << commands[i].name
1477 << "] already exists in the cmd map.";
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001478 return StringValue(strdup(""));
1479 }
1480 cmd_map[commands[i].name] = &commands[i];
Sami Tolvanen90221202014-12-09 16:39:47 +00001481 }
1482
Tao Bao612336d2015-08-27 16:41:21 -07001483 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001484
Tao Bao612336d2015-08-27 16:41:21 -07001485 // Subsequent lines are all individual transfer commands
1486 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
Tao Bao51412212016-12-28 14:44:05 -08001487 const std::string& line(*it);
1488 if (line.empty()) continue;
Tao Bao6a47dff2015-09-25 17:12:28 -07001489
Tao Bao51412212016-12-28 14:44:05 -08001490 params.tokens = android::base::Split(line, " ");
Tao Baobaad2d42015-12-06 16:56:27 -08001491 params.cpos = 0;
1492 params.cmdname = params.tokens[params.cpos++].c_str();
Tao Bao51412212016-12-28 14:44:05 -08001493 params.cmdline = line.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001494
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001495 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001496 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001497 goto pbiudone;
1498 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001499
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001500 const Command* cmd = cmd_map[params.cmdname];
1501
Tao Bao0940fe12015-08-27 16:41:21 -07001502 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao51412212016-12-28 14:44:05 -08001503 LOG(ERROR) << "failed to execute command [" << line << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001504 goto pbiudone;
1505 }
1506
Sami Tolvanen90221202014-12-09 16:39:47 +00001507 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001508 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001509 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001510 PLOG(ERROR) << "fsync failed";
Tao Bao187efff2015-07-27 14:07:08 -07001511 goto pbiudone;
1512 }
Tao Bao51412212016-12-28 14:44:05 -08001513 fprintf(cmd_pipe, "set_progress %.4f\n",
1514 static_cast<double>(params.written) / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001515 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001516 }
1517 }
1518
Sami Tolvanen90221202014-12-09 16:39:47 +00001519 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001520 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001521
Tao Bao039f2da2016-11-22 16:29:50 -08001522 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1523 LOG(INFO) << "stashed " << params.stashed << " blocks";
1524 LOG(INFO) << "max alloc needed was " << params.buffer.size();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001525
Tianjie Xuaced5d92016-10-12 10:55:04 -07001526 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
Tao Bao51412212016-12-28 14:44:05 -08001527 if (partition != nullptr && *(partition + 1) != 0) {
Tianjie Xudd874b12016-05-13 12:13:15 -07001528 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1529 params.written * BLOCKSIZE);
1530 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1531 params.stashed * BLOCKSIZE);
1532 fflush(cmd_pipe);
1533 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001534 // Delete stash only after successfully completing the update, as it
1535 // may contain blocks needed to complete the update later.
1536 DeleteStash(params.stashbase);
1537 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001538 LOG(INFO) << "verified partition contents; update may be resumed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001539 }
1540
1541 rc = 0;
1542
1543pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001544 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001545 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001546 PLOG(ERROR) << "fsync failed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001547 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001548 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001549
Sami Tolvanen90221202014-12-09 16:39:47 +00001550 // Only delete the stash if the update cannot be resumed, or it's
1551 // a verification run and we created the stash.
1552 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1553 DeleteStash(params.stashbase);
1554 }
1555
Tianjie Xu16255832016-04-30 11:49:59 -07001556 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1557 state->cause_code = failure_type;
1558 }
1559
Tianjie Xuaced5d92016-10-12 10:55:04 -07001560 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001561}
1562
1563// The transfer list is a text file containing commands to
1564// transfer data from one place to another on the target
1565// partition. We parse it and execute the commands in order:
1566//
1567// zero [rangeset]
1568// - fill the indicated blocks with zeros
1569//
1570// new [rangeset]
1571// - fill the blocks with data read from the new_data file
1572//
1573// erase [rangeset]
1574// - mark the given blocks as empty
1575//
1576// move <...>
1577// bsdiff <patchstart> <patchlen> <...>
1578// imgdiff <patchstart> <patchlen> <...>
1579// - read the source blocks, apply a patch (or not in the
1580// case of move), write result to target blocks. bsdiff or
1581// imgdiff specifies the type of patch; move means no patch
1582// at all.
1583//
1584// The format of <...> differs between versions 1 and 2;
1585// see the LoadSrcTgtVersion{1,2}() functions for a
1586// description of what's expected.
1587//
1588// stash <stash_id> <src_range>
1589// - (version 2+ only) load the given source range and stash
1590// the data in the given slot of the stash table.
1591//
Tao Baobaad2d42015-12-06 16:56:27 -08001592// free <stash_id>
1593// - (version 3+ only) free the given stash data.
1594//
Sami Tolvanen90221202014-12-09 16:39:47 +00001595// The creator of the transfer list will guarantee that no block
1596// is read (ie, used as the source for a patch or move) after it
1597// has been written.
1598//
1599// In version 2, the creator will guarantee that a given stash is
1600// loaded (with a stash command) before it's used in a
1601// move/bsdiff/imgdiff command.
1602//
1603// Within one command the source and target ranges may overlap so
1604// in general we need to read the entire source into memory before
1605// writing anything to the target blocks.
1606//
1607// All the patch data is concatenated into one patch_data file in
1608// the update package. It must be stored uncompressed because we
1609// memory-map it in directly from the archive. (Since patches are
1610// already compressed, we lose very little by not compressing
1611// their concatenation.)
1612//
1613// In version 3, commands that read data from the partition (i.e.
1614// move/bsdiff/imgdiff/stash) have one or more additional hashes
1615// before the range parameters, which are used to check if the
1616// command has already been completed and verify the integrity of
1617// the source data.
1618
1619Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001620 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001621 const Command commands[] = {
1622 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001623 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001624 { "free", PerformCommandFree },
1625 { "imgdiff", PerformCommandDiff },
1626 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001627 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001628 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001629 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001630 };
1631
1632 // Perform a dry run without writing to test if an update can proceed
1633 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001634 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001635}
1636
1637Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1638 const Command commands[] = {
1639 { "bsdiff", PerformCommandDiff },
1640 { "erase", PerformCommandErase },
1641 { "free", PerformCommandFree },
1642 { "imgdiff", PerformCommandDiff },
1643 { "move", PerformCommandMove },
1644 { "new", PerformCommandNew },
1645 { "stash", PerformCommandStash },
1646 { "zero", PerformCommandZero }
1647 };
1648
1649 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001650 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001651}
1652
Tao Bao0940fe12015-08-27 16:41:21 -07001653Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001654 std::vector<std::unique_ptr<Value>> args;
1655 if (!ReadValueArgs(state, 2, argv, &args)) {
1656 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001657 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001658
1659 const Value* blockdev_filename = args[0].get();
1660 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001661
1662 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001663 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1664 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001665 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001666 }
1667 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001668 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001669 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001670 }
1671
Tianjie Xuaced5d92016-10-12 10:55:04 -07001672 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001673 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001674 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1675 blockdev_filename->data.c_str(), strerror(errno));
1676 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001677 }
1678
Tao Baoc844c062016-12-28 15:15:55 -08001679 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001680
1681 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001682 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001683
Tao Bao612336d2015-08-27 16:41:21 -07001684 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001685 for (size_t i = 0; i < rs.count; ++i) {
1686 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001687 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1688 blockdev_filename->data.c_str(), strerror(errno));
1689 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001690 }
1691
Tao Bao0940fe12015-08-27 16:41:21 -07001692 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001693 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001694 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1695 blockdev_filename->data.c_str(), strerror(errno));
1696 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001697 }
1698
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001699 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001700 }
1701 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001702 uint8_t digest[SHA_DIGEST_LENGTH];
1703 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001704
Tianjie Xuaced5d92016-10-12 10:55:04 -07001705 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001706}
1707
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001708// This function checks if a device has been remounted R/W prior to an incremental
1709// OTA update. This is an common cause of update abortion. The function reads the
1710// 1st block of each partition and check for mounting time/count. It return string "t"
1711// if executes successfully and an empty string otherwise.
1712
1713Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001714 std::vector<std::unique_ptr<Value>> args;
1715 if (!ReadValueArgs(state, 1, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001716 return nullptr;
1717 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001718
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001719 const Value* arg_filename = args[0].get();
1720
1721 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001722 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001723 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001724 }
1725
Tianjie Xuaced5d92016-10-12 10:55:04 -07001726 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001727 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001728 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001729 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001730 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001731 }
1732
1733 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1734 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1735
1736 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001737 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001738 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001739 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001740 }
1741
1742 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1743 // Super block starts from block 0, offset 0x400
1744 // 0x2C: len32 Mount time
1745 // 0x30: len32 Write time
1746 // 0x34: len16 Number of mounts since the last fsck
1747 // 0x38: len16 Magic signature 0xEF53
1748
1749 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1750 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1751
1752 if (mount_count > 0) {
1753 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1754 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1755 }
1756
Tianjie Xuaced5d92016-10-12 10:55:04 -07001757 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001758}
1759
1760
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001761Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001762 std::vector<std::unique_ptr<Value>> args;
1763 if (!ReadValueArgs(state, 2, argv, &args)) {
1764 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001765 }
1766
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001767 const Value* filename = args[0].get();
1768 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001769
1770 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001771 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001772 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001773 }
1774 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001775 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001776 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001777 }
1778
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001779 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001780 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001781
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001782 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tianjie Xuaced5d92016-10-12 10:55:04 -07001783 fec::io fh(filename->data.c_str(), O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001784
1785 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001786 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001787 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001788 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001789 }
1790
1791 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001792 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001793 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001794 }
1795
1796 fec_status status;
1797
1798 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001799 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001800 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001801 }
1802
Tao Baoc844c062016-12-28 15:15:55 -08001803 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001804
1805 uint8_t buffer[BLOCKSIZE];
1806
1807 for (size_t i = 0; i < rs.count; ++i) {
1808 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1809 // Stay within the data area, libfec validates and corrects metadata
1810 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1811 continue;
1812 }
1813
1814 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001815 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001816 filename->data.c_str(), j, strerror(errno));
1817 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001818 }
1819
1820 // If we want to be able to recover from a situation where rewriting a corrected
1821 // block doesn't guarantee the same data will be returned when re-read later, we
1822 // can save a copy of corrected blocks to /cache. Note:
1823 //
1824 // 1. Maximum space required from /cache is the same as the maximum number of
1825 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1826 // this would be ~16 MiB, for example.
1827 //
1828 // 2. To find out if this block was corrupted, call fec_get_status after each
1829 // read and check if the errors field value has increased.
1830 }
1831 }
Tao Bao039f2da2016-11-22 16:29:50 -08001832 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001833 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001834}
1835
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001836void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001837 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001838 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001839 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001840 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001841 RegisterFunction("range_sha1", RangeSha1Fn);
1842}