blob: 6e056006cadf3ce66efdf2e68a030daf9bd87987 [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
Tao Baoe6aa3322015-08-05 15:20:27 -070036#include <memory>
37#include <string>
Tao Bao0940fe12015-08-27 16:41:21 -070038#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070039
Elliott Hughes4b166f02015-12-04 15:30:20 -080040#include <android-base/parseint.h>
41#include <android-base/strings.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070042
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070043#include "applypatch/applypatch.h"
44#include "edify/expr.h"
Tianjie Xu57bed6d2015-12-15 11:47:30 -080045#include "install.h"
Sen Jiangc48cb5e2016-02-04 16:23:21 +080046#include "openssl/sha.h"
Sami Tolvanen90221202014-12-09 16:39:47 +000047#include "minzip/Hash.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070048#include "print_sha1.h"
Tao Bao0940fe12015-08-27 16:41:21 -070049#include "unique_fd.h"
50#include "updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070051
52#define BLOCKSIZE 4096
53
Sami Tolvanene82fa182015-06-10 15:58:12 +000054// Set this to 0 to interpret 'erase' transfers to mean do a
55// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
56// erase to mean fill the region with zeroes.
57#define DEBUG_ERASE 0
58
Sami Tolvanen90221202014-12-09 16:39:47 +000059#define STASH_DIRECTORY_BASE "/cache/recovery"
60#define STASH_DIRECTORY_MODE 0700
61#define STASH_FILE_MODE 0600
62
Tao Bao0940fe12015-08-27 16:41:21 -070063struct RangeSet {
64 size_t count; // Limit is INT_MAX.
Shrinivas Sahukara6153df2015-08-19 13:01:45 +053065 size_t size;
Tao Bao0940fe12015-08-27 16:41:21 -070066 std::vector<size_t> pos; // Actual limit is INT_MAX.
67};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070068
Tao Baobaad2d42015-12-06 16:56:27 -080069static void parse_range(const std::string& range_text, RangeSet& rs) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010070
Tao Baobaad2d42015-12-06 16:56:27 -080071 std::vector<std::string> pieces = android::base::Split(range_text, ",");
Tao Bao0940fe12015-08-27 16:41:21 -070072 if (pieces.size() < 3) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010073 goto err;
74 }
75
Tao Baob15fd222015-09-24 11:10:51 -070076 size_t num;
77 if (!android::base::ParseUint(pieces[0].c_str(), &num, static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010078 goto err;
79 }
80
Tao Baob15fd222015-09-24 11:10:51 -070081 if (num == 0 || num % 2) {
82 goto err; // must be even
83 } else if (num != pieces.size() - 1) {
84 goto err;
85 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +010086
Tao Bao0940fe12015-08-27 16:41:21 -070087 rs.pos.resize(num);
88 rs.count = num / 2;
89 rs.size = 0;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010090
Tao Bao0940fe12015-08-27 16:41:21 -070091 for (size_t i = 0; i < num; i += 2) {
Tao Baob15fd222015-09-24 11:10:51 -070092 if (!android::base::ParseUint(pieces[i+1].c_str(), &rs.pos[i],
93 static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010094 goto err;
95 }
96
Tao Baob15fd222015-09-24 11:10:51 -070097 if (!android::base::ParseUint(pieces[i+2].c_str(), &rs.pos[i+1],
98 static_cast<size_t>(INT_MAX))) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +053099 goto err;
100 }
101
Tao Bao0940fe12015-08-27 16:41:21 -0700102 if (rs.pos[i] >= rs.pos[i+1]) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530103 goto err; // empty or negative range
104 }
105
Tao Bao0940fe12015-08-27 16:41:21 -0700106 size_t sz = rs.pos[i+1] - rs.pos[i];
107 if (rs.size > SIZE_MAX - sz) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530108 goto err; // overflow
109 }
110
Tao Bao0940fe12015-08-27 16:41:21 -0700111 rs.size += sz;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700112 }
113
Tao Bao0940fe12015-08-27 16:41:21 -0700114 return;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100115
116err:
Tao Baobaad2d42015-12-06 16:56:27 -0800117 fprintf(stderr, "failed to parse range '%s'\n", range_text.c_str());
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100118 exit(1);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700119}
120
Tao Baoe6aa3322015-08-05 15:20:27 -0700121static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530122 for (size_t i = 0; i < r1.count; ++i) {
123 size_t r1_0 = r1.pos[i * 2];
124 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000125
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530126 for (size_t j = 0; j < r2.count; ++j) {
127 size_t r2_0 = r2.pos[j * 2];
128 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000129
Tao Baoc0f56ad2015-06-25 14:00:31 -0700130 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700131 return true;
Sami Tolvanen90221202014-12-09 16:39:47 +0000132 }
133 }
134 }
135
Tao Baoe6aa3322015-08-05 15:20:27 -0700136 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000137}
138
139static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700140 size_t so_far = 0;
141 while (so_far < size) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700142 ssize_t r = TEMP_FAILURE_RETRY(read(fd, data+so_far, size-so_far));
143 if (r == -1) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700144 fprintf(stderr, "read failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000145 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700146 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700147 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700148 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000149 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700150}
151
Tao Bao612336d2015-08-27 16:41:21 -0700152static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
153 return read_all(fd, buffer.data(), size);
154}
155
Sami Tolvanen90221202014-12-09 16:39:47 +0000156static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700157 size_t written = 0;
158 while (written < size) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700159 ssize_t w = TEMP_FAILURE_RETRY(write(fd, data+written, size-written));
160 if (w == -1) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700161 fprintf(stderr, "write failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000162 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700163 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700164 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700165 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000166
Sami Tolvanen90221202014-12-09 16:39:47 +0000167 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700168}
169
Tao Bao612336d2015-08-27 16:41:21 -0700170static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
171 return write_all(fd, buffer.data(), size);
172}
173
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700174static bool check_lseek(int fd, off64_t offset, int whence) {
175 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
176 if (rc == -1) {
177 fprintf(stderr, "lseek64 failed: %s\n", strerror(errno));
178 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700179 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700180 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700181}
182
Tao Bao612336d2015-08-27 16:41:21 -0700183static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700184 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700185 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700186
Tao Bao612336d2015-08-27 16:41:21 -0700187 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700188}
189
Tao Bao0940fe12015-08-27 16:41:21 -0700190struct RangeSinkState {
191 RangeSinkState(RangeSet& rs) : tgt(rs) { };
192
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700193 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700194 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530195 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700196 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700197};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700198
199static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700200 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700201
Tao Bao0940fe12015-08-27 16:41:21 -0700202 if (rss->p_remain == 0) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700203 fprintf(stderr, "range sink write overrun");
Sami Tolvanen90221202014-12-09 16:39:47 +0000204 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700205 }
206
207 ssize_t written = 0;
208 while (size > 0) {
209 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000210
211 if (rss->p_remain < write_now) {
212 write_now = rss->p_remain;
213 }
214
215 if (write_all(rss->fd, data, write_now) == -1) {
216 break;
217 }
218
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700219 data += write_now;
220 size -= write_now;
221
222 rss->p_remain -= write_now;
223 written += write_now;
224
225 if (rss->p_remain == 0) {
226 // move to the next block
227 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700228 if (rss->p_block < rss->tgt.count) {
229 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
230 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000231
Tao Bao0940fe12015-08-27 16:41:21 -0700232 if (!check_lseek(rss->fd, (off64_t)rss->tgt.pos[rss->p_block*2] * BLOCKSIZE,
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700233 SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000234 break;
235 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700236 } else {
237 // we can't write any more; return how many bytes have
238 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000239 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700240 }
241 }
242 }
243
244 return written;
245}
246
247// All of the data for all the 'new' transfers is contained in one
248// file in the update package, concatenated together in the order in
249// which transfers.list will need it. We want to stream it out of the
250// archive (it's compressed) without writing it to a temp file, but we
251// can't write each section until it's that transfer's turn to go.
252//
253// To achieve this, we expand the new data from the archive in a
254// background thread, and block that threads 'receive uncompressed
255// data' function until the main thread has reached a point where we
256// want some new data to be written. We signal the background thread
257// with the destination for the data and block the main thread,
258// waiting for the background thread to complete writing that section.
259// Then it signals the main thread to wake up and goes back to
260// blocking waiting for a transfer.
261//
262// NewThreadInfo is the struct used to pass information back and forth
263// between the two threads. When the main thread wants some data
264// written, it sets rss to the destination location and signals the
265// condition. When the background thread is done writing, it clears
266// rss and signals the condition again.
267
Tao Bao0940fe12015-08-27 16:41:21 -0700268struct NewThreadInfo {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700269 ZipArchive* za;
270 const ZipEntry* entry;
271
272 RangeSinkState* rss;
273
274 pthread_mutex_t mu;
275 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700276};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700277
278static bool receive_new_data(const unsigned char* data, int size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700279 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700280
281 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700282 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700283 // data is wanted.
284 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700285 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700286 pthread_cond_wait(&nti->cv, &nti->mu);
287 }
288 pthread_mutex_unlock(&nti->mu);
289
290 // At this point nti->rss is set, and we own it. The main
291 // thread is waiting for it to disappear from nti.
292 ssize_t written = RangeSinkWrite(data, size, nti->rss);
293 data += written;
294 size -= written;
295
Tao Bao0940fe12015-08-27 16:41:21 -0700296 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700297 // we have written all the bytes desired by this rss.
298
299 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700300 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700301 pthread_cond_broadcast(&nti->cv);
302 pthread_mutex_unlock(&nti->mu);
303 }
304 }
305
306 return true;
307}
308
309static void* unzip_new_data(void* cookie) {
310 NewThreadInfo* nti = (NewThreadInfo*) cookie;
311 mzProcessZipEntryContents(nti->za, nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700312 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700313}
314
Tao Bao612336d2015-08-27 16:41:21 -0700315static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000316 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700317 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000318
Tao Bao0940fe12015-08-27 16:41:21 -0700319 for (size_t i = 0; i < src.count; ++i) {
320 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000321 return -1;
322 }
323
Tao Bao0940fe12015-08-27 16:41:21 -0700324 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000325
Tao Bao612336d2015-08-27 16:41:21 -0700326 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000327 return -1;
328 }
329
330 p += size;
331 }
332
333 return 0;
334}
335
Tao Bao612336d2015-08-27 16:41:21 -0700336static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
337 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000338
Tao Bao0940fe12015-08-27 16:41:21 -0700339 size_t p = 0;
340 for (size_t i = 0; i < tgt.count; ++i) {
341 if (!check_lseek(fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000342 return -1;
343 }
344
Tao Bao0940fe12015-08-27 16:41:21 -0700345 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000346
Tao Bao612336d2015-08-27 16:41:21 -0700347 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000348 return -1;
349 }
350
351 p += size;
352 }
353
354 return 0;
355}
356
Tao Baobaad2d42015-12-06 16:56:27 -0800357// Parameters for transfer list command functions
358struct CommandParameters {
359 std::vector<std::string> tokens;
360 size_t cpos;
361 const char* cmdname;
362 const char* cmdline;
363 std::string freestash;
364 std::string stashbase;
365 bool canwrite;
366 int createdstash;
367 int fd;
368 bool foundwrites;
369 bool isunresumable;
370 int version;
371 size_t written;
372 NewThreadInfo nti;
373 pthread_t thread;
374 std::vector<uint8_t> buffer;
375 uint8_t* patch_start;
376};
377
Doug Zongker52ae67d2014-09-08 12:22:09 -0700378// Do a source/target load for move/bsdiff/imgdiff in version 1.
Tao Baobaad2d42015-12-06 16:56:27 -0800379// We expect to parse the remainder of the parameter tokens as:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700380//
381// <src_range> <tgt_range>
382//
383// The source range is loaded into the provided buffer, reallocating
Tao Bao34847b22015-09-08 11:05:49 -0700384// it to make it larger if necessary.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700385
Tao Baobaad2d42015-12-06 16:56:27 -0800386static int LoadSrcTgtVersion1(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700387 std::vector<uint8_t>& buffer, int fd) {
Tao Baobaad2d42015-12-06 16:56:27 -0800388
389 if (params.cpos + 1 >= params.tokens.size()) {
390 fprintf(stderr, "invalid parameters\n");
391 return -1;
392 }
393
Tao Bao612336d2015-08-27 16:41:21 -0700394 // <src_range>
Tao Bao0940fe12015-08-27 16:41:21 -0700395 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800396 parse_range(params.tokens[params.cpos++], src);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700397
Tao Bao612336d2015-08-27 16:41:21 -0700398 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800399 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700400
Tao Bao612336d2015-08-27 16:41:21 -0700401 allocate(src.size * BLOCKSIZE, buffer);
402 int rc = ReadBlocks(src, buffer, fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700403 src_blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000404
Sami Tolvanen90221202014-12-09 16:39:47 +0000405 return rc;
406}
407
Tao Bao612336d2015-08-27 16:41:21 -0700408static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700409 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800410 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700411 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000412
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800413 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000414
Tao Baoe6aa3322015-08-05 15:20:27 -0700415 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000416
Tao Bao0940fe12015-08-27 16:41:21 -0700417 if (hexdigest != expected) {
418 if (printerror) {
419 fprintf(stderr, "failed to verify blocks (expected %s, read %s)\n",
420 expected.c_str(), hexdigest.c_str());
421 }
422 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000423 }
424
Tao Bao0940fe12015-08-27 16:41:21 -0700425 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000426}
427
Tao Bao0940fe12015-08-27 16:41:21 -0700428static std::string GetStashFileName(const std::string& base, const std::string& id,
429 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700430 if (base.empty()) {
431 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000432 }
433
Tao Baoe6aa3322015-08-05 15:20:27 -0700434 std::string fn(STASH_DIRECTORY_BASE);
435 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000436
437 return fn;
438}
439
Tao Baoe6aa3322015-08-05 15:20:27 -0700440typedef void (*StashCallback)(const std::string&, void*);
Sami Tolvanen90221202014-12-09 16:39:47 +0000441
442// Does a best effort enumeration of stash files. Ignores possible non-file
443// items in the stash directory and continues despite of errors. Calls the
444// 'callback' function for each file and passes 'data' to the function as a
445// parameter.
446
Tao Baoe6aa3322015-08-05 15:20:27 -0700447static void EnumerateStash(const std::string& dirname, StashCallback callback, void* data) {
Tao Bao0940fe12015-08-27 16:41:21 -0700448 if (dirname.empty() || callback == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000449 return;
450 }
451
Tao Baoe6aa3322015-08-05 15:20:27 -0700452 std::unique_ptr<DIR, int(*)(DIR*)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000453
Tao Bao0940fe12015-08-27 16:41:21 -0700454 if (directory == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000455 if (errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700456 fprintf(stderr, "opendir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000457 }
458 return;
459 }
460
Tao Baoe6aa3322015-08-05 15:20:27 -0700461 struct dirent* item;
Tao Bao0940fe12015-08-27 16:41:21 -0700462 while ((item = readdir(directory.get())) != nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000463 if (item->d_type != DT_REG) {
464 continue;
465 }
466
Tao Baoe6aa3322015-08-05 15:20:27 -0700467 std::string fn = dirname + "/" + std::string(item->d_name);
Sami Tolvanen90221202014-12-09 16:39:47 +0000468 callback(fn, data);
Sami Tolvanen90221202014-12-09 16:39:47 +0000469 }
470}
471
Tao Baoe6aa3322015-08-05 15:20:27 -0700472static void UpdateFileSize(const std::string& fn, void* data) {
473 if (fn.empty() || !data) {
474 return;
475 }
476
Tao Bao0940fe12015-08-27 16:41:21 -0700477 struct stat sb;
478 if (stat(fn.c_str(), &sb) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700479 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000480 return;
481 }
482
Tao Baoe6aa3322015-08-05 15:20:27 -0700483 int* size = reinterpret_cast<int*>(data);
Tao Bao0940fe12015-08-27 16:41:21 -0700484 *size += sb.st_size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000485}
486
487// Deletes the stash directory and all files in it. Assumes that it only
488// contains files. There is nothing we can do about unlikely, but possible
489// errors, so they are merely logged.
490
Tao Bao0940fe12015-08-27 16:41:21 -0700491static void DeleteFile(const std::string& fn, void* /* data */) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700492 if (!fn.empty()) {
493 fprintf(stderr, "deleting %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000494
Tao Baoe6aa3322015-08-05 15:20:27 -0700495 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
496 fprintf(stderr, "unlink \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000497 }
498 }
499}
500
Tao Baoe6aa3322015-08-05 15:20:27 -0700501static void DeletePartial(const std::string& fn, void* data) {
502 if (android::base::EndsWith(fn, ".partial")) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000503 DeleteFile(fn, data);
504 }
505}
506
Tao Baoe6aa3322015-08-05 15:20:27 -0700507static void DeleteStash(const std::string& base) {
508 if (base.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000509 return;
510 }
511
Tao Baoe6aa3322015-08-05 15:20:27 -0700512 fprintf(stderr, "deleting stash %s\n", base.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000513
Tao Baoe6aa3322015-08-05 15:20:27 -0700514 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700515 EnumerateStash(dirname, DeleteFile, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000516
Tao Baoe6aa3322015-08-05 15:20:27 -0700517 if (rmdir(dirname.c_str()) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000518 if (errno != ENOENT && errno != ENOTDIR) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700519 fprintf(stderr, "rmdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000520 }
521 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000522}
523
Tao Bao0940fe12015-08-27 16:41:21 -0700524static int LoadStash(const std::string& base, const std::string& id, bool verify, size_t* blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700525 std::vector<uint8_t>& buffer, bool printnoent) {
526 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700527 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000528 }
529
Tao Bao0940fe12015-08-27 16:41:21 -0700530 size_t blockcount = 0;
531
Sami Tolvanen90221202014-12-09 16:39:47 +0000532 if (!blocks) {
533 blocks = &blockcount;
534 }
535
Tao Bao0940fe12015-08-27 16:41:21 -0700536 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000537
Tao Bao0940fe12015-08-27 16:41:21 -0700538 struct stat sb;
539 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000540
541 if (res == -1) {
542 if (errno != ENOENT || printnoent) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700543 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000544 }
Tao Bao0940fe12015-08-27 16:41:21 -0700545 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000546 }
547
Tao Baoe6aa3322015-08-05 15:20:27 -0700548 fprintf(stderr, " loading %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000549
Tao Bao0940fe12015-08-27 16:41:21 -0700550 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700551 fprintf(stderr, "%s size %" PRId64 " not multiple of block size %d",
Tao Bao0940fe12015-08-27 16:41:21 -0700552 fn.c_str(), static_cast<int64_t>(sb.st_size), BLOCKSIZE);
553 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000554 }
555
Tao Bao0940fe12015-08-27 16:41:21 -0700556 int fd = TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY));
557 unique_fd fd_holder(fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000558
559 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700560 fprintf(stderr, "open \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700561 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000562 }
563
Tao Bao612336d2015-08-27 16:41:21 -0700564 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000565
Tao Bao612336d2015-08-27 16:41:21 -0700566 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700567 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000568 }
569
Tao Bao0940fe12015-08-27 16:41:21 -0700570 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000571
Tao Bao612336d2015-08-27 16:41:21 -0700572 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700573 fprintf(stderr, "unexpected contents in %s\n", fn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700574 DeleteFile(fn, nullptr);
575 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000576 }
577
Tao Bao0940fe12015-08-27 16:41:21 -0700578 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000579}
580
Tao Bao612336d2015-08-27 16:41:21 -0700581static int WriteStash(const std::string& base, const std::string& id, int blocks,
582 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
583 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700584 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000585 }
586
587 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
588 fprintf(stderr, "not enough space to write stash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700589 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000590 }
591
Tao Bao0940fe12015-08-27 16:41:21 -0700592 std::string fn = GetStashFileName(base, id, ".partial");
593 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000594
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100595 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700596 struct stat sb;
597 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100598
599 if (res == 0) {
600 // The file already exists and since the name is the hash of the contents,
601 // it's safe to assume the contents are identical (accidental hash collisions
602 // are unlikely)
Tao Baoe6aa3322015-08-05 15:20:27 -0700603 fprintf(stderr, " skipping %d existing blocks in %s\n", blocks, cn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700604 *exists = true;
605 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100606 }
607
Tao Bao0940fe12015-08-27 16:41:21 -0700608 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100609 }
610
Tao Baoe6aa3322015-08-05 15:20:27 -0700611 fprintf(stderr, " writing %d blocks to %s\n", blocks, cn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000612
Tao Bao0940fe12015-08-27 16:41:21 -0700613 int fd = TEMP_FAILURE_RETRY(open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE));
614 unique_fd fd_holder(fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000615
616 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700617 fprintf(stderr, "failed to create \"%s\": %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700618 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000619 }
620
621 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700622 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000623 }
624
625 if (fsync(fd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700626 fprintf(stderr, "fsync \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700627 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000628 }
629
Tao Baoe6aa3322015-08-05 15:20:27 -0700630 if (rename(fn.c_str(), cn.c_str()) == -1) {
631 fprintf(stderr, "rename(\"%s\", \"%s\") failed: %s\n", fn.c_str(), cn.c_str(),
632 strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700633 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000634 }
635
Tao Bao0940fe12015-08-27 16:41:21 -0700636 std::string dname = GetStashFileName(base, "", "");
637 int dfd = TEMP_FAILURE_RETRY(open(dname.c_str(), O_RDONLY | O_DIRECTORY));
638 unique_fd dfd_holder(dfd);
Tao Baodc392262015-07-31 15:56:44 -0700639
640 if (dfd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700641 fprintf(stderr, "failed to open \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700642 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700643 }
644
645 if (fsync(dfd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700646 fprintf(stderr, "fsync \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700647 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700648 }
649
Tao Bao0940fe12015-08-27 16:41:21 -0700650 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000651}
652
653// Creates a directory for storing stash files and checks if the /cache partition
654// hash enough space for the expected amount of blocks we need to store. Returns
655// >0 if we created the directory, zero if it existed already, and <0 of failure.
656
Tao Bao0940fe12015-08-27 16:41:21 -0700657static int CreateStash(State* state, int maxblocks, const char* blockdev, std::string& base) {
658 if (blockdev == nullptr) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700659 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000660 }
661
662 // Stash directory should be different for each partition to avoid conflicts
663 // when updating multiple partitions at the same time, so we use the hash of
664 // the block device name as the base directory
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800665 uint8_t digest[SHA_DIGEST_LENGTH];
666 SHA1(reinterpret_cast<const uint8_t*>(blockdev), strlen(blockdev), digest);
Tao Baoe6aa3322015-08-05 15:20:27 -0700667 base = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000668
Tao Baoe6aa3322015-08-05 15:20:27 -0700669 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700670 struct stat sb;
671 int res = stat(dirname.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000672
673 if (res == -1 && errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700674 ErrorAbort(state, "stat \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
675 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000676 } else if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700677 fprintf(stderr, "creating stash %s\n", dirname.c_str());
678 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000679
680 if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700681 ErrorAbort(state, "mkdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
682 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000683 }
684
685 if (CacheSizeCheck(maxblocks * BLOCKSIZE) != 0) {
686 ErrorAbort(state, "not enough space for stash\n");
Tao Baoe6aa3322015-08-05 15:20:27 -0700687 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000688 }
689
Tao Baoe6aa3322015-08-05 15:20:27 -0700690 return 1; // Created directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000691 }
692
Tao Baoe6aa3322015-08-05 15:20:27 -0700693 fprintf(stderr, "using existing stash %s\n", dirname.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000694
695 // If the directory already exists, calculate the space already allocated to
696 // stash files and check if there's enough for all required blocks. Delete any
697 // partially completed stash files first.
698
Tao Bao0940fe12015-08-27 16:41:21 -0700699 EnumerateStash(dirname, DeletePartial, nullptr);
Tao Baoe6aa3322015-08-05 15:20:27 -0700700 int size = 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000701 EnumerateStash(dirname, UpdateFileSize, &size);
702
Tao Bao0940fe12015-08-27 16:41:21 -0700703 size = maxblocks * BLOCKSIZE - size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000704
705 if (size > 0 && CacheSizeCheck(size) != 0) {
706 ErrorAbort(state, "not enough space for stash (%d more needed)\n", size);
Tao Baoe6aa3322015-08-05 15:20:27 -0700707 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000708 }
709
Tao Baoe6aa3322015-08-05 15:20:27 -0700710 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000711}
712
Tao Baobaad2d42015-12-06 16:56:27 -0800713static int SaveStash(CommandParameters& params, const std::string& base,
714 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000715
Tao Baobaad2d42015-12-06 16:56:27 -0800716 // <stash_id> <src_range>
717 if (params.cpos + 1 >= params.tokens.size()) {
718 fprintf(stderr, "missing id and/or src range fields in stash command\n");
Sami Tolvanen90221202014-12-09 16:39:47 +0000719 return -1;
720 }
Tao Baobaad2d42015-12-06 16:56:27 -0800721 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000722
Tao Bao0940fe12015-08-27 16:41:21 -0700723 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700724 if (usehash && LoadStash(base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000725 // Stash file already exists and has expected contents. Do not
726 // read from source again, as the source may have been already
727 // overwritten during a previous attempt.
728 return 0;
729 }
730
Tao Bao34847b22015-09-08 11:05:49 -0700731 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800732 parse_range(params.tokens[params.cpos++], src);
Tao Bao34847b22015-09-08 11:05:49 -0700733
Tao Bao612336d2015-08-27 16:41:21 -0700734 allocate(src.size * BLOCKSIZE, buffer);
735 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000736 return -1;
737 }
Tao Bao34847b22015-09-08 11:05:49 -0700738 blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000739
Tao Bao612336d2015-08-27 16:41:21 -0700740 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000741 // Source blocks have unexpected contents. If we actually need this
742 // data later, this is an unrecoverable error. However, the command
743 // that uses the data may have already completed previously, so the
744 // possible failure will occur during source block verification.
Tao Bao0940fe12015-08-27 16:41:21 -0700745 fprintf(stderr, "failed to load source blocks for stash %s\n", id.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000746 return 0;
747 }
748
Tao Bao0940fe12015-08-27 16:41:21 -0700749 fprintf(stderr, "stashing %zu blocks to %s\n", blocks, id.c_str());
Tao Bao612336d2015-08-27 16:41:21 -0700750 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000751}
752
Tao Baobaad2d42015-12-06 16:56:27 -0800753static int FreeStash(const std::string& base, const std::string& id) {
754 if (base.empty() || id.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000755 return -1;
756 }
757
Tao Baobaad2d42015-12-06 16:56:27 -0800758 std::string fn = GetStashFileName(base, id, "");
Tao Bao0940fe12015-08-27 16:41:21 -0700759 DeleteFile(fn, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000760
761 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700762}
763
Tao Bao612336d2015-08-27 16:41:21 -0700764static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
765 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700766 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700767 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700768 // may be the same buffer.
769
Tao Bao612336d2015-08-27 16:41:21 -0700770 const uint8_t* from = source.data();
771 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700772 size_t start = locs.size;
773 for (int i = locs.count-1; i >= 0; --i) {
774 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700775 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700776 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700777 blocks * BLOCKSIZE);
778 }
779}
780
781// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800782// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700783//
784// <tgt_range> <src_block_count> <src_range>
785// (loads data from source image only)
786//
787// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
788// (loads data from stashes only)
789//
790// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
791// (loads data from both source image and stashes)
792//
793// On return, buffer is filled with the loaded source data (rearranged
794// and combined with stashed data as necessary). buffer may be
795// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000796// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700797
Tao Baobaad2d42015-12-06 16:56:27 -0800798static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700799 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800800
801 // At least it needs to provide three parameters: <tgt_range>,
802 // <src_block_count> and "-"/<src_range>.
803 if (params.cpos + 2 >= params.tokens.size()) {
804 fprintf(stderr, "invalid parameters\n");
805 return -1;
806 }
807
Tao Bao612336d2015-08-27 16:41:21 -0700808 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800809 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700810
Tao Bao612336d2015-08-27 16:41:21 -0700811 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800812 const std::string& token = params.tokens[params.cpos++];
813 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
814 fprintf(stderr, "invalid src_block_count \"%s\"\n", token.c_str());
815 return -1;
816 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700817
Tao Bao612336d2015-08-27 16:41:21 -0700818 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700819
Tao Bao612336d2015-08-27 16:41:21 -0700820 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800821 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700822 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800823 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700824 } else {
Tao Bao0940fe12015-08-27 16:41:21 -0700825 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800826 parse_range(params.tokens[params.cpos++], src);
Tao Bao612336d2015-08-27 16:41:21 -0700827 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700828
Tao Bao34847b22015-09-08 11:05:49 -0700829 if (overlap) {
830 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700831 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000832
Sami Tolvanen90221202014-12-09 16:39:47 +0000833 if (res == -1) {
834 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700835 }
836
Tao Baobaad2d42015-12-06 16:56:27 -0800837 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000838 // no stashes, only source range
839 return 0;
840 }
841
Tao Bao612336d2015-08-27 16:41:21 -0700842 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800843 parse_range(params.tokens[params.cpos++], locs);
Tao Bao612336d2015-08-27 16:41:21 -0700844 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700845 }
846
Tao Baobaad2d42015-12-06 16:56:27 -0800847 // <[stash_id:stash_range]>
848 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700849 // Each word is a an index into the stash table, a colon, and
850 // then a rangeset describing where in the source block that
851 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800852 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
853 if (tokens.size() != 2) {
854 fprintf(stderr, "invalid parameter\n");
855 return -1;
856 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000857
Tao Bao612336d2015-08-27 16:41:21 -0700858 std::vector<uint8_t> stash;
Tao Baobaad2d42015-12-06 16:56:27 -0800859 int res = LoadStash(stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000860
861 if (res == -1) {
862 // These source blocks will fail verification if used later, but we
863 // will let the caller decide if this is a fatal failure
Tao Baobaad2d42015-12-06 16:56:27 -0800864 fprintf(stderr, "failed to load stash %s\n", tokens[0].c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000865 continue;
866 }
867
Tao Bao612336d2015-08-27 16:41:21 -0700868 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800869 parse_range(tokens[1], locs);
Sami Tolvanen90221202014-12-09 16:39:47 +0000870
Tao Bao612336d2015-08-27 16:41:21 -0700871 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000872 }
873
874 return 0;
875}
876
Sami Tolvanen90221202014-12-09 16:39:47 +0000877// Do a source/target load for move/bsdiff/imgdiff in version 3.
878//
879// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
880// tells the function whether to expect separate source and targe block hashes, or
881// if they are both the same and only one hash should be expected, and
882// 'isunresumable', which receives a non-zero value if block verification fails in
883// a way that the update cannot be resumed anymore.
884//
885// If the function is unable to load the necessary blocks or their contents don't
886// match the hashes, the return value is -1 and the command should be aborted.
887//
888// If the return value is 1, the command has already been completed according to
889// the contents of the target blocks, and should not be performed again.
890//
891// If the return value is 0, source blocks have expected content and the command
892// can be performed.
893
Tao Bao34847b22015-09-08 11:05:49 -0700894static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -0700895 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000896
Tao Baobaad2d42015-12-06 16:56:27 -0800897 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000898 fprintf(stderr, "missing source hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700899 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000900 }
901
Tao Baobaad2d42015-12-06 16:56:27 -0800902 std::string srchash = params.tokens[params.cpos++];
903 std::string tgthash;
904
Sami Tolvanen90221202014-12-09 16:39:47 +0000905 if (onehash) {
906 tgthash = srchash;
907 } else {
Tao Baobaad2d42015-12-06 16:56:27 -0800908 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000909 fprintf(stderr, "missing target hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700910 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000911 }
Tao Baobaad2d42015-12-06 16:56:27 -0800912 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000913 }
914
Tao Baobaad2d42015-12-06 16:56:27 -0800915 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd, params.stashbase,
916 &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700917 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000918 }
919
Tao Bao34847b22015-09-08 11:05:49 -0700920 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000921
Tao Bao612336d2015-08-27 16:41:21 -0700922 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700923 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000924 }
925
Tao Bao612336d2015-08-27 16:41:21 -0700926 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000927 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -0700928 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000929 }
930
Tao Bao0940fe12015-08-27 16:41:21 -0700931 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000932 // If source and target blocks overlap, stash the source blocks so we can
933 // resume from possible write errors
Tao Bao0940fe12015-08-27 16:41:21 -0700934 if (overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800935 fprintf(stderr, "stashing %zu overlapping blocks to %s\n", src_blocks,
936 srchash.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000937
Tao Bao0940fe12015-08-27 16:41:21 -0700938 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -0700939 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -0700940 &stash_exists) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000941 fprintf(stderr, "failed to stash overlapping source blocks\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700942 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000943 }
944
945 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100946 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700947 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100948 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000949 }
950
951 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -0700952 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000953 }
954
Tao Bao612336d2015-08-27 16:41:21 -0700955 if (overlap && LoadStash(params.stashbase, srchash, true, nullptr, params.buffer, true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100956 // Overlapping source blocks were previously stashed, command can proceed.
957 // We are recovering from an interrupted command, so we don't know if the
958 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -0700959 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000960 }
961
962 // Valid source data not available, update cannot be resumed
963 fprintf(stderr, "partition has unexpected contents\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700964 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +0000965
Tao Bao0940fe12015-08-27 16:41:21 -0700966 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000967}
968
Tao Bao0940fe12015-08-27 16:41:21 -0700969static int PerformCommandMove(CommandParameters& params) {
970 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -0700971 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000972 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -0700973 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +0000974
Tao Bao0940fe12015-08-27 16:41:21 -0700975 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -0800976 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700977 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -0800978 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -0700979 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -0700980 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -0700981 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +0000982 }
983
984 if (status == -1) {
985 fprintf(stderr, "failed to read blocks for move\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700986 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000987 }
988
989 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700990 params.foundwrites = true;
991 } else if (params.foundwrites) {
992 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +0000993 }
994
Tao Bao0940fe12015-08-27 16:41:21 -0700995 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000996 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700997 fprintf(stderr, " moving %zu blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +0000998
Tao Bao0940fe12015-08-27 16:41:21 -0700999 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1000 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001001 }
1002 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001003 fprintf(stderr, "skipping %zu already moved blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001004 }
1005
1006 }
1007
Tao Baobaad2d42015-12-06 16:56:27 -08001008 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001009 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001010 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001011 }
1012
Tao Bao0940fe12015-08-27 16:41:21 -07001013 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001014
Tao Bao0940fe12015-08-27 16:41:21 -07001015 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001016}
1017
Tao Bao0940fe12015-08-27 16:41:21 -07001018static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001019 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001020 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001021}
1022
Tao Bao0940fe12015-08-27 16:41:21 -07001023static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001024 // <stash_id>
1025 if (params.cpos >= params.tokens.size()) {
1026 fprintf(stderr, "missing stash id in free command\n");
1027 return -1;
1028 }
1029
Tao Bao0940fe12015-08-27 16:41:21 -07001030 if (params.createdstash || params.canwrite) {
Tao Baobaad2d42015-12-06 16:56:27 -08001031 return FreeStash(params.stashbase, params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001032 }
1033
1034 return 0;
1035}
1036
Tao Bao0940fe12015-08-27 16:41:21 -07001037static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001038
Tao Baobaad2d42015-12-06 16:56:27 -08001039 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001040 fprintf(stderr, "missing target blocks for zero\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001041 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001042 }
1043
Tao Bao0940fe12015-08-27 16:41:21 -07001044 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001045 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001046
Tao Bao0940fe12015-08-27 16:41:21 -07001047 fprintf(stderr, " zeroing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001048
Tao Bao612336d2015-08-27 16:41:21 -07001049 allocate(BLOCKSIZE, params.buffer);
1050 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001051
Tao Bao0940fe12015-08-27 16:41:21 -07001052 if (params.canwrite) {
1053 for (size_t i = 0; i < tgt.count; ++i) {
1054 if (!check_lseek(params.fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
1055 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001056 }
1057
Tao Bao0940fe12015-08-27 16:41:21 -07001058 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1059 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1060 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001061 }
1062 }
1063 }
1064 }
1065
Tao Bao0940fe12015-08-27 16:41:21 -07001066 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001067 // Update only for the zero command, as the erase command will call
1068 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001069 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001070 }
1071
Tao Bao0940fe12015-08-27 16:41:21 -07001072 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001073}
1074
Tao Bao0940fe12015-08-27 16:41:21 -07001075static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001076
Tao Baobaad2d42015-12-06 16:56:27 -08001077 if (params.cpos >= params.tokens.size()) {
1078 fprintf(stderr, "missing target blocks for new\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001079 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001080 }
1081
Tao Bao0940fe12015-08-27 16:41:21 -07001082 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001083 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001084
Tao Bao0940fe12015-08-27 16:41:21 -07001085 if (params.canwrite) {
1086 fprintf(stderr, " writing %zu blocks of new data\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001087
Tao Bao0940fe12015-08-27 16:41:21 -07001088 RangeSinkState rss(tgt);
1089 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001090 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001091 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001092
Tao Bao0940fe12015-08-27 16:41:21 -07001093 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1094 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001095 }
1096
Tao Bao0940fe12015-08-27 16:41:21 -07001097 pthread_mutex_lock(&params.nti.mu);
1098 params.nti.rss = &rss;
1099 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001100
Tao Bao0940fe12015-08-27 16:41:21 -07001101 while (params.nti.rss) {
1102 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001103 }
1104
Tao Bao0940fe12015-08-27 16:41:21 -07001105 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001106 }
1107
Tao Bao0940fe12015-08-27 16:41:21 -07001108 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001109
Tao Bao0940fe12015-08-27 16:41:21 -07001110 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001111}
1112
Tao Bao0940fe12015-08-27 16:41:21 -07001113static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001114
Tao Baobaad2d42015-12-06 16:56:27 -08001115 // <offset> <length>
1116 if (params.cpos + 1 >= params.tokens.size()) {
1117 fprintf(stderr, "missing patch offset or length for %s\n", params.cmdname);
Tao Bao0940fe12015-08-27 16:41:21 -07001118 return -1;
1119 }
1120
Tao Baobaad2d42015-12-06 16:56:27 -08001121 size_t offset;
1122 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
1123 fprintf(stderr, "invalid patch offset\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001124 return -1;
1125 }
1126
Tao Baobaad2d42015-12-06 16:56:27 -08001127 size_t len;
1128 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
1129 fprintf(stderr, "invalid patch offset\n");
1130 return -1;
1131 }
Tao Bao0940fe12015-08-27 16:41:21 -07001132
Tao Bao612336d2015-08-27 16:41:21 -07001133 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001134 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001135 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001136 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001137 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001138 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001139 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001140 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001141 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001142 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001143 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001144 }
1145
1146 if (status == -1) {
1147 fprintf(stderr, "failed to read blocks for diff\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001148 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001149 }
1150
1151 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001152 params.foundwrites = true;
1153 } else if (params.foundwrites) {
1154 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001155 }
1156
Tao Bao0940fe12015-08-27 16:41:21 -07001157 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001158 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001159 fprintf(stderr, "patching %zu blocks to %zu\n", blocks, tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001160
Tao Bao0940fe12015-08-27 16:41:21 -07001161 Value patch_value;
Sami Tolvanen90221202014-12-09 16:39:47 +00001162 patch_value.type = VAL_BLOB;
1163 patch_value.size = len;
Tao Bao0940fe12015-08-27 16:41:21 -07001164 patch_value.data = (char*) (params.patch_start + offset);
Sami Tolvanen90221202014-12-09 16:39:47 +00001165
Tao Bao0940fe12015-08-27 16:41:21 -07001166 RangeSinkState rss(tgt);
1167 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001168 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001169 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001170
Tao Bao0940fe12015-08-27 16:41:21 -07001171 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1172 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001173 }
1174
Tao Bao0940fe12015-08-27 16:41:21 -07001175 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao612336d2015-08-27 16:41:21 -07001176 ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
Tao Bao0940fe12015-08-27 16:41:21 -07001177 &RangeSinkWrite, &rss, nullptr, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001178 } else {
Tao Bao612336d2015-08-27 16:41:21 -07001179 ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1180 &RangeSinkWrite, &rss, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001181 }
1182
1183 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001184 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001185 fprintf(stderr, "range sink underrun?\n");
1186 }
1187 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001188 fprintf(stderr, "skipping %zu blocks already patched to %zu [%s]\n",
Tao Baobaad2d42015-12-06 16:56:27 -08001189 blocks, tgt.size, params.cmdline);
Sami Tolvanen90221202014-12-09 16:39:47 +00001190 }
1191 }
1192
Tao Baobaad2d42015-12-06 16:56:27 -08001193 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001194 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001195 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001196 }
1197
Tao Bao0940fe12015-08-27 16:41:21 -07001198 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001199
Tao Bao0940fe12015-08-27 16:41:21 -07001200 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001201}
1202
Tao Bao0940fe12015-08-27 16:41:21 -07001203static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001204 if (DEBUG_ERASE) {
1205 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001206 }
1207
Tao Bao0940fe12015-08-27 16:41:21 -07001208 struct stat sb;
1209 if (fstat(params.fd, &sb) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001210 fprintf(stderr, "failed to fstat device to erase: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001211 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001212 }
1213
Tao Bao0940fe12015-08-27 16:41:21 -07001214 if (!S_ISBLK(sb.st_mode)) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001215 fprintf(stderr, "not a block device; skipping erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001216 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001217 }
1218
Tao Baobaad2d42015-12-06 16:56:27 -08001219 if (params.cpos >= params.tokens.size()) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001220 fprintf(stderr, "missing target blocks for erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001221 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001222 }
1223
Tao Bao0940fe12015-08-27 16:41:21 -07001224 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001225 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001226
Tao Bao0940fe12015-08-27 16:41:21 -07001227 if (params.canwrite) {
1228 fprintf(stderr, " erasing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001229
Tao Bao0940fe12015-08-27 16:41:21 -07001230 for (size_t i = 0; i < tgt.count; ++i) {
1231 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001232 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001233 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001234 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001235 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001236
Tao Bao0940fe12015-08-27 16:41:21 -07001237 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001238 fprintf(stderr, "BLKDISCARD ioctl failed: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001239 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001240 }
1241 }
1242 }
1243
Tao Bao0940fe12015-08-27 16:41:21 -07001244 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001245}
1246
1247// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001248typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001249
Tao Bao612336d2015-08-27 16:41:21 -07001250struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001251 const char* name;
1252 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001253};
Sami Tolvanen90221202014-12-09 16:39:47 +00001254
1255// CompareCommands and CompareCommandNames are for the hash table
1256
1257static int CompareCommands(const void* c1, const void* c2) {
1258 return strcmp(((const Command*) c1)->name, ((const Command*) c2)->name);
1259}
1260
1261static int CompareCommandNames(const void* c1, const void* c2) {
1262 return strcmp(((const Command*) c1)->name, (const char*) c2);
1263}
1264
1265// HashString is used to hash command names for the hash table
1266
1267static unsigned int HashString(const char *s) {
1268 unsigned int hash = 0;
1269 if (s) {
1270 while (*s) {
1271 hash = hash * 33 + *s++;
1272 }
1273 }
1274 return hash;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001275}
1276
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001277// args:
1278// - block device (or file) to modify in-place
1279// - transfer list (blob)
1280// - new data stream (filename within package.zip)
1281// - patch stream (filename within package.zip, must be uncompressed)
1282
Tao Bao0940fe12015-08-27 16:41:21 -07001283static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1284 const Command* commands, size_t cmdcount, bool dryrun) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001285 CommandParameters params;
Sami Tolvanen90221202014-12-09 16:39:47 +00001286 memset(&params, 0, sizeof(params));
1287 params.canwrite = !dryrun;
1288
1289 fprintf(stderr, "performing %s\n", dryrun ? "verification" : "update");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001290
Tao Bao612336d2015-08-27 16:41:21 -07001291 Value* blockdev_filename = nullptr;
1292 Value* transfer_list_value = nullptr;
1293 Value* new_data_fn = nullptr;
1294 Value* patch_data_fn = nullptr;
Doug Zongker1d5d6092014-08-21 10:47:24 -07001295 if (ReadValueArgs(state, argv, 4, &blockdev_filename, &transfer_list_value,
Sami Tolvanen90221202014-12-09 16:39:47 +00001296 &new_data_fn, &patch_data_fn) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001297 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001298 }
Tao Bao612336d2015-08-27 16:41:21 -07001299 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1300 FreeValue);
1301 std::unique_ptr<Value, decltype(&FreeValue)> transfer_list_value_holder(transfer_list_value,
1302 FreeValue);
1303 std::unique_ptr<Value, decltype(&FreeValue)> new_data_fn_holder(new_data_fn, FreeValue);
1304 std::unique_ptr<Value, decltype(&FreeValue)> patch_data_fn_holder(patch_data_fn, FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001305
1306 if (blockdev_filename->type != VAL_STRING) {
1307 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001308 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001309 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001310 if (transfer_list_value->type != VAL_BLOB) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001311 ErrorAbort(state, "transfer_list argument to %s must be blob", name);
Tao Bao612336d2015-08-27 16:41:21 -07001312 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001313 }
1314 if (new_data_fn->type != VAL_STRING) {
1315 ErrorAbort(state, "new_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001316 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001317 }
1318 if (patch_data_fn->type != VAL_STRING) {
1319 ErrorAbort(state, "patch_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001320 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001321 }
1322
Tao Bao612336d2015-08-27 16:41:21 -07001323 UpdaterInfo* ui = reinterpret_cast<UpdaterInfo*>(state->cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001324
Tao Bao0940fe12015-08-27 16:41:21 -07001325 if (ui == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001326 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001327 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001328
Tao Bao612336d2015-08-27 16:41:21 -07001329 FILE* cmd_pipe = ui->cmd_pipe;
1330 ZipArchive* za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001331
Tao Bao0940fe12015-08-27 16:41:21 -07001332 if (cmd_pipe == nullptr || za == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001333 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001334 }
1335
Tao Bao612336d2015-08-27 16:41:21 -07001336 const ZipEntry* patch_entry = mzFindZipEntry(za, patch_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001337 if (patch_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001338 fprintf(stderr, "%s(): no file \"%s\" in package", name, patch_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001339 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001340 }
1341
Sami Tolvanen90221202014-12-09 16:39:47 +00001342 params.patch_start = ui->package_zip_addr + mzGetZipEntryOffset(patch_entry);
Tao Bao612336d2015-08-27 16:41:21 -07001343 const ZipEntry* new_entry = mzFindZipEntry(za, new_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001344 if (new_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001345 fprintf(stderr, "%s(): no file \"%s\" in package", name, new_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001346 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001347 }
1348
Sami Tolvanen90221202014-12-09 16:39:47 +00001349 params.fd = TEMP_FAILURE_RETRY(open(blockdev_filename->data, O_RDWR));
Tao Bao612336d2015-08-27 16:41:21 -07001350 unique_fd fd_holder(params.fd);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001351
Sami Tolvanen90221202014-12-09 16:39:47 +00001352 if (params.fd == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001353 fprintf(stderr, "open \"%s\" failed: %s\n", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001354 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001355 }
1356
Sami Tolvanen90221202014-12-09 16:39:47 +00001357 if (params.canwrite) {
1358 params.nti.za = za;
1359 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001360
Tao Bao0940fe12015-08-27 16:41:21 -07001361 pthread_mutex_init(&params.nti.mu, nullptr);
1362 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001363 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001364 pthread_attr_init(&attr);
1365 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1366
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001367 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1368 if (error != 0) {
1369 fprintf(stderr, "pthread_create failed: %s\n", strerror(error));
Tao Bao612336d2015-08-27 16:41:21 -07001370 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001371 }
1372 }
1373
Tao Baobaad2d42015-12-06 16:56:27 -08001374 // Copy all the lines in transfer_list_value into std::string for
1375 // processing.
Tao Bao612336d2015-08-27 16:41:21 -07001376 const std::string transfer_list(transfer_list_value->data, transfer_list_value->size);
1377 std::vector<std::string> lines = android::base::Split(transfer_list, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001378 if (lines.size() < 2) {
1379 ErrorAbort(state, "too few lines in the transfer list [%zd]\n", lines.size());
1380 return StringValue(strdup(""));
1381 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001382
Sami Tolvanen90221202014-12-09 16:39:47 +00001383 // First line in transfer list is the version number
Tao Bao1fdec862015-10-21 14:57:44 -07001384 if (!android::base::ParseInt(lines[0].c_str(), &params.version, 1, 4)) {
Tao Bao612336d2015-08-27 16:41:21 -07001385 fprintf(stderr, "unexpected transfer list version [%s]\n", lines[0].c_str());
1386 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001387 }
1388
Sami Tolvanen90221202014-12-09 16:39:47 +00001389 fprintf(stderr, "blockimg version is %d\n", params.version);
1390
1391 // Second line in transfer list is the total number of blocks we expect to write
Tao Baob15fd222015-09-24 11:10:51 -07001392 int total_blocks;
1393 if (!android::base::ParseInt(lines[1].c_str(), &total_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001394 ErrorAbort(state, "unexpected block count [%s]\n", lines[1].c_str());
1395 return StringValue(strdup(""));
Tao Baob15fd222015-09-24 11:10:51 -07001396 }
1397
1398 if (total_blocks == 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001399 return StringValue(strdup("t"));
Sami Tolvanen90221202014-12-09 16:39:47 +00001400 }
1401
Tao Bao612336d2015-08-27 16:41:21 -07001402 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001403 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001404 if (lines.size() < 4) {
1405 ErrorAbort(state, "too few lines in the transfer list [%zu]\n", lines.size());
1406 return StringValue(strdup(""));
1407 }
1408
Sami Tolvanen90221202014-12-09 16:39:47 +00001409 // Third line is how many stash entries are needed simultaneously
Tao Bao612336d2015-08-27 16:41:21 -07001410 fprintf(stderr, "maximum stash entries %s\n", lines[2].c_str());
Doug Zongker52ae67d2014-09-08 12:22:09 -07001411
Sami Tolvanen90221202014-12-09 16:39:47 +00001412 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Baob15fd222015-09-24 11:10:51 -07001413 int stash_max_blocks;
1414 if (!android::base::ParseInt(lines[3].c_str(), &stash_max_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001415 ErrorAbort(state, "unexpected maximum stash blocks [%s]\n", lines[3].c_str());
1416 return StringValue(strdup(""));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001417 }
1418
Tao Baob15fd222015-09-24 11:10:51 -07001419 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001420 if (res == -1) {
1421 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001422 }
Tao Bao612336d2015-08-27 16:41:21 -07001423
Tao Baob15fd222015-09-24 11:10:51 -07001424 params.createdstash = res;
1425
Tao Bao612336d2015-08-27 16:41:21 -07001426 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001427 }
1428
Sami Tolvanen90221202014-12-09 16:39:47 +00001429 // Build a hash table of the available commands
Tao Bao612336d2015-08-27 16:41:21 -07001430 HashTable* cmdht = mzHashTableCreate(cmdcount, nullptr);
1431 std::unique_ptr<HashTable, decltype(&mzHashTableFree)> cmdht_holder(cmdht, mzHashTableFree);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001432
Tao Bao0940fe12015-08-27 16:41:21 -07001433 for (size_t i = 0; i < cmdcount; ++i) {
1434 unsigned int cmdhash = HashString(commands[i].name);
Sami Tolvanen90221202014-12-09 16:39:47 +00001435 mzHashTableLookup(cmdht, cmdhash, (void*) &commands[i], CompareCommands, true);
1436 }
1437
Tao Bao612336d2015-08-27 16:41:21 -07001438 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001439
Tao Bao612336d2015-08-27 16:41:21 -07001440 // Subsequent lines are all individual transfer commands
1441 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1442 const std::string& line_str(*it);
Tao Bao6a47dff2015-09-25 17:12:28 -07001443 if (line_str.empty()) {
1444 continue;
1445 }
1446
Tao Baobaad2d42015-12-06 16:56:27 -08001447 params.tokens = android::base::Split(line_str, " ");
1448 params.cpos = 0;
1449 params.cmdname = params.tokens[params.cpos++].c_str();
1450 params.cmdline = line_str.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001451
Tao Bao0940fe12015-08-27 16:41:21 -07001452 unsigned int cmdhash = HashString(params.cmdname);
Tao Bao612336d2015-08-27 16:41:21 -07001453 const Command* cmd = reinterpret_cast<const Command*>(mzHashTableLookup(cmdht, cmdhash,
Tao Baobaad2d42015-12-06 16:56:27 -08001454 const_cast<char*>(params.cmdname), CompareCommandNames,
1455 false));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001456
Tao Bao0940fe12015-08-27 16:41:21 -07001457 if (cmd == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001458 fprintf(stderr, "unexpected command [%s]\n", params.cmdname);
1459 goto pbiudone;
1460 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001461
Tao Bao0940fe12015-08-27 16:41:21 -07001462 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao612336d2015-08-27 16:41:21 -07001463 fprintf(stderr, "failed to execute command [%s]\n", line_str.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +00001464 goto pbiudone;
1465 }
1466
Sami Tolvanen90221202014-12-09 16:39:47 +00001467 if (params.canwrite) {
Tao Bao187efff2015-07-27 14:07:08 -07001468 if (fsync(params.fd) == -1) {
1469 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
1470 goto pbiudone;
1471 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001472 fprintf(cmd_pipe, "set_progress %.4f\n", (double) params.written / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001473 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001474 }
1475 }
1476
Sami Tolvanen90221202014-12-09 16:39:47 +00001477 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001478 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001479
Tao Bao0940fe12015-08-27 16:41:21 -07001480 fprintf(stderr, "wrote %zu blocks; expected %d\n", params.written, total_blocks);
Tao Bao612336d2015-08-27 16:41:21 -07001481 fprintf(stderr, "max alloc needed was %zu\n", params.buffer.size());
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001482
Sami Tolvanen90221202014-12-09 16:39:47 +00001483 // Delete stash only after successfully completing the update, as it
1484 // may contain blocks needed to complete the update later.
1485 DeleteStash(params.stashbase);
1486 } else {
1487 fprintf(stderr, "verified partition contents; update may be resumed\n");
1488 }
1489
1490 rc = 0;
1491
1492pbiudone:
Tao Baobaad2d42015-12-06 16:56:27 -08001493 if (fsync(params.fd) == -1) {
1494 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +00001495 }
Tao Baobaad2d42015-12-06 16:56:27 -08001496 // params.fd will be automatically closed because of the fd_holder above.
Sami Tolvanen90221202014-12-09 16:39:47 +00001497
Sami Tolvanen90221202014-12-09 16:39:47 +00001498 // Only delete the stash if the update cannot be resumed, or it's
1499 // a verification run and we created the stash.
1500 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1501 DeleteStash(params.stashbase);
1502 }
1503
Sami Tolvanen90221202014-12-09 16:39:47 +00001504 return StringValue(rc == 0 ? strdup("t") : strdup(""));
1505}
1506
1507// The transfer list is a text file containing commands to
1508// transfer data from one place to another on the target
1509// partition. We parse it and execute the commands in order:
1510//
1511// zero [rangeset]
1512// - fill the indicated blocks with zeros
1513//
1514// new [rangeset]
1515// - fill the blocks with data read from the new_data file
1516//
1517// erase [rangeset]
1518// - mark the given blocks as empty
1519//
1520// move <...>
1521// bsdiff <patchstart> <patchlen> <...>
1522// imgdiff <patchstart> <patchlen> <...>
1523// - read the source blocks, apply a patch (or not in the
1524// case of move), write result to target blocks. bsdiff or
1525// imgdiff specifies the type of patch; move means no patch
1526// at all.
1527//
1528// The format of <...> differs between versions 1 and 2;
1529// see the LoadSrcTgtVersion{1,2}() functions for a
1530// description of what's expected.
1531//
1532// stash <stash_id> <src_range>
1533// - (version 2+ only) load the given source range and stash
1534// the data in the given slot of the stash table.
1535//
Tao Baobaad2d42015-12-06 16:56:27 -08001536// free <stash_id>
1537// - (version 3+ only) free the given stash data.
1538//
Sami Tolvanen90221202014-12-09 16:39:47 +00001539// The creator of the transfer list will guarantee that no block
1540// is read (ie, used as the source for a patch or move) after it
1541// has been written.
1542//
1543// In version 2, the creator will guarantee that a given stash is
1544// loaded (with a stash command) before it's used in a
1545// move/bsdiff/imgdiff command.
1546//
1547// Within one command the source and target ranges may overlap so
1548// in general we need to read the entire source into memory before
1549// writing anything to the target blocks.
1550//
1551// All the patch data is concatenated into one patch_data file in
1552// the update package. It must be stored uncompressed because we
1553// memory-map it in directly from the archive. (Since patches are
1554// already compressed, we lose very little by not compressing
1555// their concatenation.)
1556//
1557// In version 3, commands that read data from the partition (i.e.
1558// move/bsdiff/imgdiff/stash) have one or more additional hashes
1559// before the range parameters, which are used to check if the
1560// command has already been completed and verify the integrity of
1561// the source data.
1562
1563Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001564 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001565 const Command commands[] = {
1566 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001567 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001568 { "free", PerformCommandFree },
1569 { "imgdiff", PerformCommandDiff },
1570 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001571 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001572 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001573 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001574 };
1575
1576 // Perform a dry run without writing to test if an update can proceed
1577 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001578 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001579}
1580
1581Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1582 const Command commands[] = {
1583 { "bsdiff", PerformCommandDiff },
1584 { "erase", PerformCommandErase },
1585 { "free", PerformCommandFree },
1586 { "imgdiff", PerformCommandDiff },
1587 { "move", PerformCommandMove },
1588 { "new", PerformCommandNew },
1589 { "stash", PerformCommandStash },
1590 { "zero", PerformCommandZero }
1591 };
1592
1593 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001594 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001595}
1596
Tao Bao0940fe12015-08-27 16:41:21 -07001597Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001598 Value* blockdev_filename;
1599 Value* ranges;
Tao Bao0940fe12015-08-27 16:41:21 -07001600
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001601 if (ReadValueArgs(state, argv, 2, &blockdev_filename, &ranges) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001602 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001603 }
Tao Bao612336d2015-08-27 16:41:21 -07001604 std::unique_ptr<Value, decltype(&FreeValue)> ranges_holder(ranges, FreeValue);
1605 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1606 FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001607
1608 if (blockdev_filename->type != VAL_STRING) {
1609 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001610 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001611 }
1612 if (ranges->type != VAL_STRING) {
1613 ErrorAbort(state, "ranges argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001614 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001615 }
1616
Tao Bao612336d2015-08-27 16:41:21 -07001617 int fd = open(blockdev_filename->data, O_RDWR);
1618 unique_fd fd_holder(fd);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001619 if (fd < 0) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001620 ErrorAbort(state, "open \"%s\" failed: %s", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001621 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001622 }
1623
Tao Bao612336d2015-08-27 16:41:21 -07001624 RangeSet rs;
Tao Bao0940fe12015-08-27 16:41:21 -07001625 parse_range(ranges->data, rs);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001626
1627 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001628 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001629
Tao Bao612336d2015-08-27 16:41:21 -07001630 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001631 for (size_t i = 0; i < rs.count; ++i) {
1632 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tao Bao612336d2015-08-27 16:41:21 -07001633 ErrorAbort(state, "failed to seek %s: %s", blockdev_filename->data, strerror(errno));
1634 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001635 }
1636
Tao Bao0940fe12015-08-27 16:41:21 -07001637 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001638 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1639 ErrorAbort(state, "failed to read %s: %s", blockdev_filename->data,
Tao Bao0940fe12015-08-27 16:41:21 -07001640 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001641 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001642 }
1643
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001644 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001645 }
1646 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001647 uint8_t digest[SHA_DIGEST_LENGTH];
1648 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001649
Tao Bao612336d2015-08-27 16:41:21 -07001650 return StringValue(strdup(print_sha1(digest).c_str()));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001651}
1652
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001653// This function checks if a device has been remounted R/W prior to an incremental
1654// OTA update. This is an common cause of update abortion. The function reads the
1655// 1st block of each partition and check for mounting time/count. It return string "t"
1656// if executes successfully and an empty string otherwise.
1657
1658Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
1659 Value* arg_filename;
1660
1661 if (ReadValueArgs(state, argv, 1, &arg_filename) < 0) {
1662 return nullptr;
1663 }
1664 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1665
1666 if (filename->type != VAL_STRING) {
1667 ErrorAbort(state, "filename argument to %s must be string", name);
1668 return StringValue(strdup(""));
1669 }
1670
1671 int fd = open(arg_filename->data, O_RDONLY);
1672 unique_fd fd_holder(fd);
1673 if (fd == -1) {
1674 ErrorAbort(state, "open \"%s\" failed: %s", arg_filename->data, strerror(errno));
1675 return StringValue(strdup(""));
1676 }
1677
1678 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1679 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1680
1681 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
1682 ErrorAbort(state, "failed to read %s: %s", arg_filename->data,
1683 strerror(errno));
1684 return StringValue(strdup(""));
1685 }
1686
1687 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1688 // Super block starts from block 0, offset 0x400
1689 // 0x2C: len32 Mount time
1690 // 0x30: len32 Write time
1691 // 0x34: len16 Number of mounts since the last fsck
1692 // 0x38: len16 Magic signature 0xEF53
1693
1694 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1695 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1696
1697 if (mount_count > 0) {
1698 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1699 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1700 }
1701
1702 return StringValue(strdup("t"));
1703}
1704
1705
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001706Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
1707 Value* arg_filename;
1708 Value* arg_ranges;
1709
1710 if (ReadValueArgs(state, argv, 2, &arg_filename, &arg_ranges) < 0) {
1711 return NULL;
1712 }
1713
1714 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1715 std::unique_ptr<Value, decltype(&FreeValue)> ranges(arg_ranges, FreeValue);
1716
1717 if (filename->type != VAL_STRING) {
1718 ErrorAbort(state, "filename argument to %s must be string", name);
1719 return StringValue(strdup(""));
1720 }
1721 if (ranges->type != VAL_STRING) {
1722 ErrorAbort(state, "ranges argument to %s must be string", name);
1723 return StringValue(strdup(""));
1724 }
1725
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001726 // Output notice to log when recover is attempted
1727 fprintf(stderr, "%s image corrupted, attempting to recover...\n", filename->data);
1728
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001729 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
1730 fec::io fh(filename->data, O_RDWR);
1731
1732 if (!fh) {
1733 ErrorAbort(state, "fec_open \"%s\" failed: %s", filename->data, strerror(errno));
1734 return StringValue(strdup(""));
1735 }
1736
1737 if (!fh.has_ecc() || !fh.has_verity()) {
1738 ErrorAbort(state, "unable to use metadata to correct errors");
1739 return StringValue(strdup(""));
1740 }
1741
1742 fec_status status;
1743
1744 if (!fh.get_status(status)) {
1745 ErrorAbort(state, "failed to read FEC status");
1746 return StringValue(strdup(""));
1747 }
1748
1749 RangeSet rs;
1750 parse_range(ranges->data, rs);
1751
1752 uint8_t buffer[BLOCKSIZE];
1753
1754 for (size_t i = 0; i < rs.count; ++i) {
1755 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1756 // Stay within the data area, libfec validates and corrects metadata
1757 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1758 continue;
1759 }
1760
1761 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tao Baobaad2d42015-12-06 16:56:27 -08001762 ErrorAbort(state, "failed to recover %s (block %zu): %s", filename->data,
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001763 j, strerror(errno));
1764 return StringValue(strdup(""));
1765 }
1766
1767 // If we want to be able to recover from a situation where rewriting a corrected
1768 // block doesn't guarantee the same data will be returned when re-read later, we
1769 // can save a copy of corrected blocks to /cache. Note:
1770 //
1771 // 1. Maximum space required from /cache is the same as the maximum number of
1772 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1773 // this would be ~16 MiB, for example.
1774 //
1775 // 2. To find out if this block was corrupted, call fec_get_status after each
1776 // read and check if the errors field value has increased.
1777 }
1778 }
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001779 fprintf(stderr, "...%s image recovered successfully.\n", filename->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001780 return StringValue(strdup("t"));
1781}
1782
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001783void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001784 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001785 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001786 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001787 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001788 RegisterFunction("range_sha1", RangeSha1Fn);
1789}