blob: 0fa83d9d5222cdd7ed3b4fb4fe3b7acaf231f464 [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 Xu8cf5c8f2016-09-08 20:10:11 -070047#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070048
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070049#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070050#include "error_code.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070051#include "updater/install.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080052#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070053#include "print_sha1.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070054#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070055
Sami Tolvanene82fa182015-06-10 15:58:12 +000056// Set this to 0 to interpret 'erase' transfers to mean do a
57// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
58// erase to mean fill the region with zeroes.
59#define DEBUG_ERASE 0
60
Tao Bao51412212016-12-28 14:44:05 -080061static constexpr size_t BLOCKSIZE = 4096;
62static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
63static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
64static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000065
Tao Bao0940fe12015-08-27 16:41:21 -070066struct RangeSet {
Tao Baoc844c062016-12-28 15:15:55 -080067 size_t count; // Limit is INT_MAX.
68 size_t size;
69 std::vector<size_t> pos; // Actual limit is INT_MAX.
Tianjie Xu2cd36ba2017-03-15 23:52:46 +000070
71 // Get the block number for the ith(starting from 0) block in the range set.
72 int get_block(size_t idx) const {
73 if (idx >= size) {
74 LOG(ERROR) << "index: " << idx << " is greater than range set size: " << size;
75 return -1;
76 }
77 for (size_t i = 0; i < pos.size(); i += 2) {
78 if (idx < pos[i + 1] - pos[i]) {
79 return pos[i] + idx;
80 }
81 idx -= (pos[i + 1] - pos[i]);
82 }
83 return -1;
84 }
Tao Bao0940fe12015-08-27 16:41:21 -070085};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070086
Tianjie Xu16255832016-04-30 11:49:59 -070087static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070088static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070089static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070090
Tao Baoc844c062016-12-28 15:15:55 -080091static RangeSet parse_range(const std::string& range_text) {
92 RangeSet rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010093
Tao Baoc844c062016-12-28 15:15:55 -080094 std::vector<std::string> pieces = android::base::Split(range_text, ",");
95 if (pieces.size() < 3) {
96 goto err;
97 }
98
99 size_t num;
100 if (!android::base::ParseUint(pieces[0], &num, static_cast<size_t>(INT_MAX))) {
101 goto err;
102 }
103
104 if (num == 0 || num % 2) {
105 goto err; // must be even
106 } else if (num != pieces.size() - 1) {
107 goto err;
108 }
109
110 rs.pos.resize(num);
111 rs.count = num / 2;
112 rs.size = 0;
113
114 for (size_t i = 0; i < num; i += 2) {
115 if (!android::base::ParseUint(pieces[i + 1], &rs.pos[i], static_cast<size_t>(INT_MAX))) {
116 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100117 }
118
Tao Baoc844c062016-12-28 15:15:55 -0800119 if (!android::base::ParseUint(pieces[i + 2], &rs.pos[i + 1], static_cast<size_t>(INT_MAX))) {
120 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100121 }
122
Tao Baoc844c062016-12-28 15:15:55 -0800123 if (rs.pos[i] >= rs.pos[i + 1]) {
124 goto err; // empty or negative range
Tao Baob15fd222015-09-24 11:10:51 -0700125 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100126
Tao Baoc844c062016-12-28 15:15:55 -0800127 size_t sz = rs.pos[i + 1] - rs.pos[i];
128 if (rs.size > SIZE_MAX - sz) {
129 goto err; // overflow
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700130 }
131
Tao Baoc844c062016-12-28 15:15:55 -0800132 rs.size += sz;
133 }
134
135 return rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100136
137err:
Tao Baoc844c062016-12-28 15:15:55 -0800138 LOG(ERROR) << "failed to parse range '" << range_text << "'";
Tao Bao3da88012017-02-03 13:09:23 -0800139 exit(EXIT_FAILURE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700140}
141
Tao Baoe6aa3322015-08-05 15:20:27 -0700142static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Tao Baoc844c062016-12-28 15:15:55 -0800143 for (size_t i = 0; i < r1.count; ++i) {
144 size_t r1_0 = r1.pos[i * 2];
145 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000146
Tao Baoc844c062016-12-28 15:15:55 -0800147 for (size_t j = 0; j < r2.count; ++j) {
148 size_t r2_0 = r2.pos[j * 2];
149 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000150
Tao Baoc844c062016-12-28 15:15:55 -0800151 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
152 return true;
153 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000154 }
Tao Baoc844c062016-12-28 15:15:55 -0800155 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000156
Tao Baoc844c062016-12-28 15:15:55 -0800157 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000158}
159
160static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700161 size_t so_far = 0;
162 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800163 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700164 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700165 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800166 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000167 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700168 } else if (r == 0) {
169 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800170 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700171 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700172 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700173 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700174 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000175 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700176}
177
Tao Bao612336d2015-08-27 16:41:21 -0700178static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
179 return read_all(fd, buffer.data(), size);
180}
181
Sami Tolvanen90221202014-12-09 16:39:47 +0000182static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700183 size_t written = 0;
184 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800185 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700186 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700187 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800188 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000189 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700190 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700191 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700192 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000193
Sami Tolvanen90221202014-12-09 16:39:47 +0000194 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700195}
196
Tao Bao612336d2015-08-27 16:41:21 -0700197static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
198 return write_all(fd, buffer.data(), size);
199}
200
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700201static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
202 // Don't discard blocks unless the update is a retry run.
203 if (!is_retry) {
204 return true;
205 }
206
207 uint64_t args[2] = {static_cast<uint64_t>(offset), size};
208 int status = ioctl(fd, BLKDISCARD, &args);
209 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800210 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700211 return false;
212 }
213 return true;
214}
215
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700216static bool check_lseek(int fd, off64_t offset, int whence) {
217 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
218 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700219 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800220 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700221 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700222 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700223 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700224}
225
Tao Bao612336d2015-08-27 16:41:21 -0700226static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700227 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700228 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700229
Tao Bao612336d2015-08-27 16:41:21 -0700230 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700231}
232
Tao Bao0940fe12015-08-27 16:41:21 -0700233struct RangeSinkState {
Chih-Hung Hsieh49c5c792016-04-29 14:16:35 -0700234 explicit RangeSinkState(RangeSet& rs) : tgt(rs) { };
Tao Bao0940fe12015-08-27 16:41:21 -0700235
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700236 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700237 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530238 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700239 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700240};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700241
242static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700243 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700244
Tao Bao0940fe12015-08-27 16:41:21 -0700245 if (rss->p_remain == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800246 LOG(ERROR) << "range sink write overrun";
Sami Tolvanen90221202014-12-09 16:39:47 +0000247 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700248 }
249
250 ssize_t written = 0;
251 while (size > 0) {
252 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000253
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
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700262 data += write_now;
263 size -= write_now;
264
265 rss->p_remain -= write_now;
266 written += write_now;
267
268 if (rss->p_remain == 0) {
269 // move to the next block
270 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700271 if (rss->p_block < rss->tgt.count) {
272 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
273 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000274
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700275 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)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000277 break;
278 }
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700279
280 if (!check_lseek(rss->fd, offset, SEEK_SET)) {
281 break;
282 }
283
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700284 } else {
285 // we can't write any more; return how many bytes have
286 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000287 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700288 }
289 }
290 }
291
292 return written;
293}
294
295// All of the data for all the 'new' transfers is contained in one
296// file in the update package, concatenated together in the order in
297// which transfers.list will need it. We want to stream it out of the
298// archive (it's compressed) without writing it to a temp file, but we
299// can't write each section until it's that transfer's turn to go.
300//
301// To achieve this, we expand the new data from the archive in a
302// background thread, and block that threads 'receive uncompressed
303// data' function until the main thread has reached a point where we
304// want some new data to be written. We signal the background thread
305// with the destination for the data and block the main thread,
306// waiting for the background thread to complete writing that section.
307// Then it signals the main thread to wake up and goes back to
308// blocking waiting for a transfer.
309//
310// NewThreadInfo is the struct used to pass information back and forth
311// between the two threads. When the main thread wants some data
312// written, it sets rss to the destination location and signals the
313// condition. When the background thread is done writing, it clears
314// rss and signals the condition again.
315
Tao Bao0940fe12015-08-27 16:41:21 -0700316struct NewThreadInfo {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700317 ZipArchiveHandle za;
318 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700319
320 RangeSinkState* rss;
321
322 pthread_mutex_t mu;
323 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700324};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700325
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700326static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700327 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700328
329 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700330 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700331 // data is wanted.
332 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700333 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700334 pthread_cond_wait(&nti->cv, &nti->mu);
335 }
336 pthread_mutex_unlock(&nti->mu);
337
338 // At this point nti->rss is set, and we own it. The main
339 // thread is waiting for it to disappear from nti.
340 ssize_t written = RangeSinkWrite(data, size, nti->rss);
341 data += written;
342 size -= written;
343
Tao Bao0940fe12015-08-27 16:41:21 -0700344 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700345 // we have written all the bytes desired by this rss.
346
347 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700348 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700349 pthread_cond_broadcast(&nti->cv);
350 pthread_mutex_unlock(&nti->mu);
351 }
352 }
353
354 return true;
355}
356
357static void* unzip_new_data(void* cookie) {
358 NewThreadInfo* nti = (NewThreadInfo*) cookie;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700359 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700360 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700361}
362
Tao Bao612336d2015-08-27 16:41:21 -0700363static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000364 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700365 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000366
Tao Bao0940fe12015-08-27 16:41:21 -0700367 for (size_t i = 0; i < src.count; ++i) {
368 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000369 return -1;
370 }
371
Tao Bao0940fe12015-08-27 16:41:21 -0700372 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000373
Tao Bao612336d2015-08-27 16:41:21 -0700374 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000375 return -1;
376 }
377
378 p += size;
379 }
380
381 return 0;
382}
383
Tao Bao612336d2015-08-27 16:41:21 -0700384static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
385 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000386
Tao Bao0940fe12015-08-27 16:41:21 -0700387 size_t p = 0;
388 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700389 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
390 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
391 if (!discard_blocks(fd, offset, size)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000392 return -1;
393 }
394
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700395 if (!check_lseek(fd, offset, SEEK_SET)) {
396 return -1;
397 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000398
Tao Bao612336d2015-08-27 16:41:21 -0700399 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000400 return -1;
401 }
402
403 p += size;
404 }
405
406 return 0;
407}
408
Tao Baobaad2d42015-12-06 16:56:27 -0800409// Parameters for transfer list command functions
410struct CommandParameters {
411 std::vector<std::string> tokens;
412 size_t cpos;
413 const char* cmdname;
414 const char* cmdline;
415 std::string freestash;
416 std::string stashbase;
417 bool canwrite;
418 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700419 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800420 bool foundwrites;
421 bool isunresumable;
422 int version;
423 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700424 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800425 NewThreadInfo nti;
426 pthread_t thread;
427 std::vector<uint8_t> buffer;
428 uint8_t* patch_start;
429};
430
Doug Zongker52ae67d2014-09-08 12:22:09 -0700431// Do a source/target load for move/bsdiff/imgdiff in version 1.
Tao Baobaad2d42015-12-06 16:56:27 -0800432// We expect to parse the remainder of the parameter tokens as:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700433//
434// <src_range> <tgt_range>
435//
436// The source range is loaded into the provided buffer, reallocating
Tao Bao34847b22015-09-08 11:05:49 -0700437// it to make it larger if necessary.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700438
Tao Baobaad2d42015-12-06 16:56:27 -0800439static int LoadSrcTgtVersion1(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700440 std::vector<uint8_t>& buffer, int fd) {
Tao Baobaad2d42015-12-06 16:56:27 -0800441
442 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800443 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -0800444 return -1;
445 }
446
Tao Bao612336d2015-08-27 16:41:21 -0700447 // <src_range>
Tao Baoc844c062016-12-28 15:15:55 -0800448 RangeSet src = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700449
Tao Bao612336d2015-08-27 16:41:21 -0700450 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -0800451 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700452
Tao Bao612336d2015-08-27 16:41:21 -0700453 allocate(src.size * BLOCKSIZE, buffer);
454 int rc = ReadBlocks(src, buffer, fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700455 src_blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000456
Sami Tolvanen90221202014-12-09 16:39:47 +0000457 return rc;
458}
459
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000460// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
461// handled separately).
462static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
463 const std::vector<uint8_t>& buffer) {
464 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
465 if (params.version < 3) {
466 // TODO handle version 1,2
467 LOG(WARNING) << "version number " << params.version << " is not supported to print hashes";
468 return;
469 }
470
471 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
472 params.tokens[0] == "imgdiff");
473
474 size_t pos = 0;
475 // Command example:
476 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
477 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
478 // [<loc_range> <stashed_blocks>]
479 if (params.tokens[0] == "move") {
480 // src_range for move starts at the 4th position.
481 if (params.tokens.size() < 5) {
482 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
483 return;
484 }
485 pos = 4;
486 } else {
487 // src_range for diff starts at the 7th position.
488 if (params.tokens.size() < 8) {
489 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
490 return;
491 }
492 pos = 7;
493 }
494
495 // Source blocks in stash only, no work to do.
496 if (params.tokens[pos] == "-") {
497 return;
498 }
499
500 RangeSet src = parse_range(params.tokens[pos++]);
501
502 RangeSet locs;
503 // If there's no stashed blocks, content in the buffer is consecutive and has the same
504 // order as the source blocks.
505 if (pos == params.tokens.size()) {
506 locs.count = 1;
507 locs.size = src.size;
508 locs.pos = { 0, src.size };
509 } else {
510 // Otherwise, the next token is the offset of the source blocks in the target range.
511 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
512 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
513 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
514 locs = parse_range(params.tokens[pos++]);
515 CHECK_EQ(src.size, locs.size);
516 CHECK_EQ(locs.pos.size() % 2, static_cast<size_t>(0));
517 }
518
519 LOG(INFO) << "printing hash in hex for " << src.size << " source blocks";
520 for (size_t i = 0; i < src.size; i++) {
521 int block_num = src.get_block(i);
522 CHECK_NE(block_num, -1);
523 int buffer_index = locs.get_block(i);
524 CHECK_NE(buffer_index, -1);
525 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
526
527 uint8_t digest[SHA_DIGEST_LENGTH];
528 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
529 std::string hexdigest = print_sha1(digest);
530 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
531 }
532}
533
534// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
535// in hex for each block.
536static void PrintHashForCorruptedStashedBlocks(const std::string& id,
537 const std::vector<uint8_t>& buffer,
538 const RangeSet& src) {
539 LOG(INFO) << "printing hash in hex for stash_id: " << id;
540 CHECK_EQ(src.size * BLOCKSIZE, buffer.size());
541
542 for (size_t i = 0; i < src.size; i++) {
543 int block_num = src.get_block(i);
544 CHECK_NE(block_num, -1);
545
546 uint8_t digest[SHA_DIGEST_LENGTH];
547 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
548 std::string hexdigest = print_sha1(digest);
549 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
550 }
551}
552
553// If the stash file doesn't exist, read the source blocks this stash contains and print the
554// SHA-1 for these blocks.
555static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
556 if (stash_map.find(id) == stash_map.end()) {
557 LOG(ERROR) << "No stash saved for id: " << id;
558 return;
559 }
560
561 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
562 const RangeSet& src = stash_map[id];
563 std::vector<uint8_t> buffer(src.size * BLOCKSIZE);
564 if (ReadBlocks(src, buffer, fd) == -1) {
565 LOG(ERROR) << "failed to read source blocks for stash: " << id;
566 return;
567 }
568 PrintHashForCorruptedStashedBlocks(id, buffer, src);
569}
570
Tao Bao612336d2015-08-27 16:41:21 -0700571static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700572 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800573 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700574 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000575
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800576 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000577
Tao Baoe6aa3322015-08-05 15:20:27 -0700578 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000579
Tao Bao0940fe12015-08-27 16:41:21 -0700580 if (hexdigest != expected) {
581 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800582 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
583 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700584 }
585 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000586 }
587
Tao Bao0940fe12015-08-27 16:41:21 -0700588 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000589}
590
Tao Bao0940fe12015-08-27 16:41:21 -0700591static std::string GetStashFileName(const std::string& base, const std::string& id,
592 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700593 if (base.empty()) {
594 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000595 }
596
Tao Baoe6aa3322015-08-05 15:20:27 -0700597 std::string fn(STASH_DIRECTORY_BASE);
598 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000599
600 return fn;
601}
602
Tao Baoec8272f2017-03-15 17:39:01 -0700603// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
604// directory and continues despite of errors. Calls the 'callback' function for each file.
605static void EnumerateStash(const std::string& dirname,
606 const std::function<void(const std::string&)>& callback) {
607 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000608
Tao Baoec8272f2017-03-15 17:39:01 -0700609 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000610
Tao Baoec8272f2017-03-15 17:39:01 -0700611 if (directory == nullptr) {
612 if (errno != ENOENT) {
613 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000614 }
Tao Bao51412212016-12-28 14:44:05 -0800615 return;
616 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700617
Tao Baoec8272f2017-03-15 17:39:01 -0700618 dirent* item;
619 while ((item = readdir(directory.get())) != nullptr) {
620 if (item->d_type != DT_REG) continue;
621 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800622 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000623}
624
625// Deletes the stash directory and all files in it. Assumes that it only
626// contains files. There is nothing we can do about unlikely, but possible
627// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700628static void DeleteFile(const std::string& fn) {
629 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000630
Tao Baoec8272f2017-03-15 17:39:01 -0700631 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000632
Tao Baoec8272f2017-03-15 17:39:01 -0700633 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
634 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
635 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000636}
637
Tao Baoe6aa3322015-08-05 15:20:27 -0700638static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700639 if (base.empty()) return;
640
641 LOG(INFO) << "deleting stash " << base;
642
643 std::string dirname = GetStashFileName(base, "", "");
644 EnumerateStash(dirname, DeleteFile);
645
646 if (rmdir(dirname.c_str()) == -1) {
647 if (errno != ENOENT && errno != ENOTDIR) {
648 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000649 }
Tao Baoec8272f2017-03-15 17:39:01 -0700650 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000651}
652
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700653static int LoadStash(CommandParameters& params, const std::string& base, const std::string& id,
654 bool verify, size_t* blocks, std::vector<uint8_t>& buffer, bool printnoent) {
655 // In verify mode, if source range_set was saved for the given hash,
656 // check contents in the source blocks first. If the check fails,
657 // search for the stashed files on /cache as usual.
658 if (!params.canwrite) {
659 if (stash_map.find(id) != stash_map.end()) {
660 const RangeSet& src = stash_map[id];
661 allocate(src.size * BLOCKSIZE, buffer);
662
663 if (ReadBlocks(src, buffer, params.fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800664 LOG(ERROR) << "failed to read source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700665 return -1;
666 }
667 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800668 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000669 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700670 return -1;
671 }
672 return 0;
673 }
674 }
675
Tao Bao612336d2015-08-27 16:41:21 -0700676 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700677 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000678 }
679
Tao Bao0940fe12015-08-27 16:41:21 -0700680 size_t blockcount = 0;
681
Sami Tolvanen90221202014-12-09 16:39:47 +0000682 if (!blocks) {
683 blocks = &blockcount;
684 }
685
Tao Bao0940fe12015-08-27 16:41:21 -0700686 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000687
Tao Bao0940fe12015-08-27 16:41:21 -0700688 struct stat sb;
689 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000690
691 if (res == -1) {
692 if (errno != ENOENT || printnoent) {
Tao Bao039f2da2016-11-22 16:29:50 -0800693 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000694 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000695 }
Tao Bao0940fe12015-08-27 16:41:21 -0700696 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000697 }
698
Tao Bao039f2da2016-11-22 16:29:50 -0800699 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000700
Tao Bao0940fe12015-08-27 16:41:21 -0700701 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800702 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
Tao Bao0940fe12015-08-27 16:41:21 -0700703 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000704 }
705
Elliott Hughesbcabd092016-03-22 20:19:22 -0700706 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000707 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800708 PLOG(ERROR) << "open \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700709 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000710 }
711
Tao Bao612336d2015-08-27 16:41:21 -0700712 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000713
Tao Bao612336d2015-08-27 16:41:21 -0700714 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700715 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000716 }
717
Tao Bao0940fe12015-08-27 16:41:21 -0700718 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000719
Tao Bao612336d2015-08-27 16:41:21 -0700720 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800721 LOG(ERROR) << "unexpected contents in " << fn;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000722 if (stash_map.find(id) == stash_map.end()) {
723 LOG(ERROR) << "failed to find source blocks number for stash " << id
724 << " when executing command: " << params.cmdname;
725 } else {
726 const RangeSet& src = stash_map[id];
727 PrintHashForCorruptedStashedBlocks(id, buffer, src);
728 }
Tao Baoec8272f2017-03-15 17:39:01 -0700729 DeleteFile(fn);
Tao Bao0940fe12015-08-27 16:41:21 -0700730 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000731 }
732
Tao Bao0940fe12015-08-27 16:41:21 -0700733 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000734}
735
Tao Bao612336d2015-08-27 16:41:21 -0700736static int WriteStash(const std::string& base, const std::string& id, int blocks,
737 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
738 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700739 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000740 }
741
742 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800743 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700744 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000745 }
746
Tao Bao0940fe12015-08-27 16:41:21 -0700747 std::string fn = GetStashFileName(base, id, ".partial");
748 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000749
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100750 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700751 struct stat sb;
752 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100753
754 if (res == 0) {
755 // The file already exists and since the name is the hash of the contents,
756 // it's safe to assume the contents are identical (accidental hash collisions
757 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800758 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700759 *exists = true;
760 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100761 }
762
Tao Bao0940fe12015-08-27 16:41:21 -0700763 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100764 }
765
Tao Bao039f2da2016-11-22 16:29:50 -0800766 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000767
Tao Bao039f2da2016-11-22 16:29:50 -0800768 android::base::unique_fd fd(
769 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000770 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800771 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700772 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000773 }
774
775 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700776 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000777 }
778
Jed Estepa7b9a462015-12-15 16:04:53 -0800779 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700780 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800781 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700782 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000783 }
784
Tao Baoe6aa3322015-08-05 15:20:27 -0700785 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800786 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700787 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000788 }
789
Tao Bao0940fe12015-08-27 16:41:21 -0700790 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700791 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
792 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700793 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700794 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800795 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700796 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700797 }
798
Jed Estepa7b9a462015-12-15 16:04:53 -0800799 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700800 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800801 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700802 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700803 }
804
Tao Bao0940fe12015-08-27 16:41:21 -0700805 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000806}
807
808// Creates a directory for storing stash files and checks if the /cache partition
809// hash enough space for the expected amount of blocks we need to store. Returns
810// >0 if we created the directory, zero if it existed already, and <0 of failure.
811
Tao Bao51412212016-12-28 14:44:05 -0800812static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
813 std::string& base) {
814 if (blockdev.empty()) {
815 return -1;
816 }
817
818 // Stash directory should be different for each partition to avoid conflicts
819 // when updating multiple partitions at the same time, so we use the hash of
820 // the block device name as the base directory
821 uint8_t digest[SHA_DIGEST_LENGTH];
822 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
823 base = print_sha1(digest);
824
825 std::string dirname = GetStashFileName(base, "", "");
826 struct stat sb;
827 int res = stat(dirname.c_str(), &sb);
828 size_t max_stash_size = maxblocks * BLOCKSIZE;
829
830 if (res == -1 && errno != ENOENT) {
831 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
832 strerror(errno));
833 return -1;
834 } else if (res != 0) {
835 LOG(INFO) << "creating stash " << dirname;
836 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
837
838 if (res != 0) {
839 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
840 strerror(errno));
841 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000842 }
843
Tao Bao51412212016-12-28 14:44:05 -0800844 if (CacheSizeCheck(max_stash_size) != 0) {
845 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
846 max_stash_size);
847 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000848 }
849
Tao Bao51412212016-12-28 14:44:05 -0800850 return 1; // Created directory
851 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000852
Tao Bao51412212016-12-28 14:44:05 -0800853 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000854
Tao Baoec8272f2017-03-15 17:39:01 -0700855 // If the directory already exists, calculate the space already allocated to stash files and check
856 // if there's enough for all required blocks. Delete any partially completed stash files first.
857 EnumerateStash(dirname, [](const std::string& fn) {
858 if (android::base::EndsWith(fn, ".partial")) {
859 DeleteFile(fn);
860 }
861 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000862
Tao Bao51412212016-12-28 14:44:05 -0800863 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700864 EnumerateStash(dirname, [&existing](const std::string& fn) {
865 if (fn.empty()) return;
866 struct stat sb;
867 if (stat(fn.c_str(), &sb) == -1) {
868 PLOG(ERROR) << "stat \"" << fn << "\" failed";
869 return;
870 }
871 existing += static_cast<size_t>(sb.st_size);
872 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000873
Tao Bao51412212016-12-28 14:44:05 -0800874 if (max_stash_size > existing) {
875 size_t needed = max_stash_size - existing;
876 if (CacheSizeCheck(needed) != 0) {
877 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
878 needed);
879 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000880 }
Tao Bao51412212016-12-28 14:44:05 -0800881 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000882
Tao Bao51412212016-12-28 14:44:05 -0800883 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000884}
885
Tao Baobaad2d42015-12-06 16:56:27 -0800886static int SaveStash(CommandParameters& params, const std::string& base,
887 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000888
Tao Baobaad2d42015-12-06 16:56:27 -0800889 // <stash_id> <src_range>
890 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800891 LOG(ERROR) << "missing id and/or src range fields in stash command";
Sami Tolvanen90221202014-12-09 16:39:47 +0000892 return -1;
893 }
Tao Baobaad2d42015-12-06 16:56:27 -0800894 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000895
Tao Bao0940fe12015-08-27 16:41:21 -0700896 size_t blocks = 0;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700897 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000898 // Stash file already exists and has expected contents. Do not
899 // read from source again, as the source may have been already
900 // overwritten during a previous attempt.
901 return 0;
902 }
903
Tao Baoc844c062016-12-28 15:15:55 -0800904 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao34847b22015-09-08 11:05:49 -0700905
Tao Bao612336d2015-08-27 16:41:21 -0700906 allocate(src.size * BLOCKSIZE, buffer);
907 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000908 return -1;
909 }
Tao Bao34847b22015-09-08 11:05:49 -0700910 blocks = src.size;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000911 stash_map[id] = src;
Sami Tolvanen90221202014-12-09 16:39:47 +0000912
Tao Bao612336d2015-08-27 16:41:21 -0700913 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000914 // Source blocks have unexpected contents. If we actually need this
915 // data later, this is an unrecoverable error. However, the command
916 // that uses the data may have already completed previously, so the
917 // possible failure will occur during source block verification.
Tao Bao039f2da2016-11-22 16:29:50 -0800918 LOG(ERROR) << "failed to load source blocks for stash " << id;
Sami Tolvanen90221202014-12-09 16:39:47 +0000919 return 0;
920 }
921
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000922 // In verify mode, we don't need to stash any blocks.
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700923 if (!params.canwrite && usehash) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700924 return 0;
925 }
926
Tao Bao039f2da2016-11-22 16:29:50 -0800927 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xudd874b12016-05-13 12:13:15 -0700928 params.stashed += blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700929 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000930}
931
Tao Baobaad2d42015-12-06 16:56:27 -0800932static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700933 if (base.empty() || id.empty()) {
934 return -1;
935 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000936
Tao Baoec8272f2017-03-15 17:39:01 -0700937 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000938
Tao Baoec8272f2017-03-15 17:39:01 -0700939 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700940}
941
Tao Bao612336d2015-08-27 16:41:21 -0700942static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
943 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700944 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700945 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700946 // may be the same buffer.
947
Tao Bao612336d2015-08-27 16:41:21 -0700948 const uint8_t* from = source.data();
949 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700950 size_t start = locs.size;
951 for (int i = locs.count-1; i >= 0; --i) {
952 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700953 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700954 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700955 blocks * BLOCKSIZE);
956 }
957}
958
959// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800960// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700961//
962// <tgt_range> <src_block_count> <src_range>
963// (loads data from source image only)
964//
965// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
966// (loads data from stashes only)
967//
968// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
969// (loads data from both source image and stashes)
970//
971// On return, buffer is filled with the loaded source data (rearranged
972// and combined with stashed data as necessary). buffer may be
973// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000974// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700975
Tao Baobaad2d42015-12-06 16:56:27 -0800976static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700977 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800978
979 // At least it needs to provide three parameters: <tgt_range>,
980 // <src_block_count> and "-"/<src_range>.
981 if (params.cpos + 2 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800982 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -0800983 return -1;
984 }
985
Tao Bao612336d2015-08-27 16:41:21 -0700986 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -0800987 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700988
Tao Bao612336d2015-08-27 16:41:21 -0700989 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800990 const std::string& token = params.tokens[params.cpos++];
991 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
Tao Bao039f2da2016-11-22 16:29:50 -0800992 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
Tao Baobaad2d42015-12-06 16:56:27 -0800993 return -1;
994 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700995
Tao Bao612336d2015-08-27 16:41:21 -0700996 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700997
Tao Bao612336d2015-08-27 16:41:21 -0700998 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800999 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -07001000 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -08001001 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001002 } else {
Tao Baoc844c062016-12-28 15:15:55 -08001003 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -07001004 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001005
Tao Bao34847b22015-09-08 11:05:49 -07001006 if (overlap) {
1007 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001008 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001009
Sami Tolvanen90221202014-12-09 16:39:47 +00001010 if (res == -1) {
1011 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001012 }
1013
Tao Baobaad2d42015-12-06 16:56:27 -08001014 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001015 // no stashes, only source range
1016 return 0;
1017 }
1018
Tao Baoc844c062016-12-28 15:15:55 -08001019 RangeSet locs = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -07001020 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001021 }
1022
Tao Baobaad2d42015-12-06 16:56:27 -08001023 // <[stash_id:stash_range]>
1024 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -07001025 // Each word is a an index into the stash table, a colon, and
1026 // then a rangeset describing where in the source block that
1027 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -08001028 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1029 if (tokens.size() != 2) {
Tao Bao039f2da2016-11-22 16:29:50 -08001030 LOG(ERROR) << "invalid parameter";
Tao Baobaad2d42015-12-06 16:56:27 -08001031 return -1;
1032 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001033
Tao Bao612336d2015-08-27 16:41:21 -07001034 std::vector<uint8_t> stash;
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001035 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001036
1037 if (res == -1) {
1038 // These source blocks will fail verification if used later, but we
1039 // will let the caller decide if this is a fatal failure
Tao Bao039f2da2016-11-22 16:29:50 -08001040 LOG(ERROR) << "failed to load stash " << tokens[0];
Sami Tolvanen90221202014-12-09 16:39:47 +00001041 continue;
1042 }
1043
Tao Baoc844c062016-12-28 15:15:55 -08001044 RangeSet locs = parse_range(tokens[1]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001045
Tao Bao612336d2015-08-27 16:41:21 -07001046 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +00001047 }
1048
1049 return 0;
1050}
1051
Sami Tolvanen90221202014-12-09 16:39:47 +00001052// Do a source/target load for move/bsdiff/imgdiff in version 3.
1053//
1054// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
1055// tells the function whether to expect separate source and targe block hashes, or
1056// if they are both the same and only one hash should be expected, and
1057// 'isunresumable', which receives a non-zero value if block verification fails in
1058// a way that the update cannot be resumed anymore.
1059//
1060// If the function is unable to load the necessary blocks or their contents don't
1061// match the hashes, the return value is -1 and the command should be aborted.
1062//
1063// If the return value is 1, the command has already been completed according to
1064// the contents of the target blocks, and should not be performed again.
1065//
1066// If the return value is 0, source blocks have expected content and the command
1067// can be performed.
1068
Tao Bao34847b22015-09-08 11:05:49 -07001069static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -07001070 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001071
Tao Baobaad2d42015-12-06 16:56:27 -08001072 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001073 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001074 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001075 }
1076
Tao Baobaad2d42015-12-06 16:56:27 -08001077 std::string srchash = params.tokens[params.cpos++];
1078 std::string tgthash;
1079
Sami Tolvanen90221202014-12-09 16:39:47 +00001080 if (onehash) {
1081 tgthash = srchash;
1082 } else {
Tao Baobaad2d42015-12-06 16:56:27 -08001083 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001084 LOG(ERROR) << "missing target hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001085 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001086 }
Tao Baobaad2d42015-12-06 16:56:27 -08001087 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +00001088 }
1089
Elliott Hughesbcabd092016-03-22 20:19:22 -07001090 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd,
1091 params.stashbase, &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -07001092 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001093 }
1094
Tao Bao34847b22015-09-08 11:05:49 -07001095 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001096
Tao Bao612336d2015-08-27 16:41:21 -07001097 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -07001098 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001099 }
1100
Tao Bao612336d2015-08-27 16:41:21 -07001101 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001102 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -07001103 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001104 }
1105
Tao Bao0940fe12015-08-27 16:41:21 -07001106 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001107 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001108 // resume from possible write errors. In verify mode, we can skip stashing
1109 // because the source blocks won't be overwritten.
1110 if (overlap && params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001111 LOG(INFO) << "stashing " << src_blocks << " overlapping blocks to " << srchash;
Sami Tolvanen90221202014-12-09 16:39:47 +00001112
Tao Bao0940fe12015-08-27 16:41:21 -07001113 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -07001114 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -07001115 &stash_exists) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001116 LOG(ERROR) << "failed to stash overlapping source blocks";
Tao Bao0940fe12015-08-27 16:41:21 -07001117 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001118 }
1119
Tianjie Xudd874b12016-05-13 12:13:15 -07001120 params.stashed += src_blocks;
Sami Tolvanen90221202014-12-09 16:39:47 +00001121 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001122 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -07001123 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001124 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001125 }
1126
1127 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -07001128 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001129 }
1130
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001131 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
1132 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001133 // Overlapping source blocks were previously stashed, command can proceed.
1134 // We are recovering from an interrupted command, so we don't know if the
1135 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -07001136 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001137 }
1138
1139 // Valid source data not available, update cannot be resumed
Tao Bao039f2da2016-11-22 16:29:50 -08001140 LOG(ERROR) << "partition has unexpected contents";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +00001141 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1142
Tao Bao0940fe12015-08-27 16:41:21 -07001143 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +00001144
Tao Bao0940fe12015-08-27 16:41:21 -07001145 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001146}
1147
Tao Bao0940fe12015-08-27 16:41:21 -07001148static int PerformCommandMove(CommandParameters& params) {
1149 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001150 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001151 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001152 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001153
Tao Bao0940fe12015-08-27 16:41:21 -07001154 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001155 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001156 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001157 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001158 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001159 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001160 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001161 }
1162
1163 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001164 LOG(ERROR) << "failed to read blocks for move";
Tao Bao0940fe12015-08-27 16:41:21 -07001165 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001166 }
1167
1168 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001169 params.foundwrites = true;
1170 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001171 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001172 }
1173
Tao Bao0940fe12015-08-27 16:41:21 -07001174 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001175 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001176 LOG(INFO) << " moving " << blocks << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001177
Tao Bao0940fe12015-08-27 16:41:21 -07001178 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1179 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001180 }
1181 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001182 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001183 }
1184
1185 }
1186
Tao Baobaad2d42015-12-06 16:56:27 -08001187 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001188 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001189 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001190 }
1191
Tao Bao0940fe12015-08-27 16:41:21 -07001192 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001193
Tao Bao0940fe12015-08-27 16:41:21 -07001194 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001195}
1196
Tao Bao0940fe12015-08-27 16:41:21 -07001197static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001198 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001199 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001200}
1201
Tao Bao0940fe12015-08-27 16:41:21 -07001202static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001203 // <stash_id>
1204 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001205 LOG(ERROR) << "missing stash id in free command";
Tao Baobaad2d42015-12-06 16:56:27 -08001206 return -1;
1207 }
1208
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001209 const std::string& id = params.tokens[params.cpos++];
1210
Tianjie Xu2cd36ba2017-03-15 23:52:46 +00001211 if (stash_map.find(id) != stash_map.end()) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001212 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001213 }
1214
Tao Bao0940fe12015-08-27 16:41:21 -07001215 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001216 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001217 }
1218
1219 return 0;
1220}
1221
Tao Bao0940fe12015-08-27 16:41:21 -07001222static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001223
Tao Baobaad2d42015-12-06 16:56:27 -08001224 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001225 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001226 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001227 }
1228
Tao Baoc844c062016-12-28 15:15:55 -08001229 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001230
Tao Bao039f2da2016-11-22 16:29:50 -08001231 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001232
Tao Bao612336d2015-08-27 16:41:21 -07001233 allocate(BLOCKSIZE, params.buffer);
1234 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001235
Tao Bao0940fe12015-08-27 16:41:21 -07001236 if (params.canwrite) {
1237 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001238 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1239 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1240 if (!discard_blocks(params.fd, offset, size)) {
1241 return -1;
1242 }
1243
1244 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001245 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001246 }
1247
Tao Bao0940fe12015-08-27 16:41:21 -07001248 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1249 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1250 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001251 }
1252 }
1253 }
1254 }
1255
Tao Bao0940fe12015-08-27 16:41:21 -07001256 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001257 // Update only for the zero command, as the erase command will call
1258 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001259 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001260 }
1261
Tao Bao0940fe12015-08-27 16:41:21 -07001262 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001263}
1264
Tao Bao0940fe12015-08-27 16:41:21 -07001265static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001266
Tao Baobaad2d42015-12-06 16:56:27 -08001267 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001268 LOG(ERROR) << "missing target blocks for new";
Tao Bao0940fe12015-08-27 16:41:21 -07001269 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001270 }
1271
Tao Baoc844c062016-12-28 15:15:55 -08001272 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001273
Tao Bao0940fe12015-08-27 16:41:21 -07001274 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001275 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
Sami Tolvanen90221202014-12-09 16:39:47 +00001276
Tao Bao0940fe12015-08-27 16:41:21 -07001277 RangeSinkState rss(tgt);
1278 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001279 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001280 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001281
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001282 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1283 if (!discard_blocks(params.fd, offset, tgt.size * BLOCKSIZE)) {
1284 return -1;
1285 }
1286
1287 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001288 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001289 }
1290
Tao Bao0940fe12015-08-27 16:41:21 -07001291 pthread_mutex_lock(&params.nti.mu);
1292 params.nti.rss = &rss;
1293 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001294
Tao Bao0940fe12015-08-27 16:41:21 -07001295 while (params.nti.rss) {
1296 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001297 }
1298
Tao Bao0940fe12015-08-27 16:41:21 -07001299 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001300 }
1301
Tao Bao0940fe12015-08-27 16:41:21 -07001302 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001303
Tao Bao0940fe12015-08-27 16:41:21 -07001304 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001305}
1306
Tao Bao0940fe12015-08-27 16:41:21 -07001307static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001308
Tao Baobaad2d42015-12-06 16:56:27 -08001309 // <offset> <length>
1310 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001311 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
Tao Bao0940fe12015-08-27 16:41:21 -07001312 return -1;
1313 }
1314
Tao Baobaad2d42015-12-06 16:56:27 -08001315 size_t offset;
1316 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001317 LOG(ERROR) << "invalid patch offset";
Tao Bao0940fe12015-08-27 16:41:21 -07001318 return -1;
1319 }
1320
Tao Baobaad2d42015-12-06 16:56:27 -08001321 size_t len;
1322 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001323 LOG(ERROR) << "invalid patch len";
Tao Baobaad2d42015-12-06 16:56:27 -08001324 return -1;
1325 }
Tao Bao0940fe12015-08-27 16:41:21 -07001326
Tao Bao612336d2015-08-27 16:41:21 -07001327 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001328 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001329 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001330 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001331 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001332 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001333 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001334 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001335 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001336 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001337 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001338 }
1339
1340 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001341 LOG(ERROR) << "failed to read blocks for diff";
Tao Bao0940fe12015-08-27 16:41:21 -07001342 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001343 }
1344
1345 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001346 params.foundwrites = true;
1347 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001348 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001349 }
1350
Tao Bao0940fe12015-08-27 16:41:21 -07001351 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001352 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001353 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
Tianjie Xuaced5d92016-10-12 10:55:04 -07001354 Value patch_value(VAL_BLOB,
1355 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Tao Bao0940fe12015-08-27 16:41:21 -07001356 RangeSinkState rss(tgt);
1357 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001358 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001359 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001360
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001361 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1362 if (!discard_blocks(params.fd, offset, rss.p_remain)) {
1363 return -1;
1364 }
1365
1366 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001367 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001368 }
1369
Tao Bao0940fe12015-08-27 16:41:21 -07001370 if (params.cmdname[0] == 'i') { // imgdiff
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001371 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1372 &RangeSinkWrite, &rss, nullptr, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001373 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001374 return -1;
1375 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001376 } else {
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001377 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1378 0, &RangeSinkWrite, &rss, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001379 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001380 return -1;
1381 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001382 }
1383
1384 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001385 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001386 LOG(ERROR) << "range sink underrun?";
Sami Tolvanen90221202014-12-09 16:39:47 +00001387 }
1388 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001389 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size
1390 << " [" << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001391 }
1392 }
1393
Tao Baobaad2d42015-12-06 16:56:27 -08001394 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001395 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001396 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001397 }
1398
Tao Bao0940fe12015-08-27 16:41:21 -07001399 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001400
Tao Bao0940fe12015-08-27 16:41:21 -07001401 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001402}
1403
Tao Bao0940fe12015-08-27 16:41:21 -07001404static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001405 if (DEBUG_ERASE) {
1406 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001407 }
1408
Tao Bao0940fe12015-08-27 16:41:21 -07001409 struct stat sb;
1410 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001411 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001412 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001413 }
1414
Tao Bao0940fe12015-08-27 16:41:21 -07001415 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001416 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001417 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001418 }
1419
Tao Baobaad2d42015-12-06 16:56:27 -08001420 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001421 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001422 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001423 }
1424
Tao Baoc844c062016-12-28 15:15:55 -08001425 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001426
Tao Bao0940fe12015-08-27 16:41:21 -07001427 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001428 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001429
Tao Bao0940fe12015-08-27 16:41:21 -07001430 for (size_t i = 0; i < tgt.count; ++i) {
1431 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001432 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001433 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001434 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001435 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001436
Tao Bao0940fe12015-08-27 16:41:21 -07001437 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001438 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001439 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001440 }
1441 }
1442 }
1443
Tao Bao0940fe12015-08-27 16:41:21 -07001444 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001445}
1446
1447// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001448typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001449
Tao Bao612336d2015-08-27 16:41:21 -07001450struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001451 const char* name;
1452 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001453};
Sami Tolvanen90221202014-12-09 16:39:47 +00001454
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001455// args:
1456// - block device (or file) to modify in-place
1457// - transfer list (blob)
1458// - new data stream (filename within package.zip)
1459// - patch stream (filename within package.zip, must be uncompressed)
1460
Tao Bao0940fe12015-08-27 16:41:21 -07001461static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1462 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao73064612016-04-26 17:14:32 -07001463 CommandParameters params = {};
Sami Tolvanen90221202014-12-09 16:39:47 +00001464 params.canwrite = !dryrun;
1465
Tao Bao5354f602016-12-14 11:31:18 -08001466 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001467 if (state->is_retry) {
1468 is_retry = true;
Tao Bao039f2da2016-11-22 16:29:50 -08001469 LOG(INFO) << "This update is a retry.";
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001470 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001471
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001472 std::vector<std::unique_ptr<Value>> args;
1473 if (!ReadValueArgs(state, 4, argv, &args)) {
1474 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001475 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001476
1477 const Value* blockdev_filename = args[0].get();
1478 const Value* transfer_list_value = args[1].get();
1479 const Value* new_data_fn = args[2].get();
1480 const Value* patch_data_fn = args[3].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001481
1482 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001483 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1484 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001485 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001486 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001487 if (transfer_list_value->type != VAL_BLOB) {
Tianjie Xu16255832016-04-30 11:49:59 -07001488 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001489 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001490 }
1491 if (new_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001492 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001493 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001494 }
1495 if (patch_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001496 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string",
1497 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001498 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001499 }
1500
Tao Bao51412212016-12-28 14:44:05 -08001501 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
Tao Bao0940fe12015-08-27 16:41:21 -07001502 if (ui == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001503 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001504 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001505
Tao Bao612336d2015-08-27 16:41:21 -07001506 FILE* cmd_pipe = ui->cmd_pipe;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001507 ZipArchiveHandle za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001508
Tao Bao0940fe12015-08-27 16:41:21 -07001509 if (cmd_pipe == nullptr || za == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001510 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001511 }
1512
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001513 ZipString path_data(patch_data_fn->data.c_str());
1514 ZipEntry patch_entry;
1515 if (FindEntry(za, path_data, &patch_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001516 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001517 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001518 }
1519
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001520 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1521 ZipString new_data(new_data_fn->data.c_str());
1522 ZipEntry new_entry;
1523 if (FindEntry(za, new_data, &new_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001524 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001525 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001526 }
1527
Tianjie Xuaced5d92016-10-12 10:55:04 -07001528 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001529 if (params.fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001530 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001531 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001532 }
1533
Sami Tolvanen90221202014-12-09 16:39:47 +00001534 if (params.canwrite) {
1535 params.nti.za = za;
1536 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001537
Tao Bao0940fe12015-08-27 16:41:21 -07001538 pthread_mutex_init(&params.nti.mu, nullptr);
1539 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001540 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001541 pthread_attr_init(&attr);
1542 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1543
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001544 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1545 if (error != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001546 PLOG(ERROR) << "pthread_create failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001547 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001548 }
1549 }
1550
Tianjie Xuaced5d92016-10-12 10:55:04 -07001551 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001552 if (lines.size() < 2) {
Tianjie Xu16255832016-04-30 11:49:59 -07001553 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1554 lines.size());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001555 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001556 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001557
Sami Tolvanen90221202014-12-09 16:39:47 +00001558 // First line in transfer list is the version number
Tao Bao51412212016-12-28 14:44:05 -08001559 if (!android::base::ParseInt(lines[0], &params.version, 1, 4)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001560 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001561 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001562 }
1563
Tao Bao039f2da2016-11-22 16:29:50 -08001564 LOG(INFO) << "blockimg version is " << params.version;
Sami Tolvanen90221202014-12-09 16:39:47 +00001565
1566 // Second line in transfer list is the total number of blocks we expect to write
Tao Bao51412212016-12-28 14:44:05 -08001567 size_t total_blocks;
1568 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001569 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001570 return StringValue("");
Tao Baob15fd222015-09-24 11:10:51 -07001571 }
1572
1573 if (total_blocks == 0) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001574 return StringValue("t");
Sami Tolvanen90221202014-12-09 16:39:47 +00001575 }
1576
Tao Bao612336d2015-08-27 16:41:21 -07001577 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001578 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001579 if (lines.size() < 4) {
Tao Bao51412212016-12-28 14:44:05 -08001580 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1581 lines.size());
1582 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001583 }
1584
Sami Tolvanen90221202014-12-09 16:39:47 +00001585 // Third line is how many stash entries are needed simultaneously
Tao Bao039f2da2016-11-22 16:29:50 -08001586 LOG(INFO) << "maximum stash entries " << lines[2];
Doug Zongker52ae67d2014-09-08 12:22:09 -07001587
Sami Tolvanen90221202014-12-09 16:39:47 +00001588 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Bao51412212016-12-28 14:44:05 -08001589 size_t stash_max_blocks;
1590 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001591 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1592 lines[3].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001593 return StringValue("");
Doug Zongker52ae67d2014-09-08 12:22:09 -07001594 }
1595
Tao Bao51412212016-12-28 14:44:05 -08001596 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001597 if (res == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001598 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001599 }
Tao Bao612336d2015-08-27 16:41:21 -07001600
Tao Baob15fd222015-09-24 11:10:51 -07001601 params.createdstash = res;
1602
Tao Bao612336d2015-08-27 16:41:21 -07001603 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001604 }
1605
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001606 // Build a map of the available commands
1607 std::unordered_map<std::string, const Command*> cmd_map;
Tao Bao0940fe12015-08-27 16:41:21 -07001608 for (size_t i = 0; i < cmdcount; ++i) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001609 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001610 LOG(ERROR) << "Error: command [" << commands[i].name
1611 << "] already exists in the cmd map.";
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001612 return StringValue(strdup(""));
1613 }
1614 cmd_map[commands[i].name] = &commands[i];
Sami Tolvanen90221202014-12-09 16:39:47 +00001615 }
1616
Tao Bao612336d2015-08-27 16:41:21 -07001617 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001618
Tao Bao612336d2015-08-27 16:41:21 -07001619 // Subsequent lines are all individual transfer commands
1620 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
Tao Bao51412212016-12-28 14:44:05 -08001621 const std::string& line(*it);
1622 if (line.empty()) continue;
Tao Bao6a47dff2015-09-25 17:12:28 -07001623
Tao Bao51412212016-12-28 14:44:05 -08001624 params.tokens = android::base::Split(line, " ");
Tao Baobaad2d42015-12-06 16:56:27 -08001625 params.cpos = 0;
1626 params.cmdname = params.tokens[params.cpos++].c_str();
Tao Bao51412212016-12-28 14:44:05 -08001627 params.cmdline = line.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001628
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001629 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001630 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001631 goto pbiudone;
1632 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001633
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001634 const Command* cmd = cmd_map[params.cmdname];
1635
Tao Bao0940fe12015-08-27 16:41:21 -07001636 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao51412212016-12-28 14:44:05 -08001637 LOG(ERROR) << "failed to execute command [" << line << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001638 goto pbiudone;
1639 }
1640
Sami Tolvanen90221202014-12-09 16:39:47 +00001641 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001642 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001643 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001644 PLOG(ERROR) << "fsync failed";
Tao Bao187efff2015-07-27 14:07:08 -07001645 goto pbiudone;
1646 }
Tao Bao51412212016-12-28 14:44:05 -08001647 fprintf(cmd_pipe, "set_progress %.4f\n",
1648 static_cast<double>(params.written) / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001649 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001650 }
1651 }
1652
Sami Tolvanen90221202014-12-09 16:39:47 +00001653 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001654 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001655
Tao Bao039f2da2016-11-22 16:29:50 -08001656 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1657 LOG(INFO) << "stashed " << params.stashed << " blocks";
1658 LOG(INFO) << "max alloc needed was " << params.buffer.size();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001659
Tianjie Xuaced5d92016-10-12 10:55:04 -07001660 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
Tao Bao51412212016-12-28 14:44:05 -08001661 if (partition != nullptr && *(partition + 1) != 0) {
Tianjie Xudd874b12016-05-13 12:13:15 -07001662 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1663 params.written * BLOCKSIZE);
1664 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1665 params.stashed * BLOCKSIZE);
1666 fflush(cmd_pipe);
1667 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001668 // Delete stash only after successfully completing the update, as it
1669 // may contain blocks needed to complete the update later.
1670 DeleteStash(params.stashbase);
1671 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001672 LOG(INFO) << "verified partition contents; update may be resumed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001673 }
1674
1675 rc = 0;
1676
1677pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001678 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001679 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001680 PLOG(ERROR) << "fsync failed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001681 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001682 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001683
Sami Tolvanen90221202014-12-09 16:39:47 +00001684 // Only delete the stash if the update cannot be resumed, or it's
1685 // a verification run and we created the stash.
1686 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1687 DeleteStash(params.stashbase);
1688 }
1689
Tianjie Xu16255832016-04-30 11:49:59 -07001690 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1691 state->cause_code = failure_type;
1692 }
1693
Tianjie Xuaced5d92016-10-12 10:55:04 -07001694 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001695}
1696
1697// The transfer list is a text file containing commands to
1698// transfer data from one place to another on the target
1699// partition. We parse it and execute the commands in order:
1700//
1701// zero [rangeset]
1702// - fill the indicated blocks with zeros
1703//
1704// new [rangeset]
1705// - fill the blocks with data read from the new_data file
1706//
1707// erase [rangeset]
1708// - mark the given blocks as empty
1709//
1710// move <...>
1711// bsdiff <patchstart> <patchlen> <...>
1712// imgdiff <patchstart> <patchlen> <...>
1713// - read the source blocks, apply a patch (or not in the
1714// case of move), write result to target blocks. bsdiff or
1715// imgdiff specifies the type of patch; move means no patch
1716// at all.
1717//
1718// The format of <...> differs between versions 1 and 2;
1719// see the LoadSrcTgtVersion{1,2}() functions for a
1720// description of what's expected.
1721//
1722// stash <stash_id> <src_range>
1723// - (version 2+ only) load the given source range and stash
1724// the data in the given slot of the stash table.
1725//
Tao Baobaad2d42015-12-06 16:56:27 -08001726// free <stash_id>
1727// - (version 3+ only) free the given stash data.
1728//
Sami Tolvanen90221202014-12-09 16:39:47 +00001729// The creator of the transfer list will guarantee that no block
1730// is read (ie, used as the source for a patch or move) after it
1731// has been written.
1732//
1733// In version 2, the creator will guarantee that a given stash is
1734// loaded (with a stash command) before it's used in a
1735// move/bsdiff/imgdiff command.
1736//
1737// Within one command the source and target ranges may overlap so
1738// in general we need to read the entire source into memory before
1739// writing anything to the target blocks.
1740//
1741// All the patch data is concatenated into one patch_data file in
1742// the update package. It must be stored uncompressed because we
1743// memory-map it in directly from the archive. (Since patches are
1744// already compressed, we lose very little by not compressing
1745// their concatenation.)
1746//
1747// In version 3, commands that read data from the partition (i.e.
1748// move/bsdiff/imgdiff/stash) have one or more additional hashes
1749// before the range parameters, which are used to check if the
1750// command has already been completed and verify the integrity of
1751// the source data.
1752
1753Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001754 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001755 const Command commands[] = {
1756 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001757 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001758 { "free", PerformCommandFree },
1759 { "imgdiff", PerformCommandDiff },
1760 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001761 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001762 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001763 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001764 };
1765
1766 // Perform a dry run without writing to test if an update can proceed
1767 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001768 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001769}
1770
1771Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1772 const Command commands[] = {
1773 { "bsdiff", PerformCommandDiff },
1774 { "erase", PerformCommandErase },
1775 { "free", PerformCommandFree },
1776 { "imgdiff", PerformCommandDiff },
1777 { "move", PerformCommandMove },
1778 { "new", PerformCommandNew },
1779 { "stash", PerformCommandStash },
1780 { "zero", PerformCommandZero }
1781 };
1782
1783 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001784 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001785}
1786
Tao Bao0940fe12015-08-27 16:41:21 -07001787Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001788 std::vector<std::unique_ptr<Value>> args;
1789 if (!ReadValueArgs(state, 2, argv, &args)) {
1790 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001791 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001792
1793 const Value* blockdev_filename = args[0].get();
1794 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001795
1796 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001797 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1798 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001799 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001800 }
1801 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001802 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001803 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001804 }
1805
Tianjie Xuaced5d92016-10-12 10:55:04 -07001806 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001807 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001808 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1809 blockdev_filename->data.c_str(), strerror(errno));
1810 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001811 }
1812
Tao Baoc844c062016-12-28 15:15:55 -08001813 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001814
1815 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001816 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001817
Tao Bao612336d2015-08-27 16:41:21 -07001818 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001819 for (size_t i = 0; i < rs.count; ++i) {
1820 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001821 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1822 blockdev_filename->data.c_str(), strerror(errno));
1823 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001824 }
1825
Tao Bao0940fe12015-08-27 16:41:21 -07001826 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001827 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001828 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1829 blockdev_filename->data.c_str(), strerror(errno));
1830 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001831 }
1832
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001833 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001834 }
1835 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001836 uint8_t digest[SHA_DIGEST_LENGTH];
1837 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001838
Tianjie Xuaced5d92016-10-12 10:55:04 -07001839 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001840}
1841
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001842// This function checks if a device has been remounted R/W prior to an incremental
1843// OTA update. This is an common cause of update abortion. The function reads the
1844// 1st block of each partition and check for mounting time/count. It return string "t"
1845// if executes successfully and an empty string otherwise.
1846
1847Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001848 std::vector<std::unique_ptr<Value>> args;
1849 if (!ReadValueArgs(state, 1, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001850 return nullptr;
1851 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001852
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001853 const Value* arg_filename = args[0].get();
1854
1855 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001856 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001857 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001858 }
1859
Tianjie Xuaced5d92016-10-12 10:55:04 -07001860 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001861 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001862 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001863 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001864 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001865 }
1866
1867 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1868 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1869
1870 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001871 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001872 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001873 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001874 }
1875
1876 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1877 // Super block starts from block 0, offset 0x400
1878 // 0x2C: len32 Mount time
1879 // 0x30: len32 Write time
1880 // 0x34: len16 Number of mounts since the last fsck
1881 // 0x38: len16 Magic signature 0xEF53
1882
1883 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1884 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1885
1886 if (mount_count > 0) {
1887 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1888 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1889 }
1890
Tianjie Xuaced5d92016-10-12 10:55:04 -07001891 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001892}
1893
1894
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001895Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001896 std::vector<std::unique_ptr<Value>> args;
1897 if (!ReadValueArgs(state, 2, argv, &args)) {
1898 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001899 }
1900
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001901 const Value* filename = args[0].get();
1902 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001903
1904 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001905 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001906 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001907 }
1908 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001909 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001910 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001911 }
1912
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001913 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001914 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001915
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001916 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tianjie Xuaced5d92016-10-12 10:55:04 -07001917 fec::io fh(filename->data.c_str(), O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001918
1919 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001920 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001921 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001922 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001923 }
1924
1925 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001926 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001927 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001928 }
1929
1930 fec_status status;
1931
1932 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001933 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001934 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001935 }
1936
Tao Baoc844c062016-12-28 15:15:55 -08001937 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001938
1939 uint8_t buffer[BLOCKSIZE];
1940
1941 for (size_t i = 0; i < rs.count; ++i) {
1942 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1943 // Stay within the data area, libfec validates and corrects metadata
1944 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1945 continue;
1946 }
1947
1948 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001949 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001950 filename->data.c_str(), j, strerror(errno));
1951 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001952 }
1953
1954 // If we want to be able to recover from a situation where rewriting a corrected
1955 // block doesn't guarantee the same data will be returned when re-read later, we
1956 // can save a copy of corrected blocks to /cache. Note:
1957 //
1958 // 1. Maximum space required from /cache is the same as the maximum number of
1959 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1960 // this would be ~16 MiB, for example.
1961 //
1962 // 2. To find out if this block was corrupted, call fec_get_status after each
1963 // read and check if the errors field value has increased.
1964 }
1965 }
Tao Bao039f2da2016-11-22 16:29:50 -08001966 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001967 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001968}
1969
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001970void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001971 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001972 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001973 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001974 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001975 RegisterFunction("range_sha1", RangeSha1Fn);
1976}