blob: 8dbd8c7d1d83698556f5418a0a97eefd4cbe8158 [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
Tao Bao0940fe12015-08-27 16:41:21 -07001473static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1474 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao73064612016-04-26 17:14:32 -07001475 CommandParameters params = {};
Sami Tolvanen90221202014-12-09 16:39:47 +00001476 params.canwrite = !dryrun;
1477
Tao Bao5354f602016-12-14 11:31:18 -08001478 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001479 if (state->is_retry) {
1480 is_retry = true;
Tao Bao039f2da2016-11-22 16:29:50 -08001481 LOG(INFO) << "This update is a retry.";
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001482 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001483
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001484 std::vector<std::unique_ptr<Value>> args;
1485 if (!ReadValueArgs(state, 4, argv, &args)) {
1486 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001487 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001488
1489 const Value* blockdev_filename = args[0].get();
1490 const Value* transfer_list_value = args[1].get();
1491 const Value* new_data_fn = args[2].get();
1492 const Value* patch_data_fn = args[3].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001493
1494 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001495 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1496 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001497 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001498 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001499 if (transfer_list_value->type != VAL_BLOB) {
Tianjie Xu16255832016-04-30 11:49:59 -07001500 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001501 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001502 }
1503 if (new_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001504 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001505 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001506 }
1507 if (patch_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001508 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string",
1509 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001510 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001511 }
1512
Tao Bao51412212016-12-28 14:44:05 -08001513 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
Tao Bao0940fe12015-08-27 16:41:21 -07001514 if (ui == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001515 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001516 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001517
Tao Bao612336d2015-08-27 16:41:21 -07001518 FILE* cmd_pipe = ui->cmd_pipe;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001519 ZipArchiveHandle za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001520
Tao Bao0940fe12015-08-27 16:41:21 -07001521 if (cmd_pipe == nullptr || za == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001522 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001523 }
1524
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001525 ZipString path_data(patch_data_fn->data.c_str());
1526 ZipEntry patch_entry;
1527 if (FindEntry(za, path_data, &patch_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001528 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001529 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001530 }
1531
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001532 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1533 ZipString new_data(new_data_fn->data.c_str());
1534 ZipEntry new_entry;
1535 if (FindEntry(za, new_data, &new_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001536 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001537 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001538 }
1539
Tianjie Xuaced5d92016-10-12 10:55:04 -07001540 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001541 if (params.fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001542 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001543 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001544 }
1545
Sami Tolvanen90221202014-12-09 16:39:47 +00001546 if (params.canwrite) {
1547 params.nti.za = za;
1548 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001549
Tao Bao0940fe12015-08-27 16:41:21 -07001550 pthread_mutex_init(&params.nti.mu, nullptr);
1551 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001552 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001553 pthread_attr_init(&attr);
1554 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1555
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001556 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1557 if (error != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001558 PLOG(ERROR) << "pthread_create failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001559 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001560 }
1561 }
1562
Tianjie Xuaced5d92016-10-12 10:55:04 -07001563 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001564 if (lines.size() < 2) {
Tianjie Xu16255832016-04-30 11:49:59 -07001565 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1566 lines.size());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001567 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001568 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001569
Sami Tolvanen90221202014-12-09 16:39:47 +00001570 // First line in transfer list is the version number
Tao Bao51412212016-12-28 14:44:05 -08001571 if (!android::base::ParseInt(lines[0], &params.version, 1, 4)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001572 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001573 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001574 }
1575
Tao Bao039f2da2016-11-22 16:29:50 -08001576 LOG(INFO) << "blockimg version is " << params.version;
Sami Tolvanen90221202014-12-09 16:39:47 +00001577
1578 // Second line in transfer list is the total number of blocks we expect to write
Tao Bao51412212016-12-28 14:44:05 -08001579 size_t total_blocks;
1580 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001581 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001582 return StringValue("");
Tao Baob15fd222015-09-24 11:10:51 -07001583 }
1584
1585 if (total_blocks == 0) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001586 return StringValue("t");
Sami Tolvanen90221202014-12-09 16:39:47 +00001587 }
1588
Tao Bao612336d2015-08-27 16:41:21 -07001589 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001590 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001591 if (lines.size() < 4) {
Tao Bao51412212016-12-28 14:44:05 -08001592 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1593 lines.size());
1594 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001595 }
1596
Sami Tolvanen90221202014-12-09 16:39:47 +00001597 // Third line is how many stash entries are needed simultaneously
Tao Bao039f2da2016-11-22 16:29:50 -08001598 LOG(INFO) << "maximum stash entries " << lines[2];
Doug Zongker52ae67d2014-09-08 12:22:09 -07001599
Sami Tolvanen90221202014-12-09 16:39:47 +00001600 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Bao51412212016-12-28 14:44:05 -08001601 size_t stash_max_blocks;
1602 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001603 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1604 lines[3].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001605 return StringValue("");
Doug Zongker52ae67d2014-09-08 12:22:09 -07001606 }
1607
Tao Bao51412212016-12-28 14:44:05 -08001608 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001609 if (res == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001610 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001611 }
Tao Bao612336d2015-08-27 16:41:21 -07001612
Tao Baob15fd222015-09-24 11:10:51 -07001613 params.createdstash = res;
1614
Tao Bao612336d2015-08-27 16:41:21 -07001615 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001616 }
1617
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001618 // Build a map of the available commands
1619 std::unordered_map<std::string, const Command*> cmd_map;
Tao Bao0940fe12015-08-27 16:41:21 -07001620 for (size_t i = 0; i < cmdcount; ++i) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001621 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001622 LOG(ERROR) << "Error: command [" << commands[i].name
1623 << "] already exists in the cmd map.";
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001624 return StringValue(strdup(""));
1625 }
1626 cmd_map[commands[i].name] = &commands[i];
Sami Tolvanen90221202014-12-09 16:39:47 +00001627 }
1628
Tao Bao612336d2015-08-27 16:41:21 -07001629 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001630
Tao Bao612336d2015-08-27 16:41:21 -07001631 // Subsequent lines are all individual transfer commands
1632 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
Tao Bao51412212016-12-28 14:44:05 -08001633 const std::string& line(*it);
1634 if (line.empty()) continue;
Tao Bao6a47dff2015-09-25 17:12:28 -07001635
Tao Bao51412212016-12-28 14:44:05 -08001636 params.tokens = android::base::Split(line, " ");
Tao Baobaad2d42015-12-06 16:56:27 -08001637 params.cpos = 0;
1638 params.cmdname = params.tokens[params.cpos++].c_str();
Tao Bao51412212016-12-28 14:44:05 -08001639 params.cmdline = line.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001640
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001641 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001642 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001643 goto pbiudone;
1644 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001645
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001646 const Command* cmd = cmd_map[params.cmdname];
1647
Tao Bao0940fe12015-08-27 16:41:21 -07001648 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao51412212016-12-28 14:44:05 -08001649 LOG(ERROR) << "failed to execute command [" << line << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001650 goto pbiudone;
1651 }
1652
Sami Tolvanen90221202014-12-09 16:39:47 +00001653 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001654 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001655 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001656 PLOG(ERROR) << "fsync failed";
Tao Bao187efff2015-07-27 14:07:08 -07001657 goto pbiudone;
1658 }
Tao Bao51412212016-12-28 14:44:05 -08001659 fprintf(cmd_pipe, "set_progress %.4f\n",
1660 static_cast<double>(params.written) / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001661 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001662 }
1663 }
1664
Sami Tolvanen90221202014-12-09 16:39:47 +00001665 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001666 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001667
Tao Bao039f2da2016-11-22 16:29:50 -08001668 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1669 LOG(INFO) << "stashed " << params.stashed << " blocks";
1670 LOG(INFO) << "max alloc needed was " << params.buffer.size();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001671
Tianjie Xuaced5d92016-10-12 10:55:04 -07001672 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
Tao Bao51412212016-12-28 14:44:05 -08001673 if (partition != nullptr && *(partition + 1) != 0) {
Tianjie Xudd874b12016-05-13 12:13:15 -07001674 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1675 params.written * BLOCKSIZE);
1676 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1677 params.stashed * BLOCKSIZE);
1678 fflush(cmd_pipe);
1679 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001680 // Delete stash only after successfully completing the update, as it
1681 // may contain blocks needed to complete the update later.
1682 DeleteStash(params.stashbase);
1683 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001684 LOG(INFO) << "verified partition contents; update may be resumed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001685 }
1686
1687 rc = 0;
1688
1689pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001690 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001691 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001692 PLOG(ERROR) << "fsync failed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001693 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001694 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001695
Sami Tolvanen90221202014-12-09 16:39:47 +00001696 // Only delete the stash if the update cannot be resumed, or it's
1697 // a verification run and we created the stash.
1698 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1699 DeleteStash(params.stashbase);
1700 }
1701
Tianjie Xu16255832016-04-30 11:49:59 -07001702 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1703 state->cause_code = failure_type;
1704 }
1705
Tianjie Xuaced5d92016-10-12 10:55:04 -07001706 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001707}
1708
1709// The transfer list is a text file containing commands to
1710// transfer data from one place to another on the target
1711// partition. We parse it and execute the commands in order:
1712//
1713// zero [rangeset]
1714// - fill the indicated blocks with zeros
1715//
1716// new [rangeset]
1717// - fill the blocks with data read from the new_data file
1718//
1719// erase [rangeset]
1720// - mark the given blocks as empty
1721//
1722// move <...>
1723// bsdiff <patchstart> <patchlen> <...>
1724// imgdiff <patchstart> <patchlen> <...>
1725// - read the source blocks, apply a patch (or not in the
1726// case of move), write result to target blocks. bsdiff or
1727// imgdiff specifies the type of patch; move means no patch
1728// at all.
1729//
1730// The format of <...> differs between versions 1 and 2;
1731// see the LoadSrcTgtVersion{1,2}() functions for a
1732// description of what's expected.
1733//
1734// stash <stash_id> <src_range>
1735// - (version 2+ only) load the given source range and stash
1736// the data in the given slot of the stash table.
1737//
Tao Baobaad2d42015-12-06 16:56:27 -08001738// free <stash_id>
1739// - (version 3+ only) free the given stash data.
1740//
Sami Tolvanen90221202014-12-09 16:39:47 +00001741// The creator of the transfer list will guarantee that no block
1742// is read (ie, used as the source for a patch or move) after it
1743// has been written.
1744//
1745// In version 2, the creator will guarantee that a given stash is
1746// loaded (with a stash command) before it's used in a
1747// move/bsdiff/imgdiff command.
1748//
1749// Within one command the source and target ranges may overlap so
1750// in general we need to read the entire source into memory before
1751// writing anything to the target blocks.
1752//
1753// All the patch data is concatenated into one patch_data file in
1754// the update package. It must be stored uncompressed because we
1755// memory-map it in directly from the archive. (Since patches are
1756// already compressed, we lose very little by not compressing
1757// their concatenation.)
1758//
1759// In version 3, commands that read data from the partition (i.e.
1760// move/bsdiff/imgdiff/stash) have one or more additional hashes
1761// before the range parameters, which are used to check if the
1762// command has already been completed and verify the integrity of
1763// the source data.
1764
1765Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001766 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001767 const Command commands[] = {
1768 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001769 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001770 { "free", PerformCommandFree },
1771 { "imgdiff", PerformCommandDiff },
1772 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001773 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001774 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001775 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001776 };
1777
1778 // Perform a dry run without writing to test if an update can proceed
1779 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001780 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001781}
1782
1783Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1784 const Command commands[] = {
1785 { "bsdiff", PerformCommandDiff },
1786 { "erase", PerformCommandErase },
1787 { "free", PerformCommandFree },
1788 { "imgdiff", PerformCommandDiff },
1789 { "move", PerformCommandMove },
1790 { "new", PerformCommandNew },
1791 { "stash", PerformCommandStash },
1792 { "zero", PerformCommandZero }
1793 };
1794
1795 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001796 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001797}
1798
Tao Bao0940fe12015-08-27 16:41:21 -07001799Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001800 std::vector<std::unique_ptr<Value>> args;
1801 if (!ReadValueArgs(state, 2, argv, &args)) {
1802 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001803 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001804
1805 const Value* blockdev_filename = args[0].get();
1806 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001807
1808 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001809 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1810 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001811 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001812 }
1813 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001814 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001815 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001816 }
1817
Tianjie Xuaced5d92016-10-12 10:55:04 -07001818 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001819 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001820 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1821 blockdev_filename->data.c_str(), strerror(errno));
1822 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001823 }
1824
Tao Baoc844c062016-12-28 15:15:55 -08001825 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001826
1827 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001828 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001829
Tao Bao612336d2015-08-27 16:41:21 -07001830 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001831 for (size_t i = 0; i < rs.count; ++i) {
1832 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001833 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1834 blockdev_filename->data.c_str(), strerror(errno));
1835 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001836 }
1837
Tao Bao0940fe12015-08-27 16:41:21 -07001838 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001839 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001840 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1841 blockdev_filename->data.c_str(), strerror(errno));
1842 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001843 }
1844
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001845 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001846 }
1847 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001848 uint8_t digest[SHA_DIGEST_LENGTH];
1849 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001850
Tianjie Xuaced5d92016-10-12 10:55:04 -07001851 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001852}
1853
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001854// This function checks if a device has been remounted R/W prior to an incremental
1855// OTA update. This is an common cause of update abortion. The function reads the
1856// 1st block of each partition and check for mounting time/count. It return string "t"
1857// if executes successfully and an empty string otherwise.
1858
1859Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001860 std::vector<std::unique_ptr<Value>> args;
1861 if (!ReadValueArgs(state, 1, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001862 return nullptr;
1863 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001864
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001865 const Value* arg_filename = args[0].get();
1866
1867 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001868 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001869 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001870 }
1871
Tianjie Xuaced5d92016-10-12 10:55:04 -07001872 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001873 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001874 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001875 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001876 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001877 }
1878
1879 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1880 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1881
1882 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001883 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001884 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001885 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001886 }
1887
1888 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1889 // Super block starts from block 0, offset 0x400
1890 // 0x2C: len32 Mount time
1891 // 0x30: len32 Write time
1892 // 0x34: len16 Number of mounts since the last fsck
1893 // 0x38: len16 Magic signature 0xEF53
1894
1895 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1896 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1897
1898 if (mount_count > 0) {
1899 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1900 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1901 }
1902
Tianjie Xuaced5d92016-10-12 10:55:04 -07001903 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001904}
1905
1906
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001907Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001908 std::vector<std::unique_ptr<Value>> args;
1909 if (!ReadValueArgs(state, 2, argv, &args)) {
1910 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001911 }
1912
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001913 const Value* filename = args[0].get();
1914 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001915
1916 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001917 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001918 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001919 }
1920 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001921 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001922 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001923 }
1924
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001925 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001926 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001927
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001928 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tianjie Xuaced5d92016-10-12 10:55:04 -07001929 fec::io fh(filename->data.c_str(), O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001930
1931 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001932 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001933 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001934 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001935 }
1936
1937 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001938 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001939 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001940 }
1941
1942 fec_status status;
1943
1944 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001945 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001946 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001947 }
1948
Tao Baoc844c062016-12-28 15:15:55 -08001949 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001950
1951 uint8_t buffer[BLOCKSIZE];
1952
1953 for (size_t i = 0; i < rs.count; ++i) {
1954 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1955 // Stay within the data area, libfec validates and corrects metadata
1956 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1957 continue;
1958 }
1959
1960 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001961 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001962 filename->data.c_str(), j, strerror(errno));
1963 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001964 }
1965
1966 // If we want to be able to recover from a situation where rewriting a corrected
1967 // block doesn't guarantee the same data will be returned when re-read later, we
1968 // can save a copy of corrected blocks to /cache. Note:
1969 //
1970 // 1. Maximum space required from /cache is the same as the maximum number of
1971 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1972 // this would be ~16 MiB, for example.
1973 //
1974 // 2. To find out if this block was corrupted, call fec_get_status after each
1975 // read and check if the errors field value has increased.
1976 }
1977 }
Tao Bao039f2da2016-11-22 16:29:50 -08001978 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001979 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001980}
1981
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001982void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001983 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001984 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001985 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001986 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001987 RegisterFunction("range_sha1", RangeSha1Fn);
1988}