blob: 12ca151a1585e0efa7969bed3186b16b5878adf7 [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
18#include <errno.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000019#include <dirent.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070021#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070022#include <pthread.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000027#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070028#include <sys/types.h>
29#include <sys/wait.h>
30#include <sys/ioctl.h>
31#include <time.h>
32#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010033#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070034
Tao Baoec8272f2017-03-15 17:39:01 -070035#include <functional>
Tao Baoe6aa3322015-08-05 15:20:27 -070036#include <memory>
37#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070038#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070039#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070040
Tao Bao039f2da2016-11-22 16:29:50 -080041#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080042#include <android-base/parseint.h>
43#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070044#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080045#include <applypatch/applypatch.h>
46#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070047#include <private/android_filesystem_config.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070048#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070049
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070050#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070051#include "error_code.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070052#include "updater/install.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080053#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070054#include "print_sha1.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070055#include "updater/updater.h"
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
Tao Bao51412212016-12-28 14:44:05 -080062static constexpr size_t BLOCKSIZE = 4096;
63static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
64static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
65static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000066
Tao Bao0940fe12015-08-27 16:41:21 -070067struct RangeSet {
Tao Baoc844c062016-12-28 15:15:55 -080068 size_t count; // Limit is INT_MAX.
69 size_t size;
70 std::vector<size_t> pos; // Actual limit is INT_MAX.
Tianjie Xu2cd36ba2017-03-15 23:52:46 +000071
72 // Get the block number for the ith(starting from 0) block in the range set.
73 int get_block(size_t idx) const {
74 if (idx >= size) {
75 LOG(ERROR) << "index: " << idx << " is greater than range set size: " << size;
76 return -1;
77 }
78 for (size_t i = 0; i < pos.size(); i += 2) {
79 if (idx < pos[i + 1] - pos[i]) {
80 return pos[i] + idx;
81 }
82 idx -= (pos[i + 1] - pos[i]);
83 }
84 return -1;
85 }
Tao Bao0940fe12015-08-27 16:41:21 -070086};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070087
Tianjie Xu16255832016-04-30 11:49:59 -070088static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070089static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070090static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070091
Tao Baoc844c062016-12-28 15:15:55 -080092static RangeSet parse_range(const std::string& range_text) {
93 RangeSet rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010094
Tao Baoc844c062016-12-28 15:15:55 -080095 std::vector<std::string> pieces = android::base::Split(range_text, ",");
96 if (pieces.size() < 3) {
97 goto err;
98 }
99
100 size_t num;
101 if (!android::base::ParseUint(pieces[0], &num, static_cast<size_t>(INT_MAX))) {
102 goto err;
103 }
104
105 if (num == 0 || num % 2) {
106 goto err; // must be even
107 } else if (num != pieces.size() - 1) {
108 goto err;
109 }
110
111 rs.pos.resize(num);
112 rs.count = num / 2;
113 rs.size = 0;
114
115 for (size_t i = 0; i < num; i += 2) {
116 if (!android::base::ParseUint(pieces[i + 1], &rs.pos[i], static_cast<size_t>(INT_MAX))) {
117 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100118 }
119
Tao Baoc844c062016-12-28 15:15:55 -0800120 if (!android::base::ParseUint(pieces[i + 2], &rs.pos[i + 1], static_cast<size_t>(INT_MAX))) {
121 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100122 }
123
Tao Baoc844c062016-12-28 15:15:55 -0800124 if (rs.pos[i] >= rs.pos[i + 1]) {
125 goto err; // empty or negative range
Tao Baob15fd222015-09-24 11:10:51 -0700126 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100127
Tao Baoc844c062016-12-28 15:15:55 -0800128 size_t sz = rs.pos[i + 1] - rs.pos[i];
129 if (rs.size > SIZE_MAX - sz) {
130 goto err; // overflow
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700131 }
132
Tao Baoc844c062016-12-28 15:15:55 -0800133 rs.size += sz;
134 }
135
136 return rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100137
138err:
Tao Baoc844c062016-12-28 15:15:55 -0800139 LOG(ERROR) << "failed to parse range '" << range_text << "'";
Tao Bao3da88012017-02-03 13:09:23 -0800140 exit(EXIT_FAILURE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700141}
142
Tao Baoe6aa3322015-08-05 15:20:27 -0700143static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Tao Baoc844c062016-12-28 15:15:55 -0800144 for (size_t i = 0; i < r1.count; ++i) {
145 size_t r1_0 = r1.pos[i * 2];
146 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000147
Tao Baoc844c062016-12-28 15:15:55 -0800148 for (size_t j = 0; j < r2.count; ++j) {
149 size_t r2_0 = r2.pos[j * 2];
150 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000151
Tao Baoc844c062016-12-28 15:15:55 -0800152 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
153 return true;
154 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000155 }
Tao Baoc844c062016-12-28 15:15:55 -0800156 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000157
Tao Baoc844c062016-12-28 15:15:55 -0800158 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000159}
160
161static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700162 size_t so_far = 0;
163 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800164 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700165 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700166 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800167 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000168 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700169 } else if (r == 0) {
170 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800171 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700172 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700173 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700174 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700175 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000176 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700177}
178
Tao Bao612336d2015-08-27 16:41:21 -0700179static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
180 return read_all(fd, buffer.data(), size);
181}
182
Sami Tolvanen90221202014-12-09 16:39:47 +0000183static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700184 size_t written = 0;
185 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800186 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700187 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700188 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800189 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000190 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700191 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700192 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700193 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000194
Sami Tolvanen90221202014-12-09 16:39:47 +0000195 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700196}
197
Tao Bao612336d2015-08-27 16:41:21 -0700198static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
199 return write_all(fd, buffer.data(), size);
200}
201
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700202static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
203 // Don't discard blocks unless the update is a retry run.
204 if (!is_retry) {
205 return true;
206 }
207
208 uint64_t args[2] = {static_cast<uint64_t>(offset), size};
209 int status = ioctl(fd, BLKDISCARD, &args);
210 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800211 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700212 return false;
213 }
214 return true;
215}
216
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700217static bool check_lseek(int fd, off64_t offset, int whence) {
218 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
219 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700220 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800221 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700222 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700223 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700224 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700225}
226
Tao Bao612336d2015-08-27 16:41:21 -0700227static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700228 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700229 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700230
Tao Bao612336d2015-08-27 16:41:21 -0700231 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700232}
233
Tao Bao0940fe12015-08-27 16:41:21 -0700234struct RangeSinkState {
Chih-Hung Hsieh49c5c792016-04-29 14:16:35 -0700235 explicit RangeSinkState(RangeSet& rs) : tgt(rs) { };
Tao Bao0940fe12015-08-27 16:41:21 -0700236
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700237 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700238 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530239 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700240 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700241};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700242
243static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700244 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700245
Tao Bao0940fe12015-08-27 16:41:21 -0700246 if (rss->p_remain == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800247 LOG(ERROR) << "range sink write overrun";
Sami Tolvanen90221202014-12-09 16:39:47 +0000248 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700249 }
250
251 ssize_t written = 0;
252 while (size > 0) {
253 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000254
255 if (rss->p_remain < write_now) {
256 write_now = rss->p_remain;
257 }
258
259 if (write_all(rss->fd, data, write_now) == -1) {
260 break;
261 }
262
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700263 data += write_now;
264 size -= write_now;
265
266 rss->p_remain -= write_now;
267 written += write_now;
268
269 if (rss->p_remain == 0) {
270 // move to the next block
271 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700272 if (rss->p_block < rss->tgt.count) {
273 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
274 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000275
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700276 off64_t offset = static_cast<off64_t>(rss->tgt.pos[rss->p_block*2]) * BLOCKSIZE;
277 if (!discard_blocks(rss->fd, offset, rss->p_remain)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000278 break;
279 }
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700280
281 if (!check_lseek(rss->fd, offset, SEEK_SET)) {
282 break;
283 }
284
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700285 } else {
286 // we can't write any more; return how many bytes have
287 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000288 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700289 }
290 }
291 }
292
293 return written;
294}
295
296// All of the data for all the 'new' transfers is contained in one
297// file in the update package, concatenated together in the order in
298// which transfers.list will need it. We want to stream it out of the
299// archive (it's compressed) without writing it to a temp file, but we
300// can't write each section until it's that transfer's turn to go.
301//
302// To achieve this, we expand the new data from the archive in a
303// background thread, and block that threads 'receive uncompressed
304// data' function until the main thread has reached a point where we
305// want some new data to be written. We signal the background thread
306// with the destination for the data and block the main thread,
307// waiting for the background thread to complete writing that section.
308// Then it signals the main thread to wake up and goes back to
309// blocking waiting for a transfer.
310//
311// NewThreadInfo is the struct used to pass information back and forth
312// between the two threads. When the main thread wants some data
313// written, it sets rss to the destination location and signals the
314// condition. When the background thread is done writing, it clears
315// rss and signals the condition again.
316
Tao Bao0940fe12015-08-27 16:41:21 -0700317struct NewThreadInfo {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700318 ZipArchiveHandle za;
319 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700320
321 RangeSinkState* rss;
322
323 pthread_mutex_t mu;
324 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700325};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700326
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700327static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700328 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700329
330 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700331 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700332 // data is wanted.
333 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700334 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700335 pthread_cond_wait(&nti->cv, &nti->mu);
336 }
337 pthread_mutex_unlock(&nti->mu);
338
339 // At this point nti->rss is set, and we own it. The main
340 // thread is waiting for it to disappear from nti.
341 ssize_t written = RangeSinkWrite(data, size, nti->rss);
342 data += written;
343 size -= written;
344
Tao Bao0940fe12015-08-27 16:41:21 -0700345 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700346 // we have written all the bytes desired by this rss.
347
348 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700349 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700350 pthread_cond_broadcast(&nti->cv);
351 pthread_mutex_unlock(&nti->mu);
352 }
353 }
354
355 return true;
356}
357
358static void* unzip_new_data(void* cookie) {
359 NewThreadInfo* nti = (NewThreadInfo*) cookie;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700360 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700361 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700362}
363
Tao Bao612336d2015-08-27 16:41:21 -0700364static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000365 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700366 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000367
Tao Bao0940fe12015-08-27 16:41:21 -0700368 for (size_t i = 0; i < src.count; ++i) {
369 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000370 return -1;
371 }
372
Tao Bao0940fe12015-08-27 16:41:21 -0700373 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000374
Tao Bao612336d2015-08-27 16:41:21 -0700375 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000376 return -1;
377 }
378
379 p += size;
380 }
381
382 return 0;
383}
384
Tao Bao612336d2015-08-27 16:41:21 -0700385static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
386 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000387
Tao Bao0940fe12015-08-27 16:41:21 -0700388 size_t p = 0;
389 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700390 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
391 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
392 if (!discard_blocks(fd, offset, size)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000393 return -1;
394 }
395
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700396 if (!check_lseek(fd, offset, SEEK_SET)) {
397 return -1;
398 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000399
Tao Bao612336d2015-08-27 16:41:21 -0700400 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000401 return -1;
402 }
403
404 p += size;
405 }
406
407 return 0;
408}
409
Tao Baobaad2d42015-12-06 16:56:27 -0800410// Parameters for transfer list command functions
411struct CommandParameters {
412 std::vector<std::string> tokens;
413 size_t cpos;
414 const char* cmdname;
415 const char* cmdline;
416 std::string freestash;
417 std::string stashbase;
418 bool canwrite;
419 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700420 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800421 bool foundwrites;
422 bool isunresumable;
423 int version;
424 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700425 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800426 NewThreadInfo nti;
427 pthread_t thread;
428 std::vector<uint8_t> buffer;
429 uint8_t* patch_start;
430};
431
Doug Zongker52ae67d2014-09-08 12:22:09 -0700432// Do a source/target load for move/bsdiff/imgdiff in version 1.
Tao Baobaad2d42015-12-06 16:56:27 -0800433// We expect to parse the remainder of the parameter tokens as:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700434//
435// <src_range> <tgt_range>
436//
437// The source range is loaded into the provided buffer, reallocating
Tao Bao34847b22015-09-08 11:05:49 -0700438// it to make it larger if necessary.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700439
Tao Baobaad2d42015-12-06 16:56:27 -0800440static int LoadSrcTgtVersion1(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700441 std::vector<uint8_t>& buffer, int fd) {
Tao Baobaad2d42015-12-06 16:56:27 -0800442
443 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800444 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -0800445 return -1;
446 }
447
Tao Bao612336d2015-08-27 16:41:21 -0700448 // <src_range>
Tao Baoc844c062016-12-28 15:15:55 -0800449 RangeSet src = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700450
Tao Bao612336d2015-08-27 16:41:21 -0700451 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -0800452 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700453
Tao Bao612336d2015-08-27 16:41:21 -0700454 allocate(src.size * BLOCKSIZE, buffer);
455 int rc = ReadBlocks(src, buffer, fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700456 src_blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000457
Sami Tolvanen90221202014-12-09 16:39:47 +0000458 return rc;
459}
460
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000461// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
462// handled separately).
463static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
464 const std::vector<uint8_t>& buffer) {
465 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
466 if (params.version < 3) {
467 // TODO handle version 1,2
468 LOG(WARNING) << "version number " << params.version << " is not supported to print hashes";
469 return;
470 }
471
472 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
473 params.tokens[0] == "imgdiff");
474
475 size_t pos = 0;
476 // Command example:
477 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
478 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
479 // [<loc_range> <stashed_blocks>]
480 if (params.tokens[0] == "move") {
481 // src_range for move starts at the 4th position.
482 if (params.tokens.size() < 5) {
483 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
484 return;
485 }
486 pos = 4;
487 } else {
488 // src_range for diff starts at the 7th position.
489 if (params.tokens.size() < 8) {
490 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
491 return;
492 }
493 pos = 7;
494 }
495
496 // Source blocks in stash only, no work to do.
497 if (params.tokens[pos] == "-") {
498 return;
499 }
500
501 RangeSet src = parse_range(params.tokens[pos++]);
502
503 RangeSet locs;
504 // If there's no stashed blocks, content in the buffer is consecutive and has the same
505 // order as the source blocks.
506 if (pos == params.tokens.size()) {
507 locs.count = 1;
508 locs.size = src.size;
509 locs.pos = { 0, src.size };
510 } else {
511 // Otherwise, the next token is the offset of the source blocks in the target range.
512 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
513 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
514 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
515 locs = parse_range(params.tokens[pos++]);
516 CHECK_EQ(src.size, locs.size);
517 CHECK_EQ(locs.pos.size() % 2, static_cast<size_t>(0));
518 }
519
520 LOG(INFO) << "printing hash in hex for " << src.size << " source blocks";
521 for (size_t i = 0; i < src.size; i++) {
522 int block_num = src.get_block(i);
523 CHECK_NE(block_num, -1);
524 int buffer_index = locs.get_block(i);
525 CHECK_NE(buffer_index, -1);
526 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
527
528 uint8_t digest[SHA_DIGEST_LENGTH];
529 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
530 std::string hexdigest = print_sha1(digest);
531 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
532 }
533}
534
535// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
536// in hex for each block.
537static void PrintHashForCorruptedStashedBlocks(const std::string& id,
538 const std::vector<uint8_t>& buffer,
539 const RangeSet& src) {
540 LOG(INFO) << "printing hash in hex for stash_id: " << id;
541 CHECK_EQ(src.size * BLOCKSIZE, buffer.size());
542
543 for (size_t i = 0; i < src.size; i++) {
544 int block_num = src.get_block(i);
545 CHECK_NE(block_num, -1);
546
547 uint8_t digest[SHA_DIGEST_LENGTH];
548 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
549 std::string hexdigest = print_sha1(digest);
550 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
551 }
552}
553
554// If the stash file doesn't exist, read the source blocks this stash contains and print the
555// SHA-1 for these blocks.
556static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
557 if (stash_map.find(id) == stash_map.end()) {
558 LOG(ERROR) << "No stash saved for id: " << id;
559 return;
560 }
561
562 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
563 const RangeSet& src = stash_map[id];
564 std::vector<uint8_t> buffer(src.size * BLOCKSIZE);
565 if (ReadBlocks(src, buffer, fd) == -1) {
566 LOG(ERROR) << "failed to read source blocks for stash: " << id;
567 return;
568 }
569 PrintHashForCorruptedStashedBlocks(id, buffer, src);
570}
571
Tao Bao612336d2015-08-27 16:41:21 -0700572static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700573 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800574 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700575 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000576
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800577 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000578
Tao Baoe6aa3322015-08-05 15:20:27 -0700579 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000580
Tao Bao0940fe12015-08-27 16:41:21 -0700581 if (hexdigest != expected) {
582 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800583 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
584 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700585 }
586 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000587 }
588
Tao Bao0940fe12015-08-27 16:41:21 -0700589 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000590}
591
Tao Bao0940fe12015-08-27 16:41:21 -0700592static std::string GetStashFileName(const std::string& base, const std::string& id,
593 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700594 if (base.empty()) {
595 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000596 }
597
Tao Baoe6aa3322015-08-05 15:20:27 -0700598 std::string fn(STASH_DIRECTORY_BASE);
599 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000600
601 return fn;
602}
603
Tao Baoec8272f2017-03-15 17:39:01 -0700604// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
605// directory and continues despite of errors. Calls the 'callback' function for each file.
606static void EnumerateStash(const std::string& dirname,
607 const std::function<void(const std::string&)>& callback) {
608 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000609
Tao Baoec8272f2017-03-15 17:39:01 -0700610 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000611
Tao Baoec8272f2017-03-15 17:39:01 -0700612 if (directory == nullptr) {
613 if (errno != ENOENT) {
614 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000615 }
Tao Bao51412212016-12-28 14:44:05 -0800616 return;
617 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700618
Tao Baoec8272f2017-03-15 17:39:01 -0700619 dirent* item;
620 while ((item = readdir(directory.get())) != nullptr) {
621 if (item->d_type != DT_REG) continue;
622 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800623 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000624}
625
626// Deletes the stash directory and all files in it. Assumes that it only
627// contains files. There is nothing we can do about unlikely, but possible
628// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700629static void DeleteFile(const std::string& fn) {
630 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000631
Tao Baoec8272f2017-03-15 17:39:01 -0700632 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000633
Tao Baoec8272f2017-03-15 17:39:01 -0700634 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
635 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
636 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000637}
638
Tao Baoe6aa3322015-08-05 15:20:27 -0700639static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700640 if (base.empty()) return;
641
642 LOG(INFO) << "deleting stash " << base;
643
644 std::string dirname = GetStashFileName(base, "", "");
645 EnumerateStash(dirname, DeleteFile);
646
647 if (rmdir(dirname.c_str()) == -1) {
648 if (errno != ENOENT && errno != ENOTDIR) {
649 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000650 }
Tao Baoec8272f2017-03-15 17:39:01 -0700651 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000652}
653
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700654static int LoadStash(CommandParameters& params, const std::string& base, const std::string& id,
655 bool verify, size_t* blocks, std::vector<uint8_t>& buffer, bool printnoent) {
656 // In verify mode, if source range_set was saved for the given hash,
657 // check contents in the source blocks first. If the check fails,
658 // search for the stashed files on /cache as usual.
659 if (!params.canwrite) {
660 if (stash_map.find(id) != stash_map.end()) {
661 const RangeSet& src = stash_map[id];
662 allocate(src.size * BLOCKSIZE, buffer);
663
664 if (ReadBlocks(src, buffer, params.fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800665 LOG(ERROR) << "failed to read source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700666 return -1;
667 }
668 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800669 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000670 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700671 return -1;
672 }
673 return 0;
674 }
675 }
676
Tao Bao612336d2015-08-27 16:41:21 -0700677 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700678 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000679 }
680
Tao Bao0940fe12015-08-27 16:41:21 -0700681 size_t blockcount = 0;
682
Sami Tolvanen90221202014-12-09 16:39:47 +0000683 if (!blocks) {
684 blocks = &blockcount;
685 }
686
Tao Bao0940fe12015-08-27 16:41:21 -0700687 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000688
Tao Bao0940fe12015-08-27 16:41:21 -0700689 struct stat sb;
690 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000691
692 if (res == -1) {
693 if (errno != ENOENT || printnoent) {
Tao Bao039f2da2016-11-22 16:29:50 -0800694 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000695 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000696 }
Tao Bao0940fe12015-08-27 16:41:21 -0700697 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000698 }
699
Tao Bao039f2da2016-11-22 16:29:50 -0800700 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000701
Tao Bao0940fe12015-08-27 16:41:21 -0700702 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800703 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
Tao Bao0940fe12015-08-27 16:41:21 -0700704 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000705 }
706
Elliott Hughesbcabd092016-03-22 20:19:22 -0700707 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000708 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800709 PLOG(ERROR) << "open \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700710 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000711 }
712
Tao Bao612336d2015-08-27 16:41:21 -0700713 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000714
Tao Bao612336d2015-08-27 16:41:21 -0700715 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700716 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000717 }
718
Tao Bao0940fe12015-08-27 16:41:21 -0700719 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000720
Tao Bao612336d2015-08-27 16:41:21 -0700721 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800722 LOG(ERROR) << "unexpected contents in " << fn;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000723 if (stash_map.find(id) == stash_map.end()) {
724 LOG(ERROR) << "failed to find source blocks number for stash " << id
725 << " when executing command: " << params.cmdname;
726 } else {
727 const RangeSet& src = stash_map[id];
728 PrintHashForCorruptedStashedBlocks(id, buffer, src);
729 }
Tao Baoec8272f2017-03-15 17:39:01 -0700730 DeleteFile(fn);
Tao Bao0940fe12015-08-27 16:41:21 -0700731 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000732 }
733
Tao Bao0940fe12015-08-27 16:41:21 -0700734 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000735}
736
Tao Bao612336d2015-08-27 16:41:21 -0700737static int WriteStash(const std::string& base, const std::string& id, int blocks,
738 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
739 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700740 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000741 }
742
743 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800744 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700745 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000746 }
747
Tao Bao0940fe12015-08-27 16:41:21 -0700748 std::string fn = GetStashFileName(base, id, ".partial");
749 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000750
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100751 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700752 struct stat sb;
753 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100754
755 if (res == 0) {
756 // The file already exists and since the name is the hash of the contents,
757 // it's safe to assume the contents are identical (accidental hash collisions
758 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800759 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700760 *exists = true;
761 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100762 }
763
Tao Bao0940fe12015-08-27 16:41:21 -0700764 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100765 }
766
Tao Bao039f2da2016-11-22 16:29:50 -0800767 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000768
Tao Bao039f2da2016-11-22 16:29:50 -0800769 android::base::unique_fd fd(
770 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000771 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800772 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700773 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000774 }
775
Tianjie Xua946b9e2017-03-21 16:24:57 -0700776 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
777 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
778 return -1;
779 }
780
Sami Tolvanen90221202014-12-09 16:39:47 +0000781 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700782 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000783 }
784
Jed Estepa7b9a462015-12-15 16:04:53 -0800785 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700786 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800787 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700788 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000789 }
790
Tao Baoe6aa3322015-08-05 15:20:27 -0700791 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800792 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700793 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000794 }
795
Tao Bao0940fe12015-08-27 16:41:21 -0700796 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700797 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
798 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700799 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700800 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800801 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700802 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700803 }
804
Jed Estepa7b9a462015-12-15 16:04:53 -0800805 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700806 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800807 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700808 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700809 }
810
Tao Bao0940fe12015-08-27 16:41:21 -0700811 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000812}
813
814// Creates a directory for storing stash files and checks if the /cache partition
815// hash enough space for the expected amount of blocks we need to store. Returns
816// >0 if we created the directory, zero if it existed already, and <0 of failure.
817
Tao Bao51412212016-12-28 14:44:05 -0800818static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
819 std::string& base) {
820 if (blockdev.empty()) {
821 return -1;
822 }
823
824 // Stash directory should be different for each partition to avoid conflicts
825 // when updating multiple partitions at the same time, so we use the hash of
826 // the block device name as the base directory
827 uint8_t digest[SHA_DIGEST_LENGTH];
828 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
829 base = print_sha1(digest);
830
831 std::string dirname = GetStashFileName(base, "", "");
832 struct stat sb;
833 int res = stat(dirname.c_str(), &sb);
834 size_t max_stash_size = maxblocks * BLOCKSIZE;
835
836 if (res == -1 && errno != ENOENT) {
837 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
838 strerror(errno));
839 return -1;
840 } else if (res != 0) {
841 LOG(INFO) << "creating stash " << dirname;
842 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
843
844 if (res != 0) {
845 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
846 strerror(errno));
847 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000848 }
849
Tianjie Xua946b9e2017-03-21 16:24:57 -0700850 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
851 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s\n", dirname.c_str(),
852 strerror(errno));
853 return -1;
854 }
855
Tao Bao51412212016-12-28 14:44:05 -0800856 if (CacheSizeCheck(max_stash_size) != 0) {
857 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
858 max_stash_size);
859 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000860 }
861
Tao Bao51412212016-12-28 14:44:05 -0800862 return 1; // Created directory
863 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000864
Tao Bao51412212016-12-28 14:44:05 -0800865 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000866
Tao Baoec8272f2017-03-15 17:39:01 -0700867 // If the directory already exists, calculate the space already allocated to stash files and check
868 // if there's enough for all required blocks. Delete any partially completed stash files first.
869 EnumerateStash(dirname, [](const std::string& fn) {
870 if (android::base::EndsWith(fn, ".partial")) {
871 DeleteFile(fn);
872 }
873 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000874
Tao Bao51412212016-12-28 14:44:05 -0800875 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700876 EnumerateStash(dirname, [&existing](const std::string& fn) {
877 if (fn.empty()) return;
878 struct stat sb;
879 if (stat(fn.c_str(), &sb) == -1) {
880 PLOG(ERROR) << "stat \"" << fn << "\" failed";
881 return;
882 }
883 existing += static_cast<size_t>(sb.st_size);
884 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000885
Tao Bao51412212016-12-28 14:44:05 -0800886 if (max_stash_size > existing) {
887 size_t needed = max_stash_size - existing;
888 if (CacheSizeCheck(needed) != 0) {
889 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
890 needed);
891 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000892 }
Tao Bao51412212016-12-28 14:44:05 -0800893 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000894
Tao Bao51412212016-12-28 14:44:05 -0800895 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000896}
897
Tao Baobaad2d42015-12-06 16:56:27 -0800898static int SaveStash(CommandParameters& params, const std::string& base,
899 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000900
Tao Baobaad2d42015-12-06 16:56:27 -0800901 // <stash_id> <src_range>
902 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800903 LOG(ERROR) << "missing id and/or src range fields in stash command";
Sami Tolvanen90221202014-12-09 16:39:47 +0000904 return -1;
905 }
Tao Baobaad2d42015-12-06 16:56:27 -0800906 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000907
Tao Bao0940fe12015-08-27 16:41:21 -0700908 size_t blocks = 0;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700909 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000910 // Stash file already exists and has expected contents. Do not
911 // read from source again, as the source may have been already
912 // overwritten during a previous attempt.
913 return 0;
914 }
915
Tao Baoc844c062016-12-28 15:15:55 -0800916 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao34847b22015-09-08 11:05:49 -0700917
Tao Bao612336d2015-08-27 16:41:21 -0700918 allocate(src.size * BLOCKSIZE, buffer);
919 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000920 return -1;
921 }
Tao Bao34847b22015-09-08 11:05:49 -0700922 blocks = src.size;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000923 stash_map[id] = src;
Sami Tolvanen90221202014-12-09 16:39:47 +0000924
Tao Bao612336d2015-08-27 16:41:21 -0700925 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000926 // Source blocks have unexpected contents. If we actually need this
927 // data later, this is an unrecoverable error. However, the command
928 // that uses the data may have already completed previously, so the
929 // possible failure will occur during source block verification.
Tao Bao039f2da2016-11-22 16:29:50 -0800930 LOG(ERROR) << "failed to load source blocks for stash " << id;
Sami Tolvanen90221202014-12-09 16:39:47 +0000931 return 0;
932 }
933
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000934 // In verify mode, we don't need to stash any blocks.
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700935 if (!params.canwrite && usehash) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700936 return 0;
937 }
938
Tao Bao039f2da2016-11-22 16:29:50 -0800939 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xudd874b12016-05-13 12:13:15 -0700940 params.stashed += blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700941 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000942}
943
Tao Baobaad2d42015-12-06 16:56:27 -0800944static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700945 if (base.empty() || id.empty()) {
946 return -1;
947 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000948
Tao Baoec8272f2017-03-15 17:39:01 -0700949 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000950
Tao Baoec8272f2017-03-15 17:39:01 -0700951 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700952}
953
Tao Bao612336d2015-08-27 16:41:21 -0700954static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
955 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700956 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700957 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700958 // may be the same buffer.
959
Tao Bao612336d2015-08-27 16:41:21 -0700960 const uint8_t* from = source.data();
961 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700962 size_t start = locs.size;
963 for (int i = locs.count-1; i >= 0; --i) {
964 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700965 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700966 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700967 blocks * BLOCKSIZE);
968 }
969}
970
971// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800972// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700973//
974// <tgt_range> <src_block_count> <src_range>
975// (loads data from source image only)
976//
977// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
978// (loads data from stashes only)
979//
980// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
981// (loads data from both source image and stashes)
982//
983// On return, buffer is filled with the loaded source data (rearranged
984// and combined with stashed data as necessary). buffer may be
985// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000986// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700987
Tao Baobaad2d42015-12-06 16:56:27 -0800988static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700989 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800990
991 // At least it needs to provide three parameters: <tgt_range>,
992 // <src_block_count> and "-"/<src_range>.
993 if (params.cpos + 2 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800994 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -0800995 return -1;
996 }
997
Tao Bao612336d2015-08-27 16:41:21 -0700998 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -0800999 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001000
Tao Bao612336d2015-08-27 16:41:21 -07001001 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -08001002 const std::string& token = params.tokens[params.cpos++];
1003 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001004 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
Tao Baobaad2d42015-12-06 16:56:27 -08001005 return -1;
1006 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001007
Tao Bao612336d2015-08-27 16:41:21 -07001008 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001009
Tao Bao612336d2015-08-27 16:41:21 -07001010 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -08001011 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -07001012 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -08001013 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001014 } else {
Tao Baoc844c062016-12-28 15:15:55 -08001015 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -07001016 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001017
Tao Bao34847b22015-09-08 11:05:49 -07001018 if (overlap) {
1019 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001020 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001021
Sami Tolvanen90221202014-12-09 16:39:47 +00001022 if (res == -1) {
1023 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001024 }
1025
Tao Baobaad2d42015-12-06 16:56:27 -08001026 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001027 // no stashes, only source range
1028 return 0;
1029 }
1030
Tao Baoc844c062016-12-28 15:15:55 -08001031 RangeSet locs = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -07001032 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001033 }
1034
Tao Baobaad2d42015-12-06 16:56:27 -08001035 // <[stash_id:stash_range]>
1036 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -07001037 // Each word is a an index into the stash table, a colon, and
1038 // then a rangeset describing where in the source block that
1039 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -08001040 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1041 if (tokens.size() != 2) {
Tao Bao039f2da2016-11-22 16:29:50 -08001042 LOG(ERROR) << "invalid parameter";
Tao Baobaad2d42015-12-06 16:56:27 -08001043 return -1;
1044 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001045
Tao Bao612336d2015-08-27 16:41:21 -07001046 std::vector<uint8_t> stash;
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001047 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001048
1049 if (res == -1) {
1050 // These source blocks will fail verification if used later, but we
1051 // will let the caller decide if this is a fatal failure
Tao Bao039f2da2016-11-22 16:29:50 -08001052 LOG(ERROR) << "failed to load stash " << tokens[0];
Sami Tolvanen90221202014-12-09 16:39:47 +00001053 continue;
1054 }
1055
Tao Baoc844c062016-12-28 15:15:55 -08001056 RangeSet locs = parse_range(tokens[1]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001057
Tao Bao612336d2015-08-27 16:41:21 -07001058 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +00001059 }
1060
1061 return 0;
1062}
1063
Sami Tolvanen90221202014-12-09 16:39:47 +00001064// Do a source/target load for move/bsdiff/imgdiff in version 3.
1065//
1066// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
1067// tells the function whether to expect separate source and targe block hashes, or
1068// if they are both the same and only one hash should be expected, and
1069// 'isunresumable', which receives a non-zero value if block verification fails in
1070// a way that the update cannot be resumed anymore.
1071//
1072// If the function is unable to load the necessary blocks or their contents don't
1073// match the hashes, the return value is -1 and the command should be aborted.
1074//
1075// If the return value is 1, the command has already been completed according to
1076// the contents of the target blocks, and should not be performed again.
1077//
1078// If the return value is 0, source blocks have expected content and the command
1079// can be performed.
1080
Tao Bao34847b22015-09-08 11:05:49 -07001081static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -07001082 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001083
Tao Baobaad2d42015-12-06 16:56:27 -08001084 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001085 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001086 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001087 }
1088
Tao Baobaad2d42015-12-06 16:56:27 -08001089 std::string srchash = params.tokens[params.cpos++];
1090 std::string tgthash;
1091
Sami Tolvanen90221202014-12-09 16:39:47 +00001092 if (onehash) {
1093 tgthash = srchash;
1094 } else {
Tao Baobaad2d42015-12-06 16:56:27 -08001095 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001096 LOG(ERROR) << "missing target hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001097 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001098 }
Tao Baobaad2d42015-12-06 16:56:27 -08001099 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +00001100 }
1101
Elliott Hughesbcabd092016-03-22 20:19:22 -07001102 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd,
1103 params.stashbase, &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -07001104 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001105 }
1106
Tao Bao34847b22015-09-08 11:05:49 -07001107 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001108
Tao Bao612336d2015-08-27 16:41:21 -07001109 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -07001110 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001111 }
1112
Tao Bao612336d2015-08-27 16:41:21 -07001113 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001114 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -07001115 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001116 }
1117
Tao Bao0940fe12015-08-27 16:41:21 -07001118 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001119 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001120 // resume from possible write errors. In verify mode, we can skip stashing
1121 // because the source blocks won't be overwritten.
1122 if (overlap && params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001123 LOG(INFO) << "stashing " << src_blocks << " overlapping blocks to " << srchash;
Sami Tolvanen90221202014-12-09 16:39:47 +00001124
Tao Bao0940fe12015-08-27 16:41:21 -07001125 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -07001126 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -07001127 &stash_exists) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001128 LOG(ERROR) << "failed to stash overlapping source blocks";
Tao Bao0940fe12015-08-27 16:41:21 -07001129 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001130 }
1131
Tianjie Xudd874b12016-05-13 12:13:15 -07001132 params.stashed += src_blocks;
Sami Tolvanen90221202014-12-09 16:39:47 +00001133 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001134 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -07001135 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001136 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001137 }
1138
1139 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -07001140 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001141 }
1142
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001143 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
1144 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001145 // Overlapping source blocks were previously stashed, command can proceed.
1146 // We are recovering from an interrupted command, so we don't know if the
1147 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -07001148 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001149 }
1150
1151 // Valid source data not available, update cannot be resumed
Tao Bao039f2da2016-11-22 16:29:50 -08001152 LOG(ERROR) << "partition has unexpected contents";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +00001153 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1154
Tao Bao0940fe12015-08-27 16:41:21 -07001155 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +00001156
Tao Bao0940fe12015-08-27 16:41:21 -07001157 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001158}
1159
Tao Bao0940fe12015-08-27 16:41:21 -07001160static int PerformCommandMove(CommandParameters& params) {
1161 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001162 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001163 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001164 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001165
Tao Bao0940fe12015-08-27 16:41:21 -07001166 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001167 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001168 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001169 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001170 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001171 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001172 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001173 }
1174
1175 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001176 LOG(ERROR) << "failed to read blocks for move";
Tao Bao0940fe12015-08-27 16:41:21 -07001177 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001178 }
1179
1180 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001181 params.foundwrites = true;
1182 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001183 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001184 }
1185
Tao Bao0940fe12015-08-27 16:41:21 -07001186 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001187 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001188 LOG(INFO) << " moving " << blocks << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001189
Tao Bao0940fe12015-08-27 16:41:21 -07001190 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1191 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001192 }
1193 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001194 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001195 }
1196
1197 }
1198
Tao Baobaad2d42015-12-06 16:56:27 -08001199 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001200 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001201 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001202 }
1203
Tao Bao0940fe12015-08-27 16:41:21 -07001204 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001205
Tao Bao0940fe12015-08-27 16:41:21 -07001206 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001207}
1208
Tao Bao0940fe12015-08-27 16:41:21 -07001209static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001210 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001211 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001212}
1213
Tao Bao0940fe12015-08-27 16:41:21 -07001214static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001215 // <stash_id>
1216 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001217 LOG(ERROR) << "missing stash id in free command";
Tao Baobaad2d42015-12-06 16:56:27 -08001218 return -1;
1219 }
1220
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001221 const std::string& id = params.tokens[params.cpos++];
1222
Mikhail Lappobb8bce92017-03-23 17:16:17 +01001223 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001224
Tao Bao0940fe12015-08-27 16:41:21 -07001225 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001226 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001227 }
1228
1229 return 0;
1230}
1231
Tao Bao0940fe12015-08-27 16:41:21 -07001232static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001233
Tao Baobaad2d42015-12-06 16:56:27 -08001234 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001235 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001236 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001237 }
1238
Tao Baoc844c062016-12-28 15:15:55 -08001239 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001240
Tao Bao039f2da2016-11-22 16:29:50 -08001241 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001242
Tao Bao612336d2015-08-27 16:41:21 -07001243 allocate(BLOCKSIZE, params.buffer);
1244 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001245
Tao Bao0940fe12015-08-27 16:41:21 -07001246 if (params.canwrite) {
1247 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001248 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1249 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1250 if (!discard_blocks(params.fd, offset, size)) {
1251 return -1;
1252 }
1253
1254 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001255 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001256 }
1257
Tao Bao0940fe12015-08-27 16:41:21 -07001258 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1259 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1260 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001261 }
1262 }
1263 }
1264 }
1265
Tao Bao0940fe12015-08-27 16:41:21 -07001266 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001267 // Update only for the zero command, as the erase command will call
1268 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001269 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001270 }
1271
Tao Bao0940fe12015-08-27 16:41:21 -07001272 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001273}
1274
Tao Bao0940fe12015-08-27 16:41:21 -07001275static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001276
Tao Baobaad2d42015-12-06 16:56:27 -08001277 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001278 LOG(ERROR) << "missing target blocks for new";
Tao Bao0940fe12015-08-27 16:41:21 -07001279 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001280 }
1281
Tao Baoc844c062016-12-28 15:15:55 -08001282 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001283
Tao Bao0940fe12015-08-27 16:41:21 -07001284 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001285 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
Sami Tolvanen90221202014-12-09 16:39:47 +00001286
Tao Bao0940fe12015-08-27 16:41:21 -07001287 RangeSinkState rss(tgt);
1288 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001289 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001290 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001291
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001292 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1293 if (!discard_blocks(params.fd, offset, tgt.size * BLOCKSIZE)) {
1294 return -1;
1295 }
1296
1297 if (!check_lseek(params.fd, offset, SEEK_SET)) {
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 pthread_mutex_lock(&params.nti.mu);
1302 params.nti.rss = &rss;
1303 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001304
Tao Bao0940fe12015-08-27 16:41:21 -07001305 while (params.nti.rss) {
1306 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001307 }
1308
Tao Bao0940fe12015-08-27 16:41:21 -07001309 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001310 }
1311
Tao Bao0940fe12015-08-27 16:41:21 -07001312 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001313
Tao Bao0940fe12015-08-27 16:41:21 -07001314 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001315}
1316
Tao Bao0940fe12015-08-27 16:41:21 -07001317static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001318
Tao Baobaad2d42015-12-06 16:56:27 -08001319 // <offset> <length>
1320 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001321 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
Tao Bao0940fe12015-08-27 16:41:21 -07001322 return -1;
1323 }
1324
Tao Baobaad2d42015-12-06 16:56:27 -08001325 size_t offset;
1326 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001327 LOG(ERROR) << "invalid patch offset";
Tao Bao0940fe12015-08-27 16:41:21 -07001328 return -1;
1329 }
1330
Tao Baobaad2d42015-12-06 16:56:27 -08001331 size_t len;
1332 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001333 LOG(ERROR) << "invalid patch len";
Tao Baobaad2d42015-12-06 16:56:27 -08001334 return -1;
1335 }
Tao Bao0940fe12015-08-27 16:41:21 -07001336
Tao Bao612336d2015-08-27 16:41:21 -07001337 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001338 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001339 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001340 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001341 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001342 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001343 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001344 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001345 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001346 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001347 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001348 }
1349
1350 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001351 LOG(ERROR) << "failed to read blocks for diff";
Tao Bao0940fe12015-08-27 16:41:21 -07001352 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001353 }
1354
1355 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001356 params.foundwrites = true;
1357 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001358 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001359 }
1360
Tao Bao0940fe12015-08-27 16:41:21 -07001361 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001362 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001363 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
Tianjie Xuaced5d92016-10-12 10:55:04 -07001364 Value patch_value(VAL_BLOB,
1365 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Tao Bao0940fe12015-08-27 16:41:21 -07001366 RangeSinkState rss(tgt);
1367 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001368 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001369 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001370
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001371 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1372 if (!discard_blocks(params.fd, offset, rss.p_remain)) {
1373 return -1;
1374 }
1375
1376 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001377 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001378 }
1379
Tao Bao0940fe12015-08-27 16:41:21 -07001380 if (params.cmdname[0] == 'i') { // imgdiff
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001381 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1382 &RangeSinkWrite, &rss, nullptr, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001383 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001384 return -1;
1385 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001386 } else {
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001387 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1388 0, &RangeSinkWrite, &rss, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001389 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001390 return -1;
1391 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001392 }
1393
1394 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001395 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001396 LOG(ERROR) << "range sink underrun?";
Sami Tolvanen90221202014-12-09 16:39:47 +00001397 }
1398 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001399 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size
1400 << " [" << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001401 }
1402 }
1403
Tao Baobaad2d42015-12-06 16:56:27 -08001404 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001405 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001406 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001407 }
1408
Tao Bao0940fe12015-08-27 16:41:21 -07001409 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001410
Tao Bao0940fe12015-08-27 16:41:21 -07001411 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001412}
1413
Tao Bao0940fe12015-08-27 16:41:21 -07001414static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001415 if (DEBUG_ERASE) {
1416 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001417 }
1418
Tao Bao0940fe12015-08-27 16:41:21 -07001419 struct stat sb;
1420 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001421 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001422 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001423 }
1424
Tao Bao0940fe12015-08-27 16:41:21 -07001425 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001426 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001427 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001428 }
1429
Tao Baobaad2d42015-12-06 16:56:27 -08001430 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001431 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001432 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001433 }
1434
Tao Baoc844c062016-12-28 15:15:55 -08001435 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001436
Tao Bao0940fe12015-08-27 16:41:21 -07001437 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001438 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001439
Tao Bao0940fe12015-08-27 16:41:21 -07001440 for (size_t i = 0; i < tgt.count; ++i) {
1441 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001442 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001443 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001444 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001445 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001446
Tao Bao0940fe12015-08-27 16:41:21 -07001447 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001448 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001449 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001450 }
1451 }
1452 }
1453
Tao Bao0940fe12015-08-27 16:41:21 -07001454 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001455}
1456
1457// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001458typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001459
Tao Bao612336d2015-08-27 16:41:21 -07001460struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001461 const char* name;
1462 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001463};
Sami Tolvanen90221202014-12-09 16:39:47 +00001464
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001465// args:
1466// - block device (or file) to modify in-place
1467// - transfer list (blob)
1468// - new data stream (filename within package.zip)
1469// - patch stream (filename within package.zip, must be uncompressed)
1470
Tianjie Xuc4447322017-03-06 14:44:59 -08001471static Value* PerformBlockImageUpdate(const char* name, State* state,
1472 const std::vector<std::unique_ptr<Expr>>& argv,
1473 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao73064612016-04-26 17:14:32 -07001474 CommandParameters params = {};
Sami Tolvanen90221202014-12-09 16:39:47 +00001475 params.canwrite = !dryrun;
1476
Tao Bao5354f602016-12-14 11:31:18 -08001477 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001478 if (state->is_retry) {
1479 is_retry = true;
Tao Bao039f2da2016-11-22 16:29:50 -08001480 LOG(INFO) << "This update is a retry.";
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001481 }
Tianjie Xuc4447322017-03-06 14:44:59 -08001482 if (argv.size() != 4) {
1483 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1484 argv.size());
1485 return StringValue("");
1486 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001487
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001488 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001489 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001490 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001491 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001492
1493 const Value* blockdev_filename = args[0].get();
1494 const Value* transfer_list_value = args[1].get();
1495 const Value* new_data_fn = args[2].get();
1496 const Value* patch_data_fn = args[3].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001497
1498 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001499 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1500 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001501 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001502 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001503 if (transfer_list_value->type != VAL_BLOB) {
Tianjie Xu16255832016-04-30 11:49:59 -07001504 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001505 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001506 }
1507 if (new_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001508 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001509 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001510 }
1511 if (patch_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001512 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string",
1513 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001514 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001515 }
1516
Tao Bao51412212016-12-28 14:44:05 -08001517 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
Tao Bao0940fe12015-08-27 16:41:21 -07001518 if (ui == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001519 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001520 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001521
Tao Bao612336d2015-08-27 16:41:21 -07001522 FILE* cmd_pipe = ui->cmd_pipe;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001523 ZipArchiveHandle za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001524
Tao Bao0940fe12015-08-27 16:41:21 -07001525 if (cmd_pipe == nullptr || za == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001526 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001527 }
1528
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001529 ZipString path_data(patch_data_fn->data.c_str());
1530 ZipEntry patch_entry;
1531 if (FindEntry(za, path_data, &patch_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001532 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001533 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001534 }
1535
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001536 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1537 ZipString new_data(new_data_fn->data.c_str());
1538 ZipEntry new_entry;
1539 if (FindEntry(za, new_data, &new_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001540 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001541 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001542 }
1543
Tianjie Xuaced5d92016-10-12 10:55:04 -07001544 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001545 if (params.fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001546 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001547 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001548 }
1549
Sami Tolvanen90221202014-12-09 16:39:47 +00001550 if (params.canwrite) {
1551 params.nti.za = za;
1552 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001553
Tao Bao0940fe12015-08-27 16:41:21 -07001554 pthread_mutex_init(&params.nti.mu, nullptr);
1555 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001556 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001557 pthread_attr_init(&attr);
1558 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1559
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001560 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1561 if (error != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001562 PLOG(ERROR) << "pthread_create failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001563 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001564 }
1565 }
1566
Tianjie Xuaced5d92016-10-12 10:55:04 -07001567 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001568 if (lines.size() < 2) {
Tianjie Xu16255832016-04-30 11:49:59 -07001569 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1570 lines.size());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001571 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001572 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001573
Sami Tolvanen90221202014-12-09 16:39:47 +00001574 // First line in transfer list is the version number
Tao Bao51412212016-12-28 14:44:05 -08001575 if (!android::base::ParseInt(lines[0], &params.version, 1, 4)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001576 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001577 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001578 }
1579
Tao Bao039f2da2016-11-22 16:29:50 -08001580 LOG(INFO) << "blockimg version is " << params.version;
Sami Tolvanen90221202014-12-09 16:39:47 +00001581
1582 // Second line in transfer list is the total number of blocks we expect to write
Tao Bao51412212016-12-28 14:44:05 -08001583 size_t total_blocks;
1584 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001585 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001586 return StringValue("");
Tao Baob15fd222015-09-24 11:10:51 -07001587 }
1588
1589 if (total_blocks == 0) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001590 return StringValue("t");
Sami Tolvanen90221202014-12-09 16:39:47 +00001591 }
1592
Tao Bao612336d2015-08-27 16:41:21 -07001593 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001594 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001595 if (lines.size() < 4) {
Tao Bao51412212016-12-28 14:44:05 -08001596 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1597 lines.size());
1598 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001599 }
1600
Sami Tolvanen90221202014-12-09 16:39:47 +00001601 // Third line is how many stash entries are needed simultaneously
Tao Bao039f2da2016-11-22 16:29:50 -08001602 LOG(INFO) << "maximum stash entries " << lines[2];
Doug Zongker52ae67d2014-09-08 12:22:09 -07001603
Sami Tolvanen90221202014-12-09 16:39:47 +00001604 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Bao51412212016-12-28 14:44:05 -08001605 size_t stash_max_blocks;
1606 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001607 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1608 lines[3].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001609 return StringValue("");
Doug Zongker52ae67d2014-09-08 12:22:09 -07001610 }
1611
Tao Bao51412212016-12-28 14:44:05 -08001612 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001613 if (res == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001614 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001615 }
Tao Bao612336d2015-08-27 16:41:21 -07001616
Tao Baob15fd222015-09-24 11:10:51 -07001617 params.createdstash = res;
1618
Tao Bao612336d2015-08-27 16:41:21 -07001619 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001620 }
1621
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001622 // Build a map of the available commands
1623 std::unordered_map<std::string, const Command*> cmd_map;
Tao Bao0940fe12015-08-27 16:41:21 -07001624 for (size_t i = 0; i < cmdcount; ++i) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001625 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001626 LOG(ERROR) << "Error: command [" << commands[i].name
1627 << "] already exists in the cmd map.";
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001628 return StringValue(strdup(""));
1629 }
1630 cmd_map[commands[i].name] = &commands[i];
Sami Tolvanen90221202014-12-09 16:39:47 +00001631 }
1632
Tao Bao612336d2015-08-27 16:41:21 -07001633 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001634
Tao Bao612336d2015-08-27 16:41:21 -07001635 // Subsequent lines are all individual transfer commands
1636 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
Tao Bao51412212016-12-28 14:44:05 -08001637 const std::string& line(*it);
1638 if (line.empty()) continue;
Tao Bao6a47dff2015-09-25 17:12:28 -07001639
Tao Bao51412212016-12-28 14:44:05 -08001640 params.tokens = android::base::Split(line, " ");
Tao Baobaad2d42015-12-06 16:56:27 -08001641 params.cpos = 0;
1642 params.cmdname = params.tokens[params.cpos++].c_str();
Tao Bao51412212016-12-28 14:44:05 -08001643 params.cmdline = line.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001644
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001645 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001646 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001647 goto pbiudone;
1648 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001649
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001650 const Command* cmd = cmd_map[params.cmdname];
1651
Tao Bao0940fe12015-08-27 16:41:21 -07001652 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao51412212016-12-28 14:44:05 -08001653 LOG(ERROR) << "failed to execute command [" << line << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001654 goto pbiudone;
1655 }
1656
Sami Tolvanen90221202014-12-09 16:39:47 +00001657 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001658 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001659 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001660 PLOG(ERROR) << "fsync failed";
Tao Bao187efff2015-07-27 14:07:08 -07001661 goto pbiudone;
1662 }
Tao Bao51412212016-12-28 14:44:05 -08001663 fprintf(cmd_pipe, "set_progress %.4f\n",
1664 static_cast<double>(params.written) / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001665 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001666 }
1667 }
1668
Sami Tolvanen90221202014-12-09 16:39:47 +00001669 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001670 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001671
Tao Bao039f2da2016-11-22 16:29:50 -08001672 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1673 LOG(INFO) << "stashed " << params.stashed << " blocks";
1674 LOG(INFO) << "max alloc needed was " << params.buffer.size();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001675
Tianjie Xuaced5d92016-10-12 10:55:04 -07001676 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
Tao Bao51412212016-12-28 14:44:05 -08001677 if (partition != nullptr && *(partition + 1) != 0) {
Tianjie Xudd874b12016-05-13 12:13:15 -07001678 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1679 params.written * BLOCKSIZE);
1680 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1681 params.stashed * BLOCKSIZE);
1682 fflush(cmd_pipe);
1683 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001684 // Delete stash only after successfully completing the update, as it
1685 // may contain blocks needed to complete the update later.
1686 DeleteStash(params.stashbase);
1687 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001688 LOG(INFO) << "verified partition contents; update may be resumed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001689 }
1690
1691 rc = 0;
1692
1693pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001694 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001695 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001696 PLOG(ERROR) << "fsync failed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001697 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001698 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001699
Sami Tolvanen90221202014-12-09 16:39:47 +00001700 // Only delete the stash if the update cannot be resumed, or it's
1701 // a verification run and we created the stash.
1702 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1703 DeleteStash(params.stashbase);
1704 }
1705
Tianjie Xu16255832016-04-30 11:49:59 -07001706 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1707 state->cause_code = failure_type;
1708 }
1709
Tianjie Xuaced5d92016-10-12 10:55:04 -07001710 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001711}
1712
1713// The transfer list is a text file containing commands to
1714// transfer data from one place to another on the target
1715// partition. We parse it and execute the commands in order:
1716//
1717// zero [rangeset]
1718// - fill the indicated blocks with zeros
1719//
1720// new [rangeset]
1721// - fill the blocks with data read from the new_data file
1722//
1723// erase [rangeset]
1724// - mark the given blocks as empty
1725//
1726// move <...>
1727// bsdiff <patchstart> <patchlen> <...>
1728// imgdiff <patchstart> <patchlen> <...>
1729// - read the source blocks, apply a patch (or not in the
1730// case of move), write result to target blocks. bsdiff or
1731// imgdiff specifies the type of patch; move means no patch
1732// at all.
1733//
1734// The format of <...> differs between versions 1 and 2;
1735// see the LoadSrcTgtVersion{1,2}() functions for a
1736// description of what's expected.
1737//
1738// stash <stash_id> <src_range>
1739// - (version 2+ only) load the given source range and stash
1740// the data in the given slot of the stash table.
1741//
Tao Baobaad2d42015-12-06 16:56:27 -08001742// free <stash_id>
1743// - (version 3+ only) free the given stash data.
1744//
Sami Tolvanen90221202014-12-09 16:39:47 +00001745// The creator of the transfer list will guarantee that no block
1746// is read (ie, used as the source for a patch or move) after it
1747// has been written.
1748//
1749// In version 2, the creator will guarantee that a given stash is
1750// loaded (with a stash command) before it's used in a
1751// move/bsdiff/imgdiff command.
1752//
1753// Within one command the source and target ranges may overlap so
1754// in general we need to read the entire source into memory before
1755// writing anything to the target blocks.
1756//
1757// All the patch data is concatenated into one patch_data file in
1758// the update package. It must be stored uncompressed because we
1759// memory-map it in directly from the archive. (Since patches are
1760// already compressed, we lose very little by not compressing
1761// their concatenation.)
1762//
1763// In version 3, commands that read data from the partition (i.e.
1764// move/bsdiff/imgdiff/stash) have one or more additional hashes
1765// before the range parameters, which are used to check if the
1766// command has already been completed and verify the integrity of
1767// the source data.
1768
Tianjie Xuc4447322017-03-06 14:44:59 -08001769Value* BlockImageVerifyFn(const char* name, State* state,
1770 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001771 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001772 const Command commands[] = {
1773 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001774 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001775 { "free", PerformCommandFree },
1776 { "imgdiff", PerformCommandDiff },
1777 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001778 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001779 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001780 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001781 };
1782
1783 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001784 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001785 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001786}
1787
Tianjie Xuc4447322017-03-06 14:44:59 -08001788Value* BlockImageUpdateFn(const char* name, State* state,
1789 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001790 const Command commands[] = {
1791 { "bsdiff", PerformCommandDiff },
1792 { "erase", PerformCommandErase },
1793 { "free", PerformCommandFree },
1794 { "imgdiff", PerformCommandDiff },
1795 { "move", PerformCommandMove },
1796 { "new", PerformCommandNew },
1797 { "stash", PerformCommandStash },
1798 { "zero", PerformCommandZero }
1799 };
1800
Tianjie Xuc4447322017-03-06 14:44:59 -08001801 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001802 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001803}
1804
Tianjie Xuc4447322017-03-06 14:44:59 -08001805Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1806 if (argv.size() != 2) {
1807 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu",
1808 argv.size());
1809 return StringValue("");
1810 }
1811
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001812 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001813 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001814 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001815 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001816
1817 const Value* blockdev_filename = args[0].get();
1818 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001819
1820 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001821 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1822 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001823 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001824 }
1825 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001826 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001827 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001828 }
1829
Tianjie Xuaced5d92016-10-12 10:55:04 -07001830 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001831 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001832 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1833 blockdev_filename->data.c_str(), strerror(errno));
1834 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001835 }
1836
Tao Baoc844c062016-12-28 15:15:55 -08001837 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001838
1839 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001840 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001841
Tao Bao612336d2015-08-27 16:41:21 -07001842 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001843 for (size_t i = 0; i < rs.count; ++i) {
1844 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001845 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1846 blockdev_filename->data.c_str(), strerror(errno));
1847 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001848 }
1849
Tao Bao0940fe12015-08-27 16:41:21 -07001850 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001851 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001852 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1853 blockdev_filename->data.c_str(), strerror(errno));
1854 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001855 }
1856
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001857 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001858 }
1859 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001860 uint8_t digest[SHA_DIGEST_LENGTH];
1861 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001862
Tianjie Xuaced5d92016-10-12 10:55:04 -07001863 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001864}
1865
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001866// This function checks if a device has been remounted R/W prior to an incremental
1867// OTA update. This is an common cause of update abortion. The function reads the
1868// 1st block of each partition and check for mounting time/count. It return string "t"
1869// if executes successfully and an empty string otherwise.
1870
Tianjie Xuc4447322017-03-06 14:44:59 -08001871Value* CheckFirstBlockFn(const char* name, State* state,
1872 const std::vector<std::unique_ptr<Expr>>& argv) {
1873 if (argv.size() != 1) {
1874 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1875 argv.size());
1876 return StringValue("");
1877 }
1878
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001879 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001880 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001881 return nullptr;
1882 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001883
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001884 const Value* arg_filename = args[0].get();
1885
1886 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001887 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001888 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001889 }
1890
Tianjie Xuaced5d92016-10-12 10:55:04 -07001891 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001892 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001893 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001894 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001895 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001896 }
1897
1898 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1899 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1900
1901 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001902 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001903 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001904 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001905 }
1906
1907 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1908 // Super block starts from block 0, offset 0x400
1909 // 0x2C: len32 Mount time
1910 // 0x30: len32 Write time
1911 // 0x34: len16 Number of mounts since the last fsck
1912 // 0x38: len16 Magic signature 0xEF53
1913
1914 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1915 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1916
1917 if (mount_count > 0) {
1918 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1919 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1920 }
1921
Tianjie Xuaced5d92016-10-12 10:55:04 -07001922 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001923}
1924
1925
Tianjie Xuc4447322017-03-06 14:44:59 -08001926Value* BlockImageRecoverFn(const char* name, State* state,
1927 const std::vector<std::unique_ptr<Expr>>& argv) {
1928 if (argv.size() != 2) {
1929 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
1930 argv.size());
1931 return StringValue("");
1932 }
1933
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001934 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001935 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001936 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001937 }
1938
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001939 const Value* filename = args[0].get();
1940 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001941
1942 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001943 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001944 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001945 }
1946 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001947 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001948 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001949 }
1950
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001951 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001952 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001953
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001954 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tianjie Xuaced5d92016-10-12 10:55:04 -07001955 fec::io fh(filename->data.c_str(), O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001956
1957 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001958 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001959 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001960 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001961 }
1962
1963 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001964 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001965 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001966 }
1967
1968 fec_status status;
1969
1970 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001971 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001972 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001973 }
1974
Tao Baoc844c062016-12-28 15:15:55 -08001975 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001976
1977 uint8_t buffer[BLOCKSIZE];
1978
1979 for (size_t i = 0; i < rs.count; ++i) {
1980 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1981 // Stay within the data area, libfec validates and corrects metadata
1982 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1983 continue;
1984 }
1985
1986 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001987 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001988 filename->data.c_str(), j, strerror(errno));
1989 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001990 }
1991
1992 // If we want to be able to recover from a situation where rewriting a corrected
1993 // block doesn't guarantee the same data will be returned when re-read later, we
1994 // can save a copy of corrected blocks to /cache. Note:
1995 //
1996 // 1. Maximum space required from /cache is the same as the maximum number of
1997 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1998 // this would be ~16 MiB, for example.
1999 //
2000 // 2. To find out if this block was corrupted, call fec_get_status after each
2001 // read and check if the errors field value has increased.
2002 }
2003 }
Tao Bao039f2da2016-11-22 16:29:50 -08002004 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07002005 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002006}
2007
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002008void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00002009 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002010 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002011 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002012 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002013 RegisterFunction("range_sha1", RangeSha1Fn);
2014}