blob: df366b0b8ba278e5b33790026b7515a8a6782611 [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)
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700152 : fd_(fd), tgt_(tgt), next_range_(0), current_range_left_(0), bytes_written_(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
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700204 bytes_written_ += written;
Tao Bao60a70af2017-03-26 14:03:52 -0700205 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700206 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700207
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700208 size_t BytesWritten() const {
209 return bytes_written_;
210 }
211
Tao Bao60a70af2017-03-26 14:03:52 -0700212 private:
213 // The input data.
214 int fd_;
215 // The destination for the data.
216 const RangeSet& tgt_;
217 // The next range that we should write to.
218 size_t next_range_;
219 // The number of bytes to write before moving to the next range.
220 size_t current_range_left_;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700221 // Total bytes written by the writer.
222 size_t bytes_written_;
Tao Bao60a70af2017-03-26 14:03:52 -0700223};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700224
Tao Bao60a70af2017-03-26 14:03:52 -0700225/**
226 * All of the data for all the 'new' transfers is contained in one file in the update package,
227 * concatenated together in the order in which transfers.list will need it. We want to stream it out
228 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
229 * section until it's that transfer's turn to go.
230 *
231 * To achieve this, we expand the new data from the archive in a background thread, and block that
232 * threads 'receive uncompressed data' function until the main thread has reached a point where we
233 * want some new data to be written. We signal the background thread with the destination for the
234 * data and block the main thread, waiting for the background thread to complete writing that
235 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
236 * transfer.
237 *
238 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
239 * the main thread wants some data written, it sets writer to the destination location and signals
240 * the condition. When the background thread is done writing, it clears writer and signals the
241 * condition again.
242 */
Tao Bao0940fe12015-08-27 16:41:21 -0700243struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700244 ZipArchiveHandle za;
245 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700246
Tao Bao60a70af2017-03-26 14:03:52 -0700247 RangeSinkWriter* writer;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700248 bool receiver_available;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700249
Tao Bao60a70af2017-03-26 14:03:52 -0700250 pthread_mutex_t mu;
251 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700252};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700253
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700254static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700255 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700256
Tao Bao60a70af2017-03-26 14:03:52 -0700257 while (size > 0) {
258 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
259 pthread_mutex_lock(&nti->mu);
260 while (nti->writer == nullptr) {
261 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700262 }
Tao Bao60a70af2017-03-26 14:03:52 -0700263 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700264
Tao Bao60a70af2017-03-26 14:03:52 -0700265 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
266 // disappear from nti.
267 size_t written = nti->writer->Write(data, size);
268 data += written;
269 size -= written;
270
271 if (nti->writer->Finished()) {
272 // We have written all the bytes desired by this writer.
273
274 pthread_mutex_lock(&nti->mu);
275 nti->writer = nullptr;
276 pthread_cond_broadcast(&nti->cv);
277 pthread_mutex_unlock(&nti->mu);
278 }
279 }
280
281 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700282}
283
284static void* unzip_new_data(void* cookie) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700285 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
286 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
287
288 pthread_mutex_lock(&nti->mu);
289 nti->receiver_available = false;
290 if (nti->writer != nullptr) {
291 pthread_cond_broadcast(&nti->cv);
292 }
293 pthread_mutex_unlock(&nti->mu);
294 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700295}
296
Tao Bao612336d2015-08-27 16:41:21 -0700297static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700298 size_t p = 0;
299 for (const auto& range : src) {
300 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
301 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000302 }
303
Tao Baobf5b77d2017-03-30 16:57:29 -0700304 size_t size = (range.second - range.first) * BLOCKSIZE;
305 if (read_all(fd, buffer.data() + p, size) == -1) {
306 return -1;
307 }
308
309 p += size;
310 }
311
312 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000313}
314
Tao Bao612336d2015-08-27 16:41:21 -0700315static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700316 size_t written = 0;
Tao Baobf5b77d2017-03-30 16:57:29 -0700317 for (const auto& range : tgt) {
318 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
319 size_t size = (range.second - range.first) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700320 if (!discard_blocks(fd, offset, size)) {
321 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000322 }
323
Tao Bao60a70af2017-03-26 14:03:52 -0700324 if (!check_lseek(fd, offset, SEEK_SET)) {
325 return -1;
326 }
327
328 if (write_all(fd, buffer.data() + written, size) == -1) {
329 return -1;
330 }
331
332 written += size;
333 }
334
335 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000336}
337
Tao Baobaad2d42015-12-06 16:56:27 -0800338// Parameters for transfer list command functions
339struct CommandParameters {
340 std::vector<std::string> tokens;
341 size_t cpos;
342 const char* cmdname;
343 const char* cmdline;
344 std::string freestash;
345 std::string stashbase;
346 bool canwrite;
347 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700348 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800349 bool foundwrites;
350 bool isunresumable;
351 int version;
352 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700353 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800354 NewThreadInfo nti;
355 pthread_t thread;
356 std::vector<uint8_t> buffer;
357 uint8_t* patch_start;
358};
359
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000360// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
361// handled separately).
362static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
363 const std::vector<uint8_t>& buffer) {
364 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000365 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
366 params.tokens[0] == "imgdiff");
367
368 size_t pos = 0;
369 // Command example:
370 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
371 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
372 // [<loc_range> <stashed_blocks>]
373 if (params.tokens[0] == "move") {
374 // src_range for move starts at the 4th position.
375 if (params.tokens.size() < 5) {
376 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
377 return;
378 }
379 pos = 4;
380 } else {
381 // src_range for diff starts at the 7th position.
382 if (params.tokens.size() < 8) {
383 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
384 return;
385 }
386 pos = 7;
387 }
388
389 // Source blocks in stash only, no work to do.
390 if (params.tokens[pos] == "-") {
391 return;
392 }
393
Tao Bao8f237572017-03-26 13:36:49 -0700394 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000395
396 RangeSet locs;
397 // If there's no stashed blocks, content in the buffer is consecutive and has the same
398 // order as the source blocks.
399 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700400 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000401 } else {
402 // Otherwise, the next token is the offset of the source blocks in the target range.
403 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
404 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
405 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700406 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700407 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000408 }
409
Tao Baobf5b77d2017-03-30 16:57:29 -0700410 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
411 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700412 size_t block_num = src.GetBlockNumber(i);
413 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000414 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
415
416 uint8_t digest[SHA_DIGEST_LENGTH];
417 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
418 std::string hexdigest = print_sha1(digest);
419 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
420 }
421}
422
423// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
424// in hex for each block.
425static void PrintHashForCorruptedStashedBlocks(const std::string& id,
426 const std::vector<uint8_t>& buffer,
427 const RangeSet& src) {
428 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700429 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000430
Tao Baobf5b77d2017-03-30 16:57:29 -0700431 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700432 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000433
434 uint8_t digest[SHA_DIGEST_LENGTH];
435 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
436 std::string hexdigest = print_sha1(digest);
437 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
438 }
439}
440
441// If the stash file doesn't exist, read the source blocks this stash contains and print the
442// SHA-1 for these blocks.
443static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
444 if (stash_map.find(id) == stash_map.end()) {
445 LOG(ERROR) << "No stash saved for id: " << id;
446 return;
447 }
448
449 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
450 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700451 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000452 if (ReadBlocks(src, buffer, fd) == -1) {
453 LOG(ERROR) << "failed to read source blocks for stash: " << id;
454 return;
455 }
456 PrintHashForCorruptedStashedBlocks(id, buffer, src);
457}
458
Tao Bao612336d2015-08-27 16:41:21 -0700459static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700460 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800461 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700462 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000463
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800464 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000465
Tao Baoe6aa3322015-08-05 15:20:27 -0700466 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000467
Tao Bao0940fe12015-08-27 16:41:21 -0700468 if (hexdigest != expected) {
469 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800470 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
471 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700472 }
473 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000474 }
475
Tao Bao0940fe12015-08-27 16:41:21 -0700476 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000477}
478
Tao Bao0940fe12015-08-27 16:41:21 -0700479static std::string GetStashFileName(const std::string& base, const std::string& id,
480 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700481 if (base.empty()) {
482 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000483 }
484
Tao Baoe6aa3322015-08-05 15:20:27 -0700485 std::string fn(STASH_DIRECTORY_BASE);
486 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000487
488 return fn;
489}
490
Tao Baoec8272f2017-03-15 17:39:01 -0700491// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
492// directory and continues despite of errors. Calls the 'callback' function for each file.
493static void EnumerateStash(const std::string& dirname,
494 const std::function<void(const std::string&)>& callback) {
495 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000496
Tao Baoec8272f2017-03-15 17:39:01 -0700497 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000498
Tao Baoec8272f2017-03-15 17:39:01 -0700499 if (directory == nullptr) {
500 if (errno != ENOENT) {
501 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000502 }
Tao Bao51412212016-12-28 14:44:05 -0800503 return;
504 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700505
Tao Baoec8272f2017-03-15 17:39:01 -0700506 dirent* item;
507 while ((item = readdir(directory.get())) != nullptr) {
508 if (item->d_type != DT_REG) continue;
509 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800510 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000511}
512
513// Deletes the stash directory and all files in it. Assumes that it only
514// contains files. There is nothing we can do about unlikely, but possible
515// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700516static void DeleteFile(const std::string& fn) {
517 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000518
Tao Baoec8272f2017-03-15 17:39:01 -0700519 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000520
Tao Baoec8272f2017-03-15 17:39:01 -0700521 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
522 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
523 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000524}
525
Tao Baoe6aa3322015-08-05 15:20:27 -0700526static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700527 if (base.empty()) return;
528
529 LOG(INFO) << "deleting stash " << base;
530
531 std::string dirname = GetStashFileName(base, "", "");
532 EnumerateStash(dirname, DeleteFile);
533
534 if (rmdir(dirname.c_str()) == -1) {
535 if (errno != ENOENT && errno != ENOTDIR) {
536 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000537 }
Tao Baoec8272f2017-03-15 17:39:01 -0700538 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000539}
540
Tao Baobcf46492017-03-23 15:28:20 -0700541static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
542 std::vector<uint8_t>& buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700543 // In verify mode, if source range_set was saved for the given hash, check contents in the source
544 // blocks first. If the check fails, search for the stashed files on /cache as usual.
545 if (!params.canwrite) {
546 if (stash_map.find(id) != stash_map.end()) {
547 const RangeSet& src = stash_map[id];
548 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700549
Tao Baobf5b77d2017-03-30 16:57:29 -0700550 if (ReadBlocks(src, buffer, params.fd) == -1) {
551 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700552 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700553 }
554 if (VerifyBlocks(id, buffer, src.blocks(), true) != 0) {
555 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
556 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tao Bao0940fe12015-08-27 16:41:21 -0700557 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700558 }
559 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000560 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700561 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000562
Tao Baobf5b77d2017-03-30 16:57:29 -0700563 size_t blockcount = 0;
564 if (!blocks) {
565 blocks = &blockcount;
566 }
567
568 std::string fn = GetStashFileName(params.stashbase, id, "");
569
570 struct stat sb;
571 if (stat(fn.c_str(), &sb) == -1) {
572 if (errno != ENOENT || printnoent) {
573 PLOG(ERROR) << "stat \"" << fn << "\" failed";
574 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000575 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700576 return -1;
577 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000578
Tao Baobf5b77d2017-03-30 16:57:29 -0700579 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000580
Tao Baobf5b77d2017-03-30 16:57:29 -0700581 if ((sb.st_size % BLOCKSIZE) != 0) {
582 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
583 return -1;
584 }
585
586 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
587 if (fd == -1) {
588 PLOG(ERROR) << "open \"" << fn << "\" failed";
589 return -1;
590 }
591
592 allocate(sb.st_size, buffer);
593
594 if (read_all(fd, buffer, sb.st_size) == -1) {
595 return -1;
596 }
597
598 *blocks = sb.st_size / BLOCKSIZE;
599
600 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
601 LOG(ERROR) << "unexpected contents in " << fn;
602 if (stash_map.find(id) == stash_map.end()) {
603 LOG(ERROR) << "failed to find source blocks number for stash " << id
604 << " when executing command: " << params.cmdname;
605 } else {
606 const RangeSet& src = stash_map[id];
607 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000608 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700609 DeleteFile(fn);
610 return -1;
611 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000612
Tao Baobf5b77d2017-03-30 16:57:29 -0700613 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000614}
615
Tao Bao612336d2015-08-27 16:41:21 -0700616static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baod2aecd42017-03-23 14:43:44 -0700617 std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700618 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700619 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000620 }
621
622 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800623 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700624 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000625 }
626
Tao Bao0940fe12015-08-27 16:41:21 -0700627 std::string fn = GetStashFileName(base, id, ".partial");
628 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000629
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100630 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700631 struct stat sb;
632 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100633
634 if (res == 0) {
635 // The file already exists and since the name is the hash of the contents,
636 // it's safe to assume the contents are identical (accidental hash collisions
637 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800638 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700639 *exists = true;
640 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100641 }
642
Tao Bao0940fe12015-08-27 16:41:21 -0700643 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100644 }
645
Tao Bao039f2da2016-11-22 16:29:50 -0800646 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000647
Tao Bao039f2da2016-11-22 16:29:50 -0800648 android::base::unique_fd fd(
649 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000650 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800651 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700652 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000653 }
654
Tianjie Xua946b9e2017-03-21 16:24:57 -0700655 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
656 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
657 return -1;
658 }
659
Sami Tolvanen90221202014-12-09 16:39:47 +0000660 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700661 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000662 }
663
Jed Estepa7b9a462015-12-15 16:04:53 -0800664 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700665 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800666 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700667 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000668 }
669
Tao Baoe6aa3322015-08-05 15:20:27 -0700670 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800671 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700672 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000673 }
674
Tao Bao0940fe12015-08-27 16:41:21 -0700675 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700676 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
677 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700678 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700679 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800680 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700681 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700682 }
683
Jed Estepa7b9a462015-12-15 16:04:53 -0800684 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700685 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800686 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700687 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700688 }
689
Tao Bao0940fe12015-08-27 16:41:21 -0700690 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000691}
692
693// Creates a directory for storing stash files and checks if the /cache partition
694// hash enough space for the expected amount of blocks we need to store. Returns
695// >0 if we created the directory, zero if it existed already, and <0 of failure.
696
Tao Bao51412212016-12-28 14:44:05 -0800697static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
698 std::string& base) {
699 if (blockdev.empty()) {
700 return -1;
701 }
702
703 // Stash directory should be different for each partition to avoid conflicts
704 // when updating multiple partitions at the same time, so we use the hash of
705 // the block device name as the base directory
706 uint8_t digest[SHA_DIGEST_LENGTH];
707 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
708 base = print_sha1(digest);
709
710 std::string dirname = GetStashFileName(base, "", "");
711 struct stat sb;
712 int res = stat(dirname.c_str(), &sb);
713 size_t max_stash_size = maxblocks * BLOCKSIZE;
714
715 if (res == -1 && errno != ENOENT) {
716 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
717 strerror(errno));
718 return -1;
719 } else if (res != 0) {
720 LOG(INFO) << "creating stash " << dirname;
721 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
722
723 if (res != 0) {
724 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
725 strerror(errno));
726 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000727 }
728
Tianjie Xua946b9e2017-03-21 16:24:57 -0700729 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
730 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s\n", dirname.c_str(),
731 strerror(errno));
732 return -1;
733 }
734
Tao Bao51412212016-12-28 14:44:05 -0800735 if (CacheSizeCheck(max_stash_size) != 0) {
736 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
737 max_stash_size);
738 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000739 }
740
Tao Bao51412212016-12-28 14:44:05 -0800741 return 1; // Created directory
742 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000743
Tao Bao51412212016-12-28 14:44:05 -0800744 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000745
Tao Baoec8272f2017-03-15 17:39:01 -0700746 // If the directory already exists, calculate the space already allocated to stash files and check
747 // if there's enough for all required blocks. Delete any partially completed stash files first.
748 EnumerateStash(dirname, [](const std::string& fn) {
749 if (android::base::EndsWith(fn, ".partial")) {
750 DeleteFile(fn);
751 }
752 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000753
Tao Bao51412212016-12-28 14:44:05 -0800754 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700755 EnumerateStash(dirname, [&existing](const std::string& fn) {
756 if (fn.empty()) return;
757 struct stat sb;
758 if (stat(fn.c_str(), &sb) == -1) {
759 PLOG(ERROR) << "stat \"" << fn << "\" failed";
760 return;
761 }
762 existing += static_cast<size_t>(sb.st_size);
763 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000764
Tao Bao51412212016-12-28 14:44:05 -0800765 if (max_stash_size > existing) {
766 size_t needed = max_stash_size - existing;
767 if (CacheSizeCheck(needed) != 0) {
768 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
769 needed);
770 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000771 }
Tao Bao51412212016-12-28 14:44:05 -0800772 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000773
Tao Bao51412212016-12-28 14:44:05 -0800774 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000775}
776
Tao Baobaad2d42015-12-06 16:56:27 -0800777static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700778 if (base.empty() || id.empty()) {
779 return -1;
780 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000781
Tao Baoec8272f2017-03-15 17:39:01 -0700782 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000783
Tao Baoec8272f2017-03-15 17:39:01 -0700784 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700785}
786
Tao Baobf5b77d2017-03-30 16:57:29 -0700787// Source contains packed data, which we want to move to the locations given in locs in the dest
788// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700789static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700790 const std::vector<uint8_t>& source) {
791 const uint8_t* from = source.data();
792 uint8_t* to = dest.data();
793 size_t start = locs.blocks();
794 // Must do the movement backward.
795 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
796 size_t blocks = it->second - it->first;
797 start -= blocks;
798 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
799 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700800}
801
Tao Baod2aecd42017-03-23 14:43:44 -0700802/**
803 * We expect to parse the remainder of the parameter tokens as one of:
804 *
805 * <src_block_count> <src_range>
806 * (loads data from source image only)
807 *
808 * <src_block_count> - <[stash_id:stash_range] ...>
809 * (loads data from stashes only)
810 *
811 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
812 * (loads data from both source image and stashes)
813 *
814 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
815 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
816 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
817 * LoadStash.
818 */
819static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
820 bool* overlap) {
821 CHECK(src_blocks != nullptr);
822 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700823
Tao Baod2aecd42017-03-23 14:43:44 -0700824 // <src_block_count>
825 const std::string& token = params.tokens[params.cpos++];
826 if (!android::base::ParseUint(token, src_blocks)) {
827 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
828 return -1;
829 }
Tao Baobaad2d42015-12-06 16:56:27 -0800830
Tao Baod2aecd42017-03-23 14:43:44 -0700831 allocate(*src_blocks * BLOCKSIZE, params.buffer);
832
833 // "-" or <src_range> [<src_loc>]
834 if (params.tokens[params.cpos] == "-") {
835 // no source ranges, only stashes
836 params.cpos++;
837 } else {
Tao Bao8f237572017-03-26 13:36:49 -0700838 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
839 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -0700840
841 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
842 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -0800843 }
844
Tao Baod2aecd42017-03-23 14:43:44 -0700845 if (params.cpos >= params.tokens.size()) {
846 // no stashes, only source range
847 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -0800848 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700849
Tao Bao8f237572017-03-26 13:36:49 -0700850 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Baod2aecd42017-03-23 14:43:44 -0700851 MoveRange(params.buffer, locs, params.buffer);
852 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700853
Tao Baod2aecd42017-03-23 14:43:44 -0700854 // <[stash_id:stash_range]>
855 while (params.cpos < params.tokens.size()) {
856 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
857 // in the source block that stashed data should go.
858 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
859 if (tokens.size() != 2) {
860 LOG(ERROR) << "invalid parameter";
861 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700862 }
863
Tao Baod2aecd42017-03-23 14:43:44 -0700864 std::vector<uint8_t> stash;
865 if (LoadStash(params, tokens[0], false, nullptr, stash, true) == -1) {
866 // These source blocks will fail verification if used later, but we
867 // will let the caller decide if this is a fatal failure
868 LOG(ERROR) << "failed to load stash " << tokens[0];
869 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +0000870 }
871
Tao Bao8f237572017-03-26 13:36:49 -0700872 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Baod2aecd42017-03-23 14:43:44 -0700873 MoveRange(params.buffer, locs, stash);
874 }
875
876 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000877}
878
Tao Bao33567772017-03-13 14:57:34 -0700879/**
880 * Do a source/target load for move/bsdiff/imgdiff in version 3.
881 *
882 * We expect to parse the remainder of the parameter tokens as one of:
883 *
884 * <tgt_range> <src_block_count> <src_range>
885 * (loads data from source image only)
886 *
887 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
888 * (loads data from stashes only)
889 *
890 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
891 * (loads data from both source image and stashes)
892 *
Tao Baod2aecd42017-03-23 14:43:44 -0700893 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
894 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -0700895 * verification fails in a way that the update cannot be resumed anymore.
896 *
897 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
898 * the return value is -1 and the command should be aborted.
899 *
900 * If the return value is 1, the command has already been completed according to the contents of the
901 * target blocks, and should not be performed again.
902 *
903 * If the return value is 0, source blocks have expected content and the command can be performed.
904 */
Tao Baod2aecd42017-03-23 14:43:44 -0700905static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
906 bool onehash, bool* overlap) {
907 CHECK(src_blocks != nullptr);
908 CHECK(overlap != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000909
Tao Baod2aecd42017-03-23 14:43:44 -0700910 if (params.cpos >= params.tokens.size()) {
911 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -0700912 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -0700913 }
914
915 std::string srchash = params.tokens[params.cpos++];
916 std::string tgthash;
917
918 if (onehash) {
919 tgthash = srchash;
920 } else {
921 if (params.cpos >= params.tokens.size()) {
922 LOG(ERROR) << "missing target hash";
923 return -1;
924 }
925 tgthash = params.tokens[params.cpos++];
926 }
927
928 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
929 // "-"/<src_range>.
930 if (params.cpos + 2 >= params.tokens.size()) {
931 LOG(ERROR) << "invalid parameters";
932 return -1;
933 }
934
935 // <tgt_range>
Tao Bao8f237572017-03-26 13:36:49 -0700936 tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Baod2aecd42017-03-23 14:43:44 -0700937
Tao Baobf5b77d2017-03-30 16:57:29 -0700938 std::vector<uint8_t> tgtbuffer(tgt.blocks() * BLOCKSIZE);
Tao Baod2aecd42017-03-23 14:43:44 -0700939 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
940 return -1;
941 }
942
943 // Return now if target blocks already have expected content.
Tao Baobf5b77d2017-03-30 16:57:29 -0700944 if (VerifyBlocks(tgthash, tgtbuffer, tgt.blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -0700945 return 1;
946 }
947
948 // Load source blocks.
949 if (LoadSourceBlocks(params, tgt, src_blocks, overlap) == -1) {
950 return -1;
951 }
952
953 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
954 // If source and target blocks overlap, stash the source blocks so we can
955 // resume from possible write errors. In verify mode, we can skip stashing
956 // because the source blocks won't be overwritten.
957 if (*overlap && params.canwrite) {
958 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
959
960 bool stash_exists = false;
961 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
962 &stash_exists) != 0) {
963 LOG(ERROR) << "failed to stash overlapping source blocks";
964 return -1;
965 }
966
967 params.stashed += *src_blocks;
968 // Can be deleted when the write has completed.
969 if (!stash_exists) {
970 params.freestash = srchash;
971 }
972 }
973
974 // Source blocks have expected content, command can proceed.
975 return 0;
976 }
977
978 if (*overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
979 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
980 // from an interrupted command, so we don't know if the stash can safely be deleted after this
981 // command.
982 return 0;
983 }
984
985 // Valid source data not available, update cannot be resumed.
986 LOG(ERROR) << "partition has unexpected contents";
987 PrintHashForCorruptedSourceBlocks(params, params.buffer);
988
989 params.isunresumable = true;
990
991 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000992}
993
Tao Bao0940fe12015-08-27 16:41:21 -0700994static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -0700995 size_t blocks = 0;
996 bool overlap = false;
997 RangeSet tgt;
Tao Baod2aecd42017-03-23 14:43:44 -0700998 int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +0000999
Tao Bao33567772017-03-13 14:57:34 -07001000 if (status == -1) {
1001 LOG(ERROR) << "failed to read blocks for move";
1002 return -1;
1003 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001004
Tao Bao33567772017-03-13 14:57:34 -07001005 if (status == 0) {
1006 params.foundwrites = true;
1007 } else if (params.foundwrites) {
1008 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1009 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001010
Tao Bao33567772017-03-13 14:57:34 -07001011 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001012 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001013 LOG(INFO) << " moving " << blocks << " blocks";
1014
1015 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1016 return -1;
1017 }
1018 } else {
1019 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001020 }
Tao Bao33567772017-03-13 14:57:34 -07001021 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001022
Tao Bao33567772017-03-13 14:57:34 -07001023 if (!params.freestash.empty()) {
1024 FreeStash(params.stashbase, params.freestash);
1025 params.freestash.clear();
1026 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001027
Tao Baobf5b77d2017-03-30 16:57:29 -07001028 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001029
Tao Bao33567772017-03-13 14:57:34 -07001030 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001031}
1032
Tao Bao0940fe12015-08-27 16:41:21 -07001033static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001034 // <stash_id> <src_range>
1035 if (params.cpos + 1 >= params.tokens.size()) {
1036 LOG(ERROR) << "missing id and/or src range fields in stash command";
1037 return -1;
1038 }
1039
1040 const std::string& id = params.tokens[params.cpos++];
1041 size_t blocks = 0;
1042 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1043 // Stash file already exists and has expected contents. Do not read from source again, as the
1044 // source may have been already overwritten during a previous attempt.
1045 return 0;
1046 }
1047
Tao Bao8f237572017-03-26 13:36:49 -07001048 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Baobcf46492017-03-23 15:28:20 -07001049
Tao Baobf5b77d2017-03-30 16:57:29 -07001050 allocate(src.blocks() * BLOCKSIZE, params.buffer);
Tao Baobcf46492017-03-23 15:28:20 -07001051 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1052 return -1;
1053 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001054 blocks = src.blocks();
Tao Baobcf46492017-03-23 15:28:20 -07001055 stash_map[id] = src;
1056
1057 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1058 // Source blocks have unexpected contents. If we actually need this data later, this is an
1059 // unrecoverable error. However, the command that uses the data may have already completed
1060 // previously, so the possible failure will occur during source block verification.
1061 LOG(ERROR) << "failed to load source blocks for stash " << id;
1062 return 0;
1063 }
1064
1065 // In verify mode, we don't need to stash any blocks.
1066 if (!params.canwrite) {
1067 return 0;
1068 }
1069
1070 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
1071 params.stashed += blocks;
1072 return WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001073}
1074
Tao Bao0940fe12015-08-27 16:41:21 -07001075static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001076 // <stash_id>
1077 if (params.cpos >= params.tokens.size()) {
1078 LOG(ERROR) << "missing stash id in free command";
1079 return -1;
1080 }
Tao Baobaad2d42015-12-06 16:56:27 -08001081
Tao Baobcf46492017-03-23 15:28:20 -07001082 const std::string& id = params.tokens[params.cpos++];
1083 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001084
Tao Baobcf46492017-03-23 15:28:20 -07001085 if (params.createdstash || params.canwrite) {
1086 return FreeStash(params.stashbase, id);
1087 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001088
Tao Baobcf46492017-03-23 15:28:20 -07001089 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001090}
1091
Tao Bao0940fe12015-08-27 16:41:21 -07001092static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001093 if (params.cpos >= params.tokens.size()) {
1094 LOG(ERROR) << "missing target blocks for zero";
1095 return -1;
1096 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001097
Tao Baobf5b77d2017-03-30 16:57:29 -07001098 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1099
1100 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1101
1102 allocate(BLOCKSIZE, params.buffer);
1103 memset(params.buffer.data(), 0, BLOCKSIZE);
1104
1105 if (params.canwrite) {
1106 for (const auto& range : tgt) {
1107 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
1108 size_t size = (range.second - range.first) * BLOCKSIZE;
1109 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001110 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001111 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001112
Tao Baobf5b77d2017-03-30 16:57:29 -07001113 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1114 return -1;
1115 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001116
Tao Baobf5b77d2017-03-30 16:57:29 -07001117 for (size_t j = range.first; j < range.second; ++j) {
1118 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1119 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001120 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001121 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001122 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001123 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001124
Tao Baobf5b77d2017-03-30 16:57:29 -07001125 if (params.cmdname[0] == 'z') {
1126 // Update only for the zero command, as the erase command will call
1127 // this if DEBUG_ERASE is defined.
1128 params.written += tgt.blocks();
1129 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001130
Tao Baobf5b77d2017-03-30 16:57:29 -07001131 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001132}
1133
Tao Bao0940fe12015-08-27 16:41:21 -07001134static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001135 if (params.cpos >= params.tokens.size()) {
1136 LOG(ERROR) << "missing target blocks for new";
1137 return -1;
1138 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001139
Tao Bao8f237572017-03-26 13:36:49 -07001140 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao60a70af2017-03-26 14:03:52 -07001141
1142 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001143 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001144
1145 RangeSinkWriter writer(params.fd, tgt);
1146 pthread_mutex_lock(&params.nti.mu);
1147 params.nti.writer = &writer;
1148 pthread_cond_broadcast(&params.nti.cv);
1149
1150 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001151 if (!params.nti.receiver_available) {
1152 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1153 << " bytes of new data";
1154 pthread_mutex_unlock(&params.nti.mu);
1155 return -1;
1156 }
Tao Bao60a70af2017-03-26 14:03:52 -07001157 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001158 }
1159
Tao Bao60a70af2017-03-26 14:03:52 -07001160 pthread_mutex_unlock(&params.nti.mu);
1161 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001162
Tao Baobf5b77d2017-03-30 16:57:29 -07001163 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001164
Tao Bao60a70af2017-03-26 14:03:52 -07001165 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001166}
1167
Tao Bao0940fe12015-08-27 16:41:21 -07001168static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001169 // <offset> <length>
1170 if (params.cpos + 1 >= params.tokens.size()) {
1171 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1172 return -1;
1173 }
Tao Bao0940fe12015-08-27 16:41:21 -07001174
Tao Baoc0e1c462017-02-01 10:20:10 -08001175 size_t offset;
1176 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1177 LOG(ERROR) << "invalid patch offset";
1178 return -1;
1179 }
Tao Bao0940fe12015-08-27 16:41:21 -07001180
Tao Baoc0e1c462017-02-01 10:20:10 -08001181 size_t len;
1182 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1183 LOG(ERROR) << "invalid patch len";
1184 return -1;
1185 }
Tao Bao0940fe12015-08-27 16:41:21 -07001186
Tao Baoc0e1c462017-02-01 10:20:10 -08001187 RangeSet tgt;
1188 size_t blocks = 0;
1189 bool overlap = false;
1190 int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
Tao Bao0940fe12015-08-27 16:41:21 -07001191
Tao Baoc0e1c462017-02-01 10:20:10 -08001192 if (status == -1) {
1193 LOG(ERROR) << "failed to read blocks for diff";
1194 return -1;
1195 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001196
Tao Baoc0e1c462017-02-01 10:20:10 -08001197 if (status == 0) {
1198 params.foundwrites = true;
1199 } else if (params.foundwrites) {
1200 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1201 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001202
Tao Baoc0e1c462017-02-01 10:20:10 -08001203 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001204 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001205 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001206 Value patch_value(
1207 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001208
Tao Bao60a70af2017-03-26 14:03:52 -07001209 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001210 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao60a70af2017-03-26 14:03:52 -07001211 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1212 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1213 std::placeholders::_2),
1214 nullptr, nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001215 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001216 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001217 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001218 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001219 } else {
Tao Bao60a70af2017-03-26 14:03:52 -07001220 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1221 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1222 std::placeholders::_2),
1223 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001224 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001225 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001226 return -1;
1227 }
1228 }
1229
1230 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001231 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001232 LOG(ERROR) << "range sink underrun?";
1233 }
1234 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001235 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001236 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001237 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001238 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001239
Tao Baoc0e1c462017-02-01 10:20:10 -08001240 if (!params.freestash.empty()) {
1241 FreeStash(params.stashbase, params.freestash);
1242 params.freestash.clear();
1243 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001244
Tao Baobf5b77d2017-03-30 16:57:29 -07001245 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001246
Tao Baoc0e1c462017-02-01 10:20:10 -08001247 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001248}
1249
Tao Bao0940fe12015-08-27 16:41:21 -07001250static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001251 if (DEBUG_ERASE) {
1252 return PerformCommandZero(params);
1253 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001254
Tao Baobf5b77d2017-03-30 16:57:29 -07001255 struct stat sb;
1256 if (fstat(params.fd, &sb) == -1) {
1257 PLOG(ERROR) << "failed to fstat device to erase";
1258 return -1;
1259 }
1260
1261 if (!S_ISBLK(sb.st_mode)) {
1262 LOG(ERROR) << "not a block device; skipping erase";
1263 return -1;
1264 }
1265
1266 if (params.cpos >= params.tokens.size()) {
1267 LOG(ERROR) << "missing target blocks for erase";
1268 return -1;
1269 }
1270
1271 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1272
1273 if (params.canwrite) {
1274 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1275
1276 for (const auto& range : tgt) {
1277 uint64_t blocks[2];
1278 // offset in bytes
1279 blocks[0] = range.first * static_cast<uint64_t>(BLOCKSIZE);
1280 // length in bytes
1281 blocks[1] = (range.second - range.first) * static_cast<uint64_t>(BLOCKSIZE);
1282
1283 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
1284 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001285 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001286 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001287 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001288 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001289
Tao Baobf5b77d2017-03-30 16:57:29 -07001290 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001291}
1292
1293// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001294typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001295
Tao Bao612336d2015-08-27 16:41:21 -07001296struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001297 const char* name;
1298 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001299};
Sami Tolvanen90221202014-12-09 16:39:47 +00001300
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001301// args:
1302// - block device (or file) to modify in-place
1303// - transfer list (blob)
1304// - new data stream (filename within package.zip)
1305// - patch stream (filename within package.zip, must be uncompressed)
1306
Tianjie Xuc4447322017-03-06 14:44:59 -08001307static Value* PerformBlockImageUpdate(const char* name, State* state,
1308 const std::vector<std::unique_ptr<Expr>>& argv,
1309 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001310 CommandParameters params = {};
1311 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001312
Tao Bao33567772017-03-13 14:57:34 -07001313 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1314 if (state->is_retry) {
1315 is_retry = true;
1316 LOG(INFO) << "This update is a retry.";
1317 }
1318 if (argv.size() != 4) {
1319 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1320 argv.size());
1321 return StringValue("");
1322 }
1323
1324 std::vector<std::unique_ptr<Value>> args;
1325 if (!ReadValueArgs(state, argv, &args)) {
1326 return nullptr;
1327 }
1328
Tao Baoc97edcb2017-03-31 01:18:13 -07001329 const std::unique_ptr<Value>& blockdev_filename = args[0];
1330 const std::unique_ptr<Value>& transfer_list_value = args[1];
1331 const std::unique_ptr<Value>& new_data_fn = args[2];
1332 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001333
1334 if (blockdev_filename->type != VAL_STRING) {
1335 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1336 return StringValue("");
1337 }
1338 if (transfer_list_value->type != VAL_BLOB) {
1339 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1340 return StringValue("");
1341 }
1342 if (new_data_fn->type != VAL_STRING) {
1343 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1344 return StringValue("");
1345 }
1346 if (patch_data_fn->type != VAL_STRING) {
1347 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1348 return StringValue("");
1349 }
1350
1351 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1352 if (ui == nullptr) {
1353 return StringValue("");
1354 }
1355
1356 FILE* cmd_pipe = ui->cmd_pipe;
1357 ZipArchiveHandle za = ui->package_zip;
1358
1359 if (cmd_pipe == nullptr || za == nullptr) {
1360 return StringValue("");
1361 }
1362
1363 ZipString path_data(patch_data_fn->data.c_str());
1364 ZipEntry patch_entry;
1365 if (FindEntry(za, path_data, &patch_entry) != 0) {
1366 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1367 return StringValue("");
1368 }
1369
1370 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1371 ZipString new_data(new_data_fn->data.c_str());
1372 ZipEntry new_entry;
1373 if (FindEntry(za, new_data, &new_entry) != 0) {
1374 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1375 return StringValue("");
1376 }
1377
1378 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1379 if (params.fd == -1) {
1380 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1381 return StringValue("");
1382 }
1383
1384 if (params.canwrite) {
1385 params.nti.za = za;
1386 params.nti.entry = new_entry;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001387 params.nti.receiver_available = true;
Tao Bao33567772017-03-13 14:57:34 -07001388
1389 pthread_mutex_init(&params.nti.mu, nullptr);
1390 pthread_cond_init(&params.nti.cv, nullptr);
1391 pthread_attr_t attr;
1392 pthread_attr_init(&attr);
1393 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1394
1395 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1396 if (error != 0) {
1397 PLOG(ERROR) << "pthread_create failed";
1398 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001399 }
Tao Bao33567772017-03-13 14:57:34 -07001400 }
1401
1402 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1403 if (lines.size() < 2) {
1404 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1405 lines.size());
1406 return StringValue("");
1407 }
1408
1409 // First line in transfer list is the version number.
1410 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1411 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1412 return StringValue("");
1413 }
1414
1415 LOG(INFO) << "blockimg version is " << params.version;
1416
1417 // Second line in transfer list is the total number of blocks we expect to write.
1418 size_t total_blocks;
1419 if (!android::base::ParseUint(lines[1], &total_blocks)) {
1420 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
1421 return StringValue("");
1422 }
1423
1424 if (total_blocks == 0) {
1425 return StringValue("t");
1426 }
1427
1428 size_t start = 2;
1429 if (lines.size() < 4) {
1430 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1431 lines.size());
1432 return StringValue("");
1433 }
1434
1435 // Third line is how many stash entries are needed simultaneously.
1436 LOG(INFO) << "maximum stash entries " << lines[2];
1437
1438 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1439 size_t stash_max_blocks;
1440 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
1441 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1442 lines[3].c_str());
1443 return StringValue("");
1444 }
1445
1446 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
1447 if (res == -1) {
1448 return StringValue("");
1449 }
1450
1451 params.createdstash = res;
1452
1453 start += 2;
1454
1455 // Build a map of the available commands
1456 std::unordered_map<std::string, const Command*> cmd_map;
1457 for (size_t i = 0; i < cmdcount; ++i) {
1458 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1459 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
1460 return StringValue(strdup(""));
1461 }
1462 cmd_map[commands[i].name] = &commands[i];
1463 }
1464
1465 int rc = -1;
1466
1467 // Subsequent lines are all individual transfer commands
1468 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1469 const std::string& line(*it);
1470 if (line.empty()) continue;
1471
1472 params.tokens = android::base::Split(line, " ");
1473 params.cpos = 0;
1474 params.cmdname = params.tokens[params.cpos++].c_str();
1475 params.cmdline = line.c_str();
1476
1477 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1478 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1479 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001480 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001481
Tao Bao33567772017-03-13 14:57:34 -07001482 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001483
Tao Bao33567772017-03-13 14:57:34 -07001484 if (cmd->f != nullptr && cmd->f(params) == -1) {
1485 LOG(ERROR) << "failed to execute command [" << line << "]";
1486 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001487 }
1488
Sami Tolvanen90221202014-12-09 16:39:47 +00001489 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001490 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001491 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001492 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001493 goto pbiudone;
1494 }
1495 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1496 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001497 }
Tao Bao33567772017-03-13 14:57:34 -07001498 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001499
Tao Bao33567772017-03-13 14:57:34 -07001500 if (params.canwrite) {
1501 pthread_join(params.thread, nullptr);
1502
1503 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1504 LOG(INFO) << "stashed " << params.stashed << " blocks";
1505 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1506
1507 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1508 if (partition != nullptr && *(partition + 1) != 0) {
1509 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1510 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1511 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001512 }
Tao Bao33567772017-03-13 14:57:34 -07001513 // Delete stash only after successfully completing the update, as it may contain blocks needed
1514 // to complete the update later.
1515 DeleteStash(params.stashbase);
1516 } else {
1517 LOG(INFO) << "verified partition contents; update may be resumed";
1518 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001519
Tao Bao33567772017-03-13 14:57:34 -07001520 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001521
Tao Bao33567772017-03-13 14:57:34 -07001522pbiudone:
1523 if (ota_fsync(params.fd) == -1) {
1524 failure_type = kFsyncFailure;
1525 PLOG(ERROR) << "fsync failed";
1526 }
1527 // params.fd will be automatically closed because it's a unique_fd.
1528
1529 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1530 // created the stash.
1531 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1532 DeleteStash(params.stashbase);
1533 }
1534
1535 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1536 state->cause_code = failure_type;
1537 }
1538
1539 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001540}
1541
Tao Bao33567772017-03-13 14:57:34 -07001542/**
1543 * The transfer list is a text file containing commands to transfer data from one place to another
1544 * on the target partition. We parse it and execute the commands in order:
1545 *
1546 * zero [rangeset]
1547 * - Fill the indicated blocks with zeros.
1548 *
1549 * new [rangeset]
1550 * - Fill the blocks with data read from the new_data file.
1551 *
1552 * erase [rangeset]
1553 * - Mark the given blocks as empty.
1554 *
1555 * move <...>
1556 * bsdiff <patchstart> <patchlen> <...>
1557 * imgdiff <patchstart> <patchlen> <...>
1558 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1559 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1560 *
1561 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1562 *
1563 * stash <stash_id> <src_range>
1564 * - Load the given source range and stash the data in the given slot of the stash table.
1565 *
1566 * free <stash_id>
1567 * - Free the given stash data.
1568 *
1569 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1570 * a patch or move) after it has been written.
1571 *
1572 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1573 * in a move/bsdiff/imgdiff command.
1574 *
1575 * Within one command the source and target ranges may overlap so in general we need to read the
1576 * entire source into memory before writing anything to the target blocks.
1577 *
1578 * All the patch data is concatenated into one patch_data file in the update package. It must be
1579 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1580 * already compressed, we lose very little by not compressing their concatenation.)
1581 *
1582 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1583 * additional hashes before the range parameters, which are used to check if the command has already
1584 * been completed and verify the integrity of the source data.
1585 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001586Value* BlockImageVerifyFn(const char* name, State* state,
1587 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001588 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001589 const Command commands[] = {
1590 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001591 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001592 { "free", PerformCommandFree },
1593 { "imgdiff", PerformCommandDiff },
1594 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001595 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001596 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001597 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001598 };
1599
1600 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001601 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001602 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001603}
1604
Tianjie Xuc4447322017-03-06 14:44:59 -08001605Value* BlockImageUpdateFn(const char* name, State* state,
1606 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001607 const Command commands[] = {
1608 { "bsdiff", PerformCommandDiff },
1609 { "erase", PerformCommandErase },
1610 { "free", PerformCommandFree },
1611 { "imgdiff", PerformCommandDiff },
1612 { "move", PerformCommandMove },
1613 { "new", PerformCommandNew },
1614 { "stash", PerformCommandStash },
1615 { "zero", PerformCommandZero }
1616 };
1617
Tianjie Xuc4447322017-03-06 14:44:59 -08001618 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001619 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001620}
1621
Tianjie Xuc4447322017-03-06 14:44:59 -08001622Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001623 if (argv.size() != 2) {
1624 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
1625 return StringValue("");
1626 }
1627
1628 std::vector<std::unique_ptr<Value>> args;
1629 if (!ReadValueArgs(state, argv, &args)) {
1630 return nullptr;
1631 }
1632
1633 const std::unique_ptr<Value>& blockdev_filename = args[0];
1634 const std::unique_ptr<Value>& ranges = args[1];
1635
1636 if (blockdev_filename->type != VAL_STRING) {
1637 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1638 return StringValue("");
1639 }
1640 if (ranges->type != VAL_STRING) {
1641 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
1642 return StringValue("");
1643 }
1644
1645 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
1646 if (fd == -1) {
1647 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", blockdev_filename->data.c_str(),
1648 strerror(errno));
1649 return StringValue("");
1650 }
1651
1652 RangeSet rs = RangeSet::Parse(ranges->data);
1653
1654 SHA_CTX ctx;
1655 SHA1_Init(&ctx);
1656
1657 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Baobf5b77d2017-03-30 16:57:29 -07001658 for (const auto& range : rs) {
1659 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001660 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
1661 strerror(errno));
1662 return StringValue("");
1663 }
1664
Tao Baobf5b77d2017-03-30 16:57:29 -07001665 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001666 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1667 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data.c_str(),
1668 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08001669 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07001670 }
1671
1672 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08001673 }
Tao Baoc97edcb2017-03-31 01:18:13 -07001674 }
1675 uint8_t digest[SHA_DIGEST_LENGTH];
1676 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08001677
Tao Baoc97edcb2017-03-31 01:18:13 -07001678 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001679}
1680
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001681// This function checks if a device has been remounted R/W prior to an incremental
1682// OTA update. This is an common cause of update abortion. The function reads the
1683// 1st block of each partition and check for mounting time/count. It return string "t"
1684// if executes successfully and an empty string otherwise.
1685
Tianjie Xuc4447322017-03-06 14:44:59 -08001686Value* CheckFirstBlockFn(const char* name, State* state,
1687 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001688 if (argv.size() != 1) {
1689 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1690 argv.size());
1691 return StringValue("");
1692 }
Tianjie Xuc4447322017-03-06 14:44:59 -08001693
Tao Baoc97edcb2017-03-31 01:18:13 -07001694 std::vector<std::unique_ptr<Value>> args;
1695 if (!ReadValueArgs(state, argv, &args)) {
1696 return nullptr;
1697 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001698
Tao Baoc97edcb2017-03-31 01:18:13 -07001699 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001700
Tao Baoc97edcb2017-03-31 01:18:13 -07001701 if (arg_filename->type != VAL_STRING) {
1702 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
1703 return StringValue("");
1704 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001705
Tao Baoc97edcb2017-03-31 01:18:13 -07001706 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
1707 if (fd == -1) {
1708 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
1709 strerror(errno));
1710 return StringValue("");
1711 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001712
Tao Baobf5b77d2017-03-30 16:57:29 -07001713 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07001714 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001715
Tao Baoc97edcb2017-03-31 01:18:13 -07001716 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
1717 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
1718 strerror(errno));
1719 return StringValue("");
1720 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001721
Tao Baoc97edcb2017-03-31 01:18:13 -07001722 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1723 // Super block starts from block 0, offset 0x400
1724 // 0x2C: len32 Mount time
1725 // 0x30: len32 Write time
1726 // 0x34: len16 Number of mounts since the last fsck
1727 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001728
Tao Baoc97edcb2017-03-31 01:18:13 -07001729 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
1730 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001731
Tao Baoc97edcb2017-03-31 01:18:13 -07001732 if (mount_count > 0) {
1733 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
1734 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1735 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001736
Tao Baoc97edcb2017-03-31 01:18:13 -07001737 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001738}
1739
Tianjie Xuc4447322017-03-06 14:44:59 -08001740Value* BlockImageRecoverFn(const char* name, State* state,
1741 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001742 if (argv.size() != 2) {
1743 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
1744 argv.size());
1745 return StringValue("");
1746 }
1747
1748 std::vector<std::unique_ptr<Value>> args;
1749 if (!ReadValueArgs(state, argv, &args)) {
1750 return nullptr;
1751 }
1752
1753 const std::unique_ptr<Value>& filename = args[0];
1754 const std::unique_ptr<Value>& ranges = args[1];
1755
1756 if (filename->type != VAL_STRING) {
1757 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
1758 return StringValue("");
1759 }
1760 if (ranges->type != VAL_STRING) {
1761 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
1762 return StringValue("");
1763 }
1764
1765 // Output notice to log when recover is attempted
1766 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
1767
1768 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
1769 fec::io fh(filename->data, O_RDWR);
1770
1771 if (!fh) {
1772 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
1773 strerror(errno));
1774 return StringValue("");
1775 }
1776
1777 if (!fh.has_ecc() || !fh.has_verity()) {
1778 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
1779 return StringValue("");
1780 }
1781
1782 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07001783 if (!fh.get_status(status)) {
1784 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
1785 return StringValue("");
1786 }
1787
Tao Baoc97edcb2017-03-31 01:18:13 -07001788 uint8_t buffer[BLOCKSIZE];
Tao Baobf5b77d2017-03-30 16:57:29 -07001789 for (const auto& range : RangeSet::Parse(ranges->data)) {
1790 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001791 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07001792 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001793 continue;
1794 }
1795
Tao Baobf5b77d2017-03-30 16:57:29 -07001796 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001797 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
1798 filename->data.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08001799 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07001800 }
1801
1802 // If we want to be able to recover from a situation where rewriting a corrected
1803 // block doesn't guarantee the same data will be returned when re-read later, we
1804 // can save a copy of corrected blocks to /cache. Note:
1805 //
1806 // 1. Maximum space required from /cache is the same as the maximum number of
1807 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1808 // this would be ~16 MiB, for example.
1809 //
1810 // 2. To find out if this block was corrupted, call fec_get_status after each
1811 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08001812 }
Tao Baoc97edcb2017-03-31 01:18:13 -07001813 }
1814 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
1815 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001816}
1817
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001818void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07001819 RegisterFunction("block_image_verify", BlockImageVerifyFn);
1820 RegisterFunction("block_image_update", BlockImageUpdateFn);
1821 RegisterFunction("block_image_recover", BlockImageRecoverFn);
1822 RegisterFunction("check_first_block", CheckFirstBlockFn);
1823 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001824}