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