blob: 908e11631eaf83680f73044adf74ac1686393a7e [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
18#include <errno.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000019#include <dirent.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
21#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000028#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070029#include <sys/types.h>
30#include <sys/wait.h>
31#include <sys/ioctl.h>
32#include <time.h>
33#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010034#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070035
Tianjie Xu7eca97e2016-03-22 18:08:12 -070036#include <map>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tao Bao0940fe12015-08-27 16:41:21 -070039#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070040
Elliott Hughes4b166f02015-12-04 15:30:20 -080041#include <android-base/parseint.h>
42#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070043#include <android-base/unique_fd.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070044
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070045#include "applypatch/applypatch.h"
46#include "edify/expr.h"
Tianjie Xu57bed6d2015-12-15 11:47:30 -080047#include "install.h"
Sen Jiangc48cb5e2016-02-04 16:23:21 +080048#include "openssl/sha.h"
Sami Tolvanen90221202014-12-09 16:39:47 +000049#include "minzip/Hash.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080050#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070051#include "print_sha1.h"
Tao Bao0940fe12015-08-27 16:41:21 -070052#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;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700371 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800372 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
Elliott Hughesbcabd092016-03-22 20:19:22 -0700580 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000581 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700582 fprintf(stderr, "open \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700583 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000584 }
585
Tao Bao612336d2015-08-27 16:41:21 -0700586 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000587
Tao Bao612336d2015-08-27 16:41:21 -0700588 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700589 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000590 }
591
Tao Bao0940fe12015-08-27 16:41:21 -0700592 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000593
Tao Bao612336d2015-08-27 16:41:21 -0700594 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700595 fprintf(stderr, "unexpected contents in %s\n", fn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700596 DeleteFile(fn, nullptr);
597 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000598 }
599
Tao Bao0940fe12015-08-27 16:41:21 -0700600 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000601}
602
Tao Bao612336d2015-08-27 16:41:21 -0700603static int WriteStash(const std::string& base, const std::string& id, int blocks,
604 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
605 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700606 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000607 }
608
609 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
610 fprintf(stderr, "not enough space to write stash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700611 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000612 }
613
Tao Bao0940fe12015-08-27 16:41:21 -0700614 std::string fn = GetStashFileName(base, id, ".partial");
615 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000616
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100617 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700618 struct stat sb;
619 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100620
621 if (res == 0) {
622 // The file already exists and since the name is the hash of the contents,
623 // it's safe to assume the contents are identical (accidental hash collisions
624 // are unlikely)
Tao Baoe6aa3322015-08-05 15:20:27 -0700625 fprintf(stderr, " skipping %d existing blocks in %s\n", blocks, cn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700626 *exists = true;
627 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100628 }
629
Tao Bao0940fe12015-08-27 16:41:21 -0700630 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100631 }
632
Tao Baoe6aa3322015-08-05 15:20:27 -0700633 fprintf(stderr, " writing %d blocks to %s\n", blocks, cn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000634
Elliott Hughesbcabd092016-03-22 20:19:22 -0700635 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(),
636 O_WRONLY | O_CREAT | O_TRUNC,
637 STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000638 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700639 fprintf(stderr, "failed to create \"%s\": %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700640 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000641 }
642
643 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700644 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000645 }
646
Jed Estepa7b9a462015-12-15 16:04:53 -0800647 if (ota_fsync(fd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700648 fprintf(stderr, "fsync \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700649 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000650 }
651
Tao Baoe6aa3322015-08-05 15:20:27 -0700652 if (rename(fn.c_str(), cn.c_str()) == -1) {
653 fprintf(stderr, "rename(\"%s\", \"%s\") failed: %s\n", fn.c_str(), cn.c_str(),
654 strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700655 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000656 }
657
Tao Bao0940fe12015-08-27 16:41:21 -0700658 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700659 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
660 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700661 if (dfd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700662 fprintf(stderr, "failed to open \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700663 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700664 }
665
Jed Estepa7b9a462015-12-15 16:04:53 -0800666 if (ota_fsync(dfd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700667 fprintf(stderr, "fsync \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700668 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700669 }
670
Tao Bao0940fe12015-08-27 16:41:21 -0700671 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000672}
673
674// Creates a directory for storing stash files and checks if the /cache partition
675// hash enough space for the expected amount of blocks we need to store. Returns
676// >0 if we created the directory, zero if it existed already, and <0 of failure.
677
Tao Bao0940fe12015-08-27 16:41:21 -0700678static int CreateStash(State* state, int maxblocks, const char* blockdev, std::string& base) {
679 if (blockdev == nullptr) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700680 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000681 }
682
683 // Stash directory should be different for each partition to avoid conflicts
684 // when updating multiple partitions at the same time, so we use the hash of
685 // the block device name as the base directory
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800686 uint8_t digest[SHA_DIGEST_LENGTH];
687 SHA1(reinterpret_cast<const uint8_t*>(blockdev), strlen(blockdev), digest);
Tao Baoe6aa3322015-08-05 15:20:27 -0700688 base = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000689
Tao Baoe6aa3322015-08-05 15:20:27 -0700690 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700691 struct stat sb;
692 int res = stat(dirname.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000693
694 if (res == -1 && errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700695 ErrorAbort(state, "stat \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
696 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000697 } else if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700698 fprintf(stderr, "creating stash %s\n", dirname.c_str());
699 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000700
701 if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700702 ErrorAbort(state, "mkdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
703 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000704 }
705
706 if (CacheSizeCheck(maxblocks * BLOCKSIZE) != 0) {
707 ErrorAbort(state, "not enough space for stash\n");
Tao Baoe6aa3322015-08-05 15:20:27 -0700708 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000709 }
710
Tao Baoe6aa3322015-08-05 15:20:27 -0700711 return 1; // Created directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000712 }
713
Tao Baoe6aa3322015-08-05 15:20:27 -0700714 fprintf(stderr, "using existing stash %s\n", dirname.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000715
716 // If the directory already exists, calculate the space already allocated to
717 // stash files and check if there's enough for all required blocks. Delete any
718 // partially completed stash files first.
719
Tao Bao0940fe12015-08-27 16:41:21 -0700720 EnumerateStash(dirname, DeletePartial, nullptr);
Tao Baoe6aa3322015-08-05 15:20:27 -0700721 int size = 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000722 EnumerateStash(dirname, UpdateFileSize, &size);
723
Tao Bao0940fe12015-08-27 16:41:21 -0700724 size = maxblocks * BLOCKSIZE - size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000725
726 if (size > 0 && CacheSizeCheck(size) != 0) {
727 ErrorAbort(state, "not enough space for stash (%d more needed)\n", size);
Tao Baoe6aa3322015-08-05 15:20:27 -0700728 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000729 }
730
Tao Baoe6aa3322015-08-05 15:20:27 -0700731 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000732}
733
Tao Baobaad2d42015-12-06 16:56:27 -0800734static int SaveStash(CommandParameters& params, const std::string& base,
735 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000736
Tao Baobaad2d42015-12-06 16:56:27 -0800737 // <stash_id> <src_range>
738 if (params.cpos + 1 >= params.tokens.size()) {
739 fprintf(stderr, "missing id and/or src range fields in stash command\n");
Sami Tolvanen90221202014-12-09 16:39:47 +0000740 return -1;
741 }
Tao Baobaad2d42015-12-06 16:56:27 -0800742 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000743
Tao Bao0940fe12015-08-27 16:41:21 -0700744 size_t blocks = 0;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700745 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000746 // Stash file already exists and has expected contents. Do not
747 // read from source again, as the source may have been already
748 // overwritten during a previous attempt.
749 return 0;
750 }
751
Tao Bao34847b22015-09-08 11:05:49 -0700752 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800753 parse_range(params.tokens[params.cpos++], src);
Tao Bao34847b22015-09-08 11:05:49 -0700754
Tao Bao612336d2015-08-27 16:41:21 -0700755 allocate(src.size * BLOCKSIZE, buffer);
756 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000757 return -1;
758 }
Tao Bao34847b22015-09-08 11:05:49 -0700759 blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000760
Tao Bao612336d2015-08-27 16:41:21 -0700761 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000762 // Source blocks have unexpected contents. If we actually need this
763 // data later, this is an unrecoverable error. However, the command
764 // that uses the data may have already completed previously, so the
765 // possible failure will occur during source block verification.
Tao Bao0940fe12015-08-27 16:41:21 -0700766 fprintf(stderr, "failed to load source blocks for stash %s\n", id.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000767 return 0;
768 }
769
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700770 // In verify mode, save source range_set instead of stashing blocks.
771 if (!params.canwrite && usehash) {
772 stash_map[id] = src;
773 return 0;
774 }
775
Tao Bao0940fe12015-08-27 16:41:21 -0700776 fprintf(stderr, "stashing %zu blocks to %s\n", blocks, id.c_str());
Tao Bao612336d2015-08-27 16:41:21 -0700777 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000778}
779
Tao Baobaad2d42015-12-06 16:56:27 -0800780static int FreeStash(const std::string& base, const std::string& id) {
781 if (base.empty() || id.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000782 return -1;
783 }
784
Tao Baobaad2d42015-12-06 16:56:27 -0800785 std::string fn = GetStashFileName(base, id, "");
Tao Bao0940fe12015-08-27 16:41:21 -0700786 DeleteFile(fn, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000787
788 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700789}
790
Tao Bao612336d2015-08-27 16:41:21 -0700791static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
792 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700793 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700794 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700795 // may be the same buffer.
796
Tao Bao612336d2015-08-27 16:41:21 -0700797 const uint8_t* from = source.data();
798 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700799 size_t start = locs.size;
800 for (int i = locs.count-1; i >= 0; --i) {
801 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700802 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700803 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700804 blocks * BLOCKSIZE);
805 }
806}
807
808// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800809// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700810//
811// <tgt_range> <src_block_count> <src_range>
812// (loads data from source image only)
813//
814// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
815// (loads data from stashes only)
816//
817// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
818// (loads data from both source image and stashes)
819//
820// On return, buffer is filled with the loaded source data (rearranged
821// and combined with stashed data as necessary). buffer may be
822// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000823// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700824
Tao Baobaad2d42015-12-06 16:56:27 -0800825static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700826 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800827
828 // At least it needs to provide three parameters: <tgt_range>,
829 // <src_block_count> and "-"/<src_range>.
830 if (params.cpos + 2 >= params.tokens.size()) {
831 fprintf(stderr, "invalid parameters\n");
832 return -1;
833 }
834
Tao Bao612336d2015-08-27 16:41:21 -0700835 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800836 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700837
Tao Bao612336d2015-08-27 16:41:21 -0700838 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800839 const std::string& token = params.tokens[params.cpos++];
840 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
841 fprintf(stderr, "invalid src_block_count \"%s\"\n", token.c_str());
842 return -1;
843 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700844
Tao Bao612336d2015-08-27 16:41:21 -0700845 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700846
Tao Bao612336d2015-08-27 16:41:21 -0700847 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800848 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700849 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800850 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700851 } else {
Tao Bao0940fe12015-08-27 16:41:21 -0700852 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800853 parse_range(params.tokens[params.cpos++], src);
Tao Bao612336d2015-08-27 16:41:21 -0700854 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700855
Tao Bao34847b22015-09-08 11:05:49 -0700856 if (overlap) {
857 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700858 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000859
Sami Tolvanen90221202014-12-09 16:39:47 +0000860 if (res == -1) {
861 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700862 }
863
Tao Baobaad2d42015-12-06 16:56:27 -0800864 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000865 // no stashes, only source range
866 return 0;
867 }
868
Tao Bao612336d2015-08-27 16:41:21 -0700869 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800870 parse_range(params.tokens[params.cpos++], locs);
Tao Bao612336d2015-08-27 16:41:21 -0700871 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700872 }
873
Tao Baobaad2d42015-12-06 16:56:27 -0800874 // <[stash_id:stash_range]>
875 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700876 // Each word is a an index into the stash table, a colon, and
877 // then a rangeset describing where in the source block that
878 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800879 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
880 if (tokens.size() != 2) {
881 fprintf(stderr, "invalid parameter\n");
882 return -1;
883 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000884
Tao Bao612336d2015-08-27 16:41:21 -0700885 std::vector<uint8_t> stash;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700886 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000887
888 if (res == -1) {
889 // These source blocks will fail verification if used later, but we
890 // will let the caller decide if this is a fatal failure
Tao Baobaad2d42015-12-06 16:56:27 -0800891 fprintf(stderr, "failed to load stash %s\n", tokens[0].c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000892 continue;
893 }
894
Tao Bao612336d2015-08-27 16:41:21 -0700895 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800896 parse_range(tokens[1], locs);
Sami Tolvanen90221202014-12-09 16:39:47 +0000897
Tao Bao612336d2015-08-27 16:41:21 -0700898 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000899 }
900
901 return 0;
902}
903
Sami Tolvanen90221202014-12-09 16:39:47 +0000904// Do a source/target load for move/bsdiff/imgdiff in version 3.
905//
906// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
907// tells the function whether to expect separate source and targe block hashes, or
908// if they are both the same and only one hash should be expected, and
909// 'isunresumable', which receives a non-zero value if block verification fails in
910// a way that the update cannot be resumed anymore.
911//
912// If the function is unable to load the necessary blocks or their contents don't
913// match the hashes, the return value is -1 and the command should be aborted.
914//
915// If the return value is 1, the command has already been completed according to
916// the contents of the target blocks, and should not be performed again.
917//
918// If the return value is 0, source blocks have expected content and the command
919// can be performed.
920
Tao Bao34847b22015-09-08 11:05:49 -0700921static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -0700922 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000923
Tao Baobaad2d42015-12-06 16:56:27 -0800924 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000925 fprintf(stderr, "missing source hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700926 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000927 }
928
Tao Baobaad2d42015-12-06 16:56:27 -0800929 std::string srchash = params.tokens[params.cpos++];
930 std::string tgthash;
931
Sami Tolvanen90221202014-12-09 16:39:47 +0000932 if (onehash) {
933 tgthash = srchash;
934 } else {
Tao Baobaad2d42015-12-06 16:56:27 -0800935 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000936 fprintf(stderr, "missing target hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700937 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000938 }
Tao Baobaad2d42015-12-06 16:56:27 -0800939 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000940 }
941
Elliott Hughesbcabd092016-03-22 20:19:22 -0700942 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd,
943 params.stashbase, &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700944 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000945 }
946
Tao Bao34847b22015-09-08 11:05:49 -0700947 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000948
Tao Bao612336d2015-08-27 16:41:21 -0700949 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700950 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000951 }
952
Tao Bao612336d2015-08-27 16:41:21 -0700953 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000954 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -0700955 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000956 }
957
Tao Bao0940fe12015-08-27 16:41:21 -0700958 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000959 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700960 // resume from possible write errors. In verify mode, we can skip stashing
961 // because the source blocks won't be overwritten.
962 if (overlap && params.canwrite) {
Tao Baobaad2d42015-12-06 16:56:27 -0800963 fprintf(stderr, "stashing %zu overlapping blocks to %s\n", src_blocks,
964 srchash.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000965
Tao Bao0940fe12015-08-27 16:41:21 -0700966 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -0700967 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -0700968 &stash_exists) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000969 fprintf(stderr, "failed to stash overlapping source blocks\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700970 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000971 }
972
973 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100974 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700975 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100976 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000977 }
978
979 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -0700980 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000981 }
982
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700983 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
984 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100985 // Overlapping source blocks were previously stashed, command can proceed.
986 // We are recovering from an interrupted command, so we don't know if the
987 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -0700988 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000989 }
990
991 // Valid source data not available, update cannot be resumed
992 fprintf(stderr, "partition has unexpected contents\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700993 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +0000994
Tao Bao0940fe12015-08-27 16:41:21 -0700995 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000996}
997
Tao Bao0940fe12015-08-27 16:41:21 -0700998static int PerformCommandMove(CommandParameters& params) {
999 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001000 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001001 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001002 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001003
Tao Bao0940fe12015-08-27 16:41:21 -07001004 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001005 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001006 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001007 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001008 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001009 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001010 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001011 }
1012
1013 if (status == -1) {
1014 fprintf(stderr, "failed to read blocks for move\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001015 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001016 }
1017
1018 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001019 params.foundwrites = true;
1020 } else if (params.foundwrites) {
1021 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001022 }
1023
Tao Bao0940fe12015-08-27 16:41:21 -07001024 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001025 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001026 fprintf(stderr, " moving %zu blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001027
Tao Bao0940fe12015-08-27 16:41:21 -07001028 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1029 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001030 }
1031 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001032 fprintf(stderr, "skipping %zu already moved blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001033 }
1034
1035 }
1036
Tao Baobaad2d42015-12-06 16:56:27 -08001037 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001038 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001039 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001040 }
1041
Tao Bao0940fe12015-08-27 16:41:21 -07001042 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001043
Tao Bao0940fe12015-08-27 16:41:21 -07001044 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001045}
1046
Tao Bao0940fe12015-08-27 16:41:21 -07001047static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001048 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001049 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001050}
1051
Tao Bao0940fe12015-08-27 16:41:21 -07001052static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001053 // <stash_id>
1054 if (params.cpos >= params.tokens.size()) {
1055 fprintf(stderr, "missing stash id in free command\n");
1056 return -1;
1057 }
1058
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001059 const std::string& id = params.tokens[params.cpos++];
1060
1061 if (!params.canwrite && stash_map.find(id) != stash_map.end()) {
1062 stash_map.erase(id);
1063 return 0;
1064 }
1065
Tao Bao0940fe12015-08-27 16:41:21 -07001066 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001067 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001068 }
1069
1070 return 0;
1071}
1072
Tao Bao0940fe12015-08-27 16:41:21 -07001073static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001074
Tao Baobaad2d42015-12-06 16:56:27 -08001075 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001076 fprintf(stderr, "missing target blocks for zero\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001077 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001078 }
1079
Tao Bao0940fe12015-08-27 16:41:21 -07001080 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001081 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001082
Tao Bao0940fe12015-08-27 16:41:21 -07001083 fprintf(stderr, " zeroing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001084
Tao Bao612336d2015-08-27 16:41:21 -07001085 allocate(BLOCKSIZE, params.buffer);
1086 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001087
Tao Bao0940fe12015-08-27 16:41:21 -07001088 if (params.canwrite) {
1089 for (size_t i = 0; i < tgt.count; ++i) {
1090 if (!check_lseek(params.fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
1091 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001092 }
1093
Tao Bao0940fe12015-08-27 16:41:21 -07001094 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1095 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1096 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001097 }
1098 }
1099 }
1100 }
1101
Tao Bao0940fe12015-08-27 16:41:21 -07001102 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001103 // Update only for the zero command, as the erase command will call
1104 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001105 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001106 }
1107
Tao Bao0940fe12015-08-27 16:41:21 -07001108 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001109}
1110
Tao Bao0940fe12015-08-27 16:41:21 -07001111static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001112
Tao Baobaad2d42015-12-06 16:56:27 -08001113 if (params.cpos >= params.tokens.size()) {
1114 fprintf(stderr, "missing target blocks for new\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001115 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001116 }
1117
Tao Bao0940fe12015-08-27 16:41:21 -07001118 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001119 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001120
Tao Bao0940fe12015-08-27 16:41:21 -07001121 if (params.canwrite) {
1122 fprintf(stderr, " writing %zu blocks of new data\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001123
Tao Bao0940fe12015-08-27 16:41:21 -07001124 RangeSinkState rss(tgt);
1125 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001126 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001127 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001128
Tao Bao0940fe12015-08-27 16:41:21 -07001129 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1130 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001131 }
1132
Tao Bao0940fe12015-08-27 16:41:21 -07001133 pthread_mutex_lock(&params.nti.mu);
1134 params.nti.rss = &rss;
1135 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001136
Tao Bao0940fe12015-08-27 16:41:21 -07001137 while (params.nti.rss) {
1138 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001139 }
1140
Tao Bao0940fe12015-08-27 16:41:21 -07001141 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001142 }
1143
Tao Bao0940fe12015-08-27 16:41:21 -07001144 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001145
Tao Bao0940fe12015-08-27 16:41:21 -07001146 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001147}
1148
Tao Bao0940fe12015-08-27 16:41:21 -07001149static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001150
Tao Baobaad2d42015-12-06 16:56:27 -08001151 // <offset> <length>
1152 if (params.cpos + 1 >= params.tokens.size()) {
1153 fprintf(stderr, "missing patch offset or length for %s\n", params.cmdname);
Tao Bao0940fe12015-08-27 16:41:21 -07001154 return -1;
1155 }
1156
Tao Baobaad2d42015-12-06 16:56:27 -08001157 size_t offset;
1158 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
1159 fprintf(stderr, "invalid patch offset\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001160 return -1;
1161 }
1162
Tao Baobaad2d42015-12-06 16:56:27 -08001163 size_t len;
1164 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
1165 fprintf(stderr, "invalid patch offset\n");
1166 return -1;
1167 }
Tao Bao0940fe12015-08-27 16:41:21 -07001168
Tao Bao612336d2015-08-27 16:41:21 -07001169 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001170 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001171 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001172 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001173 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001174 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001175 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001176 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001177 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001178 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001179 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001180 }
1181
1182 if (status == -1) {
1183 fprintf(stderr, "failed to read blocks for diff\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001184 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001185 }
1186
1187 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001188 params.foundwrites = true;
1189 } else if (params.foundwrites) {
1190 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001191 }
1192
Tao Bao0940fe12015-08-27 16:41:21 -07001193 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001194 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001195 fprintf(stderr, "patching %zu blocks to %zu\n", blocks, tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001196
Tao Bao0940fe12015-08-27 16:41:21 -07001197 Value patch_value;
Sami Tolvanen90221202014-12-09 16:39:47 +00001198 patch_value.type = VAL_BLOB;
1199 patch_value.size = len;
Tao Bao0940fe12015-08-27 16:41:21 -07001200 patch_value.data = (char*) (params.patch_start + offset);
Sami Tolvanen90221202014-12-09 16:39:47 +00001201
Tao Bao0940fe12015-08-27 16:41:21 -07001202 RangeSinkState rss(tgt);
1203 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001204 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001205 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001206
Tao Bao0940fe12015-08-27 16:41:21 -07001207 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1208 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001209 }
1210
Tao Bao0940fe12015-08-27 16:41:21 -07001211 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao612336d2015-08-27 16:41:21 -07001212 ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
Tao Bao0940fe12015-08-27 16:41:21 -07001213 &RangeSinkWrite, &rss, nullptr, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001214 } else {
Tao Bao612336d2015-08-27 16:41:21 -07001215 ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1216 &RangeSinkWrite, &rss, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001217 }
1218
1219 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001220 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001221 fprintf(stderr, "range sink underrun?\n");
1222 }
1223 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001224 fprintf(stderr, "skipping %zu blocks already patched to %zu [%s]\n",
Tao Baobaad2d42015-12-06 16:56:27 -08001225 blocks, tgt.size, params.cmdline);
Sami Tolvanen90221202014-12-09 16:39:47 +00001226 }
1227 }
1228
Tao Baobaad2d42015-12-06 16:56:27 -08001229 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001230 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001231 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001232 }
1233
Tao Bao0940fe12015-08-27 16:41:21 -07001234 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001235
Tao Bao0940fe12015-08-27 16:41:21 -07001236 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001237}
1238
Tao Bao0940fe12015-08-27 16:41:21 -07001239static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001240 if (DEBUG_ERASE) {
1241 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001242 }
1243
Tao Bao0940fe12015-08-27 16:41:21 -07001244 struct stat sb;
1245 if (fstat(params.fd, &sb) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001246 fprintf(stderr, "failed to fstat device to erase: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001247 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001248 }
1249
Tao Bao0940fe12015-08-27 16:41:21 -07001250 if (!S_ISBLK(sb.st_mode)) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001251 fprintf(stderr, "not a block device; skipping erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001252 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001253 }
1254
Tao Baobaad2d42015-12-06 16:56:27 -08001255 if (params.cpos >= params.tokens.size()) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001256 fprintf(stderr, "missing target blocks for erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001257 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001258 }
1259
Tao Bao0940fe12015-08-27 16:41:21 -07001260 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001261 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001262
Tao Bao0940fe12015-08-27 16:41:21 -07001263 if (params.canwrite) {
1264 fprintf(stderr, " erasing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001265
Tao Bao0940fe12015-08-27 16:41:21 -07001266 for (size_t i = 0; i < tgt.count; ++i) {
1267 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001268 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001269 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001270 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001271 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001272
Tao Bao0940fe12015-08-27 16:41:21 -07001273 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001274 fprintf(stderr, "BLKDISCARD ioctl failed: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001275 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001276 }
1277 }
1278 }
1279
Tao Bao0940fe12015-08-27 16:41:21 -07001280 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001281}
1282
1283// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001284typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001285
Tao Bao612336d2015-08-27 16:41:21 -07001286struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001287 const char* name;
1288 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001289};
Sami Tolvanen90221202014-12-09 16:39:47 +00001290
1291// CompareCommands and CompareCommandNames are for the hash table
1292
1293static int CompareCommands(const void* c1, const void* c2) {
1294 return strcmp(((const Command*) c1)->name, ((const Command*) c2)->name);
1295}
1296
1297static int CompareCommandNames(const void* c1, const void* c2) {
1298 return strcmp(((const Command*) c1)->name, (const char*) c2);
1299}
1300
1301// HashString is used to hash command names for the hash table
1302
1303static unsigned int HashString(const char *s) {
1304 unsigned int hash = 0;
1305 if (s) {
1306 while (*s) {
1307 hash = hash * 33 + *s++;
1308 }
1309 }
1310 return hash;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001311}
1312
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001313// args:
1314// - block device (or file) to modify in-place
1315// - transfer list (blob)
1316// - new data stream (filename within package.zip)
1317// - patch stream (filename within package.zip, must be uncompressed)
1318
Tao Bao0940fe12015-08-27 16:41:21 -07001319static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1320 const Command* commands, size_t cmdcount, bool dryrun) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001321 CommandParameters params;
Sami Tolvanen90221202014-12-09 16:39:47 +00001322 memset(&params, 0, sizeof(params));
1323 params.canwrite = !dryrun;
1324
1325 fprintf(stderr, "performing %s\n", dryrun ? "verification" : "update");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001326
Tao Bao612336d2015-08-27 16:41:21 -07001327 Value* blockdev_filename = nullptr;
1328 Value* transfer_list_value = nullptr;
1329 Value* new_data_fn = nullptr;
1330 Value* patch_data_fn = nullptr;
Doug Zongker1d5d6092014-08-21 10:47:24 -07001331 if (ReadValueArgs(state, argv, 4, &blockdev_filename, &transfer_list_value,
Sami Tolvanen90221202014-12-09 16:39:47 +00001332 &new_data_fn, &patch_data_fn) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001333 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001334 }
Tao Bao612336d2015-08-27 16:41:21 -07001335 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1336 FreeValue);
1337 std::unique_ptr<Value, decltype(&FreeValue)> transfer_list_value_holder(transfer_list_value,
1338 FreeValue);
1339 std::unique_ptr<Value, decltype(&FreeValue)> new_data_fn_holder(new_data_fn, FreeValue);
1340 std::unique_ptr<Value, decltype(&FreeValue)> patch_data_fn_holder(patch_data_fn, FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001341
1342 if (blockdev_filename->type != VAL_STRING) {
1343 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001344 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001345 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001346 if (transfer_list_value->type != VAL_BLOB) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001347 ErrorAbort(state, "transfer_list argument to %s must be blob", name);
Tao Bao612336d2015-08-27 16:41:21 -07001348 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001349 }
1350 if (new_data_fn->type != VAL_STRING) {
1351 ErrorAbort(state, "new_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001352 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001353 }
1354 if (patch_data_fn->type != VAL_STRING) {
1355 ErrorAbort(state, "patch_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001356 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001357 }
1358
Tao Bao612336d2015-08-27 16:41:21 -07001359 UpdaterInfo* ui = reinterpret_cast<UpdaterInfo*>(state->cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001360
Tao Bao0940fe12015-08-27 16:41:21 -07001361 if (ui == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001362 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001363 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001364
Tao Bao612336d2015-08-27 16:41:21 -07001365 FILE* cmd_pipe = ui->cmd_pipe;
1366 ZipArchive* za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001367
Tao Bao0940fe12015-08-27 16:41:21 -07001368 if (cmd_pipe == nullptr || za == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001369 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001370 }
1371
Tao Bao612336d2015-08-27 16:41:21 -07001372 const ZipEntry* patch_entry = mzFindZipEntry(za, patch_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001373 if (patch_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001374 fprintf(stderr, "%s(): no file \"%s\" in package", name, patch_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001375 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001376 }
1377
Sami Tolvanen90221202014-12-09 16:39:47 +00001378 params.patch_start = ui->package_zip_addr + mzGetZipEntryOffset(patch_entry);
Tao Bao612336d2015-08-27 16:41:21 -07001379 const ZipEntry* new_entry = mzFindZipEntry(za, new_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001380 if (new_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001381 fprintf(stderr, "%s(): no file \"%s\" in package", name, new_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001382 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001383 }
1384
Elliott Hughesbcabd092016-03-22 20:19:22 -07001385 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data, O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001386 if (params.fd == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001387 fprintf(stderr, "open \"%s\" failed: %s\n", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001388 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001389 }
1390
Sami Tolvanen90221202014-12-09 16:39:47 +00001391 if (params.canwrite) {
1392 params.nti.za = za;
1393 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001394
Tao Bao0940fe12015-08-27 16:41:21 -07001395 pthread_mutex_init(&params.nti.mu, nullptr);
1396 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001397 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001398 pthread_attr_init(&attr);
1399 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1400
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001401 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1402 if (error != 0) {
1403 fprintf(stderr, "pthread_create failed: %s\n", strerror(error));
Tao Bao612336d2015-08-27 16:41:21 -07001404 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001405 }
1406 }
1407
Tao Baobaad2d42015-12-06 16:56:27 -08001408 // Copy all the lines in transfer_list_value into std::string for
1409 // processing.
Tao Bao612336d2015-08-27 16:41:21 -07001410 const std::string transfer_list(transfer_list_value->data, transfer_list_value->size);
1411 std::vector<std::string> lines = android::base::Split(transfer_list, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001412 if (lines.size() < 2) {
1413 ErrorAbort(state, "too few lines in the transfer list [%zd]\n", lines.size());
1414 return StringValue(strdup(""));
1415 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001416
Sami Tolvanen90221202014-12-09 16:39:47 +00001417 // First line in transfer list is the version number
Tao Bao1fdec862015-10-21 14:57:44 -07001418 if (!android::base::ParseInt(lines[0].c_str(), &params.version, 1, 4)) {
Tao Bao612336d2015-08-27 16:41:21 -07001419 fprintf(stderr, "unexpected transfer list version [%s]\n", lines[0].c_str());
1420 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001421 }
1422
Sami Tolvanen90221202014-12-09 16:39:47 +00001423 fprintf(stderr, "blockimg version is %d\n", params.version);
1424
1425 // Second line in transfer list is the total number of blocks we expect to write
Tao Baob15fd222015-09-24 11:10:51 -07001426 int total_blocks;
1427 if (!android::base::ParseInt(lines[1].c_str(), &total_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001428 ErrorAbort(state, "unexpected block count [%s]\n", lines[1].c_str());
1429 return StringValue(strdup(""));
Tao Baob15fd222015-09-24 11:10:51 -07001430 }
1431
1432 if (total_blocks == 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001433 return StringValue(strdup("t"));
Sami Tolvanen90221202014-12-09 16:39:47 +00001434 }
1435
Tao Bao612336d2015-08-27 16:41:21 -07001436 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001437 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001438 if (lines.size() < 4) {
1439 ErrorAbort(state, "too few lines in the transfer list [%zu]\n", lines.size());
1440 return StringValue(strdup(""));
1441 }
1442
Sami Tolvanen90221202014-12-09 16:39:47 +00001443 // Third line is how many stash entries are needed simultaneously
Tao Bao612336d2015-08-27 16:41:21 -07001444 fprintf(stderr, "maximum stash entries %s\n", lines[2].c_str());
Doug Zongker52ae67d2014-09-08 12:22:09 -07001445
Sami Tolvanen90221202014-12-09 16:39:47 +00001446 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Baob15fd222015-09-24 11:10:51 -07001447 int stash_max_blocks;
1448 if (!android::base::ParseInt(lines[3].c_str(), &stash_max_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001449 ErrorAbort(state, "unexpected maximum stash blocks [%s]\n", lines[3].c_str());
1450 return StringValue(strdup(""));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001451 }
1452
Tao Baob15fd222015-09-24 11:10:51 -07001453 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001454 if (res == -1) {
1455 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001456 }
Tao Bao612336d2015-08-27 16:41:21 -07001457
Tao Baob15fd222015-09-24 11:10:51 -07001458 params.createdstash = res;
1459
Tao Bao612336d2015-08-27 16:41:21 -07001460 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001461 }
1462
Sami Tolvanen90221202014-12-09 16:39:47 +00001463 // Build a hash table of the available commands
Tao Bao612336d2015-08-27 16:41:21 -07001464 HashTable* cmdht = mzHashTableCreate(cmdcount, nullptr);
1465 std::unique_ptr<HashTable, decltype(&mzHashTableFree)> cmdht_holder(cmdht, mzHashTableFree);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001466
Tao Bao0940fe12015-08-27 16:41:21 -07001467 for (size_t i = 0; i < cmdcount; ++i) {
1468 unsigned int cmdhash = HashString(commands[i].name);
Sami Tolvanen90221202014-12-09 16:39:47 +00001469 mzHashTableLookup(cmdht, cmdhash, (void*) &commands[i], CompareCommands, true);
1470 }
1471
Tao Bao612336d2015-08-27 16:41:21 -07001472 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001473
Tao Bao612336d2015-08-27 16:41:21 -07001474 // Subsequent lines are all individual transfer commands
1475 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1476 const std::string& line_str(*it);
Tao Bao6a47dff2015-09-25 17:12:28 -07001477 if (line_str.empty()) {
1478 continue;
1479 }
1480
Tao Baobaad2d42015-12-06 16:56:27 -08001481 params.tokens = android::base::Split(line_str, " ");
1482 params.cpos = 0;
1483 params.cmdname = params.tokens[params.cpos++].c_str();
1484 params.cmdline = line_str.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001485
Tao Bao0940fe12015-08-27 16:41:21 -07001486 unsigned int cmdhash = HashString(params.cmdname);
Tao Bao612336d2015-08-27 16:41:21 -07001487 const Command* cmd = reinterpret_cast<const Command*>(mzHashTableLookup(cmdht, cmdhash,
Tao Baobaad2d42015-12-06 16:56:27 -08001488 const_cast<char*>(params.cmdname), CompareCommandNames,
1489 false));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001490
Tao Bao0940fe12015-08-27 16:41:21 -07001491 if (cmd == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001492 fprintf(stderr, "unexpected command [%s]\n", params.cmdname);
1493 goto pbiudone;
1494 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001495
Tao Bao0940fe12015-08-27 16:41:21 -07001496 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao612336d2015-08-27 16:41:21 -07001497 fprintf(stderr, "failed to execute command [%s]\n", line_str.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +00001498 goto pbiudone;
1499 }
1500
Sami Tolvanen90221202014-12-09 16:39:47 +00001501 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001502 if (ota_fsync(params.fd) == -1) {
Tao Bao187efff2015-07-27 14:07:08 -07001503 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
1504 goto pbiudone;
1505 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001506 fprintf(cmd_pipe, "set_progress %.4f\n", (double) params.written / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001507 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001508 }
1509 }
1510
Sami Tolvanen90221202014-12-09 16:39:47 +00001511 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001512 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001513
Tao Bao0940fe12015-08-27 16:41:21 -07001514 fprintf(stderr, "wrote %zu blocks; expected %d\n", params.written, total_blocks);
Tao Bao612336d2015-08-27 16:41:21 -07001515 fprintf(stderr, "max alloc needed was %zu\n", params.buffer.size());
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001516
Sami Tolvanen90221202014-12-09 16:39:47 +00001517 // Delete stash only after successfully completing the update, as it
1518 // may contain blocks needed to complete the update later.
1519 DeleteStash(params.stashbase);
1520 } else {
1521 fprintf(stderr, "verified partition contents; update may be resumed\n");
1522 }
1523
1524 rc = 0;
1525
1526pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001527 if (ota_fsync(params.fd) == -1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001528 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +00001529 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001530 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001531
Sami Tolvanen90221202014-12-09 16:39:47 +00001532 // Only delete the stash if the update cannot be resumed, or it's
1533 // a verification run and we created the stash.
1534 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1535 DeleteStash(params.stashbase);
1536 }
1537
Sami Tolvanen90221202014-12-09 16:39:47 +00001538 return StringValue(rc == 0 ? strdup("t") : strdup(""));
1539}
1540
1541// The transfer list is a text file containing commands to
1542// transfer data from one place to another on the target
1543// partition. We parse it and execute the commands in order:
1544//
1545// zero [rangeset]
1546// - fill the indicated blocks with zeros
1547//
1548// new [rangeset]
1549// - fill the blocks with data read from the new_data file
1550//
1551// erase [rangeset]
1552// - mark the given blocks as empty
1553//
1554// move <...>
1555// bsdiff <patchstart> <patchlen> <...>
1556// imgdiff <patchstart> <patchlen> <...>
1557// - read the source blocks, apply a patch (or not in the
1558// case of move), write result to target blocks. bsdiff or
1559// imgdiff specifies the type of patch; move means no patch
1560// at all.
1561//
1562// The format of <...> differs between versions 1 and 2;
1563// see the LoadSrcTgtVersion{1,2}() functions for a
1564// description of what's expected.
1565//
1566// stash <stash_id> <src_range>
1567// - (version 2+ only) load the given source range and stash
1568// the data in the given slot of the stash table.
1569//
Tao Baobaad2d42015-12-06 16:56:27 -08001570// free <stash_id>
1571// - (version 3+ only) free the given stash data.
1572//
Sami Tolvanen90221202014-12-09 16:39:47 +00001573// The creator of the transfer list will guarantee that no block
1574// is read (ie, used as the source for a patch or move) after it
1575// has been written.
1576//
1577// In version 2, the creator will guarantee that a given stash is
1578// loaded (with a stash command) before it's used in a
1579// move/bsdiff/imgdiff command.
1580//
1581// Within one command the source and target ranges may overlap so
1582// in general we need to read the entire source into memory before
1583// writing anything to the target blocks.
1584//
1585// All the patch data is concatenated into one patch_data file in
1586// the update package. It must be stored uncompressed because we
1587// memory-map it in directly from the archive. (Since patches are
1588// already compressed, we lose very little by not compressing
1589// their concatenation.)
1590//
1591// In version 3, commands that read data from the partition (i.e.
1592// move/bsdiff/imgdiff/stash) have one or more additional hashes
1593// before the range parameters, which are used to check if the
1594// command has already been completed and verify the integrity of
1595// the source data.
1596
1597Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001598 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001599 const Command commands[] = {
1600 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001601 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001602 { "free", PerformCommandFree },
1603 { "imgdiff", PerformCommandDiff },
1604 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001605 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001606 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001607 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001608 };
1609
1610 // Perform a dry run without writing to test if an update can proceed
1611 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001612 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001613}
1614
1615Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1616 const Command commands[] = {
1617 { "bsdiff", PerformCommandDiff },
1618 { "erase", PerformCommandErase },
1619 { "free", PerformCommandFree },
1620 { "imgdiff", PerformCommandDiff },
1621 { "move", PerformCommandMove },
1622 { "new", PerformCommandNew },
1623 { "stash", PerformCommandStash },
1624 { "zero", PerformCommandZero }
1625 };
1626
1627 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001628 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001629}
1630
Tao Bao0940fe12015-08-27 16:41:21 -07001631Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001632 Value* blockdev_filename;
1633 Value* ranges;
Tao Bao0940fe12015-08-27 16:41:21 -07001634
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001635 if (ReadValueArgs(state, argv, 2, &blockdev_filename, &ranges) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001636 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001637 }
Tao Bao612336d2015-08-27 16:41:21 -07001638 std::unique_ptr<Value, decltype(&FreeValue)> ranges_holder(ranges, FreeValue);
1639 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1640 FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001641
1642 if (blockdev_filename->type != VAL_STRING) {
1643 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001644 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001645 }
1646 if (ranges->type != VAL_STRING) {
1647 ErrorAbort(state, "ranges argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001648 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001649 }
1650
Elliott Hughesbcabd092016-03-22 20:19:22 -07001651 android::base::unique_fd fd(ota_open(blockdev_filename->data, O_RDWR));
1652 if (fd == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001653 ErrorAbort(state, "open \"%s\" failed: %s", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001654 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001655 }
1656
Tao Bao612336d2015-08-27 16:41:21 -07001657 RangeSet rs;
Tao Bao0940fe12015-08-27 16:41:21 -07001658 parse_range(ranges->data, rs);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001659
1660 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001661 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001662
Tao Bao612336d2015-08-27 16:41:21 -07001663 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001664 for (size_t i = 0; i < rs.count; ++i) {
1665 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tao Bao612336d2015-08-27 16:41:21 -07001666 ErrorAbort(state, "failed to seek %s: %s", blockdev_filename->data, strerror(errno));
1667 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001668 }
1669
Tao Bao0940fe12015-08-27 16:41:21 -07001670 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001671 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1672 ErrorAbort(state, "failed to read %s: %s", blockdev_filename->data,
Elliott Hughesbcabd092016-03-22 20:19:22 -07001673 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001674 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001675 }
1676
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001677 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001678 }
1679 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001680 uint8_t digest[SHA_DIGEST_LENGTH];
1681 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001682
Tao Bao612336d2015-08-27 16:41:21 -07001683 return StringValue(strdup(print_sha1(digest).c_str()));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001684}
1685
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001686// This function checks if a device has been remounted R/W prior to an incremental
1687// OTA update. This is an common cause of update abortion. The function reads the
1688// 1st block of each partition and check for mounting time/count. It return string "t"
1689// if executes successfully and an empty string otherwise.
1690
1691Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
1692 Value* arg_filename;
1693
1694 if (ReadValueArgs(state, argv, 1, &arg_filename) < 0) {
1695 return nullptr;
1696 }
1697 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1698
1699 if (filename->type != VAL_STRING) {
1700 ErrorAbort(state, "filename argument to %s must be string", name);
1701 return StringValue(strdup(""));
1702 }
1703
Elliott Hughesbcabd092016-03-22 20:19:22 -07001704 android::base::unique_fd fd(ota_open(arg_filename->data, O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001705 if (fd == -1) {
1706 ErrorAbort(state, "open \"%s\" failed: %s", arg_filename->data, strerror(errno));
1707 return StringValue(strdup(""));
1708 }
1709
1710 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1711 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1712
1713 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Elliott Hughesbcabd092016-03-22 20:19:22 -07001714 ErrorAbort(state, "failed to read %s: %s", arg_filename->data, strerror(errno));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001715 return StringValue(strdup(""));
1716 }
1717
1718 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1719 // Super block starts from block 0, offset 0x400
1720 // 0x2C: len32 Mount time
1721 // 0x30: len32 Write time
1722 // 0x34: len16 Number of mounts since the last fsck
1723 // 0x38: len16 Magic signature 0xEF53
1724
1725 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1726 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1727
1728 if (mount_count > 0) {
1729 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1730 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1731 }
1732
1733 return StringValue(strdup("t"));
1734}
1735
1736
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001737Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
1738 Value* arg_filename;
1739 Value* arg_ranges;
1740
1741 if (ReadValueArgs(state, argv, 2, &arg_filename, &arg_ranges) < 0) {
1742 return NULL;
1743 }
1744
1745 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1746 std::unique_ptr<Value, decltype(&FreeValue)> ranges(arg_ranges, FreeValue);
1747
1748 if (filename->type != VAL_STRING) {
1749 ErrorAbort(state, "filename argument to %s must be string", name);
1750 return StringValue(strdup(""));
1751 }
1752 if (ranges->type != VAL_STRING) {
1753 ErrorAbort(state, "ranges argument to %s must be string", name);
1754 return StringValue(strdup(""));
1755 }
1756
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001757 // Output notice to log when recover is attempted
1758 fprintf(stderr, "%s image corrupted, attempting to recover...\n", filename->data);
1759
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001760 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
1761 fec::io fh(filename->data, O_RDWR);
1762
1763 if (!fh) {
1764 ErrorAbort(state, "fec_open \"%s\" failed: %s", filename->data, strerror(errno));
1765 return StringValue(strdup(""));
1766 }
1767
1768 if (!fh.has_ecc() || !fh.has_verity()) {
1769 ErrorAbort(state, "unable to use metadata to correct errors");
1770 return StringValue(strdup(""));
1771 }
1772
1773 fec_status status;
1774
1775 if (!fh.get_status(status)) {
1776 ErrorAbort(state, "failed to read FEC status");
1777 return StringValue(strdup(""));
1778 }
1779
1780 RangeSet rs;
1781 parse_range(ranges->data, rs);
1782
1783 uint8_t buffer[BLOCKSIZE];
1784
1785 for (size_t i = 0; i < rs.count; ++i) {
1786 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1787 // Stay within the data area, libfec validates and corrects metadata
1788 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1789 continue;
1790 }
1791
1792 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tao Baobaad2d42015-12-06 16:56:27 -08001793 ErrorAbort(state, "failed to recover %s (block %zu): %s", filename->data,
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001794 j, strerror(errno));
1795 return StringValue(strdup(""));
1796 }
1797
1798 // If we want to be able to recover from a situation where rewriting a corrected
1799 // block doesn't guarantee the same data will be returned when re-read later, we
1800 // can save a copy of corrected blocks to /cache. Note:
1801 //
1802 // 1. Maximum space required from /cache is the same as the maximum number of
1803 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1804 // this would be ~16 MiB, for example.
1805 //
1806 // 2. To find out if this block was corrupted, call fec_get_status after each
1807 // read and check if the errors field value has increased.
1808 }
1809 }
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001810 fprintf(stderr, "...%s image recovered successfully.\n", filename->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001811 return StringValue(strdup("t"));
1812}
1813
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001814void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001815 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001816 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001817 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001818 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001819 RegisterFunction("range_sha1", RangeSha1Fn);
1820}