blob: 9d329cd240ae95c73b0d1afe8ea248e17d57d97c [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
18#include <errno.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000019#include <dirent.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
21#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000028#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070029#include <sys/types.h>
30#include <sys/wait.h>
31#include <sys/ioctl.h>
32#include <time.h>
33#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010034#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070035
Tianjie Xu7eca97e2016-03-22 18:08:12 -070036#include <map>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tao Bao0940fe12015-08-27 16:41:21 -070039#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070040
Elliott Hughes4b166f02015-12-04 15:30:20 -080041#include <android-base/parseint.h>
42#include <android-base/strings.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070043
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070044#include "applypatch/applypatch.h"
45#include "edify/expr.h"
Tianjie Xu57bed6d2015-12-15 11:47:30 -080046#include "install.h"
Sen Jiangc48cb5e2016-02-04 16:23:21 +080047#include "openssl/sha.h"
Sami Tolvanen90221202014-12-09 16:39:47 +000048#include "minzip/Hash.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080049#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070050#include "print_sha1.h"
Tao Bao0940fe12015-08-27 16:41:21 -070051#include "unique_fd.h"
52#include "updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070053
54#define BLOCKSIZE 4096
55
Sami Tolvanene82fa182015-06-10 15:58:12 +000056// Set this to 0 to interpret 'erase' transfers to mean do a
57// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
58// erase to mean fill the region with zeroes.
59#define DEBUG_ERASE 0
60
Sami Tolvanen90221202014-12-09 16:39:47 +000061#define STASH_DIRECTORY_BASE "/cache/recovery"
62#define STASH_DIRECTORY_MODE 0700
63#define STASH_FILE_MODE 0600
64
Tao Bao0940fe12015-08-27 16:41:21 -070065struct RangeSet {
66 size_t count; // Limit is INT_MAX.
Shrinivas Sahukara6153df2015-08-19 13:01:45 +053067 size_t size;
Tao Bao0940fe12015-08-27 16:41:21 -070068 std::vector<size_t> pos; // Actual limit is INT_MAX.
69};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070070
Tianjie Xu7eca97e2016-03-22 18:08:12 -070071static std::map<std::string, RangeSet> stash_map;
72
Tao Baobaad2d42015-12-06 16:56:27 -080073static void parse_range(const std::string& range_text, RangeSet& rs) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010074
Tao Baobaad2d42015-12-06 16:56:27 -080075 std::vector<std::string> pieces = android::base::Split(range_text, ",");
Tao Bao0940fe12015-08-27 16:41:21 -070076 if (pieces.size() < 3) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010077 goto err;
78 }
79
Tao Baob15fd222015-09-24 11:10:51 -070080 size_t num;
81 if (!android::base::ParseUint(pieces[0].c_str(), &num, static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010082 goto err;
83 }
84
Tao Baob15fd222015-09-24 11:10:51 -070085 if (num == 0 || num % 2) {
86 goto err; // must be even
87 } else if (num != pieces.size() - 1) {
88 goto err;
89 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +010090
Tao Bao0940fe12015-08-27 16:41:21 -070091 rs.pos.resize(num);
92 rs.count = num / 2;
93 rs.size = 0;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010094
Tao Bao0940fe12015-08-27 16:41:21 -070095 for (size_t i = 0; i < num; i += 2) {
Tao Baob15fd222015-09-24 11:10:51 -070096 if (!android::base::ParseUint(pieces[i+1].c_str(), &rs.pos[i],
97 static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010098 goto err;
99 }
100
Tao Baob15fd222015-09-24 11:10:51 -0700101 if (!android::base::ParseUint(pieces[i+2].c_str(), &rs.pos[i+1],
102 static_cast<size_t>(INT_MAX))) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530103 goto err;
104 }
105
Tao Bao0940fe12015-08-27 16:41:21 -0700106 if (rs.pos[i] >= rs.pos[i+1]) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530107 goto err; // empty or negative range
108 }
109
Tao Bao0940fe12015-08-27 16:41:21 -0700110 size_t sz = rs.pos[i+1] - rs.pos[i];
111 if (rs.size > SIZE_MAX - sz) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530112 goto err; // overflow
113 }
114
Tao Bao0940fe12015-08-27 16:41:21 -0700115 rs.size += sz;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700116 }
117
Tao Bao0940fe12015-08-27 16:41:21 -0700118 return;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100119
120err:
Tao Baobaad2d42015-12-06 16:56:27 -0800121 fprintf(stderr, "failed to parse range '%s'\n", range_text.c_str());
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100122 exit(1);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700123}
124
Tao Baoe6aa3322015-08-05 15:20:27 -0700125static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530126 for (size_t i = 0; i < r1.count; ++i) {
127 size_t r1_0 = r1.pos[i * 2];
128 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000129
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530130 for (size_t j = 0; j < r2.count; ++j) {
131 size_t r2_0 = r2.pos[j * 2];
132 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000133
Tao Baoc0f56ad2015-06-25 14:00:31 -0700134 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700135 return true;
Sami Tolvanen90221202014-12-09 16:39:47 +0000136 }
137 }
138 }
139
Tao Baoe6aa3322015-08-05 15:20:27 -0700140 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000141}
142
143static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700144 size_t so_far = 0;
145 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800146 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700147 if (r == -1) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700148 fprintf(stderr, "read failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000149 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700150 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700151 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700152 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000153 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700154}
155
Tao Bao612336d2015-08-27 16:41:21 -0700156static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
157 return read_all(fd, buffer.data(), size);
158}
159
Sami Tolvanen90221202014-12-09 16:39:47 +0000160static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700161 size_t written = 0;
162 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800163 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700164 if (w == -1) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700165 fprintf(stderr, "write failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000166 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700167 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700168 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700169 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000170
Sami Tolvanen90221202014-12-09 16:39:47 +0000171 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700172}
173
Tao Bao612336d2015-08-27 16:41:21 -0700174static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
175 return write_all(fd, buffer.data(), size);
176}
177
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700178static bool check_lseek(int fd, off64_t offset, int whence) {
179 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
180 if (rc == -1) {
181 fprintf(stderr, "lseek64 failed: %s\n", strerror(errno));
182 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700183 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700184 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700185}
186
Tao Bao612336d2015-08-27 16:41:21 -0700187static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700188 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700189 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700190
Tao Bao612336d2015-08-27 16:41:21 -0700191 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700192}
193
Tao Bao0940fe12015-08-27 16:41:21 -0700194struct RangeSinkState {
195 RangeSinkState(RangeSet& rs) : tgt(rs) { };
196
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700197 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700198 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530199 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700200 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700201};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700202
203static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700204 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700205
Tao Bao0940fe12015-08-27 16:41:21 -0700206 if (rss->p_remain == 0) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700207 fprintf(stderr, "range sink write overrun");
Sami Tolvanen90221202014-12-09 16:39:47 +0000208 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700209 }
210
211 ssize_t written = 0;
212 while (size > 0) {
213 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000214
215 if (rss->p_remain < write_now) {
216 write_now = rss->p_remain;
217 }
218
219 if (write_all(rss->fd, data, write_now) == -1) {
220 break;
221 }
222
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700223 data += write_now;
224 size -= write_now;
225
226 rss->p_remain -= write_now;
227 written += write_now;
228
229 if (rss->p_remain == 0) {
230 // move to the next block
231 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700232 if (rss->p_block < rss->tgt.count) {
233 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
234 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000235
Tao Bao0940fe12015-08-27 16:41:21 -0700236 if (!check_lseek(rss->fd, (off64_t)rss->tgt.pos[rss->p_block*2] * BLOCKSIZE,
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700237 SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000238 break;
239 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700240 } else {
241 // we can't write any more; return how many bytes have
242 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000243 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700244 }
245 }
246 }
247
248 return written;
249}
250
251// All of the data for all the 'new' transfers is contained in one
252// file in the update package, concatenated together in the order in
253// which transfers.list will need it. We want to stream it out of the
254// archive (it's compressed) without writing it to a temp file, but we
255// can't write each section until it's that transfer's turn to go.
256//
257// To achieve this, we expand the new data from the archive in a
258// background thread, and block that threads 'receive uncompressed
259// data' function until the main thread has reached a point where we
260// want some new data to be written. We signal the background thread
261// with the destination for the data and block the main thread,
262// waiting for the background thread to complete writing that section.
263// Then it signals the main thread to wake up and goes back to
264// blocking waiting for a transfer.
265//
266// NewThreadInfo is the struct used to pass information back and forth
267// between the two threads. When the main thread wants some data
268// written, it sets rss to the destination location and signals the
269// condition. When the background thread is done writing, it clears
270// rss and signals the condition again.
271
Tao Bao0940fe12015-08-27 16:41:21 -0700272struct NewThreadInfo {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700273 ZipArchive* za;
274 const ZipEntry* entry;
275
276 RangeSinkState* rss;
277
278 pthread_mutex_t mu;
279 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700280};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700281
282static bool receive_new_data(const unsigned char* data, int size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700283 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700284
285 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700286 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700287 // data is wanted.
288 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700289 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700290 pthread_cond_wait(&nti->cv, &nti->mu);
291 }
292 pthread_mutex_unlock(&nti->mu);
293
294 // At this point nti->rss is set, and we own it. The main
295 // thread is waiting for it to disappear from nti.
296 ssize_t written = RangeSinkWrite(data, size, nti->rss);
297 data += written;
298 size -= written;
299
Tao Bao0940fe12015-08-27 16:41:21 -0700300 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700301 // we have written all the bytes desired by this rss.
302
303 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700304 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700305 pthread_cond_broadcast(&nti->cv);
306 pthread_mutex_unlock(&nti->mu);
307 }
308 }
309
310 return true;
311}
312
313static void* unzip_new_data(void* cookie) {
314 NewThreadInfo* nti = (NewThreadInfo*) cookie;
315 mzProcessZipEntryContents(nti->za, nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700316 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700317}
318
Tao Bao612336d2015-08-27 16:41:21 -0700319static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000320 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700321 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000322
Tao Bao0940fe12015-08-27 16:41:21 -0700323 for (size_t i = 0; i < src.count; ++i) {
324 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000325 return -1;
326 }
327
Tao Bao0940fe12015-08-27 16:41:21 -0700328 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000329
Tao Bao612336d2015-08-27 16:41:21 -0700330 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000331 return -1;
332 }
333
334 p += size;
335 }
336
337 return 0;
338}
339
Tao Bao612336d2015-08-27 16:41:21 -0700340static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
341 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000342
Tao Bao0940fe12015-08-27 16:41:21 -0700343 size_t p = 0;
344 for (size_t i = 0; i < tgt.count; ++i) {
345 if (!check_lseek(fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000346 return -1;
347 }
348
Tao Bao0940fe12015-08-27 16:41:21 -0700349 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000350
Tao Bao612336d2015-08-27 16:41:21 -0700351 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000352 return -1;
353 }
354
355 p += size;
356 }
357
358 return 0;
359}
360
Tao Baobaad2d42015-12-06 16:56:27 -0800361// Parameters for transfer list command functions
362struct CommandParameters {
363 std::vector<std::string> tokens;
364 size_t cpos;
365 const char* cmdname;
366 const char* cmdline;
367 std::string freestash;
368 std::string stashbase;
369 bool canwrite;
370 int createdstash;
371 int fd;
372 bool foundwrites;
373 bool isunresumable;
374 int version;
375 size_t written;
376 NewThreadInfo nti;
377 pthread_t thread;
378 std::vector<uint8_t> buffer;
379 uint8_t* patch_start;
380};
381
Doug Zongker52ae67d2014-09-08 12:22:09 -0700382// Do a source/target load for move/bsdiff/imgdiff in version 1.
Tao Baobaad2d42015-12-06 16:56:27 -0800383// We expect to parse the remainder of the parameter tokens as:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700384//
385// <src_range> <tgt_range>
386//
387// The source range is loaded into the provided buffer, reallocating
Tao Bao34847b22015-09-08 11:05:49 -0700388// it to make it larger if necessary.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700389
Tao Baobaad2d42015-12-06 16:56:27 -0800390static int LoadSrcTgtVersion1(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700391 std::vector<uint8_t>& buffer, int fd) {
Tao Baobaad2d42015-12-06 16:56:27 -0800392
393 if (params.cpos + 1 >= params.tokens.size()) {
394 fprintf(stderr, "invalid parameters\n");
395 return -1;
396 }
397
Tao Bao612336d2015-08-27 16:41:21 -0700398 // <src_range>
Tao Bao0940fe12015-08-27 16:41:21 -0700399 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800400 parse_range(params.tokens[params.cpos++], src);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700401
Tao Bao612336d2015-08-27 16:41:21 -0700402 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800403 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700404
Tao Bao612336d2015-08-27 16:41:21 -0700405 allocate(src.size * BLOCKSIZE, buffer);
406 int rc = ReadBlocks(src, buffer, fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700407 src_blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000408
Sami Tolvanen90221202014-12-09 16:39:47 +0000409 return rc;
410}
411
Tao Bao612336d2015-08-27 16:41:21 -0700412static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700413 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800414 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700415 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000416
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800417 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000418
Tao Baoe6aa3322015-08-05 15:20:27 -0700419 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000420
Tao Bao0940fe12015-08-27 16:41:21 -0700421 if (hexdigest != expected) {
422 if (printerror) {
423 fprintf(stderr, "failed to verify blocks (expected %s, read %s)\n",
424 expected.c_str(), hexdigest.c_str());
425 }
426 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000427 }
428
Tao Bao0940fe12015-08-27 16:41:21 -0700429 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000430}
431
Tao Bao0940fe12015-08-27 16:41:21 -0700432static std::string GetStashFileName(const std::string& base, const std::string& id,
433 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700434 if (base.empty()) {
435 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000436 }
437
Tao Baoe6aa3322015-08-05 15:20:27 -0700438 std::string fn(STASH_DIRECTORY_BASE);
439 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000440
441 return fn;
442}
443
Tao Baoe6aa3322015-08-05 15:20:27 -0700444typedef void (*StashCallback)(const std::string&, void*);
Sami Tolvanen90221202014-12-09 16:39:47 +0000445
446// Does a best effort enumeration of stash files. Ignores possible non-file
447// items in the stash directory and continues despite of errors. Calls the
448// 'callback' function for each file and passes 'data' to the function as a
449// parameter.
450
Tao Baoe6aa3322015-08-05 15:20:27 -0700451static void EnumerateStash(const std::string& dirname, StashCallback callback, void* data) {
Tao Bao0940fe12015-08-27 16:41:21 -0700452 if (dirname.empty() || callback == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000453 return;
454 }
455
Tao Baoe6aa3322015-08-05 15:20:27 -0700456 std::unique_ptr<DIR, int(*)(DIR*)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000457
Tao Bao0940fe12015-08-27 16:41:21 -0700458 if (directory == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000459 if (errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700460 fprintf(stderr, "opendir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000461 }
462 return;
463 }
464
Tao Baoe6aa3322015-08-05 15:20:27 -0700465 struct dirent* item;
Tao Bao0940fe12015-08-27 16:41:21 -0700466 while ((item = readdir(directory.get())) != nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000467 if (item->d_type != DT_REG) {
468 continue;
469 }
470
Tao Baoe6aa3322015-08-05 15:20:27 -0700471 std::string fn = dirname + "/" + std::string(item->d_name);
Sami Tolvanen90221202014-12-09 16:39:47 +0000472 callback(fn, data);
Sami Tolvanen90221202014-12-09 16:39:47 +0000473 }
474}
475
Tao Baoe6aa3322015-08-05 15:20:27 -0700476static void UpdateFileSize(const std::string& fn, void* data) {
477 if (fn.empty() || !data) {
478 return;
479 }
480
Tao Bao0940fe12015-08-27 16:41:21 -0700481 struct stat sb;
482 if (stat(fn.c_str(), &sb) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700483 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000484 return;
485 }
486
Tao Baoe6aa3322015-08-05 15:20:27 -0700487 int* size = reinterpret_cast<int*>(data);
Tao Bao0940fe12015-08-27 16:41:21 -0700488 *size += sb.st_size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000489}
490
491// Deletes the stash directory and all files in it. Assumes that it only
492// contains files. There is nothing we can do about unlikely, but possible
493// errors, so they are merely logged.
494
Tao Bao0940fe12015-08-27 16:41:21 -0700495static void DeleteFile(const std::string& fn, void* /* data */) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700496 if (!fn.empty()) {
497 fprintf(stderr, "deleting %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000498
Tao Baoe6aa3322015-08-05 15:20:27 -0700499 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
500 fprintf(stderr, "unlink \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000501 }
502 }
503}
504
Tao Baoe6aa3322015-08-05 15:20:27 -0700505static void DeletePartial(const std::string& fn, void* data) {
506 if (android::base::EndsWith(fn, ".partial")) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000507 DeleteFile(fn, data);
508 }
509}
510
Tao Baoe6aa3322015-08-05 15:20:27 -0700511static void DeleteStash(const std::string& base) {
512 if (base.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000513 return;
514 }
515
Tao Baoe6aa3322015-08-05 15:20:27 -0700516 fprintf(stderr, "deleting stash %s\n", base.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000517
Tao Baoe6aa3322015-08-05 15:20:27 -0700518 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700519 EnumerateStash(dirname, DeleteFile, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000520
Tao Baoe6aa3322015-08-05 15:20:27 -0700521 if (rmdir(dirname.c_str()) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000522 if (errno != ENOENT && errno != ENOTDIR) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700523 fprintf(stderr, "rmdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000524 }
525 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000526}
527
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700528static int LoadStash(CommandParameters& params, const std::string& base, const std::string& id,
529 bool verify, size_t* blocks, std::vector<uint8_t>& buffer, bool printnoent) {
530 // In verify mode, if source range_set was saved for the given hash,
531 // check contents in the source blocks first. If the check fails,
532 // search for the stashed files on /cache as usual.
533 if (!params.canwrite) {
534 if (stash_map.find(id) != stash_map.end()) {
535 const RangeSet& src = stash_map[id];
536 allocate(src.size * BLOCKSIZE, buffer);
537
538 if (ReadBlocks(src, buffer, params.fd) == -1) {
539 fprintf(stderr, "failed to read source blocks in stash map.\n");
540 return -1;
541 }
542 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
543 fprintf(stderr, "failed to verify loaded source blocks in stash map.\n");
544 return -1;
545 }
546 return 0;
547 }
548 }
549
Tao Bao612336d2015-08-27 16:41:21 -0700550 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700551 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000552 }
553
Tao Bao0940fe12015-08-27 16:41:21 -0700554 size_t blockcount = 0;
555
Sami Tolvanen90221202014-12-09 16:39:47 +0000556 if (!blocks) {
557 blocks = &blockcount;
558 }
559
Tao Bao0940fe12015-08-27 16:41:21 -0700560 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000561
Tao Bao0940fe12015-08-27 16:41:21 -0700562 struct stat sb;
563 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000564
565 if (res == -1) {
566 if (errno != ENOENT || printnoent) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700567 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000568 }
Tao Bao0940fe12015-08-27 16:41:21 -0700569 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000570 }
571
Tao Baoe6aa3322015-08-05 15:20:27 -0700572 fprintf(stderr, " loading %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000573
Tao Bao0940fe12015-08-27 16:41:21 -0700574 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700575 fprintf(stderr, "%s size %" PRId64 " not multiple of block size %d",
Tao Bao0940fe12015-08-27 16:41:21 -0700576 fn.c_str(), static_cast<int64_t>(sb.st_size), BLOCKSIZE);
577 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000578 }
579
Jed Estepa7b9a462015-12-15 16:04:53 -0800580 int fd = TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY));
Tao Bao0940fe12015-08-27 16:41:21 -0700581 unique_fd fd_holder(fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000582
583 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700584 fprintf(stderr, "open \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700585 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000586 }
587
Tao Bao612336d2015-08-27 16:41:21 -0700588 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000589
Tao Bao612336d2015-08-27 16:41:21 -0700590 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700591 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000592 }
593
Tao Bao0940fe12015-08-27 16:41:21 -0700594 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000595
Tao Bao612336d2015-08-27 16:41:21 -0700596 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700597 fprintf(stderr, "unexpected contents in %s\n", fn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700598 DeleteFile(fn, nullptr);
599 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000600 }
601
Tao Bao0940fe12015-08-27 16:41:21 -0700602 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000603}
604
Tao Bao612336d2015-08-27 16:41:21 -0700605static int WriteStash(const std::string& base, const std::string& id, int blocks,
606 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
607 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700608 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000609 }
610
611 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
612 fprintf(stderr, "not enough space to write stash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700613 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000614 }
615
Tao Bao0940fe12015-08-27 16:41:21 -0700616 std::string fn = GetStashFileName(base, id, ".partial");
617 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000618
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100619 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700620 struct stat sb;
621 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100622
623 if (res == 0) {
624 // The file already exists and since the name is the hash of the contents,
625 // it's safe to assume the contents are identical (accidental hash collisions
626 // are unlikely)
Tao Baoe6aa3322015-08-05 15:20:27 -0700627 fprintf(stderr, " skipping %d existing blocks in %s\n", blocks, cn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700628 *exists = true;
629 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100630 }
631
Tao Bao0940fe12015-08-27 16:41:21 -0700632 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100633 }
634
Tao Baoe6aa3322015-08-05 15:20:27 -0700635 fprintf(stderr, " writing %d blocks to %s\n", blocks, cn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000636
Jed Estepa7b9a462015-12-15 16:04:53 -0800637 int fd = TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE));
Tao Bao0940fe12015-08-27 16:41:21 -0700638 unique_fd fd_holder(fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000639
640 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700641 fprintf(stderr, "failed to create \"%s\": %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700642 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000643 }
644
645 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700646 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000647 }
648
Jed Estepa7b9a462015-12-15 16:04:53 -0800649 if (ota_fsync(fd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700650 fprintf(stderr, "fsync \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700651 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000652 }
653
Tao Baoe6aa3322015-08-05 15:20:27 -0700654 if (rename(fn.c_str(), cn.c_str()) == -1) {
655 fprintf(stderr, "rename(\"%s\", \"%s\") failed: %s\n", fn.c_str(), cn.c_str(),
656 strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700657 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000658 }
659
Tao Bao0940fe12015-08-27 16:41:21 -0700660 std::string dname = GetStashFileName(base, "", "");
Jed Estepa7b9a462015-12-15 16:04:53 -0800661 int dfd = TEMP_FAILURE_RETRY(ota_open(dname.c_str(), O_RDONLY | O_DIRECTORY));
Tao Bao0940fe12015-08-27 16:41:21 -0700662 unique_fd dfd_holder(dfd);
Tao Baodc392262015-07-31 15:56:44 -0700663
664 if (dfd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700665 fprintf(stderr, "failed to open \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700666 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700667 }
668
Jed Estepa7b9a462015-12-15 16:04:53 -0800669 if (ota_fsync(dfd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700670 fprintf(stderr, "fsync \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700671 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700672 }
673
Tao Bao0940fe12015-08-27 16:41:21 -0700674 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000675}
676
677// Creates a directory for storing stash files and checks if the /cache partition
678// hash enough space for the expected amount of blocks we need to store. Returns
679// >0 if we created the directory, zero if it existed already, and <0 of failure.
680
Tao Bao0940fe12015-08-27 16:41:21 -0700681static int CreateStash(State* state, int maxblocks, const char* blockdev, std::string& base) {
682 if (blockdev == nullptr) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700683 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000684 }
685
686 // Stash directory should be different for each partition to avoid conflicts
687 // when updating multiple partitions at the same time, so we use the hash of
688 // the block device name as the base directory
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800689 uint8_t digest[SHA_DIGEST_LENGTH];
690 SHA1(reinterpret_cast<const uint8_t*>(blockdev), strlen(blockdev), digest);
Tao Baoe6aa3322015-08-05 15:20:27 -0700691 base = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000692
Tao Baoe6aa3322015-08-05 15:20:27 -0700693 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700694 struct stat sb;
695 int res = stat(dirname.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000696
697 if (res == -1 && errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700698 ErrorAbort(state, "stat \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
699 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000700 } else if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700701 fprintf(stderr, "creating stash %s\n", dirname.c_str());
702 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000703
704 if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700705 ErrorAbort(state, "mkdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
706 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000707 }
708
709 if (CacheSizeCheck(maxblocks * BLOCKSIZE) != 0) {
710 ErrorAbort(state, "not enough space for stash\n");
Tao Baoe6aa3322015-08-05 15:20:27 -0700711 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000712 }
713
Tao Baoe6aa3322015-08-05 15:20:27 -0700714 return 1; // Created directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000715 }
716
Tao Baoe6aa3322015-08-05 15:20:27 -0700717 fprintf(stderr, "using existing stash %s\n", dirname.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000718
719 // If the directory already exists, calculate the space already allocated to
720 // stash files and check if there's enough for all required blocks. Delete any
721 // partially completed stash files first.
722
Tao Bao0940fe12015-08-27 16:41:21 -0700723 EnumerateStash(dirname, DeletePartial, nullptr);
Tao Baoe6aa3322015-08-05 15:20:27 -0700724 int size = 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000725 EnumerateStash(dirname, UpdateFileSize, &size);
726
Tao Bao0940fe12015-08-27 16:41:21 -0700727 size = maxblocks * BLOCKSIZE - size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000728
729 if (size > 0 && CacheSizeCheck(size) != 0) {
730 ErrorAbort(state, "not enough space for stash (%d more needed)\n", size);
Tao Baoe6aa3322015-08-05 15:20:27 -0700731 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000732 }
733
Tao Baoe6aa3322015-08-05 15:20:27 -0700734 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000735}
736
Tao Baobaad2d42015-12-06 16:56:27 -0800737static int SaveStash(CommandParameters& params, const std::string& base,
738 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000739
Tao Baobaad2d42015-12-06 16:56:27 -0800740 // <stash_id> <src_range>
741 if (params.cpos + 1 >= params.tokens.size()) {
742 fprintf(stderr, "missing id and/or src range fields in stash command\n");
Sami Tolvanen90221202014-12-09 16:39:47 +0000743 return -1;
744 }
Tao Baobaad2d42015-12-06 16:56:27 -0800745 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000746
Tao Bao0940fe12015-08-27 16:41:21 -0700747 size_t blocks = 0;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700748 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000749 // Stash file already exists and has expected contents. Do not
750 // read from source again, as the source may have been already
751 // overwritten during a previous attempt.
752 return 0;
753 }
754
Tao Bao34847b22015-09-08 11:05:49 -0700755 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800756 parse_range(params.tokens[params.cpos++], src);
Tao Bao34847b22015-09-08 11:05:49 -0700757
Tao Bao612336d2015-08-27 16:41:21 -0700758 allocate(src.size * BLOCKSIZE, buffer);
759 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000760 return -1;
761 }
Tao Bao34847b22015-09-08 11:05:49 -0700762 blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000763
Tao Bao612336d2015-08-27 16:41:21 -0700764 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000765 // Source blocks have unexpected contents. If we actually need this
766 // data later, this is an unrecoverable error. However, the command
767 // that uses the data may have already completed previously, so the
768 // possible failure will occur during source block verification.
Tao Bao0940fe12015-08-27 16:41:21 -0700769 fprintf(stderr, "failed to load source blocks for stash %s\n", id.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000770 return 0;
771 }
772
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700773 // In verify mode, save source range_set instead of stashing blocks.
774 if (!params.canwrite && usehash) {
775 stash_map[id] = src;
776 return 0;
777 }
778
Tao Bao0940fe12015-08-27 16:41:21 -0700779 fprintf(stderr, "stashing %zu blocks to %s\n", blocks, id.c_str());
Tao Bao612336d2015-08-27 16:41:21 -0700780 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000781}
782
Tao Baobaad2d42015-12-06 16:56:27 -0800783static int FreeStash(const std::string& base, const std::string& id) {
784 if (base.empty() || id.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000785 return -1;
786 }
787
Tao Baobaad2d42015-12-06 16:56:27 -0800788 std::string fn = GetStashFileName(base, id, "");
Tao Bao0940fe12015-08-27 16:41:21 -0700789 DeleteFile(fn, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000790
791 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700792}
793
Tao Bao612336d2015-08-27 16:41:21 -0700794static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
795 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700796 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700797 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700798 // may be the same buffer.
799
Tao Bao612336d2015-08-27 16:41:21 -0700800 const uint8_t* from = source.data();
801 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700802 size_t start = locs.size;
803 for (int i = locs.count-1; i >= 0; --i) {
804 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700805 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700806 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700807 blocks * BLOCKSIZE);
808 }
809}
810
811// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800812// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700813//
814// <tgt_range> <src_block_count> <src_range>
815// (loads data from source image only)
816//
817// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
818// (loads data from stashes only)
819//
820// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
821// (loads data from both source image and stashes)
822//
823// On return, buffer is filled with the loaded source data (rearranged
824// and combined with stashed data as necessary). buffer may be
825// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000826// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700827
Tao Baobaad2d42015-12-06 16:56:27 -0800828static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700829 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800830
831 // At least it needs to provide three parameters: <tgt_range>,
832 // <src_block_count> and "-"/<src_range>.
833 if (params.cpos + 2 >= params.tokens.size()) {
834 fprintf(stderr, "invalid parameters\n");
835 return -1;
836 }
837
Tao Bao612336d2015-08-27 16:41:21 -0700838 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800839 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700840
Tao Bao612336d2015-08-27 16:41:21 -0700841 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800842 const std::string& token = params.tokens[params.cpos++];
843 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
844 fprintf(stderr, "invalid src_block_count \"%s\"\n", token.c_str());
845 return -1;
846 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700847
Tao Bao612336d2015-08-27 16:41:21 -0700848 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700849
Tao Bao612336d2015-08-27 16:41:21 -0700850 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800851 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700852 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800853 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700854 } else {
Tao Bao0940fe12015-08-27 16:41:21 -0700855 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800856 parse_range(params.tokens[params.cpos++], src);
Tao Bao612336d2015-08-27 16:41:21 -0700857 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700858
Tao Bao34847b22015-09-08 11:05:49 -0700859 if (overlap) {
860 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700861 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000862
Sami Tolvanen90221202014-12-09 16:39:47 +0000863 if (res == -1) {
864 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700865 }
866
Tao Baobaad2d42015-12-06 16:56:27 -0800867 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000868 // no stashes, only source range
869 return 0;
870 }
871
Tao Bao612336d2015-08-27 16:41:21 -0700872 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800873 parse_range(params.tokens[params.cpos++], locs);
Tao Bao612336d2015-08-27 16:41:21 -0700874 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700875 }
876
Tao Baobaad2d42015-12-06 16:56:27 -0800877 // <[stash_id:stash_range]>
878 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700879 // Each word is a an index into the stash table, a colon, and
880 // then a rangeset describing where in the source block that
881 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800882 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
883 if (tokens.size() != 2) {
884 fprintf(stderr, "invalid parameter\n");
885 return -1;
886 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000887
Tao Bao612336d2015-08-27 16:41:21 -0700888 std::vector<uint8_t> stash;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700889 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000890
891 if (res == -1) {
892 // These source blocks will fail verification if used later, but we
893 // will let the caller decide if this is a fatal failure
Tao Baobaad2d42015-12-06 16:56:27 -0800894 fprintf(stderr, "failed to load stash %s\n", tokens[0].c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000895 continue;
896 }
897
Tao Bao612336d2015-08-27 16:41:21 -0700898 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800899 parse_range(tokens[1], locs);
Sami Tolvanen90221202014-12-09 16:39:47 +0000900
Tao Bao612336d2015-08-27 16:41:21 -0700901 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000902 }
903
904 return 0;
905}
906
Sami Tolvanen90221202014-12-09 16:39:47 +0000907// Do a source/target load for move/bsdiff/imgdiff in version 3.
908//
909// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
910// tells the function whether to expect separate source and targe block hashes, or
911// if they are both the same and only one hash should be expected, and
912// 'isunresumable', which receives a non-zero value if block verification fails in
913// a way that the update cannot be resumed anymore.
914//
915// If the function is unable to load the necessary blocks or their contents don't
916// match the hashes, the return value is -1 and the command should be aborted.
917//
918// If the return value is 1, the command has already been completed according to
919// the contents of the target blocks, and should not be performed again.
920//
921// If the return value is 0, source blocks have expected content and the command
922// can be performed.
923
Tao Bao34847b22015-09-08 11:05:49 -0700924static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -0700925 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000926
Tao Baobaad2d42015-12-06 16:56:27 -0800927 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000928 fprintf(stderr, "missing source hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700929 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000930 }
931
Tao Baobaad2d42015-12-06 16:56:27 -0800932 std::string srchash = params.tokens[params.cpos++];
933 std::string tgthash;
934
Sami Tolvanen90221202014-12-09 16:39:47 +0000935 if (onehash) {
936 tgthash = srchash;
937 } else {
Tao Baobaad2d42015-12-06 16:56:27 -0800938 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000939 fprintf(stderr, "missing target hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700940 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000941 }
Tao Baobaad2d42015-12-06 16:56:27 -0800942 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000943 }
944
Tao Baobaad2d42015-12-06 16:56:27 -0800945 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd, params.stashbase,
946 &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700947 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000948 }
949
Tao Bao34847b22015-09-08 11:05:49 -0700950 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000951
Tao Bao612336d2015-08-27 16:41:21 -0700952 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700953 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000954 }
955
Tao Bao612336d2015-08-27 16:41:21 -0700956 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000957 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -0700958 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000959 }
960
Tao Bao0940fe12015-08-27 16:41:21 -0700961 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000962 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700963 // resume from possible write errors. In verify mode, we can skip stashing
964 // because the source blocks won't be overwritten.
965 if (overlap && params.canwrite) {
Tao Baobaad2d42015-12-06 16:56:27 -0800966 fprintf(stderr, "stashing %zu overlapping blocks to %s\n", src_blocks,
967 srchash.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000968
Tao Bao0940fe12015-08-27 16:41:21 -0700969 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -0700970 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -0700971 &stash_exists) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000972 fprintf(stderr, "failed to stash overlapping source blocks\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700973 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000974 }
975
976 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100977 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700978 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100979 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000980 }
981
982 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -0700983 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000984 }
985
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700986 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
987 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100988 // Overlapping source blocks were previously stashed, command can proceed.
989 // We are recovering from an interrupted command, so we don't know if the
990 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -0700991 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000992 }
993
994 // Valid source data not available, update cannot be resumed
995 fprintf(stderr, "partition has unexpected contents\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700996 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +0000997
Tao Bao0940fe12015-08-27 16:41:21 -0700998 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000999}
1000
Tao Bao0940fe12015-08-27 16:41:21 -07001001static int PerformCommandMove(CommandParameters& params) {
1002 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001003 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001004 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001005 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001006
Tao Bao0940fe12015-08-27 16:41:21 -07001007 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001008 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001009 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001010 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001011 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001012 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001013 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001014 }
1015
1016 if (status == -1) {
1017 fprintf(stderr, "failed to read blocks for move\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001018 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001019 }
1020
1021 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001022 params.foundwrites = true;
1023 } else if (params.foundwrites) {
1024 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001025 }
1026
Tao Bao0940fe12015-08-27 16:41:21 -07001027 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001028 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001029 fprintf(stderr, " moving %zu blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001030
Tao Bao0940fe12015-08-27 16:41:21 -07001031 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1032 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001033 }
1034 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001035 fprintf(stderr, "skipping %zu already moved blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001036 }
1037
1038 }
1039
Tao Baobaad2d42015-12-06 16:56:27 -08001040 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001041 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001042 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001043 }
1044
Tao Bao0940fe12015-08-27 16:41:21 -07001045 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001046
Tao Bao0940fe12015-08-27 16:41:21 -07001047 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001048}
1049
Tao Bao0940fe12015-08-27 16:41:21 -07001050static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001051 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001052 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001053}
1054
Tao Bao0940fe12015-08-27 16:41:21 -07001055static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001056 // <stash_id>
1057 if (params.cpos >= params.tokens.size()) {
1058 fprintf(stderr, "missing stash id in free command\n");
1059 return -1;
1060 }
1061
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001062 const std::string& id = params.tokens[params.cpos++];
1063
1064 if (!params.canwrite && stash_map.find(id) != stash_map.end()) {
1065 stash_map.erase(id);
1066 return 0;
1067 }
1068
Tao Bao0940fe12015-08-27 16:41:21 -07001069 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001070 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001071 }
1072
1073 return 0;
1074}
1075
Tao Bao0940fe12015-08-27 16:41:21 -07001076static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001077
Tao Baobaad2d42015-12-06 16:56:27 -08001078 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001079 fprintf(stderr, "missing target blocks for zero\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001080 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001081 }
1082
Tao Bao0940fe12015-08-27 16:41:21 -07001083 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001084 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001085
Tao Bao0940fe12015-08-27 16:41:21 -07001086 fprintf(stderr, " zeroing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001087
Tao Bao612336d2015-08-27 16:41:21 -07001088 allocate(BLOCKSIZE, params.buffer);
1089 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001090
Tao Bao0940fe12015-08-27 16:41:21 -07001091 if (params.canwrite) {
1092 for (size_t i = 0; i < tgt.count; ++i) {
1093 if (!check_lseek(params.fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
1094 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001095 }
1096
Tao Bao0940fe12015-08-27 16:41:21 -07001097 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1098 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1099 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001100 }
1101 }
1102 }
1103 }
1104
Tao Bao0940fe12015-08-27 16:41:21 -07001105 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001106 // Update only for the zero command, as the erase command will call
1107 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001108 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001109 }
1110
Tao Bao0940fe12015-08-27 16:41:21 -07001111 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001112}
1113
Tao Bao0940fe12015-08-27 16:41:21 -07001114static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001115
Tao Baobaad2d42015-12-06 16:56:27 -08001116 if (params.cpos >= params.tokens.size()) {
1117 fprintf(stderr, "missing target blocks for new\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001118 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001119 }
1120
Tao Bao0940fe12015-08-27 16:41:21 -07001121 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001122 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001123
Tao Bao0940fe12015-08-27 16:41:21 -07001124 if (params.canwrite) {
1125 fprintf(stderr, " writing %zu blocks of new data\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001126
Tao Bao0940fe12015-08-27 16:41:21 -07001127 RangeSinkState rss(tgt);
1128 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001129 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001130 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001131
Tao Bao0940fe12015-08-27 16:41:21 -07001132 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1133 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001134 }
1135
Tao Bao0940fe12015-08-27 16:41:21 -07001136 pthread_mutex_lock(&params.nti.mu);
1137 params.nti.rss = &rss;
1138 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001139
Tao Bao0940fe12015-08-27 16:41:21 -07001140 while (params.nti.rss) {
1141 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001142 }
1143
Tao Bao0940fe12015-08-27 16:41:21 -07001144 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001145 }
1146
Tao Bao0940fe12015-08-27 16:41:21 -07001147 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001148
Tao Bao0940fe12015-08-27 16:41:21 -07001149 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001150}
1151
Tao Bao0940fe12015-08-27 16:41:21 -07001152static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001153
Tao Baobaad2d42015-12-06 16:56:27 -08001154 // <offset> <length>
1155 if (params.cpos + 1 >= params.tokens.size()) {
1156 fprintf(stderr, "missing patch offset or length for %s\n", params.cmdname);
Tao Bao0940fe12015-08-27 16:41:21 -07001157 return -1;
1158 }
1159
Tao Baobaad2d42015-12-06 16:56:27 -08001160 size_t offset;
1161 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
1162 fprintf(stderr, "invalid patch offset\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001163 return -1;
1164 }
1165
Tao Baobaad2d42015-12-06 16:56:27 -08001166 size_t len;
1167 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
1168 fprintf(stderr, "invalid patch offset\n");
1169 return -1;
1170 }
Tao Bao0940fe12015-08-27 16:41:21 -07001171
Tao Bao612336d2015-08-27 16:41:21 -07001172 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001173 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001174 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001175 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001176 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001177 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001178 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001179 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001180 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001181 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001182 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001183 }
1184
1185 if (status == -1) {
1186 fprintf(stderr, "failed to read blocks for diff\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001187 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001188 }
1189
1190 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001191 params.foundwrites = true;
1192 } else if (params.foundwrites) {
1193 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001194 }
1195
Tao Bao0940fe12015-08-27 16:41:21 -07001196 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001197 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001198 fprintf(stderr, "patching %zu blocks to %zu\n", blocks, tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001199
Tao Bao0940fe12015-08-27 16:41:21 -07001200 Value patch_value;
Sami Tolvanen90221202014-12-09 16:39:47 +00001201 patch_value.type = VAL_BLOB;
1202 patch_value.size = len;
Tao Bao0940fe12015-08-27 16:41:21 -07001203 patch_value.data = (char*) (params.patch_start + offset);
Sami Tolvanen90221202014-12-09 16:39:47 +00001204
Tao Bao0940fe12015-08-27 16:41:21 -07001205 RangeSinkState rss(tgt);
1206 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001207 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001208 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001209
Tao Bao0940fe12015-08-27 16:41:21 -07001210 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1211 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001212 }
1213
Tao Bao0940fe12015-08-27 16:41:21 -07001214 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao612336d2015-08-27 16:41:21 -07001215 ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
Tao Bao0940fe12015-08-27 16:41:21 -07001216 &RangeSinkWrite, &rss, nullptr, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001217 } else {
Tao Bao612336d2015-08-27 16:41:21 -07001218 ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1219 &RangeSinkWrite, &rss, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001220 }
1221
1222 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001223 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001224 fprintf(stderr, "range sink underrun?\n");
1225 }
1226 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001227 fprintf(stderr, "skipping %zu blocks already patched to %zu [%s]\n",
Tao Baobaad2d42015-12-06 16:56:27 -08001228 blocks, tgt.size, params.cmdline);
Sami Tolvanen90221202014-12-09 16:39:47 +00001229 }
1230 }
1231
Tao Baobaad2d42015-12-06 16:56:27 -08001232 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001233 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001234 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001235 }
1236
Tao Bao0940fe12015-08-27 16:41:21 -07001237 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001238
Tao Bao0940fe12015-08-27 16:41:21 -07001239 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001240}
1241
Tao Bao0940fe12015-08-27 16:41:21 -07001242static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001243 if (DEBUG_ERASE) {
1244 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001245 }
1246
Tao Bao0940fe12015-08-27 16:41:21 -07001247 struct stat sb;
1248 if (fstat(params.fd, &sb) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001249 fprintf(stderr, "failed to fstat device to erase: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001250 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001251 }
1252
Tao Bao0940fe12015-08-27 16:41:21 -07001253 if (!S_ISBLK(sb.st_mode)) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001254 fprintf(stderr, "not a block device; skipping erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001255 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001256 }
1257
Tao Baobaad2d42015-12-06 16:56:27 -08001258 if (params.cpos >= params.tokens.size()) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001259 fprintf(stderr, "missing target blocks for erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001260 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001261 }
1262
Tao Bao0940fe12015-08-27 16:41:21 -07001263 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001264 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001265
Tao Bao0940fe12015-08-27 16:41:21 -07001266 if (params.canwrite) {
1267 fprintf(stderr, " erasing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001268
Tao Bao0940fe12015-08-27 16:41:21 -07001269 for (size_t i = 0; i < tgt.count; ++i) {
1270 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001271 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001272 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001273 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001274 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001275
Tao Bao0940fe12015-08-27 16:41:21 -07001276 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001277 fprintf(stderr, "BLKDISCARD ioctl failed: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001278 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001279 }
1280 }
1281 }
1282
Tao Bao0940fe12015-08-27 16:41:21 -07001283 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001284}
1285
1286// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001287typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001288
Tao Bao612336d2015-08-27 16:41:21 -07001289struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001290 const char* name;
1291 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001292};
Sami Tolvanen90221202014-12-09 16:39:47 +00001293
1294// CompareCommands and CompareCommandNames are for the hash table
1295
1296static int CompareCommands(const void* c1, const void* c2) {
1297 return strcmp(((const Command*) c1)->name, ((const Command*) c2)->name);
1298}
1299
1300static int CompareCommandNames(const void* c1, const void* c2) {
1301 return strcmp(((const Command*) c1)->name, (const char*) c2);
1302}
1303
1304// HashString is used to hash command names for the hash table
1305
1306static unsigned int HashString(const char *s) {
1307 unsigned int hash = 0;
1308 if (s) {
1309 while (*s) {
1310 hash = hash * 33 + *s++;
1311 }
1312 }
1313 return hash;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001314}
1315
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001316// args:
1317// - block device (or file) to modify in-place
1318// - transfer list (blob)
1319// - new data stream (filename within package.zip)
1320// - patch stream (filename within package.zip, must be uncompressed)
1321
Tao Bao0940fe12015-08-27 16:41:21 -07001322static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1323 const Command* commands, size_t cmdcount, bool dryrun) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001324 CommandParameters params;
Sami Tolvanen90221202014-12-09 16:39:47 +00001325 memset(&params, 0, sizeof(params));
1326 params.canwrite = !dryrun;
1327
1328 fprintf(stderr, "performing %s\n", dryrun ? "verification" : "update");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001329
Tao Bao612336d2015-08-27 16:41:21 -07001330 Value* blockdev_filename = nullptr;
1331 Value* transfer_list_value = nullptr;
1332 Value* new_data_fn = nullptr;
1333 Value* patch_data_fn = nullptr;
Doug Zongker1d5d6092014-08-21 10:47:24 -07001334 if (ReadValueArgs(state, argv, 4, &blockdev_filename, &transfer_list_value,
Sami Tolvanen90221202014-12-09 16:39:47 +00001335 &new_data_fn, &patch_data_fn) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001336 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001337 }
Tao Bao612336d2015-08-27 16:41:21 -07001338 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1339 FreeValue);
1340 std::unique_ptr<Value, decltype(&FreeValue)> transfer_list_value_holder(transfer_list_value,
1341 FreeValue);
1342 std::unique_ptr<Value, decltype(&FreeValue)> new_data_fn_holder(new_data_fn, FreeValue);
1343 std::unique_ptr<Value, decltype(&FreeValue)> patch_data_fn_holder(patch_data_fn, FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001344
1345 if (blockdev_filename->type != VAL_STRING) {
1346 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001347 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001348 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001349 if (transfer_list_value->type != VAL_BLOB) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001350 ErrorAbort(state, "transfer_list argument to %s must be blob", name);
Tao Bao612336d2015-08-27 16:41:21 -07001351 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001352 }
1353 if (new_data_fn->type != VAL_STRING) {
1354 ErrorAbort(state, "new_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001355 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001356 }
1357 if (patch_data_fn->type != VAL_STRING) {
1358 ErrorAbort(state, "patch_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001359 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001360 }
1361
Tao Bao612336d2015-08-27 16:41:21 -07001362 UpdaterInfo* ui = reinterpret_cast<UpdaterInfo*>(state->cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001363
Tao Bao0940fe12015-08-27 16:41:21 -07001364 if (ui == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001365 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001366 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001367
Tao Bao612336d2015-08-27 16:41:21 -07001368 FILE* cmd_pipe = ui->cmd_pipe;
1369 ZipArchive* za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001370
Tao Bao0940fe12015-08-27 16:41:21 -07001371 if (cmd_pipe == nullptr || za == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001372 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001373 }
1374
Tao Bao612336d2015-08-27 16:41:21 -07001375 const ZipEntry* patch_entry = mzFindZipEntry(za, patch_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001376 if (patch_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001377 fprintf(stderr, "%s(): no file \"%s\" in package", name, patch_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001378 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001379 }
1380
Sami Tolvanen90221202014-12-09 16:39:47 +00001381 params.patch_start = ui->package_zip_addr + mzGetZipEntryOffset(patch_entry);
Tao Bao612336d2015-08-27 16:41:21 -07001382 const ZipEntry* new_entry = mzFindZipEntry(za, new_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001383 if (new_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001384 fprintf(stderr, "%s(): no file \"%s\" in package", name, new_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001385 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001386 }
1387
Jed Estepa7b9a462015-12-15 16:04:53 -08001388 params.fd = TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data, O_RDWR));
Tao Bao612336d2015-08-27 16:41:21 -07001389 unique_fd fd_holder(params.fd);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001390
Sami Tolvanen90221202014-12-09 16:39:47 +00001391 if (params.fd == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001392 fprintf(stderr, "open \"%s\" failed: %s\n", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001393 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001394 }
1395
Sami Tolvanen90221202014-12-09 16:39:47 +00001396 if (params.canwrite) {
1397 params.nti.za = za;
1398 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001399
Tao Bao0940fe12015-08-27 16:41:21 -07001400 pthread_mutex_init(&params.nti.mu, nullptr);
1401 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001402 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001403 pthread_attr_init(&attr);
1404 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1405
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001406 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1407 if (error != 0) {
1408 fprintf(stderr, "pthread_create failed: %s\n", strerror(error));
Tao Bao612336d2015-08-27 16:41:21 -07001409 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001410 }
1411 }
1412
Tao Baobaad2d42015-12-06 16:56:27 -08001413 // Copy all the lines in transfer_list_value into std::string for
1414 // processing.
Tao Bao612336d2015-08-27 16:41:21 -07001415 const std::string transfer_list(transfer_list_value->data, transfer_list_value->size);
1416 std::vector<std::string> lines = android::base::Split(transfer_list, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001417 if (lines.size() < 2) {
1418 ErrorAbort(state, "too few lines in the transfer list [%zd]\n", lines.size());
1419 return StringValue(strdup(""));
1420 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001421
Sami Tolvanen90221202014-12-09 16:39:47 +00001422 // First line in transfer list is the version number
Tao Bao1fdec862015-10-21 14:57:44 -07001423 if (!android::base::ParseInt(lines[0].c_str(), &params.version, 1, 4)) {
Tao Bao612336d2015-08-27 16:41:21 -07001424 fprintf(stderr, "unexpected transfer list version [%s]\n", lines[0].c_str());
1425 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001426 }
1427
Sami Tolvanen90221202014-12-09 16:39:47 +00001428 fprintf(stderr, "blockimg version is %d\n", params.version);
1429
1430 // Second line in transfer list is the total number of blocks we expect to write
Tao Baob15fd222015-09-24 11:10:51 -07001431 int total_blocks;
1432 if (!android::base::ParseInt(lines[1].c_str(), &total_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001433 ErrorAbort(state, "unexpected block count [%s]\n", lines[1].c_str());
1434 return StringValue(strdup(""));
Tao Baob15fd222015-09-24 11:10:51 -07001435 }
1436
1437 if (total_blocks == 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001438 return StringValue(strdup("t"));
Sami Tolvanen90221202014-12-09 16:39:47 +00001439 }
1440
Tao Bao612336d2015-08-27 16:41:21 -07001441 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001442 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001443 if (lines.size() < 4) {
1444 ErrorAbort(state, "too few lines in the transfer list [%zu]\n", lines.size());
1445 return StringValue(strdup(""));
1446 }
1447
Sami Tolvanen90221202014-12-09 16:39:47 +00001448 // Third line is how many stash entries are needed simultaneously
Tao Bao612336d2015-08-27 16:41:21 -07001449 fprintf(stderr, "maximum stash entries %s\n", lines[2].c_str());
Doug Zongker52ae67d2014-09-08 12:22:09 -07001450
Sami Tolvanen90221202014-12-09 16:39:47 +00001451 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Baob15fd222015-09-24 11:10:51 -07001452 int stash_max_blocks;
1453 if (!android::base::ParseInt(lines[3].c_str(), &stash_max_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001454 ErrorAbort(state, "unexpected maximum stash blocks [%s]\n", lines[3].c_str());
1455 return StringValue(strdup(""));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001456 }
1457
Tao Baob15fd222015-09-24 11:10:51 -07001458 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001459 if (res == -1) {
1460 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001461 }
Tao Bao612336d2015-08-27 16:41:21 -07001462
Tao Baob15fd222015-09-24 11:10:51 -07001463 params.createdstash = res;
1464
Tao Bao612336d2015-08-27 16:41:21 -07001465 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001466 }
1467
Sami Tolvanen90221202014-12-09 16:39:47 +00001468 // Build a hash table of the available commands
Tao Bao612336d2015-08-27 16:41:21 -07001469 HashTable* cmdht = mzHashTableCreate(cmdcount, nullptr);
1470 std::unique_ptr<HashTable, decltype(&mzHashTableFree)> cmdht_holder(cmdht, mzHashTableFree);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001471
Tao Bao0940fe12015-08-27 16:41:21 -07001472 for (size_t i = 0; i < cmdcount; ++i) {
1473 unsigned int cmdhash = HashString(commands[i].name);
Sami Tolvanen90221202014-12-09 16:39:47 +00001474 mzHashTableLookup(cmdht, cmdhash, (void*) &commands[i], CompareCommands, true);
1475 }
1476
Tao Bao612336d2015-08-27 16:41:21 -07001477 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001478
Tao Bao612336d2015-08-27 16:41:21 -07001479 // Subsequent lines are all individual transfer commands
1480 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1481 const std::string& line_str(*it);
Tao Bao6a47dff2015-09-25 17:12:28 -07001482 if (line_str.empty()) {
1483 continue;
1484 }
1485
Tao Baobaad2d42015-12-06 16:56:27 -08001486 params.tokens = android::base::Split(line_str, " ");
1487 params.cpos = 0;
1488 params.cmdname = params.tokens[params.cpos++].c_str();
1489 params.cmdline = line_str.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001490
Tao Bao0940fe12015-08-27 16:41:21 -07001491 unsigned int cmdhash = HashString(params.cmdname);
Tao Bao612336d2015-08-27 16:41:21 -07001492 const Command* cmd = reinterpret_cast<const Command*>(mzHashTableLookup(cmdht, cmdhash,
Tao Baobaad2d42015-12-06 16:56:27 -08001493 const_cast<char*>(params.cmdname), CompareCommandNames,
1494 false));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001495
Tao Bao0940fe12015-08-27 16:41:21 -07001496 if (cmd == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001497 fprintf(stderr, "unexpected command [%s]\n", params.cmdname);
1498 goto pbiudone;
1499 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001500
Tao Bao0940fe12015-08-27 16:41:21 -07001501 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao612336d2015-08-27 16:41:21 -07001502 fprintf(stderr, "failed to execute command [%s]\n", line_str.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +00001503 goto pbiudone;
1504 }
1505
Sami Tolvanen90221202014-12-09 16:39:47 +00001506 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001507 if (ota_fsync(params.fd) == -1) {
Tao Bao187efff2015-07-27 14:07:08 -07001508 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
1509 goto pbiudone;
1510 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001511 fprintf(cmd_pipe, "set_progress %.4f\n", (double) params.written / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001512 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001513 }
1514 }
1515
Sami Tolvanen90221202014-12-09 16:39:47 +00001516 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001517 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001518
Tao Bao0940fe12015-08-27 16:41:21 -07001519 fprintf(stderr, "wrote %zu blocks; expected %d\n", params.written, total_blocks);
Tao Bao612336d2015-08-27 16:41:21 -07001520 fprintf(stderr, "max alloc needed was %zu\n", params.buffer.size());
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001521
Sami Tolvanen90221202014-12-09 16:39:47 +00001522 // Delete stash only after successfully completing the update, as it
1523 // may contain blocks needed to complete the update later.
1524 DeleteStash(params.stashbase);
1525 } else {
1526 fprintf(stderr, "verified partition contents; update may be resumed\n");
1527 }
1528
1529 rc = 0;
1530
1531pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001532 if (ota_fsync(params.fd) == -1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001533 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +00001534 }
Tao Baobaad2d42015-12-06 16:56:27 -08001535 // params.fd will be automatically closed because of the fd_holder above.
Sami Tolvanen90221202014-12-09 16:39:47 +00001536
Sami Tolvanen90221202014-12-09 16:39:47 +00001537 // Only delete the stash if the update cannot be resumed, or it's
1538 // a verification run and we created the stash.
1539 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1540 DeleteStash(params.stashbase);
1541 }
1542
Sami Tolvanen90221202014-12-09 16:39:47 +00001543 return StringValue(rc == 0 ? strdup("t") : strdup(""));
1544}
1545
1546// The transfer list is a text file containing commands to
1547// transfer data from one place to another on the target
1548// partition. We parse it and execute the commands in order:
1549//
1550// zero [rangeset]
1551// - fill the indicated blocks with zeros
1552//
1553// new [rangeset]
1554// - fill the blocks with data read from the new_data file
1555//
1556// erase [rangeset]
1557// - mark the given blocks as empty
1558//
1559// move <...>
1560// bsdiff <patchstart> <patchlen> <...>
1561// imgdiff <patchstart> <patchlen> <...>
1562// - read the source blocks, apply a patch (or not in the
1563// case of move), write result to target blocks. bsdiff or
1564// imgdiff specifies the type of patch; move means no patch
1565// at all.
1566//
1567// The format of <...> differs between versions 1 and 2;
1568// see the LoadSrcTgtVersion{1,2}() functions for a
1569// description of what's expected.
1570//
1571// stash <stash_id> <src_range>
1572// - (version 2+ only) load the given source range and stash
1573// the data in the given slot of the stash table.
1574//
Tao Baobaad2d42015-12-06 16:56:27 -08001575// free <stash_id>
1576// - (version 3+ only) free the given stash data.
1577//
Sami Tolvanen90221202014-12-09 16:39:47 +00001578// The creator of the transfer list will guarantee that no block
1579// is read (ie, used as the source for a patch or move) after it
1580// has been written.
1581//
1582// In version 2, the creator will guarantee that a given stash is
1583// loaded (with a stash command) before it's used in a
1584// move/bsdiff/imgdiff command.
1585//
1586// Within one command the source and target ranges may overlap so
1587// in general we need to read the entire source into memory before
1588// writing anything to the target blocks.
1589//
1590// All the patch data is concatenated into one patch_data file in
1591// the update package. It must be stored uncompressed because we
1592// memory-map it in directly from the archive. (Since patches are
1593// already compressed, we lose very little by not compressing
1594// their concatenation.)
1595//
1596// In version 3, commands that read data from the partition (i.e.
1597// move/bsdiff/imgdiff/stash) have one or more additional hashes
1598// before the range parameters, which are used to check if the
1599// command has already been completed and verify the integrity of
1600// the source data.
1601
1602Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001603 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001604 const Command commands[] = {
1605 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001606 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001607 { "free", PerformCommandFree },
1608 { "imgdiff", PerformCommandDiff },
1609 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001610 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001611 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001612 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001613 };
1614
1615 // Perform a dry run without writing to test if an update can proceed
1616 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001617 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001618}
1619
1620Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1621 const Command commands[] = {
1622 { "bsdiff", PerformCommandDiff },
1623 { "erase", PerformCommandErase },
1624 { "free", PerformCommandFree },
1625 { "imgdiff", PerformCommandDiff },
1626 { "move", PerformCommandMove },
1627 { "new", PerformCommandNew },
1628 { "stash", PerformCommandStash },
1629 { "zero", PerformCommandZero }
1630 };
1631
1632 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001633 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001634}
1635
Tao Bao0940fe12015-08-27 16:41:21 -07001636Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001637 Value* blockdev_filename;
1638 Value* ranges;
Tao Bao0940fe12015-08-27 16:41:21 -07001639
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001640 if (ReadValueArgs(state, argv, 2, &blockdev_filename, &ranges) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001641 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001642 }
Tao Bao612336d2015-08-27 16:41:21 -07001643 std::unique_ptr<Value, decltype(&FreeValue)> ranges_holder(ranges, FreeValue);
1644 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1645 FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001646
1647 if (blockdev_filename->type != VAL_STRING) {
1648 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001649 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001650 }
1651 if (ranges->type != VAL_STRING) {
1652 ErrorAbort(state, "ranges argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001653 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001654 }
1655
Jed Estepa7b9a462015-12-15 16:04:53 -08001656 int fd = ota_open(blockdev_filename->data, O_RDWR);
Tao Bao612336d2015-08-27 16:41:21 -07001657 unique_fd fd_holder(fd);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001658 if (fd < 0) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001659 ErrorAbort(state, "open \"%s\" failed: %s", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001660 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001661 }
1662
Tao Bao612336d2015-08-27 16:41:21 -07001663 RangeSet rs;
Tao Bao0940fe12015-08-27 16:41:21 -07001664 parse_range(ranges->data, rs);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001665
1666 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001667 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001668
Tao Bao612336d2015-08-27 16:41:21 -07001669 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001670 for (size_t i = 0; i < rs.count; ++i) {
1671 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tao Bao612336d2015-08-27 16:41:21 -07001672 ErrorAbort(state, "failed to seek %s: %s", blockdev_filename->data, strerror(errno));
1673 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001674 }
1675
Tao Bao0940fe12015-08-27 16:41:21 -07001676 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001677 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1678 ErrorAbort(state, "failed to read %s: %s", blockdev_filename->data,
Tao Bao0940fe12015-08-27 16:41:21 -07001679 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001680 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001681 }
1682
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001683 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001684 }
1685 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001686 uint8_t digest[SHA_DIGEST_LENGTH];
1687 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001688
Tao Bao612336d2015-08-27 16:41:21 -07001689 return StringValue(strdup(print_sha1(digest).c_str()));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001690}
1691
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001692// This function checks if a device has been remounted R/W prior to an incremental
1693// OTA update. This is an common cause of update abortion. The function reads the
1694// 1st block of each partition and check for mounting time/count. It return string "t"
1695// if executes successfully and an empty string otherwise.
1696
1697Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
1698 Value* arg_filename;
1699
1700 if (ReadValueArgs(state, argv, 1, &arg_filename) < 0) {
1701 return nullptr;
1702 }
1703 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1704
1705 if (filename->type != VAL_STRING) {
1706 ErrorAbort(state, "filename argument to %s must be string", name);
1707 return StringValue(strdup(""));
1708 }
1709
Jed Estepa7b9a462015-12-15 16:04:53 -08001710 int fd = ota_open(arg_filename->data, O_RDONLY);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001711 unique_fd fd_holder(fd);
1712 if (fd == -1) {
1713 ErrorAbort(state, "open \"%s\" failed: %s", arg_filename->data, strerror(errno));
1714 return StringValue(strdup(""));
1715 }
1716
1717 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1718 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1719
1720 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
1721 ErrorAbort(state, "failed to read %s: %s", arg_filename->data,
1722 strerror(errno));
1723 return StringValue(strdup(""));
1724 }
1725
1726 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1727 // Super block starts from block 0, offset 0x400
1728 // 0x2C: len32 Mount time
1729 // 0x30: len32 Write time
1730 // 0x34: len16 Number of mounts since the last fsck
1731 // 0x38: len16 Magic signature 0xEF53
1732
1733 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1734 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1735
1736 if (mount_count > 0) {
1737 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1738 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1739 }
1740
1741 return StringValue(strdup("t"));
1742}
1743
1744
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001745Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
1746 Value* arg_filename;
1747 Value* arg_ranges;
1748
1749 if (ReadValueArgs(state, argv, 2, &arg_filename, &arg_ranges) < 0) {
1750 return NULL;
1751 }
1752
1753 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1754 std::unique_ptr<Value, decltype(&FreeValue)> ranges(arg_ranges, FreeValue);
1755
1756 if (filename->type != VAL_STRING) {
1757 ErrorAbort(state, "filename argument to %s must be string", name);
1758 return StringValue(strdup(""));
1759 }
1760 if (ranges->type != VAL_STRING) {
1761 ErrorAbort(state, "ranges argument to %s must be string", name);
1762 return StringValue(strdup(""));
1763 }
1764
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001765 // Output notice to log when recover is attempted
1766 fprintf(stderr, "%s image corrupted, attempting to recover...\n", filename->data);
1767
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001768 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
1769 fec::io fh(filename->data, O_RDWR);
1770
1771 if (!fh) {
1772 ErrorAbort(state, "fec_open \"%s\" failed: %s", filename->data, strerror(errno));
1773 return StringValue(strdup(""));
1774 }
1775
1776 if (!fh.has_ecc() || !fh.has_verity()) {
1777 ErrorAbort(state, "unable to use metadata to correct errors");
1778 return StringValue(strdup(""));
1779 }
1780
1781 fec_status status;
1782
1783 if (!fh.get_status(status)) {
1784 ErrorAbort(state, "failed to read FEC status");
1785 return StringValue(strdup(""));
1786 }
1787
1788 RangeSet rs;
1789 parse_range(ranges->data, rs);
1790
1791 uint8_t buffer[BLOCKSIZE];
1792
1793 for (size_t i = 0; i < rs.count; ++i) {
1794 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1795 // Stay within the data area, libfec validates and corrects metadata
1796 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1797 continue;
1798 }
1799
1800 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tao Baobaad2d42015-12-06 16:56:27 -08001801 ErrorAbort(state, "failed to recover %s (block %zu): %s", filename->data,
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001802 j, strerror(errno));
1803 return StringValue(strdup(""));
1804 }
1805
1806 // If we want to be able to recover from a situation where rewriting a corrected
1807 // block doesn't guarantee the same data will be returned when re-read later, we
1808 // can save a copy of corrected blocks to /cache. Note:
1809 //
1810 // 1. Maximum space required from /cache is the same as the maximum number of
1811 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1812 // this would be ~16 MiB, for example.
1813 //
1814 // 2. To find out if this block was corrupted, call fec_get_status after each
1815 // read and check if the errors field value has increased.
1816 }
1817 }
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001818 fprintf(stderr, "...%s image recovered successfully.\n", filename->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001819 return StringValue(strdup("t"));
1820}
1821
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001822void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001823 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001824 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001825 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001826 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001827 RegisterFunction("range_sha1", RangeSha1Fn);
1828}