blob: 6755d78cb7bd205da95f95ed4741c9b6fe384629 [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.
Tao Bao0940fe12015-08-27 16:41:21 -070069};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070070
Tianjie Xu16255832016-04-30 11:49:59 -070071static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070072static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070073static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070074
Tao Baoc844c062016-12-28 15:15:55 -080075static RangeSet parse_range(const std::string& range_text) {
76 RangeSet rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010077
Tao Baoc844c062016-12-28 15:15:55 -080078 std::vector<std::string> pieces = android::base::Split(range_text, ",");
79 if (pieces.size() < 3) {
80 goto err;
81 }
82
83 size_t num;
84 if (!android::base::ParseUint(pieces[0], &num, static_cast<size_t>(INT_MAX))) {
85 goto err;
86 }
87
88 if (num == 0 || num % 2) {
89 goto err; // must be even
90 } else if (num != pieces.size() - 1) {
91 goto err;
92 }
93
94 rs.pos.resize(num);
95 rs.count = num / 2;
96 rs.size = 0;
97
98 for (size_t i = 0; i < num; i += 2) {
99 if (!android::base::ParseUint(pieces[i + 1], &rs.pos[i], static_cast<size_t>(INT_MAX))) {
100 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100101 }
102
Tao Baoc844c062016-12-28 15:15:55 -0800103 if (!android::base::ParseUint(pieces[i + 2], &rs.pos[i + 1], static_cast<size_t>(INT_MAX))) {
104 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100105 }
106
Tao Baoc844c062016-12-28 15:15:55 -0800107 if (rs.pos[i] >= rs.pos[i + 1]) {
108 goto err; // empty or negative range
Tao Baob15fd222015-09-24 11:10:51 -0700109 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100110
Tao Baoc844c062016-12-28 15:15:55 -0800111 size_t sz = rs.pos[i + 1] - rs.pos[i];
112 if (rs.size > SIZE_MAX - sz) {
113 goto err; // overflow
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700114 }
115
Tao Baoc844c062016-12-28 15:15:55 -0800116 rs.size += sz;
117 }
118
119 return rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100120
121err:
Tao Baoc844c062016-12-28 15:15:55 -0800122 LOG(ERROR) << "failed to parse range '" << range_text << "'";
123 exit(1);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700124}
125
Tao Baoe6aa3322015-08-05 15:20:27 -0700126static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Tao Baoc844c062016-12-28 15:15:55 -0800127 for (size_t i = 0; i < r1.count; ++i) {
128 size_t r1_0 = r1.pos[i * 2];
129 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000130
Tao Baoc844c062016-12-28 15:15:55 -0800131 for (size_t j = 0; j < r2.count; ++j) {
132 size_t r2_0 = r2.pos[j * 2];
133 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000134
Tao Baoc844c062016-12-28 15:15:55 -0800135 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
136 return true;
137 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000138 }
Tao Baoc844c062016-12-28 15:15:55 -0800139 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000140
Tao Baoc844c062016-12-28 15:15:55 -0800141 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000142}
143
144static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700145 size_t so_far = 0;
146 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800147 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700148 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700149 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800150 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000151 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700152 } else if (r == 0) {
153 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800154 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700155 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700156 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700157 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700158 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000159 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700160}
161
Tao Bao612336d2015-08-27 16:41:21 -0700162static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
163 return read_all(fd, buffer.data(), size);
164}
165
Sami Tolvanen90221202014-12-09 16:39:47 +0000166static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700167 size_t written = 0;
168 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800169 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700170 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700171 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800172 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000173 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700174 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700175 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700176 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000177
Sami Tolvanen90221202014-12-09 16:39:47 +0000178 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700179}
180
Tao Bao612336d2015-08-27 16:41:21 -0700181static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
182 return write_all(fd, buffer.data(), size);
183}
184
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700185static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
186 // Don't discard blocks unless the update is a retry run.
187 if (!is_retry) {
188 return true;
189 }
190
191 uint64_t args[2] = {static_cast<uint64_t>(offset), size};
192 int status = ioctl(fd, BLKDISCARD, &args);
193 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800194 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700195 return false;
196 }
197 return true;
198}
199
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700200static bool check_lseek(int fd, off64_t offset, int whence) {
201 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
202 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700203 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800204 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700205 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700206 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700207 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700208}
209
Tao Bao612336d2015-08-27 16:41:21 -0700210static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700211 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700212 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700213
Tao Bao612336d2015-08-27 16:41:21 -0700214 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700215}
216
Tao Bao0940fe12015-08-27 16:41:21 -0700217struct RangeSinkState {
Chih-Hung Hsieh49c5c792016-04-29 14:16:35 -0700218 explicit RangeSinkState(RangeSet& rs) : tgt(rs) { };
Tao Bao0940fe12015-08-27 16:41:21 -0700219
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700220 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700221 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530222 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700223 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700224};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700225
226static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700227 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700228
Tao Bao0940fe12015-08-27 16:41:21 -0700229 if (rss->p_remain == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800230 LOG(ERROR) << "range sink write overrun";
Sami Tolvanen90221202014-12-09 16:39:47 +0000231 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700232 }
233
234 ssize_t written = 0;
235 while (size > 0) {
236 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000237
238 if (rss->p_remain < write_now) {
239 write_now = rss->p_remain;
240 }
241
242 if (write_all(rss->fd, data, write_now) == -1) {
243 break;
244 }
245
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700246 data += write_now;
247 size -= write_now;
248
249 rss->p_remain -= write_now;
250 written += write_now;
251
252 if (rss->p_remain == 0) {
253 // move to the next block
254 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700255 if (rss->p_block < rss->tgt.count) {
256 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
257 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000258
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700259 off64_t offset = static_cast<off64_t>(rss->tgt.pos[rss->p_block*2]) * BLOCKSIZE;
260 if (!discard_blocks(rss->fd, offset, rss->p_remain)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000261 break;
262 }
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700263
264 if (!check_lseek(rss->fd, offset, SEEK_SET)) {
265 break;
266 }
267
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700268 } else {
269 // we can't write any more; return how many bytes have
270 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000271 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700272 }
273 }
274 }
275
276 return written;
277}
278
279// All of the data for all the 'new' transfers is contained in one
280// file in the update package, concatenated together in the order in
281// which transfers.list will need it. We want to stream it out of the
282// archive (it's compressed) without writing it to a temp file, but we
283// can't write each section until it's that transfer's turn to go.
284//
285// To achieve this, we expand the new data from the archive in a
286// background thread, and block that threads 'receive uncompressed
287// data' function until the main thread has reached a point where we
288// want some new data to be written. We signal the background thread
289// with the destination for the data and block the main thread,
290// waiting for the background thread to complete writing that section.
291// Then it signals the main thread to wake up and goes back to
292// blocking waiting for a transfer.
293//
294// NewThreadInfo is the struct used to pass information back and forth
295// between the two threads. When the main thread wants some data
296// written, it sets rss to the destination location and signals the
297// condition. When the background thread is done writing, it clears
298// rss and signals the condition again.
299
Tao Bao0940fe12015-08-27 16:41:21 -0700300struct NewThreadInfo {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700301 ZipArchiveHandle za;
302 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700303
304 RangeSinkState* rss;
305
306 pthread_mutex_t mu;
307 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700308};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700309
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700310static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700311 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700312
313 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700314 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700315 // data is wanted.
316 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700317 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700318 pthread_cond_wait(&nti->cv, &nti->mu);
319 }
320 pthread_mutex_unlock(&nti->mu);
321
322 // At this point nti->rss is set, and we own it. The main
323 // thread is waiting for it to disappear from nti.
324 ssize_t written = RangeSinkWrite(data, size, nti->rss);
325 data += written;
326 size -= written;
327
Tao Bao0940fe12015-08-27 16:41:21 -0700328 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700329 // we have written all the bytes desired by this rss.
330
331 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700332 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700333 pthread_cond_broadcast(&nti->cv);
334 pthread_mutex_unlock(&nti->mu);
335 }
336 }
337
338 return true;
339}
340
341static void* unzip_new_data(void* cookie) {
342 NewThreadInfo* nti = (NewThreadInfo*) cookie;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700343 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700344 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700345}
346
Tao Bao612336d2015-08-27 16:41:21 -0700347static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000348 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700349 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000350
Tao Bao0940fe12015-08-27 16:41:21 -0700351 for (size_t i = 0; i < src.count; ++i) {
352 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000353 return -1;
354 }
355
Tao Bao0940fe12015-08-27 16:41:21 -0700356 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000357
Tao Bao612336d2015-08-27 16:41:21 -0700358 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000359 return -1;
360 }
361
362 p += size;
363 }
364
365 return 0;
366}
367
Tao Bao612336d2015-08-27 16:41:21 -0700368static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
369 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000370
Tao Bao0940fe12015-08-27 16:41:21 -0700371 size_t p = 0;
372 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700373 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
374 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
375 if (!discard_blocks(fd, offset, size)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000376 return -1;
377 }
378
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700379 if (!check_lseek(fd, offset, SEEK_SET)) {
380 return -1;
381 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000382
Tao Bao612336d2015-08-27 16:41:21 -0700383 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000384 return -1;
385 }
386
387 p += size;
388 }
389
390 return 0;
391}
392
Tao Baobaad2d42015-12-06 16:56:27 -0800393// Parameters for transfer list command functions
394struct CommandParameters {
395 std::vector<std::string> tokens;
396 size_t cpos;
397 const char* cmdname;
398 const char* cmdline;
399 std::string freestash;
400 std::string stashbase;
401 bool canwrite;
402 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700403 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800404 bool foundwrites;
405 bool isunresumable;
406 int version;
407 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700408 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800409 NewThreadInfo nti;
410 pthread_t thread;
411 std::vector<uint8_t> buffer;
412 uint8_t* patch_start;
413};
414
Doug Zongker52ae67d2014-09-08 12:22:09 -0700415// Do a source/target load for move/bsdiff/imgdiff in version 1.
Tao Baobaad2d42015-12-06 16:56:27 -0800416// We expect to parse the remainder of the parameter tokens as:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700417//
418// <src_range> <tgt_range>
419//
420// The source range is loaded into the provided buffer, reallocating
Tao Bao34847b22015-09-08 11:05:49 -0700421// it to make it larger if necessary.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700422
Tao Baobaad2d42015-12-06 16:56:27 -0800423static int LoadSrcTgtVersion1(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700424 std::vector<uint8_t>& buffer, int fd) {
Tao Baobaad2d42015-12-06 16:56:27 -0800425
426 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800427 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -0800428 return -1;
429 }
430
Tao Bao612336d2015-08-27 16:41:21 -0700431 // <src_range>
Tao Baoc844c062016-12-28 15:15:55 -0800432 RangeSet src = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700433
Tao Bao612336d2015-08-27 16:41:21 -0700434 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -0800435 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700436
Tao Bao612336d2015-08-27 16:41:21 -0700437 allocate(src.size * BLOCKSIZE, buffer);
438 int rc = ReadBlocks(src, buffer, fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700439 src_blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000440
Sami Tolvanen90221202014-12-09 16:39:47 +0000441 return rc;
442}
443
Tao Bao612336d2015-08-27 16:41:21 -0700444static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700445 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800446 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700447 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000448
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800449 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000450
Tao Baoe6aa3322015-08-05 15:20:27 -0700451 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000452
Tao Bao0940fe12015-08-27 16:41:21 -0700453 if (hexdigest != expected) {
454 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800455 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
456 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700457 }
458 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000459 }
460
Tao Bao0940fe12015-08-27 16:41:21 -0700461 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000462}
463
Tao Bao0940fe12015-08-27 16:41:21 -0700464static std::string GetStashFileName(const std::string& base, const std::string& id,
465 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700466 if (base.empty()) {
467 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000468 }
469
Tao Baoe6aa3322015-08-05 15:20:27 -0700470 std::string fn(STASH_DIRECTORY_BASE);
471 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000472
473 return fn;
474}
475
Tao Baoe6aa3322015-08-05 15:20:27 -0700476typedef void (*StashCallback)(const std::string&, void*);
Sami Tolvanen90221202014-12-09 16:39:47 +0000477
478// Does a best effort enumeration of stash files. Ignores possible non-file
479// items in the stash directory and continues despite of errors. Calls the
480// 'callback' function for each file and passes 'data' to the function as a
481// parameter.
482
Tao Baoe6aa3322015-08-05 15:20:27 -0700483static void EnumerateStash(const std::string& dirname, StashCallback callback, void* data) {
Tao Bao0940fe12015-08-27 16:41:21 -0700484 if (dirname.empty() || callback == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000485 return;
486 }
487
Tao Baoe6aa3322015-08-05 15:20:27 -0700488 std::unique_ptr<DIR, int(*)(DIR*)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000489
Tao Bao0940fe12015-08-27 16:41:21 -0700490 if (directory == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000491 if (errno != ENOENT) {
Tao Bao039f2da2016-11-22 16:29:50 -0800492 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000493 }
494 return;
495 }
496
Tao Baoe6aa3322015-08-05 15:20:27 -0700497 struct dirent* item;
Tao Bao0940fe12015-08-27 16:41:21 -0700498 while ((item = readdir(directory.get())) != nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000499 if (item->d_type != DT_REG) {
500 continue;
501 }
502
Tao Baoe6aa3322015-08-05 15:20:27 -0700503 std::string fn = dirname + "/" + std::string(item->d_name);
Sami Tolvanen90221202014-12-09 16:39:47 +0000504 callback(fn, data);
Sami Tolvanen90221202014-12-09 16:39:47 +0000505 }
506}
507
Tao Baoe6aa3322015-08-05 15:20:27 -0700508static void UpdateFileSize(const std::string& fn, void* data) {
Tao Bao51412212016-12-28 14:44:05 -0800509 if (fn.empty() || !data) {
510 return;
511 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700512
Tao Bao51412212016-12-28 14:44:05 -0800513 struct stat sb;
514 if (stat(fn.c_str(), &sb) == -1) {
515 PLOG(ERROR) << "stat \"" << fn << "\" failed";
516 return;
517 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000518
Tao Bao51412212016-12-28 14:44:05 -0800519 size_t* size = static_cast<size_t*>(data);
520 *size += sb.st_size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000521}
522
523// Deletes the stash directory and all files in it. Assumes that it only
524// contains files. There is nothing we can do about unlikely, but possible
525// errors, so they are merely logged.
526
Tao Bao0940fe12015-08-27 16:41:21 -0700527static void DeleteFile(const std::string& fn, void* /* data */) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700528 if (!fn.empty()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800529 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000530
Tao Baoe6aa3322015-08-05 15:20:27 -0700531 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
Tao Bao039f2da2016-11-22 16:29:50 -0800532 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000533 }
534 }
535}
536
Tao Baoe6aa3322015-08-05 15:20:27 -0700537static void DeletePartial(const std::string& fn, void* data) {
538 if (android::base::EndsWith(fn, ".partial")) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000539 DeleteFile(fn, data);
540 }
541}
542
Tao Baoe6aa3322015-08-05 15:20:27 -0700543static void DeleteStash(const std::string& base) {
544 if (base.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000545 return;
546 }
547
Tao Bao039f2da2016-11-22 16:29:50 -0800548 LOG(INFO) << "deleting stash " << base;
Sami Tolvanen90221202014-12-09 16:39:47 +0000549
Tao Baoe6aa3322015-08-05 15:20:27 -0700550 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700551 EnumerateStash(dirname, DeleteFile, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000552
Tao Baoe6aa3322015-08-05 15:20:27 -0700553 if (rmdir(dirname.c_str()) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000554 if (errno != ENOENT && errno != ENOTDIR) {
Tao Bao039f2da2016-11-22 16:29:50 -0800555 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000556 }
557 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000558}
559
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700560static int LoadStash(CommandParameters& params, const std::string& base, const std::string& id,
561 bool verify, size_t* blocks, std::vector<uint8_t>& buffer, bool printnoent) {
562 // In verify mode, if source range_set was saved for the given hash,
563 // check contents in the source blocks first. If the check fails,
564 // search for the stashed files on /cache as usual.
565 if (!params.canwrite) {
566 if (stash_map.find(id) != stash_map.end()) {
567 const RangeSet& src = stash_map[id];
568 allocate(src.size * BLOCKSIZE, buffer);
569
570 if (ReadBlocks(src, buffer, params.fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800571 LOG(ERROR) << "failed to read source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700572 return -1;
573 }
574 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800575 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700576 return -1;
577 }
578 return 0;
579 }
580 }
581
Tao Bao612336d2015-08-27 16:41:21 -0700582 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700583 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000584 }
585
Tao Bao0940fe12015-08-27 16:41:21 -0700586 size_t blockcount = 0;
587
Sami Tolvanen90221202014-12-09 16:39:47 +0000588 if (!blocks) {
589 blocks = &blockcount;
590 }
591
Tao Bao0940fe12015-08-27 16:41:21 -0700592 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000593
Tao Bao0940fe12015-08-27 16:41:21 -0700594 struct stat sb;
595 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000596
597 if (res == -1) {
598 if (errno != ENOENT || printnoent) {
Tao Bao039f2da2016-11-22 16:29:50 -0800599 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000600 }
Tao Bao0940fe12015-08-27 16:41:21 -0700601 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000602 }
603
Tao Bao039f2da2016-11-22 16:29:50 -0800604 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000605
Tao Bao0940fe12015-08-27 16:41:21 -0700606 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800607 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
Tao Bao0940fe12015-08-27 16:41:21 -0700608 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000609 }
610
Elliott Hughesbcabd092016-03-22 20:19:22 -0700611 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000612 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800613 PLOG(ERROR) << "open \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700614 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000615 }
616
Tao Bao612336d2015-08-27 16:41:21 -0700617 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000618
Tao Bao612336d2015-08-27 16:41:21 -0700619 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700620 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000621 }
622
Tao Bao0940fe12015-08-27 16:41:21 -0700623 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000624
Tao Bao612336d2015-08-27 16:41:21 -0700625 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800626 LOG(ERROR) << "unexpected contents in " << fn;
Tao Bao0940fe12015-08-27 16:41:21 -0700627 DeleteFile(fn, nullptr);
628 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000629 }
630
Tao Bao0940fe12015-08-27 16:41:21 -0700631 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000632}
633
Tao Bao612336d2015-08-27 16:41:21 -0700634static int WriteStash(const std::string& base, const std::string& id, int blocks,
635 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
636 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700637 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000638 }
639
640 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800641 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700642 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000643 }
644
Tao Bao0940fe12015-08-27 16:41:21 -0700645 std::string fn = GetStashFileName(base, id, ".partial");
646 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000647
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100648 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700649 struct stat sb;
650 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100651
652 if (res == 0) {
653 // The file already exists and since the name is the hash of the contents,
654 // it's safe to assume the contents are identical (accidental hash collisions
655 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800656 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700657 *exists = true;
658 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100659 }
660
Tao Bao0940fe12015-08-27 16:41:21 -0700661 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100662 }
663
Tao Bao039f2da2016-11-22 16:29:50 -0800664 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000665
Tao Bao039f2da2016-11-22 16:29:50 -0800666 android::base::unique_fd fd(
667 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000668 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800669 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700670 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000671 }
672
673 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700674 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000675 }
676
Jed Estepa7b9a462015-12-15 16:04:53 -0800677 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700678 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800679 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700680 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000681 }
682
Tao Baoe6aa3322015-08-05 15:20:27 -0700683 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800684 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700685 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000686 }
687
Tao Bao0940fe12015-08-27 16:41:21 -0700688 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700689 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
690 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700691 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700692 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800693 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700694 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700695 }
696
Jed Estepa7b9a462015-12-15 16:04:53 -0800697 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700698 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800699 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700700 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700701 }
702
Tao Bao0940fe12015-08-27 16:41:21 -0700703 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000704}
705
706// Creates a directory for storing stash files and checks if the /cache partition
707// hash enough space for the expected amount of blocks we need to store. Returns
708// >0 if we created the directory, zero if it existed already, and <0 of failure.
709
Tao Bao51412212016-12-28 14:44:05 -0800710static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
711 std::string& base) {
712 if (blockdev.empty()) {
713 return -1;
714 }
715
716 // Stash directory should be different for each partition to avoid conflicts
717 // when updating multiple partitions at the same time, so we use the hash of
718 // the block device name as the base directory
719 uint8_t digest[SHA_DIGEST_LENGTH];
720 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
721 base = print_sha1(digest);
722
723 std::string dirname = GetStashFileName(base, "", "");
724 struct stat sb;
725 int res = stat(dirname.c_str(), &sb);
726 size_t max_stash_size = maxblocks * BLOCKSIZE;
727
728 if (res == -1 && errno != ENOENT) {
729 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
730 strerror(errno));
731 return -1;
732 } else if (res != 0) {
733 LOG(INFO) << "creating stash " << dirname;
734 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
735
736 if (res != 0) {
737 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
738 strerror(errno));
739 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000740 }
741
Tao Bao51412212016-12-28 14:44:05 -0800742 if (CacheSizeCheck(max_stash_size) != 0) {
743 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
744 max_stash_size);
745 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000746 }
747
Tao Bao51412212016-12-28 14:44:05 -0800748 return 1; // Created directory
749 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000750
Tao Bao51412212016-12-28 14:44:05 -0800751 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000752
Tao Bao51412212016-12-28 14:44:05 -0800753 // If the directory already exists, calculate the space already allocated to
754 // stash files and check if there's enough for all required blocks. Delete any
755 // partially completed stash files first.
Sami Tolvanen90221202014-12-09 16:39:47 +0000756
Tao Bao51412212016-12-28 14:44:05 -0800757 EnumerateStash(dirname, DeletePartial, nullptr);
758 size_t existing = 0;
759 EnumerateStash(dirname, UpdateFileSize, &existing);
Sami Tolvanen90221202014-12-09 16:39:47 +0000760
Tao Bao51412212016-12-28 14:44:05 -0800761 if (max_stash_size > existing) {
762 size_t needed = max_stash_size - existing;
763 if (CacheSizeCheck(needed) != 0) {
764 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
765 needed);
766 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000767 }
Tao Bao51412212016-12-28 14:44:05 -0800768 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000769
Tao Bao51412212016-12-28 14:44:05 -0800770 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000771}
772
Tao Baobaad2d42015-12-06 16:56:27 -0800773static int SaveStash(CommandParameters& params, const std::string& base,
774 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000775
Tao Baobaad2d42015-12-06 16:56:27 -0800776 // <stash_id> <src_range>
777 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800778 LOG(ERROR) << "missing id and/or src range fields in stash command";
Sami Tolvanen90221202014-12-09 16:39:47 +0000779 return -1;
780 }
Tao Baobaad2d42015-12-06 16:56:27 -0800781 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000782
Tao Bao0940fe12015-08-27 16:41:21 -0700783 size_t blocks = 0;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700784 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000785 // Stash file already exists and has expected contents. Do not
786 // read from source again, as the source may have been already
787 // overwritten during a previous attempt.
788 return 0;
789 }
790
Tao Baoc844c062016-12-28 15:15:55 -0800791 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao34847b22015-09-08 11:05:49 -0700792
Tao Bao612336d2015-08-27 16:41:21 -0700793 allocate(src.size * BLOCKSIZE, buffer);
794 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000795 return -1;
796 }
Tao Bao34847b22015-09-08 11:05:49 -0700797 blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000798
Tao Bao612336d2015-08-27 16:41:21 -0700799 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000800 // Source blocks have unexpected contents. If we actually need this
801 // data later, this is an unrecoverable error. However, the command
802 // that uses the data may have already completed previously, so the
803 // possible failure will occur during source block verification.
Tao Bao039f2da2016-11-22 16:29:50 -0800804 LOG(ERROR) << "failed to load source blocks for stash " << id;
Sami Tolvanen90221202014-12-09 16:39:47 +0000805 return 0;
806 }
807
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700808 // In verify mode, save source range_set instead of stashing blocks.
809 if (!params.canwrite && usehash) {
810 stash_map[id] = src;
811 return 0;
812 }
813
Tao Bao039f2da2016-11-22 16:29:50 -0800814 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xudd874b12016-05-13 12:13:15 -0700815 params.stashed += blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700816 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000817}
818
Tao Baobaad2d42015-12-06 16:56:27 -0800819static int FreeStash(const std::string& base, const std::string& id) {
820 if (base.empty() || id.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000821 return -1;
822 }
823
Tao Baobaad2d42015-12-06 16:56:27 -0800824 std::string fn = GetStashFileName(base, id, "");
Tao Bao0940fe12015-08-27 16:41:21 -0700825 DeleteFile(fn, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000826
827 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700828}
829
Tao Bao612336d2015-08-27 16:41:21 -0700830static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
831 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700832 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700833 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700834 // may be the same buffer.
835
Tao Bao612336d2015-08-27 16:41:21 -0700836 const uint8_t* from = source.data();
837 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700838 size_t start = locs.size;
839 for (int i = locs.count-1; i >= 0; --i) {
840 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700841 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700842 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700843 blocks * BLOCKSIZE);
844 }
845}
846
847// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800848// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700849//
850// <tgt_range> <src_block_count> <src_range>
851// (loads data from source image only)
852//
853// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
854// (loads data from stashes only)
855//
856// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
857// (loads data from both source image and stashes)
858//
859// On return, buffer is filled with the loaded source data (rearranged
860// and combined with stashed data as necessary). buffer may be
861// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000862// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700863
Tao Baobaad2d42015-12-06 16:56:27 -0800864static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700865 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800866
867 // At least it needs to provide three parameters: <tgt_range>,
868 // <src_block_count> and "-"/<src_range>.
869 if (params.cpos + 2 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800870 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -0800871 return -1;
872 }
873
Tao Bao612336d2015-08-27 16:41:21 -0700874 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -0800875 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700876
Tao Bao612336d2015-08-27 16:41:21 -0700877 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800878 const std::string& token = params.tokens[params.cpos++];
879 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
Tao Bao039f2da2016-11-22 16:29:50 -0800880 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
Tao Baobaad2d42015-12-06 16:56:27 -0800881 return -1;
882 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700883
Tao Bao612336d2015-08-27 16:41:21 -0700884 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700885
Tao Bao612336d2015-08-27 16:41:21 -0700886 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800887 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700888 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800889 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700890 } else {
Tao Baoc844c062016-12-28 15:15:55 -0800891 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -0700892 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700893
Tao Bao34847b22015-09-08 11:05:49 -0700894 if (overlap) {
895 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700896 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000897
Sami Tolvanen90221202014-12-09 16:39:47 +0000898 if (res == -1) {
899 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700900 }
901
Tao Baobaad2d42015-12-06 16:56:27 -0800902 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000903 // no stashes, only source range
904 return 0;
905 }
906
Tao Baoc844c062016-12-28 15:15:55 -0800907 RangeSet locs = parse_range(params.tokens[params.cpos++]);
Tao Bao612336d2015-08-27 16:41:21 -0700908 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700909 }
910
Tao Baobaad2d42015-12-06 16:56:27 -0800911 // <[stash_id:stash_range]>
912 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700913 // Each word is a an index into the stash table, a colon, and
914 // then a rangeset describing where in the source block that
915 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800916 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
917 if (tokens.size() != 2) {
Tao Bao039f2da2016-11-22 16:29:50 -0800918 LOG(ERROR) << "invalid parameter";
Tao Baobaad2d42015-12-06 16:56:27 -0800919 return -1;
920 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000921
Tao Bao612336d2015-08-27 16:41:21 -0700922 std::vector<uint8_t> stash;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700923 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000924
925 if (res == -1) {
926 // These source blocks will fail verification if used later, but we
927 // will let the caller decide if this is a fatal failure
Tao Bao039f2da2016-11-22 16:29:50 -0800928 LOG(ERROR) << "failed to load stash " << tokens[0];
Sami Tolvanen90221202014-12-09 16:39:47 +0000929 continue;
930 }
931
Tao Baoc844c062016-12-28 15:15:55 -0800932 RangeSet locs = parse_range(tokens[1]);
Sami Tolvanen90221202014-12-09 16:39:47 +0000933
Tao Bao612336d2015-08-27 16:41:21 -0700934 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000935 }
936
937 return 0;
938}
939
Sami Tolvanen90221202014-12-09 16:39:47 +0000940// Do a source/target load for move/bsdiff/imgdiff in version 3.
941//
942// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
943// tells the function whether to expect separate source and targe block hashes, or
944// if they are both the same and only one hash should be expected, and
945// 'isunresumable', which receives a non-zero value if block verification fails in
946// a way that the update cannot be resumed anymore.
947//
948// If the function is unable to load the necessary blocks or their contents don't
949// match the hashes, the return value is -1 and the command should be aborted.
950//
951// If the return value is 1, the command has already been completed according to
952// the contents of the target blocks, and should not be performed again.
953//
954// If the return value is 0, source blocks have expected content and the command
955// can be performed.
956
Tao Bao34847b22015-09-08 11:05:49 -0700957static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -0700958 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000959
Tao Baobaad2d42015-12-06 16:56:27 -0800960 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800961 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -0700962 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000963 }
964
Tao Baobaad2d42015-12-06 16:56:27 -0800965 std::string srchash = params.tokens[params.cpos++];
966 std::string tgthash;
967
Sami Tolvanen90221202014-12-09 16:39:47 +0000968 if (onehash) {
969 tgthash = srchash;
970 } else {
Tao Baobaad2d42015-12-06 16:56:27 -0800971 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800972 LOG(ERROR) << "missing target hash";
Tao Bao0940fe12015-08-27 16:41:21 -0700973 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000974 }
Tao Baobaad2d42015-12-06 16:56:27 -0800975 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000976 }
977
Elliott Hughesbcabd092016-03-22 20:19:22 -0700978 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd,
979 params.stashbase, &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700980 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000981 }
982
Tao Bao34847b22015-09-08 11:05:49 -0700983 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000984
Tao Bao612336d2015-08-27 16:41:21 -0700985 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700986 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000987 }
988
Tao Bao612336d2015-08-27 16:41:21 -0700989 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000990 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -0700991 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000992 }
993
Tao Bao0940fe12015-08-27 16:41:21 -0700994 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000995 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700996 // resume from possible write errors. In verify mode, we can skip stashing
997 // because the source blocks won't be overwritten.
998 if (overlap && params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -0800999 LOG(INFO) << "stashing " << src_blocks << " overlapping blocks to " << srchash;
Sami Tolvanen90221202014-12-09 16:39:47 +00001000
Tao Bao0940fe12015-08-27 16:41:21 -07001001 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -07001002 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -07001003 &stash_exists) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001004 LOG(ERROR) << "failed to stash overlapping source blocks";
Tao Bao0940fe12015-08-27 16:41:21 -07001005 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001006 }
1007
Tianjie Xudd874b12016-05-13 12:13:15 -07001008 params.stashed += src_blocks;
Sami Tolvanen90221202014-12-09 16:39:47 +00001009 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001010 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -07001011 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001012 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001013 }
1014
1015 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -07001016 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001017 }
1018
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001019 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
1020 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001021 // Overlapping source blocks were previously stashed, command can proceed.
1022 // We are recovering from an interrupted command, so we don't know if the
1023 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -07001024 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001025 }
1026
1027 // Valid source data not available, update cannot be resumed
Tao Bao039f2da2016-11-22 16:29:50 -08001028 LOG(ERROR) << "partition has unexpected contents";
Tao Bao0940fe12015-08-27 16:41:21 -07001029 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +00001030
Tao Bao0940fe12015-08-27 16:41:21 -07001031 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001032}
1033
Tao Bao0940fe12015-08-27 16:41:21 -07001034static int PerformCommandMove(CommandParameters& params) {
1035 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001036 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001037 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001038 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001039
Tao Bao0940fe12015-08-27 16:41:21 -07001040 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001041 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001042 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001043 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001044 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001045 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001046 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001047 }
1048
1049 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001050 LOG(ERROR) << "failed to read blocks for move";
Tao Bao0940fe12015-08-27 16:41:21 -07001051 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001052 }
1053
1054 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001055 params.foundwrites = true;
1056 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001057 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001058 }
1059
Tao Bao0940fe12015-08-27 16:41:21 -07001060 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001061 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001062 LOG(INFO) << " moving " << blocks << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001063
Tao Bao0940fe12015-08-27 16:41:21 -07001064 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1065 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001066 }
1067 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001068 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001069 }
1070
1071 }
1072
Tao Baobaad2d42015-12-06 16:56:27 -08001073 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001074 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001075 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001076 }
1077
Tao Bao0940fe12015-08-27 16:41:21 -07001078 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001079
Tao Bao0940fe12015-08-27 16:41:21 -07001080 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001081}
1082
Tao Bao0940fe12015-08-27 16:41:21 -07001083static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001084 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001085 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001086}
1087
Tao Bao0940fe12015-08-27 16:41:21 -07001088static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001089 // <stash_id>
1090 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001091 LOG(ERROR) << "missing stash id in free command";
Tao Baobaad2d42015-12-06 16:56:27 -08001092 return -1;
1093 }
1094
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001095 const std::string& id = params.tokens[params.cpos++];
1096
1097 if (!params.canwrite && stash_map.find(id) != stash_map.end()) {
1098 stash_map.erase(id);
1099 return 0;
1100 }
1101
Tao Bao0940fe12015-08-27 16:41:21 -07001102 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001103 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001104 }
1105
1106 return 0;
1107}
1108
Tao Bao0940fe12015-08-27 16:41:21 -07001109static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001110
Tao Baobaad2d42015-12-06 16:56:27 -08001111 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001112 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001113 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001114 }
1115
Tao Baoc844c062016-12-28 15:15:55 -08001116 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001117
Tao Bao039f2da2016-11-22 16:29:50 -08001118 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001119
Tao Bao612336d2015-08-27 16:41:21 -07001120 allocate(BLOCKSIZE, params.buffer);
1121 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001122
Tao Bao0940fe12015-08-27 16:41:21 -07001123 if (params.canwrite) {
1124 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001125 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1126 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1127 if (!discard_blocks(params.fd, offset, size)) {
1128 return -1;
1129 }
1130
1131 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001132 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001133 }
1134
Tao Bao0940fe12015-08-27 16:41:21 -07001135 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1136 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1137 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001138 }
1139 }
1140 }
1141 }
1142
Tao Bao0940fe12015-08-27 16:41:21 -07001143 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001144 // Update only for the zero command, as the erase command will call
1145 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001146 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001147 }
1148
Tao Bao0940fe12015-08-27 16:41:21 -07001149 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001150}
1151
Tao Bao0940fe12015-08-27 16:41:21 -07001152static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001153
Tao Baobaad2d42015-12-06 16:56:27 -08001154 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001155 LOG(ERROR) << "missing target blocks for new";
Tao Bao0940fe12015-08-27 16:41:21 -07001156 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001157 }
1158
Tao Baoc844c062016-12-28 15:15:55 -08001159 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001160
Tao Bao0940fe12015-08-27 16:41:21 -07001161 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001162 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
Sami Tolvanen90221202014-12-09 16:39:47 +00001163
Tao Bao0940fe12015-08-27 16:41:21 -07001164 RangeSinkState rss(tgt);
1165 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001166 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001167 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001168
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001169 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1170 if (!discard_blocks(params.fd, offset, tgt.size * BLOCKSIZE)) {
1171 return -1;
1172 }
1173
1174 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001175 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001176 }
1177
Tao Bao0940fe12015-08-27 16:41:21 -07001178 pthread_mutex_lock(&params.nti.mu);
1179 params.nti.rss = &rss;
1180 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001181
Tao Bao0940fe12015-08-27 16:41:21 -07001182 while (params.nti.rss) {
1183 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001184 }
1185
Tao Bao0940fe12015-08-27 16:41:21 -07001186 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001187 }
1188
Tao Bao0940fe12015-08-27 16:41:21 -07001189 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001190
Tao Bao0940fe12015-08-27 16:41:21 -07001191 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001192}
1193
Tao Bao0940fe12015-08-27 16:41:21 -07001194static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001195
Tao Baobaad2d42015-12-06 16:56:27 -08001196 // <offset> <length>
1197 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001198 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
Tao Bao0940fe12015-08-27 16:41:21 -07001199 return -1;
1200 }
1201
Tao Baobaad2d42015-12-06 16:56:27 -08001202 size_t offset;
1203 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001204 LOG(ERROR) << "invalid patch offset";
Tao Bao0940fe12015-08-27 16:41:21 -07001205 return -1;
1206 }
1207
Tao Baobaad2d42015-12-06 16:56:27 -08001208 size_t len;
1209 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001210 LOG(ERROR) << "invalid patch len";
Tao Baobaad2d42015-12-06 16:56:27 -08001211 return -1;
1212 }
Tao Bao0940fe12015-08-27 16:41:21 -07001213
Tao Bao612336d2015-08-27 16:41:21 -07001214 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001215 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001216 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001217 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001218 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001219 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001220 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001221 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001222 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001223 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001224 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001225 }
1226
1227 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001228 LOG(ERROR) << "failed to read blocks for diff";
Tao Bao0940fe12015-08-27 16:41:21 -07001229 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001230 }
1231
1232 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001233 params.foundwrites = true;
1234 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001235 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001236 }
1237
Tao Bao0940fe12015-08-27 16:41:21 -07001238 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001239 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001240 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001241
Tianjie Xuaced5d92016-10-12 10:55:04 -07001242 Value patch_value(VAL_BLOB,
1243 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001244
Tao Bao0940fe12015-08-27 16:41:21 -07001245 RangeSinkState rss(tgt);
1246 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001247 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001248 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001249
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001250 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1251 if (!discard_blocks(params.fd, offset, rss.p_remain)) {
1252 return -1;
1253 }
1254
1255 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001256 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001257 }
1258
Tao Bao0940fe12015-08-27 16:41:21 -07001259 if (params.cmdname[0] == 'i') { // imgdiff
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001260 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1261 &RangeSinkWrite, &rss, nullptr, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001262 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001263 return -1;
1264 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001265 } else {
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001266 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1267 0, &RangeSinkWrite, &rss, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001268 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001269 return -1;
1270 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001271 }
1272
1273 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001274 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001275 LOG(ERROR) << "range sink underrun?";
Sami Tolvanen90221202014-12-09 16:39:47 +00001276 }
1277 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001278 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size
1279 << " [" << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001280 }
1281 }
1282
Tao Baobaad2d42015-12-06 16:56:27 -08001283 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001284 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001285 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001286 }
1287
Tao Bao0940fe12015-08-27 16:41:21 -07001288 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001289
Tao Bao0940fe12015-08-27 16:41:21 -07001290 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001291}
1292
Tao Bao0940fe12015-08-27 16:41:21 -07001293static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001294 if (DEBUG_ERASE) {
1295 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001296 }
1297
Tao Bao0940fe12015-08-27 16:41:21 -07001298 struct stat sb;
1299 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001300 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001301 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001302 }
1303
Tao Bao0940fe12015-08-27 16:41:21 -07001304 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001305 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001306 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001307 }
1308
Tao Baobaad2d42015-12-06 16:56:27 -08001309 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001310 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001311 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001312 }
1313
Tao Baoc844c062016-12-28 15:15:55 -08001314 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001315
Tao Bao0940fe12015-08-27 16:41:21 -07001316 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001317 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001318
Tao Bao0940fe12015-08-27 16:41:21 -07001319 for (size_t i = 0; i < tgt.count; ++i) {
1320 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001321 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001322 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001323 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001324 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001325
Tao Bao0940fe12015-08-27 16:41:21 -07001326 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001327 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001328 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001329 }
1330 }
1331 }
1332
Tao Bao0940fe12015-08-27 16:41:21 -07001333 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001334}
1335
1336// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001337typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001338
Tao Bao612336d2015-08-27 16:41:21 -07001339struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001340 const char* name;
1341 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001342};
Sami Tolvanen90221202014-12-09 16:39:47 +00001343
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001344// args:
1345// - block device (or file) to modify in-place
1346// - transfer list (blob)
1347// - new data stream (filename within package.zip)
1348// - patch stream (filename within package.zip, must be uncompressed)
1349
Tao Bao0940fe12015-08-27 16:41:21 -07001350static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1351 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao73064612016-04-26 17:14:32 -07001352 CommandParameters params = {};
Sami Tolvanen90221202014-12-09 16:39:47 +00001353 params.canwrite = !dryrun;
1354
Tao Bao5354f602016-12-14 11:31:18 -08001355 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001356 if (state->is_retry) {
1357 is_retry = true;
Tao Bao039f2da2016-11-22 16:29:50 -08001358 LOG(INFO) << "This update is a retry.";
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001359 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001360
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001361 std::vector<std::unique_ptr<Value>> args;
1362 if (!ReadValueArgs(state, 4, argv, &args)) {
1363 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001364 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001365
1366 const Value* blockdev_filename = args[0].get();
1367 const Value* transfer_list_value = args[1].get();
1368 const Value* new_data_fn = args[2].get();
1369 const Value* patch_data_fn = args[3].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001370
1371 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001372 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1373 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001374 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001375 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001376 if (transfer_list_value->type != VAL_BLOB) {
Tianjie Xu16255832016-04-30 11:49:59 -07001377 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001378 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001379 }
1380 if (new_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001381 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001382 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001383 }
1384 if (patch_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001385 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string",
1386 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001387 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001388 }
1389
Tao Bao51412212016-12-28 14:44:05 -08001390 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
Tao Bao0940fe12015-08-27 16:41:21 -07001391 if (ui == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001392 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001393 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001394
Tao Bao612336d2015-08-27 16:41:21 -07001395 FILE* cmd_pipe = ui->cmd_pipe;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001396 ZipArchiveHandle za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001397
Tao Bao0940fe12015-08-27 16:41:21 -07001398 if (cmd_pipe == nullptr || za == nullptr) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001399 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001400 }
1401
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001402 ZipString path_data(patch_data_fn->data.c_str());
1403 ZipEntry patch_entry;
1404 if (FindEntry(za, path_data, &patch_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001405 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001406 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001407 }
1408
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001409 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1410 ZipString new_data(new_data_fn->data.c_str());
1411 ZipEntry new_entry;
1412 if (FindEntry(za, new_data, &new_entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001413 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001414 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001415 }
1416
Tianjie Xuaced5d92016-10-12 10:55:04 -07001417 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001418 if (params.fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001419 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001420 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001421 }
1422
Sami Tolvanen90221202014-12-09 16:39:47 +00001423 if (params.canwrite) {
1424 params.nti.za = za;
1425 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001426
Tao Bao0940fe12015-08-27 16:41:21 -07001427 pthread_mutex_init(&params.nti.mu, nullptr);
1428 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001429 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001430 pthread_attr_init(&attr);
1431 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1432
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001433 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1434 if (error != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001435 PLOG(ERROR) << "pthread_create failed";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001436 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001437 }
1438 }
1439
Tianjie Xuaced5d92016-10-12 10:55:04 -07001440 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001441 if (lines.size() < 2) {
Tianjie Xu16255832016-04-30 11:49:59 -07001442 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1443 lines.size());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001444 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001445 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001446
Sami Tolvanen90221202014-12-09 16:39:47 +00001447 // First line in transfer list is the version number
Tao Bao51412212016-12-28 14:44:05 -08001448 if (!android::base::ParseInt(lines[0], &params.version, 1, 4)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001449 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001450 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001451 }
1452
Tao Bao039f2da2016-11-22 16:29:50 -08001453 LOG(INFO) << "blockimg version is " << params.version;
Sami Tolvanen90221202014-12-09 16:39:47 +00001454
1455 // Second line in transfer list is the total number of blocks we expect to write
Tao Bao51412212016-12-28 14:44:05 -08001456 size_t total_blocks;
1457 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001458 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001459 return StringValue("");
Tao Baob15fd222015-09-24 11:10:51 -07001460 }
1461
1462 if (total_blocks == 0) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001463 return StringValue("t");
Sami Tolvanen90221202014-12-09 16:39:47 +00001464 }
1465
Tao Bao612336d2015-08-27 16:41:21 -07001466 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001467 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001468 if (lines.size() < 4) {
Tao Bao51412212016-12-28 14:44:05 -08001469 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1470 lines.size());
1471 return StringValue("");
Tao Baobaad2d42015-12-06 16:56:27 -08001472 }
1473
Sami Tolvanen90221202014-12-09 16:39:47 +00001474 // Third line is how many stash entries are needed simultaneously
Tao Bao039f2da2016-11-22 16:29:50 -08001475 LOG(INFO) << "maximum stash entries " << lines[2];
Doug Zongker52ae67d2014-09-08 12:22:09 -07001476
Sami Tolvanen90221202014-12-09 16:39:47 +00001477 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Bao51412212016-12-28 14:44:05 -08001478 size_t stash_max_blocks;
1479 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001480 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1481 lines[3].c_str());
Tianjie Xuaced5d92016-10-12 10:55:04 -07001482 return StringValue("");
Doug Zongker52ae67d2014-09-08 12:22:09 -07001483 }
1484
Tao Bao51412212016-12-28 14:44:05 -08001485 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001486 if (res == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001487 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001488 }
Tao Bao612336d2015-08-27 16:41:21 -07001489
Tao Baob15fd222015-09-24 11:10:51 -07001490 params.createdstash = res;
1491
Tao Bao612336d2015-08-27 16:41:21 -07001492 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001493 }
1494
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001495 // Build a map of the available commands
1496 std::unordered_map<std::string, const Command*> cmd_map;
Tao Bao0940fe12015-08-27 16:41:21 -07001497 for (size_t i = 0; i < cmdcount; ++i) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001498 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001499 LOG(ERROR) << "Error: command [" << commands[i].name
1500 << "] already exists in the cmd map.";
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001501 return StringValue(strdup(""));
1502 }
1503 cmd_map[commands[i].name] = &commands[i];
Sami Tolvanen90221202014-12-09 16:39:47 +00001504 }
1505
Tao Bao612336d2015-08-27 16:41:21 -07001506 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001507
Tao Bao612336d2015-08-27 16:41:21 -07001508 // Subsequent lines are all individual transfer commands
1509 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
Tao Bao51412212016-12-28 14:44:05 -08001510 const std::string& line(*it);
1511 if (line.empty()) continue;
Tao Bao6a47dff2015-09-25 17:12:28 -07001512
Tao Bao51412212016-12-28 14:44:05 -08001513 params.tokens = android::base::Split(line, " ");
Tao Baobaad2d42015-12-06 16:56:27 -08001514 params.cpos = 0;
1515 params.cmdname = params.tokens[params.cpos++].c_str();
Tao Bao51412212016-12-28 14:44:05 -08001516 params.cmdline = line.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001517
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001518 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001519 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001520 goto pbiudone;
1521 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001522
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -07001523 const Command* cmd = cmd_map[params.cmdname];
1524
Tao Bao0940fe12015-08-27 16:41:21 -07001525 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao51412212016-12-28 14:44:05 -08001526 LOG(ERROR) << "failed to execute command [" << line << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001527 goto pbiudone;
1528 }
1529
Sami Tolvanen90221202014-12-09 16:39:47 +00001530 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001531 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001532 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001533 PLOG(ERROR) << "fsync failed";
Tao Bao187efff2015-07-27 14:07:08 -07001534 goto pbiudone;
1535 }
Tao Bao51412212016-12-28 14:44:05 -08001536 fprintf(cmd_pipe, "set_progress %.4f\n",
1537 static_cast<double>(params.written) / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001538 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001539 }
1540 }
1541
Sami Tolvanen90221202014-12-09 16:39:47 +00001542 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001543 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001544
Tao Bao039f2da2016-11-22 16:29:50 -08001545 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1546 LOG(INFO) << "stashed " << params.stashed << " blocks";
1547 LOG(INFO) << "max alloc needed was " << params.buffer.size();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001548
Tianjie Xuaced5d92016-10-12 10:55:04 -07001549 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
Tao Bao51412212016-12-28 14:44:05 -08001550 if (partition != nullptr && *(partition + 1) != 0) {
Tianjie Xudd874b12016-05-13 12:13:15 -07001551 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1552 params.written * BLOCKSIZE);
1553 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1554 params.stashed * BLOCKSIZE);
1555 fflush(cmd_pipe);
1556 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001557 // Delete stash only after successfully completing the update, as it
1558 // may contain blocks needed to complete the update later.
1559 DeleteStash(params.stashbase);
1560 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001561 LOG(INFO) << "verified partition contents; update may be resumed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001562 }
1563
1564 rc = 0;
1565
1566pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001567 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001568 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001569 PLOG(ERROR) << "fsync failed";
Sami Tolvanen90221202014-12-09 16:39:47 +00001570 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001571 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001572
Sami Tolvanen90221202014-12-09 16:39:47 +00001573 // Only delete the stash if the update cannot be resumed, or it's
1574 // a verification run and we created the stash.
1575 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1576 DeleteStash(params.stashbase);
1577 }
1578
Tianjie Xu16255832016-04-30 11:49:59 -07001579 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1580 state->cause_code = failure_type;
1581 }
1582
Tianjie Xuaced5d92016-10-12 10:55:04 -07001583 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001584}
1585
1586// The transfer list is a text file containing commands to
1587// transfer data from one place to another on the target
1588// partition. We parse it and execute the commands in order:
1589//
1590// zero [rangeset]
1591// - fill the indicated blocks with zeros
1592//
1593// new [rangeset]
1594// - fill the blocks with data read from the new_data file
1595//
1596// erase [rangeset]
1597// - mark the given blocks as empty
1598//
1599// move <...>
1600// bsdiff <patchstart> <patchlen> <...>
1601// imgdiff <patchstart> <patchlen> <...>
1602// - read the source blocks, apply a patch (or not in the
1603// case of move), write result to target blocks. bsdiff or
1604// imgdiff specifies the type of patch; move means no patch
1605// at all.
1606//
1607// The format of <...> differs between versions 1 and 2;
1608// see the LoadSrcTgtVersion{1,2}() functions for a
1609// description of what's expected.
1610//
1611// stash <stash_id> <src_range>
1612// - (version 2+ only) load the given source range and stash
1613// the data in the given slot of the stash table.
1614//
Tao Baobaad2d42015-12-06 16:56:27 -08001615// free <stash_id>
1616// - (version 3+ only) free the given stash data.
1617//
Sami Tolvanen90221202014-12-09 16:39:47 +00001618// The creator of the transfer list will guarantee that no block
1619// is read (ie, used as the source for a patch or move) after it
1620// has been written.
1621//
1622// In version 2, the creator will guarantee that a given stash is
1623// loaded (with a stash command) before it's used in a
1624// move/bsdiff/imgdiff command.
1625//
1626// Within one command the source and target ranges may overlap so
1627// in general we need to read the entire source into memory before
1628// writing anything to the target blocks.
1629//
1630// All the patch data is concatenated into one patch_data file in
1631// the update package. It must be stored uncompressed because we
1632// memory-map it in directly from the archive. (Since patches are
1633// already compressed, we lose very little by not compressing
1634// their concatenation.)
1635//
1636// In version 3, commands that read data from the partition (i.e.
1637// move/bsdiff/imgdiff/stash) have one or more additional hashes
1638// before the range parameters, which are used to check if the
1639// command has already been completed and verify the integrity of
1640// the source data.
1641
1642Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001643 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001644 const Command commands[] = {
1645 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001646 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001647 { "free", PerformCommandFree },
1648 { "imgdiff", PerformCommandDiff },
1649 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001650 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001651 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001652 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001653 };
1654
1655 // Perform a dry run without writing to test if an update can proceed
1656 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001657 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001658}
1659
1660Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1661 const Command commands[] = {
1662 { "bsdiff", PerformCommandDiff },
1663 { "erase", PerformCommandErase },
1664 { "free", PerformCommandFree },
1665 { "imgdiff", PerformCommandDiff },
1666 { "move", PerformCommandMove },
1667 { "new", PerformCommandNew },
1668 { "stash", PerformCommandStash },
1669 { "zero", PerformCommandZero }
1670 };
1671
1672 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001673 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001674}
1675
Tao Bao0940fe12015-08-27 16:41:21 -07001676Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001677 std::vector<std::unique_ptr<Value>> args;
1678 if (!ReadValueArgs(state, 2, argv, &args)) {
1679 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001680 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001681
1682 const Value* blockdev_filename = args[0].get();
1683 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001684
1685 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001686 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1687 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001688 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001689 }
1690 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001691 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001692 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001693 }
1694
Tianjie Xuaced5d92016-10-12 10:55:04 -07001695 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001696 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001697 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1698 blockdev_filename->data.c_str(), strerror(errno));
1699 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001700 }
1701
Tao Baoc844c062016-12-28 15:15:55 -08001702 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001703
1704 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001705 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001706
Tao Bao612336d2015-08-27 16:41:21 -07001707 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001708 for (size_t i = 0; i < rs.count; ++i) {
1709 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001710 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1711 blockdev_filename->data.c_str(), strerror(errno));
1712 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001713 }
1714
Tao Bao0940fe12015-08-27 16:41:21 -07001715 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001716 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001717 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1718 blockdev_filename->data.c_str(), strerror(errno));
1719 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001720 }
1721
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001722 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001723 }
1724 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001725 uint8_t digest[SHA_DIGEST_LENGTH];
1726 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001727
Tianjie Xuaced5d92016-10-12 10:55:04 -07001728 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001729}
1730
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001731// This function checks if a device has been remounted R/W prior to an incremental
1732// OTA update. This is an common cause of update abortion. The function reads the
1733// 1st block of each partition and check for mounting time/count. It return string "t"
1734// if executes successfully and an empty string otherwise.
1735
1736Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001737 std::vector<std::unique_ptr<Value>> args;
1738 if (!ReadValueArgs(state, 1, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001739 return nullptr;
1740 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001741
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001742 const Value* arg_filename = args[0].get();
1743
1744 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001745 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001746 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001747 }
1748
Tianjie Xuaced5d92016-10-12 10:55:04 -07001749 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001750 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001751 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001752 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001753 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001754 }
1755
1756 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1757 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1758
1759 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001760 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001761 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001762 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001763 }
1764
1765 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1766 // Super block starts from block 0, offset 0x400
1767 // 0x2C: len32 Mount time
1768 // 0x30: len32 Write time
1769 // 0x34: len16 Number of mounts since the last fsck
1770 // 0x38: len16 Magic signature 0xEF53
1771
1772 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1773 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1774
1775 if (mount_count > 0) {
1776 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1777 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1778 }
1779
Tianjie Xuaced5d92016-10-12 10:55:04 -07001780 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001781}
1782
1783
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001784Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001785 std::vector<std::unique_ptr<Value>> args;
1786 if (!ReadValueArgs(state, 2, argv, &args)) {
1787 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001788 }
1789
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001790 const Value* filename = args[0].get();
1791 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001792
1793 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001794 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001795 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001796 }
1797 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001798 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001799 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001800 }
1801
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001802 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001803 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001804
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001805 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tianjie Xuaced5d92016-10-12 10:55:04 -07001806 fec::io fh(filename->data.c_str(), O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001807
1808 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001809 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001810 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001811 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001812 }
1813
1814 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001815 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001816 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001817 }
1818
1819 fec_status status;
1820
1821 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001822 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001823 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001824 }
1825
Tao Baoc844c062016-12-28 15:15:55 -08001826 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001827
1828 uint8_t buffer[BLOCKSIZE];
1829
1830 for (size_t i = 0; i < rs.count; ++i) {
1831 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1832 // Stay within the data area, libfec validates and corrects metadata
1833 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1834 continue;
1835 }
1836
1837 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001838 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001839 filename->data.c_str(), j, strerror(errno));
1840 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001841 }
1842
1843 // If we want to be able to recover from a situation where rewriting a corrected
1844 // block doesn't guarantee the same data will be returned when re-read later, we
1845 // can save a copy of corrected blocks to /cache. Note:
1846 //
1847 // 1. Maximum space required from /cache is the same as the maximum number of
1848 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1849 // this would be ~16 MiB, for example.
1850 //
1851 // 2. To find out if this block was corrupted, call fec_get_status after each
1852 // read and check if the errors field value has increased.
1853 }
1854 }
Tao Bao039f2da2016-11-22 16:29:50 -08001855 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001856 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001857}
1858
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001859void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001860 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001861 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001862 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001863 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001864 RegisterFunction("range_sha1", RangeSha1Fn);
1865}