1 /*
2  * Copyright (C) 2016 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 <stdio.h>
18 #include <stdlib.h>
19 #include <sys/stat.h>
20 #include <sys/types.h>
21 #include <unistd.h>
22 
23 #include <algorithm>
24 #include <memory>
25 #include <string>
26 #include <string_view>
27 #include <unordered_map>
28 #include <vector>
29 
30 #include <android-base/file.h>
31 #include <android-base/logging.h>
32 #include <android-base/parseint.h>
33 #include <android-base/properties.h>
34 #include <android-base/stringprintf.h>
35 #include <android-base/strings.h>
36 #include <bootloader_message/bootloader_message.h>
37 #include <brotli/encode.h>
38 #include <bsdiff/bsdiff.h>
39 #include <gtest/gtest.h>
40 #include <verity/hash_tree_builder.h>
41 #include <ziparchive/zip_archive.h>
42 #include <ziparchive/zip_writer.h>
43 
44 #include "applypatch/applypatch.h"
45 #include "common/test_constants.h"
46 #include "edify/expr.h"
47 #include "otautil/error_code.h"
48 #include "otautil/paths.h"
49 #include "otautil/print_sha1.h"
50 #include "otautil/sysutil.h"
51 #include "private/commands.h"
52 #include "updater/blockimg.h"
53 #include "updater/install.h"
54 #include "updater/updater.h"
55 #include "updater/updater_runtime.h"
56 
57 using namespace std::string_literals;
58 
59 using PackageEntries = std::unordered_map<std::string, std::string>;
60 
expect(const char * expected,const std::string & expr_str,CauseCode cause_code,Updater * updater)61 static void expect(const char* expected, const std::string& expr_str, CauseCode cause_code,
62                    Updater* updater) {
63   std::unique_ptr<Expr> e;
64   int error_count = 0;
65   ASSERT_EQ(0, ParseString(expr_str, &e, &error_count));
66   ASSERT_EQ(0, error_count);
67 
68   State state(expr_str, updater);
69 
70   std::string result;
71   bool status = Evaluate(&state, e, &result);
72 
73   if (expected == nullptr) {
74     ASSERT_FALSE(status);
75   } else {
76     ASSERT_TRUE(status) << "Evaluate() finished with error message: " << state.errmsg;
77     ASSERT_STREQ(expected, result.c_str());
78   }
79 
80   // Error code is set in updater/updater.cpp only, by parsing State.errmsg.
81   ASSERT_EQ(kNoError, state.error_code);
82 
83   // Cause code should always be available.
84   ASSERT_EQ(cause_code, state.cause_code);
85 }
86 
expect(const char * expected,const std::string & expr_str,CauseCode cause_code)87 static void expect(const char* expected, const std::string& expr_str, CauseCode cause_code) {
88   Updater updater(std::make_unique<UpdaterRuntime>(nullptr));
89   expect(expected, expr_str, cause_code, &updater);
90 }
91 
BuildUpdatePackage(const PackageEntries & entries,int fd)92 static void BuildUpdatePackage(const PackageEntries& entries, int fd) {
93   FILE* zip_file_ptr = fdopen(fd, "wb");
94   ZipWriter zip_writer(zip_file_ptr);
95 
96   for (const auto& entry : entries) {
97     // All the entries are written as STORED.
98     ASSERT_EQ(0, zip_writer.StartEntry(entry.first.c_str(), 0));
99     if (!entry.second.empty()) {
100       ASSERT_EQ(0, zip_writer.WriteBytes(entry.second.data(), entry.second.size()));
101     }
102     ASSERT_EQ(0, zip_writer.FinishEntry());
103   }
104 
105   ASSERT_EQ(0, zip_writer.Finish());
106   ASSERT_EQ(0, fclose(zip_file_ptr));
107 }
108 
GetSha1(std::string_view content)109 static std::string GetSha1(std::string_view content) {
110   uint8_t digest[SHA_DIGEST_LENGTH];
111   SHA1(reinterpret_cast<const uint8_t*>(content.data()), content.size(), digest);
112   return print_sha1(digest);
113 }
114 
BlobToString(const char * name,State * state,const std::vector<std::unique_ptr<Expr>> & argv)115 static Value* BlobToString(const char* name, State* state,
116                            const std::vector<std::unique_ptr<Expr>>& argv) {
117   if (argv.size() != 1) {
118     return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size());
119   }
120 
121   std::vector<std::unique_ptr<Value>> args;
122   if (!ReadValueArgs(state, argv, &args)) {
123     return nullptr;
124   }
125 
126   if (args[0]->type != Value::Type::BLOB) {
127     return ErrorAbort(state, kArgsParsingFailure, "%s() expects a BLOB argument", name);
128   }
129 
130   args[0]->type = Value::Type::STRING;
131   return args[0].release();
132 }
133 
134 class UpdaterTestBase {
135  protected:
UpdaterTestBase()136   UpdaterTestBase() : updater_(std::make_unique<UpdaterRuntime>(nullptr)) {}
137 
SetUp()138   void SetUp() {
139     RegisterBuiltins();
140     RegisterInstallFunctions();
141     RegisterBlockImageFunctions();
142 
143     // Each test is run in a separate process (isolated mode). Shared temporary files won't cause
144     // conflicts.
145     Paths::Get().set_cache_temp_source(temp_saved_source_.path);
146     Paths::Get().set_last_command_file(temp_last_command_.path);
147     Paths::Get().set_stash_directory_base(temp_stash_base_.path);
148 
149     last_command_file_ = temp_last_command_.path;
150     image_file_ = image_temp_file_.path;
151   }
152 
TearDown()153   void TearDown() {
154     // Clean up the last_command_file if any.
155     ASSERT_TRUE(android::base::RemoveFileIfExists(last_command_file_));
156 
157     // Clear partition updated marker if any.
158     std::string updated_marker{ temp_stash_base_.path };
159     updated_marker += "/" + GetSha1(image_temp_file_.path) + ".UPDATED";
160     ASSERT_TRUE(android::base::RemoveFileIfExists(updated_marker));
161   }
162 
RunBlockImageUpdate(bool is_verify,PackageEntries entries,const std::string & image_file,const std::string & result,CauseCode cause_code=kNoCause)163   void RunBlockImageUpdate(bool is_verify, PackageEntries entries, const std::string& image_file,
164                            const std::string& result, CauseCode cause_code = kNoCause) {
165     CHECK(entries.find("transfer_list") != entries.end());
166     std::string new_data =
167         entries.find("new_data.br") != entries.end() ? "new_data.br" : "new_data";
168     std::string script = is_verify ? "block_image_verify" : "block_image_update";
169     script += R"((")" + image_file + R"(", package_extract_file("transfer_list"), ")" + new_data +
170               R"(", "patch_data"))";
171     entries.emplace(Updater::SCRIPT_NAME, script);
172 
173     // Build the update package.
174     TemporaryFile zip_file;
175     BuildUpdatePackage(entries, zip_file.release());
176 
177     // Set up the handler, command_pipe, patch offset & length.
178     TemporaryFile temp_pipe;
179     ASSERT_TRUE(updater_.Init(temp_pipe.release(), zip_file.path, false));
180     ASSERT_TRUE(updater_.RunUpdate());
181     ASSERT_EQ(result, updater_.GetResult());
182 
183     // Parse the cause code written to the command pipe.
184     int received_cause_code = kNoCause;
185     std::string pipe_content;
186     ASSERT_TRUE(android::base::ReadFileToString(temp_pipe.path, &pipe_content));
187     auto lines = android::base::Split(pipe_content, "\n");
188     for (std::string_view line : lines) {
189       if (android::base::ConsumePrefix(&line, "log cause: ")) {
190         ASSERT_TRUE(android::base::ParseInt(line.data(), &received_cause_code));
191       }
192     }
193     ASSERT_EQ(cause_code, received_cause_code);
194   }
195 
196   TemporaryFile temp_saved_source_;
197   TemporaryDir temp_stash_base_;
198   std::string last_command_file_;
199   std::string image_file_;
200 
201   Updater updater_;
202 
203  private:
204   TemporaryFile temp_last_command_;
205   TemporaryFile image_temp_file_;
206 };
207 
208 class UpdaterTest : public UpdaterTestBase, public ::testing::Test {
209  protected:
SetUp()210   void SetUp() override {
211     UpdaterTestBase::SetUp();
212 
213     RegisterFunction("blob_to_string", BlobToString);
214     // Enable a special command "abort" to simulate interruption.
215     Command::abort_allowed_ = true;
216   }
217 
TearDown()218   void TearDown() override {
219     UpdaterTestBase::TearDown();
220   }
221 
SetUpdaterCmdPipe(int fd)222   void SetUpdaterCmdPipe(int fd) {
223     FILE* cmd_pipe = fdopen(fd, "w");
224     ASSERT_NE(nullptr, cmd_pipe);
225     updater_.cmd_pipe_.reset(cmd_pipe);
226   }
227 
SetUpdaterOtaPackageHandle(ZipArchiveHandle handle)228   void SetUpdaterOtaPackageHandle(ZipArchiveHandle handle) {
229     updater_.package_handle_ = handle;
230   }
231 
FlushUpdaterCommandPipe() const232   void FlushUpdaterCommandPipe() const {
233     fflush(updater_.cmd_pipe_.get());
234   }
235 };
236 
TEST_F(UpdaterTest,getprop)237 TEST_F(UpdaterTest, getprop) {
238     expect(android::base::GetProperty("ro.product.device", "").c_str(),
239            "getprop(\"ro.product.device\")",
240            kNoCause);
241 
242     expect(android::base::GetProperty("ro.build.fingerprint", "").c_str(),
243            "getprop(\"ro.build.fingerprint\")",
244            kNoCause);
245 
246     // getprop() accepts only one parameter.
247     expect(nullptr, "getprop()", kArgsParsingFailure);
248     expect(nullptr, "getprop(\"arg1\", \"arg2\")", kArgsParsingFailure);
249 }
250 
TEST_F(UpdaterTest,patch_partition_check)251 TEST_F(UpdaterTest, patch_partition_check) {
252   // Zero argument is not valid.
253   expect(nullptr, "patch_partition_check()", kArgsParsingFailure);
254 
255   std::string source_file = from_testdata_base("boot.img");
256   std::string source_content;
257   ASSERT_TRUE(android::base::ReadFileToString(source_file, &source_content));
258   size_t source_size = source_content.size();
259   std::string source_hash = GetSha1(source_content);
260   Partition source(source_file, source_size, source_hash);
261 
262   std::string target_file = from_testdata_base("recovery.img");
263   std::string target_content;
264   ASSERT_TRUE(android::base::ReadFileToString(target_file, &target_content));
265   size_t target_size = target_content.size();
266   std::string target_hash = GetSha1(target_content);
267   Partition target(target_file, target_size, target_hash);
268 
269   // One argument is not valid.
270   expect(nullptr, "patch_partition_check(\"" + source.ToString() + "\")", kArgsParsingFailure);
271   expect(nullptr, "patch_partition_check(\"" + target.ToString() + "\")", kArgsParsingFailure);
272 
273   // Both of the source and target have the desired checksum.
274   std::string cmd =
275       "patch_partition_check(\"" + source.ToString() + "\", \"" + target.ToString() + "\")";
276   expect("t", cmd, kNoCause);
277 
278   // Only source partition has the desired checksum.
279   Partition bad_target(target_file, target_size - 1, target_hash);
280   cmd = "patch_partition_check(\"" + source.ToString() + "\", \"" + bad_target.ToString() + "\")";
281   expect("t", cmd, kNoCause);
282 
283   // Only target partition has the desired checksum.
284   Partition bad_source(source_file, source_size + 1, source_hash);
285   cmd = "patch_partition_check(\"" + bad_source.ToString() + "\", \"" + target.ToString() + "\")";
286   expect("t", cmd, kNoCause);
287 
288   // Neither of the source or target has the desired checksum.
289   cmd =
290       "patch_partition_check(\"" + bad_source.ToString() + "\", \"" + bad_target.ToString() + "\")";
291   expect("", cmd, kNoCause);
292 }
293 
TEST_F(UpdaterTest,file_getprop)294 TEST_F(UpdaterTest, file_getprop) {
295     // file_getprop() expects two arguments.
296     expect(nullptr, "file_getprop()", kArgsParsingFailure);
297     expect(nullptr, "file_getprop(\"arg1\")", kArgsParsingFailure);
298     expect(nullptr, "file_getprop(\"arg1\", \"arg2\", \"arg3\")", kArgsParsingFailure);
299 
300     // File doesn't exist.
301     expect(nullptr, "file_getprop(\"/doesntexist\", \"key1\")", kFreadFailure);
302 
303     // Reject too large files (current limit = 65536).
304     TemporaryFile temp_file1;
305     std::string buffer(65540, '\0');
306     ASSERT_TRUE(android::base::WriteStringToFile(buffer, temp_file1.path));
307 
308     // Read some keys.
309     TemporaryFile temp_file2;
310     std::string content("ro.product.name=tardis\n"
311                         "# comment\n\n\n"
312                         "ro.product.model\n"
313                         "ro.product.board =  magic \n");
314     ASSERT_TRUE(android::base::WriteStringToFile(content, temp_file2.path));
315 
316     std::string script1("file_getprop(\"" + std::string(temp_file2.path) +
317                        "\", \"ro.product.name\")");
318     expect("tardis", script1, kNoCause);
319 
320     std::string script2("file_getprop(\"" + std::string(temp_file2.path) +
321                        "\", \"ro.product.board\")");
322     expect("magic", script2, kNoCause);
323 
324     // No match.
325     std::string script3("file_getprop(\"" + std::string(temp_file2.path) +
326                        "\", \"ro.product.wrong\")");
327     expect("", script3, kNoCause);
328 
329     std::string script4("file_getprop(\"" + std::string(temp_file2.path) +
330                        "\", \"ro.product.name=\")");
331     expect("", script4, kNoCause);
332 
333     std::string script5("file_getprop(\"" + std::string(temp_file2.path) +
334                        "\", \"ro.product.nam\")");
335     expect("", script5, kNoCause);
336 
337     std::string script6("file_getprop(\"" + std::string(temp_file2.path) +
338                        "\", \"ro.product.model\")");
339     expect("", script6, kNoCause);
340 }
341 
342 // TODO: Test extracting to block device.
TEST_F(UpdaterTest,package_extract_file)343 TEST_F(UpdaterTest, package_extract_file) {
344   // package_extract_file expects 1 or 2 arguments.
345   expect(nullptr, "package_extract_file()", kArgsParsingFailure);
346   expect(nullptr, "package_extract_file(\"arg1\", \"arg2\", \"arg3\")", kArgsParsingFailure);
347 
348   std::string zip_path = from_testdata_base("ziptest_valid.zip");
349   ZipArchiveHandle handle;
350   ASSERT_EQ(0, OpenArchive(zip_path.c_str(), &handle));
351 
352   // Need to set up the ziphandle.
353   SetUpdaterOtaPackageHandle(handle);
354 
355   // Two-argument version.
356   TemporaryFile temp_file1;
357   std::string script("package_extract_file(\"a.txt\", \"" + std::string(temp_file1.path) + "\")");
358   expect("t", script, kNoCause, &updater_);
359 
360   // Verify the extracted entry.
361   std::string data;
362   ASSERT_TRUE(android::base::ReadFileToString(temp_file1.path, &data));
363   ASSERT_EQ(kATxtContents, data);
364 
365   // Now extract another entry to the same location, which should overwrite.
366   script = "package_extract_file(\"b.txt\", \"" + std::string(temp_file1.path) + "\")";
367   expect("t", script, kNoCause, &updater_);
368 
369   ASSERT_TRUE(android::base::ReadFileToString(temp_file1.path, &data));
370   ASSERT_EQ(kBTxtContents, data);
371 
372   // Missing zip entry. The two-argument version doesn't abort.
373   script = "package_extract_file(\"doesntexist\", \"" + std::string(temp_file1.path) + "\")";
374   expect("", script, kNoCause, &updater_);
375 
376   // Extract to /dev/full should fail.
377   script = "package_extract_file(\"a.txt\", \"/dev/full\")";
378   expect("", script, kNoCause, &updater_);
379 
380   // One-argument version. package_extract_file() gives a VAL_BLOB, which needs to be converted to
381   // VAL_STRING for equality test.
382   script = "blob_to_string(package_extract_file(\"a.txt\")) == \"" + kATxtContents + "\"";
383   expect("t", script, kNoCause, &updater_);
384 
385   script = "blob_to_string(package_extract_file(\"b.txt\")) == \"" + kBTxtContents + "\"";
386   expect("t", script, kNoCause, &updater_);
387 
388   // Missing entry. The one-argument version aborts the evaluation.
389   script = "package_extract_file(\"doesntexist\")";
390   expect(nullptr, script, kPackageExtractFileFailure, &updater_);
391 }
392 
TEST_F(UpdaterTest,read_file)393 TEST_F(UpdaterTest, read_file) {
394   // read_file() expects one argument.
395   expect(nullptr, "read_file()", kArgsParsingFailure);
396   expect(nullptr, "read_file(\"arg1\", \"arg2\")", kArgsParsingFailure);
397 
398   // Write some value to file and read back.
399   TemporaryFile temp_file;
400   std::string script("write_value(\"foo\", \""s + temp_file.path + "\");");
401   expect("t", script, kNoCause);
402 
403   script = "read_file(\""s + temp_file.path + "\") == \"foo\"";
404   expect("t", script, kNoCause);
405 
406   script = "read_file(\""s + temp_file.path + "\") == \"bar\"";
407   expect("", script, kNoCause);
408 
409   // It should fail gracefully when read fails.
410   script = "read_file(\"/doesntexist\")";
411   expect("", script, kNoCause);
412 }
413 
TEST_F(UpdaterTest,compute_hash_tree_smoke)414 TEST_F(UpdaterTest, compute_hash_tree_smoke) {
415   std::string data;
416   for (unsigned char i = 0; i < 128; i++) {
417     data += std::string(4096, i);
418   }
419   // Appends an additional block for verity data.
420   data += std::string(4096, 0);
421   ASSERT_EQ(129 * 4096, data.size());
422   ASSERT_TRUE(android::base::WriteStringToFile(data, image_file_));
423 
424   std::string salt = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7";
425   std::string expected_root_hash =
426       "7e0a8d8747f54384014ab996f5b2dc4eb7ff00c630eede7134c9e3f05c0dd8ca";
427   // hash_tree_ranges, source_ranges, hash_algorithm, salt_hex, root_hash
428   std::vector<std::string> tokens{ "compute_hash_tree", "2,128,129", "2,0,128", "sha256", salt,
429                                    expected_root_hash };
430   std::string hash_tree_command = android::base::Join(tokens, " ");
431 
432   std::vector<std::string> transfer_list{
433     "4", "2", "0", "2", hash_tree_command,
434   };
435 
436   PackageEntries entries{
437     { "new_data", "" },
438     { "patch_data", "" },
439     { "transfer_list", android::base::Join(transfer_list, "\n") },
440   };
441 
442   RunBlockImageUpdate(false, entries, image_file_, "t");
443 
444   std::string updated;
445   ASSERT_TRUE(android::base::ReadFileToString(image_file_, &updated));
446   ASSERT_EQ(129 * 4096, updated.size());
447   ASSERT_EQ(data.substr(0, 128 * 4096), updated.substr(0, 128 * 4096));
448 
449   // Computes the SHA256 of the salt + hash_tree_data and expects the result to match with the
450   // root_hash.
451   std::vector<unsigned char> salt_bytes;
452   ASSERT_TRUE(HashTreeBuilder::ParseBytesArrayFromString(salt, &salt_bytes));
453   std::vector<unsigned char> hash_tree = std::move(salt_bytes);
454   hash_tree.insert(hash_tree.end(), updated.begin() + 128 * 4096, updated.end());
455 
456   std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);
457   SHA256(hash_tree.data(), hash_tree.size(), digest.data());
458   ASSERT_EQ(expected_root_hash, HashTreeBuilder::BytesArrayToString(digest));
459 }
460 
TEST_F(UpdaterTest,compute_hash_tree_root_mismatch)461 TEST_F(UpdaterTest, compute_hash_tree_root_mismatch) {
462   std::string data;
463   for (size_t i = 0; i < 128; i++) {
464     data += std::string(4096, i);
465   }
466   // Appends an additional block for verity data.
467   data += std::string(4096, 0);
468   ASSERT_EQ(129 * 4096, data.size());
469   // Corrupts one bit
470   data[4096] = 'A';
471   ASSERT_TRUE(android::base::WriteStringToFile(data, image_file_));
472 
473   std::string salt = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7";
474   std::string expected_root_hash =
475       "7e0a8d8747f54384014ab996f5b2dc4eb7ff00c630eede7134c9e3f05c0dd8ca";
476   // hash_tree_ranges, source_ranges, hash_algorithm, salt_hex, root_hash
477   std::vector<std::string> tokens{ "compute_hash_tree", "2,128,129", "2,0,128", "sha256", salt,
478                                    expected_root_hash };
479   std::string hash_tree_command = android::base::Join(tokens, " ");
480 
481   std::vector<std::string> transfer_list{
482     "4", "2", "0", "2", hash_tree_command,
483   };
484 
485   PackageEntries entries{
486     { "new_data", "" },
487     { "patch_data", "" },
488     { "transfer_list", android::base::Join(transfer_list, "\n") },
489   };
490 
491   RunBlockImageUpdate(false, entries, image_file_, "", kHashTreeComputationFailure);
492 }
493 
TEST_F(UpdaterTest,write_value)494 TEST_F(UpdaterTest, write_value) {
495   // write_value() expects two arguments.
496   expect(nullptr, "write_value()", kArgsParsingFailure);
497   expect(nullptr, "write_value(\"arg1\")", kArgsParsingFailure);
498   expect(nullptr, "write_value(\"arg1\", \"arg2\", \"arg3\")", kArgsParsingFailure);
499 
500   // filename cannot be empty.
501   expect(nullptr, "write_value(\"value\", \"\")", kArgsParsingFailure);
502 
503   // Write some value to file.
504   TemporaryFile temp_file;
505   std::string value = "magicvalue";
506   std::string script("write_value(\"" + value + "\", \"" + std::string(temp_file.path) + "\")");
507   expect("t", script, kNoCause);
508 
509   // Verify the content.
510   std::string content;
511   ASSERT_TRUE(android::base::ReadFileToString(temp_file.path, &content));
512   ASSERT_EQ(value, content);
513 
514   // Allow writing empty string.
515   script = "write_value(\"\", \"" + std::string(temp_file.path) + "\")";
516   expect("t", script, kNoCause);
517 
518   // Verify the content.
519   ASSERT_TRUE(android::base::ReadFileToString(temp_file.path, &content));
520   ASSERT_EQ("", content);
521 
522   // It should fail gracefully when write fails.
523   script = "write_value(\"value\", \"/proc/0/file1\")";
524   expect("", script, kNoCause);
525 }
526 
TEST_F(UpdaterTest,get_stage)527 TEST_F(UpdaterTest, get_stage) {
528   // get_stage() expects one argument.
529   expect(nullptr, "get_stage()", kArgsParsingFailure);
530   expect(nullptr, "get_stage(\"arg1\", \"arg2\")", kArgsParsingFailure);
531   expect(nullptr, "get_stage(\"arg1\", \"arg2\", \"arg3\")", kArgsParsingFailure);
532 
533   // Set up a local file as BCB.
534   TemporaryFile tf;
535   std::string temp_file(tf.path);
536   bootloader_message boot;
537   strlcpy(boot.stage, "2/3", sizeof(boot.stage));
538   std::string err;
539   ASSERT_TRUE(write_bootloader_message_to(boot, temp_file, &err));
540 
541   // Can read the stage value.
542   std::string script("get_stage(\"" + temp_file + "\")");
543   expect("2/3", script, kNoCause);
544 
545   // Bad BCB path.
546   script = "get_stage(\"doesntexist\")";
547   expect("", script, kNoCause);
548 }
549 
TEST_F(UpdaterTest,set_stage)550 TEST_F(UpdaterTest, set_stage) {
551   // set_stage() expects two arguments.
552   expect(nullptr, "set_stage()", kArgsParsingFailure);
553   expect(nullptr, "set_stage(\"arg1\")", kArgsParsingFailure);
554   expect(nullptr, "set_stage(\"arg1\", \"arg2\", \"arg3\")", kArgsParsingFailure);
555 
556   // Set up a local file as BCB.
557   TemporaryFile tf;
558   std::string temp_file(tf.path);
559   bootloader_message boot;
560   strlcpy(boot.command, "command", sizeof(boot.command));
561   strlcpy(boot.stage, "2/3", sizeof(boot.stage));
562   std::string err;
563   ASSERT_TRUE(write_bootloader_message_to(boot, temp_file, &err));
564 
565   // Write with set_stage().
566   std::string script("set_stage(\"" + temp_file + "\", \"1/3\")");
567   expect(tf.path, script, kNoCause);
568 
569   // Verify.
570   bootloader_message boot_verify;
571   ASSERT_TRUE(read_bootloader_message_from(&boot_verify, temp_file, &err));
572 
573   // Stage should be updated, with command part untouched.
574   ASSERT_STREQ("1/3", boot_verify.stage);
575   ASSERT_STREQ(boot.command, boot_verify.command);
576 
577   // Bad BCB path.
578   script = "set_stage(\"doesntexist\", \"1/3\")";
579   expect("", script, kNoCause);
580 
581   script = "set_stage(\"/dev/full\", \"1/3\")";
582   expect("", script, kNoCause);
583 }
584 
TEST_F(UpdaterTest,set_progress)585 TEST_F(UpdaterTest, set_progress) {
586   // set_progress() expects one argument.
587   expect(nullptr, "set_progress()", kArgsParsingFailure);
588   expect(nullptr, "set_progress(\"arg1\", \"arg2\")", kArgsParsingFailure);
589 
590   // Invalid progress argument.
591   expect(nullptr, "set_progress(\"arg1\")", kArgsParsingFailure);
592   expect(nullptr, "set_progress(\"3x+5\")", kArgsParsingFailure);
593   expect(nullptr, "set_progress(\".3.5\")", kArgsParsingFailure);
594 
595   TemporaryFile tf;
596   SetUpdaterCmdPipe(tf.release());
597   expect(".52", "set_progress(\".52\")", kNoCause, &updater_);
598   FlushUpdaterCommandPipe();
599 
600   std::string cmd;
601   ASSERT_TRUE(android::base::ReadFileToString(tf.path, &cmd));
602   ASSERT_EQ(android::base::StringPrintf("set_progress %f\n", .52), cmd);
603   // recovery-updater protocol expects 2 tokens ("set_progress <frac>").
604   ASSERT_EQ(2U, android::base::Split(cmd, " ").size());
605 }
606 
TEST_F(UpdaterTest,show_progress)607 TEST_F(UpdaterTest, show_progress) {
608   // show_progress() expects two arguments.
609   expect(nullptr, "show_progress()", kArgsParsingFailure);
610   expect(nullptr, "show_progress(\"arg1\")", kArgsParsingFailure);
611   expect(nullptr, "show_progress(\"arg1\", \"arg2\", \"arg3\")", kArgsParsingFailure);
612 
613   // Invalid progress arguments.
614   expect(nullptr, "show_progress(\"arg1\", \"arg2\")", kArgsParsingFailure);
615   expect(nullptr, "show_progress(\"3x+5\", \"10\")", kArgsParsingFailure);
616   expect(nullptr, "show_progress(\".3\", \"5a\")", kArgsParsingFailure);
617 
618   TemporaryFile tf;
619   SetUpdaterCmdPipe(tf.release());
620   expect(".52", "show_progress(\".52\", \"10\")", kNoCause, &updater_);
621   FlushUpdaterCommandPipe();
622 
623   std::string cmd;
624   ASSERT_TRUE(android::base::ReadFileToString(tf.path, &cmd));
625   ASSERT_EQ(android::base::StringPrintf("progress %f %d\n", .52, 10), cmd);
626   // recovery-updater protocol expects 3 tokens ("progress <frac> <secs>").
627   ASSERT_EQ(3U, android::base::Split(cmd, " ").size());
628 }
629 
TEST_F(UpdaterTest,block_image_update_parsing_error)630 TEST_F(UpdaterTest, block_image_update_parsing_error) {
631   std::vector<std::string> transfer_list{
632     // clang-format off
633     "4",
634     "2",
635     "0",
636     // clang-format on
637   };
638 
639   PackageEntries entries{
640     { "new_data", "" },
641     { "patch_data", "" },
642     { "transfer_list", android::base::Join(transfer_list, '\n') },
643   };
644 
645   RunBlockImageUpdate(false, entries, image_file_, "", kArgsParsingFailure);
646 }
647 
648 // Generates the bsdiff of the given source and target images, and writes the result entries.
649 // target_blocks specifies the block count to be written into the `bsdiff` command, which may be
650 // different from the given target size in order to trigger overrun / underrun paths.
GetEntriesForBsdiff(std::string_view source,std::string_view target,size_t target_blocks,PackageEntries * entries)651 static void GetEntriesForBsdiff(std::string_view source, std::string_view target,
652                                 size_t target_blocks, PackageEntries* entries) {
653   // Generate the patch data.
654   TemporaryFile patch_file;
655   ASSERT_EQ(0, bsdiff::bsdiff(reinterpret_cast<const uint8_t*>(source.data()), source.size(),
656                               reinterpret_cast<const uint8_t*>(target.data()), target.size(),
657                               patch_file.path, nullptr));
658   std::string patch_content;
659   ASSERT_TRUE(android::base::ReadFileToString(patch_file.path, &patch_content));
660 
661   // Create the transfer list that contains a bsdiff.
662   std::string src_hash = GetSha1(source);
663   std::string tgt_hash = GetSha1(target);
664   size_t source_blocks = source.size() / 4096;
665   std::vector<std::string> transfer_list{
666     // clang-format off
667     "4",
668     std::to_string(target_blocks),
669     "0",
670     "0",
671     // bsdiff patch_offset patch_length source_hash target_hash target_range source_block_count
672     // source_range
673     android::base::StringPrintf("bsdiff 0 %zu %s %s 2,0,%zu %zu 2,0,%zu", patch_content.size(),
674                                 src_hash.c_str(), tgt_hash.c_str(), target_blocks, source_blocks,
675                                 source_blocks),
676     // clang-format on
677   };
678 
679   *entries = {
680     { "new_data", "" },
681     { "patch_data", patch_content },
682     { "transfer_list", android::base::Join(transfer_list, '\n') },
683   };
684 }
685 
TEST_F(UpdaterTest,block_image_update_patch_data)686 TEST_F(UpdaterTest, block_image_update_patch_data) {
687   // Both source and target images have 10 blocks.
688   std::string source =
689       std::string(4096, 'a') + std::string(4096, 'c') + std::string(4096 * 3, '\0');
690   std::string target =
691       std::string(4096, 'b') + std::string(4096, 'd') + std::string(4096 * 3, '\0');
692   ASSERT_TRUE(android::base::WriteStringToFile(source, image_file_));
693 
694   PackageEntries entries;
695   GetEntriesForBsdiff(std::string_view(source).substr(0, 4096 * 2),
696                       std::string_view(target).substr(0, 4096 * 2), 2, &entries);
697   RunBlockImageUpdate(false, entries, image_file_, "t");
698 
699   // The update_file should be patched correctly.
700   std::string updated;
701   ASSERT_TRUE(android::base::ReadFileToString(image_file_, &updated));
702   ASSERT_EQ(target, updated);
703 }
704 
TEST_F(UpdaterTest,block_image_update_patch_overrun)705 TEST_F(UpdaterTest, block_image_update_patch_overrun) {
706   // Both source and target images have 10 blocks.
707   std::string source =
708       std::string(4096, 'a') + std::string(4096, 'c') + std::string(4096 * 3, '\0');
709   std::string target =
710       std::string(4096, 'b') + std::string(4096, 'd') + std::string(4096 * 3, '\0');
711   ASSERT_TRUE(android::base::WriteStringToFile(source, image_file_));
712 
713   // Provide one less block to trigger the overrun path.
714   PackageEntries entries;
715   GetEntriesForBsdiff(std::string_view(source).substr(0, 4096 * 2),
716                       std::string_view(target).substr(0, 4096 * 2), 1, &entries);
717 
718   // The update should fail due to overrun.
719   RunBlockImageUpdate(false, entries, image_file_, "", kPatchApplicationFailure);
720 }
721 
TEST_F(UpdaterTest,block_image_update_patch_underrun)722 TEST_F(UpdaterTest, block_image_update_patch_underrun) {
723   // Both source and target images have 10 blocks.
724   std::string source =
725       std::string(4096, 'a') + std::string(4096, 'c') + std::string(4096 * 3, '\0');
726   std::string target =
727       std::string(4096, 'b') + std::string(4096, 'd') + std::string(4096 * 3, '\0');
728   ASSERT_TRUE(android::base::WriteStringToFile(source, image_file_));
729 
730   // Provide one more block to trigger the overrun path.
731   PackageEntries entries;
732   GetEntriesForBsdiff(std::string_view(source).substr(0, 4096 * 2),
733                       std::string_view(target).substr(0, 4096 * 2), 3, &entries);
734 
735   // The update should fail due to underrun.
736   RunBlockImageUpdate(false, entries, image_file_, "", kPatchApplicationFailure);
737 }
738 
TEST_F(UpdaterTest,block_image_update_fail)739 TEST_F(UpdaterTest, block_image_update_fail) {
740   std::string src_content(4096 * 2, 'e');
741   std::string src_hash = GetSha1(src_content);
742   // Stash and free some blocks, then fail the update intentionally.
743   std::vector<std::string> transfer_list{
744     // clang-format off
745     "4",
746     "2",
747     "0",
748     "2",
749     "stash " + src_hash + " 2,0,2",
750     "free " + src_hash,
751     "abort",
752     // clang-format on
753   };
754 
755   // Add a new data of 10 bytes to test the deadlock.
756   PackageEntries entries{
757     { "new_data", std::string(10, 0) },
758     { "patch_data", "" },
759     { "transfer_list", android::base::Join(transfer_list, '\n') },
760   };
761 
762   ASSERT_TRUE(android::base::WriteStringToFile(src_content, image_file_));
763 
764   RunBlockImageUpdate(false, entries, image_file_, "");
765 
766   // Updater generates the stash name based on the input file name.
767   std::string name_digest = GetSha1(image_file_);
768   std::string stash_base = std::string(temp_stash_base_.path) + "/" + name_digest;
769   ASSERT_EQ(0, access(stash_base.c_str(), F_OK));
770   // Expect the stashed blocks to be freed.
771   ASSERT_EQ(-1, access((stash_base + src_hash).c_str(), F_OK));
772   ASSERT_EQ(0, rmdir(stash_base.c_str()));
773 }
774 
TEST_F(UpdaterTest,new_data_over_write)775 TEST_F(UpdaterTest, new_data_over_write) {
776   std::vector<std::string> transfer_list{
777     // clang-format off
778     "4",
779     "1",
780     "0",
781     "0",
782     "new 2,0,1",
783     // clang-format on
784   };
785 
786   // Write 4096 + 100 bytes of new data.
787   PackageEntries entries{
788     { "new_data", std::string(4196, 0) },
789     { "patch_data", "" },
790     { "transfer_list", android::base::Join(transfer_list, '\n') },
791   };
792 
793   RunBlockImageUpdate(false, entries, image_file_, "t");
794 }
795 
TEST_F(UpdaterTest,new_data_short_write)796 TEST_F(UpdaterTest, new_data_short_write) {
797   std::vector<std::string> transfer_list{
798     // clang-format off
799     "4",
800     "1",
801     "0",
802     "0",
803     "new 2,0,1",
804     // clang-format on
805   };
806 
807   PackageEntries entries{
808     { "patch_data", "" },
809     { "transfer_list", android::base::Join(transfer_list, '\n') },
810   };
811 
812   // Updater should report the failure gracefully rather than stuck in deadlock.
813   entries["new_data"] = "";
814   RunBlockImageUpdate(false, entries, image_file_, "");
815 
816   entries["new_data"] = std::string(10, 'a');
817   RunBlockImageUpdate(false, entries, image_file_, "");
818 
819   // Expect to write 1 block of new data successfully.
820   entries["new_data"] = std::string(4096, 'a');
821   RunBlockImageUpdate(false, entries, image_file_, "t");
822 }
823 
TEST_F(UpdaterTest,brotli_new_data)824 TEST_F(UpdaterTest, brotli_new_data) {
825   auto generator = []() { return rand() % 128; };
826   // Generate 100 blocks of random data.
827   std::string brotli_new_data;
828   brotli_new_data.reserve(4096 * 100);
829   generate_n(back_inserter(brotli_new_data), 4096 * 100, generator);
830 
831   size_t encoded_size = BrotliEncoderMaxCompressedSize(brotli_new_data.size());
832   std::string encoded_data(encoded_size, 0);
833   ASSERT_TRUE(BrotliEncoderCompress(
834       BROTLI_DEFAULT_QUALITY, BROTLI_DEFAULT_WINDOW, BROTLI_DEFAULT_MODE, brotli_new_data.size(),
835       reinterpret_cast<const uint8_t*>(brotli_new_data.data()), &encoded_size,
836       reinterpret_cast<uint8_t*>(const_cast<char*>(encoded_data.data()))));
837   encoded_data.resize(encoded_size);
838 
839   // Write a few small chunks of new data, then a large chunk, and finally a few small chunks.
840   // This helps us to catch potential short writes.
841   std::vector<std::string> transfer_list = {
842     "4",
843     "100",
844     "0",
845     "0",
846     "new 2,0,1",
847     "new 2,1,2",
848     "new 4,2,50,50,97",
849     "new 2,97,98",
850     "new 2,98,99",
851     "new 2,99,100",
852   };
853 
854   PackageEntries entries{
855     { "new_data.br", std::move(encoded_data) },
856     { "patch_data", "" },
857     { "transfer_list", android::base::Join(transfer_list, '\n') },
858   };
859 
860   RunBlockImageUpdate(false, entries, image_file_, "t");
861 
862   std::string updated_content;
863   ASSERT_TRUE(android::base::ReadFileToString(image_file_, &updated_content));
864   ASSERT_EQ(brotli_new_data, updated_content);
865 }
866 
TEST_F(UpdaterTest,last_command_update)867 TEST_F(UpdaterTest, last_command_update) {
868   std::string block1(4096, '1');
869   std::string block2(4096, '2');
870   std::string block3(4096, '3');
871   std::string block1_hash = GetSha1(block1);
872   std::string block2_hash = GetSha1(block2);
873   std::string block3_hash = GetSha1(block3);
874 
875   // Compose the transfer list to fail the first update.
876   std::vector<std::string> transfer_list_fail{
877     // clang-format off
878     "4",
879     "2",
880     "0",
881     "2",
882     "stash " + block1_hash + " 2,0,1",
883     "move " + block1_hash + " 2,1,2 1 2,0,1",
884     "stash " + block3_hash + " 2,2,3",
885     "abort",
886     // clang-format on
887   };
888 
889   // Mimic a resumed update with the same transfer commands.
890   std::vector<std::string> transfer_list_continue{
891     // clang-format off
892     "4",
893     "2",
894     "0",
895     "2",
896     "stash " + block1_hash + " 2,0,1",
897     "move " + block1_hash + " 2,1,2 1 2,0,1",
898     "stash " + block3_hash + " 2,2,3",
899     "move " + block1_hash + " 2,2,3 1 2,0,1",
900     // clang-format on
901   };
902 
903   ASSERT_TRUE(android::base::WriteStringToFile(block1 + block2 + block3, image_file_));
904 
905   PackageEntries entries{
906     { "new_data", "" },
907     { "patch_data", "" },
908     { "transfer_list", android::base::Join(transfer_list_fail, '\n') },
909   };
910 
911   // "2\nstash " + block3_hash + " 2,2,3"
912   std::string last_command_content =
913       "2\n" + transfer_list_fail[TransferList::kTransferListHeaderLines + 2];
914 
915   RunBlockImageUpdate(false, entries, image_file_, "");
916 
917   // Expect last_command to contain the last stash command.
918   std::string last_command_actual;
919   ASSERT_TRUE(android::base::ReadFileToString(last_command_file_, &last_command_actual));
920   EXPECT_EQ(last_command_content, last_command_actual);
921 
922   std::string updated_contents;
923   ASSERT_TRUE(android::base::ReadFileToString(image_file_, &updated_contents));
924   ASSERT_EQ(block1 + block1 + block3, updated_contents);
925 
926   // "Resume" the update. Expect the first 'move' to be skipped but the second 'move' to be
927   // executed. Note that we intentionally reset the image file.
928   entries["transfer_list"] = android::base::Join(transfer_list_continue, '\n');
929   ASSERT_TRUE(android::base::WriteStringToFile(block1 + block2 + block3, image_file_));
930   RunBlockImageUpdate(false, entries, image_file_, "t");
931 
932   ASSERT_TRUE(android::base::ReadFileToString(image_file_, &updated_contents));
933   ASSERT_EQ(block1 + block2 + block1, updated_contents);
934 }
935 
TEST_F(UpdaterTest,last_command_update_unresumable)936 TEST_F(UpdaterTest, last_command_update_unresumable) {
937   std::string block1(4096, '1');
938   std::string block2(4096, '2');
939   std::string block1_hash = GetSha1(block1);
940   std::string block2_hash = GetSha1(block2);
941 
942   // Construct an unresumable update with source blocks mismatch.
943   std::vector<std::string> transfer_list_unresumable{
944     // clang-format off
945     "4",
946     "2",
947     "0",
948     "2",
949     "stash " + block1_hash + " 2,0,1",
950     "move " + block2_hash + " 2,1,2 1 2,0,1",
951     // clang-format on
952   };
953 
954   PackageEntries entries{
955     { "new_data", "" },
956     { "patch_data", "" },
957     { "transfer_list", android::base::Join(transfer_list_unresumable, '\n') },
958   };
959 
960   ASSERT_TRUE(android::base::WriteStringToFile(block1 + block1, image_file_));
961 
962   std::string last_command_content =
963       "0\n" + transfer_list_unresumable[TransferList::kTransferListHeaderLines];
964   ASSERT_TRUE(android::base::WriteStringToFile(last_command_content, last_command_file_));
965 
966   RunBlockImageUpdate(false, entries, image_file_, "");
967 
968   // The last_command_file will be deleted if the update encounters an unresumable failure later.
969   ASSERT_EQ(-1, access(last_command_file_.c_str(), R_OK));
970 }
971 
TEST_F(UpdaterTest,last_command_verify)972 TEST_F(UpdaterTest, last_command_verify) {
973   std::string block1(4096, '1');
974   std::string block2(4096, '2');
975   std::string block3(4096, '3');
976   std::string block1_hash = GetSha1(block1);
977   std::string block2_hash = GetSha1(block2);
978   std::string block3_hash = GetSha1(block3);
979 
980   std::vector<std::string> transfer_list_verify{
981     // clang-format off
982     "4",
983     "2",
984     "0",
985     "2",
986     "stash " + block1_hash + " 2,0,1",
987     "move " + block1_hash + " 2,0,1 1 2,0,1",
988     "move " + block1_hash + " 2,1,2 1 2,0,1",
989     "stash " + block3_hash + " 2,2,3",
990     // clang-format on
991   };
992 
993   PackageEntries entries{
994     { "new_data", "" },
995     { "patch_data", "" },
996     { "transfer_list", android::base::Join(transfer_list_verify, '\n') },
997   };
998 
999   ASSERT_TRUE(android::base::WriteStringToFile(block1 + block1 + block3, image_file_));
1000 
1001   // Last command: "move " + block1_hash + " 2,1,2 1 2,0,1"
1002   std::string last_command_content =
1003       "2\n" + transfer_list_verify[TransferList::kTransferListHeaderLines + 2];
1004 
1005   // First run: expect the verification to succeed and the last_command_file is intact.
1006   ASSERT_TRUE(android::base::WriteStringToFile(last_command_content, last_command_file_));
1007 
1008   RunBlockImageUpdate(true, entries, image_file_, "t");
1009 
1010   std::string last_command_actual;
1011   ASSERT_TRUE(android::base::ReadFileToString(last_command_file_, &last_command_actual));
1012   EXPECT_EQ(last_command_content, last_command_actual);
1013 
1014   // Second run with a mismatching block image: expect the verification to succeed but
1015   // last_command_file to be deleted; because the target blocks in the last command don't have the
1016   // expected contents for the second move command.
1017   ASSERT_TRUE(android::base::WriteStringToFile(block1 + block2 + block3, image_file_));
1018   RunBlockImageUpdate(true, entries, image_file_, "t");
1019   ASSERT_EQ(-1, access(last_command_file_.c_str(), R_OK));
1020 }
1021 
1022 class ResumableUpdaterTest : public UpdaterTestBase, public testing::TestWithParam<size_t> {
1023  protected:
SetUp()1024   void SetUp() override {
1025     UpdaterTestBase::SetUp();
1026     // Enable a special command "abort" to simulate interruption.
1027     Command::abort_allowed_ = true;
1028     index_ = GetParam();
1029   }
1030 
TearDown()1031   void TearDown() override {
1032     UpdaterTestBase::TearDown();
1033   }
1034 
1035   size_t index_;
1036 };
1037 
1038 static std::string g_source_image;
1039 static std::string g_target_image;
1040 static PackageEntries g_entries;
1041 
GenerateTransferList()1042 static std::vector<std::string> GenerateTransferList() {
1043   std::string a(4096, 'a');
1044   std::string b(4096, 'b');
1045   std::string c(4096, 'c');
1046   std::string d(4096, 'd');
1047   std::string e(4096, 'e');
1048   std::string f(4096, 'f');
1049   std::string g(4096, 'g');
1050   std::string h(4096, 'h');
1051   std::string i(4096, 'i');
1052   std::string zero(4096, '\0');
1053 
1054   std::string a_hash = GetSha1(a);
1055   std::string b_hash = GetSha1(b);
1056   std::string c_hash = GetSha1(c);
1057   std::string e_hash = GetSha1(e);
1058 
1059   auto loc = [](const std::string& range_text) {
1060     std::vector<std::string> pieces = android::base::Split(range_text, "-");
1061     size_t left;
1062     size_t right;
1063     if (pieces.size() == 1) {
1064       CHECK(android::base::ParseUint(pieces[0], &left));
1065       right = left + 1;
1066     } else {
1067       CHECK_EQ(2u, pieces.size());
1068       CHECK(android::base::ParseUint(pieces[0], &left));
1069       CHECK(android::base::ParseUint(pieces[1], &right));
1070       right++;
1071     }
1072     return android::base::StringPrintf("2,%zu,%zu", left, right);
1073   };
1074 
1075   // patch 1: "b d c" -> "g"
1076   TemporaryFile patch_file_bdc_g;
1077   std::string bdc = b + d + c;
1078   std::string bdc_hash = GetSha1(bdc);
1079   std::string g_hash = GetSha1(g);
1080   CHECK_EQ(0, bsdiff::bsdiff(reinterpret_cast<const uint8_t*>(bdc.data()), bdc.size(),
1081                              reinterpret_cast<const uint8_t*>(g.data()), g.size(),
1082                              patch_file_bdc_g.path, nullptr));
1083   std::string patch_bdc_g;
1084   CHECK(android::base::ReadFileToString(patch_file_bdc_g.path, &patch_bdc_g));
1085 
1086   // patch 2: "a b c d" -> "d c b"
1087   TemporaryFile patch_file_abcd_dcb;
1088   std::string abcd = a + b + c + d;
1089   std::string abcd_hash = GetSha1(abcd);
1090   std::string dcb = d + c + b;
1091   std::string dcb_hash = GetSha1(dcb);
1092   CHECK_EQ(0, bsdiff::bsdiff(reinterpret_cast<const uint8_t*>(abcd.data()), abcd.size(),
1093                              reinterpret_cast<const uint8_t*>(dcb.data()), dcb.size(),
1094                              patch_file_abcd_dcb.path, nullptr));
1095   std::string patch_abcd_dcb;
1096   CHECK(android::base::ReadFileToString(patch_file_abcd_dcb.path, &patch_abcd_dcb));
1097 
1098   std::vector<std::string> transfer_list{
1099     "4",
1100     "10",  // total blocks written
1101     "2",   // maximum stash entries
1102     "2",   // maximum number of stashed blocks
1103 
1104     // a b c d e a b c d e
1105     "stash " + b_hash + " " + loc("1"),
1106     // a b c d e a b c d e    [b(1)]
1107     "stash " + c_hash + " " + loc("2"),
1108     // a b c d e a b c d e    [b(1)][c(2)]
1109     "new " + loc("1-2"),
1110     // a i h d e a b c d e    [b(1)][c(2)]
1111     "zero " + loc("0"),
1112     // 0 i h d e a b c d e    [b(1)][c(2)]
1113 
1114     // bsdiff "b d c" (from stash, 3, stash) to get g(3)
1115     android::base::StringPrintf(
1116         "bsdiff 0 %zu %s %s %s 3 %s %s %s:%s %s:%s",
1117         patch_bdc_g.size(),                  // patch start (0), patch length
1118         bdc_hash.c_str(),                    // source hash
1119         g_hash.c_str(),                      // target hash
1120         loc("3").c_str(),                    // target range
1121         loc("3").c_str(), loc("1").c_str(),  // load "d" from block 3, into buffer at offset 1
1122         b_hash.c_str(), loc("0").c_str(),    // load "b" from stash, into buffer at offset 0
1123         c_hash.c_str(), loc("2").c_str()),   // load "c" from stash, into buffer at offset 2
1124 
1125     // 0 i h g e a b c d e    [b(1)][c(2)]
1126     "free " + b_hash,
1127     // 0 i h g e a b c d e    [c(2)]
1128     "free " + a_hash,
1129     // 0 i h g e a b c d e
1130     "stash " + a_hash + " " + loc("5"),
1131     // 0 i h g e a b c d e    [a(5)]
1132     "move " + e_hash + " " + loc("5") + " 1 " + loc("4"),
1133     // 0 i h g e e b c d e    [a(5)]
1134 
1135     // bsdiff "a b c d" (from stash, 6-8) to "d c b" (6-8)
1136     android::base::StringPrintf(  //
1137         "bsdiff %zu %zu %s %s %s 4 %s %s %s:%s",
1138         patch_bdc_g.size(),                          // patch start
1139         patch_bdc_g.size() + patch_abcd_dcb.size(),  // patch length
1140         abcd_hash.c_str(),                           // source hash
1141         dcb_hash.c_str(),                            // target hash
1142         loc("6-8").c_str(),                          // target range
1143         loc("6-8").c_str(),                          // load "b c d" from blocks 6-8
1144         loc("1-3").c_str(),                          //   into buffer at offset 1-3
1145         a_hash.c_str(),                              // load "a" from stash
1146         loc("0").c_str()),                           //   into buffer at offset 0
1147 
1148     // 0 i h g e e d c b e    [a(5)]
1149     "new " + loc("4"),
1150     // 0 i h g f e d c b e    [a(5)]
1151     "move " + a_hash + " " + loc("9") + " 1 - " + a_hash + ":" + loc("0"),
1152     // 0 i h g f e d c b a    [a(5)]
1153     "free " + a_hash,
1154     // 0 i h g f e d c b a
1155   };
1156 
1157   std::string new_data = i + h + f;
1158   std::string patch_data = patch_bdc_g + patch_abcd_dcb;
1159 
1160   g_entries = {
1161     { "new_data", new_data },
1162     { "patch_data", patch_data },
1163   };
1164   g_source_image = a + b + c + d + e + a + b + c + d + e;
1165   g_target_image = zero + i + h + g + f + e + d + c + b + a;
1166 
1167   return transfer_list;
1168 }
1169 
1170 static const std::vector<std::string> g_transfer_list = GenerateTransferList();
1171 
1172 INSTANTIATE_TEST_CASE_P(InterruptAfterEachCommand, ResumableUpdaterTest,
1173                         ::testing::Range(static_cast<size_t>(0),
1174                                          g_transfer_list.size() -
1175                                              TransferList::kTransferListHeaderLines));
1176 
TEST_P(ResumableUpdaterTest,InterruptVerifyResume)1177 TEST_P(ResumableUpdaterTest, InterruptVerifyResume) {
1178   ASSERT_TRUE(android::base::WriteStringToFile(g_source_image, image_file_));
1179 
1180   LOG(INFO) << "Interrupting at line " << index_ << " ("
1181             << g_transfer_list[TransferList::kTransferListHeaderLines + index_] << ")";
1182 
1183   std::vector<std::string> transfer_list_copy{ g_transfer_list };
1184   transfer_list_copy[TransferList::kTransferListHeaderLines + index_] = "abort";
1185 
1186   g_entries["transfer_list"] = android::base::Join(transfer_list_copy, '\n');
1187 
1188   // Run update that's expected to fail.
1189   RunBlockImageUpdate(false, g_entries, image_file_, "");
1190 
1191   std::string last_command_expected;
1192 
1193   // Assert the last_command_file.
1194   if (index_ == 0) {
1195     ASSERT_EQ(-1, access(last_command_file_.c_str(), R_OK));
1196   } else {
1197     last_command_expected = std::to_string(index_ - 1) + "\n" +
1198                             g_transfer_list[TransferList::kTransferListHeaderLines + index_ - 1];
1199     std::string last_command_actual;
1200     ASSERT_TRUE(android::base::ReadFileToString(last_command_file_, &last_command_actual));
1201     ASSERT_EQ(last_command_expected, last_command_actual);
1202   }
1203 
1204   g_entries["transfer_list"] = android::base::Join(g_transfer_list, '\n');
1205 
1206   // Resume the interrupted update, by doing verification first.
1207   RunBlockImageUpdate(true, g_entries, image_file_, "t");
1208 
1209   // last_command_file should remain intact.
1210   if (index_ == 0) {
1211     ASSERT_EQ(-1, access(last_command_file_.c_str(), R_OK));
1212   } else {
1213     std::string last_command_actual;
1214     ASSERT_TRUE(android::base::ReadFileToString(last_command_file_, &last_command_actual));
1215     ASSERT_EQ(last_command_expected, last_command_actual);
1216   }
1217 
1218   // Resume the update.
1219   RunBlockImageUpdate(false, g_entries, image_file_, "t");
1220 
1221   // last_command_file should be gone after successful update.
1222   ASSERT_EQ(-1, access(last_command_file_.c_str(), R_OK));
1223 
1224   std::string updated_image_actual;
1225   ASSERT_TRUE(android::base::ReadFileToString(image_file_, &updated_image_actual));
1226   ASSERT_EQ(g_target_image, updated_image_actual);
1227 }
1228