blob: 7aff7fff70c2e39aeb70af46b63a23c662b9a54c [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>
21#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000028#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070029#include <sys/types.h>
30#include <sys/wait.h>
31#include <sys/ioctl.h>
32#include <time.h>
33#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010034#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070035
Tianjie Xu7eca97e2016-03-22 18:08:12 -070036#include <map>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tao Bao0940fe12015-08-27 16:41:21 -070039#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070040
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 Baoe6aa3322015-08-05 15:20:27 -070044
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070045#include "applypatch/applypatch.h"
46#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070047#include "error_code.h"
Tianjie Xu57bed6d2015-12-15 11:47:30 -080048#include "install.h"
Sen Jiangc48cb5e2016-02-04 16:23:21 +080049#include "openssl/sha.h"
Sami Tolvanen90221202014-12-09 16:39:47 +000050#include "minzip/Hash.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 Bao0940fe12015-08-27 16:41:21 -070053#include "updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070054
55#define BLOCKSIZE 4096
56
Sami Tolvanene82fa182015-06-10 15:58:12 +000057// Set this to 0 to interpret 'erase' transfers to mean do a
58// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
59// erase to mean fill the region with zeroes.
60#define DEBUG_ERASE 0
61
Sami Tolvanen90221202014-12-09 16:39:47 +000062#define STASH_DIRECTORY_BASE "/cache/recovery"
63#define STASH_DIRECTORY_MODE 0700
64#define STASH_FILE_MODE 0600
65
Tao Bao0940fe12015-08-27 16:41:21 -070066struct RangeSet {
67 size_t count; // Limit is INT_MAX.
Shrinivas Sahukara6153df2015-08-19 13:01:45 +053068 size_t size;
Tao Bao0940fe12015-08-27 16:41:21 -070069 std::vector<size_t> pos; // Actual limit is INT_MAX.
70};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070071
Tianjie Xu16255832016-04-30 11:49:59 -070072static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070073static bool is_retry = false;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070074static std::map<std::string, RangeSet> stash_map;
75
Tao Baobaad2d42015-12-06 16:56:27 -080076static void parse_range(const std::string& range_text, RangeSet& rs) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010077
Tao Baobaad2d42015-12-06 16:56:27 -080078 std::vector<std::string> pieces = android::base::Split(range_text, ",");
Tao Bao0940fe12015-08-27 16:41:21 -070079 if (pieces.size() < 3) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010080 goto err;
81 }
82
Tao Baob15fd222015-09-24 11:10:51 -070083 size_t num;
84 if (!android::base::ParseUint(pieces[0].c_str(), &num, static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010085 goto err;
86 }
87
Tao Baob15fd222015-09-24 11:10:51 -070088 if (num == 0 || num % 2) {
89 goto err; // must be even
90 } else if (num != pieces.size() - 1) {
91 goto err;
92 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +010093
Tao Bao0940fe12015-08-27 16:41:21 -070094 rs.pos.resize(num);
95 rs.count = num / 2;
96 rs.size = 0;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010097
Tao Bao0940fe12015-08-27 16:41:21 -070098 for (size_t i = 0; i < num; i += 2) {
Tao Baob15fd222015-09-24 11:10:51 -070099 if (!android::base::ParseUint(pieces[i+1].c_str(), &rs.pos[i],
100 static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100101 goto err;
102 }
103
Tao Baob15fd222015-09-24 11:10:51 -0700104 if (!android::base::ParseUint(pieces[i+2].c_str(), &rs.pos[i+1],
105 static_cast<size_t>(INT_MAX))) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530106 goto err;
107 }
108
Tao Bao0940fe12015-08-27 16:41:21 -0700109 if (rs.pos[i] >= rs.pos[i+1]) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530110 goto err; // empty or negative range
111 }
112
Tao Bao0940fe12015-08-27 16:41:21 -0700113 size_t sz = rs.pos[i+1] - rs.pos[i];
114 if (rs.size > SIZE_MAX - sz) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530115 goto err; // overflow
116 }
117
Tao Bao0940fe12015-08-27 16:41:21 -0700118 rs.size += sz;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700119 }
120
Tao Bao0940fe12015-08-27 16:41:21 -0700121 return;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100122
123err:
Tao Baobaad2d42015-12-06 16:56:27 -0800124 fprintf(stderr, "failed to parse range '%s'\n", range_text.c_str());
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100125 exit(1);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700126}
127
Tao Baoe6aa3322015-08-05 15:20:27 -0700128static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530129 for (size_t i = 0; i < r1.count; ++i) {
130 size_t r1_0 = r1.pos[i * 2];
131 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000132
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530133 for (size_t j = 0; j < r2.count; ++j) {
134 size_t r2_0 = r2.pos[j * 2];
135 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000136
Tao Baoc0f56ad2015-06-25 14:00:31 -0700137 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700138 return true;
Sami Tolvanen90221202014-12-09 16:39:47 +0000139 }
140 }
141 }
142
Tao Baoe6aa3322015-08-05 15:20:27 -0700143 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000144}
145
146static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700147 size_t so_far = 0;
148 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800149 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700150 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700151 failure_type = kFreadFailure;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700152 fprintf(stderr, "read failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000153 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700154 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700155 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700156 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000157 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700158}
159
Tao Bao612336d2015-08-27 16:41:21 -0700160static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
161 return read_all(fd, buffer.data(), size);
162}
163
Sami Tolvanen90221202014-12-09 16:39:47 +0000164static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700165 size_t written = 0;
166 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800167 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700168 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700169 failure_type = kFwriteFailure;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700170 fprintf(stderr, "write failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000171 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700172 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700173 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700174 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000175
Sami Tolvanen90221202014-12-09 16:39:47 +0000176 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700177}
178
Tao Bao612336d2015-08-27 16:41:21 -0700179static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
180 return write_all(fd, buffer.data(), size);
181}
182
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700183static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
184 // Don't discard blocks unless the update is a retry run.
185 if (!is_retry) {
186 return true;
187 }
188
189 uint64_t args[2] = {static_cast<uint64_t>(offset), size};
190 int status = ioctl(fd, BLKDISCARD, &args);
191 if (status == -1) {
192 fprintf(stderr, "BLKDISCARD ioctl failed: %s\n", strerror(errno));
193 return false;
194 }
195 return true;
196}
197
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700198static bool check_lseek(int fd, off64_t offset, int whence) {
199 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
200 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700201 failure_type = kLseekFailure;
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700202 fprintf(stderr, "lseek64 failed: %s\n", strerror(errno));
203 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700204 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700205 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700206}
207
Tao Bao612336d2015-08-27 16:41:21 -0700208static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700209 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700210 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700211
Tao Bao612336d2015-08-27 16:41:21 -0700212 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700213}
214
Tao Bao0940fe12015-08-27 16:41:21 -0700215struct RangeSinkState {
Chih-Hung Hsieh49c5c792016-04-29 14:16:35 -0700216 explicit RangeSinkState(RangeSet& rs) : tgt(rs) { };
Tao Bao0940fe12015-08-27 16:41:21 -0700217
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700218 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700219 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530220 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700221 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700222};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700223
224static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700225 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700226
Tao Bao0940fe12015-08-27 16:41:21 -0700227 if (rss->p_remain == 0) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700228 fprintf(stderr, "range sink write overrun");
Sami Tolvanen90221202014-12-09 16:39:47 +0000229 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700230 }
231
232 ssize_t written = 0;
233 while (size > 0) {
234 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000235
236 if (rss->p_remain < write_now) {
237 write_now = rss->p_remain;
238 }
239
240 if (write_all(rss->fd, data, write_now) == -1) {
241 break;
242 }
243
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700244 data += write_now;
245 size -= write_now;
246
247 rss->p_remain -= write_now;
248 written += write_now;
249
250 if (rss->p_remain == 0) {
251 // move to the next block
252 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700253 if (rss->p_block < rss->tgt.count) {
254 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
255 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000256
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700257 off64_t offset = static_cast<off64_t>(rss->tgt.pos[rss->p_block*2]) * BLOCKSIZE;
258 if (!discard_blocks(rss->fd, offset, rss->p_remain)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000259 break;
260 }
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700261
262 if (!check_lseek(rss->fd, offset, SEEK_SET)) {
263 break;
264 }
265
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700266 } else {
267 // we can't write any more; return how many bytes have
268 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000269 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700270 }
271 }
272 }
273
274 return written;
275}
276
277// All of the data for all the 'new' transfers is contained in one
278// file in the update package, concatenated together in the order in
279// which transfers.list will need it. We want to stream it out of the
280// archive (it's compressed) without writing it to a temp file, but we
281// can't write each section until it's that transfer's turn to go.
282//
283// To achieve this, we expand the new data from the archive in a
284// background thread, and block that threads 'receive uncompressed
285// data' function until the main thread has reached a point where we
286// want some new data to be written. We signal the background thread
287// with the destination for the data and block the main thread,
288// waiting for the background thread to complete writing that section.
289// Then it signals the main thread to wake up and goes back to
290// blocking waiting for a transfer.
291//
292// NewThreadInfo is the struct used to pass information back and forth
293// between the two threads. When the main thread wants some data
294// written, it sets rss to the destination location and signals the
295// condition. When the background thread is done writing, it clears
296// rss and signals the condition again.
297
Tao Bao0940fe12015-08-27 16:41:21 -0700298struct NewThreadInfo {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700299 ZipArchive* za;
300 const ZipEntry* entry;
301
302 RangeSinkState* rss;
303
304 pthread_mutex_t mu;
305 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700306};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700307
308static bool receive_new_data(const unsigned char* data, int size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700309 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700310
311 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700312 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700313 // data is wanted.
314 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700315 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700316 pthread_cond_wait(&nti->cv, &nti->mu);
317 }
318 pthread_mutex_unlock(&nti->mu);
319
320 // At this point nti->rss is set, and we own it. The main
321 // thread is waiting for it to disappear from nti.
322 ssize_t written = RangeSinkWrite(data, size, nti->rss);
323 data += written;
324 size -= written;
325
Tao Bao0940fe12015-08-27 16:41:21 -0700326 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700327 // we have written all the bytes desired by this rss.
328
329 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700330 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700331 pthread_cond_broadcast(&nti->cv);
332 pthread_mutex_unlock(&nti->mu);
333 }
334 }
335
336 return true;
337}
338
339static void* unzip_new_data(void* cookie) {
340 NewThreadInfo* nti = (NewThreadInfo*) cookie;
341 mzProcessZipEntryContents(nti->za, nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700342 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700343}
344
Tao Bao612336d2015-08-27 16:41:21 -0700345static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000346 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700347 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000348
Tao Bao0940fe12015-08-27 16:41:21 -0700349 for (size_t i = 0; i < src.count; ++i) {
350 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000351 return -1;
352 }
353
Tao Bao0940fe12015-08-27 16:41:21 -0700354 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000355
Tao Bao612336d2015-08-27 16:41:21 -0700356 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000357 return -1;
358 }
359
360 p += size;
361 }
362
363 return 0;
364}
365
Tao Bao612336d2015-08-27 16:41:21 -0700366static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
367 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000368
Tao Bao0940fe12015-08-27 16:41:21 -0700369 size_t p = 0;
370 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700371 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
372 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
373 if (!discard_blocks(fd, offset, size)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000374 return -1;
375 }
376
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700377 if (!check_lseek(fd, offset, SEEK_SET)) {
378 return -1;
379 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000380
Tao Bao612336d2015-08-27 16:41:21 -0700381 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000382 return -1;
383 }
384
385 p += size;
386 }
387
388 return 0;
389}
390
Tao Baobaad2d42015-12-06 16:56:27 -0800391// Parameters for transfer list command functions
392struct CommandParameters {
393 std::vector<std::string> tokens;
394 size_t cpos;
395 const char* cmdname;
396 const char* cmdline;
397 std::string freestash;
398 std::string stashbase;
399 bool canwrite;
400 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700401 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800402 bool foundwrites;
403 bool isunresumable;
404 int version;
405 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700406 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800407 NewThreadInfo nti;
408 pthread_t thread;
409 std::vector<uint8_t> buffer;
410 uint8_t* patch_start;
411};
412
Doug Zongker52ae67d2014-09-08 12:22:09 -0700413// Do a source/target load for move/bsdiff/imgdiff in version 1.
Tao Baobaad2d42015-12-06 16:56:27 -0800414// We expect to parse the remainder of the parameter tokens as:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700415//
416// <src_range> <tgt_range>
417//
418// The source range is loaded into the provided buffer, reallocating
Tao Bao34847b22015-09-08 11:05:49 -0700419// it to make it larger if necessary.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700420
Tao Baobaad2d42015-12-06 16:56:27 -0800421static int LoadSrcTgtVersion1(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700422 std::vector<uint8_t>& buffer, int fd) {
Tao Baobaad2d42015-12-06 16:56:27 -0800423
424 if (params.cpos + 1 >= params.tokens.size()) {
425 fprintf(stderr, "invalid parameters\n");
426 return -1;
427 }
428
Tao Bao612336d2015-08-27 16:41:21 -0700429 // <src_range>
Tao Bao0940fe12015-08-27 16:41:21 -0700430 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800431 parse_range(params.tokens[params.cpos++], src);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700432
Tao Bao612336d2015-08-27 16:41:21 -0700433 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800434 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700435
Tao Bao612336d2015-08-27 16:41:21 -0700436 allocate(src.size * BLOCKSIZE, buffer);
437 int rc = ReadBlocks(src, buffer, fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700438 src_blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000439
Sami Tolvanen90221202014-12-09 16:39:47 +0000440 return rc;
441}
442
Tao Bao612336d2015-08-27 16:41:21 -0700443static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700444 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800445 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700446 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000447
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800448 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000449
Tao Baoe6aa3322015-08-05 15:20:27 -0700450 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000451
Tao Bao0940fe12015-08-27 16:41:21 -0700452 if (hexdigest != expected) {
453 if (printerror) {
454 fprintf(stderr, "failed to verify blocks (expected %s, read %s)\n",
455 expected.c_str(), hexdigest.c_str());
456 }
457 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000458 }
459
Tao Bao0940fe12015-08-27 16:41:21 -0700460 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000461}
462
Tao Bao0940fe12015-08-27 16:41:21 -0700463static std::string GetStashFileName(const std::string& base, const std::string& id,
464 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700465 if (base.empty()) {
466 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000467 }
468
Tao Baoe6aa3322015-08-05 15:20:27 -0700469 std::string fn(STASH_DIRECTORY_BASE);
470 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000471
472 return fn;
473}
474
Tao Baoe6aa3322015-08-05 15:20:27 -0700475typedef void (*StashCallback)(const std::string&, void*);
Sami Tolvanen90221202014-12-09 16:39:47 +0000476
477// Does a best effort enumeration of stash files. Ignores possible non-file
478// items in the stash directory and continues despite of errors. Calls the
479// 'callback' function for each file and passes 'data' to the function as a
480// parameter.
481
Tao Baoe6aa3322015-08-05 15:20:27 -0700482static void EnumerateStash(const std::string& dirname, StashCallback callback, void* data) {
Tao Bao0940fe12015-08-27 16:41:21 -0700483 if (dirname.empty() || callback == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000484 return;
485 }
486
Tao Baoe6aa3322015-08-05 15:20:27 -0700487 std::unique_ptr<DIR, int(*)(DIR*)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000488
Tao Bao0940fe12015-08-27 16:41:21 -0700489 if (directory == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000490 if (errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700491 fprintf(stderr, "opendir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000492 }
493 return;
494 }
495
Tao Baoe6aa3322015-08-05 15:20:27 -0700496 struct dirent* item;
Tao Bao0940fe12015-08-27 16:41:21 -0700497 while ((item = readdir(directory.get())) != nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000498 if (item->d_type != DT_REG) {
499 continue;
500 }
501
Tao Baoe6aa3322015-08-05 15:20:27 -0700502 std::string fn = dirname + "/" + std::string(item->d_name);
Sami Tolvanen90221202014-12-09 16:39:47 +0000503 callback(fn, data);
Sami Tolvanen90221202014-12-09 16:39:47 +0000504 }
505}
506
Tao Baoe6aa3322015-08-05 15:20:27 -0700507static void UpdateFileSize(const std::string& fn, void* data) {
508 if (fn.empty() || !data) {
509 return;
510 }
511
Tao Bao0940fe12015-08-27 16:41:21 -0700512 struct stat sb;
513 if (stat(fn.c_str(), &sb) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700514 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000515 return;
516 }
517
Tao Baoe6aa3322015-08-05 15:20:27 -0700518 int* size = reinterpret_cast<int*>(data);
Tao Bao0940fe12015-08-27 16:41:21 -0700519 *size += sb.st_size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000520}
521
522// Deletes the stash directory and all files in it. Assumes that it only
523// contains files. There is nothing we can do about unlikely, but possible
524// errors, so they are merely logged.
525
Tao Bao0940fe12015-08-27 16:41:21 -0700526static void DeleteFile(const std::string& fn, void* /* data */) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700527 if (!fn.empty()) {
528 fprintf(stderr, "deleting %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000529
Tao Baoe6aa3322015-08-05 15:20:27 -0700530 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
531 fprintf(stderr, "unlink \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000532 }
533 }
534}
535
Tao Baoe6aa3322015-08-05 15:20:27 -0700536static void DeletePartial(const std::string& fn, void* data) {
537 if (android::base::EndsWith(fn, ".partial")) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000538 DeleteFile(fn, data);
539 }
540}
541
Tao Baoe6aa3322015-08-05 15:20:27 -0700542static void DeleteStash(const std::string& base) {
543 if (base.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000544 return;
545 }
546
Tao Baoe6aa3322015-08-05 15:20:27 -0700547 fprintf(stderr, "deleting stash %s\n", base.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000548
Tao Baoe6aa3322015-08-05 15:20:27 -0700549 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700550 EnumerateStash(dirname, DeleteFile, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000551
Tao Baoe6aa3322015-08-05 15:20:27 -0700552 if (rmdir(dirname.c_str()) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000553 if (errno != ENOENT && errno != ENOTDIR) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700554 fprintf(stderr, "rmdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000555 }
556 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000557}
558
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700559static int LoadStash(CommandParameters& params, const std::string& base, const std::string& id,
560 bool verify, size_t* blocks, std::vector<uint8_t>& buffer, bool printnoent) {
561 // In verify mode, if source range_set was saved for the given hash,
562 // check contents in the source blocks first. If the check fails,
563 // search for the stashed files on /cache as usual.
564 if (!params.canwrite) {
565 if (stash_map.find(id) != stash_map.end()) {
566 const RangeSet& src = stash_map[id];
567 allocate(src.size * BLOCKSIZE, buffer);
568
569 if (ReadBlocks(src, buffer, params.fd) == -1) {
570 fprintf(stderr, "failed to read source blocks in stash map.\n");
571 return -1;
572 }
573 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
574 fprintf(stderr, "failed to verify loaded source blocks in stash map.\n");
575 return -1;
576 }
577 return 0;
578 }
579 }
580
Tao Bao612336d2015-08-27 16:41:21 -0700581 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700582 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000583 }
584
Tao Bao0940fe12015-08-27 16:41:21 -0700585 size_t blockcount = 0;
586
Sami Tolvanen90221202014-12-09 16:39:47 +0000587 if (!blocks) {
588 blocks = &blockcount;
589 }
590
Tao Bao0940fe12015-08-27 16:41:21 -0700591 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000592
Tao Bao0940fe12015-08-27 16:41:21 -0700593 struct stat sb;
594 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000595
596 if (res == -1) {
597 if (errno != ENOENT || printnoent) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700598 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000599 }
Tao Bao0940fe12015-08-27 16:41:21 -0700600 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000601 }
602
Tao Baoe6aa3322015-08-05 15:20:27 -0700603 fprintf(stderr, " loading %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000604
Tao Bao0940fe12015-08-27 16:41:21 -0700605 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700606 fprintf(stderr, "%s size %" PRId64 " not multiple of block size %d",
Tao Bao0940fe12015-08-27 16:41:21 -0700607 fn.c_str(), static_cast<int64_t>(sb.st_size), BLOCKSIZE);
608 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 Baoe6aa3322015-08-05 15:20:27 -0700613 fprintf(stderr, "open \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
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 Baoe6aa3322015-08-05 15:20:27 -0700626 fprintf(stderr, "unexpected contents in %s\n", fn.c_str());
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) {
641 fprintf(stderr, "not enough space to write stash\n");
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 Baoe6aa3322015-08-05 15:20:27 -0700656 fprintf(stderr, " skipping %d existing blocks in %s\n", blocks, cn.c_str());
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 Baoe6aa3322015-08-05 15:20:27 -0700664 fprintf(stderr, " writing %d blocks to %s\n", blocks, cn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000665
Elliott Hughesbcabd092016-03-22 20:19:22 -0700666 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(),
667 O_WRONLY | O_CREAT | O_TRUNC,
668 STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000669 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700670 fprintf(stderr, "failed to create \"%s\": %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700671 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000672 }
673
674 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700675 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000676 }
677
Jed Estepa7b9a462015-12-15 16:04:53 -0800678 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700679 failure_type = kFsyncFailure;
Tao Baoe6aa3322015-08-05 15:20:27 -0700680 fprintf(stderr, "fsync \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700681 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000682 }
683
Tao Baoe6aa3322015-08-05 15:20:27 -0700684 if (rename(fn.c_str(), cn.c_str()) == -1) {
685 fprintf(stderr, "rename(\"%s\", \"%s\") failed: %s\n", fn.c_str(), cn.c_str(),
686 strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700687 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000688 }
689
Tao Bao0940fe12015-08-27 16:41:21 -0700690 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700691 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
692 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700693 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700694 failure_type = kFileOpenFailure;
Tao Baoe6aa3322015-08-05 15:20:27 -0700695 fprintf(stderr, "failed to open \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700696 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700697 }
698
Jed Estepa7b9a462015-12-15 16:04:53 -0800699 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700700 failure_type = kFsyncFailure;
Tao Baoe6aa3322015-08-05 15:20:27 -0700701 fprintf(stderr, "fsync \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700702 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700703 }
704
Tao Bao0940fe12015-08-27 16:41:21 -0700705 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000706}
707
708// Creates a directory for storing stash files and checks if the /cache partition
709// hash enough space for the expected amount of blocks we need to store. Returns
710// >0 if we created the directory, zero if it existed already, and <0 of failure.
711
Tao Bao0940fe12015-08-27 16:41:21 -0700712static int CreateStash(State* state, int maxblocks, const char* blockdev, std::string& base) {
713 if (blockdev == nullptr) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700714 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000715 }
716
717 // Stash directory should be different for each partition to avoid conflicts
718 // when updating multiple partitions at the same time, so we use the hash of
719 // the block device name as the base directory
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800720 uint8_t digest[SHA_DIGEST_LENGTH];
721 SHA1(reinterpret_cast<const uint8_t*>(blockdev), strlen(blockdev), digest);
Tao Baoe6aa3322015-08-05 15:20:27 -0700722 base = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000723
Tao Baoe6aa3322015-08-05 15:20:27 -0700724 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700725 struct stat sb;
726 int res = stat(dirname.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000727
728 if (res == -1 && errno != ENOENT) {
Tianjie Xu16255832016-04-30 11:49:59 -0700729 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n",
730 dirname.c_str(), strerror(errno));
Tao Baoe6aa3322015-08-05 15:20:27 -0700731 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000732 } else if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700733 fprintf(stderr, "creating stash %s\n", dirname.c_str());
734 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000735
736 if (res != 0) {
Tianjie Xu16255832016-04-30 11:49:59 -0700737 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n",
738 dirname.c_str(), strerror(errno));
Tao Baoe6aa3322015-08-05 15:20:27 -0700739 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000740 }
741
742 if (CacheSizeCheck(maxblocks * BLOCKSIZE) != 0) {
Tianjie Xu16255832016-04-30 11:49:59 -0700743 ErrorAbort(state, kStashCreationFailure, "not enough space for stash\n");
Tao Baoe6aa3322015-08-05 15:20:27 -0700744 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000745 }
746
Tao Baoe6aa3322015-08-05 15:20:27 -0700747 return 1; // Created directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000748 }
749
Tao Baoe6aa3322015-08-05 15:20:27 -0700750 fprintf(stderr, "using existing stash %s\n", dirname.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000751
752 // If the directory already exists, calculate the space already allocated to
753 // stash files and check if there's enough for all required blocks. Delete any
754 // partially completed stash files first.
755
Tao Bao0940fe12015-08-27 16:41:21 -0700756 EnumerateStash(dirname, DeletePartial, nullptr);
Tao Baoe6aa3322015-08-05 15:20:27 -0700757 int size = 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000758 EnumerateStash(dirname, UpdateFileSize, &size);
759
Tao Bao0940fe12015-08-27 16:41:21 -0700760 size = maxblocks * BLOCKSIZE - size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000761
762 if (size > 0 && CacheSizeCheck(size) != 0) {
Tianjie Xu16255832016-04-30 11:49:59 -0700763 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%d more needed)\n",
764 size);
Tao Baoe6aa3322015-08-05 15:20:27 -0700765 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000766 }
767
Tao Baoe6aa3322015-08-05 15:20:27 -0700768 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000769}
770
Tao Baobaad2d42015-12-06 16:56:27 -0800771static int SaveStash(CommandParameters& params, const std::string& base,
772 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000773
Tao Baobaad2d42015-12-06 16:56:27 -0800774 // <stash_id> <src_range>
775 if (params.cpos + 1 >= params.tokens.size()) {
776 fprintf(stderr, "missing id and/or src range fields in stash command\n");
Sami Tolvanen90221202014-12-09 16:39:47 +0000777 return -1;
778 }
Tao Baobaad2d42015-12-06 16:56:27 -0800779 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000780
Tao Bao0940fe12015-08-27 16:41:21 -0700781 size_t blocks = 0;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700782 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000783 // Stash file already exists and has expected contents. Do not
784 // read from source again, as the source may have been already
785 // overwritten during a previous attempt.
786 return 0;
787 }
788
Tao Bao34847b22015-09-08 11:05:49 -0700789 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800790 parse_range(params.tokens[params.cpos++], src);
Tao Bao34847b22015-09-08 11:05:49 -0700791
Tao Bao612336d2015-08-27 16:41:21 -0700792 allocate(src.size * BLOCKSIZE, buffer);
793 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000794 return -1;
795 }
Tao Bao34847b22015-09-08 11:05:49 -0700796 blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000797
Tao Bao612336d2015-08-27 16:41:21 -0700798 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000799 // Source blocks have unexpected contents. If we actually need this
800 // data later, this is an unrecoverable error. However, the command
801 // that uses the data may have already completed previously, so the
802 // possible failure will occur during source block verification.
Tao Bao0940fe12015-08-27 16:41:21 -0700803 fprintf(stderr, "failed to load source blocks for stash %s\n", id.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000804 return 0;
805 }
806
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700807 // In verify mode, save source range_set instead of stashing blocks.
808 if (!params.canwrite && usehash) {
809 stash_map[id] = src;
810 return 0;
811 }
812
Tao Bao0940fe12015-08-27 16:41:21 -0700813 fprintf(stderr, "stashing %zu blocks to %s\n", blocks, id.c_str());
Tianjie Xudd874b12016-05-13 12:13:15 -0700814 params.stashed += blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700815 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000816}
817
Tao Baobaad2d42015-12-06 16:56:27 -0800818static int FreeStash(const std::string& base, const std::string& id) {
819 if (base.empty() || id.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000820 return -1;
821 }
822
Tao Baobaad2d42015-12-06 16:56:27 -0800823 std::string fn = GetStashFileName(base, id, "");
Tao Bao0940fe12015-08-27 16:41:21 -0700824 DeleteFile(fn, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000825
826 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700827}
828
Tao Bao612336d2015-08-27 16:41:21 -0700829static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
830 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700831 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700832 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700833 // may be the same buffer.
834
Tao Bao612336d2015-08-27 16:41:21 -0700835 const uint8_t* from = source.data();
836 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700837 size_t start = locs.size;
838 for (int i = locs.count-1; i >= 0; --i) {
839 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700840 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700841 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700842 blocks * BLOCKSIZE);
843 }
844}
845
846// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800847// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700848//
849// <tgt_range> <src_block_count> <src_range>
850// (loads data from source image only)
851//
852// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
853// (loads data from stashes only)
854//
855// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
856// (loads data from both source image and stashes)
857//
858// On return, buffer is filled with the loaded source data (rearranged
859// and combined with stashed data as necessary). buffer may be
860// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000861// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700862
Tao Baobaad2d42015-12-06 16:56:27 -0800863static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700864 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800865
866 // At least it needs to provide three parameters: <tgt_range>,
867 // <src_block_count> and "-"/<src_range>.
868 if (params.cpos + 2 >= params.tokens.size()) {
869 fprintf(stderr, "invalid parameters\n");
870 return -1;
871 }
872
Tao Bao612336d2015-08-27 16:41:21 -0700873 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800874 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700875
Tao Bao612336d2015-08-27 16:41:21 -0700876 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800877 const std::string& token = params.tokens[params.cpos++];
878 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
879 fprintf(stderr, "invalid src_block_count \"%s\"\n", token.c_str());
880 return -1;
881 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700882
Tao Bao612336d2015-08-27 16:41:21 -0700883 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700884
Tao Bao612336d2015-08-27 16:41:21 -0700885 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800886 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700887 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800888 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700889 } else {
Tao Bao0940fe12015-08-27 16:41:21 -0700890 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800891 parse_range(params.tokens[params.cpos++], src);
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 Bao612336d2015-08-27 16:41:21 -0700907 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800908 parse_range(params.tokens[params.cpos++], locs);
Tao Bao612336d2015-08-27 16:41:21 -0700909 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700910 }
911
Tao Baobaad2d42015-12-06 16:56:27 -0800912 // <[stash_id:stash_range]>
913 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700914 // Each word is a an index into the stash table, a colon, and
915 // then a rangeset describing where in the source block that
916 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800917 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
918 if (tokens.size() != 2) {
919 fprintf(stderr, "invalid parameter\n");
920 return -1;
921 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000922
Tao Bao612336d2015-08-27 16:41:21 -0700923 std::vector<uint8_t> stash;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700924 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000925
926 if (res == -1) {
927 // These source blocks will fail verification if used later, but we
928 // will let the caller decide if this is a fatal failure
Tao Baobaad2d42015-12-06 16:56:27 -0800929 fprintf(stderr, "failed to load stash %s\n", tokens[0].c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000930 continue;
931 }
932
Tao Bao612336d2015-08-27 16:41:21 -0700933 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800934 parse_range(tokens[1], locs);
Sami Tolvanen90221202014-12-09 16:39:47 +0000935
Tao Bao612336d2015-08-27 16:41:21 -0700936 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000937 }
938
939 return 0;
940}
941
Sami Tolvanen90221202014-12-09 16:39:47 +0000942// Do a source/target load for move/bsdiff/imgdiff in version 3.
943//
944// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
945// tells the function whether to expect separate source and targe block hashes, or
946// if they are both the same and only one hash should be expected, and
947// 'isunresumable', which receives a non-zero value if block verification fails in
948// a way that the update cannot be resumed anymore.
949//
950// If the function is unable to load the necessary blocks or their contents don't
951// match the hashes, the return value is -1 and the command should be aborted.
952//
953// If the return value is 1, the command has already been completed according to
954// the contents of the target blocks, and should not be performed again.
955//
956// If the return value is 0, source blocks have expected content and the command
957// can be performed.
958
Tao Bao34847b22015-09-08 11:05:49 -0700959static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -0700960 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000961
Tao Baobaad2d42015-12-06 16:56:27 -0800962 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000963 fprintf(stderr, "missing source hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700964 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000965 }
966
Tao Baobaad2d42015-12-06 16:56:27 -0800967 std::string srchash = params.tokens[params.cpos++];
968 std::string tgthash;
969
Sami Tolvanen90221202014-12-09 16:39:47 +0000970 if (onehash) {
971 tgthash = srchash;
972 } else {
Tao Baobaad2d42015-12-06 16:56:27 -0800973 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000974 fprintf(stderr, "missing target hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700975 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000976 }
Tao Baobaad2d42015-12-06 16:56:27 -0800977 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000978 }
979
Elliott Hughesbcabd092016-03-22 20:19:22 -0700980 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd,
981 params.stashbase, &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700982 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000983 }
984
Tao Bao34847b22015-09-08 11:05:49 -0700985 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000986
Tao Bao612336d2015-08-27 16:41:21 -0700987 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700988 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000989 }
990
Tao Bao612336d2015-08-27 16:41:21 -0700991 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000992 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -0700993 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000994 }
995
Tao Bao0940fe12015-08-27 16:41:21 -0700996 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000997 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700998 // resume from possible write errors. In verify mode, we can skip stashing
999 // because the source blocks won't be overwritten.
1000 if (overlap && params.canwrite) {
Tao Baobaad2d42015-12-06 16:56:27 -08001001 fprintf(stderr, "stashing %zu overlapping blocks to %s\n", src_blocks,
1002 srchash.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +00001003
Tao Bao0940fe12015-08-27 16:41:21 -07001004 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -07001005 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -07001006 &stash_exists) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001007 fprintf(stderr, "failed to stash overlapping source blocks\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001008 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001009 }
1010
Tianjie Xudd874b12016-05-13 12:13:15 -07001011 params.stashed += src_blocks;
Sami Tolvanen90221202014-12-09 16:39:47 +00001012 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001013 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -07001014 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001015 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001016 }
1017
1018 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -07001019 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001020 }
1021
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001022 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
1023 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001024 // Overlapping source blocks were previously stashed, command can proceed.
1025 // We are recovering from an interrupted command, so we don't know if the
1026 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -07001027 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001028 }
1029
1030 // Valid source data not available, update cannot be resumed
1031 fprintf(stderr, "partition has unexpected contents\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001032 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +00001033
Tao Bao0940fe12015-08-27 16:41:21 -07001034 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001035}
1036
Tao Bao0940fe12015-08-27 16:41:21 -07001037static int PerformCommandMove(CommandParameters& params) {
1038 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001039 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001040 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001041 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001042
Tao Bao0940fe12015-08-27 16:41:21 -07001043 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001044 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001045 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001046 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001047 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001048 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001049 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001050 }
1051
1052 if (status == -1) {
1053 fprintf(stderr, "failed to read blocks for move\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001054 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001055 }
1056
1057 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001058 params.foundwrites = true;
1059 } else if (params.foundwrites) {
1060 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001061 }
1062
Tao Bao0940fe12015-08-27 16:41:21 -07001063 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001064 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001065 fprintf(stderr, " moving %zu blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001066
Tao Bao0940fe12015-08-27 16:41:21 -07001067 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1068 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001069 }
1070 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001071 fprintf(stderr, "skipping %zu already moved blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001072 }
1073
1074 }
1075
Tao Baobaad2d42015-12-06 16:56:27 -08001076 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001077 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001078 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001079 }
1080
Tao Bao0940fe12015-08-27 16:41:21 -07001081 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001082
Tao Bao0940fe12015-08-27 16:41:21 -07001083 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001084}
1085
Tao Bao0940fe12015-08-27 16:41:21 -07001086static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001087 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001088 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001089}
1090
Tao Bao0940fe12015-08-27 16:41:21 -07001091static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001092 // <stash_id>
1093 if (params.cpos >= params.tokens.size()) {
1094 fprintf(stderr, "missing stash id in free command\n");
1095 return -1;
1096 }
1097
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001098 const std::string& id = params.tokens[params.cpos++];
1099
1100 if (!params.canwrite && stash_map.find(id) != stash_map.end()) {
1101 stash_map.erase(id);
1102 return 0;
1103 }
1104
Tao Bao0940fe12015-08-27 16:41:21 -07001105 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001106 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001107 }
1108
1109 return 0;
1110}
1111
Tao Bao0940fe12015-08-27 16:41:21 -07001112static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001113
Tao Baobaad2d42015-12-06 16:56:27 -08001114 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001115 fprintf(stderr, "missing target blocks for zero\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001116 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001117 }
1118
Tao Bao0940fe12015-08-27 16:41:21 -07001119 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001120 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001121
Tao Bao0940fe12015-08-27 16:41:21 -07001122 fprintf(stderr, " zeroing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001123
Tao Bao612336d2015-08-27 16:41:21 -07001124 allocate(BLOCKSIZE, params.buffer);
1125 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001126
Tao Bao0940fe12015-08-27 16:41:21 -07001127 if (params.canwrite) {
1128 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001129 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1130 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1131 if (!discard_blocks(params.fd, offset, size)) {
1132 return -1;
1133 }
1134
1135 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001136 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001137 }
1138
Tao Bao0940fe12015-08-27 16:41:21 -07001139 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1140 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1141 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001142 }
1143 }
1144 }
1145 }
1146
Tao Bao0940fe12015-08-27 16:41:21 -07001147 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001148 // Update only for the zero command, as the erase command will call
1149 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001150 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001151 }
1152
Tao Bao0940fe12015-08-27 16:41:21 -07001153 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001154}
1155
Tao Bao0940fe12015-08-27 16:41:21 -07001156static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001157
Tao Baobaad2d42015-12-06 16:56:27 -08001158 if (params.cpos >= params.tokens.size()) {
1159 fprintf(stderr, "missing target blocks for new\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001160 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001161 }
1162
Tao Bao0940fe12015-08-27 16:41:21 -07001163 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001164 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001165
Tao Bao0940fe12015-08-27 16:41:21 -07001166 if (params.canwrite) {
1167 fprintf(stderr, " writing %zu blocks of new data\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001168
Tao Bao0940fe12015-08-27 16:41:21 -07001169 RangeSinkState rss(tgt);
1170 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001171 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001172 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001173
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001174 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1175 if (!discard_blocks(params.fd, offset, tgt.size * BLOCKSIZE)) {
1176 return -1;
1177 }
1178
1179 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001180 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001181 }
1182
Tao Bao0940fe12015-08-27 16:41:21 -07001183 pthread_mutex_lock(&params.nti.mu);
1184 params.nti.rss = &rss;
1185 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001186
Tao Bao0940fe12015-08-27 16:41:21 -07001187 while (params.nti.rss) {
1188 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001189 }
1190
Tao Bao0940fe12015-08-27 16:41:21 -07001191 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001192 }
1193
Tao Bao0940fe12015-08-27 16:41:21 -07001194 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001195
Tao Bao0940fe12015-08-27 16:41:21 -07001196 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001197}
1198
Tao Bao0940fe12015-08-27 16:41:21 -07001199static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001200
Tao Baobaad2d42015-12-06 16:56:27 -08001201 // <offset> <length>
1202 if (params.cpos + 1 >= params.tokens.size()) {
1203 fprintf(stderr, "missing patch offset or length for %s\n", params.cmdname);
Tao Bao0940fe12015-08-27 16:41:21 -07001204 return -1;
1205 }
1206
Tao Baobaad2d42015-12-06 16:56:27 -08001207 size_t offset;
1208 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
1209 fprintf(stderr, "invalid patch offset\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001210 return -1;
1211 }
1212
Tao Baobaad2d42015-12-06 16:56:27 -08001213 size_t len;
1214 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
1215 fprintf(stderr, "invalid patch offset\n");
1216 return -1;
1217 }
Tao Bao0940fe12015-08-27 16:41:21 -07001218
Tao Bao612336d2015-08-27 16:41:21 -07001219 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001220 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001221 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001222 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001223 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001224 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001225 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001226 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001227 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001228 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001229 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001230 }
1231
1232 if (status == -1) {
1233 fprintf(stderr, "failed to read blocks for diff\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001234 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001235 }
1236
1237 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001238 params.foundwrites = true;
1239 } else if (params.foundwrites) {
1240 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001241 }
1242
Tao Bao0940fe12015-08-27 16:41:21 -07001243 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001244 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001245 fprintf(stderr, "patching %zu blocks to %zu\n", blocks, tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001246
Tao Bao0940fe12015-08-27 16:41:21 -07001247 Value patch_value;
Sami Tolvanen90221202014-12-09 16:39:47 +00001248 patch_value.type = VAL_BLOB;
1249 patch_value.size = len;
Tao Bao0940fe12015-08-27 16:41:21 -07001250 patch_value.data = (char*) (params.patch_start + offset);
Sami Tolvanen90221202014-12-09 16:39:47 +00001251
Tao Bao0940fe12015-08-27 16:41:21 -07001252 RangeSinkState rss(tgt);
1253 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001254 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001255 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001256
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001257 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1258 if (!discard_blocks(params.fd, offset, rss.p_remain)) {
1259 return -1;
1260 }
1261
1262 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001263 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001264 }
1265
Tao Bao0940fe12015-08-27 16:41:21 -07001266 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao612336d2015-08-27 16:41:21 -07001267 ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
Tao Bao0940fe12015-08-27 16:41:21 -07001268 &RangeSinkWrite, &rss, nullptr, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001269 } else {
Tao Bao612336d2015-08-27 16:41:21 -07001270 ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1271 &RangeSinkWrite, &rss, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001272 }
1273
1274 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001275 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001276 fprintf(stderr, "range sink underrun?\n");
1277 }
1278 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001279 fprintf(stderr, "skipping %zu blocks already patched to %zu [%s]\n",
Tao Baobaad2d42015-12-06 16:56:27 -08001280 blocks, tgt.size, params.cmdline);
Sami Tolvanen90221202014-12-09 16:39:47 +00001281 }
1282 }
1283
Tao Baobaad2d42015-12-06 16:56:27 -08001284 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001285 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001286 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001287 }
1288
Tao Bao0940fe12015-08-27 16:41:21 -07001289 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001290
Tao Bao0940fe12015-08-27 16:41:21 -07001291 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001292}
1293
Tao Bao0940fe12015-08-27 16:41:21 -07001294static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001295 if (DEBUG_ERASE) {
1296 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001297 }
1298
Tao Bao0940fe12015-08-27 16:41:21 -07001299 struct stat sb;
1300 if (fstat(params.fd, &sb) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001301 fprintf(stderr, "failed to fstat device to erase: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001302 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001303 }
1304
Tao Bao0940fe12015-08-27 16:41:21 -07001305 if (!S_ISBLK(sb.st_mode)) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001306 fprintf(stderr, "not a block device; skipping erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001307 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001308 }
1309
Tao Baobaad2d42015-12-06 16:56:27 -08001310 if (params.cpos >= params.tokens.size()) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001311 fprintf(stderr, "missing target blocks for erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001312 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001313 }
1314
Tao Bao0940fe12015-08-27 16:41:21 -07001315 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001316 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001317
Tao Bao0940fe12015-08-27 16:41:21 -07001318 if (params.canwrite) {
1319 fprintf(stderr, " erasing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001320
Tao Bao0940fe12015-08-27 16:41:21 -07001321 for (size_t i = 0; i < tgt.count; ++i) {
1322 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001323 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001324 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001325 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001326 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001327
Tao Bao0940fe12015-08-27 16:41:21 -07001328 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001329 fprintf(stderr, "BLKDISCARD ioctl failed: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001330 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001331 }
1332 }
1333 }
1334
Tao Bao0940fe12015-08-27 16:41:21 -07001335 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001336}
1337
1338// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001339typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001340
Tao Bao612336d2015-08-27 16:41:21 -07001341struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001342 const char* name;
1343 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001344};
Sami Tolvanen90221202014-12-09 16:39:47 +00001345
1346// CompareCommands and CompareCommandNames are for the hash table
1347
1348static int CompareCommands(const void* c1, const void* c2) {
1349 return strcmp(((const Command*) c1)->name, ((const Command*) c2)->name);
1350}
1351
1352static int CompareCommandNames(const void* c1, const void* c2) {
1353 return strcmp(((const Command*) c1)->name, (const char*) c2);
1354}
1355
1356// HashString is used to hash command names for the hash table
1357
1358static unsigned int HashString(const char *s) {
1359 unsigned int hash = 0;
1360 if (s) {
1361 while (*s) {
1362 hash = hash * 33 + *s++;
1363 }
1364 }
1365 return hash;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001366}
1367
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001368// args:
1369// - block device (or file) to modify in-place
1370// - transfer list (blob)
1371// - new data stream (filename within package.zip)
1372// - patch stream (filename within package.zip, must be uncompressed)
1373
Tao Bao0940fe12015-08-27 16:41:21 -07001374static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1375 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao73064612016-04-26 17:14:32 -07001376 CommandParameters params = {};
Sami Tolvanen90221202014-12-09 16:39:47 +00001377 params.canwrite = !dryrun;
1378
1379 fprintf(stderr, "performing %s\n", dryrun ? "verification" : "update");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001380 if (state->is_retry) {
1381 is_retry = true;
1382 fprintf(stderr, "This update is a retry.\n");
1383 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001384
Tao Bao612336d2015-08-27 16:41:21 -07001385 Value* blockdev_filename = nullptr;
1386 Value* transfer_list_value = nullptr;
1387 Value* new_data_fn = nullptr;
1388 Value* patch_data_fn = nullptr;
Doug Zongker1d5d6092014-08-21 10:47:24 -07001389 if (ReadValueArgs(state, argv, 4, &blockdev_filename, &transfer_list_value,
Sami Tolvanen90221202014-12-09 16:39:47 +00001390 &new_data_fn, &patch_data_fn) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001391 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001392 }
Tao Bao612336d2015-08-27 16:41:21 -07001393 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1394 FreeValue);
1395 std::unique_ptr<Value, decltype(&FreeValue)> transfer_list_value_holder(transfer_list_value,
1396 FreeValue);
1397 std::unique_ptr<Value, decltype(&FreeValue)> new_data_fn_holder(new_data_fn, FreeValue);
1398 std::unique_ptr<Value, decltype(&FreeValue)> patch_data_fn_holder(patch_data_fn, FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001399
1400 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001401 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1402 name);
Tao Bao612336d2015-08-27 16:41:21 -07001403 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001404 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001405 if (transfer_list_value->type != VAL_BLOB) {
Tianjie Xu16255832016-04-30 11:49:59 -07001406 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
Tao Bao612336d2015-08-27 16:41:21 -07001407 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001408 }
1409 if (new_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001410 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001411 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001412 }
1413 if (patch_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001414 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string",
1415 name);
Tao Bao612336d2015-08-27 16:41:21 -07001416 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001417 }
1418
Tao Bao612336d2015-08-27 16:41:21 -07001419 UpdaterInfo* ui = reinterpret_cast<UpdaterInfo*>(state->cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001420
Tao Bao0940fe12015-08-27 16:41:21 -07001421 if (ui == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001422 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001423 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001424
Tao Bao612336d2015-08-27 16:41:21 -07001425 FILE* cmd_pipe = ui->cmd_pipe;
1426 ZipArchive* za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001427
Tao Bao0940fe12015-08-27 16:41:21 -07001428 if (cmd_pipe == nullptr || za == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001429 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001430 }
1431
Tao Bao612336d2015-08-27 16:41:21 -07001432 const ZipEntry* patch_entry = mzFindZipEntry(za, patch_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001433 if (patch_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001434 fprintf(stderr, "%s(): no file \"%s\" in package", name, patch_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001435 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001436 }
1437
Sami Tolvanen90221202014-12-09 16:39:47 +00001438 params.patch_start = ui->package_zip_addr + mzGetZipEntryOffset(patch_entry);
Tao Bao612336d2015-08-27 16:41:21 -07001439 const ZipEntry* new_entry = mzFindZipEntry(za, new_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001440 if (new_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001441 fprintf(stderr, "%s(): no file \"%s\" in package", name, new_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001442 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001443 }
1444
Elliott Hughesbcabd092016-03-22 20:19:22 -07001445 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data, O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001446 if (params.fd == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001447 fprintf(stderr, "open \"%s\" failed: %s\n", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001448 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001449 }
1450
Sami Tolvanen90221202014-12-09 16:39:47 +00001451 if (params.canwrite) {
1452 params.nti.za = za;
1453 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001454
Tao Bao0940fe12015-08-27 16:41:21 -07001455 pthread_mutex_init(&params.nti.mu, nullptr);
1456 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001457 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001458 pthread_attr_init(&attr);
1459 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1460
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001461 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1462 if (error != 0) {
1463 fprintf(stderr, "pthread_create failed: %s\n", strerror(error));
Tao Bao612336d2015-08-27 16:41:21 -07001464 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001465 }
1466 }
1467
Tao Baobaad2d42015-12-06 16:56:27 -08001468 // Copy all the lines in transfer_list_value into std::string for
1469 // processing.
Tao Bao612336d2015-08-27 16:41:21 -07001470 const std::string transfer_list(transfer_list_value->data, transfer_list_value->size);
1471 std::vector<std::string> lines = android::base::Split(transfer_list, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001472 if (lines.size() < 2) {
Tianjie Xu16255832016-04-30 11:49:59 -07001473 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1474 lines.size());
Tao Baobaad2d42015-12-06 16:56:27 -08001475 return StringValue(strdup(""));
1476 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001477
Sami Tolvanen90221202014-12-09 16:39:47 +00001478 // First line in transfer list is the version number
Tao Bao1fdec862015-10-21 14:57:44 -07001479 if (!android::base::ParseInt(lines[0].c_str(), &params.version, 1, 4)) {
Tao Bao612336d2015-08-27 16:41:21 -07001480 fprintf(stderr, "unexpected transfer list version [%s]\n", lines[0].c_str());
1481 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001482 }
1483
Sami Tolvanen90221202014-12-09 16:39:47 +00001484 fprintf(stderr, "blockimg version is %d\n", params.version);
1485
1486 // Second line in transfer list is the total number of blocks we expect to write
Tao Baob15fd222015-09-24 11:10:51 -07001487 int total_blocks;
1488 if (!android::base::ParseInt(lines[1].c_str(), &total_blocks, 0)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001489 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
Tao Bao612336d2015-08-27 16:41:21 -07001490 return StringValue(strdup(""));
Tao Baob15fd222015-09-24 11:10:51 -07001491 }
1492
1493 if (total_blocks == 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001494 return StringValue(strdup("t"));
Sami Tolvanen90221202014-12-09 16:39:47 +00001495 }
1496
Tao Bao612336d2015-08-27 16:41:21 -07001497 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001498 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001499 if (lines.size() < 4) {
Tianjie Xu16255832016-04-30 11:49:59 -07001500 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1501 lines.size());
Tao Baobaad2d42015-12-06 16:56:27 -08001502 return StringValue(strdup(""));
1503 }
1504
Sami Tolvanen90221202014-12-09 16:39:47 +00001505 // Third line is how many stash entries are needed simultaneously
Tao Bao612336d2015-08-27 16:41:21 -07001506 fprintf(stderr, "maximum stash entries %s\n", lines[2].c_str());
Doug Zongker52ae67d2014-09-08 12:22:09 -07001507
Sami Tolvanen90221202014-12-09 16:39:47 +00001508 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Baob15fd222015-09-24 11:10:51 -07001509 int stash_max_blocks;
1510 if (!android::base::ParseInt(lines[3].c_str(), &stash_max_blocks, 0)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001511 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1512 lines[3].c_str());
Tao Bao612336d2015-08-27 16:41:21 -07001513 return StringValue(strdup(""));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001514 }
1515
Tao Baob15fd222015-09-24 11:10:51 -07001516 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001517 if (res == -1) {
1518 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001519 }
Tao Bao612336d2015-08-27 16:41:21 -07001520
Tao Baob15fd222015-09-24 11:10:51 -07001521 params.createdstash = res;
1522
Tao Bao612336d2015-08-27 16:41:21 -07001523 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001524 }
1525
Sami Tolvanen90221202014-12-09 16:39:47 +00001526 // Build a hash table of the available commands
Tao Bao612336d2015-08-27 16:41:21 -07001527 HashTable* cmdht = mzHashTableCreate(cmdcount, nullptr);
1528 std::unique_ptr<HashTable, decltype(&mzHashTableFree)> cmdht_holder(cmdht, mzHashTableFree);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001529
Tao Bao0940fe12015-08-27 16:41:21 -07001530 for (size_t i = 0; i < cmdcount; ++i) {
1531 unsigned int cmdhash = HashString(commands[i].name);
Sami Tolvanen90221202014-12-09 16:39:47 +00001532 mzHashTableLookup(cmdht, cmdhash, (void*) &commands[i], CompareCommands, true);
1533 }
1534
Tao Bao612336d2015-08-27 16:41:21 -07001535 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001536
Tao Bao612336d2015-08-27 16:41:21 -07001537 // Subsequent lines are all individual transfer commands
1538 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1539 const std::string& line_str(*it);
Tao Bao6a47dff2015-09-25 17:12:28 -07001540 if (line_str.empty()) {
1541 continue;
1542 }
1543
Tao Baobaad2d42015-12-06 16:56:27 -08001544 params.tokens = android::base::Split(line_str, " ");
1545 params.cpos = 0;
1546 params.cmdname = params.tokens[params.cpos++].c_str();
1547 params.cmdline = line_str.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001548
Tao Bao0940fe12015-08-27 16:41:21 -07001549 unsigned int cmdhash = HashString(params.cmdname);
Tao Bao612336d2015-08-27 16:41:21 -07001550 const Command* cmd = reinterpret_cast<const Command*>(mzHashTableLookup(cmdht, cmdhash,
Tao Baobaad2d42015-12-06 16:56:27 -08001551 const_cast<char*>(params.cmdname), CompareCommandNames,
1552 false));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001553
Tao Bao0940fe12015-08-27 16:41:21 -07001554 if (cmd == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001555 fprintf(stderr, "unexpected command [%s]\n", params.cmdname);
1556 goto pbiudone;
1557 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001558
Tao Bao0940fe12015-08-27 16:41:21 -07001559 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao612336d2015-08-27 16:41:21 -07001560 fprintf(stderr, "failed to execute command [%s]\n", line_str.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +00001561 goto pbiudone;
1562 }
1563
Sami Tolvanen90221202014-12-09 16:39:47 +00001564 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001565 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001566 failure_type = kFsyncFailure;
Tao Bao187efff2015-07-27 14:07:08 -07001567 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
1568 goto pbiudone;
1569 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001570 fprintf(cmd_pipe, "set_progress %.4f\n", (double) params.written / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001571 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001572 }
1573 }
1574
Sami Tolvanen90221202014-12-09 16:39:47 +00001575 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001576 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001577
Tao Bao0940fe12015-08-27 16:41:21 -07001578 fprintf(stderr, "wrote %zu blocks; expected %d\n", params.written, total_blocks);
Tianjie Xudd874b12016-05-13 12:13:15 -07001579 fprintf(stderr, "stashed %zu blocks\n", params.stashed);
Tao Bao612336d2015-08-27 16:41:21 -07001580 fprintf(stderr, "max alloc needed was %zu\n", params.buffer.size());
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001581
Tianjie Xudd874b12016-05-13 12:13:15 -07001582 const char* partition = strrchr(blockdev_filename->data, '/');
1583 if (partition != nullptr && *(partition+1) != 0) {
1584 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1585 params.written * BLOCKSIZE);
1586 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1587 params.stashed * BLOCKSIZE);
1588 fflush(cmd_pipe);
1589 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001590 // Delete stash only after successfully completing the update, as it
1591 // may contain blocks needed to complete the update later.
1592 DeleteStash(params.stashbase);
1593 } else {
1594 fprintf(stderr, "verified partition contents; update may be resumed\n");
1595 }
1596
1597 rc = 0;
1598
1599pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001600 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001601 failure_type = kFsyncFailure;
Tao Baobaad2d42015-12-06 16:56:27 -08001602 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +00001603 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001604 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001605
Sami Tolvanen90221202014-12-09 16:39:47 +00001606 // Only delete the stash if the update cannot be resumed, or it's
1607 // a verification run and we created the stash.
1608 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1609 DeleteStash(params.stashbase);
1610 }
1611
Tianjie Xu16255832016-04-30 11:49:59 -07001612 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1613 state->cause_code = failure_type;
1614 }
1615
Sami Tolvanen90221202014-12-09 16:39:47 +00001616 return StringValue(rc == 0 ? strdup("t") : strdup(""));
1617}
1618
1619// The transfer list is a text file containing commands to
1620// transfer data from one place to another on the target
1621// partition. We parse it and execute the commands in order:
1622//
1623// zero [rangeset]
1624// - fill the indicated blocks with zeros
1625//
1626// new [rangeset]
1627// - fill the blocks with data read from the new_data file
1628//
1629// erase [rangeset]
1630// - mark the given blocks as empty
1631//
1632// move <...>
1633// bsdiff <patchstart> <patchlen> <...>
1634// imgdiff <patchstart> <patchlen> <...>
1635// - read the source blocks, apply a patch (or not in the
1636// case of move), write result to target blocks. bsdiff or
1637// imgdiff specifies the type of patch; move means no patch
1638// at all.
1639//
1640// The format of <...> differs between versions 1 and 2;
1641// see the LoadSrcTgtVersion{1,2}() functions for a
1642// description of what's expected.
1643//
1644// stash <stash_id> <src_range>
1645// - (version 2+ only) load the given source range and stash
1646// the data in the given slot of the stash table.
1647//
Tao Baobaad2d42015-12-06 16:56:27 -08001648// free <stash_id>
1649// - (version 3+ only) free the given stash data.
1650//
Sami Tolvanen90221202014-12-09 16:39:47 +00001651// The creator of the transfer list will guarantee that no block
1652// is read (ie, used as the source for a patch or move) after it
1653// has been written.
1654//
1655// In version 2, the creator will guarantee that a given stash is
1656// loaded (with a stash command) before it's used in a
1657// move/bsdiff/imgdiff command.
1658//
1659// Within one command the source and target ranges may overlap so
1660// in general we need to read the entire source into memory before
1661// writing anything to the target blocks.
1662//
1663// All the patch data is concatenated into one patch_data file in
1664// the update package. It must be stored uncompressed because we
1665// memory-map it in directly from the archive. (Since patches are
1666// already compressed, we lose very little by not compressing
1667// their concatenation.)
1668//
1669// In version 3, commands that read data from the partition (i.e.
1670// move/bsdiff/imgdiff/stash) have one or more additional hashes
1671// before the range parameters, which are used to check if the
1672// command has already been completed and verify the integrity of
1673// the source data.
1674
1675Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001676 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001677 const Command commands[] = {
1678 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001679 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001680 { "free", PerformCommandFree },
1681 { "imgdiff", PerformCommandDiff },
1682 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001683 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001684 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001685 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001686 };
1687
1688 // Perform a dry run without writing to test if an update can proceed
1689 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001690 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001691}
1692
1693Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1694 const Command commands[] = {
1695 { "bsdiff", PerformCommandDiff },
1696 { "erase", PerformCommandErase },
1697 { "free", PerformCommandFree },
1698 { "imgdiff", PerformCommandDiff },
1699 { "move", PerformCommandMove },
1700 { "new", PerformCommandNew },
1701 { "stash", PerformCommandStash },
1702 { "zero", PerformCommandZero }
1703 };
1704
1705 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001706 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001707}
1708
Tao Bao0940fe12015-08-27 16:41:21 -07001709Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001710 Value* blockdev_filename;
1711 Value* ranges;
Tao Bao0940fe12015-08-27 16:41:21 -07001712
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001713 if (ReadValueArgs(state, argv, 2, &blockdev_filename, &ranges) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001714 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001715 }
Tao Bao612336d2015-08-27 16:41:21 -07001716 std::unique_ptr<Value, decltype(&FreeValue)> ranges_holder(ranges, FreeValue);
1717 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1718 FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001719
1720 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001721 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1722 name);
Tao Bao612336d2015-08-27 16:41:21 -07001723 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001724 }
1725 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001726 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001727 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001728 }
1729
Elliott Hughesbcabd092016-03-22 20:19:22 -07001730 android::base::unique_fd fd(ota_open(blockdev_filename->data, O_RDWR));
1731 if (fd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001732 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", blockdev_filename->data,
1733 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001734 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001735 }
1736
Tao Bao612336d2015-08-27 16:41:21 -07001737 RangeSet rs;
Tao Bao0940fe12015-08-27 16:41:21 -07001738 parse_range(ranges->data, rs);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001739
1740 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001741 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001742
Tao Bao612336d2015-08-27 16:41:21 -07001743 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001744 for (size_t i = 0; i < rs.count; ++i) {
1745 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001746 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data,
1747 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001748 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001749 }
1750
Tao Bao0940fe12015-08-27 16:41:21 -07001751 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001752 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001753 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data,
Tao Bao0940fe12015-08-27 16:41:21 -07001754 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001755 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001756 }
1757
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001758 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001759 }
1760 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001761 uint8_t digest[SHA_DIGEST_LENGTH];
1762 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001763
Tao Bao612336d2015-08-27 16:41:21 -07001764 return StringValue(strdup(print_sha1(digest).c_str()));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001765}
1766
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001767// This function checks if a device has been remounted R/W prior to an incremental
1768// OTA update. This is an common cause of update abortion. The function reads the
1769// 1st block of each partition and check for mounting time/count. It return string "t"
1770// if executes successfully and an empty string otherwise.
1771
1772Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
1773 Value* arg_filename;
1774
1775 if (ReadValueArgs(state, argv, 1, &arg_filename) < 0) {
1776 return nullptr;
1777 }
1778 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1779
1780 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001781 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001782 return StringValue(strdup(""));
1783 }
1784
Elliott Hughesbcabd092016-03-22 20:19:22 -07001785 android::base::unique_fd fd(ota_open(arg_filename->data, O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001786 if (fd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001787 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data,
1788 strerror(errno));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001789 return StringValue(strdup(""));
1790 }
1791
1792 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1793 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1794
1795 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001796 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data,
Tianjie Xu30bf4762015-12-15 11:47:30 -08001797 strerror(errno));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001798 return StringValue(strdup(""));
1799 }
1800
1801 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1802 // Super block starts from block 0, offset 0x400
1803 // 0x2C: len32 Mount time
1804 // 0x30: len32 Write time
1805 // 0x34: len16 Number of mounts since the last fsck
1806 // 0x38: len16 Magic signature 0xEF53
1807
1808 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1809 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1810
1811 if (mount_count > 0) {
1812 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1813 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1814 }
1815
1816 return StringValue(strdup("t"));
1817}
1818
1819
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001820Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
1821 Value* arg_filename;
1822 Value* arg_ranges;
1823
1824 if (ReadValueArgs(state, argv, 2, &arg_filename, &arg_ranges) < 0) {
1825 return NULL;
1826 }
1827
1828 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1829 std::unique_ptr<Value, decltype(&FreeValue)> ranges(arg_ranges, FreeValue);
1830
1831 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001832 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001833 return StringValue(strdup(""));
1834 }
1835 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001836 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001837 return StringValue(strdup(""));
1838 }
1839
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001840 // Output notice to log when recover is attempted
1841 fprintf(stderr, "%s image corrupted, attempting to recover...\n", filename->data);
1842
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001843 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
1844 fec::io fh(filename->data, O_RDWR);
1845
1846 if (!fh) {
Tianjie Xu16255832016-04-30 11:49:59 -07001847 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data,
1848 strerror(errno));
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001849 return StringValue(strdup(""));
1850 }
1851
1852 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001853 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001854 return StringValue(strdup(""));
1855 }
1856
1857 fec_status status;
1858
1859 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001860 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001861 return StringValue(strdup(""));
1862 }
1863
1864 RangeSet rs;
1865 parse_range(ranges->data, rs);
1866
1867 uint8_t buffer[BLOCKSIZE];
1868
1869 for (size_t i = 0; i < rs.count; ++i) {
1870 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1871 // Stay within the data area, libfec validates and corrects metadata
1872 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1873 continue;
1874 }
1875
1876 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001877 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
1878 filename->data, j, strerror(errno));
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001879 return StringValue(strdup(""));
1880 }
1881
1882 // If we want to be able to recover from a situation where rewriting a corrected
1883 // block doesn't guarantee the same data will be returned when re-read later, we
1884 // can save a copy of corrected blocks to /cache. Note:
1885 //
1886 // 1. Maximum space required from /cache is the same as the maximum number of
1887 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1888 // this would be ~16 MiB, for example.
1889 //
1890 // 2. To find out if this block was corrupted, call fec_get_status after each
1891 // read and check if the errors field value has increased.
1892 }
1893 }
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001894 fprintf(stderr, "...%s image recovered successfully.\n", filename->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001895 return StringValue(strdup("t"));
1896}
1897
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001898void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001899 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001900 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001901 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001902 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001903 RegisterFunction("range_sha1", RangeSha1Fn);
1904}