blob: 9d5b017349ecf6f2a5863f58e3716d06bbe9c716 [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
Tom Cherry04e4afb2018-10-05 14:37:13 -0700112 if (!android::base::ParseUint(lines[0], last_command_index)) {
Tianjie Xu284752e2017-12-05 11:04:17 -0800113 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
Yifan Hong363d6242019-01-04 11:14:19 -0800181static bool discard_blocks(int fd, off64_t offset, uint64_t size, bool force = false) {
182 // Don't discard blocks unless the update is a retry run or force == true
183 if (!is_retry && !force) {
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) {
Yifan Hong363d6242019-01-04 11:14:19 -0800189 // On devices that does not support BLKDISCARD, ignore the error.
190 if (errno == EOPNOTSUPP) {
191 return true;
192 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700193 PLOG(ERROR) << "BLKDISCARD ioctl failed";
194 return false;
195 }
196 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700197}
198
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700199static bool check_lseek(int fd, off64_t offset, int whence) {
200 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
201 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700202 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800203 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700204 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700205 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700206 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700207}
208
Tao Baode3bbb82018-05-30 16:14:14 -0700209static void allocate(size_t size, std::vector<uint8_t>* buffer) {
210 // If the buffer's big enough, reuse it.
211 if (size <= buffer->size()) return;
212 buffer->resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700213}
214
Tao Bao60a70af2017-03-26 14:03:52 -0700215/**
216 * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
217 * given RangeSet.
218 */
219class RangeSinkWriter {
220 public:
221 RangeSinkWriter(int fd, const RangeSet& tgt)
Tianjie Xu107a34f2017-06-29 17:04:21 -0700222 : fd_(fd),
223 tgt_(tgt),
224 next_range_(0),
225 current_range_left_(0),
226 bytes_written_(0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700227 CHECK_NE(tgt.size(), static_cast<size_t>(0));
Tao Bao60a70af2017-03-26 14:03:52 -0700228 };
Tao Bao0940fe12015-08-27 16:41:21 -0700229
Tao Bao60a70af2017-03-26 14:03:52 -0700230 bool Finished() const {
Tao Baobf5b77d2017-03-30 16:57:29 -0700231 return next_range_ == tgt_.size() && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700232 }
233
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700234 size_t AvailableSpace() const {
235 return tgt_.blocks() * BLOCKSIZE - bytes_written_;
236 }
237
238 // Return number of bytes written; and 0 indicates a writing failure.
239 size_t Write(const uint8_t* data, size_t size) {
Tao Bao60a70af2017-03-26 14:03:52 -0700240 if (Finished()) {
241 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
242 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700243 }
244
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700245 size_t written = 0;
Tao Bao60a70af2017-03-26 14:03:52 -0700246 while (size > 0) {
247 // Move to the next range as needed.
Tianjie Xu107a34f2017-06-29 17:04:21 -0700248 if (!SeekToOutputRange()) {
249 break;
Tao Bao60a70af2017-03-26 14:03:52 -0700250 }
Tao Baof7eb7602017-03-27 15:12:48 -0700251
Tao Bao60a70af2017-03-26 14:03:52 -0700252 size_t write_now = size;
253 if (current_range_left_ < write_now) {
254 write_now = current_range_left_;
255 }
Tao Baof7eb7602017-03-27 15:12:48 -0700256
Tianjie Xu22f11202018-08-27 10:50:31 -0700257 if (!android::base::WriteFully(fd_, data, write_now)) {
258 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
259 PLOG(ERROR) << "Failed to write " << write_now << " bytes of data";
Tao Baof7eb7602017-03-27 15:12:48 -0700260 break;
261 }
Tao Bao60a70af2017-03-26 14:03:52 -0700262
263 data += write_now;
264 size -= write_now;
265
266 current_range_left_ -= write_now;
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700267 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700268 }
Tao Bao60a70af2017-03-26 14:03:52 -0700269
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700270 bytes_written_ += written;
271 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700272 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700273
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700274 size_t BytesWritten() const {
275 return bytes_written_;
276 }
277
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700278 private:
Tianjie Xu107a34f2017-06-29 17:04:21 -0700279 // Set up the output cursor, move to next range if needed.
280 bool SeekToOutputRange() {
281 // We haven't finished the current range yet.
282 if (current_range_left_ != 0) {
283 return true;
284 }
285 // We can't write any more; let the write function return how many bytes have been written
286 // so far.
287 if (next_range_ >= tgt_.size()) {
288 return false;
289 }
290
291 const Range& range = tgt_[next_range_];
292 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
293 current_range_left_ = (range.second - range.first) * BLOCKSIZE;
294 next_range_++;
295
296 if (!discard_blocks(fd_, offset, current_range_left_)) {
297 return false;
298 }
299 if (!check_lseek(fd_, offset, SEEK_SET)) {
300 return false;
301 }
302 return true;
303 }
304
305 // The output file descriptor.
Tao Bao60a70af2017-03-26 14:03:52 -0700306 int fd_;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700307 // The destination ranges for the data.
Tao Bao60a70af2017-03-26 14:03:52 -0700308 const RangeSet& tgt_;
309 // The next range that we should write to.
310 size_t next_range_;
311 // The number of bytes to write before moving to the next range.
312 size_t current_range_left_;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700313 // Total bytes written by the writer.
314 size_t bytes_written_;
Tao Bao60a70af2017-03-26 14:03:52 -0700315};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700316
Tao Bao60a70af2017-03-26 14:03:52 -0700317/**
318 * All of the data for all the 'new' transfers is contained in one file in the update package,
319 * concatenated together in the order in which transfers.list will need it. We want to stream it out
320 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
321 * section until it's that transfer's turn to go.
322 *
323 * To achieve this, we expand the new data from the archive in a background thread, and block that
324 * threads 'receive uncompressed data' function until the main thread has reached a point where we
325 * want some new data to be written. We signal the background thread with the destination for the
326 * data and block the main thread, waiting for the background thread to complete writing that
327 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
328 * transfer.
329 *
330 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
331 * the main thread wants some data written, it sets writer to the destination location and signals
332 * the condition. When the background thread is done writing, it clears writer and signals the
333 * condition again.
334 */
Tao Bao0940fe12015-08-27 16:41:21 -0700335struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700336 ZipArchiveHandle za;
337 ZipEntry entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700338 bool brotli_compressed;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700339
Tianjie Xu107a34f2017-06-29 17:04:21 -0700340 std::unique_ptr<RangeSinkWriter> writer;
341 BrotliDecoderState* brotli_decoder_state;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700342 bool receiver_available;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700343
Tao Bao60a70af2017-03-26 14:03:52 -0700344 pthread_mutex_t mu;
345 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700346};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700347
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700348static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700349 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700350
Tao Bao60a70af2017-03-26 14:03:52 -0700351 while (size > 0) {
352 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
353 pthread_mutex_lock(&nti->mu);
354 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700355 // End the new data receiver if we encounter an error when performing block image update.
356 if (!nti->receiver_available) {
357 pthread_mutex_unlock(&nti->mu);
358 return false;
359 }
Tao Bao60a70af2017-03-26 14:03:52 -0700360 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700361 }
Tao Bao60a70af2017-03-26 14:03:52 -0700362 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700363
Tao Bao60a70af2017-03-26 14:03:52 -0700364 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
365 // disappear from nti.
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700366 size_t write_now = std::min(size, nti->writer->AvailableSpace());
367 if (nti->writer->Write(data, write_now) != write_now) {
368 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
Tianjie Xu107a34f2017-06-29 17:04:21 -0700369 return false;
370 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700371
372 data += write_now;
373 size -= write_now;
374
375 if (nti->writer->Finished()) {
376 // We have written all the bytes desired by this writer.
377
378 pthread_mutex_lock(&nti->mu);
379 nti->writer = nullptr;
380 pthread_cond_broadcast(&nti->cv);
381 pthread_mutex_unlock(&nti->mu);
382 }
383 }
384
385 return true;
386}
387
388static bool receive_brotli_new_data(const uint8_t* data, size_t size, void* cookie) {
389 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
390
391 while (size > 0 || BrotliDecoderHasMoreOutput(nti->brotli_decoder_state)) {
392 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
393 pthread_mutex_lock(&nti->mu);
394 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700395 // End the receiver if we encounter an error when performing block image update.
396 if (!nti->receiver_available) {
397 pthread_mutex_unlock(&nti->mu);
398 return false;
399 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700400 pthread_cond_wait(&nti->cv, &nti->mu);
401 }
402 pthread_mutex_unlock(&nti->mu);
403
404 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
405 // disappear from nti.
406
407 size_t buffer_size = std::min<size_t>(32768, nti->writer->AvailableSpace());
408 if (buffer_size == 0) {
409 LOG(ERROR) << "No space left in output range";
410 return false;
411 }
412 uint8_t buffer[buffer_size];
413 size_t available_in = size;
414 size_t available_out = buffer_size;
415 uint8_t* next_out = buffer;
416
417 // The brotli decoder will update |data|, |available_in|, |next_out| and |available_out|.
418 BrotliDecoderResult result = BrotliDecoderDecompressStream(
419 nti->brotli_decoder_state, &available_in, &data, &available_out, &next_out, nullptr);
420
421 if (result == BROTLI_DECODER_RESULT_ERROR) {
422 LOG(ERROR) << "Decompression failed with "
423 << BrotliDecoderErrorString(BrotliDecoderGetErrorCode(nti->brotli_decoder_state));
424 return false;
425 }
426
427 LOG(DEBUG) << "bytes to write: " << buffer_size - available_out << ", bytes consumed "
428 << size - available_in << ", decoder status " << result;
429
430 size_t write_now = buffer_size - available_out;
431 if (nti->writer->Write(buffer, write_now) != write_now) {
432 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
433 return false;
434 }
435
436 // Update the remaining size. The input data ptr is already updated by brotli decoder function.
437 size = available_in;
Tao Bao60a70af2017-03-26 14:03:52 -0700438
439 if (nti->writer->Finished()) {
440 // We have written all the bytes desired by this writer.
441
442 pthread_mutex_lock(&nti->mu);
443 nti->writer = nullptr;
444 pthread_cond_broadcast(&nti->cv);
445 pthread_mutex_unlock(&nti->mu);
446 }
447 }
448
449 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700450}
451
452static void* unzip_new_data(void* cookie) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700453 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700454 if (nti->brotli_compressed) {
455 ProcessZipEntryContents(nti->za, &nti->entry, receive_brotli_new_data, nti);
456 } else {
457 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
458 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700459 pthread_mutex_lock(&nti->mu);
460 nti->receiver_available = false;
461 if (nti->writer != nullptr) {
462 pthread_cond_broadcast(&nti->cv);
463 }
464 pthread_mutex_unlock(&nti->mu);
465 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700466}
467
Tao Baode3bbb82018-05-30 16:14:14 -0700468static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>* buffer, int fd) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700469 size_t p = 0;
Tao Bao43bfa6e2018-08-28 10:09:13 -0700470 for (const auto& [begin, end] : src) {
471 if (!check_lseek(fd, static_cast<off64_t>(begin) * BLOCKSIZE, SEEK_SET)) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700472 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000473 }
474
Tao Bao43bfa6e2018-08-28 10:09:13 -0700475 size_t size = (end - begin) * BLOCKSIZE;
Tianjie Xu22f11202018-08-27 10:50:31 -0700476 if (!android::base::ReadFully(fd, buffer->data() + p, size)) {
477 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
478 PLOG(ERROR) << "Failed to read " << size << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -0700479 return -1;
480 }
481
482 p += size;
483 }
484
485 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000486}
487
Tao Bao612336d2015-08-27 16:41:21 -0700488static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700489 size_t written = 0;
Tao Bao43bfa6e2018-08-28 10:09:13 -0700490 for (const auto& [begin, end] : tgt) {
491 off64_t offset = static_cast<off64_t>(begin) * BLOCKSIZE;
492 size_t size = (end - begin) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700493 if (!discard_blocks(fd, offset, size)) {
494 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000495 }
496
Tao Bao60a70af2017-03-26 14:03:52 -0700497 if (!check_lseek(fd, offset, SEEK_SET)) {
498 return -1;
499 }
500
Tianjie Xu22f11202018-08-27 10:50:31 -0700501 if (!android::base::WriteFully(fd, buffer.data() + written, size)) {
502 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
503 PLOG(ERROR) << "Failed to write " << size << " bytes of data";
Tao Bao60a70af2017-03-26 14:03:52 -0700504 return -1;
505 }
506
507 written += size;
508 }
509
510 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000511}
512
Tao Baobaad2d42015-12-06 16:56:27 -0800513// Parameters for transfer list command functions
514struct CommandParameters {
515 std::vector<std::string> tokens;
516 size_t cpos;
Tao Baoc3901232018-05-21 16:05:56 -0700517 std::string cmdname;
518 std::string cmdline;
Tao Baobaad2d42015-12-06 16:56:27 -0800519 std::string freestash;
520 std::string stashbase;
521 bool canwrite;
522 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700523 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800524 bool foundwrites;
525 bool isunresumable;
526 int version;
527 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700528 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800529 NewThreadInfo nti;
530 pthread_t thread;
531 std::vector<uint8_t> buffer;
532 uint8_t* patch_start;
Tianjie Xu284752e2017-12-05 11:04:17 -0800533 bool target_verified; // The target blocks have expected contents already.
Tao Baobaad2d42015-12-06 16:56:27 -0800534};
535
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000536// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
537// handled separately).
538static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
539 const std::vector<uint8_t>& buffer) {
540 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000541 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
542 params.tokens[0] == "imgdiff");
543
544 size_t pos = 0;
545 // Command example:
546 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
547 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
548 // [<loc_range> <stashed_blocks>]
549 if (params.tokens[0] == "move") {
550 // src_range for move starts at the 4th position.
551 if (params.tokens.size() < 5) {
552 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
553 return;
554 }
555 pos = 4;
556 } else {
557 // src_range for diff starts at the 7th position.
558 if (params.tokens.size() < 8) {
559 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
560 return;
561 }
562 pos = 7;
563 }
564
565 // Source blocks in stash only, no work to do.
566 if (params.tokens[pos] == "-") {
567 return;
568 }
569
Tao Bao8f237572017-03-26 13:36:49 -0700570 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tao Bao67983152017-11-04 00:08:08 -0700571 if (!src) {
572 LOG(ERROR) << "Failed to parse range in " << params.cmdline;
573 return;
574 }
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000575
576 RangeSet locs;
577 // If there's no stashed blocks, content in the buffer is consecutive and has the same
578 // order as the source blocks.
579 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700580 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000581 } else {
582 // Otherwise, the next token is the offset of the source blocks in the target range.
583 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
584 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
585 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700586 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700587 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000588 }
589
Tao Baobf5b77d2017-03-30 16:57:29 -0700590 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
591 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700592 size_t block_num = src.GetBlockNumber(i);
593 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000594 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
595
596 uint8_t digest[SHA_DIGEST_LENGTH];
597 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
598 std::string hexdigest = print_sha1(digest);
599 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
600 }
601}
602
603// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
604// in hex for each block.
605static void PrintHashForCorruptedStashedBlocks(const std::string& id,
606 const std::vector<uint8_t>& buffer,
607 const RangeSet& src) {
608 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700609 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000610
Tao Baobf5b77d2017-03-30 16:57:29 -0700611 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700612 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000613
614 uint8_t digest[SHA_DIGEST_LENGTH];
615 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
616 std::string hexdigest = print_sha1(digest);
617 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
618 }
619}
620
621// If the stash file doesn't exist, read the source blocks this stash contains and print the
622// SHA-1 for these blocks.
623static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
624 if (stash_map.find(id) == stash_map.end()) {
625 LOG(ERROR) << "No stash saved for id: " << id;
626 return;
627 }
628
629 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
630 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700631 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tao Baode3bbb82018-05-30 16:14:14 -0700632 if (ReadBlocks(src, &buffer, fd) == -1) {
633 LOG(ERROR) << "failed to read source blocks for stash: " << id;
634 return;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000635 }
636 PrintHashForCorruptedStashedBlocks(id, buffer, src);
637}
638
Tao Bao612336d2015-08-27 16:41:21 -0700639static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Baode3bbb82018-05-30 16:14:14 -0700640 const size_t blocks, bool printerror) {
641 uint8_t digest[SHA_DIGEST_LENGTH];
642 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000643
Tao Baode3bbb82018-05-30 16:14:14 -0700644 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000645
Tao Baode3bbb82018-05-30 16:14:14 -0700646 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000647
Tao Baode3bbb82018-05-30 16:14:14 -0700648 if (hexdigest != expected) {
649 if (printerror) {
650 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read " << hexdigest
651 << ")";
Sami Tolvanen90221202014-12-09 16:39:47 +0000652 }
Tao Baode3bbb82018-05-30 16:14:14 -0700653 return -1;
654 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000655
Tao Baode3bbb82018-05-30 16:14:14 -0700656 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000657}
658
Tao Bao0940fe12015-08-27 16:41:21 -0700659static std::string GetStashFileName(const std::string& base, const std::string& id,
Tao Bao641fa972018-04-25 18:59:40 -0700660 const std::string& postfix) {
661 if (base.empty()) {
662 return "";
663 }
Tao Bao864c6682018-05-07 11:38:25 -0700664 std::string filename = Paths::Get().stash_directory_base() + "/" + base;
665 if (id.empty() && postfix.empty()) {
666 return filename;
667 }
668 return filename + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000669}
670
Tao Baoec8272f2017-03-15 17:39:01 -0700671// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
672// directory and continues despite of errors. Calls the 'callback' function for each file.
673static void EnumerateStash(const std::string& dirname,
674 const std::function<void(const std::string&)>& callback) {
675 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000676
Tao Baoec8272f2017-03-15 17:39:01 -0700677 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000678
Tao Baoec8272f2017-03-15 17:39:01 -0700679 if (directory == nullptr) {
680 if (errno != ENOENT) {
681 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000682 }
Tao Bao51412212016-12-28 14:44:05 -0800683 return;
684 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700685
Tao Baoec8272f2017-03-15 17:39:01 -0700686 dirent* item;
687 while ((item = readdir(directory.get())) != nullptr) {
688 if (item->d_type != DT_REG) continue;
689 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800690 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000691}
692
693// Deletes the stash directory and all files in it. Assumes that it only
694// contains files. There is nothing we can do about unlikely, but possible
695// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700696static void DeleteFile(const std::string& fn) {
697 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000698
Tao Baoec8272f2017-03-15 17:39:01 -0700699 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000700
Tao Baoec8272f2017-03-15 17:39:01 -0700701 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
702 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
703 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000704}
705
Tao Baoe6aa3322015-08-05 15:20:27 -0700706static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700707 if (base.empty()) return;
708
709 LOG(INFO) << "deleting stash " << base;
710
711 std::string dirname = GetStashFileName(base, "", "");
712 EnumerateStash(dirname, DeleteFile);
713
714 if (rmdir(dirname.c_str()) == -1) {
715 if (errno != ENOENT && errno != ENOTDIR) {
716 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000717 }
Tao Baoec8272f2017-03-15 17:39:01 -0700718 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000719}
720
Tao Baode3bbb82018-05-30 16:14:14 -0700721static int LoadStash(const CommandParameters& params, const std::string& id, bool verify,
722 std::vector<uint8_t>* buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700723 // In verify mode, if source range_set was saved for the given hash, check contents in the source
724 // blocks first. If the check fails, search for the stashed files on /cache as usual.
725 if (!params.canwrite) {
726 if (stash_map.find(id) != stash_map.end()) {
727 const RangeSet& src = stash_map[id];
728 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700729
Tao Baobf5b77d2017-03-30 16:57:29 -0700730 if (ReadBlocks(src, buffer, params.fd) == -1) {
731 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700732 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700733 }
Tao Baode3bbb82018-05-30 16:14:14 -0700734 if (VerifyBlocks(id, *buffer, src.blocks(), true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700735 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu3c5958f2018-03-09 14:10:25 -0800736 if (!is_retry) {
737 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
738 }
Tao Bao0940fe12015-08-27 16:41:21 -0700739 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700740 }
741 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000742 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700743 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000744
Tao Baobf5b77d2017-03-30 16:57:29 -0700745 std::string fn = GetStashFileName(params.stashbase, id, "");
746
747 struct stat sb;
748 if (stat(fn.c_str(), &sb) == -1) {
749 if (errno != ENOENT || printnoent) {
750 PLOG(ERROR) << "stat \"" << fn << "\" failed";
751 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000752 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700753 return -1;
754 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000755
Tao Baobf5b77d2017-03-30 16:57:29 -0700756 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000757
Tao Baobf5b77d2017-03-30 16:57:29 -0700758 if ((sb.st_size % BLOCKSIZE) != 0) {
759 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
760 return -1;
761 }
762
Tianjie Xu22f11202018-08-27 10:50:31 -0700763 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY)));
Tao Baobf5b77d2017-03-30 16:57:29 -0700764 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700765 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Baobf5b77d2017-03-30 16:57:29 -0700766 PLOG(ERROR) << "open \"" << fn << "\" failed";
767 return -1;
768 }
769
770 allocate(sb.st_size, buffer);
771
Tianjie Xu22f11202018-08-27 10:50:31 -0700772 if (!android::base::ReadFully(fd, buffer->data(), sb.st_size)) {
773 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
774 PLOG(ERROR) << "Failed to read " << sb.st_size << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -0700775 return -1;
776 }
777
Tao Bao64957ce2018-05-30 16:21:39 -0700778 size_t blocks = sb.st_size / BLOCKSIZE;
Tao Baode3bbb82018-05-30 16:14:14 -0700779 if (verify && VerifyBlocks(id, *buffer, blocks, true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700780 LOG(ERROR) << "unexpected contents in " << fn;
781 if (stash_map.find(id) == stash_map.end()) {
782 LOG(ERROR) << "failed to find source blocks number for stash " << id
783 << " when executing command: " << params.cmdname;
784 } else {
785 const RangeSet& src = stash_map[id];
Tao Baode3bbb82018-05-30 16:14:14 -0700786 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000787 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700788 DeleteFile(fn);
789 return -1;
790 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000791
Tao Baobf5b77d2017-03-30 16:57:29 -0700792 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000793}
794
Tao Bao612336d2015-08-27 16:41:21 -0700795static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baode3bbb82018-05-30 16:14:14 -0700796 const std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
797 if (base.empty()) {
798 return -1;
799 }
800
Tao Bao5ee25662018-07-11 15:55:32 -0700801 if (checkspace && !CheckAndFreeSpaceOnCache(blocks * BLOCKSIZE)) {
Tao Baode3bbb82018-05-30 16:14:14 -0700802 LOG(ERROR) << "not enough space to write stash";
803 return -1;
804 }
805
806 std::string fn = GetStashFileName(base, id, ".partial");
807 std::string cn = GetStashFileName(base, id, "");
808
809 if (exists) {
810 struct stat sb;
811 int res = stat(cn.c_str(), &sb);
812
813 if (res == 0) {
814 // The file already exists and since the name is the hash of the contents,
815 // it's safe to assume the contents are identical (accidental hash collisions
816 // are unlikely)
817 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
818 *exists = true;
819 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000820 }
821
Tao Baode3bbb82018-05-30 16:14:14 -0700822 *exists = false;
823 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000824
Tao Baode3bbb82018-05-30 16:14:14 -0700825 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000826
Tao Baode3bbb82018-05-30 16:14:14 -0700827 android::base::unique_fd fd(
Tianjie Xu22f11202018-08-27 10:50:31 -0700828 TEMP_FAILURE_RETRY(open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Tao Baode3bbb82018-05-30 16:14:14 -0700829 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700830 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Baode3bbb82018-05-30 16:14:14 -0700831 PLOG(ERROR) << "failed to create \"" << fn << "\"";
832 return -1;
833 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100834
Tao Baode3bbb82018-05-30 16:14:14 -0700835 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
836 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
837 return -1;
838 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100839
Tianjie Xu22f11202018-08-27 10:50:31 -0700840 if (!android::base::WriteFully(fd, buffer.data(), blocks * BLOCKSIZE)) {
841 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
842 PLOG(ERROR) << "Failed to write " << blocks * BLOCKSIZE << " bytes of data";
Tao Baode3bbb82018-05-30 16:14:14 -0700843 return -1;
844 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100845
Tianjie Xu22f11202018-08-27 10:50:31 -0700846 if (fsync(fd) == -1) {
847 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Baode3bbb82018-05-30 16:14:14 -0700848 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
849 return -1;
850 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000851
Tao Baode3bbb82018-05-30 16:14:14 -0700852 if (rename(fn.c_str(), cn.c_str()) == -1) {
853 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
854 return -1;
855 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000856
Tao Baode3bbb82018-05-30 16:14:14 -0700857 std::string dname = GetStashFileName(base, "", "");
858 if (!FsyncDir(dname)) {
Tao Baode3bbb82018-05-30 16:14:14 -0700859 return -1;
860 }
Tianjie Xua946b9e2017-03-21 16:24:57 -0700861
Tao Baode3bbb82018-05-30 16:14:14 -0700862 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000863}
864
865// Creates a directory for storing stash files and checks if the /cache partition
866// hash enough space for the expected amount of blocks we need to store. Returns
867// >0 if we created the directory, zero if it existed already, and <0 of failure.
Tao Bao864c6682018-05-07 11:38:25 -0700868static int CreateStash(State* state, size_t maxblocks, const std::string& base) {
Tao Bao51412212016-12-28 14:44:05 -0800869 std::string dirname = GetStashFileName(base, "", "");
870 struct stat sb;
871 int res = stat(dirname.c_str(), &sb);
Tao Bao51412212016-12-28 14:44:05 -0800872 if (res == -1 && errno != ENOENT) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800873 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800874 strerror(errno));
875 return -1;
Tao Bao864c6682018-05-07 11:38:25 -0700876 }
877
878 size_t max_stash_size = maxblocks * BLOCKSIZE;
879 if (res == -1) {
Tao Bao51412212016-12-28 14:44:05 -0800880 LOG(INFO) << "creating stash " << dirname;
881 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
882
883 if (res != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800884 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800885 strerror(errno));
886 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000887 }
888
Tianjie Xua946b9e2017-03-21 16:24:57 -0700889 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
Tianjie Xu5ad80282018-01-28 15:37:48 -0800890 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s", dirname.c_str(),
Tianjie Xua946b9e2017-03-21 16:24:57 -0700891 strerror(errno));
892 return -1;
893 }
894
Tao Bao5ee25662018-07-11 15:55:32 -0700895 if (!CheckAndFreeSpaceOnCache(max_stash_size)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800896 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)",
Tao Bao51412212016-12-28 14:44:05 -0800897 max_stash_size);
898 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000899 }
900
Tao Bao51412212016-12-28 14:44:05 -0800901 return 1; // Created directory
902 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000903
Tao Bao51412212016-12-28 14:44:05 -0800904 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000905
Tao Baoec8272f2017-03-15 17:39:01 -0700906 // If the directory already exists, calculate the space already allocated to stash files and check
907 // if there's enough for all required blocks. Delete any partially completed stash files first.
908 EnumerateStash(dirname, [](const std::string& fn) {
909 if (android::base::EndsWith(fn, ".partial")) {
910 DeleteFile(fn);
911 }
912 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000913
Tao Bao51412212016-12-28 14:44:05 -0800914 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700915 EnumerateStash(dirname, [&existing](const std::string& fn) {
916 if (fn.empty()) return;
917 struct stat sb;
918 if (stat(fn.c_str(), &sb) == -1) {
919 PLOG(ERROR) << "stat \"" << fn << "\" failed";
920 return;
921 }
922 existing += static_cast<size_t>(sb.st_size);
923 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000924
Tao Bao51412212016-12-28 14:44:05 -0800925 if (max_stash_size > existing) {
926 size_t needed = max_stash_size - existing;
Tao Bao5ee25662018-07-11 15:55:32 -0700927 if (!CheckAndFreeSpaceOnCache(needed)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800928 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)",
Tao Bao51412212016-12-28 14:44:05 -0800929 needed);
930 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000931 }
Tao Bao51412212016-12-28 14:44:05 -0800932 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000933
Tao Bao51412212016-12-28 14:44:05 -0800934 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000935}
936
Tao Baobaad2d42015-12-06 16:56:27 -0800937static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700938 if (base.empty() || id.empty()) {
939 return -1;
940 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000941
Tao Baoec8272f2017-03-15 17:39:01 -0700942 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000943
Tao Baoec8272f2017-03-15 17:39:01 -0700944 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700945}
946
Tao Baobf5b77d2017-03-30 16:57:29 -0700947// Source contains packed data, which we want to move to the locations given in locs in the dest
948// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700949static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700950 const std::vector<uint8_t>& source) {
951 const uint8_t* from = source.data();
952 uint8_t* to = dest.data();
953 size_t start = locs.blocks();
954 // Must do the movement backward.
955 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
956 size_t blocks = it->second - it->first;
957 start -= blocks;
958 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
959 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700960}
961
Tao Baod2aecd42017-03-23 14:43:44 -0700962/**
963 * We expect to parse the remainder of the parameter tokens as one of:
964 *
965 * <src_block_count> <src_range>
966 * (loads data from source image only)
967 *
968 * <src_block_count> - <[stash_id:stash_range] ...>
969 * (loads data from stashes only)
970 *
971 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
972 * (loads data from both source image and stashes)
973 *
974 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
975 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
976 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
977 * LoadStash.
978 */
979static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
980 bool* overlap) {
981 CHECK(src_blocks != nullptr);
982 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700983
Tao Baod2aecd42017-03-23 14:43:44 -0700984 // <src_block_count>
985 const std::string& token = params.tokens[params.cpos++];
986 if (!android::base::ParseUint(token, src_blocks)) {
987 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
988 return -1;
989 }
Tao Baobaad2d42015-12-06 16:56:27 -0800990
Tao Baode3bbb82018-05-30 16:14:14 -0700991 allocate(*src_blocks * BLOCKSIZE, &params.buffer);
Tao Baod2aecd42017-03-23 14:43:44 -0700992
993 // "-" or <src_range> [<src_loc>]
994 if (params.tokens[params.cpos] == "-") {
995 // no source ranges, only stashes
996 params.cpos++;
997 } else {
Tao Bao8f237572017-03-26 13:36:49 -0700998 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -0700999 CHECK(static_cast<bool>(src));
Tao Bao8f237572017-03-26 13:36:49 -07001000 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -07001001
Tao Baode3bbb82018-05-30 16:14:14 -07001002 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001003 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -08001004 }
1005
Tao Baod2aecd42017-03-23 14:43:44 -07001006 if (params.cpos >= params.tokens.size()) {
1007 // no stashes, only source range
1008 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -08001009 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001010
Tao Bao8f237572017-03-26 13:36:49 -07001011 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001012 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001013 MoveRange(params.buffer, locs, params.buffer);
1014 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001015
Tao Baod2aecd42017-03-23 14:43:44 -07001016 // <[stash_id:stash_range]>
1017 while (params.cpos < params.tokens.size()) {
1018 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
1019 // in the source block that stashed data should go.
1020 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1021 if (tokens.size() != 2) {
1022 LOG(ERROR) << "invalid parameter";
1023 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001024 }
1025
Tao Baod2aecd42017-03-23 14:43:44 -07001026 std::vector<uint8_t> stash;
Tao Baode3bbb82018-05-30 16:14:14 -07001027 if (LoadStash(params, tokens[0], false, &stash, true) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001028 // These source blocks will fail verification if used later, but we
1029 // will let the caller decide if this is a fatal failure
1030 LOG(ERROR) << "failed to load stash " << tokens[0];
1031 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +00001032 }
1033
Tao Bao8f237572017-03-26 13:36:49 -07001034 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Bao67983152017-11-04 00:08:08 -07001035 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001036 MoveRange(params.buffer, locs, stash);
1037 }
1038
1039 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001040}
1041
Tao Bao33567772017-03-13 14:57:34 -07001042/**
1043 * Do a source/target load for move/bsdiff/imgdiff in version 3.
1044 *
1045 * We expect to parse the remainder of the parameter tokens as one of:
1046 *
1047 * <tgt_range> <src_block_count> <src_range>
1048 * (loads data from source image only)
1049 *
1050 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
1051 * (loads data from stashes only)
1052 *
1053 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1054 * (loads data from both source image and stashes)
1055 *
Tao Baod2aecd42017-03-23 14:43:44 -07001056 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
1057 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -07001058 * verification fails in a way that the update cannot be resumed anymore.
1059 *
1060 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
1061 * the return value is -1 and the command should be aborted.
1062 *
1063 * If the return value is 1, the command has already been completed according to the contents of the
1064 * target blocks, and should not be performed again.
1065 *
1066 * If the return value is 0, source blocks have expected content and the command can be performed.
1067 */
Tao Baode3bbb82018-05-30 16:14:14 -07001068static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet* tgt, size_t* src_blocks,
Tao Bao4a135082018-06-07 22:27:44 -07001069 bool onehash) {
Tao Baod2aecd42017-03-23 14:43:44 -07001070 CHECK(src_blocks != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001071
Tao Baod2aecd42017-03-23 14:43:44 -07001072 if (params.cpos >= params.tokens.size()) {
1073 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001074 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001075 }
1076
1077 std::string srchash = params.tokens[params.cpos++];
1078 std::string tgthash;
1079
1080 if (onehash) {
1081 tgthash = srchash;
1082 } else {
1083 if (params.cpos >= params.tokens.size()) {
1084 LOG(ERROR) << "missing target hash";
1085 return -1;
1086 }
1087 tgthash = params.tokens[params.cpos++];
1088 }
1089
1090 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1091 // "-"/<src_range>.
1092 if (params.cpos + 2 >= params.tokens.size()) {
1093 LOG(ERROR) << "invalid parameters";
1094 return -1;
1095 }
1096
1097 // <tgt_range>
Tao Baode3bbb82018-05-30 16:14:14 -07001098 *tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1099 CHECK(static_cast<bool>(*tgt));
Tao Baod2aecd42017-03-23 14:43:44 -07001100
Tao Baode3bbb82018-05-30 16:14:14 -07001101 std::vector<uint8_t> tgtbuffer(tgt->blocks() * BLOCKSIZE);
1102 if (ReadBlocks(*tgt, &tgtbuffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001103 return -1;
1104 }
1105
1106 // Return now if target blocks already have expected content.
Tao Baode3bbb82018-05-30 16:14:14 -07001107 if (VerifyBlocks(tgthash, tgtbuffer, tgt->blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001108 return 1;
1109 }
1110
1111 // Load source blocks.
Tao Bao4a135082018-06-07 22:27:44 -07001112 bool overlap = false;
1113 if (LoadSourceBlocks(params, *tgt, src_blocks, &overlap) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001114 return -1;
1115 }
1116
1117 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
Tao Bao4a135082018-06-07 22:27:44 -07001118 // If source and target blocks overlap, stash the source blocks so we can resume from possible
1119 // write errors. In verify mode, we can skip stashing because the source blocks won't be
1120 // overwritten.
1121 if (overlap && params.canwrite) {
Tao Baod2aecd42017-03-23 14:43:44 -07001122 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1123
1124 bool stash_exists = false;
1125 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1126 &stash_exists) != 0) {
1127 LOG(ERROR) << "failed to stash overlapping source blocks";
1128 return -1;
1129 }
1130
1131 params.stashed += *src_blocks;
1132 // Can be deleted when the write has completed.
1133 if (!stash_exists) {
1134 params.freestash = srchash;
1135 }
1136 }
1137
1138 // Source blocks have expected content, command can proceed.
1139 return 0;
1140 }
1141
Tao Bao4a135082018-06-07 22:27:44 -07001142 if (overlap && LoadStash(params, srchash, true, &params.buffer, true) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001143 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1144 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1145 // command.
1146 return 0;
1147 }
1148
1149 // Valid source data not available, update cannot be resumed.
1150 LOG(ERROR) << "partition has unexpected contents";
1151 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1152
1153 params.isunresumable = true;
1154
1155 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001156}
1157
Tao Bao0940fe12015-08-27 16:41:21 -07001158static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001159 size_t blocks = 0;
Tao Bao33567772017-03-13 14:57:34 -07001160 RangeSet tgt;
Tao Bao4a135082018-06-07 22:27:44 -07001161 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001162
Tao Bao33567772017-03-13 14:57:34 -07001163 if (status == -1) {
1164 LOG(ERROR) << "failed to read blocks for move";
1165 return -1;
1166 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001167
Tao Bao33567772017-03-13 14:57:34 -07001168 if (status == 0) {
1169 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001170 } else {
1171 params.target_verified = true;
1172 if (params.foundwrites) {
1173 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1174 }
Tao Bao33567772017-03-13 14:57:34 -07001175 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001176
Tao Bao33567772017-03-13 14:57:34 -07001177 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001178 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001179 LOG(INFO) << " moving " << blocks << " blocks";
1180
1181 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1182 return -1;
1183 }
1184 } else {
1185 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001186 }
Tao Bao33567772017-03-13 14:57:34 -07001187 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001188
Tao Bao33567772017-03-13 14:57:34 -07001189 if (!params.freestash.empty()) {
1190 FreeStash(params.stashbase, params.freestash);
1191 params.freestash.clear();
1192 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001193
Tao Baobf5b77d2017-03-30 16:57:29 -07001194 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001195
Tao Bao33567772017-03-13 14:57:34 -07001196 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001197}
1198
Tao Bao0940fe12015-08-27 16:41:21 -07001199static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001200 // <stash_id> <src_range>
1201 if (params.cpos + 1 >= params.tokens.size()) {
1202 LOG(ERROR) << "missing id and/or src range fields in stash command";
1203 return -1;
1204 }
1205
1206 const std::string& id = params.tokens[params.cpos++];
Tao Baode3bbb82018-05-30 16:14:14 -07001207 if (LoadStash(params, id, true, &params.buffer, false) == 0) {
Tao Baobcf46492017-03-23 15:28:20 -07001208 // Stash file already exists and has expected contents. Do not read from source again, as the
1209 // source may have been already overwritten during a previous attempt.
1210 return 0;
1211 }
1212
Tao Bao8f237572017-03-26 13:36:49 -07001213 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001214 CHECK(static_cast<bool>(src));
Tao Baobcf46492017-03-23 15:28:20 -07001215
Tao Bao64957ce2018-05-30 16:21:39 -07001216 size_t blocks = src.blocks();
Tao Baode3bbb82018-05-30 16:14:14 -07001217 allocate(blocks * BLOCKSIZE, &params.buffer);
1218 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baobcf46492017-03-23 15:28:20 -07001219 return -1;
1220 }
Tao Baobcf46492017-03-23 15:28:20 -07001221 stash_map[id] = src;
1222
1223 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1224 // Source blocks have unexpected contents. If we actually need this data later, this is an
1225 // unrecoverable error. However, the command that uses the data may have already completed
1226 // previously, so the possible failure will occur during source block verification.
1227 LOG(ERROR) << "failed to load source blocks for stash " << id;
1228 return 0;
1229 }
1230
1231 // In verify mode, we don't need to stash any blocks.
1232 if (!params.canwrite) {
1233 return 0;
1234 }
1235
1236 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xu284752e2017-12-05 11:04:17 -08001237 int result = WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
1238 if (result == 0) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001239 params.stashed += blocks;
1240 }
1241 return result;
Sami Tolvanen90221202014-12-09 16:39:47 +00001242}
1243
Tao Bao0940fe12015-08-27 16:41:21 -07001244static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001245 // <stash_id>
1246 if (params.cpos >= params.tokens.size()) {
1247 LOG(ERROR) << "missing stash id in free command";
1248 return -1;
1249 }
Tao Baobaad2d42015-12-06 16:56:27 -08001250
Tao Baobcf46492017-03-23 15:28:20 -07001251 const std::string& id = params.tokens[params.cpos++];
1252 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001253
Tao Baobcf46492017-03-23 15:28:20 -07001254 if (params.createdstash || params.canwrite) {
1255 return FreeStash(params.stashbase, id);
1256 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001257
Tao Baobcf46492017-03-23 15:28:20 -07001258 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001259}
1260
Tao Bao0940fe12015-08-27 16:41:21 -07001261static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001262 if (params.cpos >= params.tokens.size()) {
1263 LOG(ERROR) << "missing target blocks for zero";
1264 return -1;
1265 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001266
Tao Baobf5b77d2017-03-30 16:57:29 -07001267 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001268 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001269
1270 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1271
Tao Baode3bbb82018-05-30 16:14:14 -07001272 allocate(BLOCKSIZE, &params.buffer);
Tao Baobf5b77d2017-03-30 16:57:29 -07001273 memset(params.buffer.data(), 0, BLOCKSIZE);
1274
1275 if (params.canwrite) {
Tao Bao43bfa6e2018-08-28 10:09:13 -07001276 for (const auto& [begin, end] : tgt) {
1277 off64_t offset = static_cast<off64_t>(begin) * BLOCKSIZE;
1278 size_t size = (end - begin) * BLOCKSIZE;
Tao Baobf5b77d2017-03-30 16:57:29 -07001279 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001280 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001281 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001282
Tao Baobf5b77d2017-03-30 16:57:29 -07001283 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1284 return -1;
1285 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001286
Tao Bao43bfa6e2018-08-28 10:09:13 -07001287 for (size_t j = begin; j < end; ++j) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001288 if (!android::base::WriteFully(params.fd, params.buffer.data(), BLOCKSIZE)) {
1289 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
1290 PLOG(ERROR) << "Failed to write " << BLOCKSIZE << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -07001291 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001292 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001293 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001294 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001295 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001296
Tao Baobf5b77d2017-03-30 16:57:29 -07001297 if (params.cmdname[0] == 'z') {
1298 // Update only for the zero command, as the erase command will call
1299 // this if DEBUG_ERASE is defined.
1300 params.written += tgt.blocks();
1301 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001302
Tao Baobf5b77d2017-03-30 16:57:29 -07001303 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001304}
1305
Tao Bao0940fe12015-08-27 16:41:21 -07001306static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001307 if (params.cpos >= params.tokens.size()) {
1308 LOG(ERROR) << "missing target blocks for new";
1309 return -1;
1310 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001311
Tao Bao8f237572017-03-26 13:36:49 -07001312 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001313 CHECK(static_cast<bool>(tgt));
Tao Bao60a70af2017-03-26 14:03:52 -07001314
1315 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001316 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001317
Tao Bao60a70af2017-03-26 14:03:52 -07001318 pthread_mutex_lock(&params.nti.mu);
Tianjie Xu6ed175d2017-07-18 11:29:40 -07001319 params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
Tao Bao60a70af2017-03-26 14:03:52 -07001320 pthread_cond_broadcast(&params.nti.cv);
1321
1322 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001323 if (!params.nti.receiver_available) {
1324 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1325 << " bytes of new data";
1326 pthread_mutex_unlock(&params.nti.mu);
1327 return -1;
1328 }
Tao Bao60a70af2017-03-26 14:03:52 -07001329 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001330 }
1331
Tao Bao60a70af2017-03-26 14:03:52 -07001332 pthread_mutex_unlock(&params.nti.mu);
1333 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001334
Tao Baobf5b77d2017-03-30 16:57:29 -07001335 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001336
Tao Bao60a70af2017-03-26 14:03:52 -07001337 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001338}
1339
Tao Bao0940fe12015-08-27 16:41:21 -07001340static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001341 // <offset> <length>
1342 if (params.cpos + 1 >= params.tokens.size()) {
1343 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1344 return -1;
1345 }
Tao Bao0940fe12015-08-27 16:41:21 -07001346
Tao Baoc0e1c462017-02-01 10:20:10 -08001347 size_t offset;
1348 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1349 LOG(ERROR) << "invalid patch offset";
1350 return -1;
1351 }
Tao Bao0940fe12015-08-27 16:41:21 -07001352
Tao Baoc0e1c462017-02-01 10:20:10 -08001353 size_t len;
1354 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1355 LOG(ERROR) << "invalid patch len";
1356 return -1;
1357 }
Tao Bao0940fe12015-08-27 16:41:21 -07001358
Tao Baoc0e1c462017-02-01 10:20:10 -08001359 RangeSet tgt;
1360 size_t blocks = 0;
Tao Bao4a135082018-06-07 22:27:44 -07001361 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, false);
Tao Bao0940fe12015-08-27 16:41:21 -07001362
Tao Baoc0e1c462017-02-01 10:20:10 -08001363 if (status == -1) {
1364 LOG(ERROR) << "failed to read blocks for diff";
1365 return -1;
1366 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001367
Tao Baoc0e1c462017-02-01 10:20:10 -08001368 if (status == 0) {
1369 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001370 } else {
1371 params.target_verified = true;
1372 if (params.foundwrites) {
1373 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1374 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001375 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001376
Tao Baoc0e1c462017-02-01 10:20:10 -08001377 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001378 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001379 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001380 Value patch_value(
Tao Bao511d7592018-06-19 15:56:49 -07001381 Value::Type::BLOB,
1382 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001383
Tao Bao60a70af2017-03-26 14:03:52 -07001384 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001385 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao1e0941f2017-11-10 11:49:53 -08001386 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value,
Tao Bao60a70af2017-03-26 14:03:52 -07001387 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1388 std::placeholders::_2),
Tao Bao8b0b0f12018-04-19 21:02:13 -07001389 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001390 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001391 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001392 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001393 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001394 } else {
Tao Bao1e0941f2017-11-10 11:49:53 -08001395 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value, 0,
Tao Bao60a70af2017-03-26 14:03:52 -07001396 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
Tao Bao8b0b0f12018-04-19 21:02:13 -07001397 std::placeholders::_2)) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001398 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001399 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001400 return -1;
1401 }
1402 }
1403
1404 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001405 if (!writer.Finished()) {
Tao Baoa2cff952018-11-02 15:44:07 -07001406 LOG(ERROR) << "Failed to fully write target blocks (range sink underrun): Missing "
1407 << writer.AvailableSpace() << " bytes";
1408 failure_type = kPatchApplicationFailure;
1409 return -1;
Tao Baoc0e1c462017-02-01 10:20:10 -08001410 }
1411 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001412 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001413 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001414 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001415 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001416
Tao Baoc0e1c462017-02-01 10:20:10 -08001417 if (!params.freestash.empty()) {
1418 FreeStash(params.stashbase, params.freestash);
1419 params.freestash.clear();
1420 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001421
Tao Baobf5b77d2017-03-30 16:57:29 -07001422 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001423
Tao Baoc0e1c462017-02-01 10:20:10 -08001424 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001425}
1426
Tao Bao0940fe12015-08-27 16:41:21 -07001427static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001428 if (DEBUG_ERASE) {
1429 return PerformCommandZero(params);
1430 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001431
Tao Baobf5b77d2017-03-30 16:57:29 -07001432 struct stat sb;
1433 if (fstat(params.fd, &sb) == -1) {
1434 PLOG(ERROR) << "failed to fstat device to erase";
1435 return -1;
1436 }
1437
1438 if (!S_ISBLK(sb.st_mode)) {
1439 LOG(ERROR) << "not a block device; skipping erase";
1440 return -1;
1441 }
1442
1443 if (params.cpos >= params.tokens.size()) {
1444 LOG(ERROR) << "missing target blocks for erase";
1445 return -1;
1446 }
1447
1448 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001449 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001450
1451 if (params.canwrite) {
1452 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1453
Tao Bao43bfa6e2018-08-28 10:09:13 -07001454 for (const auto& [begin, end] : tgt) {
Yifan Hong363d6242019-01-04 11:14:19 -08001455 off64_t offset = static_cast<off64_t>(begin) * BLOCKSIZE;
1456 size_t size = (end - begin) * BLOCKSIZE;
1457 if (!discard_blocks(params.fd, offset, size, true /* force */)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001458 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001459 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001460 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001461 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001462
Tao Baobf5b77d2017-03-30 16:57:29 -07001463 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001464}
1465
Tao Bao91a649a2018-05-21 16:05:56 -07001466static int PerformCommandAbort(CommandParameters&) {
1467 LOG(INFO) << "Aborting as instructed";
1468 return -1;
1469}
1470
Tianjie Xu69ffa152018-08-01 16:40:00 -07001471// Computes the hash_tree bytes based on the parameters, checks if the root hash of the tree
1472// matches the expected hash and writes the result to the specified range on the block_device.
1473// Hash_tree computation arguments:
1474// hash_tree_ranges
1475// source_ranges
1476// hash_algorithm
1477// salt_hex
1478// root_hash
1479static int PerformCommandComputeHashTree(CommandParameters& params) {
1480 if (params.cpos + 5 != params.tokens.size()) {
1481 LOG(ERROR) << "Invaild arguments count in hash computation " << params.cmdline;
1482 return -1;
1483 }
1484
1485 // Expects the hash_tree data to be contiguous.
1486 RangeSet hash_tree_ranges = RangeSet::Parse(params.tokens[params.cpos++]);
1487 if (!hash_tree_ranges || hash_tree_ranges.size() != 1) {
1488 LOG(ERROR) << "Invalid hash tree ranges in " << params.cmdline;
1489 return -1;
1490 }
1491
1492 RangeSet source_ranges = RangeSet::Parse(params.tokens[params.cpos++]);
1493 if (!source_ranges) {
1494 LOG(ERROR) << "Invalid source ranges in " << params.cmdline;
1495 return -1;
1496 }
1497
1498 auto hash_function = HashTreeBuilder::HashFunction(params.tokens[params.cpos++]);
1499 if (hash_function == nullptr) {
1500 LOG(ERROR) << "Invalid hash algorithm in " << params.cmdline;
1501 return -1;
1502 }
1503
1504 std::vector<unsigned char> salt;
1505 std::string salt_hex = params.tokens[params.cpos++];
1506 if (salt_hex.empty() || !HashTreeBuilder::ParseBytesArrayFromString(salt_hex, &salt)) {
1507 LOG(ERROR) << "Failed to parse salt in " << params.cmdline;
1508 return -1;
1509 }
1510
1511 std::string expected_root_hash = params.tokens[params.cpos++];
1512 if (expected_root_hash.empty()) {
1513 LOG(ERROR) << "Invalid root hash in " << params.cmdline;
1514 return -1;
1515 }
1516
1517 // Starts the hash_tree computation.
1518 HashTreeBuilder builder(BLOCKSIZE, hash_function);
1519 if (!builder.Initialize(source_ranges.blocks() * BLOCKSIZE, salt)) {
1520 LOG(ERROR) << "Failed to initialize hash tree computation, source " << source_ranges.ToString()
1521 << ", salt " << salt_hex;
1522 return -1;
1523 }
1524
1525 // Iterates through every block in the source_ranges and updates the hash tree structure
1526 // accordingly.
Tao Bao43bfa6e2018-08-28 10:09:13 -07001527 for (const auto& [begin, end] : source_ranges) {
Tianjie Xu69ffa152018-08-01 16:40:00 -07001528 uint8_t buffer[BLOCKSIZE];
Tao Bao43bfa6e2018-08-28 10:09:13 -07001529 if (!check_lseek(params.fd, static_cast<off64_t>(begin) * BLOCKSIZE, SEEK_SET)) {
1530 PLOG(ERROR) << "Failed to seek to block: " << begin;
Tianjie Xu69ffa152018-08-01 16:40:00 -07001531 return -1;
1532 }
1533
Tao Bao43bfa6e2018-08-28 10:09:13 -07001534 for (size_t i = begin; i < end; i++) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001535 if (!android::base::ReadFully(params.fd, buffer, BLOCKSIZE)) {
1536 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
Tao Bao43bfa6e2018-08-28 10:09:13 -07001537 LOG(ERROR) << "Failed to read data in " << begin << ":" << end;
Tianjie Xu69ffa152018-08-01 16:40:00 -07001538 return -1;
1539 }
1540
1541 if (!builder.Update(reinterpret_cast<unsigned char*>(buffer), BLOCKSIZE)) {
1542 LOG(ERROR) << "Failed to update hash tree builder";
1543 return -1;
1544 }
1545 }
1546 }
1547
1548 if (!builder.BuildHashTree()) {
1549 LOG(ERROR) << "Failed to build hash tree";
1550 return -1;
1551 }
1552
1553 std::string root_hash_hex = HashTreeBuilder::BytesArrayToString(builder.root_hash());
1554 if (root_hash_hex != expected_root_hash) {
1555 LOG(ERROR) << "Root hash of the verity hash tree doesn't match the expected value. Expected: "
1556 << expected_root_hash << ", actual: " << root_hash_hex;
1557 return -1;
1558 }
1559
1560 uint64_t write_offset = static_cast<uint64_t>(hash_tree_ranges.GetBlockNumber(0)) * BLOCKSIZE;
1561 if (params.canwrite && !builder.WriteHashTreeToFd(params.fd, write_offset)) {
1562 LOG(ERROR) << "Failed to write hash tree to output";
1563 return -1;
1564 }
1565
1566 // TODO(xunchang) validates the written bytes
1567
1568 return 0;
1569}
1570
Tao Baoc3901232018-05-21 16:05:56 -07001571using CommandFunction = std::function<int(CommandParameters&)>;
Sami Tolvanen90221202014-12-09 16:39:47 +00001572
Tao Baoc3901232018-05-21 16:05:56 -07001573using CommandMap = std::unordered_map<Command::Type, CommandFunction>;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001574
Tianjie Xuc4447322017-03-06 14:44:59 -08001575static Value* PerformBlockImageUpdate(const char* name, State* state,
1576 const std::vector<std::unique_ptr<Expr>>& argv,
Tao Baoc3901232018-05-21 16:05:56 -07001577 const CommandMap& command_map, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001578 CommandParameters params = {};
Tao Baoc0299ed2018-05-24 00:16:35 -07001579 stash_map.clear();
Tao Bao33567772017-03-13 14:57:34 -07001580 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001581
Tao Bao33567772017-03-13 14:57:34 -07001582 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1583 if (state->is_retry) {
1584 is_retry = true;
1585 LOG(INFO) << "This update is a retry.";
1586 }
1587 if (argv.size() != 4) {
1588 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1589 argv.size());
1590 return StringValue("");
1591 }
1592
1593 std::vector<std::unique_ptr<Value>> args;
1594 if (!ReadValueArgs(state, argv, &args)) {
1595 return nullptr;
1596 }
1597
Tao Baoc3901232018-05-21 16:05:56 -07001598 // args:
1599 // - block device (or file) to modify in-place
1600 // - transfer list (blob)
1601 // - new data stream (filename within package.zip)
1602 // - patch stream (filename within package.zip, must be uncompressed)
Tao Baoc97edcb2017-03-31 01:18:13 -07001603 const std::unique_ptr<Value>& blockdev_filename = args[0];
1604 const std::unique_ptr<Value>& transfer_list_value = args[1];
1605 const std::unique_ptr<Value>& new_data_fn = args[2];
1606 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001607
Tao Bao511d7592018-06-19 15:56:49 -07001608 if (blockdev_filename->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001609 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1610 return StringValue("");
1611 }
Tao Bao511d7592018-06-19 15:56:49 -07001612 if (transfer_list_value->type != Value::Type::BLOB) {
Tao Bao33567772017-03-13 14:57:34 -07001613 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1614 return StringValue("");
1615 }
Tao Bao511d7592018-06-19 15:56:49 -07001616 if (new_data_fn->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001617 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1618 return StringValue("");
1619 }
Tao Bao511d7592018-06-19 15:56:49 -07001620 if (patch_data_fn->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001621 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1622 return StringValue("");
1623 }
1624
1625 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1626 if (ui == nullptr) {
1627 return StringValue("");
1628 }
1629
1630 FILE* cmd_pipe = ui->cmd_pipe;
1631 ZipArchiveHandle za = ui->package_zip;
1632
1633 if (cmd_pipe == nullptr || za == nullptr) {
1634 return StringValue("");
1635 }
1636
1637 ZipString path_data(patch_data_fn->data.c_str());
1638 ZipEntry patch_entry;
1639 if (FindEntry(za, path_data, &patch_entry) != 0) {
1640 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1641 return StringValue("");
1642 }
1643
1644 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1645 ZipString new_data(new_data_fn->data.c_str());
1646 ZipEntry new_entry;
1647 if (FindEntry(za, new_data, &new_entry) != 0) {
1648 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1649 return StringValue("");
1650 }
1651
Tianjie Xu22f11202018-08-27 10:50:31 -07001652 params.fd.reset(TEMP_FAILURE_RETRY(open(blockdev_filename->data.c_str(), O_RDWR)));
Tao Bao33567772017-03-13 14:57:34 -07001653 if (params.fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001654 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Bao33567772017-03-13 14:57:34 -07001655 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1656 return StringValue("");
1657 }
1658
Tao Bao864c6682018-05-07 11:38:25 -07001659 // Stash directory should be different for each partition to avoid conflicts when updating
1660 // multiple partitions at the same time, so we use the hash of the block device name as the base
1661 // directory.
1662 uint8_t digest[SHA_DIGEST_LENGTH];
1663 SHA1(reinterpret_cast<const uint8_t*>(blockdev_filename->data.data()),
1664 blockdev_filename->data.size(), digest);
1665 params.stashbase = print_sha1(digest);
1666
1667 // Possibly do return early on retry, by checking the marker. If the update on this partition has
1668 // been finished (but interrupted at a later point), there could be leftover on /cache that would
1669 // fail the no-op retry.
1670 std::string updated_marker = GetStashFileName(params.stashbase + ".UPDATED", "", "");
1671 if (is_retry) {
1672 struct stat sb;
1673 int result = stat(updated_marker.c_str(), &sb);
1674 if (result == 0) {
1675 LOG(INFO) << "Skipping already updated partition " << blockdev_filename->data
1676 << " based on marker";
1677 return StringValue("t");
1678 }
1679 } else {
1680 // Delete the obsolete marker if any.
1681 std::string err;
1682 if (!android::base::RemoveFileIfExists(updated_marker, &err)) {
1683 LOG(ERROR) << "Failed to remove partition updated marker " << updated_marker << ": " << err;
1684 return StringValue("");
1685 }
1686 }
1687
Tao Baoffede3e2018-06-07 09:56:19 -07001688 static constexpr size_t kTransferListHeaderLines = 4;
Tao Bao33567772017-03-13 14:57:34 -07001689 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baoffede3e2018-06-07 09:56:19 -07001690 if (lines.size() < kTransferListHeaderLines) {
1691 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]",
Tao Bao33567772017-03-13 14:57:34 -07001692 lines.size());
1693 return StringValue("");
1694 }
1695
1696 // First line in transfer list is the version number.
1697 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1698 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1699 return StringValue("");
1700 }
1701
1702 LOG(INFO) << "blockimg version is " << params.version;
1703
1704 // Second line in transfer list is the total number of blocks we expect to write.
1705 size_t total_blocks;
1706 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001707 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]", lines[1].c_str());
Tao Bao33567772017-03-13 14:57:34 -07001708 return StringValue("");
1709 }
1710
1711 if (total_blocks == 0) {
1712 return StringValue("t");
1713 }
1714
Tao Bao33567772017-03-13 14:57:34 -07001715 // Third line is how many stash entries are needed simultaneously.
1716 LOG(INFO) << "maximum stash entries " << lines[2];
1717
1718 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1719 size_t stash_max_blocks;
1720 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001721 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]",
Tao Bao33567772017-03-13 14:57:34 -07001722 lines[3].c_str());
1723 return StringValue("");
1724 }
1725
Tao Bao864c6682018-05-07 11:38:25 -07001726 int res = CreateStash(state, stash_max_blocks, params.stashbase);
Tao Bao33567772017-03-13 14:57:34 -07001727 if (res == -1) {
1728 return StringValue("");
1729 }
Tao Bao33567772017-03-13 14:57:34 -07001730 params.createdstash = res;
1731
Tao Bao0a883c12018-06-18 12:49:06 -07001732 // Set up the new data writer.
1733 if (params.canwrite) {
1734 params.nti.za = za;
1735 params.nti.entry = new_entry;
1736 params.nti.brotli_compressed = android::base::EndsWith(new_data_fn->data, ".br");
1737 if (params.nti.brotli_compressed) {
1738 // Initialize brotli decoder state.
1739 params.nti.brotli_decoder_state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
1740 }
1741 params.nti.receiver_available = true;
1742
1743 pthread_mutex_init(&params.nti.mu, nullptr);
1744 pthread_cond_init(&params.nti.cv, nullptr);
1745 pthread_attr_t attr;
1746 pthread_attr_init(&attr);
1747 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1748
1749 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1750 if (error != 0) {
1751 LOG(ERROR) << "pthread_create failed: " << strerror(error);
1752 return StringValue("");
1753 }
1754 }
1755
Tao Bao26efb0a2018-05-21 14:59:55 -07001756 // When performing an update, save the index and cmdline of the current command into the
1757 // last_command_file.
Tianjie Xu284752e2017-12-05 11:04:17 -08001758 // Upon resuming an update, read the saved index first; then
1759 // 1. In verification mode, check if the 'move' or 'diff' commands before the saved index has
1760 // the expected target blocks already. If not, these commands cannot be skipped and we need
1761 // to attempt to execute them again. Therefore, we will delete the last_command_file so that
1762 // the update will resume from the start of the transfer list.
1763 // 2. In update mode, skip all commands before the saved index. Therefore, we can avoid deleting
1764 // stashes with duplicate id unintentionally (b/69858743); and also speed up the update.
1765 // If an update succeeds or is unresumable, delete the last_command_file.
Tao Bao26efb0a2018-05-21 14:59:55 -07001766 bool skip_executed_command = true;
1767 size_t saved_last_command_index;
Tianjie Xu284752e2017-12-05 11:04:17 -08001768 if (!ParseLastCommandFile(&saved_last_command_index)) {
1769 DeleteLastCommandFile();
Tao Bao26efb0a2018-05-21 14:59:55 -07001770 // We failed to parse the last command. Disallow skipping executed commands.
1771 skip_executed_command = false;
Tianjie Xu284752e2017-12-05 11:04:17 -08001772 }
1773
Tao Bao33567772017-03-13 14:57:34 -07001774 int rc = -1;
1775
1776 // Subsequent lines are all individual transfer commands
Tao Baoab207062018-05-21 14:48:49 -07001777 for (size_t i = kTransferListHeaderLines; i < lines.size(); i++) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001778 const std::string& line = lines[i];
Tao Bao33567772017-03-13 14:57:34 -07001779 if (line.empty()) continue;
1780
Tao Bao26efb0a2018-05-21 14:59:55 -07001781 size_t cmdindex = i - kTransferListHeaderLines;
Tao Bao33567772017-03-13 14:57:34 -07001782 params.tokens = android::base::Split(line, " ");
1783 params.cpos = 0;
Tao Baoc3901232018-05-21 16:05:56 -07001784 params.cmdname = params.tokens[params.cpos++];
1785 params.cmdline = line;
Tianjie Xu284752e2017-12-05 11:04:17 -08001786 params.target_verified = false;
Tao Bao33567772017-03-13 14:57:34 -07001787
Tao Baoc3901232018-05-21 16:05:56 -07001788 Command::Type cmd_type = Command::ParseType(params.cmdname);
1789 if (cmd_type == Command::Type::LAST) {
Tao Bao33567772017-03-13 14:57:34 -07001790 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1791 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001792 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001793
Tao Baoc3901232018-05-21 16:05:56 -07001794 const CommandFunction& performer = command_map.at(cmd_type);
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001795
Tianjie Xuc2420842018-02-27 17:05:39 -08001796 // Skip the command if we explicitly set the corresponding function pointer to nullptr, e.g.
1797 // "erase" during block_image_verify.
Tao Baoc3901232018-05-21 16:05:56 -07001798 if (performer == nullptr) {
Tianjie Xuc2420842018-02-27 17:05:39 -08001799 LOG(DEBUG) << "skip executing command [" << line << "]";
1800 continue;
Tianjie Xu284752e2017-12-05 11:04:17 -08001801 }
1802
Tao Bao98f875e2018-05-07 15:03:30 -07001803 // Skip all commands before the saved last command index when resuming an update, except for
1804 // "new" command. Because new commands read in the data sequentially.
Tao Bao26efb0a2018-05-21 14:59:55 -07001805 if (params.canwrite && skip_executed_command && cmdindex <= saved_last_command_index &&
Tao Baoc3901232018-05-21 16:05:56 -07001806 cmd_type != Command::Type::NEW) {
Tao Bao26efb0a2018-05-21 14:59:55 -07001807 LOG(INFO) << "Skipping already executed command: " << cmdindex
Tianjie Xu284752e2017-12-05 11:04:17 -08001808 << ", last executed command for previous update: " << saved_last_command_index;
1809 continue;
1810 }
1811
Tao Baoc3901232018-05-21 16:05:56 -07001812 if (performer(params) == -1) {
Tao Bao33567772017-03-13 14:57:34 -07001813 LOG(ERROR) << "failed to execute command [" << line << "]";
Tianjie Xu69ffa152018-08-01 16:40:00 -07001814 if (cmd_type == Command::Type::COMPUTE_HASH_TREE && failure_type == kNoCause) {
1815 failure_type = kHashTreeComputationFailure;
1816 }
Tao Bao33567772017-03-13 14:57:34 -07001817 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001818 }
1819
Tao Bao26efb0a2018-05-21 14:59:55 -07001820 // In verify mode, check if the commands before the saved last_command_index have been executed
1821 // correctly. If some target blocks have unexpected contents, delete the last command file so
1822 // that we will resume the update from the first command in the transfer list.
1823 if (!params.canwrite && skip_executed_command && cmdindex <= saved_last_command_index) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001824 // TODO(xunchang) check that the cmdline of the saved index is correct.
Tao Baoc3901232018-05-21 16:05:56 -07001825 if ((cmd_type == Command::Type::MOVE || cmd_type == Command::Type::BSDIFF ||
1826 cmd_type == Command::Type::IMGDIFF) &&
Tianjie Xu284752e2017-12-05 11:04:17 -08001827 !params.target_verified) {
1828 LOG(WARNING) << "Previously executed command " << saved_last_command_index << ": "
1829 << params.cmdline << " doesn't produce expected target blocks.";
Tao Bao26efb0a2018-05-21 14:59:55 -07001830 skip_executed_command = false;
Tianjie Xu284752e2017-12-05 11:04:17 -08001831 DeleteLastCommandFile();
1832 }
1833 }
Tao Baoc3901232018-05-21 16:05:56 -07001834
Sami Tolvanen90221202014-12-09 16:39:47 +00001835 if (params.canwrite) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001836 if (fsync(params.fd) == -1) {
1837 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001838 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001839 goto pbiudone;
1840 }
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001841
Tao Bao26efb0a2018-05-21 14:59:55 -07001842 if (!UpdateLastCommandIndex(cmdindex, params.cmdline)) {
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001843 LOG(WARNING) << "Failed to update the last command file.";
1844 }
1845
Tao Bao33567772017-03-13 14:57:34 -07001846 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1847 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001848 }
Tao Bao33567772017-03-13 14:57:34 -07001849 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001850
Tao Bao33567772017-03-13 14:57:34 -07001851 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001852
Tao Bao33567772017-03-13 14:57:34 -07001853pbiudone:
Tianjie Xu5450c842017-10-18 13:15:21 -07001854 if (params.canwrite) {
1855 pthread_mutex_lock(&params.nti.mu);
1856 if (params.nti.receiver_available) {
1857 LOG(WARNING) << "new data receiver is still available after executing all commands.";
1858 }
1859 params.nti.receiver_available = false;
1860 pthread_cond_broadcast(&params.nti.cv);
1861 pthread_mutex_unlock(&params.nti.mu);
1862 int ret = pthread_join(params.thread, nullptr);
1863 if (ret != 0) {
1864 LOG(WARNING) << "pthread join returned with " << strerror(ret);
1865 }
1866
1867 if (rc == 0) {
1868 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1869 LOG(INFO) << "stashed " << params.stashed << " blocks";
1870 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1871
1872 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1873 if (partition != nullptr && *(partition + 1) != 0) {
1874 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1875 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1876 fflush(cmd_pipe);
1877 }
1878 // Delete stash only after successfully completing the update, as it may contain blocks needed
1879 // to complete the update later.
1880 DeleteStash(params.stashbase);
Tianjie Xu284752e2017-12-05 11:04:17 -08001881 DeleteLastCommandFile();
Tao Bao864c6682018-05-07 11:38:25 -07001882
1883 // Create a marker on /cache partition, which allows skipping the update on this partition on
1884 // retry. The marker will be removed once booting into normal boot, or before starting next
1885 // fresh install.
1886 if (!SetPartitionUpdatedMarker(updated_marker)) {
1887 LOG(WARNING) << "Failed to set updated marker; continuing";
1888 }
Tianjie Xu5450c842017-10-18 13:15:21 -07001889 }
1890
1891 pthread_mutex_destroy(&params.nti.mu);
1892 pthread_cond_destroy(&params.nti.cv);
1893 } else if (rc == 0) {
1894 LOG(INFO) << "verified partition contents; update may be resumed";
1895 }
1896
Tianjie Xu22f11202018-08-27 10:50:31 -07001897 if (fsync(params.fd) == -1) {
1898 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Bao33567772017-03-13 14:57:34 -07001899 PLOG(ERROR) << "fsync failed";
1900 }
1901 // params.fd will be automatically closed because it's a unique_fd.
1902
Tianjie Xu107a34f2017-06-29 17:04:21 -07001903 if (params.nti.brotli_decoder_state != nullptr) {
1904 BrotliDecoderDestroyInstance(params.nti.brotli_decoder_state);
1905 }
1906
Tianjie Xu284752e2017-12-05 11:04:17 -08001907 // Delete the last command file if the update cannot be resumed.
1908 if (params.isunresumable) {
1909 DeleteLastCommandFile();
1910 }
1911
Tao Bao33567772017-03-13 14:57:34 -07001912 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1913 // created the stash.
1914 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1915 DeleteStash(params.stashbase);
1916 }
1917
1918 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1919 state->cause_code = failure_type;
1920 }
1921
1922 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001923}
1924
Tao Bao33567772017-03-13 14:57:34 -07001925/**
1926 * The transfer list is a text file containing commands to transfer data from one place to another
1927 * on the target partition. We parse it and execute the commands in order:
1928 *
1929 * zero [rangeset]
1930 * - Fill the indicated blocks with zeros.
1931 *
1932 * new [rangeset]
1933 * - Fill the blocks with data read from the new_data file.
1934 *
1935 * erase [rangeset]
1936 * - Mark the given blocks as empty.
1937 *
1938 * move <...>
1939 * bsdiff <patchstart> <patchlen> <...>
1940 * imgdiff <patchstart> <patchlen> <...>
1941 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1942 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1943 *
1944 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1945 *
1946 * stash <stash_id> <src_range>
1947 * - Load the given source range and stash the data in the given slot of the stash table.
1948 *
1949 * free <stash_id>
1950 * - Free the given stash data.
1951 *
1952 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1953 * a patch or move) after it has been written.
1954 *
1955 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1956 * in a move/bsdiff/imgdiff command.
1957 *
1958 * Within one command the source and target ranges may overlap so in general we need to read the
1959 * entire source into memory before writing anything to the target blocks.
1960 *
1961 * All the patch data is concatenated into one patch_data file in the update package. It must be
1962 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1963 * already compressed, we lose very little by not compressing their concatenation.)
1964 *
1965 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1966 * additional hashes before the range parameters, which are used to check if the command has already
1967 * been completed and verify the integrity of the source data.
1968 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001969Value* BlockImageVerifyFn(const char* name, State* state,
1970 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc3901232018-05-21 16:05:56 -07001971 // Commands which are not allowed are set to nullptr to skip them completely.
1972 const CommandMap command_map{
1973 // clang-format off
Tianjie Xu69ffa152018-08-01 16:40:00 -07001974 { Command::Type::ABORT, PerformCommandAbort },
1975 { Command::Type::BSDIFF, PerformCommandDiff },
1976 { Command::Type::COMPUTE_HASH_TREE, PerformCommandComputeHashTree },
1977 { Command::Type::ERASE, nullptr },
1978 { Command::Type::FREE, PerformCommandFree },
1979 { Command::Type::IMGDIFF, PerformCommandDiff },
1980 { Command::Type::MOVE, PerformCommandMove },
1981 { Command::Type::NEW, nullptr },
1982 { Command::Type::STASH, PerformCommandStash },
1983 { Command::Type::ZERO, nullptr },
Tao Baoc3901232018-05-21 16:05:56 -07001984 // clang-format on
1985 };
1986 CHECK_EQ(static_cast<size_t>(Command::Type::LAST), command_map.size());
Sami Tolvanen90221202014-12-09 16:39:47 +00001987
Tao Baoc3901232018-05-21 16:05:56 -07001988 // Perform a dry run without writing to test if an update can proceed.
1989 return PerformBlockImageUpdate(name, state, argv, command_map, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001990}
1991
Tianjie Xuc4447322017-03-06 14:44:59 -08001992Value* BlockImageUpdateFn(const char* name, State* state,
1993 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc3901232018-05-21 16:05:56 -07001994 const CommandMap command_map{
1995 // clang-format off
Tianjie Xu69ffa152018-08-01 16:40:00 -07001996 { Command::Type::ABORT, PerformCommandAbort },
1997 { Command::Type::BSDIFF, PerformCommandDiff },
1998 { Command::Type::COMPUTE_HASH_TREE, PerformCommandComputeHashTree },
1999 { Command::Type::ERASE, PerformCommandErase },
2000 { Command::Type::FREE, PerformCommandFree },
2001 { Command::Type::IMGDIFF, PerformCommandDiff },
2002 { Command::Type::MOVE, PerformCommandMove },
2003 { Command::Type::NEW, PerformCommandNew },
2004 { Command::Type::STASH, PerformCommandStash },
2005 { Command::Type::ZERO, PerformCommandZero },
Tao Baoc3901232018-05-21 16:05:56 -07002006 // clang-format on
2007 };
2008 CHECK_EQ(static_cast<size_t>(Command::Type::LAST), command_map.size());
Sami Tolvanen90221202014-12-09 16:39:47 +00002009
Tao Baoc3901232018-05-21 16:05:56 -07002010 return PerformBlockImageUpdate(name, state, argv, command_map, false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002011}
2012
Tianjie Xuc4447322017-03-06 14:44:59 -08002013Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002014 if (argv.size() != 2) {
2015 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
2016 return StringValue("");
2017 }
2018
2019 std::vector<std::unique_ptr<Value>> args;
2020 if (!ReadValueArgs(state, argv, &args)) {
2021 return nullptr;
2022 }
2023
2024 const std::unique_ptr<Value>& blockdev_filename = args[0];
2025 const std::unique_ptr<Value>& ranges = args[1];
2026
Tao Bao511d7592018-06-19 15:56:49 -07002027 if (blockdev_filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002028 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
2029 return StringValue("");
2030 }
Tao Bao511d7592018-06-19 15:56:49 -07002031 if (ranges->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002032 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2033 return StringValue("");
2034 }
2035
Tianjie Xu22f11202018-08-27 10:50:31 -07002036 android::base::unique_fd fd(open(blockdev_filename->data.c_str(), O_RDWR));
Tao Baoc97edcb2017-03-31 01:18:13 -07002037 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002038 CauseCode cause_code = errno == EIO ? kEioFailure : kFileOpenFailure;
2039 ErrorAbort(state, cause_code, "open \"%s\" failed: %s", blockdev_filename->data.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002040 strerror(errno));
2041 return StringValue("");
2042 }
2043
2044 RangeSet rs = RangeSet::Parse(ranges->data);
Tao Bao67983152017-11-04 00:08:08 -07002045 CHECK(static_cast<bool>(rs));
Tao Baoc97edcb2017-03-31 01:18:13 -07002046
2047 SHA_CTX ctx;
2048 SHA1_Init(&ctx);
2049
2050 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao43bfa6e2018-08-28 10:09:13 -07002051 for (const auto& [begin, end] : rs) {
2052 if (!check_lseek(fd, static_cast<off64_t>(begin) * BLOCKSIZE, SEEK_SET)) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002053 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
2054 strerror(errno));
2055 return StringValue("");
2056 }
2057
Tao Bao43bfa6e2018-08-28 10:09:13 -07002058 for (size_t j = begin; j < end; ++j) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002059 if (!android::base::ReadFully(fd, buffer.data(), BLOCKSIZE)) {
2060 CauseCode cause_code = errno == EIO ? kEioFailure : kFreadFailure;
2061 ErrorAbort(state, cause_code, "failed to read %s: %s", blockdev_filename->data.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002062 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002063 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002064 }
2065
2066 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08002067 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002068 }
2069 uint8_t digest[SHA_DIGEST_LENGTH];
2070 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08002071
Tao Baoc97edcb2017-03-31 01:18:13 -07002072 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002073}
2074
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002075// This function checks if a device has been remounted R/W prior to an incremental
2076// OTA update. This is an common cause of update abortion. The function reads the
2077// 1st block of each partition and check for mounting time/count. It return string "t"
2078// if executes successfully and an empty string otherwise.
2079
Tianjie Xuc4447322017-03-06 14:44:59 -08002080Value* CheckFirstBlockFn(const char* name, State* state,
2081 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002082 if (argv.size() != 1) {
2083 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
2084 argv.size());
2085 return StringValue("");
2086 }
Tianjie Xuc4447322017-03-06 14:44:59 -08002087
Tao Baoc97edcb2017-03-31 01:18:13 -07002088 std::vector<std::unique_ptr<Value>> args;
2089 if (!ReadValueArgs(state, argv, &args)) {
2090 return nullptr;
2091 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002092
Tao Baoc97edcb2017-03-31 01:18:13 -07002093 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07002094
Tao Bao511d7592018-06-19 15:56:49 -07002095 if (arg_filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002096 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2097 return StringValue("");
2098 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002099
Tianjie Xu22f11202018-08-27 10:50:31 -07002100 android::base::unique_fd fd(open(arg_filename->data.c_str(), O_RDONLY));
Tao Baoc97edcb2017-03-31 01:18:13 -07002101 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002102 CauseCode cause_code = errno == EIO ? kEioFailure : kFileOpenFailure;
2103 ErrorAbort(state, cause_code, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002104 strerror(errno));
2105 return StringValue("");
2106 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002107
Tao Baobf5b77d2017-03-30 16:57:29 -07002108 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07002109 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002110
Tao Baode3bbb82018-05-30 16:14:14 -07002111 if (ReadBlocks(blk0, &block0_buffer, fd) == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07002112 CauseCode cause_code = errno == EIO ? kEioFailure : kFreadFailure;
2113 ErrorAbort(state, cause_code, "failed to read %s: %s", arg_filename->data.c_str(),
Tao Baoc97edcb2017-03-31 01:18:13 -07002114 strerror(errno));
2115 return StringValue("");
2116 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002117
Tao Baoc97edcb2017-03-31 01:18:13 -07002118 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
2119 // Super block starts from block 0, offset 0x400
2120 // 0x2C: len32 Mount time
2121 // 0x30: len32 Write time
2122 // 0x34: len16 Number of mounts since the last fsck
2123 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002124
Tao Baoc97edcb2017-03-31 01:18:13 -07002125 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
2126 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002127
Tao Baoc97edcb2017-03-31 01:18:13 -07002128 if (mount_count > 0) {
2129 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
2130 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
2131 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002132
Tao Baoc97edcb2017-03-31 01:18:13 -07002133 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002134}
2135
Tianjie Xuc4447322017-03-06 14:44:59 -08002136Value* BlockImageRecoverFn(const char* name, State* state,
2137 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002138 if (argv.size() != 2) {
2139 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
2140 argv.size());
2141 return StringValue("");
2142 }
2143
2144 std::vector<std::unique_ptr<Value>> args;
2145 if (!ReadValueArgs(state, argv, &args)) {
2146 return nullptr;
2147 }
2148
2149 const std::unique_ptr<Value>& filename = args[0];
2150 const std::unique_ptr<Value>& ranges = args[1];
2151
Tao Bao511d7592018-06-19 15:56:49 -07002152 if (filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002153 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2154 return StringValue("");
2155 }
Tao Bao511d7592018-06-19 15:56:49 -07002156 if (ranges->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002157 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2158 return StringValue("");
2159 }
Tao Bao67983152017-11-04 00:08:08 -07002160 RangeSet rs = RangeSet::Parse(ranges->data);
2161 if (!rs) {
2162 ErrorAbort(state, kArgsParsingFailure, "failed to parse ranges: %s", ranges->data.c_str());
2163 return StringValue("");
2164 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002165
2166 // Output notice to log when recover is attempted
2167 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
2168
2169 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
2170 fec::io fh(filename->data, O_RDWR);
2171
2172 if (!fh) {
2173 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
2174 strerror(errno));
2175 return StringValue("");
2176 }
2177
2178 if (!fh.has_ecc() || !fh.has_verity()) {
2179 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
2180 return StringValue("");
2181 }
2182
2183 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07002184 if (!fh.get_status(status)) {
2185 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
2186 return StringValue("");
2187 }
2188
Tao Baoc97edcb2017-03-31 01:18:13 -07002189 uint8_t buffer[BLOCKSIZE];
Tao Bao43bfa6e2018-08-28 10:09:13 -07002190 for (const auto& [begin, end] : rs) {
2191 for (size_t j = begin; j < end; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002192 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07002193 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002194 continue;
2195 }
2196
Tao Baobf5b77d2017-03-30 16:57:29 -07002197 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002198 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
2199 filename->data.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002200 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002201 }
2202
2203 // If we want to be able to recover from a situation where rewriting a corrected
2204 // block doesn't guarantee the same data will be returned when re-read later, we
2205 // can save a copy of corrected blocks to /cache. Note:
2206 //
2207 // 1. Maximum space required from /cache is the same as the maximum number of
2208 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
2209 // this would be ~16 MiB, for example.
2210 //
2211 // 2. To find out if this block was corrupted, call fec_get_status after each
2212 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08002213 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002214 }
2215 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
2216 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002217}
2218
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002219void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07002220 RegisterFunction("block_image_verify", BlockImageVerifyFn);
2221 RegisterFunction("block_image_update", BlockImageUpdateFn);
2222 RegisterFunction("block_image_recover", BlockImageRecoverFn);
2223 RegisterFunction("check_first_block", CheckFirstBlockFn);
2224 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002225}