blob: 55218b02381e5339dc34c1f738f40594ef81ed26 [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>
Sami Tolvanen90221202014-12-09 16:39:47 +000018#include <dirent.h>
Tao Bao641fa972018-04-25 18:59:40 -070019#include <errno.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>
Tao Bao641fa972018-04-25 18:59:40 -070028#include <sys/ioctl.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000029#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070030#include <sys/types.h>
31#include <sys/wait.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070032#include <time.h>
33#include <unistd.h>
34
Tao Baoec8272f2017-03-15 17:39:01 -070035#include <functional>
Tianjie Xu284752e2017-12-05 11:04:17 -080036#include <limits>
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
Tianjie Xu284752e2017-12-05 11:04:17 -080042#include <android-base/file.h>
Tao Bao039f2da2016-11-22 16:29:50 -080043#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080044#include <android-base/parseint.h>
Tianjie Xu58d59122019-05-03 01:05:04 -070045#include <android-base/stringprintf.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080046#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070047#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080048#include <applypatch/applypatch.h>
Tianjie Xu107a34f2017-06-29 17:04:21 -070049#include <brotli/decode.h>
Tao Bao641fa972018-04-25 18:59:40 -070050#include <fec/io.h>
Tao Bao51412212016-12-28 14:44:05 -080051#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070052#include <private/android_filesystem_config.h>
Tianjie Xu69ffa152018-08-01 16:40:00 -070053#include <verity/hash_tree_builder.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070054#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070055
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070056#include "edify/expr.h"
Tianjie Xu1536db82019-05-14 10:54:43 -070057#include "edify/updater_interface.h"
Yifan Hong63f52602019-01-11 13:52:33 -080058#include "otautil/dirutil.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070059#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070060#include "otautil/paths.h"
Tao Bao09e468f2017-09-29 14:39:33 -070061#include "otautil/print_sha1.h"
62#include "otautil/rangeset.h"
Tao Baoc3901232018-05-21 16:05:56 -070063#include "private/commands.h"
Tao Bao8f237572017-03-26 13:36:49 -070064#include "updater/install.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070065
Sami Tolvanene82fa182015-06-10 15:58:12 +000066// Set this to 0 to interpret 'erase' transfers to mean do a
67// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
68// erase to mean fill the region with zeroes.
69#define DEBUG_ERASE 0
70
Tao Bao51412212016-12-28 14:44:05 -080071static constexpr size_t BLOCKSIZE = 4096;
Tao Bao51412212016-12-28 14:44:05 -080072static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
73static constexpr mode_t STASH_FILE_MODE = 0600;
Yifan Hong8ff84d72018-12-19 16:21:55 -080074static constexpr mode_t MARKER_DIRECTORY_MODE = 0700;
Sami Tolvanen90221202014-12-09 16:39:47 +000075
Tianjie Xu16255832016-04-30 11:49:59 -070076static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070077static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070078static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070079
Tianjie Xu284752e2017-12-05 11:04:17 -080080static void DeleteLastCommandFile() {
Tao Bao641fa972018-04-25 18:59:40 -070081 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080082 if (unlink(last_command_file.c_str()) == -1 && errno != ENOENT) {
83 PLOG(ERROR) << "Failed to unlink: " << last_command_file;
84 }
85}
86
87// Parse the last command index of the last update and save the result to |last_command_index|.
88// Return true if we successfully read the index.
Tao Bao26efb0a2018-05-21 14:59:55 -070089static bool ParseLastCommandFile(size_t* last_command_index) {
Tao Bao641fa972018-04-25 18:59:40 -070090 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080091 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(last_command_file.c_str(), O_RDONLY)));
92 if (fd == -1) {
93 if (errno != ENOENT) {
94 PLOG(ERROR) << "Failed to open " << last_command_file;
95 return false;
96 }
97
98 LOG(INFO) << last_command_file << " doesn't exist.";
99 return false;
100 }
101
102 // Now that the last_command file exists, parse the last command index of previous update.
103 std::string content;
104 if (!android::base::ReadFdToString(fd.get(), &content)) {
105 LOG(ERROR) << "Failed to read: " << last_command_file;
106 return false;
107 }
108
109 std::vector<std::string> lines = android::base::Split(android::base::Trim(content), "\n");
110 if (lines.size() != 2) {
111 LOG(ERROR) << "Unexpected line counts in last command file: " << content;
112 return false;
113 }
114
Tom Cherry04e4afb2018-10-05 14:37:13 -0700115 if (!android::base::ParseUint(lines[0], last_command_index)) {
Tianjie Xu284752e2017-12-05 11:04:17 -0800116 LOG(ERROR) << "Failed to parse integer in: " << lines[0];
117 return false;
118 }
119
120 return true;
121}
122
Tao Bao864c6682018-05-07 11:38:25 -0700123static bool FsyncDir(const std::string& dirname) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700124 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_DIRECTORY)));
Tao Bao864c6682018-05-07 11:38:25 -0700125 if (dfd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700126 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Bao864c6682018-05-07 11:38:25 -0700127 PLOG(ERROR) << "Failed to open " << dirname;
128 return false;
129 }
130 if (fsync(dfd) == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700131 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Bao864c6682018-05-07 11:38:25 -0700132 PLOG(ERROR) << "Failed to fsync " << dirname;
133 return false;
134 }
135 return true;
136}
137
Tianjie Xuc2b2bb52018-05-15 15:09:59 -0700138// Update the last executed command index in the last_command_file.
Tao Bao26efb0a2018-05-21 14:59:55 -0700139static bool UpdateLastCommandIndex(size_t command_index, const std::string& command_string) {
Tao Bao641fa972018-04-25 18:59:40 -0700140 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -0800141 std::string last_command_tmp = last_command_file + ".tmp";
142 std::string content = std::to_string(command_index) + "\n" + command_string;
143 android::base::unique_fd wfd(
144 TEMP_FAILURE_RETRY(open(last_command_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0660)));
145 if (wfd == -1 || !android::base::WriteStringToFd(content, wfd)) {
146 PLOG(ERROR) << "Failed to update last command";
147 return false;
148 }
149
150 if (fsync(wfd) == -1) {
151 PLOG(ERROR) << "Failed to fsync " << last_command_tmp;
152 return false;
153 }
154
155 if (chown(last_command_tmp.c_str(), AID_SYSTEM, AID_SYSTEM) == -1) {
156 PLOG(ERROR) << "Failed to change owner for " << last_command_tmp;
157 return false;
158 }
159
160 if (rename(last_command_tmp.c_str(), last_command_file.c_str()) == -1) {
161 PLOG(ERROR) << "Failed to rename" << last_command_tmp;
162 return false;
163 }
164
Tao Bao864c6682018-05-07 11:38:25 -0700165 if (!FsyncDir(android::base::Dirname(last_command_file))) {
Tianjie Xu284752e2017-12-05 11:04:17 -0800166 return false;
167 }
168
Tao Bao864c6682018-05-07 11:38:25 -0700169 return true;
170}
171
Yifan Hong8ff84d72018-12-19 16:21:55 -0800172bool SetUpdatedMarker(const std::string& marker) {
173 auto dirname = android::base::Dirname(marker);
174 auto res = mkdir(dirname.c_str(), MARKER_DIRECTORY_MODE);
175 if (res == -1 && errno != EEXIST) {
176 PLOG(ERROR) << "Failed to create directory for marker: " << dirname;
177 return false;
178 }
179
Tao Bao864c6682018-05-07 11:38:25 -0700180 if (!android::base::WriteStringToFile("", marker)) {
181 PLOG(ERROR) << "Failed to write to marker file " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800182 return false;
183 }
Yifan Hong8ff84d72018-12-19 16:21:55 -0800184 if (!FsyncDir(dirname)) {
Tao Bao864c6682018-05-07 11:38:25 -0700185 return false;
186 }
Yifan Hong8ff84d72018-12-19 16:21:55 -0800187 LOG(INFO) << "Wrote updated marker to " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800188 return true;
189}
190
Yifan Hong363d6242019-01-04 11:14:19 -0800191static bool discard_blocks(int fd, off64_t offset, uint64_t size, bool force = false) {
192 // Don't discard blocks unless the update is a retry run or force == true
193 if (!is_retry && !force) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700194 return true;
Tao Baobf5b77d2017-03-30 16:57:29 -0700195 }
196
197 uint64_t args[2] = { static_cast<uint64_t>(offset), size };
198 if (ioctl(fd, BLKDISCARD, &args) == -1) {
Yifan Hong363d6242019-01-04 11:14:19 -0800199 // On devices that does not support BLKDISCARD, ignore the error.
200 if (errno == EOPNOTSUPP) {
201 return true;
202 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700203 PLOG(ERROR) << "BLKDISCARD ioctl failed";
204 return false;
205 }
206 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700207}
208
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700209static bool check_lseek(int fd, off64_t offset, int whence) {
210 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
211 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700212 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800213 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700214 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700215 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700216 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700217}
218
Tao Baode3bbb82018-05-30 16:14:14 -0700219static void allocate(size_t size, std::vector<uint8_t>* buffer) {
220 // If the buffer's big enough, reuse it.
221 if (size <= buffer->size()) return;
222 buffer->resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700223}
224
Tao Bao60a70af2017-03-26 14:03:52 -0700225/**
226 * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
227 * given RangeSet.
228 */
229class RangeSinkWriter {
230 public:
231 RangeSinkWriter(int fd, const RangeSet& tgt)
Tianjie Xu107a34f2017-06-29 17:04:21 -0700232 : fd_(fd),
233 tgt_(tgt),
234 next_range_(0),
235 current_range_left_(0),
236 bytes_written_(0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700237 CHECK_NE(tgt.size(), static_cast<size_t>(0));
Tao Bao60a70af2017-03-26 14:03:52 -0700238 };
Tao Bao0940fe12015-08-27 16:41:21 -0700239
Tao Bao60a70af2017-03-26 14:03:52 -0700240 bool Finished() const {
Tao Baobf5b77d2017-03-30 16:57:29 -0700241 return next_range_ == tgt_.size() && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700242 }
243
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700244 size_t AvailableSpace() const {
245 return tgt_.blocks() * BLOCKSIZE - bytes_written_;
246 }
247
248 // Return number of bytes written; and 0 indicates a writing failure.
249 size_t Write(const uint8_t* data, size_t size) {
Tao Bao60a70af2017-03-26 14:03:52 -0700250 if (Finished()) {
251 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
252 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700253 }
254
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700255 size_t written = 0;
Tao Bao60a70af2017-03-26 14:03:52 -0700256 while (size > 0) {
257 // Move to the next range as needed.
Tianjie Xu107a34f2017-06-29 17:04:21 -0700258 if (!SeekToOutputRange()) {
259 break;
Tao Bao60a70af2017-03-26 14:03:52 -0700260 }
Tao Baof7eb7602017-03-27 15:12:48 -0700261
Tao Bao60a70af2017-03-26 14:03:52 -0700262 size_t write_now = size;
263 if (current_range_left_ < write_now) {
264 write_now = current_range_left_;
265 }
Tao Baof7eb7602017-03-27 15:12:48 -0700266
Tianjie Xu22f11202018-08-27 10:50:31 -0700267 if (!android::base::WriteFully(fd_, data, write_now)) {
268 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
269 PLOG(ERROR) << "Failed to write " << write_now << " bytes of data";
Tao Baof7eb7602017-03-27 15:12:48 -0700270 break;
271 }
Tao Bao60a70af2017-03-26 14:03:52 -0700272
273 data += write_now;
274 size -= write_now;
275
276 current_range_left_ -= write_now;
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700277 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700278 }
Tao Bao60a70af2017-03-26 14:03:52 -0700279
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700280 bytes_written_ += written;
281 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700282 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700283
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700284 size_t BytesWritten() const {
285 return bytes_written_;
286 }
287
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700288 private:
Tianjie Xu107a34f2017-06-29 17:04:21 -0700289 // Set up the output cursor, move to next range if needed.
290 bool SeekToOutputRange() {
291 // We haven't finished the current range yet.
292 if (current_range_left_ != 0) {
293 return true;
294 }
295 // We can't write any more; let the write function return how many bytes have been written
296 // so far.
297 if (next_range_ >= tgt_.size()) {
298 return false;
299 }
300
301 const Range& range = tgt_[next_range_];
302 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
303 current_range_left_ = (range.second - range.first) * BLOCKSIZE;
304 next_range_++;
305
306 if (!discard_blocks(fd_, offset, current_range_left_)) {
307 return false;
308 }
309 if (!check_lseek(fd_, offset, SEEK_SET)) {
310 return false;
311 }
312 return true;
313 }
314
315 // The output file descriptor.
Tao Bao60a70af2017-03-26 14:03:52 -0700316 int fd_;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700317 // The destination ranges for the data.
Tao Bao60a70af2017-03-26 14:03:52 -0700318 const RangeSet& tgt_;
319 // The next range that we should write to.
320 size_t next_range_;
321 // The number of bytes to write before moving to the next range.
322 size_t current_range_left_;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700323 // Total bytes written by the writer.
324 size_t bytes_written_;
Tao Bao60a70af2017-03-26 14:03:52 -0700325};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700326
Tao Bao60a70af2017-03-26 14:03:52 -0700327/**
328 * All of the data for all the 'new' transfers is contained in one file in the update package,
329 * concatenated together in the order in which transfers.list will need it. We want to stream it out
330 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
331 * section until it's that transfer's turn to go.
332 *
333 * To achieve this, we expand the new data from the archive in a background thread, and block that
334 * threads 'receive uncompressed data' function until the main thread has reached a point where we
335 * want some new data to be written. We signal the background thread with the destination for the
336 * data and block the main thread, waiting for the background thread to complete writing that
337 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
338 * transfer.
339 *
340 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
341 * the main thread wants some data written, it sets writer to the destination location and signals
342 * the condition. When the background thread is done writing, it clears writer and signals the
343 * condition again.
344 */
Tao Bao0940fe12015-08-27 16:41:21 -0700345struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700346 ZipArchiveHandle za;
347 ZipEntry entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700348 bool brotli_compressed;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700349
Tianjie Xu107a34f2017-06-29 17:04:21 -0700350 std::unique_ptr<RangeSinkWriter> writer;
351 BrotliDecoderState* brotli_decoder_state;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700352 bool receiver_available;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700353
Tao Bao60a70af2017-03-26 14:03:52 -0700354 pthread_mutex_t mu;
355 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700356};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700357
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700358static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700359 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700360
Tao Bao60a70af2017-03-26 14:03:52 -0700361 while (size > 0) {
362 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
363 pthread_mutex_lock(&nti->mu);
364 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700365 // End the new data receiver if we encounter an error when performing block image update.
366 if (!nti->receiver_available) {
367 pthread_mutex_unlock(&nti->mu);
368 return false;
369 }
Tao Bao60a70af2017-03-26 14:03:52 -0700370 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700371 }
Tao Bao60a70af2017-03-26 14:03:52 -0700372 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700373
Tao Bao60a70af2017-03-26 14:03:52 -0700374 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
375 // disappear from nti.
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700376 size_t write_now = std::min(size, nti->writer->AvailableSpace());
377 if (nti->writer->Write(data, write_now) != write_now) {
378 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
Tianjie Xu107a34f2017-06-29 17:04:21 -0700379 return false;
380 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700381
382 data += write_now;
383 size -= write_now;
384
385 if (nti->writer->Finished()) {
386 // We have written all the bytes desired by this writer.
387
388 pthread_mutex_lock(&nti->mu);
389 nti->writer = nullptr;
390 pthread_cond_broadcast(&nti->cv);
391 pthread_mutex_unlock(&nti->mu);
392 }
393 }
394
395 return true;
396}
397
398static bool receive_brotli_new_data(const uint8_t* data, size_t size, void* cookie) {
399 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
400
401 while (size > 0 || BrotliDecoderHasMoreOutput(nti->brotli_decoder_state)) {
402 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
403 pthread_mutex_lock(&nti->mu);
404 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700405 // End the receiver if we encounter an error when performing block image update.
406 if (!nti->receiver_available) {
407 pthread_mutex_unlock(&nti->mu);
408 return false;
409 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700410 pthread_cond_wait(&nti->cv, &nti->mu);
411 }
412 pthread_mutex_unlock(&nti->mu);
413
414 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
415 // disappear from nti.
416
417 size_t buffer_size = std::min<size_t>(32768, nti->writer->AvailableSpace());
418 if (buffer_size == 0) {
419 LOG(ERROR) << "No space left in output range";
420 return false;
421 }
422 uint8_t buffer[buffer_size];
423 size_t available_in = size;
424 size_t available_out = buffer_size;
425 uint8_t* next_out = buffer;
426
427 // The brotli decoder will update |data|, |available_in|, |next_out| and |available_out|.
428 BrotliDecoderResult result = BrotliDecoderDecompressStream(
429 nti->brotli_decoder_state, &available_in, &data, &available_out, &next_out, nullptr);
430
431 if (result == BROTLI_DECODER_RESULT_ERROR) {
432 LOG(ERROR) << "Decompression failed with "
433 << BrotliDecoderErrorString(BrotliDecoderGetErrorCode(nti->brotli_decoder_state));
434 return false;
435 }
436
437 LOG(DEBUG) << "bytes to write: " << buffer_size - available_out << ", bytes consumed "
438 << size - available_in << ", decoder status " << result;
439
440 size_t write_now = buffer_size - available_out;
441 if (nti->writer->Write(buffer, write_now) != write_now) {
442 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
443 return false;
444 }
445
446 // Update the remaining size. The input data ptr is already updated by brotli decoder function.
447 size = available_in;
Tao Bao60a70af2017-03-26 14:03:52 -0700448
449 if (nti->writer->Finished()) {
450 // We have written all the bytes desired by this writer.
451
452 pthread_mutex_lock(&nti->mu);
453 nti->writer = nullptr;
454 pthread_cond_broadcast(&nti->cv);
455 pthread_mutex_unlock(&nti->mu);
456 }
457 }
458
459 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700460}
461
462static void* unzip_new_data(void* cookie) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700463 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700464 if (nti->brotli_compressed) {
465 ProcessZipEntryContents(nti->za, &nti->entry, receive_brotli_new_data, nti);
466 } else {
467 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
468 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700469 pthread_mutex_lock(&nti->mu);
470 nti->receiver_available = false;
471 if (nti->writer != nullptr) {
472 pthread_cond_broadcast(&nti->cv);
473 }
474 pthread_mutex_unlock(&nti->mu);
475 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700476}
477
Tao Baode3bbb82018-05-30 16:14:14 -0700478static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>* buffer, int fd) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700479 size_t p = 0;
Tao Bao43bfa6e2018-08-28 10:09:13 -0700480 for (const auto& [begin, end] : src) {
481 if (!check_lseek(fd, static_cast<off64_t>(begin) * BLOCKSIZE, SEEK_SET)) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700482 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000483 }
484
Tao Bao43bfa6e2018-08-28 10:09:13 -0700485 size_t size = (end - begin) * BLOCKSIZE;
Tianjie Xu22f11202018-08-27 10:50:31 -0700486 if (!android::base::ReadFully(fd, buffer->data() + p, size)) {
487 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
488 PLOG(ERROR) << "Failed to read " << size << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -0700489 return -1;
490 }
491
492 p += size;
493 }
494
495 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000496}
497
Tao Bao612336d2015-08-27 16:41:21 -0700498static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700499 size_t written = 0;
Tao Bao43bfa6e2018-08-28 10:09:13 -0700500 for (const auto& [begin, end] : tgt) {
501 off64_t offset = static_cast<off64_t>(begin) * BLOCKSIZE;
502 size_t size = (end - begin) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700503 if (!discard_blocks(fd, offset, size)) {
504 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000505 }
506
Tao Bao60a70af2017-03-26 14:03:52 -0700507 if (!check_lseek(fd, offset, SEEK_SET)) {
508 return -1;
509 }
510
Tianjie Xu22f11202018-08-27 10:50:31 -0700511 if (!android::base::WriteFully(fd, buffer.data() + written, size)) {
512 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
513 PLOG(ERROR) << "Failed to write " << size << " bytes of data";
Tao Bao60a70af2017-03-26 14:03:52 -0700514 return -1;
515 }
516
517 written += size;
518 }
519
520 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000521}
522
Tao Baobaad2d42015-12-06 16:56:27 -0800523// Parameters for transfer list command functions
524struct CommandParameters {
525 std::vector<std::string> tokens;
526 size_t cpos;
Tao Baoc3901232018-05-21 16:05:56 -0700527 std::string cmdname;
528 std::string cmdline;
Tao Baobaad2d42015-12-06 16:56:27 -0800529 std::string freestash;
530 std::string stashbase;
531 bool canwrite;
532 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700533 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800534 bool foundwrites;
535 bool isunresumable;
536 int version;
537 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700538 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800539 NewThreadInfo nti;
540 pthread_t thread;
541 std::vector<uint8_t> buffer;
542 uint8_t* patch_start;
Tianjie Xu284752e2017-12-05 11:04:17 -0800543 bool target_verified; // The target blocks have expected contents already.
Tao Baobaad2d42015-12-06 16:56:27 -0800544};
545
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000546// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
547// handled separately).
548static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
549 const std::vector<uint8_t>& buffer) {
550 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000551 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
552 params.tokens[0] == "imgdiff");
553
554 size_t pos = 0;
555 // Command example:
556 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
557 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
558 // [<loc_range> <stashed_blocks>]
559 if (params.tokens[0] == "move") {
560 // src_range for move starts at the 4th position.
561 if (params.tokens.size() < 5) {
562 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
563 return;
564 }
565 pos = 4;
566 } else {
567 // src_range for diff starts at the 7th position.
568 if (params.tokens.size() < 8) {
569 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
570 return;
571 }
572 pos = 7;
573 }
574
575 // Source blocks in stash only, no work to do.
576 if (params.tokens[pos] == "-") {
577 return;
578 }
579
Tao Bao8f237572017-03-26 13:36:49 -0700580 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tao Bao67983152017-11-04 00:08:08 -0700581 if (!src) {
582 LOG(ERROR) << "Failed to parse range in " << params.cmdline;
583 return;
584 }
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000585
586 RangeSet locs;
587 // If there's no stashed blocks, content in the buffer is consecutive and has the same
588 // order as the source blocks.
589 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700590 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000591 } else {
592 // Otherwise, the next token is the offset of the source blocks in the target range.
593 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
594 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
595 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700596 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700597 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000598 }
599
Tao Baobf5b77d2017-03-30 16:57:29 -0700600 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
601 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700602 size_t block_num = src.GetBlockNumber(i);
603 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000604 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
605
606 uint8_t digest[SHA_DIGEST_LENGTH];
607 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
608 std::string hexdigest = print_sha1(digest);
609 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
610 }
611}
612
613// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
614// in hex for each block.
615static void PrintHashForCorruptedStashedBlocks(const std::string& id,
616 const std::vector<uint8_t>& buffer,
617 const RangeSet& src) {
618 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700619 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000620
Tao Baobf5b77d2017-03-30 16:57:29 -0700621 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700622 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000623
624 uint8_t digest[SHA_DIGEST_LENGTH];
625 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
626 std::string hexdigest = print_sha1(digest);
627 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
628 }
629}
630
631// If the stash file doesn't exist, read the source blocks this stash contains and print the
632// SHA-1 for these blocks.
633static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
634 if (stash_map.find(id) == stash_map.end()) {
635 LOG(ERROR) << "No stash saved for id: " << id;
636 return;
637 }
638
639 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
640 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700641 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tao Baode3bbb82018-05-30 16:14:14 -0700642 if (ReadBlocks(src, &buffer, fd) == -1) {
643 LOG(ERROR) << "failed to read source blocks for stash: " << id;
644 return;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000645 }
646 PrintHashForCorruptedStashedBlocks(id, buffer, src);
647}
648
Tao Bao612336d2015-08-27 16:41:21 -0700649static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Baode3bbb82018-05-30 16:14:14 -0700650 const size_t blocks, bool printerror) {
651 uint8_t digest[SHA_DIGEST_LENGTH];
652 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000653
Tao Baode3bbb82018-05-30 16:14:14 -0700654 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000655
Tao Baode3bbb82018-05-30 16:14:14 -0700656 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000657
Tao Baode3bbb82018-05-30 16:14:14 -0700658 if (hexdigest != expected) {
659 if (printerror) {
660 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read " << hexdigest
661 << ")";
Sami Tolvanen90221202014-12-09 16:39:47 +0000662 }
Tao Baode3bbb82018-05-30 16:14:14 -0700663 return -1;
664 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000665
Tao Baode3bbb82018-05-30 16:14:14 -0700666 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000667}
668
Tao Bao0940fe12015-08-27 16:41:21 -0700669static std::string GetStashFileName(const std::string& base, const std::string& id,
Tao Bao641fa972018-04-25 18:59:40 -0700670 const std::string& postfix) {
671 if (base.empty()) {
672 return "";
673 }
Tao Bao864c6682018-05-07 11:38:25 -0700674 std::string filename = Paths::Get().stash_directory_base() + "/" + base;
675 if (id.empty() && postfix.empty()) {
676 return filename;
677 }
678 return filename + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000679}
680
Tao Baoec8272f2017-03-15 17:39:01 -0700681// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
682// directory and continues despite of errors. Calls the 'callback' function for each file.
683static void EnumerateStash(const std::string& dirname,
684 const std::function<void(const std::string&)>& callback) {
685 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000686
Tao Baoec8272f2017-03-15 17:39:01 -0700687 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000688
Tao Baoec8272f2017-03-15 17:39:01 -0700689 if (directory == nullptr) {
690 if (errno != ENOENT) {
691 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000692 }
Tao Bao51412212016-12-28 14:44:05 -0800693 return;
694 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700695
Tao Baoec8272f2017-03-15 17:39:01 -0700696 dirent* item;
697 while ((item = readdir(directory.get())) != nullptr) {
698 if (item->d_type != DT_REG) continue;
699 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800700 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000701}
702
703// Deletes the stash directory and all files in it. Assumes that it only
704// contains files. There is nothing we can do about unlikely, but possible
705// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700706static void DeleteFile(const std::string& fn) {
707 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000708
Tao Baoec8272f2017-03-15 17:39:01 -0700709 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000710
Tao Baoec8272f2017-03-15 17:39:01 -0700711 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
712 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
713 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000714}
715
Tao Baoe6aa3322015-08-05 15:20:27 -0700716static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700717 if (base.empty()) return;
718
719 LOG(INFO) << "deleting stash " << base;
720
721 std::string dirname = GetStashFileName(base, "", "");
722 EnumerateStash(dirname, DeleteFile);
723
724 if (rmdir(dirname.c_str()) == -1) {
725 if (errno != ENOENT && errno != ENOTDIR) {
726 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000727 }
Tao Baoec8272f2017-03-15 17:39:01 -0700728 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000729}
730
Tao Baode3bbb82018-05-30 16:14:14 -0700731static int LoadStash(const CommandParameters& params, const std::string& id, bool verify,
732 std::vector<uint8_t>* buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700733 // In verify mode, if source range_set was saved for the given hash, check contents in the source
734 // blocks first. If the check fails, search for the stashed files on /cache as usual.
735 if (!params.canwrite) {
736 if (stash_map.find(id) != stash_map.end()) {
737 const RangeSet& src = stash_map[id];
738 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700739
Tao Baobf5b77d2017-03-30 16:57:29 -0700740 if (ReadBlocks(src, buffer, params.fd) == -1) {
741 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700742 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700743 }
Tao Baode3bbb82018-05-30 16:14:14 -0700744 if (VerifyBlocks(id, *buffer, src.blocks(), true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700745 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu3c5958f2018-03-09 14:10:25 -0800746 if (!is_retry) {
747 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
748 }
Tao Bao0940fe12015-08-27 16:41:21 -0700749 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700750 }
751 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000752 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700753 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000754
Tao Baobf5b77d2017-03-30 16:57:29 -0700755 std::string fn = GetStashFileName(params.stashbase, id, "");
756
757 struct stat sb;
758 if (stat(fn.c_str(), &sb) == -1) {
759 if (errno != ENOENT || printnoent) {
760 PLOG(ERROR) << "stat \"" << fn << "\" failed";
761 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000762 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700763 return -1;
764 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000765
Tao Baobf5b77d2017-03-30 16:57:29 -0700766 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000767
Tao Baobf5b77d2017-03-30 16:57:29 -0700768 if ((sb.st_size % BLOCKSIZE) != 0) {
769 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
770 return -1;
771 }
772
Tianjie Xu22f11202018-08-27 10:50:31 -0700773 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY)));
Tao Baobf5b77d2017-03-30 16:57:29 -0700774 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700775 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Baobf5b77d2017-03-30 16:57:29 -0700776 PLOG(ERROR) << "open \"" << fn << "\" failed";
777 return -1;
778 }
779
780 allocate(sb.st_size, buffer);
781
Tianjie Xu22f11202018-08-27 10:50:31 -0700782 if (!android::base::ReadFully(fd, buffer->data(), sb.st_size)) {
783 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
784 PLOG(ERROR) << "Failed to read " << sb.st_size << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -0700785 return -1;
786 }
787
Tao Bao64957ce2018-05-30 16:21:39 -0700788 size_t blocks = sb.st_size / BLOCKSIZE;
Tao Baode3bbb82018-05-30 16:14:14 -0700789 if (verify && VerifyBlocks(id, *buffer, blocks, true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700790 LOG(ERROR) << "unexpected contents in " << fn;
791 if (stash_map.find(id) == stash_map.end()) {
792 LOG(ERROR) << "failed to find source blocks number for stash " << id
793 << " when executing command: " << params.cmdname;
794 } else {
795 const RangeSet& src = stash_map[id];
Tao Baode3bbb82018-05-30 16:14:14 -0700796 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000797 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700798 DeleteFile(fn);
799 return -1;
800 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000801
Tao Baobf5b77d2017-03-30 16:57:29 -0700802 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000803}
804
Tao Bao612336d2015-08-27 16:41:21 -0700805static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baode3bbb82018-05-30 16:14:14 -0700806 const std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
807 if (base.empty()) {
808 return -1;
809 }
810
Tao Bao5ee25662018-07-11 15:55:32 -0700811 if (checkspace && !CheckAndFreeSpaceOnCache(blocks * BLOCKSIZE)) {
Tao Baode3bbb82018-05-30 16:14:14 -0700812 LOG(ERROR) << "not enough space to write stash";
813 return -1;
814 }
815
816 std::string fn = GetStashFileName(base, id, ".partial");
817 std::string cn = GetStashFileName(base, id, "");
818
819 if (exists) {
820 struct stat sb;
821 int res = stat(cn.c_str(), &sb);
822
823 if (res == 0) {
824 // The file already exists and since the name is the hash of the contents,
825 // it's safe to assume the contents are identical (accidental hash collisions
826 // are unlikely)
827 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
828 *exists = true;
829 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000830 }
831
Tao Baode3bbb82018-05-30 16:14:14 -0700832 *exists = false;
833 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000834
Tao Baode3bbb82018-05-30 16:14:14 -0700835 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000836
Tao Baode3bbb82018-05-30 16:14:14 -0700837 android::base::unique_fd fd(
Tianjie Xu22f11202018-08-27 10:50:31 -0700838 TEMP_FAILURE_RETRY(open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Tao Baode3bbb82018-05-30 16:14:14 -0700839 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700840 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Baode3bbb82018-05-30 16:14:14 -0700841 PLOG(ERROR) << "failed to create \"" << fn << "\"";
842 return -1;
843 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100844
Tao Baode3bbb82018-05-30 16:14:14 -0700845 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
846 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
847 return -1;
848 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100849
Tianjie Xu22f11202018-08-27 10:50:31 -0700850 if (!android::base::WriteFully(fd, buffer.data(), blocks * BLOCKSIZE)) {
851 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
852 PLOG(ERROR) << "Failed to write " << blocks * BLOCKSIZE << " bytes of data";
Tao Baode3bbb82018-05-30 16:14:14 -0700853 return -1;
854 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100855
Tianjie Xu22f11202018-08-27 10:50:31 -0700856 if (fsync(fd) == -1) {
857 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Baode3bbb82018-05-30 16:14:14 -0700858 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
859 return -1;
860 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000861
Tao Baode3bbb82018-05-30 16:14:14 -0700862 if (rename(fn.c_str(), cn.c_str()) == -1) {
863 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
864 return -1;
865 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000866
Tao Baode3bbb82018-05-30 16:14:14 -0700867 std::string dname = GetStashFileName(base, "", "");
868 if (!FsyncDir(dname)) {
Tao Baode3bbb82018-05-30 16:14:14 -0700869 return -1;
870 }
Tianjie Xua946b9e2017-03-21 16:24:57 -0700871
Tao Baode3bbb82018-05-30 16:14:14 -0700872 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000873}
874
875// Creates a directory for storing stash files and checks if the /cache partition
876// hash enough space for the expected amount of blocks we need to store. Returns
877// >0 if we created the directory, zero if it existed already, and <0 of failure.
Tao Bao864c6682018-05-07 11:38:25 -0700878static int CreateStash(State* state, size_t maxblocks, const std::string& base) {
Tao Bao51412212016-12-28 14:44:05 -0800879 std::string dirname = GetStashFileName(base, "", "");
880 struct stat sb;
881 int res = stat(dirname.c_str(), &sb);
Tao Bao51412212016-12-28 14:44:05 -0800882 if (res == -1 && errno != ENOENT) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800883 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800884 strerror(errno));
885 return -1;
Tao Bao864c6682018-05-07 11:38:25 -0700886 }
887
888 size_t max_stash_size = maxblocks * BLOCKSIZE;
889 if (res == -1) {
Tao Bao51412212016-12-28 14:44:05 -0800890 LOG(INFO) << "creating stash " << dirname;
Yifan Hong63f52602019-01-11 13:52:33 -0800891 res = mkdir_recursively(dirname, STASH_DIRECTORY_MODE, false, nullptr);
Tao Bao51412212016-12-28 14:44:05 -0800892
893 if (res != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800894 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800895 strerror(errno));
896 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000897 }
898
Tianjie Xua946b9e2017-03-21 16:24:57 -0700899 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
Tianjie Xu5ad80282018-01-28 15:37:48 -0800900 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s", dirname.c_str(),
Tianjie Xua946b9e2017-03-21 16:24:57 -0700901 strerror(errno));
902 return -1;
903 }
904
Tao Bao5ee25662018-07-11 15:55:32 -0700905 if (!CheckAndFreeSpaceOnCache(max_stash_size)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800906 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)",
Tao Bao51412212016-12-28 14:44:05 -0800907 max_stash_size);
908 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000909 }
910
Tao Bao51412212016-12-28 14:44:05 -0800911 return 1; // Created directory
912 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000913
Tao Bao51412212016-12-28 14:44:05 -0800914 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000915
Tao Baoec8272f2017-03-15 17:39:01 -0700916 // If the directory already exists, calculate the space already allocated to stash files and check
917 // if there's enough for all required blocks. Delete any partially completed stash files first.
918 EnumerateStash(dirname, [](const std::string& fn) {
919 if (android::base::EndsWith(fn, ".partial")) {
920 DeleteFile(fn);
921 }
922 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000923
Tao Bao51412212016-12-28 14:44:05 -0800924 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700925 EnumerateStash(dirname, [&existing](const std::string& fn) {
926 if (fn.empty()) return;
927 struct stat sb;
928 if (stat(fn.c_str(), &sb) == -1) {
929 PLOG(ERROR) << "stat \"" << fn << "\" failed";
930 return;
931 }
932 existing += static_cast<size_t>(sb.st_size);
933 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000934
Tao Bao51412212016-12-28 14:44:05 -0800935 if (max_stash_size > existing) {
936 size_t needed = max_stash_size - existing;
Tao Bao5ee25662018-07-11 15:55:32 -0700937 if (!CheckAndFreeSpaceOnCache(needed)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800938 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)",
Tao Bao51412212016-12-28 14:44:05 -0800939 needed);
940 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000941 }
Tao Bao51412212016-12-28 14:44:05 -0800942 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000943
Tao Bao51412212016-12-28 14:44:05 -0800944 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000945}
946
Tao Baobaad2d42015-12-06 16:56:27 -0800947static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700948 if (base.empty() || id.empty()) {
949 return -1;
950 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000951
Tao Baoec8272f2017-03-15 17:39:01 -0700952 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000953
Tao Baoec8272f2017-03-15 17:39:01 -0700954 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700955}
956
Tao Baobf5b77d2017-03-30 16:57:29 -0700957// Source contains packed data, which we want to move to the locations given in locs in the dest
958// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700959static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700960 const std::vector<uint8_t>& source) {
961 const uint8_t* from = source.data();
962 uint8_t* to = dest.data();
963 size_t start = locs.blocks();
964 // Must do the movement backward.
965 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
966 size_t blocks = it->second - it->first;
967 start -= blocks;
968 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
969 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700970}
971
Tao Baod2aecd42017-03-23 14:43:44 -0700972/**
973 * We expect to parse the remainder of the parameter tokens as one of:
974 *
975 * <src_block_count> <src_range>
976 * (loads data from source image only)
977 *
978 * <src_block_count> - <[stash_id:stash_range] ...>
979 * (loads data from stashes only)
980 *
981 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
982 * (loads data from both source image and stashes)
983 *
984 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
985 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
986 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
987 * LoadStash.
988 */
989static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
990 bool* overlap) {
991 CHECK(src_blocks != nullptr);
992 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700993
Tao Baod2aecd42017-03-23 14:43:44 -0700994 // <src_block_count>
995 const std::string& token = params.tokens[params.cpos++];
996 if (!android::base::ParseUint(token, src_blocks)) {
997 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
998 return -1;
999 }
Tao Baobaad2d42015-12-06 16:56:27 -08001000
Tao Baode3bbb82018-05-30 16:14:14 -07001001 allocate(*src_blocks * BLOCKSIZE, &params.buffer);
Tao Baod2aecd42017-03-23 14:43:44 -07001002
1003 // "-" or <src_range> [<src_loc>]
1004 if (params.tokens[params.cpos] == "-") {
1005 // no source ranges, only stashes
1006 params.cpos++;
1007 } else {
Tao Bao8f237572017-03-26 13:36:49 -07001008 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001009 CHECK(static_cast<bool>(src));
Tao Bao8f237572017-03-26 13:36:49 -07001010 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -07001011
Tao Baode3bbb82018-05-30 16:14:14 -07001012 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001013 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -08001014 }
1015
Tao Baod2aecd42017-03-23 14:43:44 -07001016 if (params.cpos >= params.tokens.size()) {
1017 // no stashes, only source range
1018 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -08001019 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001020
Tao Bao8f237572017-03-26 13:36:49 -07001021 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001022 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001023 MoveRange(params.buffer, locs, params.buffer);
1024 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001025
Tao Baod2aecd42017-03-23 14:43:44 -07001026 // <[stash_id:stash_range]>
1027 while (params.cpos < params.tokens.size()) {
1028 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
1029 // in the source block that stashed data should go.
1030 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1031 if (tokens.size() != 2) {
1032 LOG(ERROR) << "invalid parameter";
1033 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001034 }
1035
Tao Baod2aecd42017-03-23 14:43:44 -07001036 std::vector<uint8_t> stash;
Tao Baode3bbb82018-05-30 16:14:14 -07001037 if (LoadStash(params, tokens[0], false, &stash, true) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001038 // These source blocks will fail verification if used later, but we
1039 // will let the caller decide if this is a fatal failure
1040 LOG(ERROR) << "failed to load stash " << tokens[0];
1041 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +00001042 }
1043
Tao Bao8f237572017-03-26 13:36:49 -07001044 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Bao67983152017-11-04 00:08:08 -07001045 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001046 MoveRange(params.buffer, locs, stash);
1047 }
1048
1049 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001050}
1051
Tao Bao33567772017-03-13 14:57:34 -07001052/**
1053 * Do a source/target load for move/bsdiff/imgdiff in version 3.
1054 *
1055 * We expect to parse the remainder of the parameter tokens as one of:
1056 *
1057 * <tgt_range> <src_block_count> <src_range>
1058 * (loads data from source image only)
1059 *
1060 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
1061 * (loads data from stashes only)
1062 *
1063 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1064 * (loads data from both source image and stashes)
1065 *
Tao Baod2aecd42017-03-23 14:43:44 -07001066 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
1067 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -07001068 * verification fails in a way that the update cannot be resumed anymore.
1069 *
1070 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
1071 * the return value is -1 and the command should be aborted.
1072 *
1073 * If the return value is 1, the command has already been completed according to the contents of the
1074 * target blocks, and should not be performed again.
1075 *
1076 * If the return value is 0, source blocks have expected content and the command can be performed.
1077 */
Tao Baode3bbb82018-05-30 16:14:14 -07001078static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet* tgt, size_t* src_blocks,
Tao Bao4a135082018-06-07 22:27:44 -07001079 bool onehash) {
Tao Baod2aecd42017-03-23 14:43:44 -07001080 CHECK(src_blocks != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001081
Tao Baod2aecd42017-03-23 14:43:44 -07001082 if (params.cpos >= params.tokens.size()) {
1083 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001084 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001085 }
1086
1087 std::string srchash = params.tokens[params.cpos++];
1088 std::string tgthash;
1089
1090 if (onehash) {
1091 tgthash = srchash;
1092 } else {
1093 if (params.cpos >= params.tokens.size()) {
1094 LOG(ERROR) << "missing target hash";
1095 return -1;
1096 }
1097 tgthash = params.tokens[params.cpos++];
1098 }
1099
1100 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1101 // "-"/<src_range>.
1102 if (params.cpos + 2 >= params.tokens.size()) {
1103 LOG(ERROR) << "invalid parameters";
1104 return -1;
1105 }
1106
1107 // <tgt_range>
Tao Baode3bbb82018-05-30 16:14:14 -07001108 *tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1109 CHECK(static_cast<bool>(*tgt));
Tao Baod2aecd42017-03-23 14:43:44 -07001110
Tao Baode3bbb82018-05-30 16:14:14 -07001111 std::vector<uint8_t> tgtbuffer(tgt->blocks() * BLOCKSIZE);
1112 if (ReadBlocks(*tgt, &tgtbuffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001113 return -1;
1114 }
1115
1116 // Return now if target blocks already have expected content.
Tao Baode3bbb82018-05-30 16:14:14 -07001117 if (VerifyBlocks(tgthash, tgtbuffer, tgt->blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001118 return 1;
1119 }
1120
1121 // Load source blocks.
Tao Bao4a135082018-06-07 22:27:44 -07001122 bool overlap = false;
1123 if (LoadSourceBlocks(params, *tgt, src_blocks, &overlap) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001124 return -1;
1125 }
1126
1127 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
Tao Bao4a135082018-06-07 22:27:44 -07001128 // If source and target blocks overlap, stash the source blocks so we can resume from possible
1129 // write errors. In verify mode, we can skip stashing because the source blocks won't be
1130 // overwritten.
1131 if (overlap && params.canwrite) {
Tao Baod2aecd42017-03-23 14:43:44 -07001132 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1133
1134 bool stash_exists = false;
1135 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1136 &stash_exists) != 0) {
1137 LOG(ERROR) << "failed to stash overlapping source blocks";
1138 return -1;
1139 }
1140
1141 params.stashed += *src_blocks;
1142 // Can be deleted when the write has completed.
1143 if (!stash_exists) {
1144 params.freestash = srchash;
1145 }
1146 }
1147
1148 // Source blocks have expected content, command can proceed.
1149 return 0;
1150 }
1151
Tao Bao4a135082018-06-07 22:27:44 -07001152 if (overlap && LoadStash(params, srchash, true, &params.buffer, true) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001153 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1154 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1155 // command.
1156 return 0;
1157 }
1158
1159 // Valid source data not available, update cannot be resumed.
1160 LOG(ERROR) << "partition has unexpected contents";
1161 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1162
1163 params.isunresumable = true;
1164
1165 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001166}
1167
Tao Bao0940fe12015-08-27 16:41:21 -07001168static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001169 size_t blocks = 0;
Tao Bao33567772017-03-13 14:57:34 -07001170 RangeSet tgt;
Tao Bao4a135082018-06-07 22:27:44 -07001171 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001172
Tao Bao33567772017-03-13 14:57:34 -07001173 if (status == -1) {
1174 LOG(ERROR) << "failed to read blocks for move";
1175 return -1;
1176 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001177
Tao Bao33567772017-03-13 14:57:34 -07001178 if (status == 0) {
1179 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001180 } else {
1181 params.target_verified = true;
1182 if (params.foundwrites) {
1183 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1184 }
Tao Bao33567772017-03-13 14:57:34 -07001185 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001186
Tao Bao33567772017-03-13 14:57:34 -07001187 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001188 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001189 LOG(INFO) << " moving " << blocks << " blocks";
1190
1191 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1192 return -1;
1193 }
1194 } else {
1195 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001196 }
Tao Bao33567772017-03-13 14:57:34 -07001197 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001198
Tao Bao33567772017-03-13 14:57:34 -07001199 if (!params.freestash.empty()) {
1200 FreeStash(params.stashbase, params.freestash);
1201 params.freestash.clear();
1202 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001203
Tao Baobf5b77d2017-03-30 16:57:29 -07001204 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001205
Tao Bao33567772017-03-13 14:57:34 -07001206 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001207}
1208
Tao Bao0940fe12015-08-27 16:41:21 -07001209static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001210 // <stash_id> <src_range>
1211 if (params.cpos + 1 >= params.tokens.size()) {
1212 LOG(ERROR) << "missing id and/or src range fields in stash command";
1213 return -1;
1214 }
1215
1216 const std::string& id = params.tokens[params.cpos++];
Tao Baode3bbb82018-05-30 16:14:14 -07001217 if (LoadStash(params, id, true, &params.buffer, false) == 0) {
Tao Baobcf46492017-03-23 15:28:20 -07001218 // Stash file already exists and has expected contents. Do not read from source again, as the
1219 // source may have been already overwritten during a previous attempt.
1220 return 0;
1221 }
1222
Tao Bao8f237572017-03-26 13:36:49 -07001223 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001224 CHECK(static_cast<bool>(src));
Tao Baobcf46492017-03-23 15:28:20 -07001225
Tao Bao64957ce2018-05-30 16:21:39 -07001226 size_t blocks = src.blocks();
Tao Baode3bbb82018-05-30 16:14:14 -07001227 allocate(blocks * BLOCKSIZE, &params.buffer);
1228 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baobcf46492017-03-23 15:28:20 -07001229 return -1;
1230 }
Tao Baobcf46492017-03-23 15:28:20 -07001231 stash_map[id] = src;
1232
1233 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1234 // Source blocks have unexpected contents. If we actually need this data later, this is an
1235 // unrecoverable error. However, the command that uses the data may have already completed
1236 // previously, so the possible failure will occur during source block verification.
1237 LOG(ERROR) << "failed to load source blocks for stash " << id;
1238 return 0;
1239 }
1240
1241 // In verify mode, we don't need to stash any blocks.
1242 if (!params.canwrite) {
1243 return 0;
1244 }
1245
1246 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xu284752e2017-12-05 11:04:17 -08001247 int result = WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
1248 if (result == 0) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001249 params.stashed += blocks;
1250 }
1251 return result;
Sami Tolvanen90221202014-12-09 16:39:47 +00001252}
1253
Tao Bao0940fe12015-08-27 16:41:21 -07001254static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001255 // <stash_id>
1256 if (params.cpos >= params.tokens.size()) {
1257 LOG(ERROR) << "missing stash id in free command";
1258 return -1;
1259 }
Tao Baobaad2d42015-12-06 16:56:27 -08001260
Tao Baobcf46492017-03-23 15:28:20 -07001261 const std::string& id = params.tokens[params.cpos++];
1262 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001263
Tao Baobcf46492017-03-23 15:28:20 -07001264 if (params.createdstash || params.canwrite) {
1265 return FreeStash(params.stashbase, id);
1266 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001267
Tao Baobcf46492017-03-23 15:28:20 -07001268 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001269}
1270
Tao Bao0940fe12015-08-27 16:41:21 -07001271static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001272 if (params.cpos >= params.tokens.size()) {
1273 LOG(ERROR) << "missing target blocks for zero";
1274 return -1;
1275 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001276
Tao Baobf5b77d2017-03-30 16:57:29 -07001277 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001278 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001279
1280 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1281
Tao Baode3bbb82018-05-30 16:14:14 -07001282 allocate(BLOCKSIZE, &params.buffer);
Tao Baobf5b77d2017-03-30 16:57:29 -07001283 memset(params.buffer.data(), 0, BLOCKSIZE);
1284
1285 if (params.canwrite) {
Tao Bao43bfa6e2018-08-28 10:09:13 -07001286 for (const auto& [begin, end] : tgt) {
1287 off64_t offset = static_cast<off64_t>(begin) * BLOCKSIZE;
1288 size_t size = (end - begin) * BLOCKSIZE;
Tao Baobf5b77d2017-03-30 16:57:29 -07001289 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001290 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001291 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001292
Tao Baobf5b77d2017-03-30 16:57:29 -07001293 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1294 return -1;
1295 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001296
Tao Bao43bfa6e2018-08-28 10:09:13 -07001297 for (size_t j = begin; j < end; ++j) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001298 if (!android::base::WriteFully(params.fd, params.buffer.data(), BLOCKSIZE)) {
1299 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
1300 PLOG(ERROR) << "Failed to write " << BLOCKSIZE << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -07001301 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001302 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001303 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001304 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001305 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001306
Tao Baobf5b77d2017-03-30 16:57:29 -07001307 if (params.cmdname[0] == 'z') {
1308 // Update only for the zero command, as the erase command will call
1309 // this if DEBUG_ERASE is defined.
1310 params.written += tgt.blocks();
1311 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001312
Tao Baobf5b77d2017-03-30 16:57:29 -07001313 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001314}
1315
Tao Bao0940fe12015-08-27 16:41:21 -07001316static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001317 if (params.cpos >= params.tokens.size()) {
1318 LOG(ERROR) << "missing target blocks for new";
1319 return -1;
1320 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001321
Tao Bao8f237572017-03-26 13:36:49 -07001322 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001323 CHECK(static_cast<bool>(tgt));
Tao Bao60a70af2017-03-26 14:03:52 -07001324
1325 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001326 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001327
Tao Bao60a70af2017-03-26 14:03:52 -07001328 pthread_mutex_lock(&params.nti.mu);
Tianjie Xu6ed175d2017-07-18 11:29:40 -07001329 params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
Tao Bao60a70af2017-03-26 14:03:52 -07001330 pthread_cond_broadcast(&params.nti.cv);
1331
1332 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001333 if (!params.nti.receiver_available) {
1334 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1335 << " bytes of new data";
1336 pthread_mutex_unlock(&params.nti.mu);
1337 return -1;
1338 }
Tao Bao60a70af2017-03-26 14:03:52 -07001339 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001340 }
1341
Tao Bao60a70af2017-03-26 14:03:52 -07001342 pthread_mutex_unlock(&params.nti.mu);
1343 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001344
Tao Baobf5b77d2017-03-30 16:57:29 -07001345 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001346
Tao Bao60a70af2017-03-26 14:03:52 -07001347 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001348}
1349
Tao Bao0940fe12015-08-27 16:41:21 -07001350static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001351 // <offset> <length>
1352 if (params.cpos + 1 >= params.tokens.size()) {
1353 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1354 return -1;
1355 }
Tao Bao0940fe12015-08-27 16:41:21 -07001356
Tao Baoc0e1c462017-02-01 10:20:10 -08001357 size_t offset;
1358 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1359 LOG(ERROR) << "invalid patch offset";
1360 return -1;
1361 }
Tao Bao0940fe12015-08-27 16:41:21 -07001362
Tao Baoc0e1c462017-02-01 10:20:10 -08001363 size_t len;
1364 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1365 LOG(ERROR) << "invalid patch len";
1366 return -1;
1367 }
Tao Bao0940fe12015-08-27 16:41:21 -07001368
Tao Baoc0e1c462017-02-01 10:20:10 -08001369 RangeSet tgt;
1370 size_t blocks = 0;
Tao Bao4a135082018-06-07 22:27:44 -07001371 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, false);
Tao Bao0940fe12015-08-27 16:41:21 -07001372
Tao Baoc0e1c462017-02-01 10:20:10 -08001373 if (status == -1) {
1374 LOG(ERROR) << "failed to read blocks for diff";
1375 return -1;
1376 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001377
Tao Baoc0e1c462017-02-01 10:20:10 -08001378 if (status == 0) {
1379 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001380 } else {
1381 params.target_verified = true;
1382 if (params.foundwrites) {
1383 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1384 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001385 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001386
Tao Baoc0e1c462017-02-01 10:20:10 -08001387 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001388 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001389 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001390 Value patch_value(
Tao Bao511d7592018-06-19 15:56:49 -07001391 Value::Type::BLOB,
1392 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001393
Tao Bao60a70af2017-03-26 14:03:52 -07001394 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001395 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao1e0941f2017-11-10 11:49:53 -08001396 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value,
Tao Bao60a70af2017-03-26 14:03:52 -07001397 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1398 std::placeholders::_2),
Tao Bao8b0b0f12018-04-19 21:02:13 -07001399 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001400 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001401 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001402 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001403 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001404 } else {
Tao Bao1e0941f2017-11-10 11:49:53 -08001405 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value, 0,
Tao Bao60a70af2017-03-26 14:03:52 -07001406 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
Tao Bao8b0b0f12018-04-19 21:02:13 -07001407 std::placeholders::_2)) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001408 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001409 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001410 return -1;
1411 }
1412 }
1413
1414 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001415 if (!writer.Finished()) {
Tao Baoa2cff952018-11-02 15:44:07 -07001416 LOG(ERROR) << "Failed to fully write target blocks (range sink underrun): Missing "
1417 << writer.AvailableSpace() << " bytes";
1418 failure_type = kPatchApplicationFailure;
1419 return -1;
Tao Baoc0e1c462017-02-01 10:20:10 -08001420 }
1421 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001422 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001423 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001424 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001425 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001426
Tao Baoc0e1c462017-02-01 10:20:10 -08001427 if (!params.freestash.empty()) {
1428 FreeStash(params.stashbase, params.freestash);
1429 params.freestash.clear();
1430 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001431
Tao Baobf5b77d2017-03-30 16:57:29 -07001432 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001433
Tao Baoc0e1c462017-02-01 10:20:10 -08001434 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001435}
1436
Tao Bao0940fe12015-08-27 16:41:21 -07001437static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001438 if (DEBUG_ERASE) {
1439 return PerformCommandZero(params);
1440 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001441
Tao Baobf5b77d2017-03-30 16:57:29 -07001442 struct stat sb;
1443 if (fstat(params.fd, &sb) == -1) {
1444 PLOG(ERROR) << "failed to fstat device to erase";
1445 return -1;
1446 }
1447
1448 if (!S_ISBLK(sb.st_mode)) {
1449 LOG(ERROR) << "not a block device; skipping erase";
1450 return -1;
1451 }
1452
1453 if (params.cpos >= params.tokens.size()) {
1454 LOG(ERROR) << "missing target blocks for erase";
1455 return -1;
1456 }
1457
1458 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001459 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001460
1461 if (params.canwrite) {
1462 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1463
Tao Bao43bfa6e2018-08-28 10:09:13 -07001464 for (const auto& [begin, end] : tgt) {
Yifan Hong363d6242019-01-04 11:14:19 -08001465 off64_t offset = static_cast<off64_t>(begin) * BLOCKSIZE;
1466 size_t size = (end - begin) * BLOCKSIZE;
1467 if (!discard_blocks(params.fd, offset, size, true /* force */)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001468 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001469 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001470 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001471 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001472
Tao Baobf5b77d2017-03-30 16:57:29 -07001473 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001474}
1475
Tao Bao91a649a2018-05-21 16:05:56 -07001476static int PerformCommandAbort(CommandParameters&) {
1477 LOG(INFO) << "Aborting as instructed";
1478 return -1;
1479}
1480
Tianjie Xu69ffa152018-08-01 16:40:00 -07001481// Computes the hash_tree bytes based on the parameters, checks if the root hash of the tree
1482// matches the expected hash and writes the result to the specified range on the block_device.
1483// Hash_tree computation arguments:
1484// hash_tree_ranges
1485// source_ranges
1486// hash_algorithm
1487// salt_hex
1488// root_hash
1489static int PerformCommandComputeHashTree(CommandParameters& params) {
1490 if (params.cpos + 5 != params.tokens.size()) {
1491 LOG(ERROR) << "Invaild arguments count in hash computation " << params.cmdline;
1492 return -1;
1493 }
1494
1495 // Expects the hash_tree data to be contiguous.
1496 RangeSet hash_tree_ranges = RangeSet::Parse(params.tokens[params.cpos++]);
1497 if (!hash_tree_ranges || hash_tree_ranges.size() != 1) {
1498 LOG(ERROR) << "Invalid hash tree ranges in " << params.cmdline;
1499 return -1;
1500 }
1501
1502 RangeSet source_ranges = RangeSet::Parse(params.tokens[params.cpos++]);
1503 if (!source_ranges) {
1504 LOG(ERROR) << "Invalid source ranges in " << params.cmdline;
1505 return -1;
1506 }
1507
1508 auto hash_function = HashTreeBuilder::HashFunction(params.tokens[params.cpos++]);
1509 if (hash_function == nullptr) {
1510 LOG(ERROR) << "Invalid hash algorithm in " << params.cmdline;
1511 return -1;
1512 }
1513
1514 std::vector<unsigned char> salt;
1515 std::string salt_hex = params.tokens[params.cpos++];
1516 if (salt_hex.empty() || !HashTreeBuilder::ParseBytesArrayFromString(salt_hex, &salt)) {
1517 LOG(ERROR) << "Failed to parse salt in " << params.cmdline;
1518 return -1;
1519 }
1520
1521 std::string expected_root_hash = params.tokens[params.cpos++];
1522 if (expected_root_hash.empty()) {
1523 LOG(ERROR) << "Invalid root hash in " << params.cmdline;
1524 return -1;
1525 }
1526
1527 // Starts the hash_tree computation.
1528 HashTreeBuilder builder(BLOCKSIZE, hash_function);
xunchang53158e52019-01-17 09:26:12 -08001529 if (!builder.Initialize(static_cast<int64_t>(source_ranges.blocks()) * BLOCKSIZE, salt)) {
Tianjie Xu69ffa152018-08-01 16:40:00 -07001530 LOG(ERROR) << "Failed to initialize hash tree computation, source " << source_ranges.ToString()
1531 << ", salt " << salt_hex;
1532 return -1;
1533 }
1534
1535 // Iterates through every block in the source_ranges and updates the hash tree structure
1536 // accordingly.
Tao Bao43bfa6e2018-08-28 10:09:13 -07001537 for (const auto& [begin, end] : source_ranges) {
Tianjie Xu69ffa152018-08-01 16:40:00 -07001538 uint8_t buffer[BLOCKSIZE];
Tao Bao43bfa6e2018-08-28 10:09:13 -07001539 if (!check_lseek(params.fd, static_cast<off64_t>(begin) * BLOCKSIZE, SEEK_SET)) {
1540 PLOG(ERROR) << "Failed to seek to block: " << begin;
Tianjie Xu69ffa152018-08-01 16:40:00 -07001541 return -1;
1542 }
1543
Tao Bao43bfa6e2018-08-28 10:09:13 -07001544 for (size_t i = begin; i < end; i++) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001545 if (!android::base::ReadFully(params.fd, buffer, BLOCKSIZE)) {
1546 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
Tao Bao43bfa6e2018-08-28 10:09:13 -07001547 LOG(ERROR) << "Failed to read data in " << begin << ":" << end;
Tianjie Xu69ffa152018-08-01 16:40:00 -07001548 return -1;
1549 }
1550
1551 if (!builder.Update(reinterpret_cast<unsigned char*>(buffer), BLOCKSIZE)) {
1552 LOG(ERROR) << "Failed to update hash tree builder";
1553 return -1;
1554 }
1555 }
1556 }
1557
1558 if (!builder.BuildHashTree()) {
1559 LOG(ERROR) << "Failed to build hash tree";
1560 return -1;
1561 }
1562
1563 std::string root_hash_hex = HashTreeBuilder::BytesArrayToString(builder.root_hash());
1564 if (root_hash_hex != expected_root_hash) {
1565 LOG(ERROR) << "Root hash of the verity hash tree doesn't match the expected value. Expected: "
1566 << expected_root_hash << ", actual: " << root_hash_hex;
1567 return -1;
1568 }
1569
1570 uint64_t write_offset = static_cast<uint64_t>(hash_tree_ranges.GetBlockNumber(0)) * BLOCKSIZE;
1571 if (params.canwrite && !builder.WriteHashTreeToFd(params.fd, write_offset)) {
1572 LOG(ERROR) << "Failed to write hash tree to output";
1573 return -1;
1574 }
1575
1576 // TODO(xunchang) validates the written bytes
1577
1578 return 0;
1579}
1580
Tao Baoc3901232018-05-21 16:05:56 -07001581using CommandFunction = std::function<int(CommandParameters&)>;
Sami Tolvanen90221202014-12-09 16:39:47 +00001582
Tao Baoc3901232018-05-21 16:05:56 -07001583using CommandMap = std::unordered_map<Command::Type, CommandFunction>;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001584
Yifan Hong8ff84d72018-12-19 16:21:55 -08001585static bool Sha1DevicePath(const std::string& path, uint8_t digest[SHA_DIGEST_LENGTH]) {
1586 auto device_name = android::base::Basename(path);
1587 auto dm_target_name_path = "/sys/block/" + device_name + "/dm/name";
1588
1589 struct stat sb;
1590 if (stat(dm_target_name_path.c_str(), &sb) == 0) {
1591 // This is a device mapper target. Use partition name as part of the hash instead. Do not
1592 // include extents as part of the hash, because the size of a partition may be shrunk after
1593 // the patches are applied.
1594 std::string dm_target_name;
1595 if (!android::base::ReadFileToString(dm_target_name_path, &dm_target_name)) {
1596 PLOG(ERROR) << "Cannot read " << dm_target_name_path;
1597 return false;
1598 }
1599 SHA1(reinterpret_cast<const uint8_t*>(dm_target_name.data()), dm_target_name.size(), digest);
1600 return true;
1601 }
1602
1603 if (errno != ENOENT) {
1604 // This is a device mapper target, but its name cannot be retrieved.
1605 PLOG(ERROR) << "Cannot get dm target name for " << path;
1606 return false;
1607 }
1608
1609 // This doesn't appear to be a device mapper target, but if its name starts with dm-, something
1610 // else might have gone wrong.
1611 if (android::base::StartsWith(device_name, "dm-")) {
1612 LOG(WARNING) << "Device " << path << " starts with dm- but is not mapped by device-mapper.";
1613 }
1614
1615 // Stash directory should be different for each partition to avoid conflicts when updating
1616 // multiple partitions at the same time, so we use the hash of the block device name as the base
1617 // directory.
1618 SHA1(reinterpret_cast<const uint8_t*>(path.data()), path.size(), digest);
1619 return true;
1620}
1621
Tianjie Xuc4447322017-03-06 14:44:59 -08001622static Value* PerformBlockImageUpdate(const char* name, State* state,
1623 const std::vector<std::unique_ptr<Expr>>& argv,
Tao Baoc3901232018-05-21 16:05:56 -07001624 const CommandMap& command_map, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001625 CommandParameters params = {};
Tao Baoc0299ed2018-05-24 00:16:35 -07001626 stash_map.clear();
Tao Bao33567772017-03-13 14:57:34 -07001627 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001628
Tao Bao33567772017-03-13 14:57:34 -07001629 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1630 if (state->is_retry) {
1631 is_retry = true;
1632 LOG(INFO) << "This update is a retry.";
1633 }
1634 if (argv.size() != 4) {
1635 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1636 argv.size());
1637 return StringValue("");
1638 }
1639
1640 std::vector<std::unique_ptr<Value>> args;
1641 if (!ReadValueArgs(state, argv, &args)) {
1642 return nullptr;
1643 }
1644
Tao Baoc3901232018-05-21 16:05:56 -07001645 // args:
1646 // - block device (or file) to modify in-place
1647 // - transfer list (blob)
1648 // - new data stream (filename within package.zip)
1649 // - patch stream (filename within package.zip, must be uncompressed)
Tao Baoc97edcb2017-03-31 01:18:13 -07001650 const std::unique_ptr<Value>& blockdev_filename = args[0];
1651 const std::unique_ptr<Value>& transfer_list_value = args[1];
1652 const std::unique_ptr<Value>& new_data_fn = args[2];
1653 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001654
Tao Bao511d7592018-06-19 15:56:49 -07001655 if (blockdev_filename->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001656 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1657 return StringValue("");
1658 }
Tao Bao511d7592018-06-19 15:56:49 -07001659 if (transfer_list_value->type != Value::Type::BLOB) {
Tao Bao33567772017-03-13 14:57:34 -07001660 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1661 return StringValue("");
1662 }
Tao Bao511d7592018-06-19 15:56:49 -07001663 if (new_data_fn->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001664 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1665 return StringValue("");
1666 }
Tao Bao511d7592018-06-19 15:56:49 -07001667 if (patch_data_fn->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001668 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1669 return StringValue("");
1670 }
1671
Tianjie Xu1536db82019-05-14 10:54:43 -07001672 auto updater = state->updater;
1673 auto block_device_path = updater->FindBlockDeviceName(blockdev_filename->data);
1674 if (block_device_path.empty()) {
1675 LOG(ERROR) << "Block device path for " << blockdev_filename->data << " not found. " << name
1676 << " failed.";
1677 return StringValue("");
1678 }
1679
1680 ZipArchiveHandle za = updater->GetPackageHandle();
Tianjie Xu58d59122019-05-03 01:05:04 -07001681 if (za == nullptr) {
Tao Bao33567772017-03-13 14:57:34 -07001682 return StringValue("");
1683 }
1684
Elliott Hughesa86dddb2019-05-03 22:52:37 -07001685 std::string_view path_data(patch_data_fn->data);
Tao Bao33567772017-03-13 14:57:34 -07001686 ZipEntry patch_entry;
1687 if (FindEntry(za, path_data, &patch_entry) != 0) {
1688 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1689 return StringValue("");
1690 }
Tianjie Xu58d59122019-05-03 01:05:04 -07001691 params.patch_start = updater->GetMappedPackageAddress() + patch_entry.offset;
Tao Bao33567772017-03-13 14:57:34 -07001692
Elliott Hughesa86dddb2019-05-03 22:52:37 -07001693 std::string_view new_data(new_data_fn->data);
Tao Bao33567772017-03-13 14:57:34 -07001694 ZipEntry new_entry;
1695 if (FindEntry(za, new_data, &new_entry) != 0) {
1696 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1697 return StringValue("");
1698 }
1699
Tianjie Xu1536db82019-05-14 10:54:43 -07001700 params.fd.reset(TEMP_FAILURE_RETRY(open(block_device_path.c_str(), O_RDWR)));
Tao Bao33567772017-03-13 14:57:34 -07001701 if (params.fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001702 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tianjie Xu1536db82019-05-14 10:54:43 -07001703 PLOG(ERROR) << "open \"" << block_device_path << "\" failed";
Tao Bao33567772017-03-13 14:57:34 -07001704 return StringValue("");
1705 }
1706
Tao Bao864c6682018-05-07 11:38:25 -07001707 uint8_t digest[SHA_DIGEST_LENGTH];
Tianjie Xu1536db82019-05-14 10:54:43 -07001708 if (!Sha1DevicePath(block_device_path, digest)) {
Yifan Hong8ff84d72018-12-19 16:21:55 -08001709 return StringValue("");
1710 }
Tao Bao864c6682018-05-07 11:38:25 -07001711 params.stashbase = print_sha1(digest);
1712
1713 // Possibly do return early on retry, by checking the marker. If the update on this partition has
1714 // been finished (but interrupted at a later point), there could be leftover on /cache that would
1715 // fail the no-op retry.
1716 std::string updated_marker = GetStashFileName(params.stashbase + ".UPDATED", "", "");
1717 if (is_retry) {
1718 struct stat sb;
1719 int result = stat(updated_marker.c_str(), &sb);
1720 if (result == 0) {
Tianjie Xu1536db82019-05-14 10:54:43 -07001721 LOG(INFO) << "Skipping already updated partition " << block_device_path << " based on marker";
Tao Bao864c6682018-05-07 11:38:25 -07001722 return StringValue("t");
1723 }
1724 } else {
1725 // Delete the obsolete marker if any.
1726 std::string err;
1727 if (!android::base::RemoveFileIfExists(updated_marker, &err)) {
1728 LOG(ERROR) << "Failed to remove partition updated marker " << updated_marker << ": " << err;
1729 return StringValue("");
1730 }
1731 }
1732
Tao Baoffede3e2018-06-07 09:56:19 -07001733 static constexpr size_t kTransferListHeaderLines = 4;
Tao Bao33567772017-03-13 14:57:34 -07001734 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baoffede3e2018-06-07 09:56:19 -07001735 if (lines.size() < kTransferListHeaderLines) {
1736 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]",
Tao Bao33567772017-03-13 14:57:34 -07001737 lines.size());
1738 return StringValue("");
1739 }
1740
1741 // First line in transfer list is the version number.
1742 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1743 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1744 return StringValue("");
1745 }
1746
1747 LOG(INFO) << "blockimg version is " << params.version;
1748
1749 // Second line in transfer list is the total number of blocks we expect to write.
1750 size_t total_blocks;
1751 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001752 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]", lines[1].c_str());
Tao Bao33567772017-03-13 14:57:34 -07001753 return StringValue("");
1754 }
1755
1756 if (total_blocks == 0) {
1757 return StringValue("t");
1758 }
1759
Tao Bao33567772017-03-13 14:57:34 -07001760 // Third line is how many stash entries are needed simultaneously.
1761 LOG(INFO) << "maximum stash entries " << lines[2];
1762
1763 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1764 size_t stash_max_blocks;
1765 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001766 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]",
Tao Bao33567772017-03-13 14:57:34 -07001767 lines[3].c_str());
1768 return StringValue("");
1769 }
1770
Tao Bao864c6682018-05-07 11:38:25 -07001771 int res = CreateStash(state, stash_max_blocks, params.stashbase);
Tao Bao33567772017-03-13 14:57:34 -07001772 if (res == -1) {
1773 return StringValue("");
1774 }
Tao Bao33567772017-03-13 14:57:34 -07001775 params.createdstash = res;
1776
Tao Bao0a883c12018-06-18 12:49:06 -07001777 // Set up the new data writer.
1778 if (params.canwrite) {
1779 params.nti.za = za;
1780 params.nti.entry = new_entry;
1781 params.nti.brotli_compressed = android::base::EndsWith(new_data_fn->data, ".br");
1782 if (params.nti.brotli_compressed) {
1783 // Initialize brotli decoder state.
1784 params.nti.brotli_decoder_state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
1785 }
1786 params.nti.receiver_available = true;
1787
1788 pthread_mutex_init(&params.nti.mu, nullptr);
1789 pthread_cond_init(&params.nti.cv, nullptr);
1790 pthread_attr_t attr;
1791 pthread_attr_init(&attr);
1792 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1793
1794 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1795 if (error != 0) {
1796 LOG(ERROR) << "pthread_create failed: " << strerror(error);
1797 return StringValue("");
1798 }
1799 }
1800
Tao Bao26efb0a2018-05-21 14:59:55 -07001801 // When performing an update, save the index and cmdline of the current command into the
1802 // last_command_file.
Tianjie Xu284752e2017-12-05 11:04:17 -08001803 // Upon resuming an update, read the saved index first; then
1804 // 1. In verification mode, check if the 'move' or 'diff' commands before the saved index has
1805 // the expected target blocks already. If not, these commands cannot be skipped and we need
1806 // to attempt to execute them again. Therefore, we will delete the last_command_file so that
1807 // the update will resume from the start of the transfer list.
1808 // 2. In update mode, skip all commands before the saved index. Therefore, we can avoid deleting
1809 // stashes with duplicate id unintentionally (b/69858743); and also speed up the update.
1810 // If an update succeeds or is unresumable, delete the last_command_file.
Tao Bao26efb0a2018-05-21 14:59:55 -07001811 bool skip_executed_command = true;
1812 size_t saved_last_command_index;
Tianjie Xu284752e2017-12-05 11:04:17 -08001813 if (!ParseLastCommandFile(&saved_last_command_index)) {
1814 DeleteLastCommandFile();
Tao Bao26efb0a2018-05-21 14:59:55 -07001815 // We failed to parse the last command. Disallow skipping executed commands.
1816 skip_executed_command = false;
Tianjie Xu284752e2017-12-05 11:04:17 -08001817 }
1818
Tao Bao33567772017-03-13 14:57:34 -07001819 int rc = -1;
1820
1821 // Subsequent lines are all individual transfer commands
Tao Baoab207062018-05-21 14:48:49 -07001822 for (size_t i = kTransferListHeaderLines; i < lines.size(); i++) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001823 const std::string& line = lines[i];
Tao Bao33567772017-03-13 14:57:34 -07001824 if (line.empty()) continue;
1825
Tao Bao26efb0a2018-05-21 14:59:55 -07001826 size_t cmdindex = i - kTransferListHeaderLines;
Tao Bao33567772017-03-13 14:57:34 -07001827 params.tokens = android::base::Split(line, " ");
1828 params.cpos = 0;
Tao Baoc3901232018-05-21 16:05:56 -07001829 params.cmdname = params.tokens[params.cpos++];
1830 params.cmdline = line;
Tianjie Xu284752e2017-12-05 11:04:17 -08001831 params.target_verified = false;
Tao Bao33567772017-03-13 14:57:34 -07001832
Tao Baoc3901232018-05-21 16:05:56 -07001833 Command::Type cmd_type = Command::ParseType(params.cmdname);
1834 if (cmd_type == Command::Type::LAST) {
Tao Bao33567772017-03-13 14:57:34 -07001835 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1836 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001837 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001838
Tao Baoc3901232018-05-21 16:05:56 -07001839 const CommandFunction& performer = command_map.at(cmd_type);
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001840
Tianjie Xuc2420842018-02-27 17:05:39 -08001841 // Skip the command if we explicitly set the corresponding function pointer to nullptr, e.g.
1842 // "erase" during block_image_verify.
Tao Baoc3901232018-05-21 16:05:56 -07001843 if (performer == nullptr) {
Tianjie Xuc2420842018-02-27 17:05:39 -08001844 LOG(DEBUG) << "skip executing command [" << line << "]";
1845 continue;
Tianjie Xu284752e2017-12-05 11:04:17 -08001846 }
1847
Tao Bao98f875e2018-05-07 15:03:30 -07001848 // Skip all commands before the saved last command index when resuming an update, except for
1849 // "new" command. Because new commands read in the data sequentially.
Tao Bao26efb0a2018-05-21 14:59:55 -07001850 if (params.canwrite && skip_executed_command && cmdindex <= saved_last_command_index &&
Tao Baoc3901232018-05-21 16:05:56 -07001851 cmd_type != Command::Type::NEW) {
Tao Bao26efb0a2018-05-21 14:59:55 -07001852 LOG(INFO) << "Skipping already executed command: " << cmdindex
Tianjie Xu284752e2017-12-05 11:04:17 -08001853 << ", last executed command for previous update: " << saved_last_command_index;
1854 continue;
1855 }
1856
Tao Baoc3901232018-05-21 16:05:56 -07001857 if (performer(params) == -1) {
Tao Bao33567772017-03-13 14:57:34 -07001858 LOG(ERROR) << "failed to execute command [" << line << "]";
Tianjie Xu69ffa152018-08-01 16:40:00 -07001859 if (cmd_type == Command::Type::COMPUTE_HASH_TREE && failure_type == kNoCause) {
1860 failure_type = kHashTreeComputationFailure;
1861 }
Tao Bao33567772017-03-13 14:57:34 -07001862 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001863 }
1864
Tao Bao26efb0a2018-05-21 14:59:55 -07001865 // In verify mode, check if the commands before the saved last_command_index have been executed
1866 // correctly. If some target blocks have unexpected contents, delete the last command file so
1867 // that we will resume the update from the first command in the transfer list.
1868 if (!params.canwrite && skip_executed_command && cmdindex <= saved_last_command_index) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001869 // TODO(xunchang) check that the cmdline of the saved index is correct.
Tao Baoc3901232018-05-21 16:05:56 -07001870 if ((cmd_type == Command::Type::MOVE || cmd_type == Command::Type::BSDIFF ||
1871 cmd_type == Command::Type::IMGDIFF) &&
Tianjie Xu284752e2017-12-05 11:04:17 -08001872 !params.target_verified) {
1873 LOG(WARNING) << "Previously executed command " << saved_last_command_index << ": "
1874 << params.cmdline << " doesn't produce expected target blocks.";
Tao Bao26efb0a2018-05-21 14:59:55 -07001875 skip_executed_command = false;
Tianjie Xu284752e2017-12-05 11:04:17 -08001876 DeleteLastCommandFile();
1877 }
1878 }
Tao Baoc3901232018-05-21 16:05:56 -07001879
Sami Tolvanen90221202014-12-09 16:39:47 +00001880 if (params.canwrite) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001881 if (fsync(params.fd) == -1) {
1882 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001883 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001884 goto pbiudone;
1885 }
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001886
Tao Bao26efb0a2018-05-21 14:59:55 -07001887 if (!UpdateLastCommandIndex(cmdindex, params.cmdline)) {
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001888 LOG(WARNING) << "Failed to update the last command file.";
1889 }
1890
Tianjie Xu58d59122019-05-03 01:05:04 -07001891 updater->WriteToCommandPipe(
1892 android::base::StringPrintf("set_progress %.4f",
1893 static_cast<double>(params.written) / total_blocks),
1894 true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001895 }
Tao Bao33567772017-03-13 14:57:34 -07001896 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001897
Tao Bao33567772017-03-13 14:57:34 -07001898 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001899
Tao Bao33567772017-03-13 14:57:34 -07001900pbiudone:
Tianjie Xu5450c842017-10-18 13:15:21 -07001901 if (params.canwrite) {
1902 pthread_mutex_lock(&params.nti.mu);
1903 if (params.nti.receiver_available) {
1904 LOG(WARNING) << "new data receiver is still available after executing all commands.";
1905 }
1906 params.nti.receiver_available = false;
1907 pthread_cond_broadcast(&params.nti.cv);
1908 pthread_mutex_unlock(&params.nti.mu);
1909 int ret = pthread_join(params.thread, nullptr);
1910 if (ret != 0) {
1911 LOG(WARNING) << "pthread join returned with " << strerror(ret);
1912 }
1913
1914 if (rc == 0) {
1915 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1916 LOG(INFO) << "stashed " << params.stashed << " blocks";
1917 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1918
Tianjie Xu1536db82019-05-14 10:54:43 -07001919 const char* partition = strrchr(block_device_path.c_str(), '/');
Tianjie Xu5450c842017-10-18 13:15:21 -07001920 if (partition != nullptr && *(partition + 1) != 0) {
Tianjie Xu58d59122019-05-03 01:05:04 -07001921 updater->WriteToCommandPipe(
1922 android::base::StringPrintf("log bytes_written_%s: %" PRIu64, partition + 1,
1923 static_cast<uint64_t>(params.written) * BLOCKSIZE));
1924 updater->WriteToCommandPipe(
1925 android::base::StringPrintf("log bytes_stashed_%s: %" PRIu64, partition + 1,
1926 static_cast<uint64_t>(params.stashed) * BLOCKSIZE),
1927 true);
Tianjie Xu5450c842017-10-18 13:15:21 -07001928 }
1929 // Delete stash only after successfully completing the update, as it may contain blocks needed
1930 // to complete the update later.
1931 DeleteStash(params.stashbase);
Tianjie Xu284752e2017-12-05 11:04:17 -08001932 DeleteLastCommandFile();
Tao Bao864c6682018-05-07 11:38:25 -07001933
1934 // Create a marker on /cache partition, which allows skipping the update on this partition on
1935 // retry. The marker will be removed once booting into normal boot, or before starting next
1936 // fresh install.
Yifan Hong8ff84d72018-12-19 16:21:55 -08001937 if (!SetUpdatedMarker(updated_marker)) {
Tao Bao864c6682018-05-07 11:38:25 -07001938 LOG(WARNING) << "Failed to set updated marker; continuing";
1939 }
Tianjie Xu5450c842017-10-18 13:15:21 -07001940 }
1941
1942 pthread_mutex_destroy(&params.nti.mu);
1943 pthread_cond_destroy(&params.nti.cv);
1944 } else if (rc == 0) {
1945 LOG(INFO) << "verified partition contents; update may be resumed";
1946 }
1947
Tianjie Xu22f11202018-08-27 10:50:31 -07001948 if (fsync(params.fd) == -1) {
1949 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Bao33567772017-03-13 14:57:34 -07001950 PLOG(ERROR) << "fsync failed";
1951 }
1952 // params.fd will be automatically closed because it's a unique_fd.
1953
Tianjie Xu107a34f2017-06-29 17:04:21 -07001954 if (params.nti.brotli_decoder_state != nullptr) {
1955 BrotliDecoderDestroyInstance(params.nti.brotli_decoder_state);
1956 }
1957
Tianjie Xu284752e2017-12-05 11:04:17 -08001958 // Delete the last command file if the update cannot be resumed.
1959 if (params.isunresumable) {
1960 DeleteLastCommandFile();
1961 }
1962
Tao Bao33567772017-03-13 14:57:34 -07001963 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1964 // created the stash.
1965 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1966 DeleteStash(params.stashbase);
1967 }
1968
1969 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1970 state->cause_code = failure_type;
1971 }
1972
1973 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001974}
1975
Tao Bao33567772017-03-13 14:57:34 -07001976/**
1977 * The transfer list is a text file containing commands to transfer data from one place to another
1978 * on the target partition. We parse it and execute the commands in order:
1979 *
1980 * zero [rangeset]
1981 * - Fill the indicated blocks with zeros.
1982 *
1983 * new [rangeset]
1984 * - Fill the blocks with data read from the new_data file.
1985 *
1986 * erase [rangeset]
1987 * - Mark the given blocks as empty.
1988 *
1989 * move <...>
1990 * bsdiff <patchstart> <patchlen> <...>
1991 * imgdiff <patchstart> <patchlen> <...>
1992 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1993 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1994 *
1995 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1996 *
1997 * stash <stash_id> <src_range>
1998 * - Load the given source range and stash the data in the given slot of the stash table.
1999 *
2000 * free <stash_id>
2001 * - Free the given stash data.
2002 *
2003 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
2004 * a patch or move) after it has been written.
2005 *
2006 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
2007 * in a move/bsdiff/imgdiff command.
2008 *
2009 * Within one command the source and target ranges may overlap so in general we need to read the
2010 * entire source into memory before writing anything to the target blocks.
2011 *
2012 * All the patch data is concatenated into one patch_data file in the update package. It must be
2013 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
2014 * already compressed, we lose very little by not compressing their concatenation.)
2015 *
2016 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
2017 * additional hashes before the range parameters, which are used to check if the command has already
2018 * been completed and verify the integrity of the source data.
2019 */
Tianjie Xuc4447322017-03-06 14:44:59 -08002020Value* BlockImageVerifyFn(const char* name, State* state,
2021 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc3901232018-05-21 16:05:56 -07002022 // Commands which are not allowed are set to nullptr to skip them completely.
2023 const CommandMap command_map{
2024 // clang-format off
Tianjie Xu69ffa152018-08-01 16:40:00 -07002025 { Command::Type::ABORT, PerformCommandAbort },
2026 { Command::Type::BSDIFF, PerformCommandDiff },
Tianjie Xu3fda5d62019-05-09 10:58:10 -07002027 { Command::Type::COMPUTE_HASH_TREE, nullptr },
Tianjie Xu69ffa152018-08-01 16:40:00 -07002028 { Command::Type::ERASE, nullptr },
2029 { Command::Type::FREE, PerformCommandFree },
2030 { Command::Type::IMGDIFF, PerformCommandDiff },
2031 { Command::Type::MOVE, PerformCommandMove },
2032 { Command::Type::NEW, nullptr },
2033 { Command::Type::STASH, PerformCommandStash },
2034 { Command::Type::ZERO, nullptr },
Tao Baoc3901232018-05-21 16:05:56 -07002035 // clang-format on
2036 };
2037 CHECK_EQ(static_cast<size_t>(Command::Type::LAST), command_map.size());
Sami Tolvanen90221202014-12-09 16:39:47 +00002038
Tao Baoc3901232018-05-21 16:05:56 -07002039 // Perform a dry run without writing to test if an update can proceed.
2040 return PerformBlockImageUpdate(name, state, argv, command_map, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00002041}
2042
Tianjie Xuc4447322017-03-06 14:44:59 -08002043Value* BlockImageUpdateFn(const char* name, State* state,
2044 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc3901232018-05-21 16:05:56 -07002045 const CommandMap command_map{
2046 // clang-format off
Tianjie Xu69ffa152018-08-01 16:40:00 -07002047 { Command::Type::ABORT, PerformCommandAbort },
2048 { Command::Type::BSDIFF, PerformCommandDiff },
2049 { Command::Type::COMPUTE_HASH_TREE, PerformCommandComputeHashTree },
2050 { Command::Type::ERASE, PerformCommandErase },
2051 { Command::Type::FREE, PerformCommandFree },
2052 { Command::Type::IMGDIFF, PerformCommandDiff },
2053 { Command::Type::MOVE, PerformCommandMove },
2054 { Command::Type::NEW, PerformCommandNew },
2055 { Command::Type::STASH, PerformCommandStash },
2056 { Command::Type::ZERO, PerformCommandZero },
Tao Baoc3901232018-05-21 16:05:56 -07002057 // clang-format on
2058 };
2059 CHECK_EQ(static_cast<size_t>(Command::Type::LAST), command_map.size());
Sami Tolvanen90221202014-12-09 16:39:47 +00002060
Tao Baoc3901232018-05-21 16:05:56 -07002061 return PerformBlockImageUpdate(name, state, argv, command_map, false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002062}
2063
Tianjie Xuc4447322017-03-06 14:44:59 -08002064Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002065 if (argv.size() != 2) {
2066 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
2067 return StringValue("");
2068 }
2069
2070 std::vector<std::unique_ptr<Value>> args;
2071 if (!ReadValueArgs(state, argv, &args)) {
2072 return nullptr;
2073 }
2074
2075 const std::unique_ptr<Value>& blockdev_filename = args[0];
2076 const std::unique_ptr<Value>& ranges = args[1];
2077
Tao Bao511d7592018-06-19 15:56:49 -07002078 if (blockdev_filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002079 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
2080 return StringValue("");
2081 }
Tao Bao511d7592018-06-19 15:56:49 -07002082 if (ranges->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002083 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2084 return StringValue("");
2085 }
2086
Tianjie Xu1536db82019-05-14 10:54:43 -07002087 auto block_device_path = state->updater->FindBlockDeviceName(blockdev_filename->data);
2088 if (block_device_path.empty()) {
2089 LOG(ERROR) << "Block device path for " << blockdev_filename->data << " not found. " << name
2090 << " failed.";
2091 return StringValue("");
2092 }
2093
2094 android::base::unique_fd fd(open(block_device_path.c_str(), O_RDWR));
Tao Baoc97edcb2017-03-31 01:18:13 -07002095 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002096 CauseCode cause_code = errno == EIO ? kEioFailure : kFileOpenFailure;
Tianjie Xu1536db82019-05-14 10:54:43 -07002097 ErrorAbort(state, cause_code, "open \"%s\" failed: %s", block_device_path.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002098 strerror(errno));
2099 return StringValue("");
2100 }
2101
2102 RangeSet rs = RangeSet::Parse(ranges->data);
Tao Bao67983152017-11-04 00:08:08 -07002103 CHECK(static_cast<bool>(rs));
Tao Baoc97edcb2017-03-31 01:18:13 -07002104
2105 SHA_CTX ctx;
2106 SHA1_Init(&ctx);
2107
2108 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao43bfa6e2018-08-28 10:09:13 -07002109 for (const auto& [begin, end] : rs) {
2110 if (!check_lseek(fd, static_cast<off64_t>(begin) * BLOCKSIZE, SEEK_SET)) {
Tianjie Xu1536db82019-05-14 10:54:43 -07002111 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", block_device_path.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002112 strerror(errno));
2113 return StringValue("");
2114 }
2115
Tao Bao43bfa6e2018-08-28 10:09:13 -07002116 for (size_t j = begin; j < end; ++j) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002117 if (!android::base::ReadFully(fd, buffer.data(), BLOCKSIZE)) {
2118 CauseCode cause_code = errno == EIO ? kEioFailure : kFreadFailure;
Tianjie Xu1536db82019-05-14 10:54:43 -07002119 ErrorAbort(state, cause_code, "failed to read %s: %s", block_device_path.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002120 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002121 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002122 }
2123
2124 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08002125 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002126 }
2127 uint8_t digest[SHA_DIGEST_LENGTH];
2128 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08002129
Tao Baoc97edcb2017-03-31 01:18:13 -07002130 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002131}
2132
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002133// This function checks if a device has been remounted R/W prior to an incremental
2134// OTA update. This is an common cause of update abortion. The function reads the
2135// 1st block of each partition and check for mounting time/count. It return string "t"
2136// if executes successfully and an empty string otherwise.
2137
Tianjie Xuc4447322017-03-06 14:44:59 -08002138Value* CheckFirstBlockFn(const char* name, State* state,
2139 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002140 if (argv.size() != 1) {
2141 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
2142 argv.size());
2143 return StringValue("");
2144 }
Tianjie Xuc4447322017-03-06 14:44:59 -08002145
Tao Baoc97edcb2017-03-31 01:18:13 -07002146 std::vector<std::unique_ptr<Value>> args;
2147 if (!ReadValueArgs(state, argv, &args)) {
2148 return nullptr;
2149 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002150
Tao Baoc97edcb2017-03-31 01:18:13 -07002151 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07002152
Tao Bao511d7592018-06-19 15:56:49 -07002153 if (arg_filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002154 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2155 return StringValue("");
2156 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002157
Tianjie Xu1536db82019-05-14 10:54:43 -07002158 auto block_device_path = state->updater->FindBlockDeviceName(arg_filename->data);
2159 if (block_device_path.empty()) {
2160 LOG(ERROR) << "Block device path for " << arg_filename->data << " not found. " << name
2161 << " failed.";
2162 return StringValue("");
2163 }
2164
2165 android::base::unique_fd fd(open(block_device_path.c_str(), O_RDONLY));
Tao Baoc97edcb2017-03-31 01:18:13 -07002166 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002167 CauseCode cause_code = errno == EIO ? kEioFailure : kFileOpenFailure;
Tianjie Xu1536db82019-05-14 10:54:43 -07002168 ErrorAbort(state, cause_code, "open \"%s\" failed: %s", block_device_path.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002169 strerror(errno));
2170 return StringValue("");
2171 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002172
Tao Baobf5b77d2017-03-30 16:57:29 -07002173 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07002174 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002175
Tao Baode3bbb82018-05-30 16:14:14 -07002176 if (ReadBlocks(blk0, &block0_buffer, fd) == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002177 CauseCode cause_code = errno == EIO ? kEioFailure : kFreadFailure;
Tianjie Xu1536db82019-05-14 10:54:43 -07002178 ErrorAbort(state, cause_code, "failed to read %s: %s", block_device_path.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002179 strerror(errno));
2180 return StringValue("");
2181 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002182
Tao Baoc97edcb2017-03-31 01:18:13 -07002183 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
2184 // Super block starts from block 0, offset 0x400
2185 // 0x2C: len32 Mount time
2186 // 0x30: len32 Write time
2187 // 0x34: len16 Number of mounts since the last fsck
2188 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002189
Tao Baoc97edcb2017-03-31 01:18:13 -07002190 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
2191 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002192
Tao Baoc97edcb2017-03-31 01:18:13 -07002193 if (mount_count > 0) {
Tianjie Xu1536db82019-05-14 10:54:43 -07002194 state->updater->UiPrint(
Tianjie Xu58d59122019-05-03 01:05:04 -07002195 android::base::StringPrintf("Device was remounted R/W %" PRIu16 " times", mount_count));
Tianjie Xu1536db82019-05-14 10:54:43 -07002196 state->updater->UiPrint(
Tianjie Xu58d59122019-05-03 01:05:04 -07002197 android::base::StringPrintf("Last remount happened on %s", ctime(&mount_time)));
Tao Baoc97edcb2017-03-31 01:18:13 -07002198 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002199
Tao Baoc97edcb2017-03-31 01:18:13 -07002200 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002201}
2202
Tianjie Xuc4447322017-03-06 14:44:59 -08002203Value* BlockImageRecoverFn(const char* name, State* state,
2204 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002205 if (argv.size() != 2) {
2206 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
2207 argv.size());
2208 return StringValue("");
2209 }
2210
2211 std::vector<std::unique_ptr<Value>> args;
2212 if (!ReadValueArgs(state, argv, &args)) {
2213 return nullptr;
2214 }
2215
2216 const std::unique_ptr<Value>& filename = args[0];
2217 const std::unique_ptr<Value>& ranges = args[1];
2218
Tao Bao511d7592018-06-19 15:56:49 -07002219 if (filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002220 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2221 return StringValue("");
2222 }
Tao Bao511d7592018-06-19 15:56:49 -07002223 if (ranges->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002224 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2225 return StringValue("");
2226 }
Tao Bao67983152017-11-04 00:08:08 -07002227 RangeSet rs = RangeSet::Parse(ranges->data);
2228 if (!rs) {
2229 ErrorAbort(state, kArgsParsingFailure, "failed to parse ranges: %s", ranges->data.c_str());
2230 return StringValue("");
2231 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002232
Tianjie Xu1536db82019-05-14 10:54:43 -07002233 auto block_device_path = state->updater->FindBlockDeviceName(filename->data);
2234 if (block_device_path.empty()) {
2235 LOG(ERROR) << "Block device path for " << filename->data << " not found. " << name
2236 << " failed.";
2237 return StringValue("");
2238 }
2239
Tao Baoc97edcb2017-03-31 01:18:13 -07002240 // Output notice to log when recover is attempted
Tianjie Xu1536db82019-05-14 10:54:43 -07002241 LOG(INFO) << block_device_path << " image corrupted, attempting to recover...";
Tao Baoc97edcb2017-03-31 01:18:13 -07002242
2243 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tianjie Xu1536db82019-05-14 10:54:43 -07002244 fec::io fh(block_device_path, O_RDWR);
Tao Baoc97edcb2017-03-31 01:18:13 -07002245
2246 if (!fh) {
Tianjie Xu1536db82019-05-14 10:54:43 -07002247 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", block_device_path.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002248 strerror(errno));
2249 return StringValue("");
2250 }
2251
2252 if (!fh.has_ecc() || !fh.has_verity()) {
2253 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
2254 return StringValue("");
2255 }
2256
2257 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07002258 if (!fh.get_status(status)) {
2259 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
2260 return StringValue("");
2261 }
2262
Tao Baoc97edcb2017-03-31 01:18:13 -07002263 uint8_t buffer[BLOCKSIZE];
Tao Bao43bfa6e2018-08-28 10:09:13 -07002264 for (const auto& [begin, end] : rs) {
2265 for (size_t j = begin; j < end; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002266 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07002267 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002268 continue;
2269 }
2270
Tao Baobf5b77d2017-03-30 16:57:29 -07002271 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002272 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xu1536db82019-05-14 10:54:43 -07002273 block_device_path.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002274 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002275 }
2276
2277 // If we want to be able to recover from a situation where rewriting a corrected
2278 // block doesn't guarantee the same data will be returned when re-read later, we
2279 // can save a copy of corrected blocks to /cache. Note:
2280 //
2281 // 1. Maximum space required from /cache is the same as the maximum number of
2282 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
2283 // this would be ~16 MiB, for example.
2284 //
2285 // 2. To find out if this block was corrupted, call fec_get_status after each
2286 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08002287 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002288 }
Tianjie Xu1536db82019-05-14 10:54:43 -07002289 LOG(INFO) << "..." << block_device_path << " image recovered successfully.";
Tao Baoc97edcb2017-03-31 01:18:13 -07002290 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002291}
2292
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002293void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07002294 RegisterFunction("block_image_verify", BlockImageVerifyFn);
2295 RegisterFunction("block_image_update", BlockImageUpdateFn);
2296 RegisterFunction("block_image_recover", BlockImageRecoverFn);
2297 RegisterFunction("check_first_block", CheckFirstBlockFn);
2298 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002299}