blob: 0f08d17eb7702d65728a63a063353769d809ebd0 [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 Bao0bbc7642017-03-29 23:57:47 -070021#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000028#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070029#include <sys/types.h>
30#include <sys/wait.h>
31#include <sys/ioctl.h>
32#include <time.h>
33#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010034#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070035
Tao Baoec8272f2017-03-15 17:39:01 -070036#include <functional>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070039#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070040#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070041
Tao Bao039f2da2016-11-22 16:29:50 -080042#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080043#include <android-base/parseint.h>
44#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070045#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080046#include <applypatch/applypatch.h>
47#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070048#include <private/android_filesystem_config.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070049#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070050
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070051#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070052#include "error_code.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 Bao8f237572017-03-26 13:36:49 -070055#include "updater/install.h"
56#include "updater/rangeset.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070057#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070058
Sami Tolvanene82fa182015-06-10 15:58:12 +000059// Set this to 0 to interpret 'erase' transfers to mean do a
60// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
61// erase to mean fill the region with zeroes.
62#define DEBUG_ERASE 0
63
Tao Bao51412212016-12-28 14:44:05 -080064static constexpr size_t BLOCKSIZE = 4096;
65static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
66static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
67static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000068
Tianjie Xu16255832016-04-30 11:49:59 -070069static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070070static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070071static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070072
Sami Tolvanen90221202014-12-09 16:39:47 +000073static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070074 size_t so_far = 0;
75 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -080076 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -070077 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -070078 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -080079 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +000080 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -070081 } else if (r == 0) {
82 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -080083 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -070084 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070085 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -070086 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070087 }
Sami Tolvanen90221202014-12-09 16:39:47 +000088 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070089}
90
Tao Bao612336d2015-08-27 16:41:21 -070091static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
92 return read_all(fd, buffer.data(), size);
93}
94
Sami Tolvanen90221202014-12-09 16:39:47 +000095static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070096 size_t written = 0;
97 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -080098 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -070099 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700100 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800101 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000102 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700103 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700104 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700105 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000106
Sami Tolvanen90221202014-12-09 16:39:47 +0000107 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700108}
109
Tao Bao612336d2015-08-27 16:41:21 -0700110static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
111 return write_all(fd, buffer.data(), size);
112}
113
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700114static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700115 // Don't discard blocks unless the update is a retry run.
116 if (!is_retry) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700117 return true;
Tao Baobf5b77d2017-03-30 16:57:29 -0700118 }
119
120 uint64_t args[2] = { static_cast<uint64_t>(offset), size };
121 if (ioctl(fd, BLKDISCARD, &args) == -1) {
122 PLOG(ERROR) << "BLKDISCARD ioctl failed";
123 return false;
124 }
125 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700126}
127
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700128static bool check_lseek(int fd, off64_t offset, int whence) {
129 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
130 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700131 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800132 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700133 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700134 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700135 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700136}
137
Tao Bao612336d2015-08-27 16:41:21 -0700138static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700139 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700140 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700141
Tao Bao612336d2015-08-27 16:41:21 -0700142 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700143}
144
Tao Bao60a70af2017-03-26 14:03:52 -0700145/**
146 * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
147 * given RangeSet.
148 */
149class RangeSinkWriter {
150 public:
151 RangeSinkWriter(int fd, const RangeSet& tgt)
152 : fd_(fd), tgt_(tgt), next_range_(0), current_range_left_(0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700153 CHECK_NE(tgt.size(), static_cast<size_t>(0));
Tao Bao60a70af2017-03-26 14:03:52 -0700154 };
Tao Bao0940fe12015-08-27 16:41:21 -0700155
Tao Bao60a70af2017-03-26 14:03:52 -0700156 bool Finished() const {
Tao Baobf5b77d2017-03-30 16:57:29 -0700157 return next_range_ == tgt_.size() && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700158 }
159
Tao Bao60a70af2017-03-26 14:03:52 -0700160 size_t Write(const uint8_t* data, size_t size) {
161 if (Finished()) {
162 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
163 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700164 }
165
Tao Bao60a70af2017-03-26 14:03:52 -0700166 size_t written = 0;
167 while (size > 0) {
168 // Move to the next range as needed.
169 if (current_range_left_ == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700170 if (next_range_ < tgt_.size()) {
171 const Range& range = tgt_[next_range_];
172 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
173 current_range_left_ = (range.second - range.first) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700174 next_range_++;
175 if (!discard_blocks(fd_, offset, current_range_left_)) {
176 break;
177 }
Tao Baof7eb7602017-03-27 15:12:48 -0700178
Tao Bao60a70af2017-03-26 14:03:52 -0700179 if (!check_lseek(fd_, offset, SEEK_SET)) {
180 break;
181 }
182 } else {
183 // We can't write any more; return how many bytes have been written so far.
Tao Baof7eb7602017-03-27 15:12:48 -0700184 break;
185 }
Tao Bao60a70af2017-03-26 14:03:52 -0700186 }
Tao Baof7eb7602017-03-27 15:12:48 -0700187
Tao Bao60a70af2017-03-26 14:03:52 -0700188 size_t write_now = size;
189 if (current_range_left_ < write_now) {
190 write_now = current_range_left_;
191 }
Tao Baof7eb7602017-03-27 15:12:48 -0700192
Tao Bao60a70af2017-03-26 14:03:52 -0700193 if (write_all(fd_, data, write_now) == -1) {
Tao Baof7eb7602017-03-27 15:12:48 -0700194 break;
195 }
Tao Bao60a70af2017-03-26 14:03:52 -0700196
197 data += write_now;
198 size -= write_now;
199
200 current_range_left_ -= write_now;
201 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700202 }
Tao Bao60a70af2017-03-26 14:03:52 -0700203
204 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700205 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700206
Tao Bao60a70af2017-03-26 14:03:52 -0700207 private:
208 // The input data.
209 int fd_;
210 // The destination for the data.
211 const RangeSet& tgt_;
212 // The next range that we should write to.
213 size_t next_range_;
214 // The number of bytes to write before moving to the next range.
215 size_t current_range_left_;
216};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700217
Tao Bao60a70af2017-03-26 14:03:52 -0700218/**
219 * All of the data for all the 'new' transfers is contained in one file in the update package,
220 * concatenated together in the order in which transfers.list will need it. We want to stream it out
221 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
222 * section until it's that transfer's turn to go.
223 *
224 * To achieve this, we expand the new data from the archive in a background thread, and block that
225 * threads 'receive uncompressed data' function until the main thread has reached a point where we
226 * want some new data to be written. We signal the background thread with the destination for the
227 * data and block the main thread, waiting for the background thread to complete writing that
228 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
229 * transfer.
230 *
231 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
232 * the main thread wants some data written, it sets writer to the destination location and signals
233 * the condition. When the background thread is done writing, it clears writer and signals the
234 * condition again.
235 */
Tao Bao0940fe12015-08-27 16:41:21 -0700236struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700237 ZipArchiveHandle za;
238 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700239
Tao Bao60a70af2017-03-26 14:03:52 -0700240 RangeSinkWriter* writer;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700241
Tao Bao60a70af2017-03-26 14:03:52 -0700242 pthread_mutex_t mu;
243 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700244};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700245
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700246static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700247 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700248
Tao Bao60a70af2017-03-26 14:03:52 -0700249 while (size > 0) {
250 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
251 pthread_mutex_lock(&nti->mu);
252 while (nti->writer == nullptr) {
253 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700254 }
Tao Bao60a70af2017-03-26 14:03:52 -0700255 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700256
Tao Bao60a70af2017-03-26 14:03:52 -0700257 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
258 // disappear from nti.
259 size_t written = nti->writer->Write(data, size);
260 data += written;
261 size -= written;
262
263 if (nti->writer->Finished()) {
264 // We have written all the bytes desired by this writer.
265
266 pthread_mutex_lock(&nti->mu);
267 nti->writer = nullptr;
268 pthread_cond_broadcast(&nti->cv);
269 pthread_mutex_unlock(&nti->mu);
270 }
271 }
272
273 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700274}
275
276static void* unzip_new_data(void* cookie) {
Mikhail Lappo20791bd2017-03-23 21:30:36 +0100277 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700278 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700279 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700280}
281
Tao Bao612336d2015-08-27 16:41:21 -0700282static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700283 size_t p = 0;
284 for (const auto& range : src) {
285 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
286 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000287 }
288
Tao Baobf5b77d2017-03-30 16:57:29 -0700289 size_t size = (range.second - range.first) * BLOCKSIZE;
290 if (read_all(fd, buffer.data() + p, size) == -1) {
291 return -1;
292 }
293
294 p += size;
295 }
296
297 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000298}
299
Tao Bao612336d2015-08-27 16:41:21 -0700300static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700301 size_t written = 0;
Tao Baobf5b77d2017-03-30 16:57:29 -0700302 for (const auto& range : tgt) {
303 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
304 size_t size = (range.second - range.first) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700305 if (!discard_blocks(fd, offset, size)) {
306 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000307 }
308
Tao Bao60a70af2017-03-26 14:03:52 -0700309 if (!check_lseek(fd, offset, SEEK_SET)) {
310 return -1;
311 }
312
313 if (write_all(fd, buffer.data() + written, size) == -1) {
314 return -1;
315 }
316
317 written += size;
318 }
319
320 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000321}
322
Tao Baobaad2d42015-12-06 16:56:27 -0800323// Parameters for transfer list command functions
324struct CommandParameters {
325 std::vector<std::string> tokens;
326 size_t cpos;
327 const char* cmdname;
328 const char* cmdline;
329 std::string freestash;
330 std::string stashbase;
331 bool canwrite;
332 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700333 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800334 bool foundwrites;
335 bool isunresumable;
336 int version;
337 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700338 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800339 NewThreadInfo nti;
340 pthread_t thread;
341 std::vector<uint8_t> buffer;
342 uint8_t* patch_start;
343};
344
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000345// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
346// handled separately).
347static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
348 const std::vector<uint8_t>& buffer) {
349 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000350 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
351 params.tokens[0] == "imgdiff");
352
353 size_t pos = 0;
354 // Command example:
355 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
356 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
357 // [<loc_range> <stashed_blocks>]
358 if (params.tokens[0] == "move") {
359 // src_range for move starts at the 4th position.
360 if (params.tokens.size() < 5) {
361 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
362 return;
363 }
364 pos = 4;
365 } else {
366 // src_range for diff starts at the 7th position.
367 if (params.tokens.size() < 8) {
368 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
369 return;
370 }
371 pos = 7;
372 }
373
374 // Source blocks in stash only, no work to do.
375 if (params.tokens[pos] == "-") {
376 return;
377 }
378
Tao Bao8f237572017-03-26 13:36:49 -0700379 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000380
381 RangeSet locs;
382 // If there's no stashed blocks, content in the buffer is consecutive and has the same
383 // order as the source blocks.
384 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700385 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000386 } else {
387 // Otherwise, the next token is the offset of the source blocks in the target range.
388 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
389 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
390 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700391 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700392 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000393 }
394
Tao Baobf5b77d2017-03-30 16:57:29 -0700395 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
396 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700397 size_t block_num = src.GetBlockNumber(i);
398 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000399 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
400
401 uint8_t digest[SHA_DIGEST_LENGTH];
402 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
403 std::string hexdigest = print_sha1(digest);
404 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
405 }
406}
407
408// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
409// in hex for each block.
410static void PrintHashForCorruptedStashedBlocks(const std::string& id,
411 const std::vector<uint8_t>& buffer,
412 const RangeSet& src) {
413 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700414 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000415
Tao Baobf5b77d2017-03-30 16:57:29 -0700416 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700417 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000418
419 uint8_t digest[SHA_DIGEST_LENGTH];
420 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
421 std::string hexdigest = print_sha1(digest);
422 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
423 }
424}
425
426// If the stash file doesn't exist, read the source blocks this stash contains and print the
427// SHA-1 for these blocks.
428static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
429 if (stash_map.find(id) == stash_map.end()) {
430 LOG(ERROR) << "No stash saved for id: " << id;
431 return;
432 }
433
434 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
435 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700436 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000437 if (ReadBlocks(src, buffer, fd) == -1) {
438 LOG(ERROR) << "failed to read source blocks for stash: " << id;
439 return;
440 }
441 PrintHashForCorruptedStashedBlocks(id, buffer, src);
442}
443
Tao Bao612336d2015-08-27 16:41:21 -0700444static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700445 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800446 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700447 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000448
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800449 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000450
Tao Baoe6aa3322015-08-05 15:20:27 -0700451 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000452
Tao Bao0940fe12015-08-27 16:41:21 -0700453 if (hexdigest != expected) {
454 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800455 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
456 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700457 }
458 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000459 }
460
Tao Bao0940fe12015-08-27 16:41:21 -0700461 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000462}
463
Tao Bao0940fe12015-08-27 16:41:21 -0700464static std::string GetStashFileName(const std::string& base, const std::string& id,
465 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700466 if (base.empty()) {
467 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000468 }
469
Tao Baoe6aa3322015-08-05 15:20:27 -0700470 std::string fn(STASH_DIRECTORY_BASE);
471 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000472
473 return fn;
474}
475
Tao Baoec8272f2017-03-15 17:39:01 -0700476// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
477// directory and continues despite of errors. Calls the 'callback' function for each file.
478static void EnumerateStash(const std::string& dirname,
479 const std::function<void(const std::string&)>& callback) {
480 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000481
Tao Baoec8272f2017-03-15 17:39:01 -0700482 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000483
Tao Baoec8272f2017-03-15 17:39:01 -0700484 if (directory == nullptr) {
485 if (errno != ENOENT) {
486 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000487 }
Tao Bao51412212016-12-28 14:44:05 -0800488 return;
489 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700490
Tao Baoec8272f2017-03-15 17:39:01 -0700491 dirent* item;
492 while ((item = readdir(directory.get())) != nullptr) {
493 if (item->d_type != DT_REG) continue;
494 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800495 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000496}
497
498// Deletes the stash directory and all files in it. Assumes that it only
499// contains files. There is nothing we can do about unlikely, but possible
500// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700501static void DeleteFile(const std::string& fn) {
502 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000503
Tao Baoec8272f2017-03-15 17:39:01 -0700504 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000505
Tao Baoec8272f2017-03-15 17:39:01 -0700506 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
507 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
508 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000509}
510
Tao Baoe6aa3322015-08-05 15:20:27 -0700511static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700512 if (base.empty()) return;
513
514 LOG(INFO) << "deleting stash " << base;
515
516 std::string dirname = GetStashFileName(base, "", "");
517 EnumerateStash(dirname, DeleteFile);
518
519 if (rmdir(dirname.c_str()) == -1) {
520 if (errno != ENOENT && errno != ENOTDIR) {
521 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000522 }
Tao Baoec8272f2017-03-15 17:39:01 -0700523 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000524}
525
Tao Baobcf46492017-03-23 15:28:20 -0700526static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
527 std::vector<uint8_t>& buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700528 // In verify mode, if source range_set was saved for the given hash, check contents in the source
529 // blocks first. If the check fails, search for the stashed files on /cache as usual.
530 if (!params.canwrite) {
531 if (stash_map.find(id) != stash_map.end()) {
532 const RangeSet& src = stash_map[id];
533 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700534
Tao Baobf5b77d2017-03-30 16:57:29 -0700535 if (ReadBlocks(src, buffer, params.fd) == -1) {
536 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700537 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700538 }
539 if (VerifyBlocks(id, buffer, src.blocks(), true) != 0) {
540 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
541 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tao Bao0940fe12015-08-27 16:41:21 -0700542 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700543 }
544 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000545 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700546 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000547
Tao Baobf5b77d2017-03-30 16:57:29 -0700548 size_t blockcount = 0;
549 if (!blocks) {
550 blocks = &blockcount;
551 }
552
553 std::string fn = GetStashFileName(params.stashbase, id, "");
554
555 struct stat sb;
556 if (stat(fn.c_str(), &sb) == -1) {
557 if (errno != ENOENT || printnoent) {
558 PLOG(ERROR) << "stat \"" << fn << "\" failed";
559 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000560 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700561 return -1;
562 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000563
Tao Baobf5b77d2017-03-30 16:57:29 -0700564 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000565
Tao Baobf5b77d2017-03-30 16:57:29 -0700566 if ((sb.st_size % BLOCKSIZE) != 0) {
567 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
568 return -1;
569 }
570
571 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
572 if (fd == -1) {
573 PLOG(ERROR) << "open \"" << fn << "\" failed";
574 return -1;
575 }
576
577 allocate(sb.st_size, buffer);
578
579 if (read_all(fd, buffer, sb.st_size) == -1) {
580 return -1;
581 }
582
583 *blocks = sb.st_size / BLOCKSIZE;
584
585 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
586 LOG(ERROR) << "unexpected contents in " << fn;
587 if (stash_map.find(id) == stash_map.end()) {
588 LOG(ERROR) << "failed to find source blocks number for stash " << id
589 << " when executing command: " << params.cmdname;
590 } else {
591 const RangeSet& src = stash_map[id];
592 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000593 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700594 DeleteFile(fn);
595 return -1;
596 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000597
Tao Baobf5b77d2017-03-30 16:57:29 -0700598 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000599}
600
Tao Bao612336d2015-08-27 16:41:21 -0700601static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baod2aecd42017-03-23 14:43:44 -0700602 std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700603 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700604 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000605 }
606
607 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800608 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700609 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000610 }
611
Tao Bao0940fe12015-08-27 16:41:21 -0700612 std::string fn = GetStashFileName(base, id, ".partial");
613 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000614
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100615 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700616 struct stat sb;
617 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100618
619 if (res == 0) {
620 // The file already exists and since the name is the hash of the contents,
621 // it's safe to assume the contents are identical (accidental hash collisions
622 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800623 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700624 *exists = true;
625 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100626 }
627
Tao Bao0940fe12015-08-27 16:41:21 -0700628 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100629 }
630
Tao Bao039f2da2016-11-22 16:29:50 -0800631 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000632
Tao Bao039f2da2016-11-22 16:29:50 -0800633 android::base::unique_fd fd(
634 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000635 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800636 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700637 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000638 }
639
Tianjie Xua946b9e2017-03-21 16:24:57 -0700640 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
641 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
642 return -1;
643 }
644
Sami Tolvanen90221202014-12-09 16:39:47 +0000645 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700646 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000647 }
648
Jed Estepa7b9a462015-12-15 16:04:53 -0800649 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700650 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800651 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700652 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000653 }
654
Tao Baoe6aa3322015-08-05 15:20:27 -0700655 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800656 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700657 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000658 }
659
Tao Bao0940fe12015-08-27 16:41:21 -0700660 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700661 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
662 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700663 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700664 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800665 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700666 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700667 }
668
Jed Estepa7b9a462015-12-15 16:04:53 -0800669 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700670 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800671 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700672 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700673 }
674
Tao Bao0940fe12015-08-27 16:41:21 -0700675 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000676}
677
678// Creates a directory for storing stash files and checks if the /cache partition
679// hash enough space for the expected amount of blocks we need to store. Returns
680// >0 if we created the directory, zero if it existed already, and <0 of failure.
681
Tao Bao51412212016-12-28 14:44:05 -0800682static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
683 std::string& base) {
684 if (blockdev.empty()) {
685 return -1;
686 }
687
688 // Stash directory should be different for each partition to avoid conflicts
689 // when updating multiple partitions at the same time, so we use the hash of
690 // the block device name as the base directory
691 uint8_t digest[SHA_DIGEST_LENGTH];
692 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
693 base = print_sha1(digest);
694
695 std::string dirname = GetStashFileName(base, "", "");
696 struct stat sb;
697 int res = stat(dirname.c_str(), &sb);
698 size_t max_stash_size = maxblocks * BLOCKSIZE;
699
700 if (res == -1 && errno != ENOENT) {
701 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
702 strerror(errno));
703 return -1;
704 } else if (res != 0) {
705 LOG(INFO) << "creating stash " << dirname;
706 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
707
708 if (res != 0) {
709 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
710 strerror(errno));
711 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000712 }
713
Tianjie Xua946b9e2017-03-21 16:24:57 -0700714 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
715 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s\n", dirname.c_str(),
716 strerror(errno));
717 return -1;
718 }
719
Tao Bao51412212016-12-28 14:44:05 -0800720 if (CacheSizeCheck(max_stash_size) != 0) {
721 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
722 max_stash_size);
723 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000724 }
725
Tao Bao51412212016-12-28 14:44:05 -0800726 return 1; // Created directory
727 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000728
Tao Bao51412212016-12-28 14:44:05 -0800729 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000730
Tao Baoec8272f2017-03-15 17:39:01 -0700731 // If the directory already exists, calculate the space already allocated to stash files and check
732 // if there's enough for all required blocks. Delete any partially completed stash files first.
733 EnumerateStash(dirname, [](const std::string& fn) {
734 if (android::base::EndsWith(fn, ".partial")) {
735 DeleteFile(fn);
736 }
737 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000738
Tao Bao51412212016-12-28 14:44:05 -0800739 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700740 EnumerateStash(dirname, [&existing](const std::string& fn) {
741 if (fn.empty()) return;
742 struct stat sb;
743 if (stat(fn.c_str(), &sb) == -1) {
744 PLOG(ERROR) << "stat \"" << fn << "\" failed";
745 return;
746 }
747 existing += static_cast<size_t>(sb.st_size);
748 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000749
Tao Bao51412212016-12-28 14:44:05 -0800750 if (max_stash_size > existing) {
751 size_t needed = max_stash_size - existing;
752 if (CacheSizeCheck(needed) != 0) {
753 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
754 needed);
755 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000756 }
Tao Bao51412212016-12-28 14:44:05 -0800757 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000758
Tao Bao51412212016-12-28 14:44:05 -0800759 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000760}
761
Tao Baobaad2d42015-12-06 16:56:27 -0800762static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700763 if (base.empty() || id.empty()) {
764 return -1;
765 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000766
Tao Baoec8272f2017-03-15 17:39:01 -0700767 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000768
Tao Baoec8272f2017-03-15 17:39:01 -0700769 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700770}
771
Tao Baobf5b77d2017-03-30 16:57:29 -0700772// Source contains packed data, which we want to move to the locations given in locs in the dest
773// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700774static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700775 const std::vector<uint8_t>& source) {
776 const uint8_t* from = source.data();
777 uint8_t* to = dest.data();
778 size_t start = locs.blocks();
779 // Must do the movement backward.
780 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
781 size_t blocks = it->second - it->first;
782 start -= blocks;
783 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
784 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700785}
786
Tao Baod2aecd42017-03-23 14:43:44 -0700787/**
788 * We expect to parse the remainder of the parameter tokens as one of:
789 *
790 * <src_block_count> <src_range>
791 * (loads data from source image only)
792 *
793 * <src_block_count> - <[stash_id:stash_range] ...>
794 * (loads data from stashes only)
795 *
796 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
797 * (loads data from both source image and stashes)
798 *
799 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
800 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
801 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
802 * LoadStash.
803 */
804static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
805 bool* overlap) {
806 CHECK(src_blocks != nullptr);
807 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700808
Tao Baod2aecd42017-03-23 14:43:44 -0700809 // <src_block_count>
810 const std::string& token = params.tokens[params.cpos++];
811 if (!android::base::ParseUint(token, src_blocks)) {
812 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
813 return -1;
814 }
Tao Baobaad2d42015-12-06 16:56:27 -0800815
Tao Baod2aecd42017-03-23 14:43:44 -0700816 allocate(*src_blocks * BLOCKSIZE, params.buffer);
817
818 // "-" or <src_range> [<src_loc>]
819 if (params.tokens[params.cpos] == "-") {
820 // no source ranges, only stashes
821 params.cpos++;
822 } else {
Tao Bao8f237572017-03-26 13:36:49 -0700823 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
824 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -0700825
826 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
827 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -0800828 }
829
Tao Baod2aecd42017-03-23 14:43:44 -0700830 if (params.cpos >= params.tokens.size()) {
831 // no stashes, only source range
832 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -0800833 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700834
Tao Bao8f237572017-03-26 13:36:49 -0700835 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Baod2aecd42017-03-23 14:43:44 -0700836 MoveRange(params.buffer, locs, params.buffer);
837 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700838
Tao Baod2aecd42017-03-23 14:43:44 -0700839 // <[stash_id:stash_range]>
840 while (params.cpos < params.tokens.size()) {
841 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
842 // in the source block that stashed data should go.
843 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
844 if (tokens.size() != 2) {
845 LOG(ERROR) << "invalid parameter";
846 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700847 }
848
Tao Baod2aecd42017-03-23 14:43:44 -0700849 std::vector<uint8_t> stash;
850 if (LoadStash(params, tokens[0], false, nullptr, stash, true) == -1) {
851 // These source blocks will fail verification if used later, but we
852 // will let the caller decide if this is a fatal failure
853 LOG(ERROR) << "failed to load stash " << tokens[0];
854 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +0000855 }
856
Tao Bao8f237572017-03-26 13:36:49 -0700857 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Baod2aecd42017-03-23 14:43:44 -0700858 MoveRange(params.buffer, locs, stash);
859 }
860
861 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000862}
863
Tao Bao33567772017-03-13 14:57:34 -0700864/**
865 * Do a source/target load for move/bsdiff/imgdiff in version 3.
866 *
867 * We expect to parse the remainder of the parameter tokens as one of:
868 *
869 * <tgt_range> <src_block_count> <src_range>
870 * (loads data from source image only)
871 *
872 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
873 * (loads data from stashes only)
874 *
875 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
876 * (loads data from both source image and stashes)
877 *
Tao Baod2aecd42017-03-23 14:43:44 -0700878 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
879 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -0700880 * verification fails in a way that the update cannot be resumed anymore.
881 *
882 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
883 * the return value is -1 and the command should be aborted.
884 *
885 * If the return value is 1, the command has already been completed according to the contents of the
886 * target blocks, and should not be performed again.
887 *
888 * If the return value is 0, source blocks have expected content and the command can be performed.
889 */
Tao Baod2aecd42017-03-23 14:43:44 -0700890static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
891 bool onehash, bool* overlap) {
892 CHECK(src_blocks != nullptr);
893 CHECK(overlap != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000894
Tao Baod2aecd42017-03-23 14:43:44 -0700895 if (params.cpos >= params.tokens.size()) {
896 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -0700897 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -0700898 }
899
900 std::string srchash = params.tokens[params.cpos++];
901 std::string tgthash;
902
903 if (onehash) {
904 tgthash = srchash;
905 } else {
906 if (params.cpos >= params.tokens.size()) {
907 LOG(ERROR) << "missing target hash";
908 return -1;
909 }
910 tgthash = params.tokens[params.cpos++];
911 }
912
913 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
914 // "-"/<src_range>.
915 if (params.cpos + 2 >= params.tokens.size()) {
916 LOG(ERROR) << "invalid parameters";
917 return -1;
918 }
919
920 // <tgt_range>
Tao Bao8f237572017-03-26 13:36:49 -0700921 tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Baod2aecd42017-03-23 14:43:44 -0700922
Tao Baobf5b77d2017-03-30 16:57:29 -0700923 std::vector<uint8_t> tgtbuffer(tgt.blocks() * BLOCKSIZE);
Tao Baod2aecd42017-03-23 14:43:44 -0700924 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
925 return -1;
926 }
927
928 // Return now if target blocks already have expected content.
Tao Baobf5b77d2017-03-30 16:57:29 -0700929 if (VerifyBlocks(tgthash, tgtbuffer, tgt.blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -0700930 return 1;
931 }
932
933 // Load source blocks.
934 if (LoadSourceBlocks(params, tgt, src_blocks, overlap) == -1) {
935 return -1;
936 }
937
938 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
939 // If source and target blocks overlap, stash the source blocks so we can
940 // resume from possible write errors. In verify mode, we can skip stashing
941 // because the source blocks won't be overwritten.
942 if (*overlap && params.canwrite) {
943 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
944
945 bool stash_exists = false;
946 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
947 &stash_exists) != 0) {
948 LOG(ERROR) << "failed to stash overlapping source blocks";
949 return -1;
950 }
951
952 params.stashed += *src_blocks;
953 // Can be deleted when the write has completed.
954 if (!stash_exists) {
955 params.freestash = srchash;
956 }
957 }
958
959 // Source blocks have expected content, command can proceed.
960 return 0;
961 }
962
963 if (*overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
964 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
965 // from an interrupted command, so we don't know if the stash can safely be deleted after this
966 // command.
967 return 0;
968 }
969
970 // Valid source data not available, update cannot be resumed.
971 LOG(ERROR) << "partition has unexpected contents";
972 PrintHashForCorruptedSourceBlocks(params, params.buffer);
973
974 params.isunresumable = true;
975
976 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000977}
978
Tao Bao0940fe12015-08-27 16:41:21 -0700979static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -0700980 size_t blocks = 0;
981 bool overlap = false;
982 RangeSet tgt;
Tao Baod2aecd42017-03-23 14:43:44 -0700983 int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +0000984
Tao Bao33567772017-03-13 14:57:34 -0700985 if (status == -1) {
986 LOG(ERROR) << "failed to read blocks for move";
987 return -1;
988 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000989
Tao Bao33567772017-03-13 14:57:34 -0700990 if (status == 0) {
991 params.foundwrites = true;
992 } else if (params.foundwrites) {
993 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
994 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000995
Tao Bao33567772017-03-13 14:57:34 -0700996 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000997 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -0700998 LOG(INFO) << " moving " << blocks << " blocks";
999
1000 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1001 return -1;
1002 }
1003 } else {
1004 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001005 }
Tao Bao33567772017-03-13 14:57:34 -07001006 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001007
Tao Bao33567772017-03-13 14:57:34 -07001008 if (!params.freestash.empty()) {
1009 FreeStash(params.stashbase, params.freestash);
1010 params.freestash.clear();
1011 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001012
Tao Baobf5b77d2017-03-30 16:57:29 -07001013 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001014
Tao Bao33567772017-03-13 14:57:34 -07001015 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001016}
1017
Tao Bao0940fe12015-08-27 16:41:21 -07001018static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001019 // <stash_id> <src_range>
1020 if (params.cpos + 1 >= params.tokens.size()) {
1021 LOG(ERROR) << "missing id and/or src range fields in stash command";
1022 return -1;
1023 }
1024
1025 const std::string& id = params.tokens[params.cpos++];
1026 size_t blocks = 0;
1027 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1028 // Stash file already exists and has expected contents. Do not read from source again, as the
1029 // source may have been already overwritten during a previous attempt.
1030 return 0;
1031 }
1032
Tao Bao8f237572017-03-26 13:36:49 -07001033 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Baobcf46492017-03-23 15:28:20 -07001034
Tao Baobf5b77d2017-03-30 16:57:29 -07001035 allocate(src.blocks() * BLOCKSIZE, params.buffer);
Tao Baobcf46492017-03-23 15:28:20 -07001036 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1037 return -1;
1038 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001039 blocks = src.blocks();
Tao Baobcf46492017-03-23 15:28:20 -07001040 stash_map[id] = src;
1041
1042 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1043 // Source blocks have unexpected contents. If we actually need this data later, this is an
1044 // unrecoverable error. However, the command that uses the data may have already completed
1045 // previously, so the possible failure will occur during source block verification.
1046 LOG(ERROR) << "failed to load source blocks for stash " << id;
1047 return 0;
1048 }
1049
1050 // In verify mode, we don't need to stash any blocks.
1051 if (!params.canwrite) {
1052 return 0;
1053 }
1054
1055 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
1056 params.stashed += blocks;
1057 return WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001058}
1059
Tao Bao0940fe12015-08-27 16:41:21 -07001060static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001061 // <stash_id>
1062 if (params.cpos >= params.tokens.size()) {
1063 LOG(ERROR) << "missing stash id in free command";
1064 return -1;
1065 }
Tao Baobaad2d42015-12-06 16:56:27 -08001066
Tao Baobcf46492017-03-23 15:28:20 -07001067 const std::string& id = params.tokens[params.cpos++];
1068 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001069
Tao Baobcf46492017-03-23 15:28:20 -07001070 if (params.createdstash || params.canwrite) {
1071 return FreeStash(params.stashbase, id);
1072 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001073
Tao Baobcf46492017-03-23 15:28:20 -07001074 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001075}
1076
Tao Bao0940fe12015-08-27 16:41:21 -07001077static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001078 if (params.cpos >= params.tokens.size()) {
1079 LOG(ERROR) << "missing target blocks for zero";
1080 return -1;
1081 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001082
Tao Baobf5b77d2017-03-30 16:57:29 -07001083 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1084
1085 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1086
1087 allocate(BLOCKSIZE, params.buffer);
1088 memset(params.buffer.data(), 0, BLOCKSIZE);
1089
1090 if (params.canwrite) {
1091 for (const auto& range : tgt) {
1092 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
1093 size_t size = (range.second - range.first) * BLOCKSIZE;
1094 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001095 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001096 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001097
Tao Baobf5b77d2017-03-30 16:57:29 -07001098 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1099 return -1;
1100 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001101
Tao Baobf5b77d2017-03-30 16:57:29 -07001102 for (size_t j = range.first; j < range.second; ++j) {
1103 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1104 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001105 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001106 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001107 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001108 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001109
Tao Baobf5b77d2017-03-30 16:57:29 -07001110 if (params.cmdname[0] == 'z') {
1111 // Update only for the zero command, as the erase command will call
1112 // this if DEBUG_ERASE is defined.
1113 params.written += tgt.blocks();
1114 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001115
Tao Baobf5b77d2017-03-30 16:57:29 -07001116 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001117}
1118
Tao Bao0940fe12015-08-27 16:41:21 -07001119static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001120 if (params.cpos >= params.tokens.size()) {
1121 LOG(ERROR) << "missing target blocks for new";
1122 return -1;
1123 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001124
Tao Bao8f237572017-03-26 13:36:49 -07001125 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao60a70af2017-03-26 14:03:52 -07001126
1127 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001128 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001129
1130 RangeSinkWriter writer(params.fd, tgt);
1131 pthread_mutex_lock(&params.nti.mu);
1132 params.nti.writer = &writer;
1133 pthread_cond_broadcast(&params.nti.cv);
1134
1135 while (params.nti.writer != nullptr) {
1136 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001137 }
1138
Tao Bao60a70af2017-03-26 14:03:52 -07001139 pthread_mutex_unlock(&params.nti.mu);
1140 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001141
Tao Baobf5b77d2017-03-30 16:57:29 -07001142 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001143
Tao Bao60a70af2017-03-26 14:03:52 -07001144 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001145}
1146
Tao Bao0940fe12015-08-27 16:41:21 -07001147static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001148 // <offset> <length>
1149 if (params.cpos + 1 >= params.tokens.size()) {
1150 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1151 return -1;
1152 }
Tao Bao0940fe12015-08-27 16:41:21 -07001153
Tao Baoc0e1c462017-02-01 10:20:10 -08001154 size_t offset;
1155 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1156 LOG(ERROR) << "invalid patch offset";
1157 return -1;
1158 }
Tao Bao0940fe12015-08-27 16:41:21 -07001159
Tao Baoc0e1c462017-02-01 10:20:10 -08001160 size_t len;
1161 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1162 LOG(ERROR) << "invalid patch len";
1163 return -1;
1164 }
Tao Bao0940fe12015-08-27 16:41:21 -07001165
Tao Baoc0e1c462017-02-01 10:20:10 -08001166 RangeSet tgt;
1167 size_t blocks = 0;
1168 bool overlap = false;
1169 int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
Tao Bao0940fe12015-08-27 16:41:21 -07001170
Tao Baoc0e1c462017-02-01 10:20:10 -08001171 if (status == -1) {
1172 LOG(ERROR) << "failed to read blocks for diff";
1173 return -1;
1174 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001175
Tao Baoc0e1c462017-02-01 10:20:10 -08001176 if (status == 0) {
1177 params.foundwrites = true;
1178 } else if (params.foundwrites) {
1179 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1180 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001181
Tao Baoc0e1c462017-02-01 10:20:10 -08001182 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001183 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001184 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001185 Value patch_value(
1186 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001187
Tao Bao60a70af2017-03-26 14:03:52 -07001188 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001189 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao60a70af2017-03-26 14:03:52 -07001190 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1191 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1192 std::placeholders::_2),
1193 nullptr, nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001194 LOG(ERROR) << "Failed to apply image patch.";
1195 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001196 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001197 } else {
Tao Bao60a70af2017-03-26 14:03:52 -07001198 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1199 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1200 std::placeholders::_2),
1201 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001202 LOG(ERROR) << "Failed to apply bsdiff patch.";
1203 return -1;
1204 }
1205 }
1206
1207 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001208 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001209 LOG(ERROR) << "range sink underrun?";
1210 }
1211 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001212 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001213 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001214 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001215 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001216
Tao Baoc0e1c462017-02-01 10:20:10 -08001217 if (!params.freestash.empty()) {
1218 FreeStash(params.stashbase, params.freestash);
1219 params.freestash.clear();
1220 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001221
Tao Baobf5b77d2017-03-30 16:57:29 -07001222 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001223
Tao Baoc0e1c462017-02-01 10:20:10 -08001224 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001225}
1226
Tao Bao0940fe12015-08-27 16:41:21 -07001227static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001228 if (DEBUG_ERASE) {
1229 return PerformCommandZero(params);
1230 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001231
Tao Baobf5b77d2017-03-30 16:57:29 -07001232 struct stat sb;
1233 if (fstat(params.fd, &sb) == -1) {
1234 PLOG(ERROR) << "failed to fstat device to erase";
1235 return -1;
1236 }
1237
1238 if (!S_ISBLK(sb.st_mode)) {
1239 LOG(ERROR) << "not a block device; skipping erase";
1240 return -1;
1241 }
1242
1243 if (params.cpos >= params.tokens.size()) {
1244 LOG(ERROR) << "missing target blocks for erase";
1245 return -1;
1246 }
1247
1248 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1249
1250 if (params.canwrite) {
1251 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1252
1253 for (const auto& range : tgt) {
1254 uint64_t blocks[2];
1255 // offset in bytes
1256 blocks[0] = range.first * static_cast<uint64_t>(BLOCKSIZE);
1257 // length in bytes
1258 blocks[1] = (range.second - range.first) * static_cast<uint64_t>(BLOCKSIZE);
1259
1260 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
1261 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001262 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001263 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001264 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001265 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001266
Tao Baobf5b77d2017-03-30 16:57:29 -07001267 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001268}
1269
1270// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001271typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001272
Tao Bao612336d2015-08-27 16:41:21 -07001273struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001274 const char* name;
1275 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001276};
Sami Tolvanen90221202014-12-09 16:39:47 +00001277
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001278// args:
1279// - block device (or file) to modify in-place
1280// - transfer list (blob)
1281// - new data stream (filename within package.zip)
1282// - patch stream (filename within package.zip, must be uncompressed)
1283
Tianjie Xuc4447322017-03-06 14:44:59 -08001284static Value* PerformBlockImageUpdate(const char* name, State* state,
1285 const std::vector<std::unique_ptr<Expr>>& argv,
1286 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001287 CommandParameters params = {};
1288 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001289
Tao Bao33567772017-03-13 14:57:34 -07001290 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1291 if (state->is_retry) {
1292 is_retry = true;
1293 LOG(INFO) << "This update is a retry.";
1294 }
1295 if (argv.size() != 4) {
1296 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1297 argv.size());
1298 return StringValue("");
1299 }
1300
1301 std::vector<std::unique_ptr<Value>> args;
1302 if (!ReadValueArgs(state, argv, &args)) {
1303 return nullptr;
1304 }
1305
Tao Baoc97edcb2017-03-31 01:18:13 -07001306 const std::unique_ptr<Value>& blockdev_filename = args[0];
1307 const std::unique_ptr<Value>& transfer_list_value = args[1];
1308 const std::unique_ptr<Value>& new_data_fn = args[2];
1309 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001310
1311 if (blockdev_filename->type != VAL_STRING) {
1312 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1313 return StringValue("");
1314 }
1315 if (transfer_list_value->type != VAL_BLOB) {
1316 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1317 return StringValue("");
1318 }
1319 if (new_data_fn->type != VAL_STRING) {
1320 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1321 return StringValue("");
1322 }
1323 if (patch_data_fn->type != VAL_STRING) {
1324 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1325 return StringValue("");
1326 }
1327
1328 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1329 if (ui == nullptr) {
1330 return StringValue("");
1331 }
1332
1333 FILE* cmd_pipe = ui->cmd_pipe;
1334 ZipArchiveHandle za = ui->package_zip;
1335
1336 if (cmd_pipe == nullptr || za == nullptr) {
1337 return StringValue("");
1338 }
1339
1340 ZipString path_data(patch_data_fn->data.c_str());
1341 ZipEntry patch_entry;
1342 if (FindEntry(za, path_data, &patch_entry) != 0) {
1343 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1344 return StringValue("");
1345 }
1346
1347 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1348 ZipString new_data(new_data_fn->data.c_str());
1349 ZipEntry new_entry;
1350 if (FindEntry(za, new_data, &new_entry) != 0) {
1351 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1352 return StringValue("");
1353 }
1354
1355 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1356 if (params.fd == -1) {
1357 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1358 return StringValue("");
1359 }
1360
1361 if (params.canwrite) {
1362 params.nti.za = za;
1363 params.nti.entry = new_entry;
1364
1365 pthread_mutex_init(&params.nti.mu, nullptr);
1366 pthread_cond_init(&params.nti.cv, nullptr);
1367 pthread_attr_t attr;
1368 pthread_attr_init(&attr);
1369 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1370
1371 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1372 if (error != 0) {
1373 PLOG(ERROR) << "pthread_create failed";
1374 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001375 }
Tao Bao33567772017-03-13 14:57:34 -07001376 }
1377
1378 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1379 if (lines.size() < 2) {
1380 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1381 lines.size());
1382 return StringValue("");
1383 }
1384
1385 // First line in transfer list is the version number.
1386 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1387 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1388 return StringValue("");
1389 }
1390
1391 LOG(INFO) << "blockimg version is " << params.version;
1392
1393 // Second line in transfer list is the total number of blocks we expect to write.
1394 size_t total_blocks;
1395 if (!android::base::ParseUint(lines[1], &total_blocks)) {
1396 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
1397 return StringValue("");
1398 }
1399
1400 if (total_blocks == 0) {
1401 return StringValue("t");
1402 }
1403
1404 size_t start = 2;
1405 if (lines.size() < 4) {
1406 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1407 lines.size());
1408 return StringValue("");
1409 }
1410
1411 // Third line is how many stash entries are needed simultaneously.
1412 LOG(INFO) << "maximum stash entries " << lines[2];
1413
1414 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1415 size_t stash_max_blocks;
1416 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
1417 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1418 lines[3].c_str());
1419 return StringValue("");
1420 }
1421
1422 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
1423 if (res == -1) {
1424 return StringValue("");
1425 }
1426
1427 params.createdstash = res;
1428
1429 start += 2;
1430
1431 // Build a map of the available commands
1432 std::unordered_map<std::string, const Command*> cmd_map;
1433 for (size_t i = 0; i < cmdcount; ++i) {
1434 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1435 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
1436 return StringValue(strdup(""));
1437 }
1438 cmd_map[commands[i].name] = &commands[i];
1439 }
1440
1441 int rc = -1;
1442
1443 // Subsequent lines are all individual transfer commands
1444 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1445 const std::string& line(*it);
1446 if (line.empty()) continue;
1447
1448 params.tokens = android::base::Split(line, " ");
1449 params.cpos = 0;
1450 params.cmdname = params.tokens[params.cpos++].c_str();
1451 params.cmdline = line.c_str();
1452
1453 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1454 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1455 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001456 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001457
Tao Bao33567772017-03-13 14:57:34 -07001458 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001459
Tao Bao33567772017-03-13 14:57:34 -07001460 if (cmd->f != nullptr && cmd->f(params) == -1) {
1461 LOG(ERROR) << "failed to execute command [" << line << "]";
1462 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001463 }
1464
Sami Tolvanen90221202014-12-09 16:39:47 +00001465 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001466 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001467 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001468 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001469 goto pbiudone;
1470 }
1471 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1472 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001473 }
Tao Bao33567772017-03-13 14:57:34 -07001474 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001475
Tao Bao33567772017-03-13 14:57:34 -07001476 if (params.canwrite) {
1477 pthread_join(params.thread, nullptr);
1478
1479 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1480 LOG(INFO) << "stashed " << params.stashed << " blocks";
1481 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1482
1483 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1484 if (partition != nullptr && *(partition + 1) != 0) {
1485 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1486 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1487 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001488 }
Tao Bao33567772017-03-13 14:57:34 -07001489 // Delete stash only after successfully completing the update, as it may contain blocks needed
1490 // to complete the update later.
1491 DeleteStash(params.stashbase);
1492 } else {
1493 LOG(INFO) << "verified partition contents; update may be resumed";
1494 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001495
Tao Bao33567772017-03-13 14:57:34 -07001496 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001497
Tao Bao33567772017-03-13 14:57:34 -07001498pbiudone:
1499 if (ota_fsync(params.fd) == -1) {
1500 failure_type = kFsyncFailure;
1501 PLOG(ERROR) << "fsync failed";
1502 }
1503 // params.fd will be automatically closed because it's a unique_fd.
1504
1505 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1506 // created the stash.
1507 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1508 DeleteStash(params.stashbase);
1509 }
1510
1511 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1512 state->cause_code = failure_type;
1513 }
1514
1515 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001516}
1517
Tao Bao33567772017-03-13 14:57:34 -07001518/**
1519 * The transfer list is a text file containing commands to transfer data from one place to another
1520 * on the target partition. We parse it and execute the commands in order:
1521 *
1522 * zero [rangeset]
1523 * - Fill the indicated blocks with zeros.
1524 *
1525 * new [rangeset]
1526 * - Fill the blocks with data read from the new_data file.
1527 *
1528 * erase [rangeset]
1529 * - Mark the given blocks as empty.
1530 *
1531 * move <...>
1532 * bsdiff <patchstart> <patchlen> <...>
1533 * imgdiff <patchstart> <patchlen> <...>
1534 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1535 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1536 *
1537 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1538 *
1539 * stash <stash_id> <src_range>
1540 * - Load the given source range and stash the data in the given slot of the stash table.
1541 *
1542 * free <stash_id>
1543 * - Free the given stash data.
1544 *
1545 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1546 * a patch or move) after it has been written.
1547 *
1548 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1549 * in a move/bsdiff/imgdiff command.
1550 *
1551 * Within one command the source and target ranges may overlap so in general we need to read the
1552 * entire source into memory before writing anything to the target blocks.
1553 *
1554 * All the patch data is concatenated into one patch_data file in the update package. It must be
1555 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1556 * already compressed, we lose very little by not compressing their concatenation.)
1557 *
1558 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1559 * additional hashes before the range parameters, which are used to check if the command has already
1560 * been completed and verify the integrity of the source data.
1561 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001562Value* BlockImageVerifyFn(const char* name, State* state,
1563 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001564 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001565 const Command commands[] = {
1566 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001567 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001568 { "free", PerformCommandFree },
1569 { "imgdiff", PerformCommandDiff },
1570 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001571 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001572 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001573 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001574 };
1575
1576 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001577 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001578 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001579}
1580
Tianjie Xuc4447322017-03-06 14:44:59 -08001581Value* BlockImageUpdateFn(const char* name, State* state,
1582 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001583 const Command commands[] = {
1584 { "bsdiff", PerformCommandDiff },
1585 { "erase", PerformCommandErase },
1586 { "free", PerformCommandFree },
1587 { "imgdiff", PerformCommandDiff },
1588 { "move", PerformCommandMove },
1589 { "new", PerformCommandNew },
1590 { "stash", PerformCommandStash },
1591 { "zero", PerformCommandZero }
1592 };
1593
Tianjie Xuc4447322017-03-06 14:44:59 -08001594 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001595 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001596}
1597
Tianjie Xuc4447322017-03-06 14:44:59 -08001598Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001599 if (argv.size() != 2) {
1600 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
1601 return StringValue("");
1602 }
1603
1604 std::vector<std::unique_ptr<Value>> args;
1605 if (!ReadValueArgs(state, argv, &args)) {
1606 return nullptr;
1607 }
1608
1609 const std::unique_ptr<Value>& blockdev_filename = args[0];
1610 const std::unique_ptr<Value>& ranges = args[1];
1611
1612 if (blockdev_filename->type != VAL_STRING) {
1613 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1614 return StringValue("");
1615 }
1616 if (ranges->type != VAL_STRING) {
1617 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
1618 return StringValue("");
1619 }
1620
1621 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
1622 if (fd == -1) {
1623 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", blockdev_filename->data.c_str(),
1624 strerror(errno));
1625 return StringValue("");
1626 }
1627
1628 RangeSet rs = RangeSet::Parse(ranges->data);
1629
1630 SHA_CTX ctx;
1631 SHA1_Init(&ctx);
1632
1633 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Baobf5b77d2017-03-30 16:57:29 -07001634 for (const auto& range : rs) {
1635 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001636 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
1637 strerror(errno));
1638 return StringValue("");
1639 }
1640
Tao Baobf5b77d2017-03-30 16:57:29 -07001641 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001642 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1643 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data.c_str(),
1644 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08001645 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07001646 }
1647
1648 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08001649 }
Tao Baoc97edcb2017-03-31 01:18:13 -07001650 }
1651 uint8_t digest[SHA_DIGEST_LENGTH];
1652 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08001653
Tao Baoc97edcb2017-03-31 01:18:13 -07001654 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001655}
1656
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001657// This function checks if a device has been remounted R/W prior to an incremental
1658// OTA update. This is an common cause of update abortion. The function reads the
1659// 1st block of each partition and check for mounting time/count. It return string "t"
1660// if executes successfully and an empty string otherwise.
1661
Tianjie Xuc4447322017-03-06 14:44:59 -08001662Value* CheckFirstBlockFn(const char* name, State* state,
1663 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001664 if (argv.size() != 1) {
1665 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1666 argv.size());
1667 return StringValue("");
1668 }
Tianjie Xuc4447322017-03-06 14:44:59 -08001669
Tao Baoc97edcb2017-03-31 01:18:13 -07001670 std::vector<std::unique_ptr<Value>> args;
1671 if (!ReadValueArgs(state, argv, &args)) {
1672 return nullptr;
1673 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001674
Tao Baoc97edcb2017-03-31 01:18:13 -07001675 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001676
Tao Baoc97edcb2017-03-31 01:18:13 -07001677 if (arg_filename->type != VAL_STRING) {
1678 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
1679 return StringValue("");
1680 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001681
Tao Baoc97edcb2017-03-31 01:18:13 -07001682 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
1683 if (fd == -1) {
1684 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
1685 strerror(errno));
1686 return StringValue("");
1687 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001688
Tao Baobf5b77d2017-03-30 16:57:29 -07001689 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07001690 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001691
Tao Baoc97edcb2017-03-31 01:18:13 -07001692 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
1693 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
1694 strerror(errno));
1695 return StringValue("");
1696 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001697
Tao Baoc97edcb2017-03-31 01:18:13 -07001698 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1699 // Super block starts from block 0, offset 0x400
1700 // 0x2C: len32 Mount time
1701 // 0x30: len32 Write time
1702 // 0x34: len16 Number of mounts since the last fsck
1703 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001704
Tao Baoc97edcb2017-03-31 01:18:13 -07001705 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
1706 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001707
Tao Baoc97edcb2017-03-31 01:18:13 -07001708 if (mount_count > 0) {
1709 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
1710 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1711 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001712
Tao Baoc97edcb2017-03-31 01:18:13 -07001713 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001714}
1715
Tianjie Xuc4447322017-03-06 14:44:59 -08001716Value* BlockImageRecoverFn(const char* name, State* state,
1717 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001718 if (argv.size() != 2) {
1719 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
1720 argv.size());
1721 return StringValue("");
1722 }
1723
1724 std::vector<std::unique_ptr<Value>> args;
1725 if (!ReadValueArgs(state, argv, &args)) {
1726 return nullptr;
1727 }
1728
1729 const std::unique_ptr<Value>& filename = args[0];
1730 const std::unique_ptr<Value>& ranges = args[1];
1731
1732 if (filename->type != VAL_STRING) {
1733 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
1734 return StringValue("");
1735 }
1736 if (ranges->type != VAL_STRING) {
1737 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
1738 return StringValue("");
1739 }
1740
1741 // Output notice to log when recover is attempted
1742 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
1743
1744 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
1745 fec::io fh(filename->data, O_RDWR);
1746
1747 if (!fh) {
1748 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
1749 strerror(errno));
1750 return StringValue("");
1751 }
1752
1753 if (!fh.has_ecc() || !fh.has_verity()) {
1754 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
1755 return StringValue("");
1756 }
1757
1758 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07001759 if (!fh.get_status(status)) {
1760 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
1761 return StringValue("");
1762 }
1763
Tao Baoc97edcb2017-03-31 01:18:13 -07001764 uint8_t buffer[BLOCKSIZE];
Tao Baobf5b77d2017-03-30 16:57:29 -07001765 for (const auto& range : RangeSet::Parse(ranges->data)) {
1766 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001767 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07001768 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001769 continue;
1770 }
1771
Tao Baobf5b77d2017-03-30 16:57:29 -07001772 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001773 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
1774 filename->data.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08001775 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07001776 }
1777
1778 // If we want to be able to recover from a situation where rewriting a corrected
1779 // block doesn't guarantee the same data will be returned when re-read later, we
1780 // can save a copy of corrected blocks to /cache. Note:
1781 //
1782 // 1. Maximum space required from /cache is the same as the maximum number of
1783 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1784 // this would be ~16 MiB, for example.
1785 //
1786 // 2. To find out if this block was corrupted, call fec_get_status after each
1787 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08001788 }
Tao Baoc97edcb2017-03-31 01:18:13 -07001789 }
1790 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
1791 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001792}
1793
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001794void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07001795 RegisterFunction("block_image_verify", BlockImageVerifyFn);
1796 RegisterFunction("block_image_update", BlockImageUpdateFn);
1797 RegisterFunction("block_image_recover", BlockImageRecoverFn);
1798 RegisterFunction("check_first_block", CheckFirstBlockFn);
1799 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001800}