blob: 4409cbefe102dc16f113f317a79025e3145a1489 [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 Bao0bbc7642017-03-29 23:57:47 -070021#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000028#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070029#include <sys/types.h>
30#include <sys/wait.h>
31#include <sys/ioctl.h>
32#include <time.h>
33#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010034#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070035
Tao Baoec8272f2017-03-15 17:39:01 -070036#include <functional>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070039#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070040#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070041
Tao Bao039f2da2016-11-22 16:29:50 -080042#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080043#include <android-base/parseint.h>
44#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070045#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080046#include <applypatch/applypatch.h>
47#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070048#include <private/android_filesystem_config.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070049#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070050
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070051#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070052#include "error_code.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070053#include "updater/install.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080054#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070055#include "print_sha1.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070056#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070057
Sami Tolvanene82fa182015-06-10 15:58:12 +000058// Set this to 0 to interpret 'erase' transfers to mean do a
59// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
60// erase to mean fill the region with zeroes.
61#define DEBUG_ERASE 0
62
Tao Bao51412212016-12-28 14:44:05 -080063static constexpr size_t BLOCKSIZE = 4096;
64static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
65static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
66static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000067
Tao Bao0940fe12015-08-27 16:41:21 -070068struct RangeSet {
Tao Baoc844c062016-12-28 15:15:55 -080069 size_t count; // Limit is INT_MAX.
70 size_t size;
71 std::vector<size_t> pos; // Actual limit is INT_MAX.
Tianjie Xu2cd36ba2017-03-15 23:52:46 +000072
73 // Get the block number for the ith(starting from 0) block in the range set.
74 int get_block(size_t idx) const {
75 if (idx >= size) {
76 LOG(ERROR) << "index: " << idx << " is greater than range set size: " << size;
77 return -1;
78 }
79 for (size_t i = 0; i < pos.size(); i += 2) {
80 if (idx < pos[i + 1] - pos[i]) {
81 return pos[i] + idx;
82 }
83 idx -= (pos[i + 1] - pos[i]);
84 }
85 return -1;
86 }
Tao Bao0940fe12015-08-27 16:41:21 -070087};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070088
Tianjie Xu16255832016-04-30 11:49:59 -070089static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070090static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070091static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070092
Tao Baoc844c062016-12-28 15:15:55 -080093static RangeSet parse_range(const std::string& range_text) {
94 RangeSet rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010095
Tao Baoc844c062016-12-28 15:15:55 -080096 std::vector<std::string> pieces = android::base::Split(range_text, ",");
97 if (pieces.size() < 3) {
98 goto err;
99 }
100
101 size_t num;
102 if (!android::base::ParseUint(pieces[0], &num, static_cast<size_t>(INT_MAX))) {
103 goto err;
104 }
105
106 if (num == 0 || num % 2) {
107 goto err; // must be even
108 } else if (num != pieces.size() - 1) {
109 goto err;
110 }
111
112 rs.pos.resize(num);
113 rs.count = num / 2;
114 rs.size = 0;
115
116 for (size_t i = 0; i < num; i += 2) {
117 if (!android::base::ParseUint(pieces[i + 1], &rs.pos[i], static_cast<size_t>(INT_MAX))) {
118 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100119 }
120
Tao Baoc844c062016-12-28 15:15:55 -0800121 if (!android::base::ParseUint(pieces[i + 2], &rs.pos[i + 1], static_cast<size_t>(INT_MAX))) {
122 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100123 }
124
Tao Baoc844c062016-12-28 15:15:55 -0800125 if (rs.pos[i] >= rs.pos[i + 1]) {
126 goto err; // empty or negative range
Tao Baob15fd222015-09-24 11:10:51 -0700127 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100128
Tao Baoc844c062016-12-28 15:15:55 -0800129 size_t sz = rs.pos[i + 1] - rs.pos[i];
130 if (rs.size > SIZE_MAX - sz) {
131 goto err; // overflow
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700132 }
133
Tao Baoc844c062016-12-28 15:15:55 -0800134 rs.size += sz;
135 }
136
137 return rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100138
139err:
Tao Baoc844c062016-12-28 15:15:55 -0800140 LOG(ERROR) << "failed to parse range '" << range_text << "'";
Tao Bao3da88012017-02-03 13:09:23 -0800141 exit(EXIT_FAILURE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700142}
143
Tao Baoe6aa3322015-08-05 15:20:27 -0700144static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Tao Baoc844c062016-12-28 15:15:55 -0800145 for (size_t i = 0; i < r1.count; ++i) {
146 size_t r1_0 = r1.pos[i * 2];
147 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000148
Tao Baoc844c062016-12-28 15:15:55 -0800149 for (size_t j = 0; j < r2.count; ++j) {
150 size_t r2_0 = r2.pos[j * 2];
151 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000152
Tao Baoc844c062016-12-28 15:15:55 -0800153 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
154 return true;
155 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000156 }
Tao Baoc844c062016-12-28 15:15:55 -0800157 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000158
Tao Baoc844c062016-12-28 15:15:55 -0800159 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000160}
161
162static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700163 size_t so_far = 0;
164 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800165 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700166 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700167 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800168 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000169 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700170 } else if (r == 0) {
171 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800172 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700173 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700174 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700175 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700176 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000177 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700178}
179
Tao Bao612336d2015-08-27 16:41:21 -0700180static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
181 return read_all(fd, buffer.data(), size);
182}
183
Sami Tolvanen90221202014-12-09 16:39:47 +0000184static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700185 size_t written = 0;
186 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800187 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700188 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700189 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800190 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000191 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700192 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700193 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700194 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000195
Sami Tolvanen90221202014-12-09 16:39:47 +0000196 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700197}
198
Tao Bao612336d2015-08-27 16:41:21 -0700199static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
200 return write_all(fd, buffer.data(), size);
201}
202
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700203static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
204 // Don't discard blocks unless the update is a retry run.
205 if (!is_retry) {
206 return true;
207 }
208
209 uint64_t args[2] = {static_cast<uint64_t>(offset), size};
210 int status = ioctl(fd, BLKDISCARD, &args);
211 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800212 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700213 return false;
214 }
215 return true;
216}
217
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700218static bool check_lseek(int fd, off64_t offset, int whence) {
219 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
220 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700221 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800222 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700223 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700224 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700225 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700226}
227
Tao Bao612336d2015-08-27 16:41:21 -0700228static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700229 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700230 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700231
Tao Bao612336d2015-08-27 16:41:21 -0700232 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700233}
234
Tao Bao0940fe12015-08-27 16:41:21 -0700235struct RangeSinkState {
Chih-Hung Hsieh49c5c792016-04-29 14:16:35 -0700236 explicit RangeSinkState(RangeSet& rs) : tgt(rs) { };
Tao Bao0940fe12015-08-27 16:41:21 -0700237
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700238 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700239 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530240 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700241 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700242};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700243
Tao Baoc0e1c462017-02-01 10:20:10 -0800244static size_t RangeSinkWrite(const uint8_t* data, size_t size, RangeSinkState* rss) {
Tao Baof7eb7602017-03-27 15:12:48 -0700245 if (rss->p_remain == 0) {
246 LOG(ERROR) << "range sink write overrun";
247 return 0;
248 }
249
250 size_t written = 0;
251 while (size > 0) {
252 size_t write_now = size;
253
254 if (rss->p_remain < write_now) {
255 write_now = rss->p_remain;
256 }
257
258 if (write_all(rss->fd, data, write_now) == -1) {
259 break;
260 }
261
262 data += write_now;
263 size -= write_now;
264
265 rss->p_remain -= write_now;
266 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700267
Tao Bao0940fe12015-08-27 16:41:21 -0700268 if (rss->p_remain == 0) {
Tao Baof7eb7602017-03-27 15:12:48 -0700269 // Move to the next block.
270 ++rss->p_block;
271 if (rss->p_block < rss->tgt.count) {
272 rss->p_remain =
273 (rss->tgt.pos[rss->p_block * 2 + 1] - rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
274
275 off64_t offset = static_cast<off64_t>(rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
276 if (!discard_blocks(rss->fd, offset, rss->p_remain)) {
277 break;
278 }
279
280 if (!check_lseek(rss->fd, offset, SEEK_SET)) {
281 break;
282 }
283
284 } else {
285 // We can't write any more; return how many bytes have been written so far.
286 break;
287 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700288 }
Tao Baof7eb7602017-03-27 15:12:48 -0700289 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700290
Tao Baof7eb7602017-03-27 15:12:48 -0700291 return written;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700292}
293
294// All of the data for all the 'new' transfers is contained in one
295// file in the update package, concatenated together in the order in
296// which transfers.list will need it. We want to stream it out of the
297// archive (it's compressed) without writing it to a temp file, but we
298// can't write each section until it's that transfer's turn to go.
299//
300// To achieve this, we expand the new data from the archive in a
301// background thread, and block that threads 'receive uncompressed
302// data' function until the main thread has reached a point where we
303// want some new data to be written. We signal the background thread
304// with the destination for the data and block the main thread,
305// waiting for the background thread to complete writing that section.
306// Then it signals the main thread to wake up and goes back to
307// blocking waiting for a transfer.
308//
309// NewThreadInfo is the struct used to pass information back and forth
310// between the two threads. When the main thread wants some data
311// written, it sets rss to the destination location and signals the
312// condition. When the background thread is done writing, it clears
313// rss and signals the condition again.
314
Tao Bao0940fe12015-08-27 16:41:21 -0700315struct NewThreadInfo {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700316 ZipArchiveHandle za;
317 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700318
319 RangeSinkState* rss;
320
321 pthread_mutex_t mu;
322 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700323};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700324
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700325static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700326 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700327
328 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700329 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700330 // data is wanted.
331 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700332 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700333 pthread_cond_wait(&nti->cv, &nti->mu);
334 }
335 pthread_mutex_unlock(&nti->mu);
336
337 // At this point nti->rss is set, and we own it. The main
338 // thread is waiting for it to disappear from nti.
Tao Baof7eb7602017-03-27 15:12:48 -0700339 size_t written = RangeSinkWrite(data, size, nti->rss);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700340 data += written;
341 size -= written;
342
Tao Bao0940fe12015-08-27 16:41:21 -0700343 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700344 // we have written all the bytes desired by this rss.
345
346 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700347 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700348 pthread_cond_broadcast(&nti->cv);
349 pthread_mutex_unlock(&nti->mu);
350 }
351 }
352
353 return true;
354}
355
356static void* unzip_new_data(void* cookie) {
Mikhail Lappo20791bd2017-03-23 21:30:36 +0100357 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700358 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700359 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700360}
361
Tao Bao612336d2015-08-27 16:41:21 -0700362static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000363 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700364 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000365
Tao Bao0940fe12015-08-27 16:41:21 -0700366 for (size_t i = 0; i < src.count; ++i) {
367 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000368 return -1;
369 }
370
Tao Bao0940fe12015-08-27 16:41:21 -0700371 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000372
Tao Bao612336d2015-08-27 16:41:21 -0700373 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000374 return -1;
375 }
376
377 p += size;
378 }
379
380 return 0;
381}
382
Tao Bao612336d2015-08-27 16:41:21 -0700383static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
384 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000385
Tao Bao0940fe12015-08-27 16:41:21 -0700386 size_t p = 0;
387 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700388 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
389 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
390 if (!discard_blocks(fd, offset, size)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000391 return -1;
392 }
393
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700394 if (!check_lseek(fd, offset, SEEK_SET)) {
395 return -1;
396 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000397
Tao Bao612336d2015-08-27 16:41:21 -0700398 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000399 return -1;
400 }
401
402 p += size;
403 }
404
405 return 0;
406}
407
Tao Baobaad2d42015-12-06 16:56:27 -0800408// Parameters for transfer list command functions
409struct CommandParameters {
410 std::vector<std::string> tokens;
411 size_t cpos;
412 const char* cmdname;
413 const char* cmdline;
414 std::string freestash;
415 std::string stashbase;
416 bool canwrite;
417 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700418 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800419 bool foundwrites;
420 bool isunresumable;
421 int version;
422 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700423 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800424 NewThreadInfo nti;
425 pthread_t thread;
426 std::vector<uint8_t> buffer;
427 uint8_t* patch_start;
428};
429
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000430// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
431// handled separately).
432static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
433 const std::vector<uint8_t>& buffer) {
434 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000435 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
436 params.tokens[0] == "imgdiff");
437
438 size_t pos = 0;
439 // Command example:
440 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
441 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
442 // [<loc_range> <stashed_blocks>]
443 if (params.tokens[0] == "move") {
444 // src_range for move starts at the 4th position.
445 if (params.tokens.size() < 5) {
446 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
447 return;
448 }
449 pos = 4;
450 } else {
451 // src_range for diff starts at the 7th position.
452 if (params.tokens.size() < 8) {
453 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
454 return;
455 }
456 pos = 7;
457 }
458
459 // Source blocks in stash only, no work to do.
460 if (params.tokens[pos] == "-") {
461 return;
462 }
463
464 RangeSet src = parse_range(params.tokens[pos++]);
465
466 RangeSet locs;
467 // If there's no stashed blocks, content in the buffer is consecutive and has the same
468 // order as the source blocks.
469 if (pos == params.tokens.size()) {
470 locs.count = 1;
471 locs.size = src.size;
472 locs.pos = { 0, src.size };
473 } else {
474 // Otherwise, the next token is the offset of the source blocks in the target range.
475 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
476 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
477 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
478 locs = parse_range(params.tokens[pos++]);
479 CHECK_EQ(src.size, locs.size);
480 CHECK_EQ(locs.pos.size() % 2, static_cast<size_t>(0));
481 }
482
483 LOG(INFO) << "printing hash in hex for " << src.size << " source blocks";
484 for (size_t i = 0; i < src.size; i++) {
485 int block_num = src.get_block(i);
486 CHECK_NE(block_num, -1);
487 int buffer_index = locs.get_block(i);
488 CHECK_NE(buffer_index, -1);
489 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
490
491 uint8_t digest[SHA_DIGEST_LENGTH];
492 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
493 std::string hexdigest = print_sha1(digest);
494 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
495 }
496}
497
498// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
499// in hex for each block.
500static void PrintHashForCorruptedStashedBlocks(const std::string& id,
501 const std::vector<uint8_t>& buffer,
502 const RangeSet& src) {
503 LOG(INFO) << "printing hash in hex for stash_id: " << id;
504 CHECK_EQ(src.size * BLOCKSIZE, buffer.size());
505
506 for (size_t i = 0; i < src.size; i++) {
507 int block_num = src.get_block(i);
508 CHECK_NE(block_num, -1);
509
510 uint8_t digest[SHA_DIGEST_LENGTH];
511 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
512 std::string hexdigest = print_sha1(digest);
513 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
514 }
515}
516
517// If the stash file doesn't exist, read the source blocks this stash contains and print the
518// SHA-1 for these blocks.
519static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
520 if (stash_map.find(id) == stash_map.end()) {
521 LOG(ERROR) << "No stash saved for id: " << id;
522 return;
523 }
524
525 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
526 const RangeSet& src = stash_map[id];
527 std::vector<uint8_t> buffer(src.size * BLOCKSIZE);
528 if (ReadBlocks(src, buffer, fd) == -1) {
529 LOG(ERROR) << "failed to read source blocks for stash: " << id;
530 return;
531 }
532 PrintHashForCorruptedStashedBlocks(id, buffer, src);
533}
534
Tao Bao612336d2015-08-27 16:41:21 -0700535static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700536 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800537 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700538 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000539
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800540 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000541
Tao Baoe6aa3322015-08-05 15:20:27 -0700542 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000543
Tao Bao0940fe12015-08-27 16:41:21 -0700544 if (hexdigest != expected) {
545 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800546 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
547 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700548 }
549 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000550 }
551
Tao Bao0940fe12015-08-27 16:41:21 -0700552 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000553}
554
Tao Bao0940fe12015-08-27 16:41:21 -0700555static std::string GetStashFileName(const std::string& base, const std::string& id,
556 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700557 if (base.empty()) {
558 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000559 }
560
Tao Baoe6aa3322015-08-05 15:20:27 -0700561 std::string fn(STASH_DIRECTORY_BASE);
562 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000563
564 return fn;
565}
566
Tao Baoec8272f2017-03-15 17:39:01 -0700567// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
568// directory and continues despite of errors. Calls the 'callback' function for each file.
569static void EnumerateStash(const std::string& dirname,
570 const std::function<void(const std::string&)>& callback) {
571 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000572
Tao Baoec8272f2017-03-15 17:39:01 -0700573 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000574
Tao Baoec8272f2017-03-15 17:39:01 -0700575 if (directory == nullptr) {
576 if (errno != ENOENT) {
577 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000578 }
Tao Bao51412212016-12-28 14:44:05 -0800579 return;
580 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700581
Tao Baoec8272f2017-03-15 17:39:01 -0700582 dirent* item;
583 while ((item = readdir(directory.get())) != nullptr) {
584 if (item->d_type != DT_REG) continue;
585 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800586 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000587}
588
589// Deletes the stash directory and all files in it. Assumes that it only
590// contains files. There is nothing we can do about unlikely, but possible
591// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700592static void DeleteFile(const std::string& fn) {
593 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000594
Tao Baoec8272f2017-03-15 17:39:01 -0700595 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000596
Tao Baoec8272f2017-03-15 17:39:01 -0700597 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
598 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
599 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000600}
601
Tao Baoe6aa3322015-08-05 15:20:27 -0700602static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700603 if (base.empty()) return;
604
605 LOG(INFO) << "deleting stash " << base;
606
607 std::string dirname = GetStashFileName(base, "", "");
608 EnumerateStash(dirname, DeleteFile);
609
610 if (rmdir(dirname.c_str()) == -1) {
611 if (errno != ENOENT && errno != ENOTDIR) {
612 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000613 }
Tao Baoec8272f2017-03-15 17:39:01 -0700614 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000615}
616
Tao Baobcf46492017-03-23 15:28:20 -0700617static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
618 std::vector<uint8_t>& buffer, bool printnoent) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700619 // In verify mode, if source range_set was saved for the given hash,
620 // check contents in the source blocks first. If the check fails,
621 // search for the stashed files on /cache as usual.
622 if (!params.canwrite) {
623 if (stash_map.find(id) != stash_map.end()) {
624 const RangeSet& src = stash_map[id];
625 allocate(src.size * BLOCKSIZE, buffer);
626
627 if (ReadBlocks(src, buffer, params.fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800628 LOG(ERROR) << "failed to read source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700629 return -1;
630 }
631 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800632 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000633 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700634 return -1;
635 }
636 return 0;
637 }
638 }
639
Tao Bao0940fe12015-08-27 16:41:21 -0700640 size_t blockcount = 0;
641
Sami Tolvanen90221202014-12-09 16:39:47 +0000642 if (!blocks) {
643 blocks = &blockcount;
644 }
645
Tao Baobcf46492017-03-23 15:28:20 -0700646 std::string fn = GetStashFileName(params.stashbase, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000647
Tao Bao0940fe12015-08-27 16:41:21 -0700648 struct stat sb;
649 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000650
651 if (res == -1) {
652 if (errno != ENOENT || printnoent) {
Tao Bao039f2da2016-11-22 16:29:50 -0800653 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000654 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000655 }
Tao Bao0940fe12015-08-27 16:41:21 -0700656 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000657 }
658
Tao Bao039f2da2016-11-22 16:29:50 -0800659 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000660
Tao Bao0940fe12015-08-27 16:41:21 -0700661 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800662 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
Tao Bao0940fe12015-08-27 16:41:21 -0700663 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000664 }
665
Elliott Hughesbcabd092016-03-22 20:19:22 -0700666 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000667 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800668 PLOG(ERROR) << "open \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700669 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000670 }
671
Tao Bao612336d2015-08-27 16:41:21 -0700672 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000673
Tao Bao612336d2015-08-27 16:41:21 -0700674 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700675 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000676 }
677
Tao Bao0940fe12015-08-27 16:41:21 -0700678 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000679
Tao Bao612336d2015-08-27 16:41:21 -0700680 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800681 LOG(ERROR) << "unexpected contents in " << fn;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000682 if (stash_map.find(id) == stash_map.end()) {
683 LOG(ERROR) << "failed to find source blocks number for stash " << id
684 << " when executing command: " << params.cmdname;
685 } else {
686 const RangeSet& src = stash_map[id];
687 PrintHashForCorruptedStashedBlocks(id, buffer, src);
688 }
Tao Baoec8272f2017-03-15 17:39:01 -0700689 DeleteFile(fn);
Tao Bao0940fe12015-08-27 16:41:21 -0700690 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000691 }
692
Tao Bao0940fe12015-08-27 16:41:21 -0700693 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000694}
695
Tao Bao612336d2015-08-27 16:41:21 -0700696static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baod2aecd42017-03-23 14:43:44 -0700697 std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700698 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700699 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000700 }
701
702 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800703 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700704 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000705 }
706
Tao Bao0940fe12015-08-27 16:41:21 -0700707 std::string fn = GetStashFileName(base, id, ".partial");
708 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000709
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100710 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700711 struct stat sb;
712 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100713
714 if (res == 0) {
715 // The file already exists and since the name is the hash of the contents,
716 // it's safe to assume the contents are identical (accidental hash collisions
717 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800718 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700719 *exists = true;
720 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100721 }
722
Tao Bao0940fe12015-08-27 16:41:21 -0700723 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100724 }
725
Tao Bao039f2da2016-11-22 16:29:50 -0800726 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000727
Tao Bao039f2da2016-11-22 16:29:50 -0800728 android::base::unique_fd fd(
729 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000730 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800731 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700732 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000733 }
734
Tianjie Xua946b9e2017-03-21 16:24:57 -0700735 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
736 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
737 return -1;
738 }
739
Sami Tolvanen90221202014-12-09 16:39:47 +0000740 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700741 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000742 }
743
Jed Estepa7b9a462015-12-15 16:04:53 -0800744 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700745 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800746 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700747 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000748 }
749
Tao Baoe6aa3322015-08-05 15:20:27 -0700750 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800751 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700752 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000753 }
754
Tao Bao0940fe12015-08-27 16:41:21 -0700755 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700756 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
757 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700758 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700759 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800760 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700761 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700762 }
763
Jed Estepa7b9a462015-12-15 16:04:53 -0800764 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700765 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800766 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700767 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700768 }
769
Tao Bao0940fe12015-08-27 16:41:21 -0700770 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000771}
772
773// Creates a directory for storing stash files and checks if the /cache partition
774// hash enough space for the expected amount of blocks we need to store. Returns
775// >0 if we created the directory, zero if it existed already, and <0 of failure.
776
Tao Bao51412212016-12-28 14:44:05 -0800777static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
778 std::string& base) {
779 if (blockdev.empty()) {
780 return -1;
781 }
782
783 // Stash directory should be different for each partition to avoid conflicts
784 // when updating multiple partitions at the same time, so we use the hash of
785 // the block device name as the base directory
786 uint8_t digest[SHA_DIGEST_LENGTH];
787 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
788 base = print_sha1(digest);
789
790 std::string dirname = GetStashFileName(base, "", "");
791 struct stat sb;
792 int res = stat(dirname.c_str(), &sb);
793 size_t max_stash_size = maxblocks * BLOCKSIZE;
794
795 if (res == -1 && errno != ENOENT) {
796 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
797 strerror(errno));
798 return -1;
799 } else if (res != 0) {
800 LOG(INFO) << "creating stash " << dirname;
801 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
802
803 if (res != 0) {
804 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
805 strerror(errno));
806 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000807 }
808
Tianjie Xua946b9e2017-03-21 16:24:57 -0700809 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
810 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s\n", dirname.c_str(),
811 strerror(errno));
812 return -1;
813 }
814
Tao Bao51412212016-12-28 14:44:05 -0800815 if (CacheSizeCheck(max_stash_size) != 0) {
816 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
817 max_stash_size);
818 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000819 }
820
Tao Bao51412212016-12-28 14:44:05 -0800821 return 1; // Created directory
822 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000823
Tao Bao51412212016-12-28 14:44:05 -0800824 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000825
Tao Baoec8272f2017-03-15 17:39:01 -0700826 // If the directory already exists, calculate the space already allocated to stash files and check
827 // if there's enough for all required blocks. Delete any partially completed stash files first.
828 EnumerateStash(dirname, [](const std::string& fn) {
829 if (android::base::EndsWith(fn, ".partial")) {
830 DeleteFile(fn);
831 }
832 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000833
Tao Bao51412212016-12-28 14:44:05 -0800834 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700835 EnumerateStash(dirname, [&existing](const std::string& fn) {
836 if (fn.empty()) return;
837 struct stat sb;
838 if (stat(fn.c_str(), &sb) == -1) {
839 PLOG(ERROR) << "stat \"" << fn << "\" failed";
840 return;
841 }
842 existing += static_cast<size_t>(sb.st_size);
843 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000844
Tao Bao51412212016-12-28 14:44:05 -0800845 if (max_stash_size > existing) {
846 size_t needed = max_stash_size - existing;
847 if (CacheSizeCheck(needed) != 0) {
848 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
849 needed);
850 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000851 }
Tao Bao51412212016-12-28 14:44:05 -0800852 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000853
Tao Bao51412212016-12-28 14:44:05 -0800854 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000855}
856
Tao Baobaad2d42015-12-06 16:56:27 -0800857static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700858 if (base.empty() || id.empty()) {
859 return -1;
860 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000861
Tao Baoec8272f2017-03-15 17:39:01 -0700862 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000863
Tao Baoec8272f2017-03-15 17:39:01 -0700864 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700865}
866
Tao Bao612336d2015-08-27 16:41:21 -0700867static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
868 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700869 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700870 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700871 // may be the same buffer.
872
Tao Bao612336d2015-08-27 16:41:21 -0700873 const uint8_t* from = source.data();
874 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700875 size_t start = locs.size;
876 for (int i = locs.count-1; i >= 0; --i) {
877 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700878 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700879 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700880 blocks * BLOCKSIZE);
881 }
882}
883
Tao Baod2aecd42017-03-23 14:43:44 -0700884/**
885 * We expect to parse the remainder of the parameter tokens as one of:
886 *
887 * <src_block_count> <src_range>
888 * (loads data from source image only)
889 *
890 * <src_block_count> - <[stash_id:stash_range] ...>
891 * (loads data from stashes only)
892 *
893 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
894 * (loads data from both source image and stashes)
895 *
896 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
897 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
898 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
899 * LoadStash.
900 */
901static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
902 bool* overlap) {
903 CHECK(src_blocks != nullptr);
904 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700905
Tao Baod2aecd42017-03-23 14:43:44 -0700906 // <src_block_count>
907 const std::string& token = params.tokens[params.cpos++];
908 if (!android::base::ParseUint(token, src_blocks)) {
909 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
910 return -1;
911 }
Tao Baobaad2d42015-12-06 16:56:27 -0800912
Tao Baod2aecd42017-03-23 14:43:44 -0700913 allocate(*src_blocks * BLOCKSIZE, params.buffer);
914
915 // "-" or <src_range> [<src_loc>]
916 if (params.tokens[params.cpos] == "-") {
917 // no source ranges, only stashes
918 params.cpos++;
919 } else {
920 RangeSet src = parse_range(params.tokens[params.cpos++]);
921 *overlap = range_overlaps(src, tgt);
922
923 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
924 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -0800925 }
926
Tao Baod2aecd42017-03-23 14:43:44 -0700927 if (params.cpos >= params.tokens.size()) {
928 // no stashes, only source range
929 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -0800930 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700931
Tao Baod2aecd42017-03-23 14:43:44 -0700932 RangeSet locs = parse_range(params.tokens[params.cpos++]);
933 MoveRange(params.buffer, locs, params.buffer);
934 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700935
Tao Baod2aecd42017-03-23 14:43:44 -0700936 // <[stash_id:stash_range]>
937 while (params.cpos < params.tokens.size()) {
938 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
939 // in the source block that stashed data should go.
940 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
941 if (tokens.size() != 2) {
942 LOG(ERROR) << "invalid parameter";
943 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700944 }
945
Tao Baod2aecd42017-03-23 14:43:44 -0700946 std::vector<uint8_t> stash;
947 if (LoadStash(params, tokens[0], false, nullptr, stash, true) == -1) {
948 // These source blocks will fail verification if used later, but we
949 // will let the caller decide if this is a fatal failure
950 LOG(ERROR) << "failed to load stash " << tokens[0];
951 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +0000952 }
953
Tao Baod2aecd42017-03-23 14:43:44 -0700954 RangeSet locs = parse_range(tokens[1]);
955 MoveRange(params.buffer, locs, stash);
956 }
957
958 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000959}
960
Tao Bao33567772017-03-13 14:57:34 -0700961/**
962 * Do a source/target load for move/bsdiff/imgdiff in version 3.
963 *
964 * We expect to parse the remainder of the parameter tokens as one of:
965 *
966 * <tgt_range> <src_block_count> <src_range>
967 * (loads data from source image only)
968 *
969 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
970 * (loads data from stashes only)
971 *
972 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
973 * (loads data from both source image and stashes)
974 *
Tao Baod2aecd42017-03-23 14:43:44 -0700975 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
976 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -0700977 * verification fails in a way that the update cannot be resumed anymore.
978 *
979 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
980 * the return value is -1 and the command should be aborted.
981 *
982 * If the return value is 1, the command has already been completed according to the contents of the
983 * target blocks, and should not be performed again.
984 *
985 * If the return value is 0, source blocks have expected content and the command can be performed.
986 */
Tao Baod2aecd42017-03-23 14:43:44 -0700987static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
988 bool onehash, bool* overlap) {
989 CHECK(src_blocks != nullptr);
990 CHECK(overlap != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000991
Tao Baod2aecd42017-03-23 14:43:44 -0700992 if (params.cpos >= params.tokens.size()) {
993 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -0700994 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -0700995 }
996
997 std::string srchash = params.tokens[params.cpos++];
998 std::string tgthash;
999
1000 if (onehash) {
1001 tgthash = srchash;
1002 } else {
1003 if (params.cpos >= params.tokens.size()) {
1004 LOG(ERROR) << "missing target hash";
1005 return -1;
1006 }
1007 tgthash = params.tokens[params.cpos++];
1008 }
1009
1010 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1011 // "-"/<src_range>.
1012 if (params.cpos + 2 >= params.tokens.size()) {
1013 LOG(ERROR) << "invalid parameters";
1014 return -1;
1015 }
1016
1017 // <tgt_range>
1018 tgt = parse_range(params.tokens[params.cpos++]);
1019
1020 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
1021 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
1022 return -1;
1023 }
1024
1025 // Return now if target blocks already have expected content.
1026 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
1027 return 1;
1028 }
1029
1030 // Load source blocks.
1031 if (LoadSourceBlocks(params, tgt, src_blocks, overlap) == -1) {
1032 return -1;
1033 }
1034
1035 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
1036 // If source and target blocks overlap, stash the source blocks so we can
1037 // resume from possible write errors. In verify mode, we can skip stashing
1038 // because the source blocks won't be overwritten.
1039 if (*overlap && params.canwrite) {
1040 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1041
1042 bool stash_exists = false;
1043 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1044 &stash_exists) != 0) {
1045 LOG(ERROR) << "failed to stash overlapping source blocks";
1046 return -1;
1047 }
1048
1049 params.stashed += *src_blocks;
1050 // Can be deleted when the write has completed.
1051 if (!stash_exists) {
1052 params.freestash = srchash;
1053 }
1054 }
1055
1056 // Source blocks have expected content, command can proceed.
1057 return 0;
1058 }
1059
1060 if (*overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
1061 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1062 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1063 // command.
1064 return 0;
1065 }
1066
1067 // Valid source data not available, update cannot be resumed.
1068 LOG(ERROR) << "partition has unexpected contents";
1069 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1070
1071 params.isunresumable = true;
1072
1073 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001074}
1075
Tao Bao0940fe12015-08-27 16:41:21 -07001076static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001077 size_t blocks = 0;
1078 bool overlap = false;
1079 RangeSet tgt;
Tao Baod2aecd42017-03-23 14:43:44 -07001080 int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001081
Tao Bao33567772017-03-13 14:57:34 -07001082 if (status == -1) {
1083 LOG(ERROR) << "failed to read blocks for move";
1084 return -1;
1085 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001086
Tao Bao33567772017-03-13 14:57:34 -07001087 if (status == 0) {
1088 params.foundwrites = true;
1089 } else if (params.foundwrites) {
1090 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1091 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001092
Tao Bao33567772017-03-13 14:57:34 -07001093 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001094 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001095 LOG(INFO) << " moving " << blocks << " blocks";
1096
1097 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1098 return -1;
1099 }
1100 } else {
1101 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001102 }
Tao Bao33567772017-03-13 14:57:34 -07001103 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001104
Tao Bao33567772017-03-13 14:57:34 -07001105 if (!params.freestash.empty()) {
1106 FreeStash(params.stashbase, params.freestash);
1107 params.freestash.clear();
1108 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001109
Tao Bao33567772017-03-13 14:57:34 -07001110 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001111
Tao Bao33567772017-03-13 14:57:34 -07001112 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001113}
1114
Tao Bao0940fe12015-08-27 16:41:21 -07001115static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001116 // <stash_id> <src_range>
1117 if (params.cpos + 1 >= params.tokens.size()) {
1118 LOG(ERROR) << "missing id and/or src range fields in stash command";
1119 return -1;
1120 }
1121
1122 const std::string& id = params.tokens[params.cpos++];
1123 size_t blocks = 0;
1124 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1125 // Stash file already exists and has expected contents. Do not read from source again, as the
1126 // source may have been already overwritten during a previous attempt.
1127 return 0;
1128 }
1129
1130 RangeSet src = parse_range(params.tokens[params.cpos++]);
1131
1132 allocate(src.size * BLOCKSIZE, params.buffer);
1133 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1134 return -1;
1135 }
1136 blocks = src.size;
1137 stash_map[id] = src;
1138
1139 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1140 // Source blocks have unexpected contents. If we actually need this data later, this is an
1141 // unrecoverable error. However, the command that uses the data may have already completed
1142 // previously, so the possible failure will occur during source block verification.
1143 LOG(ERROR) << "failed to load source blocks for stash " << id;
1144 return 0;
1145 }
1146
1147 // In verify mode, we don't need to stash any blocks.
1148 if (!params.canwrite) {
1149 return 0;
1150 }
1151
1152 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
1153 params.stashed += blocks;
1154 return WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001155}
1156
Tao Bao0940fe12015-08-27 16:41:21 -07001157static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001158 // <stash_id>
1159 if (params.cpos >= params.tokens.size()) {
1160 LOG(ERROR) << "missing stash id in free command";
1161 return -1;
1162 }
Tao Baobaad2d42015-12-06 16:56:27 -08001163
Tao Baobcf46492017-03-23 15:28:20 -07001164 const std::string& id = params.tokens[params.cpos++];
1165 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001166
Tao Baobcf46492017-03-23 15:28:20 -07001167 if (params.createdstash || params.canwrite) {
1168 return FreeStash(params.stashbase, id);
1169 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001170
Tao Baobcf46492017-03-23 15:28:20 -07001171 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001172}
1173
Tao Bao0940fe12015-08-27 16:41:21 -07001174static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001175
Tao Baobaad2d42015-12-06 16:56:27 -08001176 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001177 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001178 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001179 }
1180
Tao Baoc844c062016-12-28 15:15:55 -08001181 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001182
Tao Bao039f2da2016-11-22 16:29:50 -08001183 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001184
Tao Bao612336d2015-08-27 16:41:21 -07001185 allocate(BLOCKSIZE, params.buffer);
1186 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001187
Tao Bao0940fe12015-08-27 16:41:21 -07001188 if (params.canwrite) {
1189 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001190 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1191 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1192 if (!discard_blocks(params.fd, offset, size)) {
1193 return -1;
1194 }
1195
1196 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001197 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001198 }
1199
Tao Bao0940fe12015-08-27 16:41:21 -07001200 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1201 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1202 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001203 }
1204 }
1205 }
1206 }
1207
Tao Bao0940fe12015-08-27 16:41:21 -07001208 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001209 // Update only for the zero command, as the erase command will call
1210 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001211 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001212 }
1213
Tao Bao0940fe12015-08-27 16:41:21 -07001214 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001215}
1216
Tao Bao0940fe12015-08-27 16:41:21 -07001217static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001218
Tao Baobaad2d42015-12-06 16:56:27 -08001219 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001220 LOG(ERROR) << "missing target blocks for new";
Tao Bao0940fe12015-08-27 16:41:21 -07001221 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001222 }
1223
Tao Baoc844c062016-12-28 15:15:55 -08001224 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001225
Tao Bao0940fe12015-08-27 16:41:21 -07001226 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001227 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
Sami Tolvanen90221202014-12-09 16:39:47 +00001228
Tao Bao0940fe12015-08-27 16:41:21 -07001229 RangeSinkState rss(tgt);
1230 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001231 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001232 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001233
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001234 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1235 if (!discard_blocks(params.fd, offset, tgt.size * BLOCKSIZE)) {
1236 return -1;
1237 }
1238
1239 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001240 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001241 }
1242
Tao Bao0940fe12015-08-27 16:41:21 -07001243 pthread_mutex_lock(&params.nti.mu);
1244 params.nti.rss = &rss;
1245 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001246
Tao Bao0940fe12015-08-27 16:41:21 -07001247 while (params.nti.rss) {
1248 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001249 }
1250
Tao Bao0940fe12015-08-27 16:41:21 -07001251 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001252 }
1253
Tao Bao0940fe12015-08-27 16:41:21 -07001254 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001255
Tao Bao0940fe12015-08-27 16:41:21 -07001256 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001257}
1258
Tao Bao0940fe12015-08-27 16:41:21 -07001259static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001260 // <offset> <length>
1261 if (params.cpos + 1 >= params.tokens.size()) {
1262 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1263 return -1;
1264 }
Tao Bao0940fe12015-08-27 16:41:21 -07001265
Tao Baoc0e1c462017-02-01 10:20:10 -08001266 size_t offset;
1267 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1268 LOG(ERROR) << "invalid patch offset";
1269 return -1;
1270 }
Tao Bao0940fe12015-08-27 16:41:21 -07001271
Tao Baoc0e1c462017-02-01 10:20:10 -08001272 size_t len;
1273 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1274 LOG(ERROR) << "invalid patch len";
1275 return -1;
1276 }
Tao Bao0940fe12015-08-27 16:41:21 -07001277
Tao Baoc0e1c462017-02-01 10:20:10 -08001278 RangeSet tgt;
1279 size_t blocks = 0;
1280 bool overlap = false;
1281 int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
Tao Bao0940fe12015-08-27 16:41:21 -07001282
Tao Baoc0e1c462017-02-01 10:20:10 -08001283 if (status == -1) {
1284 LOG(ERROR) << "failed to read blocks for diff";
1285 return -1;
1286 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001287
Tao Baoc0e1c462017-02-01 10:20:10 -08001288 if (status == 0) {
1289 params.foundwrites = true;
1290 } else if (params.foundwrites) {
1291 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1292 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001293
Tao Baoc0e1c462017-02-01 10:20:10 -08001294 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001295 if (status == 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001296 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
1297 Value patch_value(
1298 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
1299 RangeSinkState rss(tgt);
1300 rss.fd = params.fd;
1301 rss.p_block = 0;
1302 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001303
Tao Baoc0e1c462017-02-01 10:20:10 -08001304 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1305 if (!discard_blocks(params.fd, offset, rss.p_remain)) {
1306 return -1;
1307 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001308
Tao Baoc0e1c462017-02-01 10:20:10 -08001309 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1310 return -1;
1311 }
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001312
Tao Baoc0e1c462017-02-01 10:20:10 -08001313 if (params.cmdname[0] == 'i') { // imgdiff
1314 if (ApplyImagePatch(
1315 params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1316 std::bind(&RangeSinkWrite, std::placeholders::_1, std::placeholders::_2, &rss),
1317 nullptr, nullptr) != 0) {
1318 LOG(ERROR) << "Failed to apply image patch.";
1319 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001320 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001321 } else {
1322 if (ApplyBSDiffPatch(
1323 params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1324 std::bind(&RangeSinkWrite, std::placeholders::_1, std::placeholders::_2, &rss),
1325 nullptr) != 0) {
1326 LOG(ERROR) << "Failed to apply bsdiff patch.";
1327 return -1;
1328 }
1329 }
1330
1331 // We expect the output of the patcher to fill the tgt ranges exactly.
1332 if (rss.p_block != tgt.count || rss.p_remain != 0) {
1333 LOG(ERROR) << "range sink underrun?";
1334 }
1335 } else {
1336 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size << " ["
1337 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001338 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001339 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001340
Tao Baoc0e1c462017-02-01 10:20:10 -08001341 if (!params.freestash.empty()) {
1342 FreeStash(params.stashbase, params.freestash);
1343 params.freestash.clear();
1344 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001345
Tao Baoc0e1c462017-02-01 10:20:10 -08001346 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001347
Tao Baoc0e1c462017-02-01 10:20:10 -08001348 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001349}
1350
Tao Bao0940fe12015-08-27 16:41:21 -07001351static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001352 if (DEBUG_ERASE) {
1353 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001354 }
1355
Tao Bao0940fe12015-08-27 16:41:21 -07001356 struct stat sb;
1357 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001358 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001359 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001360 }
1361
Tao Bao0940fe12015-08-27 16:41:21 -07001362 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001363 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001364 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001365 }
1366
Tao Baobaad2d42015-12-06 16:56:27 -08001367 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001368 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001369 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001370 }
1371
Tao Baoc844c062016-12-28 15:15:55 -08001372 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001373
Tao Bao0940fe12015-08-27 16:41:21 -07001374 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001375 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001376
Tao Bao0940fe12015-08-27 16:41:21 -07001377 for (size_t i = 0; i < tgt.count; ++i) {
1378 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001379 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001380 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001381 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001382 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001383
Tao Bao0940fe12015-08-27 16:41:21 -07001384 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001385 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001386 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001387 }
1388 }
1389 }
1390
Tao Bao0940fe12015-08-27 16:41:21 -07001391 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001392}
1393
1394// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001395typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001396
Tao Bao612336d2015-08-27 16:41:21 -07001397struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001398 const char* name;
1399 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001400};
Sami Tolvanen90221202014-12-09 16:39:47 +00001401
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001402// args:
1403// - block device (or file) to modify in-place
1404// - transfer list (blob)
1405// - new data stream (filename within package.zip)
1406// - patch stream (filename within package.zip, must be uncompressed)
1407
Tianjie Xuc4447322017-03-06 14:44:59 -08001408static Value* PerformBlockImageUpdate(const char* name, State* state,
1409 const std::vector<std::unique_ptr<Expr>>& argv,
1410 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001411 CommandParameters params = {};
1412 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001413
Tao Bao33567772017-03-13 14:57:34 -07001414 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1415 if (state->is_retry) {
1416 is_retry = true;
1417 LOG(INFO) << "This update is a retry.";
1418 }
1419 if (argv.size() != 4) {
1420 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1421 argv.size());
1422 return StringValue("");
1423 }
1424
1425 std::vector<std::unique_ptr<Value>> args;
1426 if (!ReadValueArgs(state, argv, &args)) {
1427 return nullptr;
1428 }
1429
1430 const Value* blockdev_filename = args[0].get();
1431 const Value* transfer_list_value = args[1].get();
1432 const Value* new_data_fn = args[2].get();
1433 const Value* patch_data_fn = args[3].get();
1434
1435 if (blockdev_filename->type != VAL_STRING) {
1436 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1437 return StringValue("");
1438 }
1439 if (transfer_list_value->type != VAL_BLOB) {
1440 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1441 return StringValue("");
1442 }
1443 if (new_data_fn->type != VAL_STRING) {
1444 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1445 return StringValue("");
1446 }
1447 if (patch_data_fn->type != VAL_STRING) {
1448 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1449 return StringValue("");
1450 }
1451
1452 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1453 if (ui == nullptr) {
1454 return StringValue("");
1455 }
1456
1457 FILE* cmd_pipe = ui->cmd_pipe;
1458 ZipArchiveHandle za = ui->package_zip;
1459
1460 if (cmd_pipe == nullptr || za == nullptr) {
1461 return StringValue("");
1462 }
1463
1464 ZipString path_data(patch_data_fn->data.c_str());
1465 ZipEntry patch_entry;
1466 if (FindEntry(za, path_data, &patch_entry) != 0) {
1467 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1468 return StringValue("");
1469 }
1470
1471 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1472 ZipString new_data(new_data_fn->data.c_str());
1473 ZipEntry new_entry;
1474 if (FindEntry(za, new_data, &new_entry) != 0) {
1475 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1476 return StringValue("");
1477 }
1478
1479 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1480 if (params.fd == -1) {
1481 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1482 return StringValue("");
1483 }
1484
1485 if (params.canwrite) {
1486 params.nti.za = za;
1487 params.nti.entry = new_entry;
1488
1489 pthread_mutex_init(&params.nti.mu, nullptr);
1490 pthread_cond_init(&params.nti.cv, nullptr);
1491 pthread_attr_t attr;
1492 pthread_attr_init(&attr);
1493 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1494
1495 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1496 if (error != 0) {
1497 PLOG(ERROR) << "pthread_create failed";
1498 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001499 }
Tao Bao33567772017-03-13 14:57:34 -07001500 }
1501
1502 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1503 if (lines.size() < 2) {
1504 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1505 lines.size());
1506 return StringValue("");
1507 }
1508
1509 // First line in transfer list is the version number.
1510 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1511 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1512 return StringValue("");
1513 }
1514
1515 LOG(INFO) << "blockimg version is " << params.version;
1516
1517 // Second line in transfer list is the total number of blocks we expect to write.
1518 size_t total_blocks;
1519 if (!android::base::ParseUint(lines[1], &total_blocks)) {
1520 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
1521 return StringValue("");
1522 }
1523
1524 if (total_blocks == 0) {
1525 return StringValue("t");
1526 }
1527
1528 size_t start = 2;
1529 if (lines.size() < 4) {
1530 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1531 lines.size());
1532 return StringValue("");
1533 }
1534
1535 // Third line is how many stash entries are needed simultaneously.
1536 LOG(INFO) << "maximum stash entries " << lines[2];
1537
1538 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1539 size_t stash_max_blocks;
1540 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
1541 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1542 lines[3].c_str());
1543 return StringValue("");
1544 }
1545
1546 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
1547 if (res == -1) {
1548 return StringValue("");
1549 }
1550
1551 params.createdstash = res;
1552
1553 start += 2;
1554
1555 // Build a map of the available commands
1556 std::unordered_map<std::string, const Command*> cmd_map;
1557 for (size_t i = 0; i < cmdcount; ++i) {
1558 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1559 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
1560 return StringValue(strdup(""));
1561 }
1562 cmd_map[commands[i].name] = &commands[i];
1563 }
1564
1565 int rc = -1;
1566
1567 // Subsequent lines are all individual transfer commands
1568 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1569 const std::string& line(*it);
1570 if (line.empty()) continue;
1571
1572 params.tokens = android::base::Split(line, " ");
1573 params.cpos = 0;
1574 params.cmdname = params.tokens[params.cpos++].c_str();
1575 params.cmdline = line.c_str();
1576
1577 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1578 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1579 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001580 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001581
Tao Bao33567772017-03-13 14:57:34 -07001582 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001583
Tao Bao33567772017-03-13 14:57:34 -07001584 if (cmd->f != nullptr && cmd->f(params) == -1) {
1585 LOG(ERROR) << "failed to execute command [" << line << "]";
1586 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001587 }
1588
Sami Tolvanen90221202014-12-09 16:39:47 +00001589 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001590 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001591 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001592 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001593 goto pbiudone;
1594 }
1595 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1596 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001597 }
Tao Bao33567772017-03-13 14:57:34 -07001598 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001599
Tao Bao33567772017-03-13 14:57:34 -07001600 if (params.canwrite) {
1601 pthread_join(params.thread, nullptr);
1602
1603 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1604 LOG(INFO) << "stashed " << params.stashed << " blocks";
1605 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1606
1607 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1608 if (partition != nullptr && *(partition + 1) != 0) {
1609 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1610 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1611 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001612 }
Tao Bao33567772017-03-13 14:57:34 -07001613 // Delete stash only after successfully completing the update, as it may contain blocks needed
1614 // to complete the update later.
1615 DeleteStash(params.stashbase);
1616 } else {
1617 LOG(INFO) << "verified partition contents; update may be resumed";
1618 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001619
Tao Bao33567772017-03-13 14:57:34 -07001620 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001621
Tao Bao33567772017-03-13 14:57:34 -07001622pbiudone:
1623 if (ota_fsync(params.fd) == -1) {
1624 failure_type = kFsyncFailure;
1625 PLOG(ERROR) << "fsync failed";
1626 }
1627 // params.fd will be automatically closed because it's a unique_fd.
1628
1629 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1630 // created the stash.
1631 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1632 DeleteStash(params.stashbase);
1633 }
1634
1635 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1636 state->cause_code = failure_type;
1637 }
1638
1639 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001640}
1641
Tao Bao33567772017-03-13 14:57:34 -07001642/**
1643 * The transfer list is a text file containing commands to transfer data from one place to another
1644 * on the target partition. We parse it and execute the commands in order:
1645 *
1646 * zero [rangeset]
1647 * - Fill the indicated blocks with zeros.
1648 *
1649 * new [rangeset]
1650 * - Fill the blocks with data read from the new_data file.
1651 *
1652 * erase [rangeset]
1653 * - Mark the given blocks as empty.
1654 *
1655 * move <...>
1656 * bsdiff <patchstart> <patchlen> <...>
1657 * imgdiff <patchstart> <patchlen> <...>
1658 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1659 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1660 *
1661 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1662 *
1663 * stash <stash_id> <src_range>
1664 * - Load the given source range and stash the data in the given slot of the stash table.
1665 *
1666 * free <stash_id>
1667 * - Free the given stash data.
1668 *
1669 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1670 * a patch or move) after it has been written.
1671 *
1672 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1673 * in a move/bsdiff/imgdiff command.
1674 *
1675 * Within one command the source and target ranges may overlap so in general we need to read the
1676 * entire source into memory before writing anything to the target blocks.
1677 *
1678 * All the patch data is concatenated into one patch_data file in the update package. It must be
1679 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1680 * already compressed, we lose very little by not compressing their concatenation.)
1681 *
1682 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1683 * additional hashes before the range parameters, which are used to check if the command has already
1684 * been completed and verify the integrity of the source data.
1685 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001686Value* BlockImageVerifyFn(const char* name, State* state,
1687 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001688 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001689 const Command commands[] = {
1690 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001691 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001692 { "free", PerformCommandFree },
1693 { "imgdiff", PerformCommandDiff },
1694 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001695 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001696 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001697 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001698 };
1699
1700 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001701 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001702 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001703}
1704
Tianjie Xuc4447322017-03-06 14:44:59 -08001705Value* BlockImageUpdateFn(const char* name, State* state,
1706 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001707 const Command commands[] = {
1708 { "bsdiff", PerformCommandDiff },
1709 { "erase", PerformCommandErase },
1710 { "free", PerformCommandFree },
1711 { "imgdiff", PerformCommandDiff },
1712 { "move", PerformCommandMove },
1713 { "new", PerformCommandNew },
1714 { "stash", PerformCommandStash },
1715 { "zero", PerformCommandZero }
1716 };
1717
Tianjie Xuc4447322017-03-06 14:44:59 -08001718 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001719 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001720}
1721
Tianjie Xuc4447322017-03-06 14:44:59 -08001722Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1723 if (argv.size() != 2) {
1724 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu",
1725 argv.size());
1726 return StringValue("");
1727 }
1728
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001729 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001730 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001731 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001732 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001733
1734 const Value* blockdev_filename = args[0].get();
1735 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001736
1737 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001738 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1739 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001740 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001741 }
1742 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001743 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001744 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001745 }
1746
Tianjie Xuaced5d92016-10-12 10:55:04 -07001747 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001748 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001749 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1750 blockdev_filename->data.c_str(), strerror(errno));
1751 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001752 }
1753
Tao Baoc844c062016-12-28 15:15:55 -08001754 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001755
1756 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001757 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001758
Tao Bao612336d2015-08-27 16:41:21 -07001759 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001760 for (size_t i = 0; i < rs.count; ++i) {
1761 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001762 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1763 blockdev_filename->data.c_str(), strerror(errno));
1764 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001765 }
1766
Tao Bao0940fe12015-08-27 16:41:21 -07001767 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001768 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001769 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1770 blockdev_filename->data.c_str(), strerror(errno));
1771 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001772 }
1773
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001774 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001775 }
1776 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001777 uint8_t digest[SHA_DIGEST_LENGTH];
1778 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001779
Tianjie Xuaced5d92016-10-12 10:55:04 -07001780 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001781}
1782
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001783// This function checks if a device has been remounted R/W prior to an incremental
1784// OTA update. This is an common cause of update abortion. The function reads the
1785// 1st block of each partition and check for mounting time/count. It return string "t"
1786// if executes successfully and an empty string otherwise.
1787
Tianjie Xuc4447322017-03-06 14:44:59 -08001788Value* CheckFirstBlockFn(const char* name, State* state,
1789 const std::vector<std::unique_ptr<Expr>>& argv) {
1790 if (argv.size() != 1) {
1791 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1792 argv.size());
1793 return StringValue("");
1794 }
1795
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001796 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001797 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001798 return nullptr;
1799 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001800
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001801 const Value* arg_filename = args[0].get();
1802
1803 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001804 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001805 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001806 }
1807
Tianjie Xuaced5d92016-10-12 10:55:04 -07001808 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001809 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001810 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001811 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001812 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001813 }
1814
1815 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1816 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1817
1818 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001819 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001820 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001821 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001822 }
1823
1824 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1825 // Super block starts from block 0, offset 0x400
1826 // 0x2C: len32 Mount time
1827 // 0x30: len32 Write time
1828 // 0x34: len16 Number of mounts since the last fsck
1829 // 0x38: len16 Magic signature 0xEF53
1830
1831 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1832 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1833
1834 if (mount_count > 0) {
Tao Bao0bbc7642017-03-29 23:57:47 -07001835 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001836 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1837 }
1838
Tianjie Xuaced5d92016-10-12 10:55:04 -07001839 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001840}
1841
1842
Tianjie Xuc4447322017-03-06 14:44:59 -08001843Value* BlockImageRecoverFn(const char* name, State* state,
1844 const std::vector<std::unique_ptr<Expr>>& argv) {
1845 if (argv.size() != 2) {
1846 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
1847 argv.size());
1848 return StringValue("");
1849 }
1850
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001851 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001852 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001853 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001854 }
1855
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001856 const Value* filename = args[0].get();
1857 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001858
1859 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001860 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001861 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001862 }
1863 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001864 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001865 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001866 }
1867
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001868 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001869 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001870
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001871 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tao Baod2aecd42017-03-23 14:43:44 -07001872 fec::io fh(filename->data, O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001873
1874 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001875 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001876 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001877 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001878 }
1879
1880 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001881 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001882 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001883 }
1884
1885 fec_status status;
1886
1887 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001888 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001889 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001890 }
1891
Tao Baoc844c062016-12-28 15:15:55 -08001892 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001893
1894 uint8_t buffer[BLOCKSIZE];
1895
1896 for (size_t i = 0; i < rs.count; ++i) {
1897 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1898 // Stay within the data area, libfec validates and corrects metadata
1899 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1900 continue;
1901 }
1902
1903 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001904 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001905 filename->data.c_str(), j, strerror(errno));
1906 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001907 }
1908
1909 // If we want to be able to recover from a situation where rewriting a corrected
1910 // block doesn't guarantee the same data will be returned when re-read later, we
1911 // can save a copy of corrected blocks to /cache. Note:
1912 //
1913 // 1. Maximum space required from /cache is the same as the maximum number of
1914 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1915 // this would be ~16 MiB, for example.
1916 //
1917 // 2. To find out if this block was corrupted, call fec_get_status after each
1918 // read and check if the errors field value has increased.
1919 }
1920 }
Tao Bao039f2da2016-11-22 16:29:50 -08001921 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001922 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001923}
1924
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001925void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001926 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001927 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001928 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001929 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001930 RegisterFunction("range_sha1", RangeSha1Fn);
1931}