blob: 8388456739e74117ebdd7a53a8482deac92c0dcd [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>
45#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070046#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080047#include <applypatch/applypatch.h>
Tianjie Xu107a34f2017-06-29 17:04:21 -070048#include <brotli/decode.h>
Tao Bao641fa972018-04-25 18:59:40 -070049#include <fec/io.h>
Tao Bao51412212016-12-28 14:44:05 -080050#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070051#include <private/android_filesystem_config.h>
Tianjie Xu69ffa152018-08-01 16:40:00 -070052#include <verity/hash_tree_builder.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070053#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070054
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070055#include "edify/expr.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070056#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070057#include "otautil/paths.h"
Tao Bao09e468f2017-09-29 14:39:33 -070058#include "otautil/print_sha1.h"
59#include "otautil/rangeset.h"
Tao Baoc3901232018-05-21 16:05:56 -070060#include "private/commands.h"
Tao Bao8f237572017-03-26 13:36:49 -070061#include "updater/install.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070062#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070063
Sami Tolvanene82fa182015-06-10 15:58:12 +000064// Set this to 0 to interpret 'erase' transfers to mean do a
65// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
66// erase to mean fill the region with zeroes.
67#define DEBUG_ERASE 0
68
Tao Bao51412212016-12-28 14:44:05 -080069static constexpr size_t BLOCKSIZE = 4096;
Tao Bao51412212016-12-28 14:44:05 -080070static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
71static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000072
Tianjie Xu16255832016-04-30 11:49:59 -070073static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070074static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070075static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070076
Tianjie Xu284752e2017-12-05 11:04:17 -080077static void DeleteLastCommandFile() {
Tao Bao641fa972018-04-25 18:59:40 -070078 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080079 if (unlink(last_command_file.c_str()) == -1 && errno != ENOENT) {
80 PLOG(ERROR) << "Failed to unlink: " << last_command_file;
81 }
82}
83
84// Parse the last command index of the last update and save the result to |last_command_index|.
85// Return true if we successfully read the index.
Tao Bao26efb0a2018-05-21 14:59:55 -070086static bool ParseLastCommandFile(size_t* last_command_index) {
Tao Bao641fa972018-04-25 18:59:40 -070087 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080088 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(last_command_file.c_str(), O_RDONLY)));
89 if (fd == -1) {
90 if (errno != ENOENT) {
91 PLOG(ERROR) << "Failed to open " << last_command_file;
92 return false;
93 }
94
95 LOG(INFO) << last_command_file << " doesn't exist.";
96 return false;
97 }
98
99 // Now that the last_command file exists, parse the last command index of previous update.
100 std::string content;
101 if (!android::base::ReadFdToString(fd.get(), &content)) {
102 LOG(ERROR) << "Failed to read: " << last_command_file;
103 return false;
104 }
105
106 std::vector<std::string> lines = android::base::Split(android::base::Trim(content), "\n");
107 if (lines.size() != 2) {
108 LOG(ERROR) << "Unexpected line counts in last command file: " << content;
109 return false;
110 }
111
112 if (!android::base::ParseInt(lines[0], last_command_index)) {
113 LOG(ERROR) << "Failed to parse integer in: " << lines[0];
114 return false;
115 }
116
117 return true;
118}
119
Tao Bao864c6682018-05-07 11:38:25 -0700120static bool FsyncDir(const std::string& dirname) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700121 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_DIRECTORY)));
Tao Bao864c6682018-05-07 11:38:25 -0700122 if (dfd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700123 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Bao864c6682018-05-07 11:38:25 -0700124 PLOG(ERROR) << "Failed to open " << dirname;
125 return false;
126 }
127 if (fsync(dfd) == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700128 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Bao864c6682018-05-07 11:38:25 -0700129 PLOG(ERROR) << "Failed to fsync " << dirname;
130 return false;
131 }
132 return true;
133}
134
Tianjie Xuc2b2bb52018-05-15 15:09:59 -0700135// Update the last executed command index in the last_command_file.
Tao Bao26efb0a2018-05-21 14:59:55 -0700136static bool UpdateLastCommandIndex(size_t command_index, const std::string& command_string) {
Tao Bao641fa972018-04-25 18:59:40 -0700137 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -0800138 std::string last_command_tmp = last_command_file + ".tmp";
139 std::string content = std::to_string(command_index) + "\n" + command_string;
140 android::base::unique_fd wfd(
141 TEMP_FAILURE_RETRY(open(last_command_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0660)));
142 if (wfd == -1 || !android::base::WriteStringToFd(content, wfd)) {
143 PLOG(ERROR) << "Failed to update last command";
144 return false;
145 }
146
147 if (fsync(wfd) == -1) {
148 PLOG(ERROR) << "Failed to fsync " << last_command_tmp;
149 return false;
150 }
151
152 if (chown(last_command_tmp.c_str(), AID_SYSTEM, AID_SYSTEM) == -1) {
153 PLOG(ERROR) << "Failed to change owner for " << last_command_tmp;
154 return false;
155 }
156
157 if (rename(last_command_tmp.c_str(), last_command_file.c_str()) == -1) {
158 PLOG(ERROR) << "Failed to rename" << last_command_tmp;
159 return false;
160 }
161
Tao Bao864c6682018-05-07 11:38:25 -0700162 if (!FsyncDir(android::base::Dirname(last_command_file))) {
Tianjie Xu284752e2017-12-05 11:04:17 -0800163 return false;
164 }
165
Tao Bao864c6682018-05-07 11:38:25 -0700166 return true;
167}
168
169static bool SetPartitionUpdatedMarker(const std::string& marker) {
170 if (!android::base::WriteStringToFile("", marker)) {
171 PLOG(ERROR) << "Failed to write to marker file " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800172 return false;
173 }
Tao Bao864c6682018-05-07 11:38:25 -0700174 if (!FsyncDir(android::base::Dirname(marker))) {
175 return false;
176 }
177 LOG(INFO) << "Wrote partition updated marker to " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800178 return true;
179}
180
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700181static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700182 // Don't discard blocks unless the update is a retry run.
183 if (!is_retry) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700184 return true;
Tao Baobf5b77d2017-03-30 16:57:29 -0700185 }
186
187 uint64_t args[2] = { static_cast<uint64_t>(offset), size };
188 if (ioctl(fd, BLKDISCARD, &args) == -1) {
189 PLOG(ERROR) << "BLKDISCARD ioctl failed";
190 return false;
191 }
192 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700193}
194
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700195static bool check_lseek(int fd, off64_t offset, int whence) {
196 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
197 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700198 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800199 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700200 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700201 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700202 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700203}
204
Tao Baode3bbb82018-05-30 16:14:14 -0700205static void allocate(size_t size, std::vector<uint8_t>* buffer) {
206 // If the buffer's big enough, reuse it.
207 if (size <= buffer->size()) return;
208 buffer->resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700209}
210
Tao Bao60a70af2017-03-26 14:03:52 -0700211/**
212 * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
213 * given RangeSet.
214 */
215class RangeSinkWriter {
216 public:
217 RangeSinkWriter(int fd, const RangeSet& tgt)
Tianjie Xu107a34f2017-06-29 17:04:21 -0700218 : fd_(fd),
219 tgt_(tgt),
220 next_range_(0),
221 current_range_left_(0),
222 bytes_written_(0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700223 CHECK_NE(tgt.size(), static_cast<size_t>(0));
Tao Bao60a70af2017-03-26 14:03:52 -0700224 };
Tao Bao0940fe12015-08-27 16:41:21 -0700225
Tao Bao60a70af2017-03-26 14:03:52 -0700226 bool Finished() const {
Tao Baobf5b77d2017-03-30 16:57:29 -0700227 return next_range_ == tgt_.size() && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700228 }
229
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700230 size_t AvailableSpace() const {
231 return tgt_.blocks() * BLOCKSIZE - bytes_written_;
232 }
233
234 // Return number of bytes written; and 0 indicates a writing failure.
235 size_t Write(const uint8_t* data, size_t size) {
Tao Bao60a70af2017-03-26 14:03:52 -0700236 if (Finished()) {
237 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
238 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700239 }
240
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700241 size_t written = 0;
Tao Bao60a70af2017-03-26 14:03:52 -0700242 while (size > 0) {
243 // Move to the next range as needed.
Tianjie Xu107a34f2017-06-29 17:04:21 -0700244 if (!SeekToOutputRange()) {
245 break;
Tao Bao60a70af2017-03-26 14:03:52 -0700246 }
Tao Baof7eb7602017-03-27 15:12:48 -0700247
Tao Bao60a70af2017-03-26 14:03:52 -0700248 size_t write_now = size;
249 if (current_range_left_ < write_now) {
250 write_now = current_range_left_;
251 }
Tao Baof7eb7602017-03-27 15:12:48 -0700252
Tianjie Xu22f11202018-08-27 10:50:31 -0700253 if (!android::base::WriteFully(fd_, data, write_now)) {
254 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
255 PLOG(ERROR) << "Failed to write " << write_now << " bytes of data";
Tao Baof7eb7602017-03-27 15:12:48 -0700256 break;
257 }
Tao Bao60a70af2017-03-26 14:03:52 -0700258
259 data += write_now;
260 size -= write_now;
261
262 current_range_left_ -= write_now;
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700263 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700264 }
Tao Bao60a70af2017-03-26 14:03:52 -0700265
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700266 bytes_written_ += written;
267 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700268 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700269
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700270 size_t BytesWritten() const {
271 return bytes_written_;
272 }
273
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700274 private:
Tianjie Xu107a34f2017-06-29 17:04:21 -0700275 // Set up the output cursor, move to next range if needed.
276 bool SeekToOutputRange() {
277 // We haven't finished the current range yet.
278 if (current_range_left_ != 0) {
279 return true;
280 }
281 // We can't write any more; let the write function return how many bytes have been written
282 // so far.
283 if (next_range_ >= tgt_.size()) {
284 return false;
285 }
286
287 const Range& range = tgt_[next_range_];
288 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
289 current_range_left_ = (range.second - range.first) * BLOCKSIZE;
290 next_range_++;
291
292 if (!discard_blocks(fd_, offset, current_range_left_)) {
293 return false;
294 }
295 if (!check_lseek(fd_, offset, SEEK_SET)) {
296 return false;
297 }
298 return true;
299 }
300
301 // The output file descriptor.
Tao Bao60a70af2017-03-26 14:03:52 -0700302 int fd_;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700303 // The destination ranges for the data.
Tao Bao60a70af2017-03-26 14:03:52 -0700304 const RangeSet& tgt_;
305 // The next range that we should write to.
306 size_t next_range_;
307 // The number of bytes to write before moving to the next range.
308 size_t current_range_left_;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700309 // Total bytes written by the writer.
310 size_t bytes_written_;
Tao Bao60a70af2017-03-26 14:03:52 -0700311};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700312
Tao Bao60a70af2017-03-26 14:03:52 -0700313/**
314 * All of the data for all the 'new' transfers is contained in one file in the update package,
315 * concatenated together in the order in which transfers.list will need it. We want to stream it out
316 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
317 * section until it's that transfer's turn to go.
318 *
319 * To achieve this, we expand the new data from the archive in a background thread, and block that
320 * threads 'receive uncompressed data' function until the main thread has reached a point where we
321 * want some new data to be written. We signal the background thread with the destination for the
322 * data and block the main thread, waiting for the background thread to complete writing that
323 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
324 * transfer.
325 *
326 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
327 * the main thread wants some data written, it sets writer to the destination location and signals
328 * the condition. When the background thread is done writing, it clears writer and signals the
329 * condition again.
330 */
Tao Bao0940fe12015-08-27 16:41:21 -0700331struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700332 ZipArchiveHandle za;
333 ZipEntry entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700334 bool brotli_compressed;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700335
Tianjie Xu107a34f2017-06-29 17:04:21 -0700336 std::unique_ptr<RangeSinkWriter> writer;
337 BrotliDecoderState* brotli_decoder_state;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700338 bool receiver_available;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700339
Tao Bao60a70af2017-03-26 14:03:52 -0700340 pthread_mutex_t mu;
341 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700342};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700343
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700344static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700345 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700346
Tao Bao60a70af2017-03-26 14:03:52 -0700347 while (size > 0) {
348 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
349 pthread_mutex_lock(&nti->mu);
350 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700351 // End the new data receiver if we encounter an error when performing block image update.
352 if (!nti->receiver_available) {
353 pthread_mutex_unlock(&nti->mu);
354 return false;
355 }
Tao Bao60a70af2017-03-26 14:03:52 -0700356 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700357 }
Tao Bao60a70af2017-03-26 14:03:52 -0700358 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700359
Tao Bao60a70af2017-03-26 14:03:52 -0700360 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
361 // disappear from nti.
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700362 size_t write_now = std::min(size, nti->writer->AvailableSpace());
363 if (nti->writer->Write(data, write_now) != write_now) {
364 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
Tianjie Xu107a34f2017-06-29 17:04:21 -0700365 return false;
366 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700367
368 data += write_now;
369 size -= write_now;
370
371 if (nti->writer->Finished()) {
372 // We have written all the bytes desired by this writer.
373
374 pthread_mutex_lock(&nti->mu);
375 nti->writer = nullptr;
376 pthread_cond_broadcast(&nti->cv);
377 pthread_mutex_unlock(&nti->mu);
378 }
379 }
380
381 return true;
382}
383
384static bool receive_brotli_new_data(const uint8_t* data, size_t size, void* cookie) {
385 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
386
387 while (size > 0 || BrotliDecoderHasMoreOutput(nti->brotli_decoder_state)) {
388 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
389 pthread_mutex_lock(&nti->mu);
390 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700391 // End the receiver if we encounter an error when performing block image update.
392 if (!nti->receiver_available) {
393 pthread_mutex_unlock(&nti->mu);
394 return false;
395 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700396 pthread_cond_wait(&nti->cv, &nti->mu);
397 }
398 pthread_mutex_unlock(&nti->mu);
399
400 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
401 // disappear from nti.
402
403 size_t buffer_size = std::min<size_t>(32768, nti->writer->AvailableSpace());
404 if (buffer_size == 0) {
405 LOG(ERROR) << "No space left in output range";
406 return false;
407 }
408 uint8_t buffer[buffer_size];
409 size_t available_in = size;
410 size_t available_out = buffer_size;
411 uint8_t* next_out = buffer;
412
413 // The brotli decoder will update |data|, |available_in|, |next_out| and |available_out|.
414 BrotliDecoderResult result = BrotliDecoderDecompressStream(
415 nti->brotli_decoder_state, &available_in, &data, &available_out, &next_out, nullptr);
416
417 if (result == BROTLI_DECODER_RESULT_ERROR) {
418 LOG(ERROR) << "Decompression failed with "
419 << BrotliDecoderErrorString(BrotliDecoderGetErrorCode(nti->brotli_decoder_state));
420 return false;
421 }
422
423 LOG(DEBUG) << "bytes to write: " << buffer_size - available_out << ", bytes consumed "
424 << size - available_in << ", decoder status " << result;
425
426 size_t write_now = buffer_size - available_out;
427 if (nti->writer->Write(buffer, write_now) != write_now) {
428 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
429 return false;
430 }
431
432 // Update the remaining size. The input data ptr is already updated by brotli decoder function.
433 size = available_in;
Tao Bao60a70af2017-03-26 14:03:52 -0700434
435 if (nti->writer->Finished()) {
436 // We have written all the bytes desired by this writer.
437
438 pthread_mutex_lock(&nti->mu);
439 nti->writer = nullptr;
440 pthread_cond_broadcast(&nti->cv);
441 pthread_mutex_unlock(&nti->mu);
442 }
443 }
444
445 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700446}
447
448static void* unzip_new_data(void* cookie) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700449 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700450 if (nti->brotli_compressed) {
451 ProcessZipEntryContents(nti->za, &nti->entry, receive_brotli_new_data, nti);
452 } else {
453 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
454 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700455 pthread_mutex_lock(&nti->mu);
456 nti->receiver_available = false;
457 if (nti->writer != nullptr) {
458 pthread_cond_broadcast(&nti->cv);
459 }
460 pthread_mutex_unlock(&nti->mu);
461 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700462}
463
Tao Baode3bbb82018-05-30 16:14:14 -0700464static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>* buffer, int fd) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700465 size_t p = 0;
Tao Bao43bfa6e2018-08-28 10:09:13 -0700466 for (const auto& [begin, end] : src) {
467 if (!check_lseek(fd, static_cast<off64_t>(begin) * BLOCKSIZE, SEEK_SET)) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700468 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000469 }
470
Tao Bao43bfa6e2018-08-28 10:09:13 -0700471 size_t size = (end - begin) * BLOCKSIZE;
Tianjie Xu22f11202018-08-27 10:50:31 -0700472 if (!android::base::ReadFully(fd, buffer->data() + p, size)) {
473 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
474 PLOG(ERROR) << "Failed to read " << size << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -0700475 return -1;
476 }
477
478 p += size;
479 }
480
481 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000482}
483
Tao Bao612336d2015-08-27 16:41:21 -0700484static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700485 size_t written = 0;
Tao Bao43bfa6e2018-08-28 10:09:13 -0700486 for (const auto& [begin, end] : tgt) {
487 off64_t offset = static_cast<off64_t>(begin) * BLOCKSIZE;
488 size_t size = (end - begin) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700489 if (!discard_blocks(fd, offset, size)) {
490 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000491 }
492
Tao Bao60a70af2017-03-26 14:03:52 -0700493 if (!check_lseek(fd, offset, SEEK_SET)) {
494 return -1;
495 }
496
Tianjie Xu22f11202018-08-27 10:50:31 -0700497 if (!android::base::WriteFully(fd, buffer.data() + written, size)) {
498 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
499 PLOG(ERROR) << "Failed to write " << size << " bytes of data";
Tao Bao60a70af2017-03-26 14:03:52 -0700500 return -1;
501 }
502
503 written += size;
504 }
505
506 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000507}
508
Tao Baobaad2d42015-12-06 16:56:27 -0800509// Parameters for transfer list command functions
510struct CommandParameters {
511 std::vector<std::string> tokens;
512 size_t cpos;
Tao Baoc3901232018-05-21 16:05:56 -0700513 std::string cmdname;
514 std::string cmdline;
Tao Baobaad2d42015-12-06 16:56:27 -0800515 std::string freestash;
516 std::string stashbase;
517 bool canwrite;
518 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700519 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800520 bool foundwrites;
521 bool isunresumable;
522 int version;
523 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700524 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800525 NewThreadInfo nti;
526 pthread_t thread;
527 std::vector<uint8_t> buffer;
528 uint8_t* patch_start;
Tianjie Xu284752e2017-12-05 11:04:17 -0800529 bool target_verified; // The target blocks have expected contents already.
Tao Baobaad2d42015-12-06 16:56:27 -0800530};
531
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000532// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
533// handled separately).
534static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
535 const std::vector<uint8_t>& buffer) {
536 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000537 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
538 params.tokens[0] == "imgdiff");
539
540 size_t pos = 0;
541 // Command example:
542 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
543 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
544 // [<loc_range> <stashed_blocks>]
545 if (params.tokens[0] == "move") {
546 // src_range for move starts at the 4th position.
547 if (params.tokens.size() < 5) {
548 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
549 return;
550 }
551 pos = 4;
552 } else {
553 // src_range for diff starts at the 7th position.
554 if (params.tokens.size() < 8) {
555 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
556 return;
557 }
558 pos = 7;
559 }
560
561 // Source blocks in stash only, no work to do.
562 if (params.tokens[pos] == "-") {
563 return;
564 }
565
Tao Bao8f237572017-03-26 13:36:49 -0700566 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tao Bao67983152017-11-04 00:08:08 -0700567 if (!src) {
568 LOG(ERROR) << "Failed to parse range in " << params.cmdline;
569 return;
570 }
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000571
572 RangeSet locs;
573 // If there's no stashed blocks, content in the buffer is consecutive and has the same
574 // order as the source blocks.
575 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700576 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000577 } else {
578 // Otherwise, the next token is the offset of the source blocks in the target range.
579 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
580 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
581 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700582 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700583 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000584 }
585
Tao Baobf5b77d2017-03-30 16:57:29 -0700586 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
587 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700588 size_t block_num = src.GetBlockNumber(i);
589 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000590 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
591
592 uint8_t digest[SHA_DIGEST_LENGTH];
593 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
594 std::string hexdigest = print_sha1(digest);
595 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
596 }
597}
598
599// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
600// in hex for each block.
601static void PrintHashForCorruptedStashedBlocks(const std::string& id,
602 const std::vector<uint8_t>& buffer,
603 const RangeSet& src) {
604 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700605 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000606
Tao Baobf5b77d2017-03-30 16:57:29 -0700607 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700608 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000609
610 uint8_t digest[SHA_DIGEST_LENGTH];
611 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
612 std::string hexdigest = print_sha1(digest);
613 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
614 }
615}
616
617// If the stash file doesn't exist, read the source blocks this stash contains and print the
618// SHA-1 for these blocks.
619static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
620 if (stash_map.find(id) == stash_map.end()) {
621 LOG(ERROR) << "No stash saved for id: " << id;
622 return;
623 }
624
625 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
626 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700627 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tao Baode3bbb82018-05-30 16:14:14 -0700628 if (ReadBlocks(src, &buffer, fd) == -1) {
629 LOG(ERROR) << "failed to read source blocks for stash: " << id;
630 return;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000631 }
632 PrintHashForCorruptedStashedBlocks(id, buffer, src);
633}
634
Tao Bao612336d2015-08-27 16:41:21 -0700635static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Baode3bbb82018-05-30 16:14:14 -0700636 const size_t blocks, bool printerror) {
637 uint8_t digest[SHA_DIGEST_LENGTH];
638 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000639
Tao Baode3bbb82018-05-30 16:14:14 -0700640 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000641
Tao Baode3bbb82018-05-30 16:14:14 -0700642 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000643
Tao Baode3bbb82018-05-30 16:14:14 -0700644 if (hexdigest != expected) {
645 if (printerror) {
646 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read " << hexdigest
647 << ")";
Sami Tolvanen90221202014-12-09 16:39:47 +0000648 }
Tao Baode3bbb82018-05-30 16:14:14 -0700649 return -1;
650 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000651
Tao Baode3bbb82018-05-30 16:14:14 -0700652 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000653}
654
Tao Bao0940fe12015-08-27 16:41:21 -0700655static std::string GetStashFileName(const std::string& base, const std::string& id,
Tao Bao641fa972018-04-25 18:59:40 -0700656 const std::string& postfix) {
657 if (base.empty()) {
658 return "";
659 }
Tao Bao864c6682018-05-07 11:38:25 -0700660 std::string filename = Paths::Get().stash_directory_base() + "/" + base;
661 if (id.empty() && postfix.empty()) {
662 return filename;
663 }
664 return filename + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000665}
666
Tao Baoec8272f2017-03-15 17:39:01 -0700667// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
668// directory and continues despite of errors. Calls the 'callback' function for each file.
669static void EnumerateStash(const std::string& dirname,
670 const std::function<void(const std::string&)>& callback) {
671 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000672
Tao Baoec8272f2017-03-15 17:39:01 -0700673 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000674
Tao Baoec8272f2017-03-15 17:39:01 -0700675 if (directory == nullptr) {
676 if (errno != ENOENT) {
677 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000678 }
Tao Bao51412212016-12-28 14:44:05 -0800679 return;
680 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700681
Tao Baoec8272f2017-03-15 17:39:01 -0700682 dirent* item;
683 while ((item = readdir(directory.get())) != nullptr) {
684 if (item->d_type != DT_REG) continue;
685 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800686 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000687}
688
689// Deletes the stash directory and all files in it. Assumes that it only
690// contains files. There is nothing we can do about unlikely, but possible
691// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700692static void DeleteFile(const std::string& fn) {
693 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000694
Tao Baoec8272f2017-03-15 17:39:01 -0700695 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000696
Tao Baoec8272f2017-03-15 17:39:01 -0700697 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
698 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
699 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000700}
701
Tao Baoe6aa3322015-08-05 15:20:27 -0700702static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700703 if (base.empty()) return;
704
705 LOG(INFO) << "deleting stash " << base;
706
707 std::string dirname = GetStashFileName(base, "", "");
708 EnumerateStash(dirname, DeleteFile);
709
710 if (rmdir(dirname.c_str()) == -1) {
711 if (errno != ENOENT && errno != ENOTDIR) {
712 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000713 }
Tao Baoec8272f2017-03-15 17:39:01 -0700714 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000715}
716
Tao Baode3bbb82018-05-30 16:14:14 -0700717static int LoadStash(const CommandParameters& params, const std::string& id, bool verify,
718 std::vector<uint8_t>* buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700719 // In verify mode, if source range_set was saved for the given hash, check contents in the source
720 // blocks first. If the check fails, search for the stashed files on /cache as usual.
721 if (!params.canwrite) {
722 if (stash_map.find(id) != stash_map.end()) {
723 const RangeSet& src = stash_map[id];
724 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700725
Tao Baobf5b77d2017-03-30 16:57:29 -0700726 if (ReadBlocks(src, buffer, params.fd) == -1) {
727 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700728 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700729 }
Tao Baode3bbb82018-05-30 16:14:14 -0700730 if (VerifyBlocks(id, *buffer, src.blocks(), true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700731 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu3c5958f2018-03-09 14:10:25 -0800732 if (!is_retry) {
733 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
734 }
Tao Bao0940fe12015-08-27 16:41:21 -0700735 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700736 }
737 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000738 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700739 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000740
Tao Baobf5b77d2017-03-30 16:57:29 -0700741 std::string fn = GetStashFileName(params.stashbase, id, "");
742
743 struct stat sb;
744 if (stat(fn.c_str(), &sb) == -1) {
745 if (errno != ENOENT || printnoent) {
746 PLOG(ERROR) << "stat \"" << fn << "\" failed";
747 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000748 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700749 return -1;
750 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000751
Tao Baobf5b77d2017-03-30 16:57:29 -0700752 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000753
Tao Baobf5b77d2017-03-30 16:57:29 -0700754 if ((sb.st_size % BLOCKSIZE) != 0) {
755 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
756 return -1;
757 }
758
Tianjie Xu22f11202018-08-27 10:50:31 -0700759 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY)));
Tao Baobf5b77d2017-03-30 16:57:29 -0700760 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700761 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Baobf5b77d2017-03-30 16:57:29 -0700762 PLOG(ERROR) << "open \"" << fn << "\" failed";
763 return -1;
764 }
765
766 allocate(sb.st_size, buffer);
767
Tianjie Xu22f11202018-08-27 10:50:31 -0700768 if (!android::base::ReadFully(fd, buffer->data(), sb.st_size)) {
769 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
770 PLOG(ERROR) << "Failed to read " << sb.st_size << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -0700771 return -1;
772 }
773
Tao Bao64957ce2018-05-30 16:21:39 -0700774 size_t blocks = sb.st_size / BLOCKSIZE;
Tao Baode3bbb82018-05-30 16:14:14 -0700775 if (verify && VerifyBlocks(id, *buffer, blocks, true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700776 LOG(ERROR) << "unexpected contents in " << fn;
777 if (stash_map.find(id) == stash_map.end()) {
778 LOG(ERROR) << "failed to find source blocks number for stash " << id
779 << " when executing command: " << params.cmdname;
780 } else {
781 const RangeSet& src = stash_map[id];
Tao Baode3bbb82018-05-30 16:14:14 -0700782 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000783 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700784 DeleteFile(fn);
785 return -1;
786 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000787
Tao Baobf5b77d2017-03-30 16:57:29 -0700788 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000789}
790
Tao Bao612336d2015-08-27 16:41:21 -0700791static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baode3bbb82018-05-30 16:14:14 -0700792 const std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
793 if (base.empty()) {
794 return -1;
795 }
796
Tao Bao5ee25662018-07-11 15:55:32 -0700797 if (checkspace && !CheckAndFreeSpaceOnCache(blocks * BLOCKSIZE)) {
Tao Baode3bbb82018-05-30 16:14:14 -0700798 LOG(ERROR) << "not enough space to write stash";
799 return -1;
800 }
801
802 std::string fn = GetStashFileName(base, id, ".partial");
803 std::string cn = GetStashFileName(base, id, "");
804
805 if (exists) {
806 struct stat sb;
807 int res = stat(cn.c_str(), &sb);
808
809 if (res == 0) {
810 // The file already exists and since the name is the hash of the contents,
811 // it's safe to assume the contents are identical (accidental hash collisions
812 // are unlikely)
813 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
814 *exists = true;
815 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000816 }
817
Tao Baode3bbb82018-05-30 16:14:14 -0700818 *exists = false;
819 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000820
Tao Baode3bbb82018-05-30 16:14:14 -0700821 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000822
Tao Baode3bbb82018-05-30 16:14:14 -0700823 android::base::unique_fd fd(
Tianjie Xu22f11202018-08-27 10:50:31 -0700824 TEMP_FAILURE_RETRY(open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Tao Baode3bbb82018-05-30 16:14:14 -0700825 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700826 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Baode3bbb82018-05-30 16:14:14 -0700827 PLOG(ERROR) << "failed to create \"" << fn << "\"";
828 return -1;
829 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100830
Tao Baode3bbb82018-05-30 16:14:14 -0700831 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
832 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
833 return -1;
834 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100835
Tianjie Xu22f11202018-08-27 10:50:31 -0700836 if (!android::base::WriteFully(fd, buffer.data(), blocks * BLOCKSIZE)) {
837 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
838 PLOG(ERROR) << "Failed to write " << blocks * BLOCKSIZE << " bytes of data";
Tao Baode3bbb82018-05-30 16:14:14 -0700839 return -1;
840 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100841
Tianjie Xu22f11202018-08-27 10:50:31 -0700842 if (fsync(fd) == -1) {
843 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Baode3bbb82018-05-30 16:14:14 -0700844 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
845 return -1;
846 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000847
Tao Baode3bbb82018-05-30 16:14:14 -0700848 if (rename(fn.c_str(), cn.c_str()) == -1) {
849 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
850 return -1;
851 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000852
Tao Baode3bbb82018-05-30 16:14:14 -0700853 std::string dname = GetStashFileName(base, "", "");
854 if (!FsyncDir(dname)) {
Tao Baode3bbb82018-05-30 16:14:14 -0700855 return -1;
856 }
Tianjie Xua946b9e2017-03-21 16:24:57 -0700857
Tao Baode3bbb82018-05-30 16:14:14 -0700858 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000859}
860
861// Creates a directory for storing stash files and checks if the /cache partition
862// hash enough space for the expected amount of blocks we need to store. Returns
863// >0 if we created the directory, zero if it existed already, and <0 of failure.
Tao Bao864c6682018-05-07 11:38:25 -0700864static int CreateStash(State* state, size_t maxblocks, const std::string& base) {
Tao Bao51412212016-12-28 14:44:05 -0800865 std::string dirname = GetStashFileName(base, "", "");
866 struct stat sb;
867 int res = stat(dirname.c_str(), &sb);
Tao Bao51412212016-12-28 14:44:05 -0800868 if (res == -1 && errno != ENOENT) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800869 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800870 strerror(errno));
871 return -1;
Tao Bao864c6682018-05-07 11:38:25 -0700872 }
873
874 size_t max_stash_size = maxblocks * BLOCKSIZE;
875 if (res == -1) {
Tao Bao51412212016-12-28 14:44:05 -0800876 LOG(INFO) << "creating stash " << dirname;
877 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
878
879 if (res != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800880 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800881 strerror(errno));
882 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000883 }
884
Tianjie Xua946b9e2017-03-21 16:24:57 -0700885 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
Tianjie Xu5ad80282018-01-28 15:37:48 -0800886 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s", dirname.c_str(),
Tianjie Xua946b9e2017-03-21 16:24:57 -0700887 strerror(errno));
888 return -1;
889 }
890
Tao Bao5ee25662018-07-11 15:55:32 -0700891 if (!CheckAndFreeSpaceOnCache(max_stash_size)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800892 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)",
Tao Bao51412212016-12-28 14:44:05 -0800893 max_stash_size);
894 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000895 }
896
Tao Bao51412212016-12-28 14:44:05 -0800897 return 1; // Created directory
898 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000899
Tao Bao51412212016-12-28 14:44:05 -0800900 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000901
Tao Baoec8272f2017-03-15 17:39:01 -0700902 // If the directory already exists, calculate the space already allocated to stash files and check
903 // if there's enough for all required blocks. Delete any partially completed stash files first.
904 EnumerateStash(dirname, [](const std::string& fn) {
905 if (android::base::EndsWith(fn, ".partial")) {
906 DeleteFile(fn);
907 }
908 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000909
Tao Bao51412212016-12-28 14:44:05 -0800910 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700911 EnumerateStash(dirname, [&existing](const std::string& fn) {
912 if (fn.empty()) return;
913 struct stat sb;
914 if (stat(fn.c_str(), &sb) == -1) {
915 PLOG(ERROR) << "stat \"" << fn << "\" failed";
916 return;
917 }
918 existing += static_cast<size_t>(sb.st_size);
919 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000920
Tao Bao51412212016-12-28 14:44:05 -0800921 if (max_stash_size > existing) {
922 size_t needed = max_stash_size - existing;
Tao Bao5ee25662018-07-11 15:55:32 -0700923 if (!CheckAndFreeSpaceOnCache(needed)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800924 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)",
Tao Bao51412212016-12-28 14:44:05 -0800925 needed);
926 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000927 }
Tao Bao51412212016-12-28 14:44:05 -0800928 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000929
Tao Bao51412212016-12-28 14:44:05 -0800930 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000931}
932
Tao Baobaad2d42015-12-06 16:56:27 -0800933static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700934 if (base.empty() || id.empty()) {
935 return -1;
936 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000937
Tao Baoec8272f2017-03-15 17:39:01 -0700938 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000939
Tao Baoec8272f2017-03-15 17:39:01 -0700940 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700941}
942
Tao Baobf5b77d2017-03-30 16:57:29 -0700943// Source contains packed data, which we want to move to the locations given in locs in the dest
944// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700945static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700946 const std::vector<uint8_t>& source) {
947 const uint8_t* from = source.data();
948 uint8_t* to = dest.data();
949 size_t start = locs.blocks();
950 // Must do the movement backward.
951 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
952 size_t blocks = it->second - it->first;
953 start -= blocks;
954 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
955 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700956}
957
Tao Baod2aecd42017-03-23 14:43:44 -0700958/**
959 * We expect to parse the remainder of the parameter tokens as one of:
960 *
961 * <src_block_count> <src_range>
962 * (loads data from source image only)
963 *
964 * <src_block_count> - <[stash_id:stash_range] ...>
965 * (loads data from stashes only)
966 *
967 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
968 * (loads data from both source image and stashes)
969 *
970 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
971 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
972 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
973 * LoadStash.
974 */
975static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
976 bool* overlap) {
977 CHECK(src_blocks != nullptr);
978 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700979
Tao Baod2aecd42017-03-23 14:43:44 -0700980 // <src_block_count>
981 const std::string& token = params.tokens[params.cpos++];
982 if (!android::base::ParseUint(token, src_blocks)) {
983 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
984 return -1;
985 }
Tao Baobaad2d42015-12-06 16:56:27 -0800986
Tao Baode3bbb82018-05-30 16:14:14 -0700987 allocate(*src_blocks * BLOCKSIZE, &params.buffer);
Tao Baod2aecd42017-03-23 14:43:44 -0700988
989 // "-" or <src_range> [<src_loc>]
990 if (params.tokens[params.cpos] == "-") {
991 // no source ranges, only stashes
992 params.cpos++;
993 } else {
Tao Bao8f237572017-03-26 13:36:49 -0700994 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -0700995 CHECK(static_cast<bool>(src));
Tao Bao8f237572017-03-26 13:36:49 -0700996 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -0700997
Tao Baode3bbb82018-05-30 16:14:14 -0700998 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -0700999 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -08001000 }
1001
Tao Baod2aecd42017-03-23 14:43:44 -07001002 if (params.cpos >= params.tokens.size()) {
1003 // no stashes, only source range
1004 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -08001005 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001006
Tao Bao8f237572017-03-26 13:36:49 -07001007 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001008 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001009 MoveRange(params.buffer, locs, params.buffer);
1010 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001011
Tao Baod2aecd42017-03-23 14:43:44 -07001012 // <[stash_id:stash_range]>
1013 while (params.cpos < params.tokens.size()) {
1014 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
1015 // in the source block that stashed data should go.
1016 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1017 if (tokens.size() != 2) {
1018 LOG(ERROR) << "invalid parameter";
1019 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001020 }
1021
Tao Baod2aecd42017-03-23 14:43:44 -07001022 std::vector<uint8_t> stash;
Tao Baode3bbb82018-05-30 16:14:14 -07001023 if (LoadStash(params, tokens[0], false, &stash, true) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001024 // These source blocks will fail verification if used later, but we
1025 // will let the caller decide if this is a fatal failure
1026 LOG(ERROR) << "failed to load stash " << tokens[0];
1027 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +00001028 }
1029
Tao Bao8f237572017-03-26 13:36:49 -07001030 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Bao67983152017-11-04 00:08:08 -07001031 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001032 MoveRange(params.buffer, locs, stash);
1033 }
1034
1035 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001036}
1037
Tao Bao33567772017-03-13 14:57:34 -07001038/**
1039 * Do a source/target load for move/bsdiff/imgdiff in version 3.
1040 *
1041 * We expect to parse the remainder of the parameter tokens as one of:
1042 *
1043 * <tgt_range> <src_block_count> <src_range>
1044 * (loads data from source image only)
1045 *
1046 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
1047 * (loads data from stashes only)
1048 *
1049 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1050 * (loads data from both source image and stashes)
1051 *
Tao Baod2aecd42017-03-23 14:43:44 -07001052 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
1053 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -07001054 * verification fails in a way that the update cannot be resumed anymore.
1055 *
1056 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
1057 * the return value is -1 and the command should be aborted.
1058 *
1059 * If the return value is 1, the command has already been completed according to the contents of the
1060 * target blocks, and should not be performed again.
1061 *
1062 * If the return value is 0, source blocks have expected content and the command can be performed.
1063 */
Tao Baode3bbb82018-05-30 16:14:14 -07001064static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet* tgt, size_t* src_blocks,
Tao Bao4a135082018-06-07 22:27:44 -07001065 bool onehash) {
Tao Baod2aecd42017-03-23 14:43:44 -07001066 CHECK(src_blocks != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001067
Tao Baod2aecd42017-03-23 14:43:44 -07001068 if (params.cpos >= params.tokens.size()) {
1069 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001070 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001071 }
1072
1073 std::string srchash = params.tokens[params.cpos++];
1074 std::string tgthash;
1075
1076 if (onehash) {
1077 tgthash = srchash;
1078 } else {
1079 if (params.cpos >= params.tokens.size()) {
1080 LOG(ERROR) << "missing target hash";
1081 return -1;
1082 }
1083 tgthash = params.tokens[params.cpos++];
1084 }
1085
1086 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1087 // "-"/<src_range>.
1088 if (params.cpos + 2 >= params.tokens.size()) {
1089 LOG(ERROR) << "invalid parameters";
1090 return -1;
1091 }
1092
1093 // <tgt_range>
Tao Baode3bbb82018-05-30 16:14:14 -07001094 *tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1095 CHECK(static_cast<bool>(*tgt));
Tao Baod2aecd42017-03-23 14:43:44 -07001096
Tao Baode3bbb82018-05-30 16:14:14 -07001097 std::vector<uint8_t> tgtbuffer(tgt->blocks() * BLOCKSIZE);
1098 if (ReadBlocks(*tgt, &tgtbuffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001099 return -1;
1100 }
1101
1102 // Return now if target blocks already have expected content.
Tao Baode3bbb82018-05-30 16:14:14 -07001103 if (VerifyBlocks(tgthash, tgtbuffer, tgt->blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001104 return 1;
1105 }
1106
1107 // Load source blocks.
Tao Bao4a135082018-06-07 22:27:44 -07001108 bool overlap = false;
1109 if (LoadSourceBlocks(params, *tgt, src_blocks, &overlap) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001110 return -1;
1111 }
1112
1113 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
Tao Bao4a135082018-06-07 22:27:44 -07001114 // If source and target blocks overlap, stash the source blocks so we can resume from possible
1115 // write errors. In verify mode, we can skip stashing because the source blocks won't be
1116 // overwritten.
1117 if (overlap && params.canwrite) {
Tao Baod2aecd42017-03-23 14:43:44 -07001118 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1119
1120 bool stash_exists = false;
1121 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1122 &stash_exists) != 0) {
1123 LOG(ERROR) << "failed to stash overlapping source blocks";
1124 return -1;
1125 }
1126
1127 params.stashed += *src_blocks;
1128 // Can be deleted when the write has completed.
1129 if (!stash_exists) {
1130 params.freestash = srchash;
1131 }
1132 }
1133
1134 // Source blocks have expected content, command can proceed.
1135 return 0;
1136 }
1137
Tao Bao4a135082018-06-07 22:27:44 -07001138 if (overlap && LoadStash(params, srchash, true, &params.buffer, true) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001139 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1140 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1141 // command.
1142 return 0;
1143 }
1144
1145 // Valid source data not available, update cannot be resumed.
1146 LOG(ERROR) << "partition has unexpected contents";
1147 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1148
1149 params.isunresumable = true;
1150
1151 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001152}
1153
Tao Bao0940fe12015-08-27 16:41:21 -07001154static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001155 size_t blocks = 0;
Tao Bao33567772017-03-13 14:57:34 -07001156 RangeSet tgt;
Tao Bao4a135082018-06-07 22:27:44 -07001157 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001158
Tao Bao33567772017-03-13 14:57:34 -07001159 if (status == -1) {
1160 LOG(ERROR) << "failed to read blocks for move";
1161 return -1;
1162 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001163
Tao Bao33567772017-03-13 14:57:34 -07001164 if (status == 0) {
1165 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001166 } else {
1167 params.target_verified = true;
1168 if (params.foundwrites) {
1169 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1170 }
Tao Bao33567772017-03-13 14:57:34 -07001171 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001172
Tao Bao33567772017-03-13 14:57:34 -07001173 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001174 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001175 LOG(INFO) << " moving " << blocks << " blocks";
1176
1177 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1178 return -1;
1179 }
1180 } else {
1181 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001182 }
Tao Bao33567772017-03-13 14:57:34 -07001183 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001184
Tao Bao33567772017-03-13 14:57:34 -07001185 if (!params.freestash.empty()) {
1186 FreeStash(params.stashbase, params.freestash);
1187 params.freestash.clear();
1188 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001189
Tao Baobf5b77d2017-03-30 16:57:29 -07001190 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001191
Tao Bao33567772017-03-13 14:57:34 -07001192 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001193}
1194
Tao Bao0940fe12015-08-27 16:41:21 -07001195static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001196 // <stash_id> <src_range>
1197 if (params.cpos + 1 >= params.tokens.size()) {
1198 LOG(ERROR) << "missing id and/or src range fields in stash command";
1199 return -1;
1200 }
1201
1202 const std::string& id = params.tokens[params.cpos++];
Tao Baode3bbb82018-05-30 16:14:14 -07001203 if (LoadStash(params, id, true, &params.buffer, false) == 0) {
Tao Baobcf46492017-03-23 15:28:20 -07001204 // Stash file already exists and has expected contents. Do not read from source again, as the
1205 // source may have been already overwritten during a previous attempt.
1206 return 0;
1207 }
1208
Tao Bao8f237572017-03-26 13:36:49 -07001209 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001210 CHECK(static_cast<bool>(src));
Tao Baobcf46492017-03-23 15:28:20 -07001211
Tao Bao64957ce2018-05-30 16:21:39 -07001212 size_t blocks = src.blocks();
Tao Baode3bbb82018-05-30 16:14:14 -07001213 allocate(blocks * BLOCKSIZE, &params.buffer);
1214 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baobcf46492017-03-23 15:28:20 -07001215 return -1;
1216 }
Tao Baobcf46492017-03-23 15:28:20 -07001217 stash_map[id] = src;
1218
1219 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1220 // Source blocks have unexpected contents. If we actually need this data later, this is an
1221 // unrecoverable error. However, the command that uses the data may have already completed
1222 // previously, so the possible failure will occur during source block verification.
1223 LOG(ERROR) << "failed to load source blocks for stash " << id;
1224 return 0;
1225 }
1226
1227 // In verify mode, we don't need to stash any blocks.
1228 if (!params.canwrite) {
1229 return 0;
1230 }
1231
1232 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xu284752e2017-12-05 11:04:17 -08001233 int result = WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
1234 if (result == 0) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001235 params.stashed += blocks;
1236 }
1237 return result;
Sami Tolvanen90221202014-12-09 16:39:47 +00001238}
1239
Tao Bao0940fe12015-08-27 16:41:21 -07001240static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001241 // <stash_id>
1242 if (params.cpos >= params.tokens.size()) {
1243 LOG(ERROR) << "missing stash id in free command";
1244 return -1;
1245 }
Tao Baobaad2d42015-12-06 16:56:27 -08001246
Tao Baobcf46492017-03-23 15:28:20 -07001247 const std::string& id = params.tokens[params.cpos++];
1248 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001249
Tao Baobcf46492017-03-23 15:28:20 -07001250 if (params.createdstash || params.canwrite) {
1251 return FreeStash(params.stashbase, id);
1252 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001253
Tao Baobcf46492017-03-23 15:28:20 -07001254 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001255}
1256
Tao Bao0940fe12015-08-27 16:41:21 -07001257static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001258 if (params.cpos >= params.tokens.size()) {
1259 LOG(ERROR) << "missing target blocks for zero";
1260 return -1;
1261 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001262
Tao Baobf5b77d2017-03-30 16:57:29 -07001263 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001264 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001265
1266 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1267
Tao Baode3bbb82018-05-30 16:14:14 -07001268 allocate(BLOCKSIZE, &params.buffer);
Tao Baobf5b77d2017-03-30 16:57:29 -07001269 memset(params.buffer.data(), 0, BLOCKSIZE);
1270
1271 if (params.canwrite) {
Tao Bao43bfa6e2018-08-28 10:09:13 -07001272 for (const auto& [begin, end] : tgt) {
1273 off64_t offset = static_cast<off64_t>(begin) * BLOCKSIZE;
1274 size_t size = (end - begin) * BLOCKSIZE;
Tao Baobf5b77d2017-03-30 16:57:29 -07001275 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001276 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001277 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001278
Tao Baobf5b77d2017-03-30 16:57:29 -07001279 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1280 return -1;
1281 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001282
Tao Bao43bfa6e2018-08-28 10:09:13 -07001283 for (size_t j = begin; j < end; ++j) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001284 if (!android::base::WriteFully(params.fd, params.buffer.data(), BLOCKSIZE)) {
1285 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
1286 PLOG(ERROR) << "Failed to write " << BLOCKSIZE << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -07001287 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001288 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001289 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001290 }
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 (params.cmdname[0] == 'z') {
1294 // Update only for the zero command, as the erase command will call
1295 // this if DEBUG_ERASE is defined.
1296 params.written += tgt.blocks();
1297 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001298
Tao Baobf5b77d2017-03-30 16:57:29 -07001299 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001300}
1301
Tao Bao0940fe12015-08-27 16:41:21 -07001302static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001303 if (params.cpos >= params.tokens.size()) {
1304 LOG(ERROR) << "missing target blocks for new";
1305 return -1;
1306 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001307
Tao Bao8f237572017-03-26 13:36:49 -07001308 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001309 CHECK(static_cast<bool>(tgt));
Tao Bao60a70af2017-03-26 14:03:52 -07001310
1311 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001312 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001313
Tao Bao60a70af2017-03-26 14:03:52 -07001314 pthread_mutex_lock(&params.nti.mu);
Tianjie Xu6ed175d2017-07-18 11:29:40 -07001315 params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
Tao Bao60a70af2017-03-26 14:03:52 -07001316 pthread_cond_broadcast(&params.nti.cv);
1317
1318 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001319 if (!params.nti.receiver_available) {
1320 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1321 << " bytes of new data";
1322 pthread_mutex_unlock(&params.nti.mu);
1323 return -1;
1324 }
Tao Bao60a70af2017-03-26 14:03:52 -07001325 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001326 }
1327
Tao Bao60a70af2017-03-26 14:03:52 -07001328 pthread_mutex_unlock(&params.nti.mu);
1329 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001330
Tao Baobf5b77d2017-03-30 16:57:29 -07001331 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001332
Tao Bao60a70af2017-03-26 14:03:52 -07001333 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001334}
1335
Tao Bao0940fe12015-08-27 16:41:21 -07001336static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001337 // <offset> <length>
1338 if (params.cpos + 1 >= params.tokens.size()) {
1339 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1340 return -1;
1341 }
Tao Bao0940fe12015-08-27 16:41:21 -07001342
Tao Baoc0e1c462017-02-01 10:20:10 -08001343 size_t offset;
1344 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1345 LOG(ERROR) << "invalid patch offset";
1346 return -1;
1347 }
Tao Bao0940fe12015-08-27 16:41:21 -07001348
Tao Baoc0e1c462017-02-01 10:20:10 -08001349 size_t len;
1350 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1351 LOG(ERROR) << "invalid patch len";
1352 return -1;
1353 }
Tao Bao0940fe12015-08-27 16:41:21 -07001354
Tao Baoc0e1c462017-02-01 10:20:10 -08001355 RangeSet tgt;
1356 size_t blocks = 0;
Tao Bao4a135082018-06-07 22:27:44 -07001357 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, false);
Tao Bao0940fe12015-08-27 16:41:21 -07001358
Tao Baoc0e1c462017-02-01 10:20:10 -08001359 if (status == -1) {
1360 LOG(ERROR) << "failed to read blocks for diff";
1361 return -1;
1362 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001363
Tao Baoc0e1c462017-02-01 10:20:10 -08001364 if (status == 0) {
1365 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001366 } else {
1367 params.target_verified = true;
1368 if (params.foundwrites) {
1369 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1370 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001371 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001372
Tao Baoc0e1c462017-02-01 10:20:10 -08001373 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001374 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001375 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001376 Value patch_value(
Tao Bao511d7592018-06-19 15:56:49 -07001377 Value::Type::BLOB,
1378 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001379
Tao Bao60a70af2017-03-26 14:03:52 -07001380 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001381 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao1e0941f2017-11-10 11:49:53 -08001382 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value,
Tao Bao60a70af2017-03-26 14:03:52 -07001383 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1384 std::placeholders::_2),
Tao Bao8b0b0f12018-04-19 21:02:13 -07001385 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001386 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001387 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001388 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001389 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001390 } else {
Tao Bao1e0941f2017-11-10 11:49:53 -08001391 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value, 0,
Tao Bao60a70af2017-03-26 14:03:52 -07001392 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
Tao Bao8b0b0f12018-04-19 21:02:13 -07001393 std::placeholders::_2)) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001394 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001395 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001396 return -1;
1397 }
1398 }
1399
1400 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001401 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001402 LOG(ERROR) << "range sink underrun?";
1403 }
1404 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001405 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001406 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001407 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001408 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001409
Tao Baoc0e1c462017-02-01 10:20:10 -08001410 if (!params.freestash.empty()) {
1411 FreeStash(params.stashbase, params.freestash);
1412 params.freestash.clear();
1413 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001414
Tao Baobf5b77d2017-03-30 16:57:29 -07001415 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001416
Tao Baoc0e1c462017-02-01 10:20:10 -08001417 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001418}
1419
Tao Bao0940fe12015-08-27 16:41:21 -07001420static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001421 if (DEBUG_ERASE) {
1422 return PerformCommandZero(params);
1423 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001424
Tao Baobf5b77d2017-03-30 16:57:29 -07001425 struct stat sb;
1426 if (fstat(params.fd, &sb) == -1) {
1427 PLOG(ERROR) << "failed to fstat device to erase";
1428 return -1;
1429 }
1430
1431 if (!S_ISBLK(sb.st_mode)) {
1432 LOG(ERROR) << "not a block device; skipping erase";
1433 return -1;
1434 }
1435
1436 if (params.cpos >= params.tokens.size()) {
1437 LOG(ERROR) << "missing target blocks for erase";
1438 return -1;
1439 }
1440
1441 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001442 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001443
1444 if (params.canwrite) {
1445 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1446
Tao Bao43bfa6e2018-08-28 10:09:13 -07001447 for (const auto& [begin, end] : tgt) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001448 uint64_t blocks[2];
1449 // offset in bytes
Tao Bao43bfa6e2018-08-28 10:09:13 -07001450 blocks[0] = begin * static_cast<uint64_t>(BLOCKSIZE);
Tao Baobf5b77d2017-03-30 16:57:29 -07001451 // length in bytes
Tao Bao43bfa6e2018-08-28 10:09:13 -07001452 blocks[1] = (end - begin) * static_cast<uint64_t>(BLOCKSIZE);
Tao Baobf5b77d2017-03-30 16:57:29 -07001453
1454 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
1455 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001456 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001457 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001458 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001459 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001460
Tao Baobf5b77d2017-03-30 16:57:29 -07001461 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001462}
1463
Tao Bao91a649a2018-05-21 16:05:56 -07001464static int PerformCommandAbort(CommandParameters&) {
1465 LOG(INFO) << "Aborting as instructed";
1466 return -1;
1467}
1468
Tianjie Xu69ffa152018-08-01 16:40:00 -07001469// Computes the hash_tree bytes based on the parameters, checks if the root hash of the tree
1470// matches the expected hash and writes the result to the specified range on the block_device.
1471// Hash_tree computation arguments:
1472// hash_tree_ranges
1473// source_ranges
1474// hash_algorithm
1475// salt_hex
1476// root_hash
1477static int PerformCommandComputeHashTree(CommandParameters& params) {
1478 if (params.cpos + 5 != params.tokens.size()) {
1479 LOG(ERROR) << "Invaild arguments count in hash computation " << params.cmdline;
1480 return -1;
1481 }
1482
1483 // Expects the hash_tree data to be contiguous.
1484 RangeSet hash_tree_ranges = RangeSet::Parse(params.tokens[params.cpos++]);
1485 if (!hash_tree_ranges || hash_tree_ranges.size() != 1) {
1486 LOG(ERROR) << "Invalid hash tree ranges in " << params.cmdline;
1487 return -1;
1488 }
1489
1490 RangeSet source_ranges = RangeSet::Parse(params.tokens[params.cpos++]);
1491 if (!source_ranges) {
1492 LOG(ERROR) << "Invalid source ranges in " << params.cmdline;
1493 return -1;
1494 }
1495
1496 auto hash_function = HashTreeBuilder::HashFunction(params.tokens[params.cpos++]);
1497 if (hash_function == nullptr) {
1498 LOG(ERROR) << "Invalid hash algorithm in " << params.cmdline;
1499 return -1;
1500 }
1501
1502 std::vector<unsigned char> salt;
1503 std::string salt_hex = params.tokens[params.cpos++];
1504 if (salt_hex.empty() || !HashTreeBuilder::ParseBytesArrayFromString(salt_hex, &salt)) {
1505 LOG(ERROR) << "Failed to parse salt in " << params.cmdline;
1506 return -1;
1507 }
1508
1509 std::string expected_root_hash = params.tokens[params.cpos++];
1510 if (expected_root_hash.empty()) {
1511 LOG(ERROR) << "Invalid root hash in " << params.cmdline;
1512 return -1;
1513 }
1514
1515 // Starts the hash_tree computation.
1516 HashTreeBuilder builder(BLOCKSIZE, hash_function);
1517 if (!builder.Initialize(source_ranges.blocks() * BLOCKSIZE, salt)) {
1518 LOG(ERROR) << "Failed to initialize hash tree computation, source " << source_ranges.ToString()
1519 << ", salt " << salt_hex;
1520 return -1;
1521 }
1522
1523 // Iterates through every block in the source_ranges and updates the hash tree structure
1524 // accordingly.
Tao Bao43bfa6e2018-08-28 10:09:13 -07001525 for (const auto& [begin, end] : source_ranges) {
Tianjie Xu69ffa152018-08-01 16:40:00 -07001526 uint8_t buffer[BLOCKSIZE];
Tao Bao43bfa6e2018-08-28 10:09:13 -07001527 if (!check_lseek(params.fd, static_cast<off64_t>(begin) * BLOCKSIZE, SEEK_SET)) {
1528 PLOG(ERROR) << "Failed to seek to block: " << begin;
Tianjie Xu69ffa152018-08-01 16:40:00 -07001529 return -1;
1530 }
1531
Tao Bao43bfa6e2018-08-28 10:09:13 -07001532 for (size_t i = begin; i < end; i++) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001533 if (!android::base::ReadFully(params.fd, buffer, BLOCKSIZE)) {
1534 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
Tao Bao43bfa6e2018-08-28 10:09:13 -07001535 LOG(ERROR) << "Failed to read data in " << begin << ":" << end;
Tianjie Xu69ffa152018-08-01 16:40:00 -07001536 return -1;
1537 }
1538
1539 if (!builder.Update(reinterpret_cast<unsigned char*>(buffer), BLOCKSIZE)) {
1540 LOG(ERROR) << "Failed to update hash tree builder";
1541 return -1;
1542 }
1543 }
1544 }
1545
1546 if (!builder.BuildHashTree()) {
1547 LOG(ERROR) << "Failed to build hash tree";
1548 return -1;
1549 }
1550
1551 std::string root_hash_hex = HashTreeBuilder::BytesArrayToString(builder.root_hash());
1552 if (root_hash_hex != expected_root_hash) {
1553 LOG(ERROR) << "Root hash of the verity hash tree doesn't match the expected value. Expected: "
1554 << expected_root_hash << ", actual: " << root_hash_hex;
1555 return -1;
1556 }
1557
1558 uint64_t write_offset = static_cast<uint64_t>(hash_tree_ranges.GetBlockNumber(0)) * BLOCKSIZE;
1559 if (params.canwrite && !builder.WriteHashTreeToFd(params.fd, write_offset)) {
1560 LOG(ERROR) << "Failed to write hash tree to output";
1561 return -1;
1562 }
1563
1564 // TODO(xunchang) validates the written bytes
1565
1566 return 0;
1567}
1568
Tao Baoc3901232018-05-21 16:05:56 -07001569using CommandFunction = std::function<int(CommandParameters&)>;
Sami Tolvanen90221202014-12-09 16:39:47 +00001570
Tao Baoc3901232018-05-21 16:05:56 -07001571using CommandMap = std::unordered_map<Command::Type, CommandFunction>;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001572
Tianjie Xuc4447322017-03-06 14:44:59 -08001573static Value* PerformBlockImageUpdate(const char* name, State* state,
1574 const std::vector<std::unique_ptr<Expr>>& argv,
Tao Baoc3901232018-05-21 16:05:56 -07001575 const CommandMap& command_map, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001576 CommandParameters params = {};
Tao Baoc0299ed2018-05-24 00:16:35 -07001577 stash_map.clear();
Tao Bao33567772017-03-13 14:57:34 -07001578 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001579
Tao Bao33567772017-03-13 14:57:34 -07001580 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1581 if (state->is_retry) {
1582 is_retry = true;
1583 LOG(INFO) << "This update is a retry.";
1584 }
1585 if (argv.size() != 4) {
1586 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1587 argv.size());
1588 return StringValue("");
1589 }
1590
1591 std::vector<std::unique_ptr<Value>> args;
1592 if (!ReadValueArgs(state, argv, &args)) {
1593 return nullptr;
1594 }
1595
Tao Baoc3901232018-05-21 16:05:56 -07001596 // args:
1597 // - block device (or file) to modify in-place
1598 // - transfer list (blob)
1599 // - new data stream (filename within package.zip)
1600 // - patch stream (filename within package.zip, must be uncompressed)
Tao Baoc97edcb2017-03-31 01:18:13 -07001601 const std::unique_ptr<Value>& blockdev_filename = args[0];
1602 const std::unique_ptr<Value>& transfer_list_value = args[1];
1603 const std::unique_ptr<Value>& new_data_fn = args[2];
1604 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001605
Tao Bao511d7592018-06-19 15:56:49 -07001606 if (blockdev_filename->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001607 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1608 return StringValue("");
1609 }
Tao Bao511d7592018-06-19 15:56:49 -07001610 if (transfer_list_value->type != Value::Type::BLOB) {
Tao Bao33567772017-03-13 14:57:34 -07001611 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1612 return StringValue("");
1613 }
Tao Bao511d7592018-06-19 15:56:49 -07001614 if (new_data_fn->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001615 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1616 return StringValue("");
1617 }
Tao Bao511d7592018-06-19 15:56:49 -07001618 if (patch_data_fn->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001619 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1620 return StringValue("");
1621 }
1622
1623 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1624 if (ui == nullptr) {
1625 return StringValue("");
1626 }
1627
1628 FILE* cmd_pipe = ui->cmd_pipe;
1629 ZipArchiveHandle za = ui->package_zip;
1630
1631 if (cmd_pipe == nullptr || za == nullptr) {
1632 return StringValue("");
1633 }
1634
1635 ZipString path_data(patch_data_fn->data.c_str());
1636 ZipEntry patch_entry;
1637 if (FindEntry(za, path_data, &patch_entry) != 0) {
1638 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1639 return StringValue("");
1640 }
1641
1642 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1643 ZipString new_data(new_data_fn->data.c_str());
1644 ZipEntry new_entry;
1645 if (FindEntry(za, new_data, &new_entry) != 0) {
1646 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1647 return StringValue("");
1648 }
1649
Tianjie Xu22f11202018-08-27 10:50:31 -07001650 params.fd.reset(TEMP_FAILURE_RETRY(open(blockdev_filename->data.c_str(), O_RDWR)));
Tao Bao33567772017-03-13 14:57:34 -07001651 if (params.fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001652 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Bao33567772017-03-13 14:57:34 -07001653 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1654 return StringValue("");
1655 }
1656
Tao Bao864c6682018-05-07 11:38:25 -07001657 // Stash directory should be different for each partition to avoid conflicts when updating
1658 // multiple partitions at the same time, so we use the hash of the block device name as the base
1659 // directory.
1660 uint8_t digest[SHA_DIGEST_LENGTH];
1661 SHA1(reinterpret_cast<const uint8_t*>(blockdev_filename->data.data()),
1662 blockdev_filename->data.size(), digest);
1663 params.stashbase = print_sha1(digest);
1664
1665 // Possibly do return early on retry, by checking the marker. If the update on this partition has
1666 // been finished (but interrupted at a later point), there could be leftover on /cache that would
1667 // fail the no-op retry.
1668 std::string updated_marker = GetStashFileName(params.stashbase + ".UPDATED", "", "");
1669 if (is_retry) {
1670 struct stat sb;
1671 int result = stat(updated_marker.c_str(), &sb);
1672 if (result == 0) {
1673 LOG(INFO) << "Skipping already updated partition " << blockdev_filename->data
1674 << " based on marker";
1675 return StringValue("t");
1676 }
1677 } else {
1678 // Delete the obsolete marker if any.
1679 std::string err;
1680 if (!android::base::RemoveFileIfExists(updated_marker, &err)) {
1681 LOG(ERROR) << "Failed to remove partition updated marker " << updated_marker << ": " << err;
1682 return StringValue("");
1683 }
1684 }
1685
Tao Baoffede3e2018-06-07 09:56:19 -07001686 static constexpr size_t kTransferListHeaderLines = 4;
Tao Bao33567772017-03-13 14:57:34 -07001687 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baoffede3e2018-06-07 09:56:19 -07001688 if (lines.size() < kTransferListHeaderLines) {
1689 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]",
Tao Bao33567772017-03-13 14:57:34 -07001690 lines.size());
1691 return StringValue("");
1692 }
1693
1694 // First line in transfer list is the version number.
1695 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1696 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1697 return StringValue("");
1698 }
1699
1700 LOG(INFO) << "blockimg version is " << params.version;
1701
1702 // Second line in transfer list is the total number of blocks we expect to write.
1703 size_t total_blocks;
1704 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001705 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]", lines[1].c_str());
Tao Bao33567772017-03-13 14:57:34 -07001706 return StringValue("");
1707 }
1708
1709 if (total_blocks == 0) {
1710 return StringValue("t");
1711 }
1712
Tao Bao33567772017-03-13 14:57:34 -07001713 // Third line is how many stash entries are needed simultaneously.
1714 LOG(INFO) << "maximum stash entries " << lines[2];
1715
1716 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1717 size_t stash_max_blocks;
1718 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001719 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]",
Tao Bao33567772017-03-13 14:57:34 -07001720 lines[3].c_str());
1721 return StringValue("");
1722 }
1723
Tao Bao864c6682018-05-07 11:38:25 -07001724 int res = CreateStash(state, stash_max_blocks, params.stashbase);
Tao Bao33567772017-03-13 14:57:34 -07001725 if (res == -1) {
1726 return StringValue("");
1727 }
Tao Bao33567772017-03-13 14:57:34 -07001728 params.createdstash = res;
1729
Tao Bao0a883c12018-06-18 12:49:06 -07001730 // Set up the new data writer.
1731 if (params.canwrite) {
1732 params.nti.za = za;
1733 params.nti.entry = new_entry;
1734 params.nti.brotli_compressed = android::base::EndsWith(new_data_fn->data, ".br");
1735 if (params.nti.brotli_compressed) {
1736 // Initialize brotli decoder state.
1737 params.nti.brotli_decoder_state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
1738 }
1739 params.nti.receiver_available = true;
1740
1741 pthread_mutex_init(&params.nti.mu, nullptr);
1742 pthread_cond_init(&params.nti.cv, nullptr);
1743 pthread_attr_t attr;
1744 pthread_attr_init(&attr);
1745 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1746
1747 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1748 if (error != 0) {
1749 LOG(ERROR) << "pthread_create failed: " << strerror(error);
1750 return StringValue("");
1751 }
1752 }
1753
Tao Bao26efb0a2018-05-21 14:59:55 -07001754 // When performing an update, save the index and cmdline of the current command into the
1755 // last_command_file.
Tianjie Xu284752e2017-12-05 11:04:17 -08001756 // Upon resuming an update, read the saved index first; then
1757 // 1. In verification mode, check if the 'move' or 'diff' commands before the saved index has
1758 // the expected target blocks already. If not, these commands cannot be skipped and we need
1759 // to attempt to execute them again. Therefore, we will delete the last_command_file so that
1760 // the update will resume from the start of the transfer list.
1761 // 2. In update mode, skip all commands before the saved index. Therefore, we can avoid deleting
1762 // stashes with duplicate id unintentionally (b/69858743); and also speed up the update.
1763 // If an update succeeds or is unresumable, delete the last_command_file.
Tao Bao26efb0a2018-05-21 14:59:55 -07001764 bool skip_executed_command = true;
1765 size_t saved_last_command_index;
Tianjie Xu284752e2017-12-05 11:04:17 -08001766 if (!ParseLastCommandFile(&saved_last_command_index)) {
1767 DeleteLastCommandFile();
Tao Bao26efb0a2018-05-21 14:59:55 -07001768 // We failed to parse the last command. Disallow skipping executed commands.
1769 skip_executed_command = false;
Tianjie Xu284752e2017-12-05 11:04:17 -08001770 }
1771
Tao Bao33567772017-03-13 14:57:34 -07001772 int rc = -1;
1773
1774 // Subsequent lines are all individual transfer commands
Tao Baoab207062018-05-21 14:48:49 -07001775 for (size_t i = kTransferListHeaderLines; i < lines.size(); i++) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001776 const std::string& line = lines[i];
Tao Bao33567772017-03-13 14:57:34 -07001777 if (line.empty()) continue;
1778
Tao Bao26efb0a2018-05-21 14:59:55 -07001779 size_t cmdindex = i - kTransferListHeaderLines;
Tao Bao33567772017-03-13 14:57:34 -07001780 params.tokens = android::base::Split(line, " ");
1781 params.cpos = 0;
Tao Baoc3901232018-05-21 16:05:56 -07001782 params.cmdname = params.tokens[params.cpos++];
1783 params.cmdline = line;
Tianjie Xu284752e2017-12-05 11:04:17 -08001784 params.target_verified = false;
Tao Bao33567772017-03-13 14:57:34 -07001785
Tao Baoc3901232018-05-21 16:05:56 -07001786 Command::Type cmd_type = Command::ParseType(params.cmdname);
1787 if (cmd_type == Command::Type::LAST) {
Tao Bao33567772017-03-13 14:57:34 -07001788 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1789 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001790 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001791
Tao Baoc3901232018-05-21 16:05:56 -07001792 const CommandFunction& performer = command_map.at(cmd_type);
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001793
Tianjie Xuc2420842018-02-27 17:05:39 -08001794 // Skip the command if we explicitly set the corresponding function pointer to nullptr, e.g.
1795 // "erase" during block_image_verify.
Tao Baoc3901232018-05-21 16:05:56 -07001796 if (performer == nullptr) {
Tianjie Xuc2420842018-02-27 17:05:39 -08001797 LOG(DEBUG) << "skip executing command [" << line << "]";
1798 continue;
Tianjie Xu284752e2017-12-05 11:04:17 -08001799 }
1800
Tao Bao98f875e2018-05-07 15:03:30 -07001801 // Skip all commands before the saved last command index when resuming an update, except for
1802 // "new" command. Because new commands read in the data sequentially.
Tao Bao26efb0a2018-05-21 14:59:55 -07001803 if (params.canwrite && skip_executed_command && cmdindex <= saved_last_command_index &&
Tao Baoc3901232018-05-21 16:05:56 -07001804 cmd_type != Command::Type::NEW) {
Tao Bao26efb0a2018-05-21 14:59:55 -07001805 LOG(INFO) << "Skipping already executed command: " << cmdindex
Tianjie Xu284752e2017-12-05 11:04:17 -08001806 << ", last executed command for previous update: " << saved_last_command_index;
1807 continue;
1808 }
1809
Tao Baoc3901232018-05-21 16:05:56 -07001810 if (performer(params) == -1) {
Tao Bao33567772017-03-13 14:57:34 -07001811 LOG(ERROR) << "failed to execute command [" << line << "]";
Tianjie Xu69ffa152018-08-01 16:40:00 -07001812 if (cmd_type == Command::Type::COMPUTE_HASH_TREE && failure_type == kNoCause) {
1813 failure_type = kHashTreeComputationFailure;
1814 }
Tao Bao33567772017-03-13 14:57:34 -07001815 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001816 }
1817
Tao Bao26efb0a2018-05-21 14:59:55 -07001818 // In verify mode, check if the commands before the saved last_command_index have been executed
1819 // correctly. If some target blocks have unexpected contents, delete the last command file so
1820 // that we will resume the update from the first command in the transfer list.
1821 if (!params.canwrite && skip_executed_command && cmdindex <= saved_last_command_index) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001822 // TODO(xunchang) check that the cmdline of the saved index is correct.
Tao Baoc3901232018-05-21 16:05:56 -07001823 if ((cmd_type == Command::Type::MOVE || cmd_type == Command::Type::BSDIFF ||
1824 cmd_type == Command::Type::IMGDIFF) &&
Tianjie Xu284752e2017-12-05 11:04:17 -08001825 !params.target_verified) {
1826 LOG(WARNING) << "Previously executed command " << saved_last_command_index << ": "
1827 << params.cmdline << " doesn't produce expected target blocks.";
Tao Bao26efb0a2018-05-21 14:59:55 -07001828 skip_executed_command = false;
Tianjie Xu284752e2017-12-05 11:04:17 -08001829 DeleteLastCommandFile();
1830 }
1831 }
Tao Baoc3901232018-05-21 16:05:56 -07001832
Sami Tolvanen90221202014-12-09 16:39:47 +00001833 if (params.canwrite) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001834 if (fsync(params.fd) == -1) {
1835 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001836 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001837 goto pbiudone;
1838 }
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001839
Tao Bao26efb0a2018-05-21 14:59:55 -07001840 if (!UpdateLastCommandIndex(cmdindex, params.cmdline)) {
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001841 LOG(WARNING) << "Failed to update the last command file.";
1842 }
1843
Tao Bao33567772017-03-13 14:57:34 -07001844 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1845 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001846 }
Tao Bao33567772017-03-13 14:57:34 -07001847 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001848
Tao Bao33567772017-03-13 14:57:34 -07001849 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001850
Tao Bao33567772017-03-13 14:57:34 -07001851pbiudone:
Tianjie Xu5450c842017-10-18 13:15:21 -07001852 if (params.canwrite) {
1853 pthread_mutex_lock(&params.nti.mu);
1854 if (params.nti.receiver_available) {
1855 LOG(WARNING) << "new data receiver is still available after executing all commands.";
1856 }
1857 params.nti.receiver_available = false;
1858 pthread_cond_broadcast(&params.nti.cv);
1859 pthread_mutex_unlock(&params.nti.mu);
1860 int ret = pthread_join(params.thread, nullptr);
1861 if (ret != 0) {
1862 LOG(WARNING) << "pthread join returned with " << strerror(ret);
1863 }
1864
1865 if (rc == 0) {
1866 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1867 LOG(INFO) << "stashed " << params.stashed << " blocks";
1868 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1869
1870 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1871 if (partition != nullptr && *(partition + 1) != 0) {
1872 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1873 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1874 fflush(cmd_pipe);
1875 }
1876 // Delete stash only after successfully completing the update, as it may contain blocks needed
1877 // to complete the update later.
1878 DeleteStash(params.stashbase);
Tianjie Xu284752e2017-12-05 11:04:17 -08001879 DeleteLastCommandFile();
Tao Bao864c6682018-05-07 11:38:25 -07001880
1881 // Create a marker on /cache partition, which allows skipping the update on this partition on
1882 // retry. The marker will be removed once booting into normal boot, or before starting next
1883 // fresh install.
1884 if (!SetPartitionUpdatedMarker(updated_marker)) {
1885 LOG(WARNING) << "Failed to set updated marker; continuing";
1886 }
Tianjie Xu5450c842017-10-18 13:15:21 -07001887 }
1888
1889 pthread_mutex_destroy(&params.nti.mu);
1890 pthread_cond_destroy(&params.nti.cv);
1891 } else if (rc == 0) {
1892 LOG(INFO) << "verified partition contents; update may be resumed";
1893 }
1894
Tianjie Xu22f11202018-08-27 10:50:31 -07001895 if (fsync(params.fd) == -1) {
1896 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Bao33567772017-03-13 14:57:34 -07001897 PLOG(ERROR) << "fsync failed";
1898 }
1899 // params.fd will be automatically closed because it's a unique_fd.
1900
Tianjie Xu107a34f2017-06-29 17:04:21 -07001901 if (params.nti.brotli_decoder_state != nullptr) {
1902 BrotliDecoderDestroyInstance(params.nti.brotli_decoder_state);
1903 }
1904
Tianjie Xu284752e2017-12-05 11:04:17 -08001905 // Delete the last command file if the update cannot be resumed.
1906 if (params.isunresumable) {
1907 DeleteLastCommandFile();
1908 }
1909
Tao Bao33567772017-03-13 14:57:34 -07001910 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1911 // created the stash.
1912 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1913 DeleteStash(params.stashbase);
1914 }
1915
1916 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1917 state->cause_code = failure_type;
1918 }
1919
1920 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001921}
1922
Tao Bao33567772017-03-13 14:57:34 -07001923/**
1924 * The transfer list is a text file containing commands to transfer data from one place to another
1925 * on the target partition. We parse it and execute the commands in order:
1926 *
1927 * zero [rangeset]
1928 * - Fill the indicated blocks with zeros.
1929 *
1930 * new [rangeset]
1931 * - Fill the blocks with data read from the new_data file.
1932 *
1933 * erase [rangeset]
1934 * - Mark the given blocks as empty.
1935 *
1936 * move <...>
1937 * bsdiff <patchstart> <patchlen> <...>
1938 * imgdiff <patchstart> <patchlen> <...>
1939 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1940 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1941 *
1942 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1943 *
1944 * stash <stash_id> <src_range>
1945 * - Load the given source range and stash the data in the given slot of the stash table.
1946 *
1947 * free <stash_id>
1948 * - Free the given stash data.
1949 *
1950 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1951 * a patch or move) after it has been written.
1952 *
1953 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1954 * in a move/bsdiff/imgdiff command.
1955 *
1956 * Within one command the source and target ranges may overlap so in general we need to read the
1957 * entire source into memory before writing anything to the target blocks.
1958 *
1959 * All the patch data is concatenated into one patch_data file in the update package. It must be
1960 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1961 * already compressed, we lose very little by not compressing their concatenation.)
1962 *
1963 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1964 * additional hashes before the range parameters, which are used to check if the command has already
1965 * been completed and verify the integrity of the source data.
1966 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001967Value* BlockImageVerifyFn(const char* name, State* state,
1968 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc3901232018-05-21 16:05:56 -07001969 // Commands which are not allowed are set to nullptr to skip them completely.
1970 const CommandMap command_map{
1971 // clang-format off
Tianjie Xu69ffa152018-08-01 16:40:00 -07001972 { Command::Type::ABORT, PerformCommandAbort },
1973 { Command::Type::BSDIFF, PerformCommandDiff },
1974 { Command::Type::COMPUTE_HASH_TREE, PerformCommandComputeHashTree },
1975 { Command::Type::ERASE, nullptr },
1976 { Command::Type::FREE, PerformCommandFree },
1977 { Command::Type::IMGDIFF, PerformCommandDiff },
1978 { Command::Type::MOVE, PerformCommandMove },
1979 { Command::Type::NEW, nullptr },
1980 { Command::Type::STASH, PerformCommandStash },
1981 { Command::Type::ZERO, nullptr },
Tao Baoc3901232018-05-21 16:05:56 -07001982 // clang-format on
1983 };
1984 CHECK_EQ(static_cast<size_t>(Command::Type::LAST), command_map.size());
Sami Tolvanen90221202014-12-09 16:39:47 +00001985
Tao Baoc3901232018-05-21 16:05:56 -07001986 // Perform a dry run without writing to test if an update can proceed.
1987 return PerformBlockImageUpdate(name, state, argv, command_map, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001988}
1989
Tianjie Xuc4447322017-03-06 14:44:59 -08001990Value* BlockImageUpdateFn(const char* name, State* state,
1991 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc3901232018-05-21 16:05:56 -07001992 const CommandMap command_map{
1993 // clang-format off
Tianjie Xu69ffa152018-08-01 16:40:00 -07001994 { Command::Type::ABORT, PerformCommandAbort },
1995 { Command::Type::BSDIFF, PerformCommandDiff },
1996 { Command::Type::COMPUTE_HASH_TREE, PerformCommandComputeHashTree },
1997 { Command::Type::ERASE, PerformCommandErase },
1998 { Command::Type::FREE, PerformCommandFree },
1999 { Command::Type::IMGDIFF, PerformCommandDiff },
2000 { Command::Type::MOVE, PerformCommandMove },
2001 { Command::Type::NEW, PerformCommandNew },
2002 { Command::Type::STASH, PerformCommandStash },
2003 { Command::Type::ZERO, PerformCommandZero },
Tao Baoc3901232018-05-21 16:05:56 -07002004 // clang-format on
2005 };
2006 CHECK_EQ(static_cast<size_t>(Command::Type::LAST), command_map.size());
Sami Tolvanen90221202014-12-09 16:39:47 +00002007
Tao Baoc3901232018-05-21 16:05:56 -07002008 return PerformBlockImageUpdate(name, state, argv, command_map, false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002009}
2010
Tianjie Xuc4447322017-03-06 14:44:59 -08002011Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002012 if (argv.size() != 2) {
2013 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
2014 return StringValue("");
2015 }
2016
2017 std::vector<std::unique_ptr<Value>> args;
2018 if (!ReadValueArgs(state, argv, &args)) {
2019 return nullptr;
2020 }
2021
2022 const std::unique_ptr<Value>& blockdev_filename = args[0];
2023 const std::unique_ptr<Value>& ranges = args[1];
2024
Tao Bao511d7592018-06-19 15:56:49 -07002025 if (blockdev_filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002026 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
2027 return StringValue("");
2028 }
Tao Bao511d7592018-06-19 15:56:49 -07002029 if (ranges->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002030 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2031 return StringValue("");
2032 }
2033
Tianjie Xu22f11202018-08-27 10:50:31 -07002034 android::base::unique_fd fd(open(blockdev_filename->data.c_str(), O_RDWR));
Tao Baoc97edcb2017-03-31 01:18:13 -07002035 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002036 CauseCode cause_code = errno == EIO ? kEioFailure : kFileOpenFailure;
2037 ErrorAbort(state, cause_code, "open \"%s\" failed: %s", blockdev_filename->data.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002038 strerror(errno));
2039 return StringValue("");
2040 }
2041
2042 RangeSet rs = RangeSet::Parse(ranges->data);
Tao Bao67983152017-11-04 00:08:08 -07002043 CHECK(static_cast<bool>(rs));
Tao Baoc97edcb2017-03-31 01:18:13 -07002044
2045 SHA_CTX ctx;
2046 SHA1_Init(&ctx);
2047
2048 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao43bfa6e2018-08-28 10:09:13 -07002049 for (const auto& [begin, end] : rs) {
2050 if (!check_lseek(fd, static_cast<off64_t>(begin) * BLOCKSIZE, SEEK_SET)) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002051 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
2052 strerror(errno));
2053 return StringValue("");
2054 }
2055
Tao Bao43bfa6e2018-08-28 10:09:13 -07002056 for (size_t j = begin; j < end; ++j) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002057 if (!android::base::ReadFully(fd, buffer.data(), BLOCKSIZE)) {
2058 CauseCode cause_code = errno == EIO ? kEioFailure : kFreadFailure;
2059 ErrorAbort(state, cause_code, "failed to read %s: %s", blockdev_filename->data.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002060 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002061 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002062 }
2063
2064 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08002065 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002066 }
2067 uint8_t digest[SHA_DIGEST_LENGTH];
2068 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08002069
Tao Baoc97edcb2017-03-31 01:18:13 -07002070 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002071}
2072
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002073// This function checks if a device has been remounted R/W prior to an incremental
2074// OTA update. This is an common cause of update abortion. The function reads the
2075// 1st block of each partition and check for mounting time/count. It return string "t"
2076// if executes successfully and an empty string otherwise.
2077
Tianjie Xuc4447322017-03-06 14:44:59 -08002078Value* CheckFirstBlockFn(const char* name, State* state,
2079 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002080 if (argv.size() != 1) {
2081 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
2082 argv.size());
2083 return StringValue("");
2084 }
Tianjie Xuc4447322017-03-06 14:44:59 -08002085
Tao Baoc97edcb2017-03-31 01:18:13 -07002086 std::vector<std::unique_ptr<Value>> args;
2087 if (!ReadValueArgs(state, argv, &args)) {
2088 return nullptr;
2089 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002090
Tao Baoc97edcb2017-03-31 01:18:13 -07002091 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07002092
Tao Bao511d7592018-06-19 15:56:49 -07002093 if (arg_filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002094 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2095 return StringValue("");
2096 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002097
Tianjie Xu22f11202018-08-27 10:50:31 -07002098 android::base::unique_fd fd(open(arg_filename->data.c_str(), O_RDONLY));
Tao Baoc97edcb2017-03-31 01:18:13 -07002099 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002100 CauseCode cause_code = errno == EIO ? kEioFailure : kFileOpenFailure;
2101 ErrorAbort(state, cause_code, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002102 strerror(errno));
2103 return StringValue("");
2104 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002105
Tao Baobf5b77d2017-03-30 16:57:29 -07002106 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07002107 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002108
Tao Baode3bbb82018-05-30 16:14:14 -07002109 if (ReadBlocks(blk0, &block0_buffer, fd) == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002110 CauseCode cause_code = errno == EIO ? kEioFailure : kFreadFailure;
2111 ErrorAbort(state, cause_code, "failed to read %s: %s", arg_filename->data.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002112 strerror(errno));
2113 return StringValue("");
2114 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002115
Tao Baoc97edcb2017-03-31 01:18:13 -07002116 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
2117 // Super block starts from block 0, offset 0x400
2118 // 0x2C: len32 Mount time
2119 // 0x30: len32 Write time
2120 // 0x34: len16 Number of mounts since the last fsck
2121 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002122
Tao Baoc97edcb2017-03-31 01:18:13 -07002123 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
2124 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002125
Tao Baoc97edcb2017-03-31 01:18:13 -07002126 if (mount_count > 0) {
2127 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
2128 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
2129 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002130
Tao Baoc97edcb2017-03-31 01:18:13 -07002131 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002132}
2133
Tianjie Xuc4447322017-03-06 14:44:59 -08002134Value* BlockImageRecoverFn(const char* name, State* state,
2135 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002136 if (argv.size() != 2) {
2137 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
2138 argv.size());
2139 return StringValue("");
2140 }
2141
2142 std::vector<std::unique_ptr<Value>> args;
2143 if (!ReadValueArgs(state, argv, &args)) {
2144 return nullptr;
2145 }
2146
2147 const std::unique_ptr<Value>& filename = args[0];
2148 const std::unique_ptr<Value>& ranges = args[1];
2149
Tao Bao511d7592018-06-19 15:56:49 -07002150 if (filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002151 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2152 return StringValue("");
2153 }
Tao Bao511d7592018-06-19 15:56:49 -07002154 if (ranges->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002155 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2156 return StringValue("");
2157 }
Tao Bao67983152017-11-04 00:08:08 -07002158 RangeSet rs = RangeSet::Parse(ranges->data);
2159 if (!rs) {
2160 ErrorAbort(state, kArgsParsingFailure, "failed to parse ranges: %s", ranges->data.c_str());
2161 return StringValue("");
2162 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002163
2164 // Output notice to log when recover is attempted
2165 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
2166
2167 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
2168 fec::io fh(filename->data, O_RDWR);
2169
2170 if (!fh) {
2171 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
2172 strerror(errno));
2173 return StringValue("");
2174 }
2175
2176 if (!fh.has_ecc() || !fh.has_verity()) {
2177 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
2178 return StringValue("");
2179 }
2180
2181 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07002182 if (!fh.get_status(status)) {
2183 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
2184 return StringValue("");
2185 }
2186
Tao Baoc97edcb2017-03-31 01:18:13 -07002187 uint8_t buffer[BLOCKSIZE];
Tao Bao43bfa6e2018-08-28 10:09:13 -07002188 for (const auto& [begin, end] : rs) {
2189 for (size_t j = begin; j < end; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002190 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07002191 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002192 continue;
2193 }
2194
Tao Baobf5b77d2017-03-30 16:57:29 -07002195 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002196 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
2197 filename->data.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002198 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002199 }
2200
2201 // If we want to be able to recover from a situation where rewriting a corrected
2202 // block doesn't guarantee the same data will be returned when re-read later, we
2203 // can save a copy of corrected blocks to /cache. Note:
2204 //
2205 // 1. Maximum space required from /cache is the same as the maximum number of
2206 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
2207 // this would be ~16 MiB, for example.
2208 //
2209 // 2. To find out if this block was corrupted, call fec_get_status after each
2210 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08002211 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002212 }
2213 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
2214 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002215}
2216
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002217void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07002218 RegisterFunction("block_image_verify", BlockImageVerifyFn);
2219 RegisterFunction("block_image_update", BlockImageUpdateFn);
2220 RegisterFunction("block_image_recover", BlockImageRecoverFn);
2221 RegisterFunction("check_first_block", CheckFirstBlockFn);
2222 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002223}