blob: e39fac30db16b33a0df64d30a4ec019461345c67 [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
18#include <errno.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000019#include <dirent.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070021#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070022#include <pthread.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000027#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070028#include <sys/types.h>
29#include <sys/wait.h>
30#include <sys/ioctl.h>
31#include <time.h>
32#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010033#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070034
Tao Baoec8272f2017-03-15 17:39:01 -070035#include <functional>
Tao Baoe6aa3322015-08-05 15:20:27 -070036#include <memory>
37#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070038#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070039#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070040
Tao Bao039f2da2016-11-22 16:29:50 -080041#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080042#include <android-base/parseint.h>
43#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070044#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080045#include <applypatch/applypatch.h>
46#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070047#include <private/android_filesystem_config.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070048#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070049
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070050#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070051#include "error_code.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070052#include "updater/install.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080053#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070054#include "print_sha1.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070055#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070056
Sami Tolvanene82fa182015-06-10 15:58:12 +000057// Set this to 0 to interpret 'erase' transfers to mean do a
58// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
59// erase to mean fill the region with zeroes.
60#define DEBUG_ERASE 0
61
Tao Bao51412212016-12-28 14:44:05 -080062static constexpr size_t BLOCKSIZE = 4096;
63static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
64static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
65static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000066
Tao Bao0940fe12015-08-27 16:41:21 -070067struct RangeSet {
Tao Baoc844c062016-12-28 15:15:55 -080068 size_t count; // Limit is INT_MAX.
69 size_t size;
70 std::vector<size_t> pos; // Actual limit is INT_MAX.
Tianjie Xu2cd36ba2017-03-15 23:52:46 +000071
72 // Get the block number for the ith(starting from 0) block in the range set.
73 int get_block(size_t idx) const {
74 if (idx >= size) {
75 LOG(ERROR) << "index: " << idx << " is greater than range set size: " << size;
76 return -1;
77 }
78 for (size_t i = 0; i < pos.size(); i += 2) {
79 if (idx < pos[i + 1] - pos[i]) {
80 return pos[i] + idx;
81 }
82 idx -= (pos[i + 1] - pos[i]);
83 }
84 return -1;
85 }
Tao Bao0940fe12015-08-27 16:41:21 -070086};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070087
Tianjie Xu16255832016-04-30 11:49:59 -070088static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070089static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070090static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070091
Tao Baoc844c062016-12-28 15:15:55 -080092static RangeSet parse_range(const std::string& range_text) {
93 RangeSet rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010094
Tao Baoc844c062016-12-28 15:15:55 -080095 std::vector<std::string> pieces = android::base::Split(range_text, ",");
96 if (pieces.size() < 3) {
97 goto err;
98 }
99
100 size_t num;
101 if (!android::base::ParseUint(pieces[0], &num, static_cast<size_t>(INT_MAX))) {
102 goto err;
103 }
104
105 if (num == 0 || num % 2) {
106 goto err; // must be even
107 } else if (num != pieces.size() - 1) {
108 goto err;
109 }
110
111 rs.pos.resize(num);
112 rs.count = num / 2;
113 rs.size = 0;
114
115 for (size_t i = 0; i < num; i += 2) {
116 if (!android::base::ParseUint(pieces[i + 1], &rs.pos[i], static_cast<size_t>(INT_MAX))) {
117 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100118 }
119
Tao Baoc844c062016-12-28 15:15:55 -0800120 if (!android::base::ParseUint(pieces[i + 2], &rs.pos[i + 1], static_cast<size_t>(INT_MAX))) {
121 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100122 }
123
Tao Baoc844c062016-12-28 15:15:55 -0800124 if (rs.pos[i] >= rs.pos[i + 1]) {
125 goto err; // empty or negative range
Tao Baob15fd222015-09-24 11:10:51 -0700126 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100127
Tao Baoc844c062016-12-28 15:15:55 -0800128 size_t sz = rs.pos[i + 1] - rs.pos[i];
129 if (rs.size > SIZE_MAX - sz) {
130 goto err; // overflow
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700131 }
132
Tao Baoc844c062016-12-28 15:15:55 -0800133 rs.size += sz;
134 }
135
136 return rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100137
138err:
Tao Baoc844c062016-12-28 15:15:55 -0800139 LOG(ERROR) << "failed to parse range '" << range_text << "'";
Tao Bao3da88012017-02-03 13:09:23 -0800140 exit(EXIT_FAILURE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700141}
142
Tao Baoe6aa3322015-08-05 15:20:27 -0700143static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Tao Baoc844c062016-12-28 15:15:55 -0800144 for (size_t i = 0; i < r1.count; ++i) {
145 size_t r1_0 = r1.pos[i * 2];
146 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000147
Tao Baoc844c062016-12-28 15:15:55 -0800148 for (size_t j = 0; j < r2.count; ++j) {
149 size_t r2_0 = r2.pos[j * 2];
150 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000151
Tao Baoc844c062016-12-28 15:15:55 -0800152 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
153 return true;
154 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000155 }
Tao Baoc844c062016-12-28 15:15:55 -0800156 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000157
Tao Baoc844c062016-12-28 15:15:55 -0800158 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000159}
160
161static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700162 size_t so_far = 0;
163 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800164 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700165 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700166 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800167 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000168 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700169 } else if (r == 0) {
170 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800171 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700172 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700173 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700174 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700175 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000176 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700177}
178
Tao Bao612336d2015-08-27 16:41:21 -0700179static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
180 return read_all(fd, buffer.data(), size);
181}
182
Sami Tolvanen90221202014-12-09 16:39:47 +0000183static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700184 size_t written = 0;
185 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800186 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700187 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700188 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800189 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000190 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700191 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700192 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700193 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000194
Sami Tolvanen90221202014-12-09 16:39:47 +0000195 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700196}
197
Tao Bao612336d2015-08-27 16:41:21 -0700198static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
199 return write_all(fd, buffer.data(), size);
200}
201
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700202static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
203 // Don't discard blocks unless the update is a retry run.
204 if (!is_retry) {
205 return true;
206 }
207
208 uint64_t args[2] = {static_cast<uint64_t>(offset), size};
209 int status = ioctl(fd, BLKDISCARD, &args);
210 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800211 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700212 return false;
213 }
214 return true;
215}
216
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700217static bool check_lseek(int fd, off64_t offset, int whence) {
218 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
219 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700220 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800221 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700222 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700223 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700224 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700225}
226
Tao Bao612336d2015-08-27 16:41:21 -0700227static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700228 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700229 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700230
Tao Bao612336d2015-08-27 16:41:21 -0700231 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700232}
233
Tao Bao60a70af2017-03-26 14:03:52 -0700234/**
235 * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
236 * given RangeSet.
237 */
238class RangeSinkWriter {
239 public:
240 RangeSinkWriter(int fd, const RangeSet& tgt)
241 : fd_(fd), tgt_(tgt), next_range_(0), current_range_left_(0) {
242 CHECK_NE(tgt.count, static_cast<size_t>(0));
243 };
Tao Bao0940fe12015-08-27 16:41:21 -0700244
Tao Bao60a70af2017-03-26 14:03:52 -0700245 bool Finished() const {
246 return next_range_ == tgt_.count && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700247 }
248
Tao Bao60a70af2017-03-26 14:03:52 -0700249 size_t Write(const uint8_t* data, size_t size) {
250 if (Finished()) {
251 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
252 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700253 }
254
Tao Bao60a70af2017-03-26 14:03:52 -0700255 size_t written = 0;
256 while (size > 0) {
257 // Move to the next range as needed.
258 if (current_range_left_ == 0) {
259 if (next_range_ < tgt_.count) {
260 off64_t offset = static_cast<off64_t>(tgt_.pos[next_range_ * 2]) * BLOCKSIZE;
261 current_range_left_ =
262 (tgt_.pos[next_range_ * 2 + 1] - tgt_.pos[next_range_ * 2]) * BLOCKSIZE;
263 next_range_++;
264 if (!discard_blocks(fd_, offset, current_range_left_)) {
265 break;
266 }
Tao Baof7eb7602017-03-27 15:12:48 -0700267
Tao Bao60a70af2017-03-26 14:03:52 -0700268 if (!check_lseek(fd_, offset, SEEK_SET)) {
269 break;
270 }
271 } else {
272 // We can't write any more; return how many bytes have been written so far.
Tao Baof7eb7602017-03-27 15:12:48 -0700273 break;
274 }
Tao Bao60a70af2017-03-26 14:03:52 -0700275 }
Tao Baof7eb7602017-03-27 15:12:48 -0700276
Tao Bao60a70af2017-03-26 14:03:52 -0700277 size_t write_now = size;
278 if (current_range_left_ < write_now) {
279 write_now = current_range_left_;
280 }
Tao Baof7eb7602017-03-27 15:12:48 -0700281
Tao Bao60a70af2017-03-26 14:03:52 -0700282 if (write_all(fd_, data, write_now) == -1) {
Tao Baof7eb7602017-03-27 15:12:48 -0700283 break;
284 }
Tao Bao60a70af2017-03-26 14:03:52 -0700285
286 data += write_now;
287 size -= write_now;
288
289 current_range_left_ -= write_now;
290 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700291 }
Tao Bao60a70af2017-03-26 14:03:52 -0700292
293 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700294 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700295
Tao Bao60a70af2017-03-26 14:03:52 -0700296 private:
297 // The input data.
298 int fd_;
299 // The destination for the data.
300 const RangeSet& tgt_;
301 // The next range that we should write to.
302 size_t next_range_;
303 // The number of bytes to write before moving to the next range.
304 size_t current_range_left_;
305};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700306
Tao Bao60a70af2017-03-26 14:03:52 -0700307/**
308 * All of the data for all the 'new' transfers is contained in one file in the update package,
309 * concatenated together in the order in which transfers.list will need it. We want to stream it out
310 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
311 * section until it's that transfer's turn to go.
312 *
313 * To achieve this, we expand the new data from the archive in a background thread, and block that
314 * threads 'receive uncompressed data' function until the main thread has reached a point where we
315 * want some new data to be written. We signal the background thread with the destination for the
316 * data and block the main thread, waiting for the background thread to complete writing that
317 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
318 * transfer.
319 *
320 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
321 * the main thread wants some data written, it sets writer to the destination location and signals
322 * the condition. When the background thread is done writing, it clears writer and signals the
323 * condition again.
324 */
Tao Bao0940fe12015-08-27 16:41:21 -0700325struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700326 ZipArchiveHandle za;
327 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700328
Tao Bao60a70af2017-03-26 14:03:52 -0700329 RangeSinkWriter* writer;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700330
Tao Bao60a70af2017-03-26 14:03:52 -0700331 pthread_mutex_t mu;
332 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700333};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700334
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700335static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700336 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700337
Tao Bao60a70af2017-03-26 14:03:52 -0700338 while (size > 0) {
339 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
340 pthread_mutex_lock(&nti->mu);
341 while (nti->writer == nullptr) {
342 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700343 }
Tao Bao60a70af2017-03-26 14:03:52 -0700344 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700345
Tao Bao60a70af2017-03-26 14:03:52 -0700346 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
347 // disappear from nti.
348 size_t written = nti->writer->Write(data, size);
349 data += written;
350 size -= written;
351
352 if (nti->writer->Finished()) {
353 // We have written all the bytes desired by this writer.
354
355 pthread_mutex_lock(&nti->mu);
356 nti->writer = nullptr;
357 pthread_cond_broadcast(&nti->cv);
358 pthread_mutex_unlock(&nti->mu);
359 }
360 }
361
362 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700363}
364
365static void* unzip_new_data(void* cookie) {
Mikhail Lappo20791bd2017-03-23 21:30:36 +0100366 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700367 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700368 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700369}
370
Tao Bao612336d2015-08-27 16:41:21 -0700371static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000372 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700373 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000374
Tao Bao0940fe12015-08-27 16:41:21 -0700375 for (size_t i = 0; i < src.count; ++i) {
376 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000377 return -1;
378 }
379
Tao Bao0940fe12015-08-27 16:41:21 -0700380 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000381
Tao Bao612336d2015-08-27 16:41:21 -0700382 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000383 return -1;
384 }
385
386 p += size;
387 }
388
389 return 0;
390}
391
Tao Bao612336d2015-08-27 16:41:21 -0700392static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700393 size_t written = 0;
394 for (size_t i = 0; i < tgt.count; ++i) {
395 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
396 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
397 if (!discard_blocks(fd, offset, size)) {
398 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000399 }
400
Tao Bao60a70af2017-03-26 14:03:52 -0700401 if (!check_lseek(fd, offset, SEEK_SET)) {
402 return -1;
403 }
404
405 if (write_all(fd, buffer.data() + written, size) == -1) {
406 return -1;
407 }
408
409 written += size;
410 }
411
412 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000413}
414
Tao Baobaad2d42015-12-06 16:56:27 -0800415// Parameters for transfer list command functions
416struct CommandParameters {
417 std::vector<std::string> tokens;
418 size_t cpos;
419 const char* cmdname;
420 const char* cmdline;
421 std::string freestash;
422 std::string stashbase;
423 bool canwrite;
424 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700425 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800426 bool foundwrites;
427 bool isunresumable;
428 int version;
429 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700430 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800431 NewThreadInfo nti;
432 pthread_t thread;
433 std::vector<uint8_t> buffer;
434 uint8_t* patch_start;
435};
436
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000437// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
438// handled separately).
439static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
440 const std::vector<uint8_t>& buffer) {
441 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000442 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
443 params.tokens[0] == "imgdiff");
444
445 size_t pos = 0;
446 // Command example:
447 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
448 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
449 // [<loc_range> <stashed_blocks>]
450 if (params.tokens[0] == "move") {
451 // src_range for move starts at the 4th position.
452 if (params.tokens.size() < 5) {
453 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
454 return;
455 }
456 pos = 4;
457 } else {
458 // src_range for diff starts at the 7th position.
459 if (params.tokens.size() < 8) {
460 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
461 return;
462 }
463 pos = 7;
464 }
465
466 // Source blocks in stash only, no work to do.
467 if (params.tokens[pos] == "-") {
468 return;
469 }
470
471 RangeSet src = parse_range(params.tokens[pos++]);
472
473 RangeSet locs;
474 // If there's no stashed blocks, content in the buffer is consecutive and has the same
475 // order as the source blocks.
476 if (pos == params.tokens.size()) {
477 locs.count = 1;
478 locs.size = src.size;
479 locs.pos = { 0, src.size };
480 } else {
481 // Otherwise, the next token is the offset of the source blocks in the target range.
482 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
483 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
484 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
485 locs = parse_range(params.tokens[pos++]);
486 CHECK_EQ(src.size, locs.size);
487 CHECK_EQ(locs.pos.size() % 2, static_cast<size_t>(0));
488 }
489
490 LOG(INFO) << "printing hash in hex for " << src.size << " source blocks";
491 for (size_t i = 0; i < src.size; i++) {
492 int block_num = src.get_block(i);
493 CHECK_NE(block_num, -1);
494 int buffer_index = locs.get_block(i);
495 CHECK_NE(buffer_index, -1);
496 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
497
498 uint8_t digest[SHA_DIGEST_LENGTH];
499 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
500 std::string hexdigest = print_sha1(digest);
501 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
502 }
503}
504
505// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
506// in hex for each block.
507static void PrintHashForCorruptedStashedBlocks(const std::string& id,
508 const std::vector<uint8_t>& buffer,
509 const RangeSet& src) {
510 LOG(INFO) << "printing hash in hex for stash_id: " << id;
511 CHECK_EQ(src.size * BLOCKSIZE, buffer.size());
512
513 for (size_t i = 0; i < src.size; i++) {
514 int block_num = src.get_block(i);
515 CHECK_NE(block_num, -1);
516
517 uint8_t digest[SHA_DIGEST_LENGTH];
518 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
519 std::string hexdigest = print_sha1(digest);
520 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
521 }
522}
523
524// If the stash file doesn't exist, read the source blocks this stash contains and print the
525// SHA-1 for these blocks.
526static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
527 if (stash_map.find(id) == stash_map.end()) {
528 LOG(ERROR) << "No stash saved for id: " << id;
529 return;
530 }
531
532 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
533 const RangeSet& src = stash_map[id];
534 std::vector<uint8_t> buffer(src.size * BLOCKSIZE);
535 if (ReadBlocks(src, buffer, fd) == -1) {
536 LOG(ERROR) << "failed to read source blocks for stash: " << id;
537 return;
538 }
539 PrintHashForCorruptedStashedBlocks(id, buffer, src);
540}
541
Tao Bao612336d2015-08-27 16:41:21 -0700542static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700543 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800544 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700545 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000546
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800547 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000548
Tao Baoe6aa3322015-08-05 15:20:27 -0700549 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000550
Tao Bao0940fe12015-08-27 16:41:21 -0700551 if (hexdigest != expected) {
552 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800553 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
554 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700555 }
556 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000557 }
558
Tao Bao0940fe12015-08-27 16:41:21 -0700559 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000560}
561
Tao Bao0940fe12015-08-27 16:41:21 -0700562static std::string GetStashFileName(const std::string& base, const std::string& id,
563 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700564 if (base.empty()) {
565 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000566 }
567
Tao Baoe6aa3322015-08-05 15:20:27 -0700568 std::string fn(STASH_DIRECTORY_BASE);
569 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000570
571 return fn;
572}
573
Tao Baoec8272f2017-03-15 17:39:01 -0700574// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
575// directory and continues despite of errors. Calls the 'callback' function for each file.
576static void EnumerateStash(const std::string& dirname,
577 const std::function<void(const std::string&)>& callback) {
578 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000579
Tao Baoec8272f2017-03-15 17:39:01 -0700580 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000581
Tao Baoec8272f2017-03-15 17:39:01 -0700582 if (directory == nullptr) {
583 if (errno != ENOENT) {
584 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000585 }
Tao Bao51412212016-12-28 14:44:05 -0800586 return;
587 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700588
Tao Baoec8272f2017-03-15 17:39:01 -0700589 dirent* item;
590 while ((item = readdir(directory.get())) != nullptr) {
591 if (item->d_type != DT_REG) continue;
592 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800593 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000594}
595
596// Deletes the stash directory and all files in it. Assumes that it only
597// contains files. There is nothing we can do about unlikely, but possible
598// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700599static void DeleteFile(const std::string& fn) {
600 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000601
Tao Baoec8272f2017-03-15 17:39:01 -0700602 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000603
Tao Baoec8272f2017-03-15 17:39:01 -0700604 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
605 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
606 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000607}
608
Tao Baoe6aa3322015-08-05 15:20:27 -0700609static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700610 if (base.empty()) return;
611
612 LOG(INFO) << "deleting stash " << base;
613
614 std::string dirname = GetStashFileName(base, "", "");
615 EnumerateStash(dirname, DeleteFile);
616
617 if (rmdir(dirname.c_str()) == -1) {
618 if (errno != ENOENT && errno != ENOTDIR) {
619 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000620 }
Tao Baoec8272f2017-03-15 17:39:01 -0700621 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000622}
623
Tao Baobcf46492017-03-23 15:28:20 -0700624static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
625 std::vector<uint8_t>& buffer, bool printnoent) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700626 // In verify mode, if source range_set was saved for the given hash,
627 // check contents in the source blocks first. If the check fails,
628 // search for the stashed files on /cache as usual.
629 if (!params.canwrite) {
630 if (stash_map.find(id) != stash_map.end()) {
631 const RangeSet& src = stash_map[id];
632 allocate(src.size * BLOCKSIZE, buffer);
633
634 if (ReadBlocks(src, buffer, params.fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800635 LOG(ERROR) << "failed to read source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700636 return -1;
637 }
638 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800639 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000640 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700641 return -1;
642 }
643 return 0;
644 }
645 }
646
Tao Bao0940fe12015-08-27 16:41:21 -0700647 size_t blockcount = 0;
648
Sami Tolvanen90221202014-12-09 16:39:47 +0000649 if (!blocks) {
650 blocks = &blockcount;
651 }
652
Tao Baobcf46492017-03-23 15:28:20 -0700653 std::string fn = GetStashFileName(params.stashbase, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000654
Tao Bao0940fe12015-08-27 16:41:21 -0700655 struct stat sb;
656 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000657
658 if (res == -1) {
659 if (errno != ENOENT || printnoent) {
Tao Bao039f2da2016-11-22 16:29:50 -0800660 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000661 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000662 }
Tao Bao0940fe12015-08-27 16:41:21 -0700663 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000664 }
665
Tao Bao039f2da2016-11-22 16:29:50 -0800666 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000667
Tao Bao0940fe12015-08-27 16:41:21 -0700668 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800669 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
Tao Bao0940fe12015-08-27 16:41:21 -0700670 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000671 }
672
Elliott Hughesbcabd092016-03-22 20:19:22 -0700673 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000674 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800675 PLOG(ERROR) << "open \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700676 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000677 }
678
Tao Bao612336d2015-08-27 16:41:21 -0700679 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000680
Tao Bao612336d2015-08-27 16:41:21 -0700681 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700682 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000683 }
684
Tao Bao0940fe12015-08-27 16:41:21 -0700685 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000686
Tao Bao612336d2015-08-27 16:41:21 -0700687 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800688 LOG(ERROR) << "unexpected contents in " << fn;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000689 if (stash_map.find(id) == stash_map.end()) {
690 LOG(ERROR) << "failed to find source blocks number for stash " << id
691 << " when executing command: " << params.cmdname;
692 } else {
693 const RangeSet& src = stash_map[id];
694 PrintHashForCorruptedStashedBlocks(id, buffer, src);
695 }
Tao Baoec8272f2017-03-15 17:39:01 -0700696 DeleteFile(fn);
Tao Bao0940fe12015-08-27 16:41:21 -0700697 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000698 }
699
Tao Bao0940fe12015-08-27 16:41:21 -0700700 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000701}
702
Tao Bao612336d2015-08-27 16:41:21 -0700703static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baod2aecd42017-03-23 14:43:44 -0700704 std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700705 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700706 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000707 }
708
709 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800710 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700711 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000712 }
713
Tao Bao0940fe12015-08-27 16:41:21 -0700714 std::string fn = GetStashFileName(base, id, ".partial");
715 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000716
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100717 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700718 struct stat sb;
719 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100720
721 if (res == 0) {
722 // The file already exists and since the name is the hash of the contents,
723 // it's safe to assume the contents are identical (accidental hash collisions
724 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800725 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700726 *exists = true;
727 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100728 }
729
Tao Bao0940fe12015-08-27 16:41:21 -0700730 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100731 }
732
Tao Bao039f2da2016-11-22 16:29:50 -0800733 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000734
Tao Bao039f2da2016-11-22 16:29:50 -0800735 android::base::unique_fd fd(
736 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000737 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800738 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700739 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000740 }
741
Tianjie Xua946b9e2017-03-21 16:24:57 -0700742 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
743 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
744 return -1;
745 }
746
Sami Tolvanen90221202014-12-09 16:39:47 +0000747 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700748 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000749 }
750
Jed Estepa7b9a462015-12-15 16:04:53 -0800751 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700752 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800753 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700754 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000755 }
756
Tao Baoe6aa3322015-08-05 15:20:27 -0700757 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800758 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700759 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000760 }
761
Tao Bao0940fe12015-08-27 16:41:21 -0700762 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700763 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
764 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700765 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700766 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800767 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700768 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700769 }
770
Jed Estepa7b9a462015-12-15 16:04:53 -0800771 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700772 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800773 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700774 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700775 }
776
Tao Bao0940fe12015-08-27 16:41:21 -0700777 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000778}
779
780// Creates a directory for storing stash files and checks if the /cache partition
781// hash enough space for the expected amount of blocks we need to store. Returns
782// >0 if we created the directory, zero if it existed already, and <0 of failure.
783
Tao Bao51412212016-12-28 14:44:05 -0800784static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
785 std::string& base) {
786 if (blockdev.empty()) {
787 return -1;
788 }
789
790 // Stash directory should be different for each partition to avoid conflicts
791 // when updating multiple partitions at the same time, so we use the hash of
792 // the block device name as the base directory
793 uint8_t digest[SHA_DIGEST_LENGTH];
794 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
795 base = print_sha1(digest);
796
797 std::string dirname = GetStashFileName(base, "", "");
798 struct stat sb;
799 int res = stat(dirname.c_str(), &sb);
800 size_t max_stash_size = maxblocks * BLOCKSIZE;
801
802 if (res == -1 && errno != ENOENT) {
803 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
804 strerror(errno));
805 return -1;
806 } else if (res != 0) {
807 LOG(INFO) << "creating stash " << dirname;
808 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
809
810 if (res != 0) {
811 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
812 strerror(errno));
813 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000814 }
815
Tianjie Xua946b9e2017-03-21 16:24:57 -0700816 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
817 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s\n", dirname.c_str(),
818 strerror(errno));
819 return -1;
820 }
821
Tao Bao51412212016-12-28 14:44:05 -0800822 if (CacheSizeCheck(max_stash_size) != 0) {
823 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
824 max_stash_size);
825 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000826 }
827
Tao Bao51412212016-12-28 14:44:05 -0800828 return 1; // Created directory
829 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000830
Tao Bao51412212016-12-28 14:44:05 -0800831 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000832
Tao Baoec8272f2017-03-15 17:39:01 -0700833 // If the directory already exists, calculate the space already allocated to stash files and check
834 // if there's enough for all required blocks. Delete any partially completed stash files first.
835 EnumerateStash(dirname, [](const std::string& fn) {
836 if (android::base::EndsWith(fn, ".partial")) {
837 DeleteFile(fn);
838 }
839 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000840
Tao Bao51412212016-12-28 14:44:05 -0800841 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700842 EnumerateStash(dirname, [&existing](const std::string& fn) {
843 if (fn.empty()) return;
844 struct stat sb;
845 if (stat(fn.c_str(), &sb) == -1) {
846 PLOG(ERROR) << "stat \"" << fn << "\" failed";
847 return;
848 }
849 existing += static_cast<size_t>(sb.st_size);
850 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000851
Tao Bao51412212016-12-28 14:44:05 -0800852 if (max_stash_size > existing) {
853 size_t needed = max_stash_size - existing;
854 if (CacheSizeCheck(needed) != 0) {
855 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
856 needed);
857 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000858 }
Tao Bao51412212016-12-28 14:44:05 -0800859 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000860
Tao Bao51412212016-12-28 14:44:05 -0800861 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000862}
863
Tao Baobaad2d42015-12-06 16:56:27 -0800864static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700865 if (base.empty() || id.empty()) {
866 return -1;
867 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000868
Tao Baoec8272f2017-03-15 17:39:01 -0700869 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000870
Tao Baoec8272f2017-03-15 17:39:01 -0700871 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700872}
873
Tao Bao612336d2015-08-27 16:41:21 -0700874static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
875 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700876 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700877 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700878 // may be the same buffer.
879
Tao Bao612336d2015-08-27 16:41:21 -0700880 const uint8_t* from = source.data();
881 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700882 size_t start = locs.size;
883 for (int i = locs.count-1; i >= 0; --i) {
884 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700885 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700886 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700887 blocks * BLOCKSIZE);
888 }
889}
890
Tao Baod2aecd42017-03-23 14:43:44 -0700891/**
892 * We expect to parse the remainder of the parameter tokens as one of:
893 *
894 * <src_block_count> <src_range>
895 * (loads data from source image only)
896 *
897 * <src_block_count> - <[stash_id:stash_range] ...>
898 * (loads data from stashes only)
899 *
900 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
901 * (loads data from both source image and stashes)
902 *
903 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
904 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
905 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
906 * LoadStash.
907 */
908static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
909 bool* overlap) {
910 CHECK(src_blocks != nullptr);
911 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700912
Tao Baod2aecd42017-03-23 14:43:44 -0700913 // <src_block_count>
914 const std::string& token = params.tokens[params.cpos++];
915 if (!android::base::ParseUint(token, src_blocks)) {
916 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
917 return -1;
918 }
Tao Baobaad2d42015-12-06 16:56:27 -0800919
Tao Baod2aecd42017-03-23 14:43:44 -0700920 allocate(*src_blocks * BLOCKSIZE, params.buffer);
921
922 // "-" or <src_range> [<src_loc>]
923 if (params.tokens[params.cpos] == "-") {
924 // no source ranges, only stashes
925 params.cpos++;
926 } else {
927 RangeSet src = parse_range(params.tokens[params.cpos++]);
928 *overlap = range_overlaps(src, tgt);
929
930 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
931 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -0800932 }
933
Tao Baod2aecd42017-03-23 14:43:44 -0700934 if (params.cpos >= params.tokens.size()) {
935 // no stashes, only source range
936 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -0800937 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700938
Tao Baod2aecd42017-03-23 14:43:44 -0700939 RangeSet locs = parse_range(params.tokens[params.cpos++]);
940 MoveRange(params.buffer, locs, params.buffer);
941 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700942
Tao Baod2aecd42017-03-23 14:43:44 -0700943 // <[stash_id:stash_range]>
944 while (params.cpos < params.tokens.size()) {
945 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
946 // in the source block that stashed data should go.
947 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
948 if (tokens.size() != 2) {
949 LOG(ERROR) << "invalid parameter";
950 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700951 }
952
Tao Baod2aecd42017-03-23 14:43:44 -0700953 std::vector<uint8_t> stash;
954 if (LoadStash(params, tokens[0], false, nullptr, stash, true) == -1) {
955 // These source blocks will fail verification if used later, but we
956 // will let the caller decide if this is a fatal failure
957 LOG(ERROR) << "failed to load stash " << tokens[0];
958 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +0000959 }
960
Tao Baod2aecd42017-03-23 14:43:44 -0700961 RangeSet locs = parse_range(tokens[1]);
962 MoveRange(params.buffer, locs, stash);
963 }
964
965 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000966}
967
Tao Bao33567772017-03-13 14:57:34 -0700968/**
969 * Do a source/target load for move/bsdiff/imgdiff in version 3.
970 *
971 * We expect to parse the remainder of the parameter tokens as one of:
972 *
973 * <tgt_range> <src_block_count> <src_range>
974 * (loads data from source image only)
975 *
976 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
977 * (loads data from stashes only)
978 *
979 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
980 * (loads data from both source image and stashes)
981 *
Tao Baod2aecd42017-03-23 14:43:44 -0700982 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
983 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -0700984 * verification fails in a way that the update cannot be resumed anymore.
985 *
986 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
987 * the return value is -1 and the command should be aborted.
988 *
989 * If the return value is 1, the command has already been completed according to the contents of the
990 * target blocks, and should not be performed again.
991 *
992 * If the return value is 0, source blocks have expected content and the command can be performed.
993 */
Tao Baod2aecd42017-03-23 14:43:44 -0700994static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
995 bool onehash, bool* overlap) {
996 CHECK(src_blocks != nullptr);
997 CHECK(overlap != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000998
Tao Baod2aecd42017-03-23 14:43:44 -0700999 if (params.cpos >= params.tokens.size()) {
1000 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001001 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001002 }
1003
1004 std::string srchash = params.tokens[params.cpos++];
1005 std::string tgthash;
1006
1007 if (onehash) {
1008 tgthash = srchash;
1009 } else {
1010 if (params.cpos >= params.tokens.size()) {
1011 LOG(ERROR) << "missing target hash";
1012 return -1;
1013 }
1014 tgthash = params.tokens[params.cpos++];
1015 }
1016
1017 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1018 // "-"/<src_range>.
1019 if (params.cpos + 2 >= params.tokens.size()) {
1020 LOG(ERROR) << "invalid parameters";
1021 return -1;
1022 }
1023
1024 // <tgt_range>
1025 tgt = parse_range(params.tokens[params.cpos++]);
1026
1027 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
1028 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
1029 return -1;
1030 }
1031
1032 // Return now if target blocks already have expected content.
1033 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
1034 return 1;
1035 }
1036
1037 // Load source blocks.
1038 if (LoadSourceBlocks(params, tgt, src_blocks, overlap) == -1) {
1039 return -1;
1040 }
1041
1042 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
1043 // If source and target blocks overlap, stash the source blocks so we can
1044 // resume from possible write errors. In verify mode, we can skip stashing
1045 // because the source blocks won't be overwritten.
1046 if (*overlap && params.canwrite) {
1047 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1048
1049 bool stash_exists = false;
1050 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1051 &stash_exists) != 0) {
1052 LOG(ERROR) << "failed to stash overlapping source blocks";
1053 return -1;
1054 }
1055
1056 params.stashed += *src_blocks;
1057 // Can be deleted when the write has completed.
1058 if (!stash_exists) {
1059 params.freestash = srchash;
1060 }
1061 }
1062
1063 // Source blocks have expected content, command can proceed.
1064 return 0;
1065 }
1066
1067 if (*overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
1068 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1069 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1070 // command.
1071 return 0;
1072 }
1073
1074 // Valid source data not available, update cannot be resumed.
1075 LOG(ERROR) << "partition has unexpected contents";
1076 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1077
1078 params.isunresumable = true;
1079
1080 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001081}
1082
Tao Bao0940fe12015-08-27 16:41:21 -07001083static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001084 size_t blocks = 0;
1085 bool overlap = false;
1086 RangeSet tgt;
Tao Baod2aecd42017-03-23 14:43:44 -07001087 int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001088
Tao Bao33567772017-03-13 14:57:34 -07001089 if (status == -1) {
1090 LOG(ERROR) << "failed to read blocks for move";
1091 return -1;
1092 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001093
Tao Bao33567772017-03-13 14:57:34 -07001094 if (status == 0) {
1095 params.foundwrites = true;
1096 } else if (params.foundwrites) {
1097 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1098 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001099
Tao Bao33567772017-03-13 14:57:34 -07001100 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001101 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001102 LOG(INFO) << " moving " << blocks << " blocks";
1103
1104 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1105 return -1;
1106 }
1107 } else {
1108 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001109 }
Tao Bao33567772017-03-13 14:57:34 -07001110 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001111
Tao Bao33567772017-03-13 14:57:34 -07001112 if (!params.freestash.empty()) {
1113 FreeStash(params.stashbase, params.freestash);
1114 params.freestash.clear();
1115 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001116
Tao Bao33567772017-03-13 14:57:34 -07001117 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001118
Tao Bao33567772017-03-13 14:57:34 -07001119 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001120}
1121
Tao Bao0940fe12015-08-27 16:41:21 -07001122static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001123 // <stash_id> <src_range>
1124 if (params.cpos + 1 >= params.tokens.size()) {
1125 LOG(ERROR) << "missing id and/or src range fields in stash command";
1126 return -1;
1127 }
1128
1129 const std::string& id = params.tokens[params.cpos++];
1130 size_t blocks = 0;
1131 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1132 // Stash file already exists and has expected contents. Do not read from source again, as the
1133 // source may have been already overwritten during a previous attempt.
1134 return 0;
1135 }
1136
1137 RangeSet src = parse_range(params.tokens[params.cpos++]);
1138
1139 allocate(src.size * BLOCKSIZE, params.buffer);
1140 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1141 return -1;
1142 }
1143 blocks = src.size;
1144 stash_map[id] = src;
1145
1146 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1147 // Source blocks have unexpected contents. If we actually need this data later, this is an
1148 // unrecoverable error. However, the command that uses the data may have already completed
1149 // previously, so the possible failure will occur during source block verification.
1150 LOG(ERROR) << "failed to load source blocks for stash " << id;
1151 return 0;
1152 }
1153
1154 // In verify mode, we don't need to stash any blocks.
1155 if (!params.canwrite) {
1156 return 0;
1157 }
1158
1159 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
1160 params.stashed += blocks;
1161 return WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001162}
1163
Tao Bao0940fe12015-08-27 16:41:21 -07001164static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001165 // <stash_id>
1166 if (params.cpos >= params.tokens.size()) {
1167 LOG(ERROR) << "missing stash id in free command";
1168 return -1;
1169 }
Tao Baobaad2d42015-12-06 16:56:27 -08001170
Tao Baobcf46492017-03-23 15:28:20 -07001171 const std::string& id = params.tokens[params.cpos++];
1172 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001173
Tao Baobcf46492017-03-23 15:28:20 -07001174 if (params.createdstash || params.canwrite) {
1175 return FreeStash(params.stashbase, id);
1176 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001177
Tao Baobcf46492017-03-23 15:28:20 -07001178 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001179}
1180
Tao Bao0940fe12015-08-27 16:41:21 -07001181static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001182
Tao Baobaad2d42015-12-06 16:56:27 -08001183 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001184 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001185 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001186 }
1187
Tao Baoc844c062016-12-28 15:15:55 -08001188 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001189
Tao Bao039f2da2016-11-22 16:29:50 -08001190 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001191
Tao Bao612336d2015-08-27 16:41:21 -07001192 allocate(BLOCKSIZE, params.buffer);
1193 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001194
Tao Bao0940fe12015-08-27 16:41:21 -07001195 if (params.canwrite) {
1196 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001197 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1198 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1199 if (!discard_blocks(params.fd, offset, size)) {
1200 return -1;
1201 }
1202
1203 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001204 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001205 }
1206
Tao Bao0940fe12015-08-27 16:41:21 -07001207 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1208 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1209 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001210 }
1211 }
1212 }
1213 }
1214
Tao Bao0940fe12015-08-27 16:41:21 -07001215 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001216 // Update only for the zero command, as the erase command will call
1217 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001218 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001219 }
1220
Tao Bao0940fe12015-08-27 16:41:21 -07001221 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001222}
1223
Tao Bao0940fe12015-08-27 16:41:21 -07001224static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001225 if (params.cpos >= params.tokens.size()) {
1226 LOG(ERROR) << "missing target blocks for new";
1227 return -1;
1228 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001229
Tao Bao60a70af2017-03-26 14:03:52 -07001230 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
1231
1232 if (params.canwrite) {
1233 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
1234
1235 RangeSinkWriter writer(params.fd, tgt);
1236 pthread_mutex_lock(&params.nti.mu);
1237 params.nti.writer = &writer;
1238 pthread_cond_broadcast(&params.nti.cv);
1239
1240 while (params.nti.writer != nullptr) {
1241 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001242 }
1243
Tao Bao60a70af2017-03-26 14:03:52 -07001244 pthread_mutex_unlock(&params.nti.mu);
1245 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001246
Tao Bao60a70af2017-03-26 14:03:52 -07001247 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001248
Tao Bao60a70af2017-03-26 14:03:52 -07001249 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001250}
1251
Tao Bao0940fe12015-08-27 16:41:21 -07001252static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001253 // <offset> <length>
1254 if (params.cpos + 1 >= params.tokens.size()) {
1255 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1256 return -1;
1257 }
Tao Bao0940fe12015-08-27 16:41:21 -07001258
Tao Baoc0e1c462017-02-01 10:20:10 -08001259 size_t offset;
1260 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1261 LOG(ERROR) << "invalid patch offset";
1262 return -1;
1263 }
Tao Bao0940fe12015-08-27 16:41:21 -07001264
Tao Baoc0e1c462017-02-01 10:20:10 -08001265 size_t len;
1266 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1267 LOG(ERROR) << "invalid patch len";
1268 return -1;
1269 }
Tao Bao0940fe12015-08-27 16:41:21 -07001270
Tao Baoc0e1c462017-02-01 10:20:10 -08001271 RangeSet tgt;
1272 size_t blocks = 0;
1273 bool overlap = false;
1274 int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
Tao Bao0940fe12015-08-27 16:41:21 -07001275
Tao Baoc0e1c462017-02-01 10:20:10 -08001276 if (status == -1) {
1277 LOG(ERROR) << "failed to read blocks for diff";
1278 return -1;
1279 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001280
Tao Baoc0e1c462017-02-01 10:20:10 -08001281 if (status == 0) {
1282 params.foundwrites = true;
1283 } else if (params.foundwrites) {
1284 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1285 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001286
Tao Baoc0e1c462017-02-01 10:20:10 -08001287 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001288 if (status == 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001289 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
1290 Value patch_value(
1291 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001292
Tao Bao60a70af2017-03-26 14:03:52 -07001293 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001294 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao60a70af2017-03-26 14:03:52 -07001295 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1296 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1297 std::placeholders::_2),
1298 nullptr, nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001299 LOG(ERROR) << "Failed to apply image patch.";
1300 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001301 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001302 } else {
Tao Bao60a70af2017-03-26 14:03:52 -07001303 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1304 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1305 std::placeholders::_2),
1306 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001307 LOG(ERROR) << "Failed to apply bsdiff patch.";
1308 return -1;
1309 }
1310 }
1311
1312 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001313 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001314 LOG(ERROR) << "range sink underrun?";
1315 }
1316 } else {
1317 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size << " ["
1318 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001319 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001320 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001321
Tao Baoc0e1c462017-02-01 10:20:10 -08001322 if (!params.freestash.empty()) {
1323 FreeStash(params.stashbase, params.freestash);
1324 params.freestash.clear();
1325 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001326
Tao Baoc0e1c462017-02-01 10:20:10 -08001327 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001328
Tao Baoc0e1c462017-02-01 10:20:10 -08001329 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001330}
1331
Tao Bao0940fe12015-08-27 16:41:21 -07001332static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001333 if (DEBUG_ERASE) {
1334 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001335 }
1336
Tao Bao0940fe12015-08-27 16:41:21 -07001337 struct stat sb;
1338 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001339 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001340 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001341 }
1342
Tao Bao0940fe12015-08-27 16:41:21 -07001343 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001344 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001345 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001346 }
1347
Tao Baobaad2d42015-12-06 16:56:27 -08001348 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001349 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001350 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001351 }
1352
Tao Baoc844c062016-12-28 15:15:55 -08001353 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001354
Tao Bao0940fe12015-08-27 16:41:21 -07001355 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001356 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001357
Tao Bao0940fe12015-08-27 16:41:21 -07001358 for (size_t i = 0; i < tgt.count; ++i) {
1359 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001360 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001361 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001362 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001363 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001364
Tao Bao0940fe12015-08-27 16:41:21 -07001365 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001366 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001367 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001368 }
1369 }
1370 }
1371
Tao Bao0940fe12015-08-27 16:41:21 -07001372 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001373}
1374
1375// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001376typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001377
Tao Bao612336d2015-08-27 16:41:21 -07001378struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001379 const char* name;
1380 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001381};
Sami Tolvanen90221202014-12-09 16:39:47 +00001382
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001383// args:
1384// - block device (or file) to modify in-place
1385// - transfer list (blob)
1386// - new data stream (filename within package.zip)
1387// - patch stream (filename within package.zip, must be uncompressed)
1388
Tianjie Xuc4447322017-03-06 14:44:59 -08001389static Value* PerformBlockImageUpdate(const char* name, State* state,
1390 const std::vector<std::unique_ptr<Expr>>& argv,
1391 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001392 CommandParameters params = {};
1393 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001394
Tao Bao33567772017-03-13 14:57:34 -07001395 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1396 if (state->is_retry) {
1397 is_retry = true;
1398 LOG(INFO) << "This update is a retry.";
1399 }
1400 if (argv.size() != 4) {
1401 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1402 argv.size());
1403 return StringValue("");
1404 }
1405
1406 std::vector<std::unique_ptr<Value>> args;
1407 if (!ReadValueArgs(state, argv, &args)) {
1408 return nullptr;
1409 }
1410
1411 const Value* blockdev_filename = args[0].get();
1412 const Value* transfer_list_value = args[1].get();
1413 const Value* new_data_fn = args[2].get();
1414 const Value* patch_data_fn = args[3].get();
1415
1416 if (blockdev_filename->type != VAL_STRING) {
1417 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1418 return StringValue("");
1419 }
1420 if (transfer_list_value->type != VAL_BLOB) {
1421 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1422 return StringValue("");
1423 }
1424 if (new_data_fn->type != VAL_STRING) {
1425 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1426 return StringValue("");
1427 }
1428 if (patch_data_fn->type != VAL_STRING) {
1429 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1430 return StringValue("");
1431 }
1432
1433 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1434 if (ui == nullptr) {
1435 return StringValue("");
1436 }
1437
1438 FILE* cmd_pipe = ui->cmd_pipe;
1439 ZipArchiveHandle za = ui->package_zip;
1440
1441 if (cmd_pipe == nullptr || za == nullptr) {
1442 return StringValue("");
1443 }
1444
1445 ZipString path_data(patch_data_fn->data.c_str());
1446 ZipEntry patch_entry;
1447 if (FindEntry(za, path_data, &patch_entry) != 0) {
1448 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1449 return StringValue("");
1450 }
1451
1452 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1453 ZipString new_data(new_data_fn->data.c_str());
1454 ZipEntry new_entry;
1455 if (FindEntry(za, new_data, &new_entry) != 0) {
1456 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1457 return StringValue("");
1458 }
1459
1460 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1461 if (params.fd == -1) {
1462 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1463 return StringValue("");
1464 }
1465
1466 if (params.canwrite) {
1467 params.nti.za = za;
1468 params.nti.entry = new_entry;
1469
1470 pthread_mutex_init(&params.nti.mu, nullptr);
1471 pthread_cond_init(&params.nti.cv, nullptr);
1472 pthread_attr_t attr;
1473 pthread_attr_init(&attr);
1474 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1475
1476 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1477 if (error != 0) {
1478 PLOG(ERROR) << "pthread_create failed";
1479 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001480 }
Tao Bao33567772017-03-13 14:57:34 -07001481 }
1482
1483 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1484 if (lines.size() < 2) {
1485 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1486 lines.size());
1487 return StringValue("");
1488 }
1489
1490 // First line in transfer list is the version number.
1491 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1492 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1493 return StringValue("");
1494 }
1495
1496 LOG(INFO) << "blockimg version is " << params.version;
1497
1498 // Second line in transfer list is the total number of blocks we expect to write.
1499 size_t total_blocks;
1500 if (!android::base::ParseUint(lines[1], &total_blocks)) {
1501 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
1502 return StringValue("");
1503 }
1504
1505 if (total_blocks == 0) {
1506 return StringValue("t");
1507 }
1508
1509 size_t start = 2;
1510 if (lines.size() < 4) {
1511 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1512 lines.size());
1513 return StringValue("");
1514 }
1515
1516 // Third line is how many stash entries are needed simultaneously.
1517 LOG(INFO) << "maximum stash entries " << lines[2];
1518
1519 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1520 size_t stash_max_blocks;
1521 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
1522 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1523 lines[3].c_str());
1524 return StringValue("");
1525 }
1526
1527 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
1528 if (res == -1) {
1529 return StringValue("");
1530 }
1531
1532 params.createdstash = res;
1533
1534 start += 2;
1535
1536 // Build a map of the available commands
1537 std::unordered_map<std::string, const Command*> cmd_map;
1538 for (size_t i = 0; i < cmdcount; ++i) {
1539 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1540 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
1541 return StringValue(strdup(""));
1542 }
1543 cmd_map[commands[i].name] = &commands[i];
1544 }
1545
1546 int rc = -1;
1547
1548 // Subsequent lines are all individual transfer commands
1549 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1550 const std::string& line(*it);
1551 if (line.empty()) continue;
1552
1553 params.tokens = android::base::Split(line, " ");
1554 params.cpos = 0;
1555 params.cmdname = params.tokens[params.cpos++].c_str();
1556 params.cmdline = line.c_str();
1557
1558 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1559 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1560 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001561 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001562
Tao Bao33567772017-03-13 14:57:34 -07001563 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001564
Tao Bao33567772017-03-13 14:57:34 -07001565 if (cmd->f != nullptr && cmd->f(params) == -1) {
1566 LOG(ERROR) << "failed to execute command [" << line << "]";
1567 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001568 }
1569
Sami Tolvanen90221202014-12-09 16:39:47 +00001570 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001571 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001572 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001573 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001574 goto pbiudone;
1575 }
1576 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1577 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001578 }
Tao Bao33567772017-03-13 14:57:34 -07001579 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001580
Tao Bao33567772017-03-13 14:57:34 -07001581 if (params.canwrite) {
1582 pthread_join(params.thread, nullptr);
1583
1584 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1585 LOG(INFO) << "stashed " << params.stashed << " blocks";
1586 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1587
1588 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1589 if (partition != nullptr && *(partition + 1) != 0) {
1590 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1591 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1592 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001593 }
Tao Bao33567772017-03-13 14:57:34 -07001594 // Delete stash only after successfully completing the update, as it may contain blocks needed
1595 // to complete the update later.
1596 DeleteStash(params.stashbase);
1597 } else {
1598 LOG(INFO) << "verified partition contents; update may be resumed";
1599 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001600
Tao Bao33567772017-03-13 14:57:34 -07001601 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001602
Tao Bao33567772017-03-13 14:57:34 -07001603pbiudone:
1604 if (ota_fsync(params.fd) == -1) {
1605 failure_type = kFsyncFailure;
1606 PLOG(ERROR) << "fsync failed";
1607 }
1608 // params.fd will be automatically closed because it's a unique_fd.
1609
1610 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1611 // created the stash.
1612 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1613 DeleteStash(params.stashbase);
1614 }
1615
1616 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1617 state->cause_code = failure_type;
1618 }
1619
1620 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001621}
1622
Tao Bao33567772017-03-13 14:57:34 -07001623/**
1624 * The transfer list is a text file containing commands to transfer data from one place to another
1625 * on the target partition. We parse it and execute the commands in order:
1626 *
1627 * zero [rangeset]
1628 * - Fill the indicated blocks with zeros.
1629 *
1630 * new [rangeset]
1631 * - Fill the blocks with data read from the new_data file.
1632 *
1633 * erase [rangeset]
1634 * - Mark the given blocks as empty.
1635 *
1636 * move <...>
1637 * bsdiff <patchstart> <patchlen> <...>
1638 * imgdiff <patchstart> <patchlen> <...>
1639 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1640 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1641 *
1642 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1643 *
1644 * stash <stash_id> <src_range>
1645 * - Load the given source range and stash the data in the given slot of the stash table.
1646 *
1647 * free <stash_id>
1648 * - Free the given stash data.
1649 *
1650 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1651 * a patch or move) after it has been written.
1652 *
1653 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1654 * in a move/bsdiff/imgdiff command.
1655 *
1656 * Within one command the source and target ranges may overlap so in general we need to read the
1657 * entire source into memory before writing anything to the target blocks.
1658 *
1659 * All the patch data is concatenated into one patch_data file in the update package. It must be
1660 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1661 * already compressed, we lose very little by not compressing their concatenation.)
1662 *
1663 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1664 * additional hashes before the range parameters, which are used to check if the command has already
1665 * been completed and verify the integrity of the source data.
1666 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001667Value* BlockImageVerifyFn(const char* name, State* state,
1668 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001669 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001670 const Command commands[] = {
1671 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001672 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001673 { "free", PerformCommandFree },
1674 { "imgdiff", PerformCommandDiff },
1675 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001676 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001677 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001678 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001679 };
1680
1681 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001682 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001683 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001684}
1685
Tianjie Xuc4447322017-03-06 14:44:59 -08001686Value* BlockImageUpdateFn(const char* name, State* state,
1687 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001688 const Command commands[] = {
1689 { "bsdiff", PerformCommandDiff },
1690 { "erase", PerformCommandErase },
1691 { "free", PerformCommandFree },
1692 { "imgdiff", PerformCommandDiff },
1693 { "move", PerformCommandMove },
1694 { "new", PerformCommandNew },
1695 { "stash", PerformCommandStash },
1696 { "zero", PerformCommandZero }
1697 };
1698
Tianjie Xuc4447322017-03-06 14:44:59 -08001699 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001700 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001701}
1702
Tianjie Xuc4447322017-03-06 14:44:59 -08001703Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1704 if (argv.size() != 2) {
1705 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu",
1706 argv.size());
1707 return StringValue("");
1708 }
1709
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001710 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001711 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001712 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001713 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001714
1715 const Value* blockdev_filename = args[0].get();
1716 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001717
1718 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001719 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1720 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001721 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001722 }
1723 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001724 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001725 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001726 }
1727
Tianjie Xuaced5d92016-10-12 10:55:04 -07001728 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001729 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001730 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1731 blockdev_filename->data.c_str(), strerror(errno));
1732 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001733 }
1734
Tao Baoc844c062016-12-28 15:15:55 -08001735 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001736
1737 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001738 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001739
Tao Bao612336d2015-08-27 16:41:21 -07001740 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001741 for (size_t i = 0; i < rs.count; ++i) {
1742 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001743 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1744 blockdev_filename->data