blob: 03089ae418fe5caac5c355d490e7ab7e006f8152 [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 Baoe6aa3322015-08-05 15:20:27 -070035#include <memory>
36#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070037#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070038#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070039
Tao Bao039f2da2016-11-22 16:29:50 -080040#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080041#include <android-base/parseint.h>
42#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070043#include <android-base/unique_fd.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070044#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070045
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070046#include "applypatch/applypatch.h"
47#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070048#include "error_code.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070049#include "updater/install.h"
Sen Jiangc48cb5e2016-02-04 16:23:21 +080050#include "openssl/sha.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080051#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070052#include "print_sha1.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070053#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070054
Tao Bao039f2da2016-11-22 16:29:50 -080055static constexpr size_t BLOCKSIZE = 4096;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070056
Sami Tolvanene82fa182015-06-10 15:58:12 +000057// Set this to 0 to interpret 'erase' transfers to mean do a
58// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
59// erase to mean fill the region with zeroes.
60#define DEBUG_ERASE 0
61
Sami Tolvanen90221202014-12-09 16:39:47 +000062#define STASH_DIRECTORY_BASE "/cache/recovery"
63#define STASH_DIRECTORY_MODE 0700
64#define STASH_FILE_MODE 0600
65
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 << "'";
124 exit(1);
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 Baoe6aa3322015-08-05 15:20:27 -0700477typedef void (*StashCallback)(const std::string&, void*);
Sami Tolvanen90221202014-12-09 16:39:47 +0000478
479// Does a best effort enumeration of stash files. Ignores possible non-file
480// items in the stash directory and continues despite of errors. Calls the
481// 'callback' function for each file and passes 'data' to the function as a
482// parameter.
483
Tao Baoe6aa3322015-08-05 15:20:27 -0700484static void EnumerateStash(const std::string& dirname, StashCallback callback, void* data) {
Tao Bao0940fe12015-08-27 16:41:21 -0700485 if (dirname.empty() || callback == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000486 return;
487 }
488
Tao Baoe6aa3322015-08-05 15:20:27 -0700489 std::unique_ptr<DIR, int(*)(DIR*)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000490
Tao Bao0940fe12015-08-27 16:41:21 -0700491 if (directory == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000492 if (errno != ENOENT) {
Tao Bao039f2da2016-11-22 16:29:50 -0800493 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000494 }
495 return;
496 }
497
Tao Baoe6aa3322015-08-05 15:20:27 -0700498 struct dirent* item;
Tao Bao0940fe12015-08-27 16:41:21 -0700499 while ((item = readdir(directory.get())) != nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000500 if (item->d_type != DT_REG) {
501 continue;
502 }
503
Tao Baoe6aa3322015-08-05 15:20:27 -0700504 std::string fn = dirname + "/" + std::string(item->d_name);
Sami Tolvanen90221202014-12-09 16:39:47 +0000505 callback(fn, data);
Sami Tolvanen90221202014-12-09 16:39:47 +0000506 }
507}
508
Tao Baoe6aa3322015-08-05 15:20:27 -0700509static void UpdateFileSize(const std::string& fn, void* data) {
510 if (fn.empty() || !data) {
511 return;
512 }
513
Tao Bao0940fe12015-08-27 16:41:21 -0700514 struct stat sb;
515 if (stat(fn.c_str(), &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800516 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000517 return;
518 }
519
Tao Baoe6aa3322015-08-05 15:20:27 -0700520 int* size = reinterpret_cast<int*>(data);
Tao Bao0940fe12015-08-27 16:41:21 -0700521 *size += sb.st_size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000522}
523
524// Deletes the stash directory and all files in it. Assumes that it only
525// contains files. There is nothing we can do about unlikely, but possible
526// errors, so they are merely logged.
527
Tao Bao0940fe12015-08-27 16:41:21 -0700528static void DeleteFile(const std::string& fn, void* /* data */) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700529 if (!fn.empty()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800530 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000531
Tao Baoe6aa3322015-08-05 15:20:27 -0700532 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
Tao Bao039f2da2016-11-22 16:29:50 -0800533 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000534 }
535 }
536}
537
Tao Baoe6aa3322015-08-05 15:20:27 -0700538static void DeletePartial(const std::string& fn, void* data) {
539 if (android::base::EndsWith(fn, ".partial")) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000540 DeleteFile(fn, data);
541 }
542}
543
Tao Baoe6aa3322015-08-05 15:20:27 -0700544static void DeleteStash(const std::string& base) {
545 if (base.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000546 return;
547 }
548
Tao Bao039f2da2016-11-22 16:29:50 -0800549 LOG(INFO) << "deleting stash " << base;
Sami Tolvanen90221202014-12-09 16:39:47 +0000550
Tao Baoe6aa3322015-08-05 15:20:27 -0700551 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700552 EnumerateStash(dirname, DeleteFile, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000553
Tao Baoe6aa3322015-08-05 15:20:27 -0700554 if (rmdir(dirname.c_str()) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000555 if (errno != ENOENT && errno != ENOTDIR) {
Tao Bao039f2da2016-11-22 16:29:50 -0800556 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000557 }
558 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000559}
560
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700561static int LoadStash(CommandParameters& params, const std::string& base, const std::string& id,
562 bool verify, size_t* blocks, std::vector<uint8_t>& buffer, bool printnoent) {
563 // In verify mode, if source range_set was saved for the given hash,
564 // check contents in the source blocks first. If the check fails,
565 // search for the stashed files on /cache as usual.
566 if (!params.canwrite) {
567 if (stash_map.find(id) != stash_map.end()) {
568 const RangeSet& src = stash_map[id];
569 allocate(src.size * BLOCKSIZE, buffer);
570
571 if (ReadBlocks(src, buffer, params.fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800572 LOG(ERROR) << "failed to read source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700573 return -1;
574 }
575 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800576 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700577 return -1;
578 }
579 return 0;
580 }
581 }
582
Tao Bao612336d2015-08-27 16:41:21 -0700583 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700584 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000585 }
586
Tao Bao0940fe12015-08-27 16:41:21 -0700587 size_t blockcount = 0;
588
Sami Tolvanen90221202014-12-09 16:39:47 +0000589 if (!blocks) {
590 blocks = &blockcount;
591 }
592
Tao Bao0940fe12015-08-27 16:41:21 -0700593 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000594
Tao Bao0940fe12015-08-27 16:41:21 -0700595 struct stat sb;
596 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000597
598 if (res == -1) {
599 if (errno != ENOENT || printnoent) {
Tao Bao039f2da2016-11-22 16:29:50 -0800600 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000601 }
Tao Bao0940fe12015-08-27 16:41:21 -0700602 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000603 }
604
Tao Bao039f2da2016-11-22 16:29:50 -0800605 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000606
Tao Bao0940fe12015-08-27 16:41:21 -0700607 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800608 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
Tao Bao0940fe12015-08-27 16:41:21 -0700609 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000610 }
611
Elliott Hughesbcabd092016-03-22 20:19:22 -0700612 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000613 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800614 PLOG(ERROR) << "open \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700615 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000616 }
617
Tao Bao612336d2015-08-27 16:41:21 -0700618 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000619
Tao Bao612336d2015-08-27 16:41:21 -0700620 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700621 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000622 }
623
Tao Bao0940fe12015-08-27 16:41:21 -0700624 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000625
Tao Bao612336d2015-08-27 16:41:21 -0700626 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800627 LOG(ERROR) << "unexpected contents in " << fn;
Tao Bao0940fe12015-08-27 16:41:21 -0700628 DeleteFile(fn, nullptr);
629 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000630 }
631
Tao Bao0940fe12015-08-27 16:41:21 -0700632 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000633}
634
Tao Bao612336d2015-08-27 16:41:21 -0700635static int WriteStash(const std::string& base, const std::string& id, int blocks,
636 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
637 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700638 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000639 }
640
641 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800642 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700643 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000644 }
645
Tao Bao0940fe12015-08-27 16:41:21 -0700646 std::string fn = GetStashFileName(base, id, ".partial");
647 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000648
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100649 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700650 struct stat sb;
651 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100652
653 if (res == 0) {
654 // The file already exists and since the name is the hash of the contents,
655 // it's safe to assume the contents are identical (accidental hash collisions
656 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800657 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700658 *exists = true;
659 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100660 }
661
Tao Bao0940fe12015-08-27 16:41:21 -0700662 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100663 }
664
Tao Bao039f2da2016-11-22 16:29:50 -0800665 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000666
Tao Bao039f2da2016-11-22 16:29:50 -0800667 android::base::unique_fd fd(
668 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000669 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800670 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700671 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000672 }
673
674 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700675 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000676 }
677
Jed Estepa7b9a462015-12-15 16:04:53 -0800678 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700679 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800680 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700681 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000682 }
683
Tao Baoe6aa3322015-08-05 15:20:27 -0700684 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800685 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700686 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000687 }
688
Tao Bao0940fe12015-08-27 16:41:21 -0700689 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700690 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
691 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700692 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700693 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800694 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700695 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700696 }
697
Jed Estepa7b9a462015-12-15 16:04:53 -0800698 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700699 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800700 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700701 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700702 }
703
Tao Bao0940fe12015-08-27 16:41:21 -0700704 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000705}
706
707// Creates a directory for storing stash files and checks if the /cache partition
708// hash enough space for the expected amount of blocks we need to store. Returns
709// >0 if we created the directory, zero if it existed already, and <0 of failure.
710
Tao Bao0940fe12015-08-27 16:41:21 -0700711static int CreateStash(State* state, int maxblocks, const char* blockdev, std::string& base) {
712 if (blockdev == nullptr) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700713 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000714 }
715
716 // Stash directory should be different for each partition to avoid conflicts
717 // when updating multiple partitions at the same time, so we use the hash of
718 // the block device name as the base directory
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800719 uint8_t digest[SHA_DIGEST_LENGTH];
720 SHA1(reinterpret_cast<const uint8_t*>(blockdev), strlen(blockdev), digest);
Tao Baoe6aa3322015-08-05 15:20:27 -0700721 base = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000722
Tao Baoe6aa3322015-08-05 15:20:27 -0700723 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700724 struct stat sb;
725 int res = stat(dirname.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000726
727 if (res == -1 && errno != ENOENT) {
Tianjie Xu16255832016-04-30 11:49:59 -0700728 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n",
729 dirname.c_str(), strerror(errno));
Tao Baoe6aa3322015-08-05 15:20:27 -0700730 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000731 } else if (res != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800732 LOG(INFO) << "creating stash " << dirname;
Tao Baoe6aa3322015-08-05 15:20:27 -0700733 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000734
735 if (res != 0) {
Tianjie Xu16255832016-04-30 11:49:59 -0700736 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n",
737 dirname.c_str(), strerror(errno));
Tao Baoe6aa3322015-08-05 15:20:27 -0700738 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000739 }
740
741 if (CacheSizeCheck(maxblocks * BLOCKSIZE) != 0) {
Tianjie Xu16255832016-04-30 11:49:59 -0700742 ErrorAbort(state, kStashCreationFailure, "not enough space for stash\n");
Tao Baoe6aa3322015-08-05 15:20:27 -0700743 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000744 }
745
Tao Baoe6aa3322015-08-05 15:20:27 -0700746 return 1; // Created directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000747 }
748
Tao Bao039f2da2016-11-22 16:29:50 -0800749 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000750
751 // If the directory already exists, calculate the space already allocated to
752 // stash files and check if there's enough for all required blocks. Delete any
753 // partially completed stash files first.
754
Tao Bao0940fe12015-08-27 16:41:21 -0700755 EnumerateStash(dirname, DeletePartial, nullptr);
Tao Baoe6aa3322015-08-05 15:20:27 -0700756 int size = 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000757 EnumerateStash(dirname, UpdateFileSize, &size);
758
Tao Bao0940fe12015-08-27 16:41:21 -0700759 size = maxblocks * BLOCKSIZE - size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000760
761 if (size > 0 && CacheSizeCheck(size) != 0) {
Tianjie Xu16255832016-04-30 11:49:59 -0700762 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%d more needed)\n",
763 size);
Tao Baoe6aa3322015-08-05 15:20:27 -0700764 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000765 }
766
Tao Baoe6aa3322015-08-05 15:20:27 -0700767 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000768}
769
Tao Baobaad2d42015-12-06 16:56:27 -0800770static int SaveStash(CommandParameters& params, const std::string& base,
771 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000772
Tao Baobaad2d42015-12-06 16:56:27 -0800773 // <stash_id> <src_range>
774 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800775 LOG(ERROR) << "missing id and/or src range fields in stash command";
Sami Tolvanen90221202014-12-09 16:39:47 +0000776 return -1;
777 }
Tao Baobaad2d42015-12-06 16:56:27 -0800778 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000779
Tao Bao0940fe12015-08-27 16:41:21 -0700780 size_t blocks = 0;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700781 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000782 // Stash file already exists and has expected contents. Do not
783 // read from source again, as the source may have been already
784 // overwritten during a previous attempt.
785 return 0;
786 }
787
Tao Baoc844c062016-12-28 15:15:55 -0800788 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao34847b22015-09-08 11:05:49 -0700789
Tao Bao612336d2015-08-27 16:41:21 -0700790 allocate(src.size * BLOCKSIZE, buffer);
791 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000792 return -1;
793 }
Tao Bao34847b22015-09-08 11:05:49 -0700794 blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000795
Tao Bao612336d2015-08-27 16:41:21 -0700796 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000797 // Source blocks have unexpected contents. If we actually need this
798 // data later, this is an unrecoverable error. However, the command
799 // that uses the data may have already completed previously, so the
800 // possible failure will occur during source block verification.
Tao Bao039f2da2016-11-22 16:29:50 -0800801 LOG(ERROR) << "failed to load source blocks for stash " << id;
Sami Tolvanen90221202014-12-09 16:39:47 +0000802 return 0;
803 }
804
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700805 // In verify mode, save source range_set instead of stashing blocks.
806 if (!params.canwrite && usehash) {
807 stash_map[id] = src;
808 return 0;
809 }
810
Tao Bao039f2da2016-11-22 16:29:50 -0800811 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xudd874b12016-05-13 12:13:15 -0700812 params.stashed += blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700813 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000814}
815
Tao Baobaad2d42015-12-06 16:56:27 -0800816static int FreeStash(const std::string& base, const std::string& id) {
817 if (base.empty() || id.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000818 return -1;
819 }
820
Tao Baobaad2d42015-12-06 16:56:27 -0800821 std::string fn = GetStashFileName(base, id, "");
Tao Bao0940fe12015-08-27 16:41:21 -0700822 DeleteFile(fn, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000823
824 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700825}
826
Tao Bao612336d2015-08-27 16:41:21 -0700827static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
828 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700829 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700830 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700831 // may be the same buffer.
832
Tao Bao612336d2015-08-27 16:41:21 -0700833 const uint8_t* from = source.data();
834 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700835 size_t start = locs.size;
836 for (int i = locs.count-1; i >= 0; --i) {
837 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700838 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700839 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700840 blocks * BLOCKSIZE);
841 }
842}
843
844// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800845// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700846//
847// <tgt_range> <src_block_count> <src_range>
848// (loads data from source image only)
849//
850// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
851// (loads data from stashes only)
852//
853// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
854// (loads data from both source image and stashes)
855//
856// On return, buffer is filled with the loaded source data (rearranged
857// and combined with stashed data as necessary). buffer may be
858// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000859// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700860
Tao Baobaad2d42015-12-06 16:56:27 -0800861static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700862 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800863
864 // At least it needs to provide three parameters: <tgt_range>,
865 // <src_block_count> and "-"/<src_range>.
866 if (params.cpos + 2 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800867 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -0800868 return -1;
869 }
870
Tao Bao612336d2015-08-27 16:41:21 -0700871 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -0800872 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700873
Tao Bao612336d2015-08-27 16:41:21 -0700874 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800875 const std::string& token = params.tokens[params.cpos++];
876 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
Tao Bao039f2da2016-11-22 16:29:50 -0800877 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
Tao Baobaad2d42015-12-06 16:56:27 -0800878 return -1;
879 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700880
Tao Bao612336d2015-08-27 16:41:21 -0700881 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700882
Tao Bao612336d2015-08-27 16:41:21 -0700883 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800884 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700885 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800886 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700887 } else {
Tao Baoc844c062016-12-28 15:15:55 -0800888 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -0700889 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700890
Tao Bao34847b22015-09-08 11:05:49 -0700891 if (overlap) {
892 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700893 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000894
Sami Tolvanen90221202014-12-09 16:39:47 +0000895 if (res == -1) {
896 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700897 }
898
Tao Baobaad2d42015-12-06 16:56:27 -0800899 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000900 // no stashes, only source range
901 return 0;
902 }
903
Tao Baoc844c062016-12-28 15:15:55 -0800904 RangeSet locs = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -0700905 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700906 }
907
Tao Baobaad2d42015-12-06 16:56:27 -0800908 // <[stash_id:stash_range]>
909 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700910 // Each word is a an index into the stash table, a colon, and
911 // then a rangeset describing where in the source block that
912 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800913 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
914 if (tokens.size() != 2) {
Tao Bao039f2da2016-11-22 16:29:50 -0800915 LOG(ERROR) << "invalid parameter";
Tao Baobaad2d42015-12-06 16:56:27 -0800916 return -1;
917 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000918
Tao Bao612336d2015-08-27 16:41:21 -0700919 std::vector<uint8_t> stash;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700920 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000921
922 if (res == -1) {
923 // These source blocks will fail verification if used later, but we
924 // will let the caller decide if this is a fatal failure
Tao Bao039f2da2016-11-22 16:29:50 -0800925 LOG(ERROR) << "failed to load stash " << tokens[0];
Sami Tolvanen90221202014-12-09 16:39:47 +0000926 continue;
927 }
928
Tao Baoc844c062016-12-28 15:15:55 -0800929 RangeSet locs = parse_range(tokens[1]);
Sami Tolvanen90221202014-12-09 16:39:47 +0000930
Tao Bao612336d2015-08-27 16:41:21 -0700931 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000932 }
933
934 return 0;
935}
936
Sami Tolvanen90221202014-12-09 16:39:47 +0000937// Do a source/target load for move/bsdiff/imgdiff in version 3.
938//
939// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
940// tells the function whether to expect separate source and targe block hashes, or
941// if they are both the same and only one hash should be expected, and
942// 'isunresumable', which receives a non-zero value if block verification fails in
943// a way that the update cannot be resumed anymore.
944//
945// If the function is unable to load the necessary blocks or their contents don't
946// match the hashes, the return value is -1 and the command should be aborted.
947//
948// If the return value is 1, the command has already been completed according to
949// the contents of the target blocks, and should not be performed again.
950//
951// If the return value is 0, source blocks have expected content and the command
952// can be performed.
953
Tao Bao34847b22015-09-08 11:05:49 -0700954static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -0700955 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000956
Tao Baobaad2d42015-12-06 16:56:27 -0800957 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800958 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -0700959 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000960 }
961
Tao Baobaad2d42015-12-06 16:56:27 -0800962 std::string srchash = params.tokens[params.cpos++];
963 std::string tgthash;
964
Sami Tolvanen90221202014-12-09 16:39:47 +0000965 if (onehash) {
966 tgthash = srchash;
967 } else {
Tao Baobaad2d42015-12-06 16:56:27 -0800968 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800969 LOG(ERROR) << "missing target hash";
Tao Bao0940fe12015-08-27 16:41:21 -0700970 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000971 }
Tao Baobaad2d42015-12-06 16:56:27 -0800972 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000973 }
974
Elliott Hughesbcabd092016-03-22 20:19:22 -0700975 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd,
976 params.stashbase, &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700977 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000978 }
979
Tao Bao34847b22015-09-08 11:05:49 -0700980 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000981
Tao Bao612336d2015-08-27 16:41:21 -0700982 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700983 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000984 }
985
Tao Bao612336d2015-08-27 16:41:21 -0700986 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000987 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -0700988 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000989 }
990
Tao Bao0940fe12015-08-27 16:41:21 -0700991 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000992 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700993 // resume from possible write errors. In verify mode, we can skip stashing
994 // because the source blocks won't be overwritten.
995 if (overlap && params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -0800996 LOG(INFO) << "stashing " << src_blocks << " overlapping blocks to " << srchash;
Sami Tolvanen90221202014-12-09 16:39:47 +0000997
Tao Bao0940fe12015-08-27 16:41:21 -0700998 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -0700999 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -07001000 &stash_exists) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001001 LOG(ERROR) << "failed to stash overlapping source blocks";
Tao Bao0940fe12015-08-27 16:41:21 -07001002 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001003 }
1004
Tianjie Xudd874b12016-05-13 12:13:15 -07001005 params.stashed += src_blocks;
Sami Tolvanen90221202014-12-09 16:39:47 +00001006 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001007 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -07001008 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001009 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001010 }
1011
1012 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -07001013 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001014 }
1015
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001016 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
1017 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001018 // Overlapping source blocks were previously stashed, command can proceed.
1019 // We are recovering from an interrupted command, so we don't know if the
1020 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -07001021 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001022 }
1023
1024 // Valid source data not available, update cannot be resumed
Tao Bao039f2da2016-11-22 16:29:50 -08001025 LOG(ERROR) << "partition has unexpected contents";
Tao Bao0940fe12015-08-27 16:41:21 -07001026 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +00001027
Tao Bao0940fe12015-08-27 16:41:21 -07001028 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001029}
1030
Tao Bao0940fe12015-08-27 16:41:21 -07001031static int PerformCommandMove(CommandParameters& params) {
1032 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001033 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001034 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001035 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001036
Tao Bao0940fe12015-08-27 16:41:21 -07001037 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001038 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001039 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001040 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001041 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001042 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001043 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001044 }
1045
1046 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001047 LOG(ERROR) << "failed to read blocks for move";
Tao Bao0940fe12015-08-27 16:41:21 -07001048 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001049 }
1050
1051 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001052 params.foundwrites = true;
1053 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001054 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001055 }
1056
Tao Bao0940fe12015-08-27 16:41:21 -07001057 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001058 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001059 LOG(INFO) << " moving " << blocks << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001060
Tao Bao0940fe12015-08-27 16:41:21 -07001061 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1062 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001063 }
1064 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001065 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001066 }
1067
1068 }
1069
Tao Baobaad2d42015-12-06 16:56:27 -08001070 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001071 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001072 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001073 }
1074
Tao Bao0940fe12015-08-27 16:41:21 -07001075 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001076
Tao Bao0940fe12015-08-27 16:41:21 -07001077 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001078}
1079
Tao Bao0940fe12015-08-27 16:41:21 -07001080static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001081 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001082 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001083}
1084
Tao Bao0940fe12015-08-27 16:41:21 -07001085static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001086 // <stash_id>
1087 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001088 LOG(ERROR) << "missing stash id in free command";
Tao Baobaad2d42015-12-06 16:56:27 -08001089 return -1;
1090 }
1091
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001092 const std::string& id = params.tokens[params.cpos++];
1093
1094 if (!params.canwrite && stash_map.find(id) != stash_map.end()) {
1095 stash_map.erase(id);
1096 return 0;
1097 }
1098
Tao Bao0940fe12015-08-27 16:41:21 -07001099 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001100 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001101 }
1102
1103 return 0;
1104}
1105
Tao Bao0940fe12015-08-27 16:41:21 -07001106static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001107
Tao Baobaad2d42015-12-06 16:56:27 -08001108 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001109 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001110 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001111 }
1112
Tao Baoc844c062016-12-28 15:15:55 -08001113 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001114
Tao Bao039f2da2016-11-22 16:29:50 -08001115 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001116
Tao Bao612336d2015-08-27 16:41:21 -07001117 allocate(BLOCKSIZE, params.buffer);
1118 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001119
Tao Bao0940fe12015-08-27 16:41:21 -07001120 if (params.canwrite) {
1121 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001122 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1123 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1124 if (!discard_blocks(params.fd, offset, size)) {
1125 return -1;
1126 }
1127
1128 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001129 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001130 }
1131
Tao Bao0940fe12015-08-27 16:41:21 -07001132 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1133 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1134 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001135 }
1136 }
1137 }
1138 }
1139
Tao Bao0940fe12015-08-27 16:41:21 -07001140 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001141 // Update only for the zero command, as the erase command will call
1142 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001143 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001144 }
1145
Tao Bao0940fe12015-08-27 16:41:21 -07001146 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001147}
1148
Tao Bao0940fe12015-08-27 16:41:21 -07001149static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001150
Tao Baobaad2d42015-12-06 16:56:27 -08001151 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001152 LOG(ERROR) << "missing target blocks for new";
Tao Bao0940fe12015-08-27 16:41:21 -07001153 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001154 }
1155
Tao Baoc844c062016-12-28 15:15:55 -08001156 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001157
Tao Bao0940fe12015-08-27 16:41:21 -07001158 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001159 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
Sami Tolvanen90221202014-12-09 16:39:47 +00001160
Tao Bao0940fe12015-08-27 16:41:21 -07001161 RangeSinkState rss(tgt);
1162 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001163 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001164 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001165
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001166 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1167 if (!discard_blocks(params.fd, offset, tgt.size * BLOCKSIZE)) {
1168 return -1;
1169 }
1170
1171 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001172 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001173 }
1174
Tao Bao0940fe12015-08-27 16:41:21 -07001175 pthread_mutex_lock(&params.nti.mu);
1176 params.nti.rss = &rss;
1177 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001178
Tao Bao0940fe12015-08-27 16:41:21 -07001179 while (params.nti.rss) {
1180 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001181 }
1182
Tao Bao0940fe12015-08-27 16:41:21 -07001183 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001184 }
1185
Tao Bao0940fe12015-08-27 16:41:21 -07001186 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001187
Tao Bao0940fe12015-08-27 16:41:21 -07001188 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001189}
1190
Tao Bao0940fe12015-08-27 16:41:21 -07001191static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001192
Tao Baobaad2d42015-12-06 16:56:27 -08001193 // <offset> <length>
1194 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001195 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
Tao Bao0940fe12015-08-27 16:41:21 -07001196 return -1;
1197 }
1198
Tao Baobaad2d42015-12-06 16:56:27 -08001199 size_t offset;
1200 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001201 LOG(ERROR) << "invalid patch offset";
Tao Bao0940fe12015-08-27 16:41:21 -07001202 return -1;
1203 }
1204
Tao Baobaad2d42015-12-06 16:56:27 -08001205 size_t len;
1206 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001207 LOG(ERROR) << "invalid patch len";
Tao Baobaad2d42015-12-06 16:56:27 -08001208 return -1;
1209 }
Tao Bao0940fe12015-08-27 16:41:21 -07001210
Tao Bao612336d2015-08-27 16:41:21 -07001211 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001212 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001213 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001214 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001215 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001216 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001217 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001218 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001219 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001220 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001221 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001222 }
1223
1224 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001225 LOG(ERROR) << "failed to read blocks for diff";
Tao Bao0940fe12015-08-27 16:41:21 -07001226 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001227 }
1228
1229 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001230 params.foundwrites = true;
1231 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001232 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001233 }
1234
Tao Bao0940fe12015-08-27 16:41:21 -07001235 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001236 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001237 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001238
Tianjie Xuaced5d92016-10-12 10:55:04 -07001239 Value patch_value(VAL_BLOB,
1240 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001241
Tao Bao0940fe12015-08-27 16:41:21 -07001242 RangeSinkState rss(tgt);
1243 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001244 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001245 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001246
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001247 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1248 if (!discard_blocks(params.fd, offset, rss.p_remain)) {
1249 return -1;
1250 }
1251
1252 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001253 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001254 }
1255
Tao Bao0940fe12015-08-27 16:41:21 -07001256 if (params.cmdname[0] == 'i') { // imgdiff
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001257 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1258 &RangeSinkWrite, &rss, nullptr, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001259 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001260 return -1;
1261 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001262 } else {
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001263 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1264 0, &RangeSinkWrite, &rss, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001265 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001266 return -1;
1267 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001268 }
1269
1270 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001271 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001272 LOG(ERROR) << "range sink underrun?";
Sami Tolvanen90221202014-12-09 16:39:47 +00001273 }
1274 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001275 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size
1276 << " [" << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001277 }
1278 }
1279
Tao Baobaad2d42015-12-06 16:56:27 -08001280 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001281 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001282 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001283 }
1284
Tao Bao0940fe12015-08-27 16:41:21 -07001285 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001286
Tao Bao0940fe12015-08-27 16:41:21 -07001287 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001288}
1289
Tao Bao0940fe12015-08-27 16:41:21 -07001290static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001291 if (DEBUG_ERASE) {
1292 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001293 }
1294
Tao Bao0940fe12015-08-27 16:41:21 -07001295 struct stat sb;
1296 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001297 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001298 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001299 }
1300
Tao Bao0940fe12015-08-27 16:41:21 -07001301 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001302 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001303 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001304 }
1305
Tao Baobaad2d42015-12-06 16:56:27 -08001306 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001307 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001308 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001309 }
1310
Tao Baoc844c062016-12-28 15:15:55 -08001311 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001312
Tao Bao0940fe12015-08-27 16:41:21 -07001313 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001314 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001315
Tao Bao0940fe12015-08-27 16:41:21 -07001316 for (size_t i = 0; i < tgt.count; ++i) {
1317 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001318 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001319 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001320 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001321 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001322
Tao Bao0940fe12015-08-27 16:41:21 -07001323 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001324 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001325 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001326 }
1327 }
1328 }
1329
Tao Bao0940fe12015-08-27 16:41:21 -07001330 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001331}
1332
1333// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001334typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001335
Tao Bao612336d2015-08-27 16:41:21 -07001336struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001337 const char* name;
1338 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001339};
Sami Tolvanen90221202014-12-09 16:39:47 +00001340
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001341// args:
1342// - block device (or file) to modify in-place
1343// - transfer list (blob)
1344// - new data stream (filename within package.zip)
1345// - patch stream (filename within package.zip, must be uncompressed)
1346
Tao Bao0940fe12015-08-27 16:41:21 -07001347static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1348 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao73064612016-04-26 17:14:32 -07001349 CommandParameters params = {};
Sami Tolvanen90221202014-12-09 16:39:47 +00001350 params.canwrite = !dryrun;
1351
Tao Bao5354f602016-12-14 11:31:18 -08001352 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001353 if (state->is_retry) {
1354 is_retry = true;
Tao Bao039f2da2016-11-22 16:29:50 -08001355 LOG(INFO) << "This update is a retry.";
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001356 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001357
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001358 std::vector<std::unique_ptr<Value>> args;
1359 if (!ReadValueArgs(state, 4, argv, &args)) {
1360 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001361 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001362
1363 const Value* blockdev_filename = args[0].get();
1364 const Value* transfer_list_value = args[1].get();
1365 const Value* new_data_fn = args[2].get();
1366 const Value* patch_data_fn = args[3].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001367
1368 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001369 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1370 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001371 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001372 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001373 if (transfer_list_value->type != VAL_BLOB) {
Tianjie Xu16255832016-04-30 11:49:59 -07001374 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001375 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001376 }
1377 if (new_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001378 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001379 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001380 }
1381 if (patch_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001382 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string",
1383 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001384 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001385 }
1386
Tao Bao612336d2015-08-27 16:41:21 -07001387 UpdaterInfo* ui = reinterpret_cast<UpdaterInfo*>(state->cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001388
Tao Bao0940fe12015-08-27 16:41:21 -07001389 if (ui == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001390 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001391 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001392
Tao Bao612336d2015-08-27 16:41:21 -07001393 FILE* cmd_pipe = ui->cmd_pipe;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001394 ZipArchiveHandle za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001395
Tao Bao0940fe12015-08-27 16:41:21 -07001396 if (cmd_pipe == nullptr || za == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001397 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001398 }
1399
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001400 ZipString path_data(patch_data_fn->data.c_str());
1401 ZipEntry patch_entry;
1402 if (FindEntry(za, path_data, &patch_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001403 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001404 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001405 }
1406
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001407 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1408 ZipString new_data(new_data_fn->data.c_str());
1409 ZipEntry new_entry;
1410 if (FindEntry(za, new_data, &new_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001411 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001412 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001413 }
1414
Tianjie Xuaced5d92016-10-12 10:55:04 -07001415 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001416 if (params.fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001417 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001418 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001419 }
1420
Sami Tolvanen90221202014-12-09 16:39:47 +00001421 if (params.canwrite) {
1422 params.nti.za = za;
1423 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001424
Tao Bao0940fe12015-08-27 16:41:21 -07001425 pthread_mutex_init(&params.nti.mu, nullptr);
1426 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001427 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001428 pthread_attr_init(&attr);
1429 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1430
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001431 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1432 if (error != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001433 PLOG(ERROR) << "pthread_create failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001434 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001435 }
1436 }
1437
Tianjie Xuaced5d92016-10-12 10:55:04 -07001438 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001439 if (lines.size() < 2) {
Tianjie Xu16255832016-04-30 11:49:59 -07001440 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1441 lines.size());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001442 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001443 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001444
Sami Tolvanen90221202014-12-09 16:39:47 +00001445 // First line in transfer list is the version number
Tao Bao1fdec862015-10-21 14:57:44 -07001446 if (!android::base::ParseInt(lines[0].c_str(), &params.version, 1, 4)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001447 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001448 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001449 }
1450
Tao Bao039f2da2016-11-22 16:29:50 -08001451 LOG(INFO) << "blockimg version is " << params.version;
Sami Tolvanen90221202014-12-09 16:39:47 +00001452
1453 // Second line in transfer list is the total number of blocks we expect to write
Tao Baob15fd222015-09-24 11:10:51 -07001454 int total_blocks;
1455 if (!android::base::ParseInt(lines[1].c_str(), &total_blocks, 0)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001456 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001457 return StringValue("");
Tao Baob15fd222015-09-24 11:10:51 -07001458 }
1459
1460 if (total_blocks == 0) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001461 return StringValue("t");
Sami Tolvanen90221202014-12-09 16:39:47 +00001462 }
1463
Tao Bao612336d2015-08-27 16:41:21 -07001464 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001465 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001466 if (lines.size() < 4) {
Tianjie Xu16255832016-04-30 11:49:59 -07001467 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1468 lines.size());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001469 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001470 }
1471
Sami Tolvanen90221202014-12-09 16:39:47 +00001472 // Third line is how many stash entries are needed simultaneously
Tao Bao039f2da2016-11-22 16:29:50 -08001473 LOG(INFO) << "maximum stash entries " << lines[2];
Doug Zongker52ae67d2014-09-08 12:22:09 -07001474
Sami Tolvanen90221202014-12-09 16:39:47 +00001475 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Baob15fd222015-09-24 11:10:51 -07001476 int stash_max_blocks;
1477 if (!android::base::ParseInt(lines[3].c_str(), &stash_max_blocks, 0)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001478 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1479 lines[3].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001480 return StringValue("");
Doug Zongker52ae67d2014-09-08 12:22:09 -07001481 }
1482
Tianjie Xuaced5d92016-10-12 10:55:04 -07001483 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data.c_str(), params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001484 if (res == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001485 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001486 }
Tao Bao612336d2015-08-27 16:41:21 -07001487
Tao Baob15fd222015-09-24 11:10:51 -07001488 params.createdstash = res;
1489
Tao Bao612336d2015-08-27 16:41:21 -07001490 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001491 }
1492
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001493 // Build a map of the available commands
1494 std::unordered_map<std::string, const Command*> cmd_map;
Tao Bao0940fe12015-08-27 16:41:21 -07001495 for (size_t i = 0; i < cmdcount; ++i) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001496 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001497 LOG(ERROR) << "Error: command [" << commands[i].name
1498 << "] already exists in the cmd map.";
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001499 return StringValue(strdup(""));
1500 }
1501 cmd_map[commands[i].name] = &commands[i];
Sami Tolvanen90221202014-12-09 16:39:47 +00001502 }
1503
Tao Bao612336d2015-08-27 16:41:21 -07001504 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001505
Tao Bao612336d2015-08-27 16:41:21 -07001506 // Subsequent lines are all individual transfer commands
1507 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1508 const std::string& line_str(*it);
Tao Bao6a47dff2015-09-25 17:12:28 -07001509 if (line_str.empty()) {
1510 continue;
1511 }
1512
Tao Baobaad2d42015-12-06 16:56:27 -08001513 params.tokens = android::base::Split(line_str, " ");
1514 params.cpos = 0;
1515 params.cmdname = params.tokens[params.cpos++].c_str();
1516 params.cmdline = line_str.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001517
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001518 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001519 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001520 goto pbiudone;
1521 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001522
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001523 const Command* cmd = cmd_map[params.cmdname];
1524
Tao Bao0940fe12015-08-27 16:41:21 -07001525 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001526 LOG(ERROR) << "failed to execute command [" << line_str << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001527 goto pbiudone;
1528 }
1529
Sami Tolvanen90221202014-12-09 16:39:47 +00001530 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001531 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001532 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001533 PLOG(ERROR) << "fsync failed";
Tao Bao187efff2015-07-27 14:07:08 -07001534 goto pbiudone;
1535 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001536 fprintf(cmd_pipe, "set_progress %.4f\n", (double) params.written / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001537 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001538 }
1539 }
1540
Sami Tolvanen90221202014-12-09 16:39:47 +00001541 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001542 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001543
Tao Bao039f2da2016-11-22 16:29:50 -08001544 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1545 LOG(INFO) << "stashed " << params.stashed << " blocks";
1546 LOG(INFO) << "max alloc needed was " << params.buffer.size();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001547
Tianjie Xuaced5d92016-10-12 10:55:04 -07001548 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
Tianjie Xudd874b12016-05-13 12:13:15 -07001549 if (partition != nullptr && *(partition+1) != 0) {
1550 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1551 params.written * BLOCKSIZE);
1552 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1553 params.stashed * BLOCKSIZE);
1554 fflush(cmd_pipe);
1555 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001556 // Delete stash only after successfully completing the update, as it
1557 // may contain blocks needed to complete the update later.
1558 DeleteStash(params.stashbase);
1559 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001560 LOG(INFO) << "verified partition contents; update may be resumed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001561 }
1562
1563 rc = 0;
1564
1565pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001566 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001567 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001568 PLOG(ERROR) << "fsync failed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001569 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001570 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001571
Sami Tolvanen90221202014-12-09 16:39:47 +00001572 // Only delete the stash if the update cannot be resumed, or it's
1573 // a verification run and we created the stash.
1574 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1575 DeleteStash(params.stashbase);
1576 }
1577
Tianjie Xu16255832016-04-30 11:49:59 -07001578 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1579 state->cause_code = failure_type;
1580 }
1581
Tianjie Xuaced5d92016-10-12 10:55:04 -07001582 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001583}
1584
1585// The transfer list is a text file containing commands to
1586// transfer data from one place to another on the target
1587// partition. We parse it and execute the commands in order:
1588//
1589// zero [rangeset]
1590// - fill the indicated blocks with zeros
1591//
1592// new [rangeset]
1593// - fill the blocks with data read from the new_data file
1594//
1595// erase [rangeset]
1596// - mark the given blocks as empty
1597//
1598// move <...>
1599// bsdiff <patchstart> <patchlen> <...>
1600// imgdiff <patchstart> <patchlen> <...>
1601// - read the source blocks, apply a patch (or not in the
1602// case of move), write result to target blocks. bsdiff or
1603// imgdiff specifies the type of patch; move means no patch
1604// at all.
1605//
1606// The format of <...> differs between versions 1 and 2;
1607// see the LoadSrcTgtVersion{1,2}() functions for a
1608// description of what's expected.
1609//
1610// stash <stash_id> <src_range>
1611// - (version 2+ only) load the given source range and stash
1612// the data in the given slot of the stash table.
1613//
Tao Baobaad2d42015-12-06 16:56:27 -08001614// free <stash_id>
1615// - (version 3+ only) free the given stash data.
1616//
Sami Tolvanen90221202014-12-09 16:39:47 +00001617// The creator of the transfer list will guarantee that no block
1618// is read (ie, used as the source for a patch or move) after it
1619// has been written.
1620//
1621// In version 2, the creator will guarantee that a given stash is
1622// loaded (with a stash command) before it's used in a
1623// move/bsdiff/imgdiff command.
1624//
1625// Within one command the source and target ranges may overlap so
1626// in general we need to read the entire source into memory before
1627// writing anything to the target blocks.
1628//
1629// All the patch data is concatenated into one patch_data file in
1630// the update package. It must be stored uncompressed because we
1631// memory-map it in directly from the archive. (Since patches are
1632// already compressed, we lose very little by not compressing
1633// their concatenation.)
1634//
1635// In version 3, commands that read data from the partition (i.e.
1636// move/bsdiff/imgdiff/stash) have one or more additional hashes
1637// before the range parameters, which are used to check if the
1638// command has already been completed and verify the integrity of
1639// the source data.
1640
1641Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001642 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001643 const Command commands[] = {
1644 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001645 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001646 { "free", PerformCommandFree },
1647 { "imgdiff", PerformCommandDiff },
1648 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001649 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001650 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001651 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001652 };
1653
1654 // Perform a dry run without writing to test if an update can proceed
1655 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001656 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001657}
1658
1659Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1660 const Command commands[] = {
1661 { "bsdiff", PerformCommandDiff },
1662 { "erase", PerformCommandErase },
1663 { "free", PerformCommandFree },
1664 { "imgdiff", PerformCommandDiff },
1665 { "move", PerformCommandMove },
1666 { "new", PerformCommandNew },
1667 { "stash", PerformCommandStash },
1668 { "zero", PerformCommandZero }
1669 };
1670
1671 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001672 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001673}
1674
Tao Bao0940fe12015-08-27 16:41:21 -07001675Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001676 std::vector<std::unique_ptr<Value>> args;
1677 if (!ReadValueArgs(state, 2, argv, &args)) {
1678 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001679 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001680
1681 const Value* blockdev_filename = args[0].get();
1682 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001683
1684 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001685 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1686 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001687 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001688 }
1689 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001690 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001691 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001692 }
1693
Tianjie Xuaced5d92016-10-12 10:55:04 -07001694 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001695 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001696 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1697 blockdev_filename->data.c_str(), strerror(errno));
1698 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001699 }
1700
Tao Baoc844c062016-12-28 15:15:55 -08001701 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001702
1703 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001704 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001705
Tao Bao612336d2015-08-27 16:41:21 -07001706 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001707 for (size_t i = 0; i < rs.count; ++i) {
1708 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001709 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1710 blockdev_filename->data.c_str(), strerror(errno));
1711 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001712 }
1713
Tao Bao0940fe12015-08-27 16:41:21 -07001714 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001715 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001716 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1717 blockdev_filename->data.c_str(), strerror(errno));
1718 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001719 }
1720
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001721 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001722 }
1723 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001724 uint8_t digest[SHA_DIGEST_LENGTH];
1725 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001726
Tianjie Xuaced5d92016-10-12 10:55:04 -07001727 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001728}
1729
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001730// This function checks if a device has been remounted R/W prior to an incremental
1731// OTA update. This is an common cause of update abortion. The function reads the
1732// 1st block of each partition and check for mounting time/count. It return string "t"
1733// if executes successfully and an empty string otherwise.
1734
1735Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001736 std::vector<std::unique_ptr<Value>> args;
1737 if (!ReadValueArgs(state, 1, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001738 return nullptr;
1739 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001740
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001741 const Value* arg_filename = args[0].get();
1742
1743 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001744 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001745 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001746 }
1747
Tianjie Xuaced5d92016-10-12 10:55:04 -07001748 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001749 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001750 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001751 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001752 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001753 }
1754
1755 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1756 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1757
1758 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001759 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001760 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001761 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001762 }
1763
1764 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1765 // Super block starts from block 0, offset 0x400
1766 // 0x2C: len32 Mount time
1767 // 0x30: len32 Write time
1768 // 0x34: len16 Number of mounts since the last fsck
1769 // 0x38: len16 Magic signature 0xEF53
1770
1771 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1772 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1773
1774 if (mount_count > 0) {
1775 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1776 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1777 }
1778
Tianjie Xuaced5d92016-10-12 10:55:04 -07001779 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001780}
1781
1782
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001783Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001784 std::vector<std::unique_ptr<Value>> args;
1785 if (!ReadValueArgs(state, 2, argv, &args)) {
1786 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001787 }
1788
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001789 const Value* filename = args[0].get();
1790 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001791
1792 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001793 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001794 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001795 }
1796 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001797 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001798 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001799 }
1800
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001801 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001802 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001803
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001804 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tianjie Xuaced5d92016-10-12 10:55:04 -07001805 fec::io fh(filename->data.c_str(), O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001806
1807 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001808 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001809 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001810 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001811 }
1812
1813 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001814 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001815 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001816 }
1817
1818 fec_status status;
1819
1820 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001821 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001822 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001823 }
1824
Tao Baoc844c062016-12-28 15:15:55 -08001825 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001826
1827 uint8_t buffer[BLOCKSIZE];
1828
1829 for (size_t i = 0; i < rs.count; ++i) {
1830 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1831 // Stay within the data area, libfec validates and corrects metadata
1832 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1833 continue;
1834 }
1835
1836 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001837 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001838 filename->data.c_str(), j, strerror(errno));
1839 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001840 }
1841
1842 // If we want to be able to recover from a situation where rewriting a corrected
1843 // block doesn't guarantee the same data will be returned when re-read later, we
1844 // can save a copy of corrected blocks to /cache. Note:
1845 //
1846 // 1. Maximum space required from /cache is the same as the maximum number of
1847 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1848 // this would be ~16 MiB, for example.
1849 //
1850 // 2. To find out if this block was corrupted, call fec_get_status after each
1851 // read and check if the errors field value has increased.
1852 }
1853 }
Tao Bao039f2da2016-11-22 16:29:50 -08001854 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001855 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001856}
1857
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001858void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001859 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001860 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001861 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001862 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001863 RegisterFunction("range_sha1", RangeSha1Fn);
1864}