blob: 8c0f885a12855a579d656d2417231c2016db5f86 [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
Tao Baoc0e1c462017-02-01 10:20:10 -0800243static size_t RangeSinkWrite(const uint8_t* data, size_t size, RangeSinkState* rss) {
Tao Baof7eb7602017-03-27 15:12:48 -0700244 if (rss->p_remain == 0) {
245 LOG(ERROR) << "range sink write overrun";
246 return 0;
247 }
248
249 size_t written = 0;
250 while (size > 0) {
251 size_t write_now = size;
252
253 if (rss->p_remain < write_now) {
254 write_now = rss->p_remain;
255 }
256
257 if (write_all(rss->fd, data, write_now) == -1) {
258 break;
259 }
260
261 data += write_now;
262 size -= write_now;
263
264 rss->p_remain -= write_now;
265 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700266
Tao Bao0940fe12015-08-27 16:41:21 -0700267 if (rss->p_remain == 0) {
Tao Baof7eb7602017-03-27 15:12:48 -0700268 // Move to the next block.
269 ++rss->p_block;
270 if (rss->p_block < rss->tgt.count) {
271 rss->p_remain =
272 (rss->tgt.pos[rss->p_block * 2 + 1] - rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
273
274 off64_t offset = static_cast<off64_t>(rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
275 if (!discard_blocks(rss->fd, offset, rss->p_remain)) {
276 break;
277 }
278
279 if (!check_lseek(rss->fd, offset, SEEK_SET)) {
280 break;
281 }
282
283 } else {
284 // We can't write any more; return how many bytes have been written so far.
285 break;
286 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700287 }
Tao Baof7eb7602017-03-27 15:12:48 -0700288 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700289
Tao Baof7eb7602017-03-27 15:12:48 -0700290 return written;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700291}
292
293// All of the data for all the 'new' transfers is contained in one
294// file in the update package, concatenated together in the order in
295// which transfers.list will need it. We want to stream it out of the
296// archive (it's compressed) without writing it to a temp file, but we
297// can't write each section until it's that transfer's turn to go.
298//
299// To achieve this, we expand the new data from the archive in a
300// background thread, and block that threads 'receive uncompressed
301// data' function until the main thread has reached a point where we
302// want some new data to be written. We signal the background thread
303// with the destination for the data and block the main thread,
304// waiting for the background thread to complete writing that section.
305// Then it signals the main thread to wake up and goes back to
306// blocking waiting for a transfer.
307//
308// NewThreadInfo is the struct used to pass information back and forth
309// between the two threads. When the main thread wants some data
310// written, it sets rss to the destination location and signals the
311// condition. When the background thread is done writing, it clears
312// rss and signals the condition again.
313
Tao Bao0940fe12015-08-27 16:41:21 -0700314struct NewThreadInfo {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700315 ZipArchiveHandle za;
316 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700317
318 RangeSinkState* rss;
319
320 pthread_mutex_t mu;
321 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700322};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700323
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700324static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700325 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700326
327 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700328 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700329 // data is wanted.
330 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700331 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700332 pthread_cond_wait(&nti->cv, &nti->mu);
333 }
334 pthread_mutex_unlock(&nti->mu);
335
336 // At this point nti->rss is set, and we own it. The main
337 // thread is waiting for it to disappear from nti.
Tao Baof7eb7602017-03-27 15:12:48 -0700338 size_t written = RangeSinkWrite(data, size, nti->rss);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700339 data += written;
340 size -= written;
341
Tao Bao0940fe12015-08-27 16:41:21 -0700342 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700343 // we have written all the bytes desired by this rss.
344
345 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700346 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700347 pthread_cond_broadcast(&nti->cv);
348 pthread_mutex_unlock(&nti->mu);
349 }
350 }
351
352 return true;
353}
354
355static void* unzip_new_data(void* cookie) {
Mikhail Lappo20791bd2017-03-23 21:30:36 +0100356 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700357 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700358 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700359}
360
Tao Bao612336d2015-08-27 16:41:21 -0700361static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000362 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700363 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000364
Tao Bao0940fe12015-08-27 16:41:21 -0700365 for (size_t i = 0; i < src.count; ++i) {
366 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000367 return -1;
368 }
369
Tao Bao0940fe12015-08-27 16:41:21 -0700370 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000371
Tao Bao612336d2015-08-27 16:41:21 -0700372 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000373 return -1;
374 }
375
376 p += size;
377 }
378
379 return 0;
380}
381
Tao Bao612336d2015-08-27 16:41:21 -0700382static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
383 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000384
Tao Bao0940fe12015-08-27 16:41:21 -0700385 size_t p = 0;
386 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700387 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
388 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
389 if (!discard_blocks(fd, offset, size)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000390 return -1;
391 }
392
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700393 if (!check_lseek(fd, offset, SEEK_SET)) {
394 return -1;
395 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000396
Tao Bao612336d2015-08-27 16:41:21 -0700397 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000398 return -1;
399 }
400
401 p += size;
402 }
403
404 return 0;
405}
406
Tao Baobaad2d42015-12-06 16:56:27 -0800407// Parameters for transfer list command functions
408struct CommandParameters {
409 std::vector<std::string> tokens;
410 size_t cpos;
411 const char* cmdname;
412 const char* cmdline;
413 std::string freestash;
414 std::string stashbase;
415 bool canwrite;
416 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700417 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800418 bool foundwrites;
419 bool isunresumable;
420 int version;
421 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700422 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800423 NewThreadInfo nti;
424 pthread_t thread;
425 std::vector<uint8_t> buffer;
426 uint8_t* patch_start;
427};
428
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000429// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
430// handled separately).
431static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
432 const std::vector<uint8_t>& buffer) {
433 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000434 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
435 params.tokens[0] == "imgdiff");
436
437 size_t pos = 0;
438 // Command example:
439 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
440 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
441 // [<loc_range> <stashed_blocks>]
442 if (params.tokens[0] == "move") {
443 // src_range for move starts at the 4th position.
444 if (params.tokens.size() < 5) {
445 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
446 return;
447 }
448 pos = 4;
449 } else {
450 // src_range for diff starts at the 7th position.
451 if (params.tokens.size() < 8) {
452 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
453 return;
454 }
455 pos = 7;
456 }
457
458 // Source blocks in stash only, no work to do.
459 if (params.tokens[pos] == "-") {
460 return;
461 }
462
463 RangeSet src = parse_range(params.tokens[pos++]);
464
465 RangeSet locs;
466 // If there's no stashed blocks, content in the buffer is consecutive and has the same
467 // order as the source blocks.
468 if (pos == params.tokens.size()) {
469 locs.count = 1;
470 locs.size = src.size;
471 locs.pos = { 0, src.size };
472 } else {
473 // Otherwise, the next token is the offset of the source blocks in the target range.
474 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
475 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
476 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
477 locs = parse_range(params.tokens[pos++]);
478 CHECK_EQ(src.size, locs.size);
479 CHECK_EQ(locs.pos.size() % 2, static_cast<size_t>(0));
480 }
481
482 LOG(INFO) << "printing hash in hex for " << src.size << " source blocks";
483 for (size_t i = 0; i < src.size; i++) {
484 int block_num = src.get_block(i);
485 CHECK_NE(block_num, -1);
486 int buffer_index = locs.get_block(i);
487 CHECK_NE(buffer_index, -1);
488 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
489
490 uint8_t digest[SHA_DIGEST_LENGTH];
491 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
492 std::string hexdigest = print_sha1(digest);
493 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
494 }
495}
496
497// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
498// in hex for each block.
499static void PrintHashForCorruptedStashedBlocks(const std::string& id,
500 const std::vector<uint8_t>& buffer,
501 const RangeSet& src) {
502 LOG(INFO) << "printing hash in hex for stash_id: " << id;
503 CHECK_EQ(src.size * BLOCKSIZE, buffer.size());
504
505 for (size_t i = 0; i < src.size; i++) {
506 int block_num = src.get_block(i);
507 CHECK_NE(block_num, -1);
508
509 uint8_t digest[SHA_DIGEST_LENGTH];
510 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
511 std::string hexdigest = print_sha1(digest);
512 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
513 }
514}
515
516// If the stash file doesn't exist, read the source blocks this stash contains and print the
517// SHA-1 for these blocks.
518static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
519 if (stash_map.find(id) == stash_map.end()) {
520 LOG(ERROR) << "No stash saved for id: " << id;
521 return;
522 }
523
524 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
525 const RangeSet& src = stash_map[id];
526 std::vector<uint8_t> buffer(src.size * BLOCKSIZE);
527 if (ReadBlocks(src, buffer, fd) == -1) {
528 LOG(ERROR) << "failed to read source blocks for stash: " << id;
529 return;
530 }
531 PrintHashForCorruptedStashedBlocks(id, buffer, src);
532}
533
Tao Bao612336d2015-08-27 16:41:21 -0700534static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700535 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800536 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700537 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000538
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800539 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000540
Tao Baoe6aa3322015-08-05 15:20:27 -0700541 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000542
Tao Bao0940fe12015-08-27 16:41:21 -0700543 if (hexdigest != expected) {
544 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800545 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
546 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700547 }
548 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000549 }
550
Tao Bao0940fe12015-08-27 16:41:21 -0700551 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000552}
553
Tao Bao0940fe12015-08-27 16:41:21 -0700554static std::string GetStashFileName(const std::string& base, const std::string& id,
555 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700556 if (base.empty()) {
557 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000558 }
559
Tao Baoe6aa3322015-08-05 15:20:27 -0700560 std::string fn(STASH_DIRECTORY_BASE);
561 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000562
563 return fn;
564}
565
Tao Baoec8272f2017-03-15 17:39:01 -0700566// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
567// directory and continues despite of errors. Calls the 'callback' function for each file.
568static void EnumerateStash(const std::string& dirname,
569 const std::function<void(const std::string&)>& callback) {
570 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000571
Tao Baoec8272f2017-03-15 17:39:01 -0700572 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000573
Tao Baoec8272f2017-03-15 17:39:01 -0700574 if (directory == nullptr) {
575 if (errno != ENOENT) {
576 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000577 }
Tao Bao51412212016-12-28 14:44:05 -0800578 return;
579 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700580
Tao Baoec8272f2017-03-15 17:39:01 -0700581 dirent* item;
582 while ((item = readdir(directory.get())) != nullptr) {
583 if (item->d_type != DT_REG) continue;
584 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800585 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000586}
587
588// Deletes the stash directory and all files in it. Assumes that it only
589// contains files. There is nothing we can do about unlikely, but possible
590// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700591static void DeleteFile(const std::string& fn) {
592 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000593
Tao Baoec8272f2017-03-15 17:39:01 -0700594 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000595
Tao Baoec8272f2017-03-15 17:39:01 -0700596 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
597 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
598 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000599}
600
Tao Baoe6aa3322015-08-05 15:20:27 -0700601static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700602 if (base.empty()) return;
603
604 LOG(INFO) << "deleting stash " << base;
605
606 std::string dirname = GetStashFileName(base, "", "");
607 EnumerateStash(dirname, DeleteFile);
608
609 if (rmdir(dirname.c_str()) == -1) {
610 if (errno != ENOENT && errno != ENOTDIR) {
611 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000612 }
Tao Baoec8272f2017-03-15 17:39:01 -0700613 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000614}
615
Tao Baobcf46492017-03-23 15:28:20 -0700616static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
617 std::vector<uint8_t>& buffer, bool printnoent) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700618 // In verify mode, if source range_set was saved for the given hash,
619 // check contents in the source blocks first. If the check fails,
620 // search for the stashed files on /cache as usual.
621 if (!params.canwrite) {
622 if (stash_map.find(id) != stash_map.end()) {
623 const RangeSet& src = stash_map[id];
624 allocate(src.size * BLOCKSIZE, buffer);
625
626 if (ReadBlocks(src, buffer, params.fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800627 LOG(ERROR) << "failed to read source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700628 return -1;
629 }
630 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800631 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000632 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700633 return -1;
634 }
635 return 0;
636 }
637 }
638
Tao Bao0940fe12015-08-27 16:41:21 -0700639 size_t blockcount = 0;
640
Sami Tolvanen90221202014-12-09 16:39:47 +0000641 if (!blocks) {
642 blocks = &blockcount;
643 }
644
Tao Baobcf46492017-03-23 15:28:20 -0700645 std::string fn = GetStashFileName(params.stashbase, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000646
Tao Bao0940fe12015-08-27 16:41:21 -0700647 struct stat sb;
648 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000649
650 if (res == -1) {
651 if (errno != ENOENT || printnoent) {
Tao Bao039f2da2016-11-22 16:29:50 -0800652 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000653 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000654 }
Tao Bao0940fe12015-08-27 16:41:21 -0700655 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000656 }
657
Tao Bao039f2da2016-11-22 16:29:50 -0800658 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000659
Tao Bao0940fe12015-08-27 16:41:21 -0700660 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800661 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
Tao Bao0940fe12015-08-27 16:41:21 -0700662 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000663 }
664
Elliott Hughesbcabd092016-03-22 20:19:22 -0700665 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000666 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800667 PLOG(ERROR) << "open \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700668 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000669 }
670
Tao Bao612336d2015-08-27 16:41:21 -0700671 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000672
Tao Bao612336d2015-08-27 16:41:21 -0700673 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700674 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000675 }
676
Tao Bao0940fe12015-08-27 16:41:21 -0700677 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000678
Tao Bao612336d2015-08-27 16:41:21 -0700679 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800680 LOG(ERROR) << "unexpected contents in " << fn;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000681 if (stash_map.find(id) == stash_map.end()) {
682 LOG(ERROR) << "failed to find source blocks number for stash " << id
683 << " when executing command: " << params.cmdname;
684 } else {
685 const RangeSet& src = stash_map[id];
686 PrintHashForCorruptedStashedBlocks(id, buffer, src);
687 }
Tao Baoec8272f2017-03-15 17:39:01 -0700688 DeleteFile(fn);
Tao Bao0940fe12015-08-27 16:41:21 -0700689 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000690 }
691
Tao Bao0940fe12015-08-27 16:41:21 -0700692 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000693}
694
Tao Bao612336d2015-08-27 16:41:21 -0700695static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baod2aecd42017-03-23 14:43:44 -0700696 std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700697 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700698 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000699 }
700
701 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800702 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700703 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000704 }
705
Tao Bao0940fe12015-08-27 16:41:21 -0700706 std::string fn = GetStashFileName(base, id, ".partial");
707 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000708
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100709 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700710 struct stat sb;
711 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100712
713 if (res == 0) {
714 // The file already exists and since the name is the hash of the contents,
715 // it's safe to assume the contents are identical (accidental hash collisions
716 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800717 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700718 *exists = true;
719 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100720 }
721
Tao Bao0940fe12015-08-27 16:41:21 -0700722 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100723 }
724
Tao Bao039f2da2016-11-22 16:29:50 -0800725 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000726
Tao Bao039f2da2016-11-22 16:29:50 -0800727 android::base::unique_fd fd(
728 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000729 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800730 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700731 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000732 }
733
Tianjie Xua946b9e2017-03-21 16:24:57 -0700734 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
735 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
736 return -1;
737 }
738
Sami Tolvanen90221202014-12-09 16:39:47 +0000739 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700740 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000741 }
742
Jed Estepa7b9a462015-12-15 16:04:53 -0800743 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700744 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800745 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700746 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000747 }
748
Tao Baoe6aa3322015-08-05 15:20:27 -0700749 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800750 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700751 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000752 }
753
Tao Bao0940fe12015-08-27 16:41:21 -0700754 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700755 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
756 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700757 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700758 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800759 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700760 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700761 }
762
Jed Estepa7b9a462015-12-15 16:04:53 -0800763 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700764 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800765 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700766 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700767 }
768
Tao Bao0940fe12015-08-27 16:41:21 -0700769 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000770}
771
772// Creates a directory for storing stash files and checks if the /cache partition
773// hash enough space for the expected amount of blocks we need to store. Returns
774// >0 if we created the directory, zero if it existed already, and <0 of failure.
775
Tao Bao51412212016-12-28 14:44:05 -0800776static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
777 std::string& base) {
778 if (blockdev.empty()) {
779 return -1;
780 }
781
782 // Stash directory should be different for each partition to avoid conflicts
783 // when updating multiple partitions at the same time, so we use the hash of
784 // the block device name as the base directory
785 uint8_t digest[SHA_DIGEST_LENGTH];
786 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
787 base = print_sha1(digest);
788
789 std::string dirname = GetStashFileName(base, "", "");
790 struct stat sb;
791 int res = stat(dirname.c_str(), &sb);
792 size_t max_stash_size = maxblocks * BLOCKSIZE;
793
794 if (res == -1 && errno != ENOENT) {
795 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
796 strerror(errno));
797 return -1;
798 } else if (res != 0) {
799 LOG(INFO) << "creating stash " << dirname;
800 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
801
802 if (res != 0) {
803 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
804 strerror(errno));
805 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000806 }
807
Tianjie Xua946b9e2017-03-21 16:24:57 -0700808 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
809 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s\n", dirname.c_str(),
810 strerror(errno));
811 return -1;
812 }
813
Tao Bao51412212016-12-28 14:44:05 -0800814 if (CacheSizeCheck(max_stash_size) != 0) {
815 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
816 max_stash_size);
817 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000818 }
819
Tao Bao51412212016-12-28 14:44:05 -0800820 return 1; // Created directory
821 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000822
Tao Bao51412212016-12-28 14:44:05 -0800823 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000824
Tao Baoec8272f2017-03-15 17:39:01 -0700825 // If the directory already exists, calculate the space already allocated to stash files and check
826 // if there's enough for all required blocks. Delete any partially completed stash files first.
827 EnumerateStash(dirname, [](const std::string& fn) {
828 if (android::base::EndsWith(fn, ".partial")) {
829 DeleteFile(fn);
830 }
831 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000832
Tao Bao51412212016-12-28 14:44:05 -0800833 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700834 EnumerateStash(dirname, [&existing](const std::string& fn) {
835 if (fn.empty()) return;
836 struct stat sb;
837 if (stat(fn.c_str(), &sb) == -1) {
838 PLOG(ERROR) << "stat \"" << fn << "\" failed";
839 return;
840 }
841 existing += static_cast<size_t>(sb.st_size);
842 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000843
Tao Bao51412212016-12-28 14:44:05 -0800844 if (max_stash_size > existing) {
845 size_t needed = max_stash_size - existing;
846 if (CacheSizeCheck(needed) != 0) {
847 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
848 needed);
849 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000850 }
Tao Bao51412212016-12-28 14:44:05 -0800851 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000852
Tao Bao51412212016-12-28 14:44:05 -0800853 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000854}
855
Tao Baobaad2d42015-12-06 16:56:27 -0800856static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700857 if (base.empty() || id.empty()) {
858 return -1;
859 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000860
Tao Baoec8272f2017-03-15 17:39:01 -0700861 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000862
Tao Baoec8272f2017-03-15 17:39:01 -0700863 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700864}
865
Tao Bao612336d2015-08-27 16:41:21 -0700866static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
867 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700868 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700869 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700870 // may be the same buffer.
871
Tao Bao612336d2015-08-27 16:41:21 -0700872 const uint8_t* from = source.data();
873 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700874 size_t start = locs.size;
875 for (int i = locs.count-1; i >= 0; --i) {
876 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700877 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700878 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700879 blocks * BLOCKSIZE);
880 }
881}
882
Tao Baod2aecd42017-03-23 14:43:44 -0700883/**
884 * We expect to parse the remainder of the parameter tokens as one of:
885 *
886 * <src_block_count> <src_range>
887 * (loads data from source image only)
888 *
889 * <src_block_count> - <[stash_id:stash_range] ...>
890 * (loads data from stashes only)
891 *
892 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
893 * (loads data from both source image and stashes)
894 *
895 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
896 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
897 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
898 * LoadStash.
899 */
900static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
901 bool* overlap) {
902 CHECK(src_blocks != nullptr);
903 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700904
Tao Baod2aecd42017-03-23 14:43:44 -0700905 // <src_block_count>
906 const std::string& token = params.tokens[params.cpos++];
907 if (!android::base::ParseUint(token, src_blocks)) {
908 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
909 return -1;
910 }
Tao Baobaad2d42015-12-06 16:56:27 -0800911
Tao Baod2aecd42017-03-23 14:43:44 -0700912 allocate(*src_blocks * BLOCKSIZE, params.buffer);
913
914 // "-" or <src_range> [<src_loc>]
915 if (params.tokens[params.cpos] == "-") {
916 // no source ranges, only stashes
917 params.cpos++;
918 } else {
919 RangeSet src = parse_range(params.tokens[params.cpos++]);
920 *overlap = range_overlaps(src, tgt);
921
922 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
923 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -0800924 }
925
Tao Baod2aecd42017-03-23 14:43:44 -0700926 if (params.cpos >= params.tokens.size()) {
927 // no stashes, only source range
928 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -0800929 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700930
Tao Baod2aecd42017-03-23 14:43:44 -0700931 RangeSet locs = parse_range(params.tokens[params.cpos++]);
932 MoveRange(params.buffer, locs, params.buffer);
933 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700934
Tao Baod2aecd42017-03-23 14:43:44 -0700935 // <[stash_id:stash_range]>
936 while (params.cpos < params.tokens.size()) {
937 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
938 // in the source block that stashed data should go.
939 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
940 if (tokens.size() != 2) {
941 LOG(ERROR) << "invalid parameter";
942 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700943 }
944
Tao Baod2aecd42017-03-23 14:43:44 -0700945 std::vector<uint8_t> stash;
946 if (LoadStash(params, tokens[0], false, nullptr, stash, true) == -1) {
947 // These source blocks will fail verification if used later, but we
948 // will let the caller decide if this is a fatal failure
949 LOG(ERROR) << "failed to load stash " << tokens[0];
950 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +0000951 }
952
Tao Baod2aecd42017-03-23 14:43:44 -0700953 RangeSet locs = parse_range(tokens[1]);
954 MoveRange(params.buffer, locs, stash);
955 }
956
957 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000958}
959
Tao Bao33567772017-03-13 14:57:34 -0700960/**
961 * Do a source/target load for move/bsdiff/imgdiff in version 3.
962 *
963 * We expect to parse the remainder of the parameter tokens as one of:
964 *
965 * <tgt_range> <src_block_count> <src_range>
966 * (loads data from source image only)
967 *
968 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
969 * (loads data from stashes only)
970 *
971 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
972 * (loads data from both source image and stashes)
973 *
Tao Baod2aecd42017-03-23 14:43:44 -0700974 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
975 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -0700976 * verification fails in a way that the update cannot be resumed anymore.
977 *
978 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
979 * the return value is -1 and the command should be aborted.
980 *
981 * If the return value is 1, the command has already been completed according to the contents of the
982 * target blocks, and should not be performed again.
983 *
984 * If the return value is 0, source blocks have expected content and the command can be performed.
985 */
Tao Baod2aecd42017-03-23 14:43:44 -0700986static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
987 bool onehash, bool* overlap) {
988 CHECK(src_blocks != nullptr);
989 CHECK(overlap != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000990
Tao Baod2aecd42017-03-23 14:43:44 -0700991 if (params.cpos >= params.tokens.size()) {
992 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -0700993 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -0700994 }
995
996 std::string srchash = params.tokens[params.cpos++];
997 std::string tgthash;
998
999 if (onehash) {
1000 tgthash = srchash;
1001 } else {
1002 if (params.cpos >= params.tokens.size()) {
1003 LOG(ERROR) << "missing target hash";
1004 return -1;
1005 }
1006 tgthash = params.tokens[params.cpos++];
1007 }
1008
1009 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1010 // "-"/<src_range>.
1011 if (params.cpos + 2 >= params.tokens.size()) {
1012 LOG(ERROR) << "invalid parameters";
1013 return -1;
1014 }
1015
1016 // <tgt_range>
1017 tgt = parse_range(params.tokens[params.cpos++]);
1018
1019 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
1020 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
1021 return -1;
1022 }
1023
1024 // Return now if target blocks already have expected content.
1025 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
1026 return 1;
1027 }
1028
1029 // Load source blocks.
1030 if (LoadSourceBlocks(params, tgt, src_blocks, overlap) == -1) {
1031 return -1;
1032 }
1033
1034 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
1035 // If source and target blocks overlap, stash the source blocks so we can
1036 // resume from possible write errors. In verify mode, we can skip stashing
1037 // because the source blocks won't be overwritten.
1038 if (*overlap && params.canwrite) {
1039 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1040
1041 bool stash_exists = false;
1042 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1043 &stash_exists) != 0) {
1044 LOG(ERROR) << "failed to stash overlapping source blocks";
1045 return -1;
1046 }
1047
1048 params.stashed += *src_blocks;
1049 // Can be deleted when the write has completed.
1050 if (!stash_exists) {
1051 params.freestash = srchash;
1052 }
1053 }
1054
1055 // Source blocks have expected content, command can proceed.
1056 return 0;
1057 }
1058
1059 if (*overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
1060 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1061 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1062 // command.
1063 return 0;
1064 }
1065
1066 // Valid source data not available, update cannot be resumed.
1067 LOG(ERROR) << "partition has unexpected contents";
1068 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1069
1070 params.isunresumable = true;
1071
1072 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001073}
1074
Tao Bao0940fe12015-08-27 16:41:21 -07001075static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001076 size_t blocks = 0;
1077 bool overlap = false;
1078 RangeSet tgt;
Tao Baod2aecd42017-03-23 14:43:44 -07001079 int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001080
Tao Bao33567772017-03-13 14:57:34 -07001081 if (status == -1) {
1082 LOG(ERROR) << "failed to read blocks for move";
1083 return -1;
1084 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001085
Tao Bao33567772017-03-13 14:57:34 -07001086 if (status == 0) {
1087 params.foundwrites = true;
1088 } else if (params.foundwrites) {
1089 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1090 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001091
Tao Bao33567772017-03-13 14:57:34 -07001092 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001093 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001094 LOG(INFO) << " moving " << blocks << " blocks";
1095
1096 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1097 return -1;
1098 }
1099 } else {
1100 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001101 }
Tao Bao33567772017-03-13 14:57:34 -07001102 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001103
Tao Bao33567772017-03-13 14:57:34 -07001104 if (!params.freestash.empty()) {
1105 FreeStash(params.stashbase, params.freestash);
1106 params.freestash.clear();
1107 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001108
Tao Bao33567772017-03-13 14:57:34 -07001109 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001110
Tao Bao33567772017-03-13 14:57:34 -07001111 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001112}
1113
Tao Bao0940fe12015-08-27 16:41:21 -07001114static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001115 // <stash_id> <src_range>
1116 if (params.cpos + 1 >= params.tokens.size()) {
1117 LOG(ERROR) << "missing id and/or src range fields in stash command";
1118 return -1;
1119 }
1120
1121 const std::string& id = params.tokens[params.cpos++];
1122 size_t blocks = 0;
1123 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1124 // Stash file already exists and has expected contents. Do not read from source again, as the
1125 // source may have been already overwritten during a previous attempt.
1126 return 0;
1127 }
1128
1129 RangeSet src = parse_range(params.tokens[params.cpos++]);
1130
1131 allocate(src.size * BLOCKSIZE, params.buffer);
1132 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1133 return -1;
1134 }
1135 blocks = src.size;
1136 stash_map[id] = src;
1137
1138 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1139 // Source blocks have unexpected contents. If we actually need this data later, this is an
1140 // unrecoverable error. However, the command that uses the data may have already completed
1141 // previously, so the possible failure will occur during source block verification.
1142 LOG(ERROR) << "failed to load source blocks for stash " << id;
1143 return 0;
1144 }
1145
1146 // In verify mode, we don't need to stash any blocks.
1147 if (!params.canwrite) {
1148 return 0;
1149 }
1150
1151 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
1152 params.stashed += blocks;
1153 return WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001154}
1155
Tao Bao0940fe12015-08-27 16:41:21 -07001156static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001157 // <stash_id>
1158 if (params.cpos >= params.tokens.size()) {
1159 LOG(ERROR) << "missing stash id in free command";
1160 return -1;
1161 }
Tao Baobaad2d42015-12-06 16:56:27 -08001162
Tao Baobcf46492017-03-23 15:28:20 -07001163 const std::string& id = params.tokens[params.cpos++];
1164 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001165
Tao Baobcf46492017-03-23 15:28:20 -07001166 if (params.createdstash || params.canwrite) {
1167 return FreeStash(params.stashbase, id);
1168 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001169
Tao Baobcf46492017-03-23 15:28:20 -07001170 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001171}
1172
Tao Bao0940fe12015-08-27 16:41:21 -07001173static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001174
Tao Baobaad2d42015-12-06 16:56:27 -08001175 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001176 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001177 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001178 }
1179
Tao Baoc844c062016-12-28 15:15:55 -08001180 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001181
Tao Bao039f2da2016-11-22 16:29:50 -08001182 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001183
Tao Bao612336d2015-08-27 16:41:21 -07001184 allocate(BLOCKSIZE, params.buffer);
1185 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001186
Tao Bao0940fe12015-08-27 16:41:21 -07001187 if (params.canwrite) {
1188 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001189 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1190 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1191 if (!discard_blocks(params.fd, offset, size)) {
1192 return -1;
1193 }
1194
1195 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001196 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001197 }
1198
Tao Bao0940fe12015-08-27 16:41:21 -07001199 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1200 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1201 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001202 }
1203 }
1204 }
1205 }
1206
Tao Bao0940fe12015-08-27 16:41:21 -07001207 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001208 // Update only for the zero command, as the erase command will call
1209 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001210 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001211 }
1212
Tao Bao0940fe12015-08-27 16:41:21 -07001213 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001214}
1215
Tao Bao0940fe12015-08-27 16:41:21 -07001216static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001217
Tao Baobaad2d42015-12-06 16:56:27 -08001218 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001219 LOG(ERROR) << "missing target blocks for new";
Tao Bao0940fe12015-08-27 16:41:21 -07001220 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001221 }
1222
Tao Baoc844c062016-12-28 15:15:55 -08001223 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001224
Tao Bao0940fe12015-08-27 16:41:21 -07001225 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001226 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
Sami Tolvanen90221202014-12-09 16:39:47 +00001227
Tao Bao0940fe12015-08-27 16:41:21 -07001228 RangeSinkState rss(tgt);
1229 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001230 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001231 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001232
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001233 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1234 if (!discard_blocks(params.fd, offset, tgt.size * BLOCKSIZE)) {
1235 return -1;
1236 }
1237
1238 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001239 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001240 }
1241
Tao Bao0940fe12015-08-27 16:41:21 -07001242 pthread_mutex_lock(&params.nti.mu);
1243 params.nti.rss = &rss;
1244 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001245
Tao Bao0940fe12015-08-27 16:41:21 -07001246 while (params.nti.rss) {
1247 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001248 }
1249
Tao Bao0940fe12015-08-27 16:41:21 -07001250 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001251 }
1252
Tao Bao0940fe12015-08-27 16:41:21 -07001253 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001254
Tao Bao0940fe12015-08-27 16:41:21 -07001255 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001256}
1257
Tao Bao0940fe12015-08-27 16:41:21 -07001258static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001259 // <offset> <length>
1260 if (params.cpos + 1 >= params.tokens.size()) {
1261 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1262 return -1;
1263 }
Tao Bao0940fe12015-08-27 16:41:21 -07001264
Tao Baoc0e1c462017-02-01 10:20:10 -08001265 size_t offset;
1266 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1267 LOG(ERROR) << "invalid patch offset";
1268 return -1;
1269 }
Tao Bao0940fe12015-08-27 16:41:21 -07001270
Tao Baoc0e1c462017-02-01 10:20:10 -08001271 size_t len;
1272 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1273 LOG(ERROR) << "invalid patch len";
1274 return -1;
1275 }
Tao Bao0940fe12015-08-27 16:41:21 -07001276
Tao Baoc0e1c462017-02-01 10:20:10 -08001277 RangeSet tgt;
1278 size_t blocks = 0;
1279 bool overlap = false;
1280 int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
Tao Bao0940fe12015-08-27 16:41:21 -07001281
Tao Baoc0e1c462017-02-01 10:20:10 -08001282 if (status == -1) {
1283 LOG(ERROR) << "failed to read blocks for diff";
1284 return -1;
1285 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001286
Tao Baoc0e1c462017-02-01 10:20:10 -08001287 if (status == 0) {
1288 params.foundwrites = true;
1289 } else if (params.foundwrites) {
1290 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1291 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001292
Tao Baoc0e1c462017-02-01 10:20:10 -08001293 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001294 if (status == 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001295 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
1296 Value patch_value(
1297 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
1298 RangeSinkState rss(tgt);
1299 rss.fd = params.fd;
1300 rss.p_block = 0;
1301 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001302
Tao Baoc0e1c462017-02-01 10:20:10 -08001303 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1304 if (!discard_blocks(params.fd, offset, rss.p_remain)) {
1305 return -1;
1306 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001307
Tao Baoc0e1c462017-02-01 10:20:10 -08001308 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1309 return -1;
1310 }
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001311
Tao Baoc0e1c462017-02-01 10:20:10 -08001312 if (params.cmdname[0] == 'i') { // imgdiff
1313 if (ApplyImagePatch(
1314 params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1315 std::bind(&RangeSinkWrite, std::placeholders::_1, std::placeholders::_2, &rss),
1316 nullptr, nullptr) != 0) {
1317 LOG(ERROR) << "Failed to apply image patch.";
1318 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001319 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001320 } else {
1321 if (ApplyBSDiffPatch(
1322 params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1323 std::bind(&RangeSinkWrite, std::placeholders::_1, std::placeholders::_2, &rss),
1324 nullptr) != 0) {
1325 LOG(ERROR) << "Failed to apply bsdiff patch.";
1326 return -1;
1327 }
1328 }
1329
1330 // We expect the output of the patcher to fill the tgt ranges exactly.
1331 if (rss.p_block != tgt.count || rss.p_remain != 0) {
1332 LOG(ERROR) << "range sink underrun?";
1333 }
1334 } else {
1335 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size << " ["
1336 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001337 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001338 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001339
Tao Baoc0e1c462017-02-01 10:20:10 -08001340 if (!params.freestash.empty()) {
1341 FreeStash(params.stashbase, params.freestash);
1342 params.freestash.clear();
1343 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001344
Tao Baoc0e1c462017-02-01 10:20:10 -08001345 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001346
Tao Baoc0e1c462017-02-01 10:20:10 -08001347 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001348}
1349
Tao Bao0940fe12015-08-27 16:41:21 -07001350static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001351 if (DEBUG_ERASE) {
1352 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001353 }
1354
Tao Bao0940fe12015-08-27 16:41:21 -07001355 struct stat sb;
1356 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001357 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001358 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001359 }
1360
Tao Bao0940fe12015-08-27 16:41:21 -07001361 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001362 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001363 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001364 }
1365
Tao Baobaad2d42015-12-06 16:56:27 -08001366 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001367 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001368 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001369 }
1370
Tao Baoc844c062016-12-28 15:15:55 -08001371 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001372
Tao Bao0940fe12015-08-27 16:41:21 -07001373 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001374 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001375
Tao Bao0940fe12015-08-27 16:41:21 -07001376 for (size_t i = 0; i < tgt.count; ++i) {
1377 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001378 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001379 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001380 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001381 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001382
Tao Bao0940fe12015-08-27 16:41:21 -07001383 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001384 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001385 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001386 }
1387 }
1388 }
1389
Tao Bao0940fe12015-08-27 16:41:21 -07001390 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001391}
1392
1393// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001394typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001395
Tao Bao612336d2015-08-27 16:41:21 -07001396struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001397 const char* name;
1398 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001399};
Sami Tolvanen90221202014-12-09 16:39:47 +00001400
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001401// args:
1402// - block device (or file) to modify in-place
1403// - transfer list (blob)
1404// - new data stream (filename within package.zip)
1405// - patch stream (filename within package.zip, must be uncompressed)
1406
Tianjie Xuc4447322017-03-06 14:44:59 -08001407static Value* PerformBlockImageUpdate(const char* name, State* state,
1408 const std::vector<std::unique_ptr<Expr>>& argv,
1409 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001410 CommandParameters params = {};
1411 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001412
Tao Bao33567772017-03-13 14:57:34 -07001413 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1414 if (state->is_retry) {
1415 is_retry = true;
1416 LOG(INFO) << "This update is a retry.";
1417 }
1418 if (argv.size() != 4) {
1419 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1420 argv.size());
1421 return StringValue("");
1422 }
1423
1424 std::vector<std::unique_ptr<Value>> args;
1425 if (!ReadValueArgs(state, argv, &args)) {
1426 return nullptr;
1427 }
1428
1429 const Value* blockdev_filename = args[0].get();
1430 const Value* transfer_list_value = args[1].get();
1431 const Value* new_data_fn = args[2].get();
1432 const Value* patch_data_fn = args[3].get();
1433
1434 if (blockdev_filename->type != VAL_STRING) {
1435 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1436 return StringValue("");
1437 }
1438 if (transfer_list_value->type != VAL_BLOB) {
1439 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1440 return StringValue("");
1441 }
1442 if (new_data_fn->type != VAL_STRING) {
1443 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1444 return StringValue("");
1445 }
1446 if (patch_data_fn->type != VAL_STRING) {
1447 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1448 return StringValue("");
1449 }
1450
1451 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1452 if (ui == nullptr) {
1453 return StringValue("");
1454 }
1455
1456 FILE* cmd_pipe = ui->cmd_pipe;
1457 ZipArchiveHandle za = ui->package_zip;
1458
1459 if (cmd_pipe == nullptr || za == nullptr) {
1460 return StringValue("");
1461 }
1462
1463 ZipString path_data(patch_data_fn->data.c_str());
1464 ZipEntry patch_entry;
1465 if (FindEntry(za, path_data, &patch_entry) != 0) {
1466 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1467 return StringValue("");
1468 }
1469
1470 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1471 ZipString new_data(new_data_fn->data.c_str());
1472 ZipEntry new_entry;
1473 if (FindEntry(za, new_data, &new_entry) != 0) {
1474 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1475 return StringValue("");
1476 }
1477
1478 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1479 if (params.fd == -1) {
1480 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1481 return StringValue("");
1482 }
1483
1484 if (params.canwrite) {
1485 params.nti.za = za;
1486 params.nti.entry = new_entry;
1487
1488 pthread_mutex_init(&params.nti.mu, nullptr);
1489 pthread_cond_init(&params.nti.cv, nullptr);
1490 pthread_attr_t attr;
1491 pthread_attr_init(&attr);
1492 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1493
1494 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1495 if (error != 0) {
1496 PLOG(ERROR) << "pthread_create failed";
1497 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001498 }
Tao Bao33567772017-03-13 14:57:34 -07001499 }
1500
1501 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1502 if (lines.size() < 2) {
1503 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1504 lines.size());
1505 return StringValue("");
1506 }
1507
1508 // First line in transfer list is the version number.
1509 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1510 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1511 return StringValue("");
1512 }
1513
1514 LOG(INFO) << "blockimg version is " << params.version;
1515
1516 // Second line in transfer list is the total number of blocks we expect to write.
1517 size_t total_blocks;
1518 if (!android::base::ParseUint(lines[1], &total_blocks)) {
1519 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
1520 return StringValue("");
1521 }
1522
1523 if (total_blocks == 0) {
1524 return StringValue("t");
1525 }
1526
1527 size_t start = 2;
1528 if (lines.size() < 4) {
1529 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1530 lines.size());
1531 return StringValue("");
1532 }
1533
1534 // Third line is how many stash entries are needed simultaneously.
1535 LOG(INFO) << "maximum stash entries " << lines[2];
1536
1537 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1538 size_t stash_max_blocks;
1539 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
1540 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1541 lines[3].c_str());
1542 return StringValue("");
1543 }
1544
1545 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
1546 if (res == -1) {
1547 return StringValue("");
1548 }
1549
1550 params.createdstash = res;
1551
1552 start += 2;
1553
1554 // Build a map of the available commands
1555 std::unordered_map<std::string, const Command*> cmd_map;
1556 for (size_t i = 0; i < cmdcount; ++i) {
1557 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1558 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
1559 return StringValue(strdup(""));
1560 }
1561 cmd_map[commands[i].name] = &commands[i];
1562 }
1563
1564 int rc = -1;
1565
1566 // Subsequent lines are all individual transfer commands
1567 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1568 const std::string& line(*it);
1569 if (line.empty()) continue;
1570
1571 params.tokens = android::base::Split(line, " ");
1572 params.cpos = 0;
1573 params.cmdname = params.tokens[params.cpos++].c_str();
1574 params.cmdline = line.c_str();
1575
1576 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1577 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1578 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001579 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001580
Tao Bao33567772017-03-13 14:57:34 -07001581 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001582
Tao Bao33567772017-03-13 14:57:34 -07001583 if (cmd->f != nullptr && cmd->f(params) == -1) {
1584 LOG(ERROR) << "failed to execute command [" << line << "]";
1585 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001586 }
1587
Sami Tolvanen90221202014-12-09 16:39:47 +00001588 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001589 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001590 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001591 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001592 goto pbiudone;
1593 }
1594 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1595 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001596 }
Tao Bao33567772017-03-13 14:57:34 -07001597 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001598
Tao Bao33567772017-03-13 14:57:34 -07001599 if (params.canwrite) {
1600 pthread_join(params.thread, nullptr);
1601
1602 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1603 LOG(INFO) << "stashed " << params.stashed << " blocks";
1604 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1605
1606 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1607 if (partition != nullptr && *(partition + 1) != 0) {
1608 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1609 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1610 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001611 }
Tao Bao33567772017-03-13 14:57:34 -07001612 // Delete stash only after successfully completing the update, as it may contain blocks needed
1613 // to complete the update later.
1614 DeleteStash(params.stashbase);
1615 } else {
1616 LOG(INFO) << "verified partition contents; update may be resumed";
1617 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001618
Tao Bao33567772017-03-13 14:57:34 -07001619 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001620
Tao Bao33567772017-03-13 14:57:34 -07001621pbiudone:
1622 if (ota_fsync(params.fd) == -1) {
1623 failure_type = kFsyncFailure;
1624 PLOG(ERROR) << "fsync failed";
1625 }
1626 // params.fd will be automatically closed because it's a unique_fd.
1627
1628 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1629 // created the stash.
1630 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1631 DeleteStash(params.stashbase);
1632 }
1633
1634 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1635 state->cause_code = failure_type;
1636 }
1637
1638 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001639}
1640
Tao Bao33567772017-03-13 14:57:34 -07001641/**
1642 * The transfer list is a text file containing commands to transfer data from one place to another
1643 * on the target partition. We parse it and execute the commands in order:
1644 *
1645 * zero [rangeset]
1646 * - Fill the indicated blocks with zeros.
1647 *
1648 * new [rangeset]
1649 * - Fill the blocks with data read from the new_data file.
1650 *
1651 * erase [rangeset]
1652 * - Mark the given blocks as empty.
1653 *
1654 * move <...>
1655 * bsdiff <patchstart> <patchlen> <...>
1656 * imgdiff <patchstart> <patchlen> <...>
1657 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1658 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1659 *
1660 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1661 *
1662 * stash <stash_id> <src_range>
1663 * - Load the given source range and stash the data in the given slot of the stash table.
1664 *
1665 * free <stash_id>
1666 * - Free the given stash data.
1667 *
1668 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1669 * a patch or move) after it has been written.
1670 *
1671 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1672 * in a move/bsdiff/imgdiff command.
1673 *
1674 * Within one command the source and target ranges may overlap so in general we need to read the
1675 * entire source into memory before writing anything to the target blocks.
1676 *
1677 * All the patch data is concatenated into one patch_data file in the update package. It must be
1678 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1679 * already compressed, we lose very little by not compressing their concatenation.)
1680 *
1681 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1682 * additional hashes before the range parameters, which are used to check if the command has already
1683 * been completed and verify the integrity of the source data.
1684 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001685Value* BlockImageVerifyFn(const char* name, State* state,
1686 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001687 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001688 const Command commands[] = {
1689 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001690 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001691 { "free", PerformCommandFree },
1692 { "imgdiff", PerformCommandDiff },
1693 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001694 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001695 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001696 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001697 };
1698
1699 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001700 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001701 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001702}
1703
Tianjie Xuc4447322017-03-06 14:44:59 -08001704Value* BlockImageUpdateFn(const char* name, State* state,
1705 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001706 const Command commands[] = {
1707 { "bsdiff", PerformCommandDiff },
1708 { "erase", PerformCommandErase },
1709 { "free", PerformCommandFree },
1710 { "imgdiff", PerformCommandDiff },
1711 { "move", PerformCommandMove },
1712 { "new", PerformCommandNew },
1713 { "stash", PerformCommandStash },
1714 { "zero", PerformCommandZero }
1715 };
1716
Tianjie Xuc4447322017-03-06 14:44:59 -08001717 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001718 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001719}
1720
Tianjie Xuc4447322017-03-06 14:44:59 -08001721Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1722 if (argv.size() != 2) {
1723 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu",
1724 argv.size());
1725 return StringValue("");
1726 }
1727
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001728 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001729 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001730 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001731 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001732
1733 const Value* blockdev_filename = args[0].get();
1734 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001735
1736 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001737 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1738 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001739 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001740 }
1741 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001742 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001743 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001744 }
1745
Tianjie Xuaced5d92016-10-12 10:55:04 -07001746 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001747 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001748 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1749 blockdev_filename->data.c_str(), strerror(errno));
1750 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001751 }
1752
Tao Baoc844c062016-12-28 15:15:55 -08001753 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001754
1755 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001756 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001757
Tao Bao612336d2015-08-27 16:41:21 -07001758 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001759 for (size_t i = 0; i < rs.count; ++i) {
1760 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001761 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1762 blockdev_filename->data.c_str(), strerror(errno));
1763 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001764 }
1765
Tao Bao0940fe12015-08-27 16:41:21 -07001766 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001767 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001768 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1769 blockdev_filename->data.c_str(), strerror(errno));
1770 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001771 }
1772
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001773 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001774 }
1775 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001776 uint8_t digest[SHA_DIGEST_LENGTH];
1777 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001778
Tianjie Xuaced5d92016-10-12 10:55:04 -07001779 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001780}
1781
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001782// This function checks if a device has been remounted R/W prior to an incremental
1783// OTA update. This is an common cause of update abortion. The function reads the
1784// 1st block of each partition and check for mounting time/count. It return string "t"
1785// if executes successfully and an empty string otherwise.
1786
Tianjie Xuc4447322017-03-06 14:44:59 -08001787Value* CheckFirstBlockFn(const char* name, State* state,
1788 const std::vector<std::unique_ptr<Expr>>& argv) {
1789 if (argv.size() != 1) {
1790 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1791 argv.size());
1792 return StringValue("");
1793 }
1794
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001795 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001796 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001797 return nullptr;
1798 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001799
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001800 const Value* arg_filename = args[0].get();
1801
1802 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001803 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001804 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001805 }
1806
Tianjie Xuaced5d92016-10-12 10:55:04 -07001807 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001808 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001809 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001810 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001811 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001812 }
1813
1814 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1815 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1816
1817 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001818 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001819 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001820 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001821 }
1822
1823 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1824 // Super block starts from block 0, offset 0x400
1825 // 0x2C: len32 Mount time
1826 // 0x30: len32 Write time
1827 // 0x34: len16 Number of mounts since the last fsck
1828 // 0x38: len16 Magic signature 0xEF53
1829
1830 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1831 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1832
1833 if (mount_count > 0) {
1834 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1835 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1836 }
1837
Tianjie Xuaced5d92016-10-12 10:55:04 -07001838 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001839}
1840
1841
Tianjie Xuc4447322017-03-06 14:44:59 -08001842Value* BlockImageRecoverFn(const char* name, State* state,
1843 const std::vector<std::unique_ptr<Expr>>& argv) {
1844 if (argv.size() != 2) {
1845 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
1846 argv.size());
1847 return StringValue("");
1848 }
1849
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001850 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001851 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001852 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001853 }
1854
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001855 const Value* filename = args[0].get();
1856 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001857
1858 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001859 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001860 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001861 }
1862 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001863 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001864 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001865 }
1866
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001867 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001868 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001869
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001870 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tao Baod2aecd42017-03-23 14:43:44 -07001871 fec::io fh(filename->data, O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001872
1873 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001874 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001875 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001876 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001877 }
1878
1879 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001880 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001881 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001882 }
1883
1884 fec_status status;
1885
1886 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001887 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001888 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001889 }
1890
Tao Baoc844c062016-12-28 15:15:55 -08001891 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001892
1893 uint8_t buffer[BLOCKSIZE];
1894
1895 for (size_t i = 0; i < rs.count; ++i) {
1896 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1897 // Stay within the data area, libfec validates and corrects metadata
1898 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1899 continue;
1900 }
1901
1902 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001903 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001904 filename->data.c_str(), j, strerror(errno));
1905 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001906 }
1907
1908 // If we want to be able to recover from a situation where rewriting a corrected
1909 // block doesn't guarantee the same data will be returned when re-read later, we
1910 // can save a copy of corrected blocks to /cache. Note:
1911 //
1912 // 1. Maximum space required from /cache is the same as the maximum number of
1913 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1914 // this would be ~16 MiB, for example.
1915 //
1916 // 2. To find out if this block was corrupted, call fec_get_status after each
1917 // read and check if the errors field value has increased.
1918 }
1919 }
Tao Bao039f2da2016-11-22 16:29:50 -08001920 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001921 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001922}
1923
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001924void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001925 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001926 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001927 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001928 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001929 RegisterFunction("range_sha1", RangeSha1Fn);
1930}