blob: efdfec19a4e87f752cfae26340c59086950c3402 [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
Tianjie Xu2cd36ba2017-03-15 23:52:46 +00001223 if (stash_map.find(id) != stash_map.end()) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001224 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001225 }
1226
Tao Bao0940fe12015-08-27 16:41:21 -07001227 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001228 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001229 }
1230
1231 return 0;
1232}
1233
Tao Bao0940fe12015-08-27 16:41:21 -07001234static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001235
Tao Baobaad2d42015-12-06 16:56:27 -08001236 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001237 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001238 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001239 }
1240
Tao Baoc844c062016-12-28 15:15:55 -08001241 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001242
Tao Bao039f2da2016-11-22 16:29:50 -08001243 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001244
Tao Bao612336d2015-08-27 16:41:21 -07001245 allocate(BLOCKSIZE, params.buffer);
1246 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001247
Tao Bao0940fe12015-08-27 16:41:21 -07001248 if (params.canwrite) {
1249 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001250 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1251 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1252 if (!discard_blocks(params.fd, offset, size)) {
1253 return -1;
1254 }
1255
1256 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001257 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001258 }
1259
Tao Bao0940fe12015-08-27 16:41:21 -07001260 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1261 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1262 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001263 }
1264 }
1265 }
1266 }
1267
Tao Bao0940fe12015-08-27 16:41:21 -07001268 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001269 // Update only for the zero command, as the erase command will call
1270 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001271 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001272 }
1273
Tao Bao0940fe12015-08-27 16:41:21 -07001274 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001275}
1276
Tao Bao0940fe12015-08-27 16:41:21 -07001277static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001278
Tao Baobaad2d42015-12-06 16:56:27 -08001279 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001280 LOG(ERROR) << "missing target blocks for new";
Tao Bao0940fe12015-08-27 16:41:21 -07001281 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001282 }
1283
Tao Baoc844c062016-12-28 15:15:55 -08001284 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001285
Tao Bao0940fe12015-08-27 16:41:21 -07001286 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001287 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
Sami Tolvanen90221202014-12-09 16:39:47 +00001288
Tao Bao0940fe12015-08-27 16:41:21 -07001289 RangeSinkState rss(tgt);
1290 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001291 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001292 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001293
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001294 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1295 if (!discard_blocks(params.fd, offset, tgt.size * BLOCKSIZE)) {
1296 return -1;
1297 }
1298
1299 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001300 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001301 }
1302
Tao Bao0940fe12015-08-27 16:41:21 -07001303 pthread_mutex_lock(&params.nti.mu);
1304 params.nti.rss = &rss;
1305 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001306
Tao Bao0940fe12015-08-27 16:41:21 -07001307 while (params.nti.rss) {
1308 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001309 }
1310
Tao Bao0940fe12015-08-27 16:41:21 -07001311 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001312 }
1313
Tao Bao0940fe12015-08-27 16:41:21 -07001314 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001315
Tao Bao0940fe12015-08-27 16:41:21 -07001316 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001317}
1318
Tao Bao0940fe12015-08-27 16:41:21 -07001319static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001320
Tao Baobaad2d42015-12-06 16:56:27 -08001321 // <offset> <length>
1322 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001323 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
Tao Bao0940fe12015-08-27 16:41:21 -07001324 return -1;
1325 }
1326
Tao Baobaad2d42015-12-06 16:56:27 -08001327 size_t offset;
1328 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001329 LOG(ERROR) << "invalid patch offset";
Tao Bao0940fe12015-08-27 16:41:21 -07001330 return -1;
1331 }
1332
Tao Baobaad2d42015-12-06 16:56:27 -08001333 size_t len;
1334 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001335 LOG(ERROR) << "invalid patch len";
Tao Baobaad2d42015-12-06 16:56:27 -08001336 return -1;
1337 }
Tao Bao0940fe12015-08-27 16:41:21 -07001338
Tao Bao612336d2015-08-27 16:41:21 -07001339 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001340 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001341 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001342 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001343 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001344 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001345 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001346 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001347 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001348 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001349 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001350 }
1351
1352 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001353 LOG(ERROR) << "failed to read blocks for diff";
Tao Bao0940fe12015-08-27 16:41:21 -07001354 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001355 }
1356
1357 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001358 params.foundwrites = true;
1359 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001360 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001361 }
1362
Tao Bao0940fe12015-08-27 16:41:21 -07001363 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001364 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001365 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
Tianjie Xuaced5d92016-10-12 10:55:04 -07001366 Value patch_value(VAL_BLOB,
1367 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Tao Bao0940fe12015-08-27 16:41:21 -07001368 RangeSinkState rss(tgt);
1369 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001370 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001371 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001372
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001373 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1374 if (!discard_blocks(params.fd, offset, rss.p_remain)) {
1375 return -1;
1376 }
1377
1378 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001379 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001380 }
1381
Tao Bao0940fe12015-08-27 16:41:21 -07001382 if (params.cmdname[0] == 'i') { // imgdiff
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001383 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1384 &RangeSinkWrite, &rss, nullptr, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001385 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001386 return -1;
1387 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001388 } else {
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001389 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1390 0, &RangeSinkWrite, &rss, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001391 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001392 return -1;
1393 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001394 }
1395
1396 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001397 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001398 LOG(ERROR) << "range sink underrun?";
Sami Tolvanen90221202014-12-09 16:39:47 +00001399 }
1400 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001401 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size
1402 << " [" << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001403 }
1404 }
1405
Tao Baobaad2d42015-12-06 16:56:27 -08001406 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001407 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001408 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001409 }
1410
Tao Bao0940fe12015-08-27 16:41:21 -07001411 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001412
Tao Bao0940fe12015-08-27 16:41:21 -07001413 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001414}
1415
Tao Bao0940fe12015-08-27 16:41:21 -07001416static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001417 if (DEBUG_ERASE) {
1418 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001419 }
1420
Tao Bao0940fe12015-08-27 16:41:21 -07001421 struct stat sb;
1422 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001423 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001424 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001425 }
1426
Tao Bao0940fe12015-08-27 16:41:21 -07001427 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001428 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001429 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001430 }
1431
Tao Baobaad2d42015-12-06 16:56:27 -08001432 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001433 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001434 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001435 }
1436
Tao Baoc844c062016-12-28 15:15:55 -08001437 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001438
Tao Bao0940fe12015-08-27 16:41:21 -07001439 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001440 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001441
Tao Bao0940fe12015-08-27 16:41:21 -07001442 for (size_t i = 0; i < tgt.count; ++i) {
1443 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001444 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001445 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001446 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001447 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001448
Tao Bao0940fe12015-08-27 16:41:21 -07001449 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001450 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001451 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001452 }
1453 }
1454 }
1455
Tao Bao0940fe12015-08-27 16:41:21 -07001456 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001457}
1458
1459// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001460typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001461
Tao Bao612336d2015-08-27 16:41:21 -07001462struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001463 const char* name;
1464 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001465};
Sami Tolvanen90221202014-12-09 16:39:47 +00001466
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001467// args:
1468// - block device (or file) to modify in-place
1469// - transfer list (blob)
1470// - new data stream (filename within package.zip)
1471// - patch stream (filename within package.zip, must be uncompressed)
1472
Tianjie Xuc4447322017-03-06 14:44:59 -08001473static Value* PerformBlockImageUpdate(const char* name, State* state,
1474 const std::vector<std::unique_ptr<Expr>>& argv,
1475 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao73064612016-04-26 17:14:32 -07001476 CommandParameters params = {};
Sami Tolvanen90221202014-12-09 16:39:47 +00001477 params.canwrite = !dryrun;
1478
Tao Bao5354f602016-12-14 11:31:18 -08001479 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001480 if (state->is_retry) {
1481 is_retry = true;
Tao Bao039f2da2016-11-22 16:29:50 -08001482 LOG(INFO) << "This update is a retry.";
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001483 }
Tianjie Xuc4447322017-03-06 14:44:59 -08001484 if (argv.size() != 4) {
1485 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1486 argv.size());
1487 return StringValue("");
1488 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001489
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001490 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001491 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001492 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001493 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001494
1495 const Value* blockdev_filename = args[0].get();
1496 const Value* transfer_list_value = args[1].get();
1497 const Value* new_data_fn = args[2].get();
1498 const Value* patch_data_fn = args[3].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001499
1500 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001501 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1502 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001503 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001504 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001505 if (transfer_list_value->type != VAL_BLOB) {
Tianjie Xu16255832016-04-30 11:49:59 -07001506 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001507 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001508 }
1509 if (new_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001510 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001511 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001512 }
1513 if (patch_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001514 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string",
1515 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001516 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001517 }
1518
Tao Bao51412212016-12-28 14:44:05 -08001519 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
Tao Bao0940fe12015-08-27 16:41:21 -07001520 if (ui == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001521 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001522 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001523
Tao Bao612336d2015-08-27 16:41:21 -07001524 FILE* cmd_pipe = ui->cmd_pipe;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001525 ZipArchiveHandle za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001526
Tao Bao0940fe12015-08-27 16:41:21 -07001527 if (cmd_pipe == nullptr || za == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001528 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001529 }
1530
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001531 ZipString path_data(patch_data_fn->data.c_str());
1532 ZipEntry patch_entry;
1533 if (FindEntry(za, path_data, &patch_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001534 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001535 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001536 }
1537
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001538 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1539 ZipString new_data(new_data_fn->data.c_str());
1540 ZipEntry new_entry;
1541 if (FindEntry(za, new_data, &new_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001542 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001543 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001544 }
1545
Tianjie Xuaced5d92016-10-12 10:55:04 -07001546 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001547 if (params.fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001548 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001549 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001550 }
1551
Sami Tolvanen90221202014-12-09 16:39:47 +00001552 if (params.canwrite) {
1553 params.nti.za = za;
1554 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001555
Tao Bao0940fe12015-08-27 16:41:21 -07001556 pthread_mutex_init(&params.nti.mu, nullptr);
1557 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001558 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001559 pthread_attr_init(&attr);
1560 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1561
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001562 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1563 if (error != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001564 PLOG(ERROR) << "pthread_create failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001565 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001566 }
1567 }
1568
Tianjie Xuaced5d92016-10-12 10:55:04 -07001569 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001570 if (lines.size() < 2) {
Tianjie Xu16255832016-04-30 11:49:59 -07001571 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1572 lines.size());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001573 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001574 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001575
Sami Tolvanen90221202014-12-09 16:39:47 +00001576 // First line in transfer list is the version number
Tao Bao51412212016-12-28 14:44:05 -08001577 if (!android::base::ParseInt(lines[0], &params.version, 1, 4)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001578 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001579 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001580 }
1581
Tao Bao039f2da2016-11-22 16:29:50 -08001582 LOG(INFO) << "blockimg version is " << params.version;
Sami Tolvanen90221202014-12-09 16:39:47 +00001583
1584 // Second line in transfer list is the total number of blocks we expect to write
Tao Bao51412212016-12-28 14:44:05 -08001585 size_t total_blocks;
1586 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001587 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001588 return StringValue("");
Tao Baob15fd222015-09-24 11:10:51 -07001589 }
1590
1591 if (total_blocks == 0) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001592 return StringValue("t");
Sami Tolvanen90221202014-12-09 16:39:47 +00001593 }
1594
Tao Bao612336d2015-08-27 16:41:21 -07001595 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001596 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001597 if (lines.size() < 4) {
Tao Bao51412212016-12-28 14:44:05 -08001598 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1599 lines.size());
1600 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001601 }
1602
Sami Tolvanen90221202014-12-09 16:39:47 +00001603 // Third line is how many stash entries are needed simultaneously
Tao Bao039f2da2016-11-22 16:29:50 -08001604 LOG(INFO) << "maximum stash entries " << lines[2];
Doug Zongker52ae67d2014-09-08 12:22:09 -07001605
Sami Tolvanen90221202014-12-09 16:39:47 +00001606 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Bao51412212016-12-28 14:44:05 -08001607 size_t stash_max_blocks;
1608 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001609 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1610 lines[3].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001611 return StringValue("");
Doug Zongker52ae67d2014-09-08 12:22:09 -07001612 }
1613
Tao Bao51412212016-12-28 14:44:05 -08001614 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001615 if (res == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001616 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001617 }
Tao Bao612336d2015-08-27 16:41:21 -07001618
Tao Baob15fd222015-09-24 11:10:51 -07001619 params.createdstash = res;
1620
Tao Bao612336d2015-08-27 16:41:21 -07001621 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001622 }
1623
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001624 // Build a map of the available commands
1625 std::unordered_map<std::string, const Command*> cmd_map;
Tao Bao0940fe12015-08-27 16:41:21 -07001626 for (size_t i = 0; i < cmdcount; ++i) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001627 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001628 LOG(ERROR) << "Error: command [" << commands[i].name
1629 << "] already exists in the cmd map.";
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001630 return StringValue(strdup(""));
1631 }
1632 cmd_map[commands[i].name] = &commands[i];
Sami Tolvanen90221202014-12-09 16:39:47 +00001633 }
1634
Tao Bao612336d2015-08-27 16:41:21 -07001635 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001636
Tao Bao612336d2015-08-27 16:41:21 -07001637 // Subsequent lines are all individual transfer commands
1638 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
Tao Bao51412212016-12-28 14:44:05 -08001639 const std::string& line(*it);
1640 if (line.empty()) continue;
Tao Bao6a47dff2015-09-25 17:12:28 -07001641
Tao Bao51412212016-12-28 14:44:05 -08001642 params.tokens = android::base::Split(line, " ");
Tao Baobaad2d42015-12-06 16:56:27 -08001643 params.cpos = 0;
1644 params.cmdname = params.tokens[params.cpos++].c_str();
Tao Bao51412212016-12-28 14:44:05 -08001645 params.cmdline = line.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001646
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001647 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001648 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001649 goto pbiudone;
1650 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001651
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001652 const Command* cmd = cmd_map[params.cmdname];
1653
Tao Bao0940fe12015-08-27 16:41:21 -07001654 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao51412212016-12-28 14:44:05 -08001655 LOG(ERROR) << "failed to execute command [" << line << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001656 goto pbiudone;
1657 }
1658
Sami Tolvanen90221202014-12-09 16:39:47 +00001659 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001660 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001661 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001662 PLOG(ERROR) << "fsync failed";
Tao Bao187efff2015-07-27 14:07:08 -07001663 goto pbiudone;
1664 }
Tao Bao51412212016-12-28 14:44:05 -08001665 fprintf(cmd_pipe, "set_progress %.4f\n",
1666 static_cast<double>(params.written) / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001667 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001668 }
1669 }
1670
Sami Tolvanen90221202014-12-09 16:39:47 +00001671 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001672 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001673
Tao Bao039f2da2016-11-22 16:29:50 -08001674 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1675 LOG(INFO) << "stashed " << params.stashed << " blocks";
1676 LOG(INFO) << "max alloc needed was " << params.buffer.size();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001677
Tianjie Xuaced5d92016-10-12 10:55:04 -07001678 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
Tao Bao51412212016-12-28 14:44:05 -08001679 if (partition != nullptr && *(partition + 1) != 0) {
Tianjie Xudd874b12016-05-13 12:13:15 -07001680 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1681 params.written * BLOCKSIZE);
1682 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1683 params.stashed * BLOCKSIZE);
1684 fflush(cmd_pipe);
1685 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001686 // Delete stash only after successfully completing the update, as it
1687 // may contain blocks needed to complete the update later.
1688 DeleteStash(params.stashbase);
1689 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001690 LOG(INFO) << "verified partition contents; update may be resumed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001691 }
1692
1693 rc = 0;
1694
1695pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001696 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001697 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001698 PLOG(ERROR) << "fsync failed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001699 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001700 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001701
Sami Tolvanen90221202014-12-09 16:39:47 +00001702 // Only delete the stash if the update cannot be resumed, or it's
1703 // a verification run and we created the stash.
1704 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1705 DeleteStash(params.stashbase);
1706 }
1707
Tianjie Xu16255832016-04-30 11:49:59 -07001708 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1709 state->cause_code = failure_type;
1710 }
1711
Tianjie Xuaced5d92016-10-12 10:55:04 -07001712 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001713}
1714
1715// The transfer list is a text file containing commands to
1716// transfer data from one place to another on the target
1717// partition. We parse it and execute the commands in order:
1718//
1719// zero [rangeset]
1720// - fill the indicated blocks with zeros
1721//
1722// new [rangeset]
1723// - fill the blocks with data read from the new_data file
1724//
1725// erase [rangeset]
1726// - mark the given blocks as empty
1727//
1728// move <...>
1729// bsdiff <patchstart> <patchlen> <...>
1730// imgdiff <patchstart> <patchlen> <...>
1731// - read the source blocks, apply a patch (or not in the
1732// case of move), write result to target blocks. bsdiff or
1733// imgdiff specifies the type of patch; move means no patch
1734// at all.
1735//
1736// The format of <...> differs between versions 1 and 2;
1737// see the LoadSrcTgtVersion{1,2}() functions for a
1738// description of what's expected.
1739//
1740// stash <stash_id> <src_range>
1741// - (version 2+ only) load the given source range and stash
1742// the data in the given slot of the stash table.
1743//
Tao Baobaad2d42015-12-06 16:56:27 -08001744// free <stash_id>
1745// - (version 3+ only) free the given stash data.
1746//
Sami Tolvanen90221202014-12-09 16:39:47 +00001747// The creator of the transfer list will guarantee that no block
1748// is read (ie, used as the source for a patch or move) after it
1749// has been written.
1750//
1751// In version 2, the creator will guarantee that a given stash is
1752// loaded (with a stash command) before it's used in a
1753// move/bsdiff/imgdiff command.
1754//
1755// Within one command the source and target ranges may overlap so
1756// in general we need to read the entire source into memory before
1757// writing anything to the target blocks.
1758//
1759// All the patch data is concatenated into one patch_data file in
1760// the update package. It must be stored uncompressed because we
1761// memory-map it in directly from the archive. (Since patches are
1762// already compressed, we lose very little by not compressing
1763// their concatenation.)
1764//
1765// In version 3, commands that read data from the partition (i.e.
1766// move/bsdiff/imgdiff/stash) have one or more additional hashes
1767// before the range parameters, which are used to check if the
1768// command has already been completed and verify the integrity of
1769// the source data.
1770
Tianjie Xuc4447322017-03-06 14:44:59 -08001771Value* BlockImageVerifyFn(const char* name, State* state,
1772 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001773 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001774 const Command commands[] = {
1775 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001776 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001777 { "free", PerformCommandFree },
1778 { "imgdiff", PerformCommandDiff },
1779 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001780 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001781 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001782 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001783 };
1784
1785 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001786 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001787 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001788}
1789
Tianjie Xuc4447322017-03-06 14:44:59 -08001790Value* BlockImageUpdateFn(const char* name, State* state,
1791 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001792 const Command commands[] = {
1793 { "bsdiff", PerformCommandDiff },
1794 { "erase", PerformCommandErase },
1795 { "free", PerformCommandFree },
1796 { "imgdiff", PerformCommandDiff },
1797 { "move", PerformCommandMove },
1798 { "new", PerformCommandNew },
1799 { "stash", PerformCommandStash },
1800 { "zero", PerformCommandZero }
1801 };
1802
Tianjie Xuc4447322017-03-06 14:44:59 -08001803 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001804 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001805}
1806
Tianjie Xuc4447322017-03-06 14:44:59 -08001807Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1808 if (argv.size() != 2) {
1809 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu",
1810 argv.size());
1811 return StringValue("");
1812 }
1813
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001814 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001815 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001816 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001817 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001818
1819 const Value* blockdev_filename = args[0].get();
1820 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001821
1822 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001823 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1824 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001825 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001826 }
1827 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001828 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001829 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001830 }
1831
Tianjie Xuaced5d92016-10-12 10:55:04 -07001832 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001833 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001834 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1835 blockdev_filename->data.c_str(), strerror(errno));
1836 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001837 }
1838
Tao Baoc844c062016-12-28 15:15:55 -08001839 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001840
1841 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001842 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001843
Tao Bao612336d2015-08-27 16:41:21 -07001844 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001845 for (size_t i = 0; i < rs.count; ++i) {
1846 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001847 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1848 blockdev_filename->data.c_str(), strerror(errno));
1849 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001850 }
1851
Tao Bao0940fe12015-08-27 16:41:21 -07001852 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001853 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001854 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1855 blockdev_filename->data.c_str(), strerror(errno));
1856 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001857 }
1858
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001859 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001860 }
1861 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001862 uint8_t digest[SHA_DIGEST_LENGTH];
1863 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001864
Tianjie Xuaced5d92016-10-12 10:55:04 -07001865 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001866}
1867
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001868// This function checks if a device has been remounted R/W prior to an incremental
1869// OTA update. This is an common cause of update abortion. The function reads the
1870// 1st block of each partition and check for mounting time/count. It return string "t"
1871// if executes successfully and an empty string otherwise.
1872
Tianjie Xuc4447322017-03-06 14:44:59 -08001873Value* CheckFirstBlockFn(const char* name, State* state,
1874 const std::vector<std::unique_ptr<Expr>>& argv) {
1875 if (argv.size() != 1) {
1876 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1877 argv.size());
1878 return StringValue("");
1879 }
1880
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001881 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001882 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001883 return nullptr;
1884 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001885
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001886 const Value* arg_filename = args[0].get();
1887
1888 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001889 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001890 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001891 }
1892
Tianjie Xuaced5d92016-10-12 10:55:04 -07001893 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001894 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001895 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001896 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001897 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001898 }
1899
1900 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1901 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1902
1903 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001904 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001905 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001906 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001907 }
1908
1909 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1910 // Super block starts from block 0, offset 0x400
1911 // 0x2C: len32 Mount time
1912 // 0x30: len32 Write time
1913 // 0x34: len16 Number of mounts since the last fsck
1914 // 0x38: len16 Magic signature 0xEF53
1915
1916 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1917 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1918
1919 if (mount_count > 0) {
1920 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1921 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1922 }
1923
Tianjie Xuaced5d92016-10-12 10:55:04 -07001924 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001925}
1926
1927
Tianjie Xuc4447322017-03-06 14:44:59 -08001928Value* BlockImageRecoverFn(const char* name, State* state,
1929 const std::vector<std::unique_ptr<Expr>>& argv) {
1930 if (argv.size() != 2) {
1931 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
1932 argv.size());
1933 return StringValue("");
1934 }
1935
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001936 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001937 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001938 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001939 }
1940
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001941 const Value* filename = args[0].get();
1942 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001943
1944 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001945 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001946 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001947 }
1948 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001949 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001950 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001951 }
1952
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001953 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001954 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001955
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001956 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tianjie Xuaced5d92016-10-12 10:55:04 -07001957 fec::io fh(filename->data.c_str(), O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001958
1959 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001960 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001961 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001962 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001963 }
1964
1965 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001966 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001967 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001968 }
1969
1970 fec_status status;
1971
1972 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001973 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001974 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001975 }
1976
Tao Baoc844c062016-12-28 15:15:55 -08001977 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001978
1979 uint8_t buffer[BLOCKSIZE];
1980
1981 for (size_t i = 0; i < rs.count; ++i) {
1982 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1983 // Stay within the data area, libfec validates and corrects metadata
1984 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1985 continue;
1986 }
1987
1988 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001989 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001990 filename->data.c_str(), j, strerror(errno));
1991 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001992 }
1993
1994 // If we want to be able to recover from a situation where rewriting a corrected
1995 // block doesn't guarantee the same data will be returned when re-read later, we
1996 // can save a copy of corrected blocks to /cache. Note:
1997 //
1998 // 1. Maximum space required from /cache is the same as the maximum number of
1999 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
2000 // this would be ~16 MiB, for example.
2001 //
2002 // 2. To find out if this block was corrupted, call fec_get_status after each
2003 // read and check if the errors field value has increased.
2004 }
2005 }
Tao Bao039f2da2016-11-22 16:29:50 -08002006 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07002007 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002008}
2009
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002010void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00002011 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002012 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002013 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002014 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002015 RegisterFunction("range_sha1", RangeSha1Fn);
2016}