blob: c2897a83ec2f229dd98dbe4184c43cdaa9bedc2f [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 Baoe6aa3322015-08-05 15:20:27 -070035#include <memory>
36#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070037#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070038#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070039
Tao Bao039f2da2016-11-22 16:29:50 -080040#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080041#include <android-base/parseint.h>
42#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070043#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080044#include <applypatch/applypatch.h>
45#include <openssl/sha.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070046#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070047
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070048#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070049#include "error_code.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070050#include "updater/install.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080051#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070052#include "print_sha1.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070053#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070054
Sami Tolvanene82fa182015-06-10 15:58:12 +000055// Set this to 0 to interpret 'erase' transfers to mean do a
56// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
57// erase to mean fill the region with zeroes.
58#define DEBUG_ERASE 0
59
Tao Bao51412212016-12-28 14:44:05 -080060static constexpr size_t BLOCKSIZE = 4096;
61static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
62static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
63static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000064
Tao Bao0940fe12015-08-27 16:41:21 -070065struct RangeSet {
Tao Baoc844c062016-12-28 15:15:55 -080066 size_t count; // Limit is INT_MAX.
67 size_t size;
68 std::vector<size_t> pos; // Actual limit is INT_MAX.
Tianjie Xubb0cd752017-01-06 17:46:22 -080069
70 // Get the block number for the ith(starting from 0) block in the range set.
71 int get_block(size_t idx) const {
72 if (idx >= size) {
73 LOG(ERROR) << "index: " << idx << " is greater than range set size: " << size;
74 return -1;
75 }
76 for (size_t i = 0; i < pos.size(); i += 2) {
77 if (idx < pos[i + 1] - pos[i]) {
78 return pos[i] + idx;
79 }
80 idx -= (pos[i + 1] - pos[i]);
81 }
82 return -1;
83 }
Tao Bao0940fe12015-08-27 16:41:21 -070084};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070085
Tianjie Xu16255832016-04-30 11:49:59 -070086static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070087static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070088static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070089
Tao Baoc844c062016-12-28 15:15:55 -080090static RangeSet parse_range(const std::string& range_text) {
91 RangeSet rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010092
Tao Baoc844c062016-12-28 15:15:55 -080093 std::vector<std::string> pieces = android::base::Split(range_text, ",");
94 if (pieces.size() < 3) {
95 goto err;
96 }
97
98 size_t num;
99 if (!android::base::ParseUint(pieces[0], &num, static_cast<size_t>(INT_MAX))) {
100 goto err;
101 }
102
103 if (num == 0 || num % 2) {
104 goto err; // must be even
105 } else if (num != pieces.size() - 1) {
106 goto err;
107 }
108
109 rs.pos.resize(num);
110 rs.count = num / 2;
111 rs.size = 0;
112
113 for (size_t i = 0; i < num; i += 2) {
114 if (!android::base::ParseUint(pieces[i + 1], &rs.pos[i], static_cast<size_t>(INT_MAX))) {
115 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100116 }
117
Tao Baoc844c062016-12-28 15:15:55 -0800118 if (!android::base::ParseUint(pieces[i + 2], &rs.pos[i + 1], static_cast<size_t>(INT_MAX))) {
119 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100120 }
121
Tao Baoc844c062016-12-28 15:15:55 -0800122 if (rs.pos[i] >= rs.pos[i + 1]) {
123 goto err; // empty or negative range
Tao Baob15fd222015-09-24 11:10:51 -0700124 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100125
Tao Baoc844c062016-12-28 15:15:55 -0800126 size_t sz = rs.pos[i + 1] - rs.pos[i];
127 if (rs.size > SIZE_MAX - sz) {
128 goto err; // overflow
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700129 }
130
Tao Baoc844c062016-12-28 15:15:55 -0800131 rs.size += sz;
132 }
133
134 return rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100135
136err:
Tao Baoc844c062016-12-28 15:15:55 -0800137 LOG(ERROR) << "failed to parse range '" << range_text << "'";
Tao Bao3da88012017-02-03 13:09:23 -0800138 exit(EXIT_FAILURE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700139}
140
Tao Baoe6aa3322015-08-05 15:20:27 -0700141static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Tao Baoc844c062016-12-28 15:15:55 -0800142 for (size_t i = 0; i < r1.count; ++i) {
143 size_t r1_0 = r1.pos[i * 2];
144 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000145
Tao Baoc844c062016-12-28 15:15:55 -0800146 for (size_t j = 0; j < r2.count; ++j) {
147 size_t r2_0 = r2.pos[j * 2];
148 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000149
Tao Baoc844c062016-12-28 15:15:55 -0800150 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
151 return true;
152 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000153 }
Tao Baoc844c062016-12-28 15:15:55 -0800154 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000155
Tao Baoc844c062016-12-28 15:15:55 -0800156 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000157}
158
159static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700160 size_t so_far = 0;
161 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800162 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700163 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700164 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800165 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000166 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700167 } else if (r == 0) {
168 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800169 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700170 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700171 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700172 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700173 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000174 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700175}
176
Tao Bao612336d2015-08-27 16:41:21 -0700177static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
178 return read_all(fd, buffer.data(), size);
179}
180
Sami Tolvanen90221202014-12-09 16:39:47 +0000181static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700182 size_t written = 0;
183 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800184 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700185 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700186 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800187 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000188 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700189 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700190 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700191 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000192
Sami Tolvanen90221202014-12-09 16:39:47 +0000193 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700194}
195
Tao Bao612336d2015-08-27 16:41:21 -0700196static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
197 return write_all(fd, buffer.data(), size);
198}
199
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700200static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
201 // Don't discard blocks unless the update is a retry run.
202 if (!is_retry) {
203 return true;
204 }
205
206 uint64_t args[2] = {static_cast<uint64_t>(offset), size};
207 int status = ioctl(fd, BLKDISCARD, &args);
208 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800209 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700210 return false;
211 }
212 return true;
213}
214
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700215static bool check_lseek(int fd, off64_t offset, int whence) {
216 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
217 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700218 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800219 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700220 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700221 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700222 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700223}
224
Tao Bao612336d2015-08-27 16:41:21 -0700225static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700226 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700227 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700228
Tao Bao612336d2015-08-27 16:41:21 -0700229 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700230}
231
Tao Bao0940fe12015-08-27 16:41:21 -0700232struct RangeSinkState {
Chih-Hung Hsieh49c5c792016-04-29 14:16:35 -0700233 explicit RangeSinkState(RangeSet& rs) : tgt(rs) { };
Tao Bao0940fe12015-08-27 16:41:21 -0700234
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700235 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700236 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530237 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700238 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700239};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700240
241static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700242 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700243
Tao Bao0940fe12015-08-27 16:41:21 -0700244 if (rss->p_remain == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800245 LOG(ERROR) << "range sink write overrun";
Sami Tolvanen90221202014-12-09 16:39:47 +0000246 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700247 }
248
249 ssize_t written = 0;
250 while (size > 0) {
251 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000252
253 if (rss->p_remain < write_now) {
254 write_now = rss->p_remain;
255 }
256
257 if (write_all(rss->fd, data, write_now) == -1) {
258 break;
259 }
260
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700261 data += write_now;
262 size -= write_now;
263
264 rss->p_remain -= write_now;
265 written += write_now;
266
267 if (rss->p_remain == 0) {
268 // move to the next block
269 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700270 if (rss->p_block < rss->tgt.count) {
271 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
272 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000273
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700274 off64_t offset = static_cast<off64_t>(rss->tgt.pos[rss->p_block*2]) * BLOCKSIZE;
275 if (!discard_blocks(rss->fd, offset, rss->p_remain)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000276 break;
277 }
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700278
279 if (!check_lseek(rss->fd, offset, SEEK_SET)) {
280 break;
281 }
282
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700283 } else {
284 // we can't write any more; return how many bytes have
285 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000286 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700287 }
288 }
289 }
290
291 return written;
292}
293
294// All of the data for all the 'new' transfers is contained in one
295// file in the update package, concatenated together in the order in
296// which transfers.list will need it. We want to stream it out of the
297// archive (it's compressed) without writing it to a temp file, but we
298// can't write each section until it's that transfer's turn to go.
299//
300// To achieve this, we expand the new data from the archive in a
301// background thread, and block that threads 'receive uncompressed
302// data' function until the main thread has reached a point where we
303// want some new data to be written. We signal the background thread
304// with the destination for the data and block the main thread,
305// waiting for the background thread to complete writing that section.
306// Then it signals the main thread to wake up and goes back to
307// blocking waiting for a transfer.
308//
309// NewThreadInfo is the struct used to pass information back and forth
310// between the two threads. When the main thread wants some data
311// written, it sets rss to the destination location and signals the
312// condition. When the background thread is done writing, it clears
313// rss and signals the condition again.
314
Tao Bao0940fe12015-08-27 16:41:21 -0700315struct NewThreadInfo {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700316 ZipArchiveHandle za;
317 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700318
319 RangeSinkState* rss;
320
321 pthread_mutex_t mu;
322 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700323};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700324
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700325static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700326 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700327
328 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700329 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700330 // data is wanted.
331 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700332 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700333 pthread_cond_wait(&nti->cv, &nti->mu);
334 }
335 pthread_mutex_unlock(&nti->mu);
336
337 // At this point nti->rss is set, and we own it. The main
338 // thread is waiting for it to disappear from nti.
339 ssize_t written = RangeSinkWrite(data, size, nti->rss);
340 data += written;
341 size -= written;
342
Tao Bao0940fe12015-08-27 16:41:21 -0700343 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700344 // we have written all the bytes desired by this rss.
345
346 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700347 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700348 pthread_cond_broadcast(&nti->cv);
349 pthread_mutex_unlock(&nti->mu);
350 }
351 }
352
353 return true;
354}
355
356static void* unzip_new_data(void* cookie) {
357 NewThreadInfo* nti = (NewThreadInfo*) cookie;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700358 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700359 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700360}
361
Tao Bao612336d2015-08-27 16:41:21 -0700362static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000363 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700364 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000365
Tao Bao0940fe12015-08-27 16:41:21 -0700366 for (size_t i = 0; i < src.count; ++i) {
367 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000368 return -1;
369 }
370
Tao Bao0940fe12015-08-27 16:41:21 -0700371 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000372
Tao Bao612336d2015-08-27 16:41:21 -0700373 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000374 return -1;
375 }
376
377 p += size;
378 }
379
380 return 0;
381}
382
Tao Bao612336d2015-08-27 16:41:21 -0700383static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
384 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000385
Tao Bao0940fe12015-08-27 16:41:21 -0700386 size_t p = 0;
387 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700388 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
389 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
390 if (!discard_blocks(fd, offset, size)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000391 return -1;
392 }
393
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700394 if (!check_lseek(fd, offset, SEEK_SET)) {
395 return -1;
396 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000397
Tao Bao612336d2015-08-27 16:41:21 -0700398 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000399 return -1;
400 }
401
402 p += size;
403 }
404
405 return 0;
406}
407
Tao Baobaad2d42015-12-06 16:56:27 -0800408// Parameters for transfer list command functions
409struct CommandParameters {
410 std::vector<std::string> tokens;
411 size_t cpos;
412 const char* cmdname;
413 const char* cmdline;
414 std::string freestash;
415 std::string stashbase;
416 bool canwrite;
417 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700418 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800419 bool foundwrites;
420 bool isunresumable;
421 int version;
422 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700423 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800424 NewThreadInfo nti;
425 pthread_t thread;
426 std::vector<uint8_t> buffer;
427 uint8_t* patch_start;
428};
429
Doug Zongker52ae67d2014-09-08 12:22:09 -0700430// Do a source/target load for move/bsdiff/imgdiff in version 1.
Tao Baobaad2d42015-12-06 16:56:27 -0800431// We expect to parse the remainder of the parameter tokens as:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700432//
433// <src_range> <tgt_range>
434//
435// The source range is loaded into the provided buffer, reallocating
Tao Bao34847b22015-09-08 11:05:49 -0700436// it to make it larger if necessary.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700437
Tao Baobaad2d42015-12-06 16:56:27 -0800438static int LoadSrcTgtVersion1(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700439 std::vector<uint8_t>& buffer, int fd) {
Tao Baobaad2d42015-12-06 16:56:27 -0800440
441 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800442 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -0800443 return -1;
444 }
445
Tao Bao612336d2015-08-27 16:41:21 -0700446 // <src_range>
Tao Baoc844c062016-12-28 15:15:55 -0800447 RangeSet src = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700448
Tao Bao612336d2015-08-27 16:41:21 -0700449 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -0800450 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700451
Tao Bao612336d2015-08-27 16:41:21 -0700452 allocate(src.size * BLOCKSIZE, buffer);
453 int rc = ReadBlocks(src, buffer, fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700454 src_blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000455
Sami Tolvanen90221202014-12-09 16:39:47 +0000456 return rc;
457}
458
Tianjie Xubb0cd752017-01-06 17:46:22 -0800459// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
460// handled separately).
461static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
462 const std::vector<uint8_t>& buffer) {
463 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
464 if (params.version < 3) {
465 // TODO handle version 1,2
466 LOG(WARNING) << "version number " << params.version << " is not supported to print hashes";
467 return;
468 }
469
470 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
471 params.tokens[0] == "imgdiff");
472
473 size_t pos = 0;
474 // Command example:
475 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
476 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
477 // [<loc_range> <stashed_blocks>]
478 if (params.tokens[0] == "move") {
479 // src_range for move starts at the 4th position.
480 if (params.tokens.size() < 5) {
481 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
482 return;
483 }
484 pos = 4;
485 } else {
486 // src_range for diff starts at the 7th position.
487 if (params.tokens.size() < 8) {
488 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
489 return;
490 }
491 pos = 7;
492 }
493
494 // Source blocks in stash only, no work to do.
495 if (params.tokens[pos] == "-") {
496 return;
497 }
498
499 RangeSet src = parse_range(params.tokens[pos++]);
500
501 RangeSet locs;
502 // If there's no stashed blocks, content in the buffer is consecutive and has the same
503 // order as the source blocks.
504 if (pos == params.tokens.size()) {
505 locs.count = 1;
506 locs.size = src.size;
507 locs.pos = { 0, src.size };
508 } else {
509 // Otherwise, the next token is the offset of the source blocks in the target range.
510 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
511 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
512 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
513 locs = parse_range(params.tokens[pos++]);
514 CHECK_EQ(src.size, locs.size);
515 CHECK_EQ(locs.pos.size() % 2, static_cast<size_t>(0));
516 }
517
518 LOG(INFO) << "printing hash in hex for " << src.size << " source blocks";
519 for (size_t i = 0; i < src.size; i++) {
520 int block_num = src.get_block(i);
521 CHECK_NE(block_num, -1);
522 int buffer_index = locs.get_block(i);
523 CHECK_NE(buffer_index, -1);
524 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
525
526 uint8_t digest[SHA_DIGEST_LENGTH];
527 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
528 std::string hexdigest = print_sha1(digest);
529 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
530 }
531}
532
533// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
534// in hex for each block.
535static void PrintHashForCorruptedStashedBlocks(const std::string& id,
536 const std::vector<uint8_t>& buffer,
537 const RangeSet& src) {
538 LOG(INFO) << "printing hash in hex for stash_id: " << id;
539 CHECK_EQ(src.size * BLOCKSIZE, buffer.size());
540
541 for (size_t i = 0; i < src.size; i++) {
542 int block_num = src.get_block(i);
543 CHECK_NE(block_num, -1);
544
545 uint8_t digest[SHA_DIGEST_LENGTH];
546 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
547 std::string hexdigest = print_sha1(digest);
548 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
549 }
550}
551
552// If the stash file doesn't exist, read the source blocks this stash contains and print the
553// SHA-1 for these blocks.
554static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
555 if (stash_map.find(id) == stash_map.end()) {
556 LOG(ERROR) << "No stash saved for id: " << id;
557 return;
558 }
559
560 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
561 const RangeSet& src = stash_map[id];
562 std::vector<uint8_t> buffer(src.size * BLOCKSIZE);
563 if (ReadBlocks(src, buffer, fd) == -1) {
564 LOG(ERROR) << "failed to read source blocks for stash: " << id;
565 return;
566 }
567 PrintHashForCorruptedStashedBlocks(id, buffer, src);
568}
569
Tao Bao612336d2015-08-27 16:41:21 -0700570static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700571 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800572 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700573 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000574
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800575 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000576
Tao Baoe6aa3322015-08-05 15:20:27 -0700577 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000578
Tao Bao0940fe12015-08-27 16:41:21 -0700579 if (hexdigest != expected) {
580 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800581 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
582 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700583 }
584 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000585 }
586
Tao Bao0940fe12015-08-27 16:41:21 -0700587 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000588}
589
Tao Bao0940fe12015-08-27 16:41:21 -0700590static std::string GetStashFileName(const std::string& base, const std::string& id,
591 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700592 if (base.empty()) {
593 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000594 }
595
Tao Baoe6aa3322015-08-05 15:20:27 -0700596 std::string fn(STASH_DIRECTORY_BASE);
597 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000598
599 return fn;
600}
601
Tao Baoe6aa3322015-08-05 15:20:27 -0700602typedef void (*StashCallback)(const std::string&, void*);
Sami Tolvanen90221202014-12-09 16:39:47 +0000603
604// Does a best effort enumeration of stash files. Ignores possible non-file
605// items in the stash directory and continues despite of errors. Calls the
606// 'callback' function for each file and passes 'data' to the function as a
607// parameter.
608
Tao Baoe6aa3322015-08-05 15:20:27 -0700609static void EnumerateStash(const std::string& dirname, StashCallback callback, void* data) {
Tao Bao0940fe12015-08-27 16:41:21 -0700610 if (dirname.empty() || callback == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000611 return;
612 }
613
Tao Baoe6aa3322015-08-05 15:20:27 -0700614 std::unique_ptr<DIR, int(*)(DIR*)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000615
Tao Bao0940fe12015-08-27 16:41:21 -0700616 if (directory == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000617 if (errno != ENOENT) {
Tao Bao039f2da2016-11-22 16:29:50 -0800618 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000619 }
620 return;
621 }
622
Tao Baoe6aa3322015-08-05 15:20:27 -0700623 struct dirent* item;
Tao Bao0940fe12015-08-27 16:41:21 -0700624 while ((item = readdir(directory.get())) != nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000625 if (item->d_type != DT_REG) {
626 continue;
627 }
628
Tao Baoe6aa3322015-08-05 15:20:27 -0700629 std::string fn = dirname + "/" + std::string(item->d_name);
Sami Tolvanen90221202014-12-09 16:39:47 +0000630 callback(fn, data);
Sami Tolvanen90221202014-12-09 16:39:47 +0000631 }
632}
633
Tao Baoe6aa3322015-08-05 15:20:27 -0700634static void UpdateFileSize(const std::string& fn, void* data) {
Tao Bao51412212016-12-28 14:44:05 -0800635 if (fn.empty() || !data) {
636 return;
637 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700638
Tao Bao51412212016-12-28 14:44:05 -0800639 struct stat sb;
640 if (stat(fn.c_str(), &sb) == -1) {
641 PLOG(ERROR) << "stat \"" << fn << "\" failed";
642 return;
643 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000644
Tao Bao51412212016-12-28 14:44:05 -0800645 size_t* size = static_cast<size_t*>(data);
646 *size += sb.st_size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000647}
648
649// Deletes the stash directory and all files in it. Assumes that it only
650// contains files. There is nothing we can do about unlikely, but possible
651// errors, so they are merely logged.
652
Tao Bao0940fe12015-08-27 16:41:21 -0700653static void DeleteFile(const std::string& fn, void* /* data */) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700654 if (!fn.empty()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800655 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000656
Tao Baoe6aa3322015-08-05 15:20:27 -0700657 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
Tao Bao039f2da2016-11-22 16:29:50 -0800658 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000659 }
660 }
661}
662
Tao Baoe6aa3322015-08-05 15:20:27 -0700663static void DeletePartial(const std::string& fn, void* data) {
664 if (android::base::EndsWith(fn, ".partial")) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000665 DeleteFile(fn, data);
666 }
667}
668
Tao Baoe6aa3322015-08-05 15:20:27 -0700669static void DeleteStash(const std::string& base) {
670 if (base.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000671 return;
672 }
673
Tao Bao039f2da2016-11-22 16:29:50 -0800674 LOG(INFO) << "deleting stash " << base;
Sami Tolvanen90221202014-12-09 16:39:47 +0000675
Tao Baoe6aa3322015-08-05 15:20:27 -0700676 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700677 EnumerateStash(dirname, DeleteFile, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000678
Tao Baoe6aa3322015-08-05 15:20:27 -0700679 if (rmdir(dirname.c_str()) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000680 if (errno != ENOENT && errno != ENOTDIR) {
Tao Bao039f2da2016-11-22 16:29:50 -0800681 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000682 }
683 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000684}
685
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700686static int LoadStash(CommandParameters& params, const std::string& base, const std::string& id,
687 bool verify, size_t* blocks, std::vector<uint8_t>& buffer, bool printnoent) {
688 // In verify mode, if source range_set was saved for the given hash,
689 // check contents in the source blocks first. If the check fails,
690 // search for the stashed files on /cache as usual.
691 if (!params.canwrite) {
692 if (stash_map.find(id) != stash_map.end()) {
693 const RangeSet& src = stash_map[id];
694 allocate(src.size * BLOCKSIZE, buffer);
695
696 if (ReadBlocks(src, buffer, params.fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800697 LOG(ERROR) << "failed to read source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700698 return -1;
699 }
700 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800701 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xubb0cd752017-01-06 17:46:22 -0800702 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700703 return -1;
704 }
705 return 0;
706 }
707 }
708
Tao Bao612336d2015-08-27 16:41:21 -0700709 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700710 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000711 }
712
Tao Bao0940fe12015-08-27 16:41:21 -0700713 size_t blockcount = 0;
714
Sami Tolvanen90221202014-12-09 16:39:47 +0000715 if (!blocks) {
716 blocks = &blockcount;
717 }
718
Tao Bao0940fe12015-08-27 16:41:21 -0700719 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000720
Tao Bao0940fe12015-08-27 16:41:21 -0700721 struct stat sb;
722 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000723
724 if (res == -1) {
725 if (errno != ENOENT || printnoent) {
Tao Bao039f2da2016-11-22 16:29:50 -0800726 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Tianjie Xubb0cd752017-01-06 17:46:22 -0800727 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000728 }
Tao Bao0940fe12015-08-27 16:41:21 -0700729 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000730 }
731
Tao Bao039f2da2016-11-22 16:29:50 -0800732 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000733
Tao Bao0940fe12015-08-27 16:41:21 -0700734 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800735 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
Tao Bao0940fe12015-08-27 16:41:21 -0700736 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000737 }
738
Elliott Hughesbcabd092016-03-22 20:19:22 -0700739 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000740 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800741 PLOG(ERROR) << "open \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700742 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000743 }
744
Tao Bao612336d2015-08-27 16:41:21 -0700745 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000746
Tao Bao612336d2015-08-27 16:41:21 -0700747 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700748 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000749 }
750
Tao Bao0940fe12015-08-27 16:41:21 -0700751 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000752
Tao Bao612336d2015-08-27 16:41:21 -0700753 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800754 LOG(ERROR) << "unexpected contents in " << fn;
Tianjie Xubb0cd752017-01-06 17:46:22 -0800755 if (stash_map.find(id) == stash_map.end()) {
756 LOG(ERROR) << "failed to find source blocks number for stash " << id
757 << " when executing command: " << params.cmdname;
758 } else {
759 const RangeSet& src = stash_map[id];
760 PrintHashForCorruptedStashedBlocks(id, buffer, src);
761 }
Tao Bao0940fe12015-08-27 16:41:21 -0700762 DeleteFile(fn, nullptr);
763 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000764 }
765
Tao Bao0940fe12015-08-27 16:41:21 -0700766 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000767}
768
Tao Bao612336d2015-08-27 16:41:21 -0700769static int WriteStash(const std::string& base, const std::string& id, int blocks,
770 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
771 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700772 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000773 }
774
775 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800776 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700777 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000778 }
779
Tao Bao0940fe12015-08-27 16:41:21 -0700780 std::string fn = GetStashFileName(base, id, ".partial");
781 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000782
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100783 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700784 struct stat sb;
785 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100786
787 if (res == 0) {
788 // The file already exists and since the name is the hash of the contents,
789 // it's safe to assume the contents are identical (accidental hash collisions
790 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800791 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700792 *exists = true;
793 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100794 }
795
Tao Bao0940fe12015-08-27 16:41:21 -0700796 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100797 }
798
Tao Bao039f2da2016-11-22 16:29:50 -0800799 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000800
Tao Bao039f2da2016-11-22 16:29:50 -0800801 android::base::unique_fd fd(
802 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000803 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800804 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700805 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000806 }
807
808 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700809 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000810 }
811
Jed Estepa7b9a462015-12-15 16:04:53 -0800812 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700813 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800814 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700815 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000816 }
817
Tao Baoe6aa3322015-08-05 15:20:27 -0700818 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800819 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700820 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000821 }
822
Tao Bao0940fe12015-08-27 16:41:21 -0700823 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700824 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
825 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700826 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700827 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800828 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700829 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700830 }
831
Jed Estepa7b9a462015-12-15 16:04:53 -0800832 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700833 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800834 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700835 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700836 }
837
Tao Bao0940fe12015-08-27 16:41:21 -0700838 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000839}
840
841// Creates a directory for storing stash files and checks if the /cache partition
842// hash enough space for the expected amount of blocks we need to store. Returns
843// >0 if we created the directory, zero if it existed already, and <0 of failure.
844
Tao Bao51412212016-12-28 14:44:05 -0800845static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
846 std::string& base) {
847 if (blockdev.empty()) {
848 return -1;
849 }
850
851 // Stash directory should be different for each partition to avoid conflicts
852 // when updating multiple partitions at the same time, so we use the hash of
853 // the block device name as the base directory
854 uint8_t digest[SHA_DIGEST_LENGTH];
855 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
856 base = print_sha1(digest);
857
858 std::string dirname = GetStashFileName(base, "", "");
859 struct stat sb;
860 int res = stat(dirname.c_str(), &sb);
861 size_t max_stash_size = maxblocks * BLOCKSIZE;
862
863 if (res == -1 && errno != ENOENT) {
864 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
865 strerror(errno));
866 return -1;
867 } else if (res != 0) {
868 LOG(INFO) << "creating stash " << dirname;
869 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
870
871 if (res != 0) {
872 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
873 strerror(errno));
874 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000875 }
876
Tao Bao51412212016-12-28 14:44:05 -0800877 if (CacheSizeCheck(max_stash_size) != 0) {
878 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
879 max_stash_size);
880 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000881 }
882
Tao Bao51412212016-12-28 14:44:05 -0800883 return 1; // Created directory
884 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000885
Tao Bao51412212016-12-28 14:44:05 -0800886 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000887
Tao Bao51412212016-12-28 14:44:05 -0800888 // If the directory already exists, calculate the space already allocated to
889 // stash files and check if there's enough for all required blocks. Delete any
890 // partially completed stash files first.
Sami Tolvanen90221202014-12-09 16:39:47 +0000891
Tao Bao51412212016-12-28 14:44:05 -0800892 EnumerateStash(dirname, DeletePartial, nullptr);
893 size_t existing = 0;
894 EnumerateStash(dirname, UpdateFileSize, &existing);
Sami Tolvanen90221202014-12-09 16:39:47 +0000895
Tao Bao51412212016-12-28 14:44:05 -0800896 if (max_stash_size > existing) {
897 size_t needed = max_stash_size - existing;
898 if (CacheSizeCheck(needed) != 0) {
899 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
900 needed);
901 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000902 }
Tao Bao51412212016-12-28 14:44:05 -0800903 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000904
Tao Bao51412212016-12-28 14:44:05 -0800905 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000906}
907
Tao Baobaad2d42015-12-06 16:56:27 -0800908static int SaveStash(CommandParameters& params, const std::string& base,
909 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000910
Tao Baobaad2d42015-12-06 16:56:27 -0800911 // <stash_id> <src_range>
912 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800913 LOG(ERROR) << "missing id and/or src range fields in stash command";
Sami Tolvanen90221202014-12-09 16:39:47 +0000914 return -1;
915 }
Tao Baobaad2d42015-12-06 16:56:27 -0800916 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000917
Tao Bao0940fe12015-08-27 16:41:21 -0700918 size_t blocks = 0;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700919 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000920 // Stash file already exists and has expected contents. Do not
921 // read from source again, as the source may have been already
922 // overwritten during a previous attempt.
923 return 0;
924 }
925
Tao Baoc844c062016-12-28 15:15:55 -0800926 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao34847b22015-09-08 11:05:49 -0700927
Tao Bao612336d2015-08-27 16:41:21 -0700928 allocate(src.size * BLOCKSIZE, buffer);
929 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000930 return -1;
931 }
Tao Bao34847b22015-09-08 11:05:49 -0700932 blocks = src.size;
Tianjie Xubb0cd752017-01-06 17:46:22 -0800933 stash_map[id] = src;
Sami Tolvanen90221202014-12-09 16:39:47 +0000934
Tao Bao612336d2015-08-27 16:41:21 -0700935 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000936 // Source blocks have unexpected contents. If we actually need this
937 // data later, this is an unrecoverable error. However, the command
938 // that uses the data may have already completed previously, so the
939 // possible failure will occur during source block verification.
Tao Bao039f2da2016-11-22 16:29:50 -0800940 LOG(ERROR) << "failed to load source blocks for stash " << id;
Sami Tolvanen90221202014-12-09 16:39:47 +0000941 return 0;
942 }
943
Tianjie Xubb0cd752017-01-06 17:46:22 -0800944 // In verify mode, we don't need to stash any blocks.
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700945 if (!params.canwrite && usehash) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700946 return 0;
947 }
948
Tao Bao039f2da2016-11-22 16:29:50 -0800949 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xudd874b12016-05-13 12:13:15 -0700950 params.stashed += blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700951 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000952}
953
Tao Baobaad2d42015-12-06 16:56:27 -0800954static int FreeStash(const std::string& base, const std::string& id) {
955 if (base.empty() || id.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000956 return -1;
957 }
958
Tao Baobaad2d42015-12-06 16:56:27 -0800959 std::string fn = GetStashFileName(base, id, "");
Tao Bao0940fe12015-08-27 16:41:21 -0700960 DeleteFile(fn, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000961
962 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700963}
964
Tao Bao612336d2015-08-27 16:41:21 -0700965static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
966 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700967 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700968 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700969 // may be the same buffer.
970
Tao Bao612336d2015-08-27 16:41:21 -0700971 const uint8_t* from = source.data();
972 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700973 size_t start = locs.size;
974 for (int i = locs.count-1; i >= 0; --i) {
975 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700976 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700977 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700978 blocks * BLOCKSIZE);
979 }
980}
981
982// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800983// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700984//
985// <tgt_range> <src_block_count> <src_range>
986// (loads data from source image only)
987//
988// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
989// (loads data from stashes only)
990//
991// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
992// (loads data from both source image and stashes)
993//
994// On return, buffer is filled with the loaded source data (rearranged
995// and combined with stashed data as necessary). buffer may be
996// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000997// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700998
Tao Baobaad2d42015-12-06 16:56:27 -0800999static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -07001000 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -08001001
1002 // At least it needs to provide three parameters: <tgt_range>,
1003 // <src_block_count> and "-"/<src_range>.
1004 if (params.cpos + 2 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001005 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -08001006 return -1;
1007 }
1008
Tao Bao612336d2015-08-27 16:41:21 -07001009 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -08001010 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001011
Tao Bao612336d2015-08-27 16:41:21 -07001012 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -08001013 const std::string& token = params.tokens[params.cpos++];
1014 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001015 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
Tao Baobaad2d42015-12-06 16:56:27 -08001016 return -1;
1017 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001018
Tao Bao612336d2015-08-27 16:41:21 -07001019 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001020
Tao Bao612336d2015-08-27 16:41:21 -07001021 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -08001022 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -07001023 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -08001024 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001025 } else {
Tao Baoc844c062016-12-28 15:15:55 -08001026 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -07001027 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001028
Tao Bao34847b22015-09-08 11:05:49 -07001029 if (overlap) {
1030 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001031 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001032
Sami Tolvanen90221202014-12-09 16:39:47 +00001033 if (res == -1) {
1034 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001035 }
1036
Tao Baobaad2d42015-12-06 16:56:27 -08001037 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001038 // no stashes, only source range
1039 return 0;
1040 }
1041
Tao Baoc844c062016-12-28 15:15:55 -08001042 RangeSet locs = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -07001043 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001044 }
1045
Tao Baobaad2d42015-12-06 16:56:27 -08001046 // <[stash_id:stash_range]>
1047 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -07001048 // Each word is a an index into the stash table, a colon, and
1049 // then a rangeset describing where in the source block that
1050 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -08001051 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1052 if (tokens.size() != 2) {
Tao Bao039f2da2016-11-22 16:29:50 -08001053 LOG(ERROR) << "invalid parameter";
Tao Baobaad2d42015-12-06 16:56:27 -08001054 return -1;
1055 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001056
Tao Bao612336d2015-08-27 16:41:21 -07001057 std::vector<uint8_t> stash;
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001058 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001059
1060 if (res == -1) {
1061 // These source blocks will fail verification if used later, but we
1062 // will let the caller decide if this is a fatal failure
Tao Bao039f2da2016-11-22 16:29:50 -08001063 LOG(ERROR) << "failed to load stash " << tokens[0];
Sami Tolvanen90221202014-12-09 16:39:47 +00001064 continue;
1065 }
1066
Tao Baoc844c062016-12-28 15:15:55 -08001067 RangeSet locs = parse_range(tokens[1]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001068
Tao Bao612336d2015-08-27 16:41:21 -07001069 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +00001070 }
1071
1072 return 0;
1073}
1074
Sami Tolvanen90221202014-12-09 16:39:47 +00001075// Do a source/target load for move/bsdiff/imgdiff in version 3.
1076//
1077// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
1078// tells the function whether to expect separate source and targe block hashes, or
1079// if they are both the same and only one hash should be expected, and
1080// 'isunresumable', which receives a non-zero value if block verification fails in
1081// a way that the update cannot be resumed anymore.
1082//
1083// If the function is unable to load the necessary blocks or their contents don't
1084// match the hashes, the return value is -1 and the command should be aborted.
1085//
1086// If the return value is 1, the command has already been completed according to
1087// the contents of the target blocks, and should not be performed again.
1088//
1089// If the return value is 0, source blocks have expected content and the command
1090// can be performed.
1091
Tao Bao34847b22015-09-08 11:05:49 -07001092static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -07001093 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001094
Tao Baobaad2d42015-12-06 16:56:27 -08001095 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001096 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001097 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001098 }
1099
Tao Baobaad2d42015-12-06 16:56:27 -08001100 std::string srchash = params.tokens[params.cpos++];
1101 std::string tgthash;
1102
Sami Tolvanen90221202014-12-09 16:39:47 +00001103 if (onehash) {
1104 tgthash = srchash;
1105 } else {
Tao Baobaad2d42015-12-06 16:56:27 -08001106 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001107 LOG(ERROR) << "missing target hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001108 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001109 }
Tao Baobaad2d42015-12-06 16:56:27 -08001110 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +00001111 }
1112
Elliott Hughesbcabd092016-03-22 20:19:22 -07001113 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd,
1114 params.stashbase, &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -07001115 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001116 }
1117
Tao Bao34847b22015-09-08 11:05:49 -07001118 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001119
Tao Bao612336d2015-08-27 16:41:21 -07001120 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -07001121 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001122 }
1123
Tao Bao612336d2015-08-27 16:41:21 -07001124 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001125 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -07001126 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001127 }
1128
Tao Bao0940fe12015-08-27 16:41:21 -07001129 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001130 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001131 // resume from possible write errors. In verify mode, we can skip stashing
1132 // because the source blocks won't be overwritten.
1133 if (overlap && params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001134 LOG(INFO) << "stashing " << src_blocks << " overlapping blocks to " << srchash;
Sami Tolvanen90221202014-12-09 16:39:47 +00001135
Tao Bao0940fe12015-08-27 16:41:21 -07001136 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -07001137 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -07001138 &stash_exists) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001139 LOG(ERROR) << "failed to stash overlapping source blocks";
Tao Bao0940fe12015-08-27 16:41:21 -07001140 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001141 }
1142
Tianjie Xudd874b12016-05-13 12:13:15 -07001143 params.stashed += src_blocks;
Sami Tolvanen90221202014-12-09 16:39:47 +00001144 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001145 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -07001146 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001147 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001148 }
1149
1150 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -07001151 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001152 }
1153
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001154 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
1155 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001156 // Overlapping source blocks were previously stashed, command can proceed.
1157 // We are recovering from an interrupted command, so we don't know if the
1158 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -07001159 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001160 }
1161
1162 // Valid source data not available, update cannot be resumed
Tao Bao039f2da2016-11-22 16:29:50 -08001163 LOG(ERROR) << "partition has unexpected contents";
Tianjie Xubb0cd752017-01-06 17:46:22 -08001164 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1165
Tao Bao0940fe12015-08-27 16:41:21 -07001166 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +00001167
Tao Bao0940fe12015-08-27 16:41:21 -07001168 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001169}
1170
Tao Bao0940fe12015-08-27 16:41:21 -07001171static int PerformCommandMove(CommandParameters& params) {
1172 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001173 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001174 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001175 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001176
Tao Bao0940fe12015-08-27 16:41:21 -07001177 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001178 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001179 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001180 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001181 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001182 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001183 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001184 }
1185
1186 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001187 LOG(ERROR) << "failed to read blocks for move";
Tao Bao0940fe12015-08-27 16:41:21 -07001188 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001189 }
1190
1191 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001192 params.foundwrites = true;
1193 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001194 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001195 }
1196
Tao Bao0940fe12015-08-27 16:41:21 -07001197 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001198 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001199 LOG(INFO) << " moving " << blocks << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001200
Tao Bao0940fe12015-08-27 16:41:21 -07001201 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1202 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001203 }
1204 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001205 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001206 }
1207
1208 }
1209
Tao Baobaad2d42015-12-06 16:56:27 -08001210 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001211 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001212 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001213 }
1214
Tao Bao0940fe12015-08-27 16:41:21 -07001215 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001216
Tao Bao0940fe12015-08-27 16:41:21 -07001217 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001218}
1219
Tao Bao0940fe12015-08-27 16:41:21 -07001220static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001221 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001222 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001223}
1224
Tao Bao0940fe12015-08-27 16:41:21 -07001225static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001226 // <stash_id>
1227 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001228 LOG(ERROR) << "missing stash id in free command";
Tao Baobaad2d42015-12-06 16:56:27 -08001229 return -1;
1230 }
1231
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001232 const std::string& id = params.tokens[params.cpos++];
1233
Tianjie Xubb0cd752017-01-06 17:46:22 -08001234 if (stash_map.find(id) != stash_map.end()) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001235 stash_map.erase(id);
1236 return 0;
1237 }
1238
Tao Bao0940fe12015-08-27 16:41:21 -07001239 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001240 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001241 }
1242
1243 return 0;
1244}
1245
Tao Bao0940fe12015-08-27 16:41:21 -07001246static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001247
Tao Baobaad2d42015-12-06 16:56:27 -08001248 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001249 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001250 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001251 }
1252
Tao Baoc844c062016-12-28 15:15:55 -08001253 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001254
Tao Bao039f2da2016-11-22 16:29:50 -08001255 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001256
Tao Bao612336d2015-08-27 16:41:21 -07001257 allocate(BLOCKSIZE, params.buffer);
1258 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001259
Tao Bao0940fe12015-08-27 16:41:21 -07001260 if (params.canwrite) {
1261 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001262 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1263 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1264 if (!discard_blocks(params.fd, offset, size)) {
1265 return -1;
1266 }
1267
1268 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001269 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001270 }
1271
Tao Bao0940fe12015-08-27 16:41:21 -07001272 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1273 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1274 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001275 }
1276 }
1277 }
1278 }
1279
Tao Bao0940fe12015-08-27 16:41:21 -07001280 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001281 // Update only for the zero command, as the erase command will call
1282 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001283 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001284 }
1285
Tao Bao0940fe12015-08-27 16:41:21 -07001286 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001287}
1288
Tao Bao0940fe12015-08-27 16:41:21 -07001289static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001290
Tao Baobaad2d42015-12-06 16:56:27 -08001291 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001292 LOG(ERROR) << "missing target blocks for new";
Tao Bao0940fe12015-08-27 16:41:21 -07001293 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001294 }
1295
Tao Baoc844c062016-12-28 15:15:55 -08001296 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001297
Tao Bao0940fe12015-08-27 16:41:21 -07001298 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001299 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
Sami Tolvanen90221202014-12-09 16:39:47 +00001300
Tao Bao0940fe12015-08-27 16:41:21 -07001301 RangeSinkState rss(tgt);
1302 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001303 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001304 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001305
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001306 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1307 if (!discard_blocks(params.fd, offset, tgt.size * BLOCKSIZE)) {
1308 return -1;
1309 }
1310
1311 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001312 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001313 }
1314
Tao Bao0940fe12015-08-27 16:41:21 -07001315 pthread_mutex_lock(&params.nti.mu);
1316 params.nti.rss = &rss;
1317 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001318
Tao Bao0940fe12015-08-27 16:41:21 -07001319 while (params.nti.rss) {
1320 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001321 }
1322
Tao Bao0940fe12015-08-27 16:41:21 -07001323 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001324 }
1325
Tao Bao0940fe12015-08-27 16:41:21 -07001326 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001327
Tao Bao0940fe12015-08-27 16:41:21 -07001328 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001329}
1330
Tao Bao0940fe12015-08-27 16:41:21 -07001331static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001332
Tao Baobaad2d42015-12-06 16:56:27 -08001333 // <offset> <length>
1334 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001335 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
Tao Bao0940fe12015-08-27 16:41:21 -07001336 return -1;
1337 }
1338
Tao Baobaad2d42015-12-06 16:56:27 -08001339 size_t offset;
1340 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001341 LOG(ERROR) << "invalid patch offset";
Tao Bao0940fe12015-08-27 16:41:21 -07001342 return -1;
1343 }
1344
Tao Baobaad2d42015-12-06 16:56:27 -08001345 size_t len;
1346 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001347 LOG(ERROR) << "invalid patch len";
Tao Baobaad2d42015-12-06 16:56:27 -08001348 return -1;
1349 }
Tao Bao0940fe12015-08-27 16:41:21 -07001350
Tao Bao612336d2015-08-27 16:41:21 -07001351 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001352 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001353 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001354 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001355 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001356 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001357 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001358 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001359 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001360 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001361 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001362 }
1363
1364 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001365 LOG(ERROR) << "failed to read blocks for diff";
Tao Bao0940fe12015-08-27 16:41:21 -07001366 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001367 }
1368
1369 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001370 params.foundwrites = true;
1371 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001372 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001373 }
1374
Tao Bao0940fe12015-08-27 16:41:21 -07001375 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001376 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001377 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001378
Tianjie Xuaced5d92016-10-12 10:55:04 -07001379 Value patch_value(VAL_BLOB,
1380 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001381
Tao Bao0940fe12015-08-27 16:41:21 -07001382 RangeSinkState rss(tgt);
1383 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001384 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001385 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001386
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001387 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1388 if (!discard_blocks(params.fd, offset, rss.p_remain)) {
1389 return -1;
1390 }
1391
1392 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001393 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001394 }
1395
Tao Bao0940fe12015-08-27 16:41:21 -07001396 if (params.cmdname[0] == 'i') { // imgdiff
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001397 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1398 &RangeSinkWrite, &rss, nullptr, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001399 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001400 return -1;
1401 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001402 } else {
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001403 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1404 0, &RangeSinkWrite, &rss, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001405 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001406 return -1;
1407 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001408 }
1409
1410 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001411 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001412 LOG(ERROR) << "range sink underrun?";
Sami Tolvanen90221202014-12-09 16:39:47 +00001413 }
1414 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001415 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size
1416 << " [" << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001417 }
1418 }
1419
Tao Baobaad2d42015-12-06 16:56:27 -08001420 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001421 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001422 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001423 }
1424
Tao Bao0940fe12015-08-27 16:41:21 -07001425 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001426
Tao Bao0940fe12015-08-27 16:41:21 -07001427 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001428}
1429
Tao Bao0940fe12015-08-27 16:41:21 -07001430static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001431 if (DEBUG_ERASE) {
1432 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001433 }
1434
Tao Bao0940fe12015-08-27 16:41:21 -07001435 struct stat sb;
1436 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001437 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001438 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001439 }
1440
Tao Bao0940fe12015-08-27 16:41:21 -07001441 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001442 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001443 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001444 }
1445
Tao Baobaad2d42015-12-06 16:56:27 -08001446 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001447 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001448 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001449 }
1450
Tao Baoc844c062016-12-28 15:15:55 -08001451 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001452
Tao Bao0940fe12015-08-27 16:41:21 -07001453 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001454 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001455
Tao Bao0940fe12015-08-27 16:41:21 -07001456 for (size_t i = 0; i < tgt.count; ++i) {
1457 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001458 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001459 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001460 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001461 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001462
Tao Bao0940fe12015-08-27 16:41:21 -07001463 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001464 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001465 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001466 }
1467 }
1468 }
1469
Tao Bao0940fe12015-08-27 16:41:21 -07001470 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001471}
1472
1473// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001474typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001475
Tao Bao612336d2015-08-27 16:41:21 -07001476struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001477 const char* name;
1478 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001479};
Sami Tolvanen90221202014-12-09 16:39:47 +00001480
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001481// args:
1482// - block device (or file) to modify in-place
1483// - transfer list (blob)
1484// - new data stream (filename within package.zip)
1485// - patch stream (filename within package.zip, must be uncompressed)
1486
Tao Bao0940fe12015-08-27 16:41:21 -07001487static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1488 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao73064612016-04-26 17:14:32 -07001489 CommandParameters params = {};
Sami Tolvanen90221202014-12-09 16:39:47 +00001490 params.canwrite = !dryrun;
1491
Tao Bao5354f602016-12-14 11:31:18 -08001492 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001493 if (state->is_retry) {
1494 is_retry = true;
Tao Bao039f2da2016-11-22 16:29:50 -08001495 LOG(INFO) << "This update is a retry.";
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001496 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001497
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001498 std::vector<std::unique_ptr<Value>> args;
1499 if (!ReadValueArgs(state, 4, argv, &args)) {
1500 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001501 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001502
1503 const Value* blockdev_filename = args[0].get();
1504 const Value* transfer_list_value = args[1].get();
1505 const Value* new_data_fn = args[2].get();
1506 const Value* patch_data_fn = args[3].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001507
1508 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001509 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1510 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001511 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001512 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001513 if (transfer_list_value->type != VAL_BLOB) {
Tianjie Xu16255832016-04-30 11:49:59 -07001514 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001515 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001516 }
1517 if (new_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001518 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001519 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001520 }
1521 if (patch_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001522 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string",
1523 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001524 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001525 }
1526
Tao Bao51412212016-12-28 14:44:05 -08001527 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
Tao Bao0940fe12015-08-27 16:41:21 -07001528 if (ui == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001529 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001530 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001531
Tao Bao612336d2015-08-27 16:41:21 -07001532 FILE* cmd_pipe = ui->cmd_pipe;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001533 ZipArchiveHandle za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001534
Tao Bao0940fe12015-08-27 16:41:21 -07001535 if (cmd_pipe == nullptr || za == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001536 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001537 }
1538
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001539 ZipString path_data(patch_data_fn->data.c_str());
1540 ZipEntry patch_entry;
1541 if (FindEntry(za, path_data, &patch_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001542 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001543 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001544 }
1545
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001546 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1547 ZipString new_data(new_data_fn->data.c_str());
1548 ZipEntry new_entry;
1549 if (FindEntry(za, new_data, &new_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001550 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001551 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001552 }
1553
Tianjie Xuaced5d92016-10-12 10:55:04 -07001554 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001555 if (params.fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001556 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001557 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001558 }
1559
Sami Tolvanen90221202014-12-09 16:39:47 +00001560 if (params.canwrite) {
1561 params.nti.za = za;
1562 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001563
Tao Bao0940fe12015-08-27 16:41:21 -07001564 pthread_mutex_init(&params.nti.mu, nullptr);
1565 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001566 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001567 pthread_attr_init(&attr);
1568 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1569
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001570 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1571 if (error != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001572 PLOG(ERROR) << "pthread_create failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001573 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001574 }
1575 }
1576
Tianjie Xuaced5d92016-10-12 10:55:04 -07001577 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001578 if (lines.size() < 2) {
Tianjie Xu16255832016-04-30 11:49:59 -07001579 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1580 lines.size());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001581 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001582 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001583
Sami Tolvanen90221202014-12-09 16:39:47 +00001584 // First line in transfer list is the version number
Tao Bao51412212016-12-28 14:44:05 -08001585 if (!android::base::ParseInt(lines[0], &params.version, 1, 4)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001586 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001587 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001588 }
1589
Tao Bao039f2da2016-11-22 16:29:50 -08001590 LOG(INFO) << "blockimg version is " << params.version;
Sami Tolvanen90221202014-12-09 16:39:47 +00001591
1592 // Second line in transfer list is the total number of blocks we expect to write
Tao Bao51412212016-12-28 14:44:05 -08001593 size_t total_blocks;
1594 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001595 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001596 return StringValue("");
Tao Baob15fd222015-09-24 11:10:51 -07001597 }
1598
1599 if (total_blocks == 0) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001600 return StringValue("t");
Sami Tolvanen90221202014-12-09 16:39:47 +00001601 }
1602
Tao Bao612336d2015-08-27 16:41:21 -07001603 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001604 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001605 if (lines.size() < 4) {
Tao Bao51412212016-12-28 14:44:05 -08001606 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1607 lines.size());
1608 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001609 }
1610
Sami Tolvanen90221202014-12-09 16:39:47 +00001611 // Third line is how many stash entries are needed simultaneously
Tao Bao039f2da2016-11-22 16:29:50 -08001612 LOG(INFO) << "maximum stash entries " << lines[2];
Doug Zongker52ae67d2014-09-08 12:22:09 -07001613
Sami Tolvanen90221202014-12-09 16:39:47 +00001614 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Bao51412212016-12-28 14:44:05 -08001615 size_t stash_max_blocks;
1616 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001617 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1618 lines[3].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001619 return StringValue("");
Doug Zongker52ae67d2014-09-08 12:22:09 -07001620 }
1621
Tao Bao51412212016-12-28 14:44:05 -08001622 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001623 if (res == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001624 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001625 }
Tao Bao612336d2015-08-27 16:41:21 -07001626
Tao Baob15fd222015-09-24 11:10:51 -07001627 params.createdstash = res;
1628
Tao Bao612336d2015-08-27 16:41:21 -07001629 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001630 }
1631
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001632 // Build a map of the available commands
1633 std::unordered_map<std::string, const Command*> cmd_map;
Tao Bao0940fe12015-08-27 16:41:21 -07001634 for (size_t i = 0; i < cmdcount; ++i) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001635 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001636 LOG(ERROR) << "Error: command [" << commands[i].name
1637 << "] already exists in the cmd map.";
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001638 return StringValue(strdup(""));
1639 }
1640 cmd_map[commands[i].name] = &commands[i];
Sami Tolvanen90221202014-12-09 16:39:47 +00001641 }
1642
Tao Bao612336d2015-08-27 16:41:21 -07001643 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001644
Tao Bao612336d2015-08-27 16:41:21 -07001645 // Subsequent lines are all individual transfer commands
1646 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
Tao Bao51412212016-12-28 14:44:05 -08001647 const std::string& line(*it);
1648 if (line.empty()) continue;
Tao Bao6a47dff2015-09-25 17:12:28 -07001649
Tao Bao51412212016-12-28 14:44:05 -08001650 params.tokens = android::base::Split(line, " ");
Tao Baobaad2d42015-12-06 16:56:27 -08001651 params.cpos = 0;
1652 params.cmdname = params.tokens[params.cpos++].c_str();
Tao Bao51412212016-12-28 14:44:05 -08001653 params.cmdline = line.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001654
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001655 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001656 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001657 goto pbiudone;
1658 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001659
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001660 const Command* cmd = cmd_map[params.cmdname];
1661
Tao Bao0940fe12015-08-27 16:41:21 -07001662 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao51412212016-12-28 14:44:05 -08001663 LOG(ERROR) << "failed to execute command [" << line << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001664 goto pbiudone;
1665 }
1666
Sami Tolvanen90221202014-12-09 16:39:47 +00001667 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001668 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001669 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001670 PLOG(ERROR) << "fsync failed";
Tao Bao187efff2015-07-27 14:07:08 -07001671 goto pbiudone;
1672 }
Tao Bao51412212016-12-28 14:44:05 -08001673 fprintf(cmd_pipe, "set_progress %.4f\n",
1674 static_cast<double>(params.written) / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001675 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001676 }
1677 }
1678
Sami Tolvanen90221202014-12-09 16:39:47 +00001679 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001680 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001681
Tao Bao039f2da2016-11-22 16:29:50 -08001682 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1683 LOG(INFO) << "stashed " << params.stashed << " blocks";
1684 LOG(INFO) << "max alloc needed was " << params.buffer.size();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001685
Tianjie Xuaced5d92016-10-12 10:55:04 -07001686 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
Tao Bao51412212016-12-28 14:44:05 -08001687 if (partition != nullptr && *(partition + 1) != 0) {
Tianjie Xudd874b12016-05-13 12:13:15 -07001688 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1689 params.written * BLOCKSIZE);
1690 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1691 params.stashed * BLOCKSIZE);
1692 fflush(cmd_pipe);
1693 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001694 // Delete stash only after successfully completing the update, as it
1695 // may contain blocks needed to complete the update later.
1696 DeleteStash(params.stashbase);
1697 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001698 LOG(INFO) << "verified partition contents; update may be resumed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001699 }
1700
1701 rc = 0;
1702
1703pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001704 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001705 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001706 PLOG(ERROR) << "fsync failed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001707 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001708 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001709
Sami Tolvanen90221202014-12-09 16:39:47 +00001710 // Only delete the stash if the update cannot be resumed, or it's
1711 // a verification run and we created the stash.
1712 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1713 DeleteStash(params.stashbase);
1714 }
1715
Tianjie Xu16255832016-04-30 11:49:59 -07001716 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1717 state->cause_code = failure_type;
1718 }
1719
Tianjie Xuaced5d92016-10-12 10:55:04 -07001720 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001721}
1722
1723// The transfer list is a text file containing commands to
1724// transfer data from one place to another on the target
1725// partition. We parse it and execute the commands in order:
1726//
1727// zero [rangeset]
1728// - fill the indicated blocks with zeros
1729//
1730// new [rangeset]
1731// - fill the blocks with data read from the new_data file
1732//
1733// erase [rangeset]
1734// - mark the given blocks as empty
1735//
1736// move <...>
1737// bsdiff <patchstart> <patchlen> <...>
1738// imgdiff <patchstart> <patchlen> <...>
1739// - read the source blocks, apply a patch (or not in the
1740// case of move), write result to target blocks. bsdiff or
1741// imgdiff specifies the type of patch; move means no patch
1742// at all.
1743//
1744// The format of <...> differs between versions 1 and 2;
1745// see the LoadSrcTgtVersion{1,2}() functions for a
1746// description of what's expected.
1747//
1748// stash <stash_id> <src_range>
1749// - (version 2+ only) load the given source range and stash
1750// the data in the given slot of the stash table.
1751//
Tao Baobaad2d42015-12-06 16:56:27 -08001752// free <stash_id>
1753// - (version 3+ only) free the given stash data.
1754//
Sami Tolvanen90221202014-12-09 16:39:47 +00001755// The creator of the transfer list will guarantee that no block
1756// is read (ie, used as the source for a patch or move) after it
1757// has been written.
1758//
1759// In version 2, the creator will guarantee that a given stash is
1760// loaded (with a stash command) before it's used in a
1761// move/bsdiff/imgdiff command.
1762//
1763// Within one command the source and target ranges may overlap so
1764// in general we need to read the entire source into memory before
1765// writing anything to the target blocks.
1766//
1767// All the patch data is concatenated into one patch_data file in
1768// the update package. It must be stored uncompressed because we
1769// memory-map it in directly from the archive. (Since patches are
1770// already compressed, we lose very little by not compressing
1771// their concatenation.)
1772//
1773// In version 3, commands that read data from the partition (i.e.
1774// move/bsdiff/imgdiff/stash) have one or more additional hashes
1775// before the range parameters, which are used to check if the
1776// command has already been completed and verify the integrity of
1777// the source data.
1778
1779Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001780 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001781 const Command commands[] = {
1782 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001783 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001784 { "free", PerformCommandFree },
1785 { "imgdiff", PerformCommandDiff },
1786 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001787 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001788 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001789 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001790 };
1791
1792 // Perform a dry run without writing to test if an update can proceed
1793 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001794 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001795}
1796
1797Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1798 const Command commands[] = {
1799 { "bsdiff", PerformCommandDiff },
1800 { "erase", PerformCommandErase },
1801 { "free", PerformCommandFree },
1802 { "imgdiff", PerformCommandDiff },
1803 { "move", PerformCommandMove },
1804 { "new", PerformCommandNew },
1805 { "stash", PerformCommandStash },
1806 { "zero", PerformCommandZero }
1807 };
1808
1809 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001810 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001811}
1812
Tao Bao0940fe12015-08-27 16:41:21 -07001813Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001814 std::vector<std::unique_ptr<Value>> args;
1815 if (!ReadValueArgs(state, 2, argv, &args)) {
1816 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001817 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001818
1819 const Value* blockdev_filename = args[0].get();
1820 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001821
1822 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001823 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1824 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001825 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001826 }
1827 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001828 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001829 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001830 }
1831
Tianjie Xuaced5d92016-10-12 10:55:04 -07001832 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001833 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001834 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1835 blockdev_filename->data.c_str(), strerror(errno));
1836 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001837 }
1838
Tao Baoc844c062016-12-28 15:15:55 -08001839 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001840
1841 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001842 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001843
Tao Bao612336d2015-08-27 16:41:21 -07001844 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001845 for (size_t i = 0; i < rs.count; ++i) {
1846 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001847 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1848 blockdev_filename->data.c_str(), strerror(errno));
1849 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001850 }
1851
Tao Bao0940fe12015-08-27 16:41:21 -07001852 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001853 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001854 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1855 blockdev_filename->data.c_str(), strerror(errno));
1856 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001857 }
1858
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001859 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001860 }
1861 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001862 uint8_t digest[SHA_DIGEST_LENGTH];
1863 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001864
Tianjie Xuaced5d92016-10-12 10:55:04 -07001865 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001866}
1867
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001868// This function checks if a device has been remounted R/W prior to an incremental
1869// OTA update. This is an common cause of update abortion. The function reads the
1870// 1st block of each partition and check for mounting time/count. It return string "t"
1871// if executes successfully and an empty string otherwise.
1872
1873Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001874 std::vector<std::unique_ptr<Value>> args;
1875 if (!ReadValueArgs(state, 1, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001876 return nullptr;
1877 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001878
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001879 const Value* arg_filename = args[0].get();
1880
1881 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001882 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001883 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001884 }
1885
Tianjie Xuaced5d92016-10-12 10:55:04 -07001886 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001887 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001888 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001889 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001890 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001891 }
1892
1893 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1894 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1895
1896 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001897 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001898 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001899 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001900 }
1901
1902 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1903 // Super block starts from block 0, offset 0x400
1904 // 0x2C: len32 Mount time
1905 // 0x30: len32 Write time
1906 // 0x34: len16 Number of mounts since the last fsck
1907 // 0x38: len16 Magic signature 0xEF53
1908
1909 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1910 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1911
1912 if (mount_count > 0) {
1913 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1914 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1915 }
1916
Tianjie Xuaced5d92016-10-12 10:55:04 -07001917 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001918}
1919
1920
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001921Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001922 std::vector<std::unique_ptr<Value>> args;
1923 if (!ReadValueArgs(state, 2, argv, &args)) {
1924 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001925 }
1926
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001927 const Value* filename = args[0].get();
1928 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001929
1930 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001931 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001932 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001933 }
1934 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001935 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001936 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001937 }
1938
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001939 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001940 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001941
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001942 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tianjie Xuaced5d92016-10-12 10:55:04 -07001943 fec::io fh(filename->data.c_str(), O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001944
1945 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001946 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001947 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001948 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001949 }
1950
1951 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001952 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001953 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001954 }
1955
1956 fec_status status;
1957
1958 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001959 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001960 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001961 }
1962
Tao Baoc844c062016-12-28 15:15:55 -08001963 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001964
1965 uint8_t buffer[BLOCKSIZE];
1966
1967 for (size_t i = 0; i < rs.count; ++i) {
1968 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1969 // Stay within the data area, libfec validates and corrects metadata
1970 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1971 continue;
1972 }
1973
1974 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001975 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001976 filename->data.c_str(), j, strerror(errno));
1977 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001978 }
1979
1980 // If we want to be able to recover from a situation where rewriting a corrected
1981 // block doesn't guarantee the same data will be returned when re-read later, we
1982 // can save a copy of corrected blocks to /cache. Note:
1983 //
1984 // 1. Maximum space required from /cache is the same as the maximum number of
1985 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1986 // this would be ~16 MiB, for example.
1987 //
1988 // 2. To find out if this block was corrupted, call fec_get_status after each
1989 // read and check if the errors field value has increased.
1990 }
1991 }
Tao Bao039f2da2016-11-22 16:29:50 -08001992 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001993 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001994}
1995
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001996void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001997 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001998 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001999 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002000 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002001 RegisterFunction("range_sha1", RangeSha1Fn);
2002}