1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <stdint.h>
31 #include <stdio.h>
32 #include <sys/stat.h>
33 #include <sys/time.h>
34 #include <sys/types.h>
35 #include <unistd.h>
36 #include <chrono>
37 #include <cstdlib>
38 #include <fstream>
39 #include <map>
40 #include <random>
41 #include <regex>
42 #include <set>
43 #include <thread>
44 #include <vector>
45
46 #include <android-base/parseint.h>
47 #include <android-base/stringprintf.h>
48 #include <gtest/gtest.h>
49 #include <sparse/sparse.h>
50
51 #include "fastboot_driver.h"
52 #include "usb.h"
53
54 #include "extensions.h"
55 #include "fixtures.h"
56 #include "test_utils.h"
57 #include "usb_transport_sniffer.h"
58
59 namespace fastboot {
60
61 extension::Configuration config; // The parsed XML config
62
63 std::string SEARCH_PATH;
64 std::string OUTPUT_PATH;
65
66 // gtest's INSTANTIATE_TEST_CASE_P() must be at global scope,
67 // so our autogenerated tests must be as well
68 std::vector<std::pair<std::string, extension::Configuration::GetVar>> GETVAR_XML_TESTS;
69 std::vector<std::tuple<std::string, bool, extension::Configuration::CommandTest>> OEM_XML_TESTS;
70 std::vector<std::pair<std::string, extension::Configuration::PartitionInfo>> PARTITION_XML_TESTS;
71 std::vector<std::pair<std::string, extension::Configuration::PartitionInfo>>
72 PARTITION_XML_WRITEABLE;
73 std::vector<std::pair<std::string, extension::Configuration::PartitionInfo>>
74 PARTITION_XML_WRITE_HASHABLE;
75 std::vector<std::pair<std::string, extension::Configuration::PartitionInfo>>
76 PARTITION_XML_WRITE_PARSED;
77 std::vector<std::pair<std::string, extension::Configuration::PartitionInfo>>
78 PARTITION_XML_WRITE_HASH_NONPARSED;
79 std::vector<std::pair<std::string, extension::Configuration::PartitionInfo>>
80 PARTITION_XML_USERDATA_CHECKSUM_WRITEABLE;
81 std::vector<std::pair<std::string, extension::Configuration::PackedInfoTest>>
82 PACKED_XML_SUCCESS_TESTS;
83 std::vector<std::pair<std::string, extension::Configuration::PackedInfoTest>> PACKED_XML_FAIL_TESTS;
84 // This only has 1 or zero elements so it will disappear from gtest when empty
85 std::vector<std::pair<std::string, extension::Configuration::PartitionInfo>>
86 SINGLE_PARTITION_XML_WRITE_HASHABLE;
87
88 const std::string DEFAULT_OUPUT_NAME = "out.img";
89 // const char scratch_partition[] = "userdata";
90 const std::vector<std::string> CMDS{"boot", "continue", "download:", "erase:", "flash:",
91 "getvar:", "reboot", "set_active:", "upload"};
92
93 // For pretty printing we need all these overloads
operator <<(::std::ostream & os,const RetCode & ret)94 ::std::ostream& operator<<(::std::ostream& os, const RetCode& ret) {
95 return os << FastBootDriver::RCString(ret);
96 }
97
PartitionHash(FastBootDriver * fb,const std::string & part,std::string * hash,int * retcode,std::string * err_msg)98 bool PartitionHash(FastBootDriver* fb, const std::string& part, std::string* hash, int* retcode,
99 std::string* err_msg) {
100 if (config.checksum.empty()) {
101 return -1;
102 }
103
104 std::string resp;
105 std::vector<std::string> info;
106 const std::string cmd = config.checksum + ' ' + part;
107 RetCode ret;
108 if ((ret = fb->RawCommand(cmd, &resp, &info)) != SUCCESS) {
109 *err_msg =
110 android::base::StringPrintf("Hashing partition with command '%s' failed with: %s",
111 cmd.c_str(), fb->RCString(ret).c_str());
112 return false;
113 }
114 std::stringstream imploded;
115 std::copy(info.begin(), info.end(), std::ostream_iterator<std::string>(imploded, "\n"));
116
117 // If payload, we validate that as well
118 const std::vector<std::string> args = SplitBySpace(config.checksum_parser);
119 std::vector<std::string> prog_args(args.begin() + 1, args.end());
120 prog_args.push_back(resp); // Pass in the full command
121 prog_args.push_back(SEARCH_PATH + imploded.str()); // Pass in the save location
122
123 int pipe;
124 pid_t pid = StartProgram(args[0], prog_args, &pipe);
125 if (pid <= 0) {
126 *err_msg = android::base::StringPrintf("Launching hash parser '%s' failed with: %s",
127 config.checksum_parser.c_str(), strerror(errno));
128 return false;
129 }
130 *retcode = WaitProgram(pid, pipe, hash);
131 if (*retcode) {
132 // In this case the stderr pipe is a log message
133 *err_msg = android::base::StringPrintf("Hash parser '%s' failed with: %s",
134 config.checksum_parser.c_str(), hash->c_str());
135 return false;
136 }
137
138 return true;
139 }
140
SparseToBuf(sparse_file * sf,std::vector<char> * out,bool with_crc=false)141 bool SparseToBuf(sparse_file* sf, std::vector<char>* out, bool with_crc = false) {
142 int64_t len = sparse_file_len(sf, true, with_crc);
143 if (len <= 0) {
144 return false;
145 }
146 out->clear();
147 auto cb = [](void* priv, const void* data, size_t len) {
148 auto vec = static_cast<std::vector<char>*>(priv);
149 const char* cbuf = static_cast<const char*>(data);
150 vec->insert(vec->end(), cbuf, cbuf + len);
151 return 0;
152 };
153
154 return !sparse_file_callback(sf, true, with_crc, cb, out);
155 }
156
157 // Only allow alphanumeric, _, -, and .
__anon1b1869b30202(char c) 158 const auto not_allowed = [](char c) -> int {
159 return !(isalnum(c) || c == '_' || c == '-' || c == '.');
160 };
161
162 // Test that USB even works
TEST(USBFunctionality,USBConnect)163 TEST(USBFunctionality, USBConnect) {
164 const auto matcher = [](usb_ifc_info* info) -> int {
165 return FastBootTest::MatchFastboot(info, fastboot::FastBootTest::device_serial);
166 };
167 Transport* transport = nullptr;
168 for (int i = 0; i < FastBootTest::MAX_USB_TRIES && !transport; i++) {
169 transport = usb_open(matcher);
170 std::this_thread::sleep_for(std::chrono::milliseconds(10));
171 }
172 ASSERT_NE(transport, nullptr) << "Could not find the fastboot device after: "
173 << 10 * FastBootTest::MAX_USB_TRIES << "ms";
174 if (transport) {
175 transport->Close();
176 delete transport;
177 }
178 }
179
180 // Test commands related to super partition
TEST_F(LogicalPartitionCompliance,SuperPartition)181 TEST_F(LogicalPartitionCompliance, SuperPartition) {
182 ASSERT_TRUE(UserSpaceFastboot());
183 std::string partition_type;
184 // getvar partition-type:super must fail for retrofit devices because the
185 // partition does not exist.
186 if (fb->GetVar("partition-type:super", &partition_type) == SUCCESS) {
187 std::string is_logical;
188 EXPECT_EQ(fb->GetVar("is-logical:super", &is_logical), SUCCESS)
189 << "getvar is-logical:super failed";
190 EXPECT_EQ(is_logical, "no") << "super must not be a logical partition";
191 std::string super_name;
192 EXPECT_EQ(fb->GetVar("super-partition-name", &super_name), SUCCESS)
193 << "'getvar super-partition-name' failed";
194 EXPECT_EQ(super_name, "super") << "'getvar super-partition-name' must return 'super' for "
195 "device with a super partition";
196 }
197 }
198
199 // Test 'fastboot getvar is-logical'
TEST_F(LogicalPartitionCompliance,GetVarIsLogical)200 TEST_F(LogicalPartitionCompliance, GetVarIsLogical) {
201 ASSERT_TRUE(UserSpaceFastboot());
202 std::string has_slot;
203 EXPECT_EQ(fb->GetVar("has-slot:system", &has_slot), SUCCESS) << "getvar has-slot:system failed";
204 std::string is_logical_cmd_system = "is-logical:system";
205 std::string is_logical_cmd_vendor = "is-logical:vendor";
206 std::string is_logical_cmd_boot = "is-logical:boot";
207 if (has_slot == "yes") {
208 std::string current_slot;
209 ASSERT_EQ(fb->GetVar("current-slot", ¤t_slot), SUCCESS)
210 << "getvar current-slot failed";
211 std::string slot_suffix = "_" + current_slot;
212 is_logical_cmd_system += slot_suffix;
213 is_logical_cmd_vendor += slot_suffix;
214 is_logical_cmd_boot += slot_suffix;
215 }
216 std::string is_logical;
217 EXPECT_EQ(fb->GetVar(is_logical_cmd_system, &is_logical), SUCCESS)
218 << "system must be a logical partition";
219 EXPECT_EQ(is_logical, "yes");
220 EXPECT_EQ(fb->GetVar(is_logical_cmd_vendor, &is_logical), SUCCESS)
221 << "vendor must be a logical partition";
222 EXPECT_EQ(is_logical, "yes");
223 EXPECT_EQ(fb->GetVar(is_logical_cmd_boot, &is_logical), SUCCESS)
224 << "boot must not be logical partition";
225 EXPECT_EQ(is_logical, "no");
226 }
227
TEST_F(LogicalPartitionCompliance,FastbootRebootTest)228 TEST_F(LogicalPartitionCompliance, FastbootRebootTest) {
229 ASSERT_TRUE(UserSpaceFastboot());
230 GTEST_LOG_(INFO) << "Rebooting to bootloader mode";
231 // Test 'fastboot reboot bootloader' from fastbootd
232 fb->RebootTo("bootloader");
233
234 // Test fastboot reboot fastboot from bootloader
235 ReconnectFastbootDevice();
236 ASSERT_FALSE(UserSpaceFastboot());
237 GTEST_LOG_(INFO) << "Rebooting back to fastbootd mode";
238 fb->RebootTo("fastboot");
239
240 ReconnectFastbootDevice();
241 ASSERT_TRUE(UserSpaceFastboot());
242 }
243
244 // Testing creation/resize/delete of logical partitions
TEST_F(LogicalPartitionCompliance,CreateResizeDeleteLP)245 TEST_F(LogicalPartitionCompliance, CreateResizeDeleteLP) {
246 ASSERT_TRUE(UserSpaceFastboot());
247 std::string test_partition_name = "test_partition";
248 std::string slot_count;
249 // Add suffix to test_partition_name if device is slotted.
250 EXPECT_EQ(fb->GetVar("slot-count", &slot_count), SUCCESS) << "getvar slot-count failed";
251 int32_t num_slots = strtol(slot_count.c_str(), nullptr, 10);
252 if (num_slots > 0) {
253 std::string current_slot;
254 EXPECT_EQ(fb->GetVar("current-slot", ¤t_slot), SUCCESS)
255 << "getvar current-slot failed";
256 std::string slot_suffix = "_" + current_slot;
257 test_partition_name += slot_suffix;
258 }
259
260 GTEST_LOG_(INFO) << "Testing 'fastboot create-logical-partition' command";
261 EXPECT_EQ(fb->CreatePartition(test_partition_name, "0"), SUCCESS)
262 << "create-logical-partition failed";
263 GTEST_LOG_(INFO) << "Testing 'fastboot resize-logical-partition' command";
264 EXPECT_EQ(fb->ResizePartition(test_partition_name, "4096"), SUCCESS)
265 << "resize-logical-partition failed";
266 std::vector<char> buf(4096);
267
268 GTEST_LOG_(INFO) << "Flashing a logical partition..";
269 EXPECT_EQ(fb->FlashPartition(test_partition_name, buf), SUCCESS)
270 << "flash logical -partition failed";
271 GTEST_LOG_(INFO) << "Rebooting to bootloader mode";
272 // Reboot to bootloader mode and attempt to flash the logical partitions
273 fb->RebootTo("bootloader");
274
275 ReconnectFastbootDevice();
276 ASSERT_FALSE(UserSpaceFastboot());
277 GTEST_LOG_(INFO) << "Attempt to flash a logical partition..";
278 EXPECT_EQ(fb->FlashPartition(test_partition_name, buf), DEVICE_FAIL)
279 << "flash logical partition must fail in bootloader";
280 GTEST_LOG_(INFO) << "Rebooting back to fastbootd mode";
281 fb->RebootTo("fastboot");
282
283 ReconnectFastbootDevice();
284 ASSERT_TRUE(UserSpaceFastboot());
285 GTEST_LOG_(INFO) << "Testing 'fastboot delete-logical-partition' command";
286 EXPECT_EQ(fb->DeletePartition(test_partition_name), SUCCESS)
287 << "delete logical-partition failed";
288 }
289
290 // Conformance tests
TEST_F(Conformance,GetVar)291 TEST_F(Conformance, GetVar) {
292 std::string product;
293 EXPECT_EQ(fb->GetVar("product", &product), SUCCESS) << "getvar:product failed";
294 EXPECT_NE(product, "") << "getvar:product response was empty string";
295 EXPECT_EQ(std::count_if(product.begin(), product.end(), not_allowed), 0)
296 << "getvar:product response contained illegal chars";
297 EXPECT_LE(product.size(), FB_RESPONSE_SZ - 4) << "getvar:product response was too large";
298 }
299
TEST_F(Conformance,GetVarVersionBootloader)300 TEST_F(Conformance, GetVarVersionBootloader) {
301 std::string var;
302 EXPECT_EQ(fb->GetVar("version-bootloader", &var), SUCCESS)
303 << "getvar:version-bootloader failed";
304 EXPECT_NE(var, "") << "getvar:version-bootloader response was empty string";
305 EXPECT_EQ(std::count_if(var.begin(), var.end(), not_allowed), 0)
306 << "getvar:version-bootloader response contained illegal chars";
307 EXPECT_LE(var.size(), FB_RESPONSE_SZ - 4) << "getvar:version-bootloader response was too large";
308 }
309
TEST_F(Conformance,GetVarVersionBaseband)310 TEST_F(Conformance, GetVarVersionBaseband) {
311 std::string var;
312 EXPECT_EQ(fb->GetVar("version-baseband", &var), SUCCESS) << "getvar:version-baseband failed";
313 EXPECT_NE(var, "") << "getvar:version-baseband response was empty string";
314 EXPECT_EQ(std::count_if(var.begin(), var.end(), not_allowed), 0)
315 << "getvar:version-baseband response contained illegal chars";
316 EXPECT_LE(var.size(), FB_RESPONSE_SZ - 4) << "getvar:version-baseband response was too large";
317 }
318
TEST_F(Conformance,GetVarSerialNo)319 TEST_F(Conformance, GetVarSerialNo) {
320 std::string var;
321 EXPECT_EQ(fb->GetVar("serialno", &var), SUCCESS) << "getvar:serialno failed";
322 EXPECT_NE(var, "") << "getvar:serialno can not be empty string";
323 EXPECT_EQ(std::count_if(var.begin(), var.end(), isalnum), var.size())
324 << "getvar:serialno must be alpha-numeric";
325 EXPECT_LE(var.size(), FB_RESPONSE_SZ - 4) << "getvar:serialno response is too long";
326 }
327
TEST_F(Conformance,GetVarSecure)328 TEST_F(Conformance, GetVarSecure) {
329 std::string var;
330 EXPECT_EQ(fb->GetVar("secure", &var), SUCCESS);
331 EXPECT_TRUE(var == "yes" || var == "no");
332 }
333
TEST_F(Conformance,GetVarOffModeCharge)334 TEST_F(Conformance, GetVarOffModeCharge) {
335 std::string var;
336 EXPECT_EQ(fb->GetVar("off-mode-charge", &var), SUCCESS) << "getvar:off-mode-charge failed";
337 EXPECT_TRUE(var == "0" || var == "1") << "getvar:off-mode-charge response must be '0' or '1'";
338 }
339
TEST_F(Conformance,GetVarVariant)340 TEST_F(Conformance, GetVarVariant) {
341 std::string var;
342 EXPECT_EQ(fb->GetVar("variant", &var), SUCCESS) << "getvar:variant failed";
343 EXPECT_NE(var, "") << "getvar:variant response can not be empty";
344 EXPECT_LE(var.size(), FB_RESPONSE_SZ - 4) << "getvar:variant response is too large";
345 }
346
TEST_F(Conformance,GetVarRevision)347 TEST_F(Conformance, GetVarRevision) {
348 std::string var;
349 EXPECT_EQ(fb->GetVar("hw-revision", &var), SUCCESS) << "getvar:hw-revision failed";
350 EXPECT_NE(var, "") << "getvar:battery-voltage response was empty";
351 EXPECT_EQ(std::count_if(var.begin(), var.end(), not_allowed), 0)
352 << "getvar:hw-revision contained illegal ASCII chars";
353 EXPECT_LE(var.size(), FB_RESPONSE_SZ - 4) << "getvar:hw-revision response was too large";
354 }
355
TEST_F(Conformance,GetVarBattVoltage)356 TEST_F(Conformance, GetVarBattVoltage) {
357 std::string var;
358 EXPECT_EQ(fb->GetVar("battery-voltage", &var), SUCCESS) << "getvar:battery-voltage failed";
359 EXPECT_NE(var, "") << "getvar:battery-voltage response was empty";
360 EXPECT_EQ(std::count_if(var.begin(), var.end(), not_allowed), 0)
361 << "getvar:battery-voltage response contains illegal ASCII chars";
362 EXPECT_LE(var.size(), FB_RESPONSE_SZ - 4)
363 << "getvar:battery-voltage response is too large: " + var;
364 }
365
TEST_F(Conformance,GetVarBattVoltageOk)366 TEST_F(Conformance, GetVarBattVoltageOk) {
367 std::string var;
368 EXPECT_EQ(fb->GetVar("battery-soc-ok", &var), SUCCESS) << "getvar:battery-soc-ok failed";
369 EXPECT_TRUE(var == "yes" || var == "no") << "getvar:battery-soc-ok must be 'yes' or 'no'";
370 }
371
TEST_F(Conformance,GetVarDownloadSize)372 TEST_F(Conformance, GetVarDownloadSize) {
373 std::string var;
374 EXPECT_EQ(fb->GetVar("max-download-size", &var), SUCCESS) << "getvar:max-download-size failed";
375 EXPECT_NE(var, "") << "getvar:max-download-size responded with empty string";
376 // This must start with 0x
377 EXPECT_FALSE(isspace(var.front()))
378 << "getvar:max-download-size responded with a string with leading whitespace";
379 EXPECT_FALSE(var.compare(0, 2, "0x"))
380 << "getvar:max-download-size responded with a string that does not start with 0x...";
381 int64_t size = strtoll(var.c_str(), nullptr, 16);
382 EXPECT_GT(size, 0) << "'" + var + "' is not a valid response from getvar:max-download-size";
383 // At most 32-bits
384 EXPECT_LE(size, std::numeric_limits<uint32_t>::max())
385 << "getvar:max-download-size must fit in a uint32_t";
386 EXPECT_LE(var.size(), FB_RESPONSE_SZ - 4)
387 << "getvar:max-download-size responded with too large of string: " + var;
388 }
389
TEST_F(Conformance,GetVarAll)390 TEST_F(Conformance, GetVarAll) {
391 std::vector<std::string> vars;
392 EXPECT_EQ(fb->GetVarAll(&vars), SUCCESS) << "getvar:all failed";
393 EXPECT_GT(vars.size(), 0) << "getvar:all did not respond with any INFO responses";
394 for (const auto& s : vars) {
395 EXPECT_LE(s.size(), FB_RESPONSE_SZ - 4)
396 << "getvar:all included an INFO response: 'INFO" + s << "' which is too long";
397 }
398 }
399
TEST_F(Conformance,UnlockAbility)400 TEST_F(Conformance, UnlockAbility) {
401 std::string resp;
402 std::vector<std::string> info;
403 // Userspace fastboot implementations do not have a way to get this
404 // information.
405 if (UserSpaceFastboot()) {
406 GTEST_LOG_(INFO) << "This test is skipped for userspace fastboot.";
407 return;
408 }
409 EXPECT_EQ(fb->RawCommand("flashing get_unlock_ability", &resp, &info), SUCCESS)
410 << "'flashing get_unlock_ability' failed";
411 // There are two ways this can be reported, through info or the actual response
412 char last;
413 if (!resp.empty()) { // must be in the response
414 last = resp.back();
415 } else { // else must be in info
416 ASSERT_FALSE(info.empty()) << "'flashing get_unlock_ability' returned empty response";
417 ASSERT_FALSE(info.back().empty()) << "Expected non-empty info response";
418 last = info.back().back();
419 }
420 ASSERT_TRUE(last == '1' || last == '0') << "Unlock ability must report '0' or '1' in response";
421 }
422
TEST_F(Conformance,PartitionInfo)423 TEST_F(Conformance, PartitionInfo) {
424 std::vector<std::tuple<std::string, uint64_t>> parts;
425 EXPECT_EQ(fb->Partitions(&parts), SUCCESS) << "getvar:all failed";
426 EXPECT_GT(parts.size(), 0)
427 << "getvar:all did not report any partition-size: through INFO responses";
428 std::set<std::string> allowed{"ext4", "f2fs", "raw"};
429 for (const auto& p : parts) {
430 EXPECT_GE(std::get<1>(p), 0);
431 std::string part(std::get<0>(p));
432 std::set<std::string> allowed{"ext4", "f2fs", "raw"};
433 std::string resp;
434 EXPECT_EQ(fb->GetVar("partition-type:" + part, &resp), SUCCESS);
435 EXPECT_NE(allowed.find(resp), allowed.end()) << "getvar:partition-type:" + part << " was '"
436 << resp << "' this is not a valid type";
437 const std::string cmd = "partition-size:" + part;
438 EXPECT_EQ(fb->GetVar(cmd, &resp), SUCCESS);
439
440 // This must start with 0x
441 EXPECT_FALSE(isspace(resp.front()))
442 << cmd + " responded with a string with leading whitespace";
443 EXPECT_FALSE(resp.compare(0, 2, "0x"))
444 << cmd + "responded with a string that does not start with 0x...";
445 uint64_t size;
446 ASSERT_TRUE(android::base::ParseUint(resp, &size))
447 << "'" + resp + "' is not a valid response from " + cmd;
448 }
449 }
450
TEST_F(Conformance,Slots)451 TEST_F(Conformance, Slots) {
452 std::string var;
453 ASSERT_EQ(fb->GetVar("slot-count", &var), SUCCESS) << "getvar:slot-count failed";
454 ASSERT_EQ(std::count_if(var.begin(), var.end(), isdigit), var.size())
455 << "'" << var << "' is not all digits which it should be for getvar:slot-count";
456 int32_t num_slots = strtol(var.c_str(), nullptr, 10);
457
458 // Can't run out of alphabet letters...
459 ASSERT_LE(num_slots, 26) << "What?! You can't have more than 26 slots";
460
461 std::vector<std::tuple<std::string, uint64_t>> parts;
462 EXPECT_EQ(fb->Partitions(&parts), SUCCESS) << "getvar:all failed";
463
464 std::map<std::string, std::set<char>> part_slots;
465 if (num_slots > 0) {
466 EXPECT_EQ(fb->GetVar("current-slot", &var), SUCCESS) << "getvar:current-slot failed";
467
468 for (const auto& p : parts) {
469 std::string part(std::get<0>(p));
470 std::regex reg("([[:graph:]]*)_([[:lower:]])");
471 std::smatch sm;
472
473 if (std::regex_match(part, sm, reg)) { // This partition has slots
474 std::string part_base(sm[1]);
475 std::string slot(sm[2]);
476 EXPECT_EQ(fb->GetVar("has-slot:" + part_base, &var), SUCCESS)
477 << "'getvar:has-slot:" << part_base << "' failed";
478 EXPECT_EQ(var, "yes") << "'getvar:has-slot:" << part_base << "' was not 'yes'";
479 EXPECT_TRUE(islower(slot.front()))
480 << "'" << slot.front() << "' is an invalid slot-suffix for " << part_base;
481 std::set<char> tmp{slot.front()};
482 part_slots.emplace(part_base, tmp);
483 part_slots.at(part_base).insert(slot.front());
484 } else {
485 EXPECT_EQ(fb->GetVar("has-slot:" + part, &var), SUCCESS)
486 << "'getvar:has-slot:" << part << "' failed";
487 EXPECT_EQ(var, "no") << "'getvar:has-slot:" << part << "' should be no";
488 }
489 }
490 // Ensure each partition has the correct slot suffix
491 for (const auto& iter : part_slots) {
492 const std::set<char>& char_set = iter.second;
493 std::string chars;
494 for (char c : char_set) {
495 chars += c;
496 chars += ',';
497 }
498 EXPECT_EQ(char_set.size(), num_slots)
499 << "There should only be slot suffixes from a to " << 'a' + num_slots - 1
500 << " instead encountered: " << chars;
501 for (const char c : char_set) {
502 EXPECT_GE(c, 'a') << "Encountered invalid slot suffix of '" << c << "'";
503 EXPECT_LT(c, 'a' + num_slots) << "Encountered invalid slot suffix of '" << c << "'";
504 }
505 }
506 }
507 }
508
TEST_F(Conformance,SetActive)509 TEST_F(Conformance, SetActive) {
510 std::string var;
511 ASSERT_EQ(fb->GetVar("slot-count", &var), SUCCESS) << "getvar:slot-count failed";
512 ASSERT_EQ(std::count_if(var.begin(), var.end(), isdigit), var.size())
513 << "'" << var << "' is not all digits which it should be for getvar:slot-count";
514 int32_t num_slots = strtol(var.c_str(), nullptr, 10);
515
516 // Can't run out of alphabet letters...
517 ASSERT_LE(num_slots, 26) << "You can't have more than 26 slots";
518
519 for (char c = 'a'; c < 'a' + num_slots; c++) {
520 const std::string slot(&c, &c + 1);
521 ASSERT_EQ(fb->SetActive(slot), SUCCESS) << "Set active for slot '" << c << "' failed";
522 ASSERT_EQ(fb->GetVar("current-slot", &var), SUCCESS) << "getvar:current-slot failed";
523 EXPECT_EQ(var, slot) << "getvar:current-slot repots incorrect slot after setting it";
524 }
525 }
526
TEST_F(Conformance,LockAndUnlockPrompt)527 TEST_F(Conformance, LockAndUnlockPrompt) {
528 std::string resp;
529 ASSERT_EQ(fb->GetVar("unlocked", &resp), SUCCESS) << "getvar:unlocked failed";
530 ASSERT_TRUE(resp == "yes" || resp == "no")
531 << "Device did not respond with 'yes' or 'no' for getvar:unlocked";
532 bool curr = resp == "yes";
533 if (UserSpaceFastboot()) {
534 GTEST_LOG_(INFO) << "This test is skipped for userspace fastboot.";
535 return;
536 }
537
538 for (int i = 0; i < 2; i++) {
539 std::string action = !curr ? "unlock" : "lock";
540 printf("Device should prompt to '%s' bootloader, select 'no'\n", action.c_str());
541 SetLockState(!curr, false);
542 ASSERT_EQ(fb->GetVar("unlocked", &resp), SUCCESS) << "getvar:unlocked failed";
543 ASSERT_EQ(resp, curr ? "yes" : "no") << "The locked/unlocked state of the bootloader "
544 "incorrectly changed after selecting no";
545 printf("Device should prompt to '%s' bootloader, select 'yes'\n", action.c_str());
546 SetLockState(!curr, true);
547 ASSERT_EQ(fb->GetVar("unlocked", &resp), SUCCESS) << "getvar:unlocked failed";
548 ASSERT_EQ(resp, !curr ? "yes" : "no") << "The locked/unlocked state of the bootloader "
549 "failed to change after selecting yes";
550 curr = !curr;
551 }
552 }
553
TEST_F(Conformance,SparseBlockSupport0)554 TEST_F(Conformance, SparseBlockSupport0) {
555 // The sparse block size can be any multiple of 4
556 std::string var;
557 EXPECT_EQ(fb->GetVar("max-download-size", &var), SUCCESS) << "getvar:max-download-size failed";
558 int64_t size = strtoll(var.c_str(), nullptr, 16);
559
560 // It is reasonable to expect it to handle a single dont care block equal to its DL size
561 for (int64_t bs = 4; bs < size; bs <<= 1) {
562 SparseWrapper sparse(bs, bs);
563 ASSERT_TRUE(*sparse) << "Sparse file creation failed on: " << bs;
564 EXPECT_EQ(fb->Download(*sparse), SUCCESS) << "Download sparse failed: " << sparse.Rep();
565 EXPECT_EQ(fb->Flash("userdata"), SUCCESS) << "Flashing sparse failed: " << sparse.Rep();
566 }
567 }
568
TEST_F(Conformance,SparseBlockSupport1)569 TEST_F(Conformance, SparseBlockSupport1) {
570 // The sparse block size can be any multiple of 4
571 std::string var;
572 EXPECT_EQ(fb->GetVar("max-download-size", &var), SUCCESS) << "getvar:max-download-size failed";
573 int64_t size = strtoll(var.c_str(), nullptr, 16);
574
575 // handle a packed block to half its max download size block
576 for (int64_t bs = 4; bs < size / 2; bs <<= 1) {
577 SparseWrapper sparse(bs, bs);
578 ASSERT_TRUE(*sparse) << "Sparse file creation failed on: " << bs;
579 std::vector<char> buf = RandomBuf(bs);
580 ASSERT_EQ(sparse_file_add_data(*sparse, buf.data(), buf.size(), 0), 0)
581 << "Adding data failed to sparse file: " << sparse.Rep();
582 EXPECT_EQ(fb->Download(*sparse), SUCCESS) << "Download sparse failed: " << sparse.Rep();
583 EXPECT_EQ(fb->Flash("userdata"), SUCCESS) << "Flashing sparse failed: " << sparse.Rep();
584 }
585 }
586
587 // A single don't care download
TEST_F(Conformance,SparseDownload0)588 TEST_F(Conformance, SparseDownload0) {
589 SparseWrapper sparse(4096, 4096);
590 ASSERT_TRUE(*sparse) << "Sparse image creation failed";
591 EXPECT_EQ(fb->Download(*sparse), SUCCESS) << "Download sparse failed: " << sparse.Rep();
592 EXPECT_EQ(fb->Flash("userdata"), SUCCESS) << "Flashing sparse failed: " << sparse.Rep();
593 }
594
TEST_F(Conformance,SparseDownload1)595 TEST_F(Conformance, SparseDownload1) {
596 SparseWrapper sparse(4096, 10 * 4096);
597 ASSERT_TRUE(*sparse) << "Sparse image creation failed";
598 std::vector<char> buf = RandomBuf(4096);
599 ASSERT_EQ(sparse_file_add_data(*sparse, buf.data(), buf.size(), 9), 0)
600 << "Adding data failed to sparse file: " << sparse.Rep();
601 EXPECT_EQ(fb->Download(*sparse), SUCCESS) << "Download sparse failed: " << sparse.Rep();
602 EXPECT_EQ(fb->Flash("userdata"), SUCCESS) << "Flashing sparse failed: " << sparse.Rep();
603 }
604
TEST_F(Conformance,SparseDownload2)605 TEST_F(Conformance, SparseDownload2) {
606 SparseWrapper sparse(4096, 4097);
607 ASSERT_TRUE(*sparse) << "Sparse image creation failed";
608 std::vector<char> buf = RandomBuf(4096);
609 ASSERT_EQ(sparse_file_add_data(*sparse, buf.data(), buf.size(), 0), 0)
610 << "Adding data failed to sparse file: " << sparse.Rep();
611 std::vector<char> buf2 = RandomBuf(1);
612 ASSERT_EQ(sparse_file_add_data(*sparse, buf.data(), buf.size(), 1), 0)
613 << "Adding data failed to sparse file: " << sparse.Rep();
614 EXPECT_EQ(fb->Download(*sparse), SUCCESS) << "Download sparse failed: " << sparse.Rep();
615 EXPECT_EQ(fb->Flash("userdata"), SUCCESS) << "Flashing sparse failed: " << sparse.Rep();
616 }
617
TEST_F(Conformance,SparseDownload3)618 TEST_F(Conformance, SparseDownload3) {
619 std::string var;
620 EXPECT_EQ(fb->GetVar("max-download-size", &var), SUCCESS) << "getvar:max-download-size failed";
621 int size = strtoll(var.c_str(), nullptr, 16);
622
623 SparseWrapper sparse(4096, size);
624 ASSERT_TRUE(*sparse) << "Sparse image creation failed";
625 // Don't want this to take forever
626 unsigned num_chunks = std::min(1000, size / (2 * 4096));
627 for (int i = 0; i < num_chunks; i++) {
628 std::vector<char> buf;
629 int r = random_int(0, 2);
630 // Three cases
631 switch (r) {
632 case 0:
633 break; // Dont Care chunnk
634 case 1: // Buffer
635 buf = RandomBuf(4096);
636 ASSERT_EQ(sparse_file_add_data(*sparse, buf.data(), buf.size(), i), 0)
637 << "Adding data failed to sparse file: " << sparse.Rep();
638 break;
639 case 2: // fill
640 ASSERT_EQ(sparse_file_add_fill(*sparse, 0xdeadbeef, 4096, i), 0)
641 << "Adding fill to sparse file failed: " << sparse.Rep();
642 break;
643 }
644 }
645 EXPECT_EQ(fb->Download(*sparse), SUCCESS) << "Download sparse failed: " << sparse.Rep();
646 EXPECT_EQ(fb->Flash("userdata"), SUCCESS) << "Flashing sparse failed: " << sparse.Rep();
647 }
648
TEST_F(Conformance,SparseVersionCheck)649 TEST_F(Conformance, SparseVersionCheck) {
650 SparseWrapper sparse(4096, 4096);
651 ASSERT_TRUE(*sparse) << "Sparse image creation failed";
652 std::vector<char> buf;
653 ASSERT_TRUE(SparseToBuf(*sparse, &buf)) << "Sparse buffer creation failed";
654 // Invalid, right after magic
655 buf[4] = 0xff;
656 ASSERT_EQ(DownloadCommand(buf.size()), SUCCESS) << "Device rejected download command";
657 ASSERT_EQ(SendBuffer(buf), SUCCESS) << "Downloading payload failed";
658
659 // It can either reject this download or reject it during flash
660 if (HandleResponse() != DEVICE_FAIL) {
661 EXPECT_EQ(fb->Flash("userdata"), DEVICE_FAIL)
662 << "Flashing an invalid sparse version should fail " << sparse.Rep();
663 }
664 }
665
TEST_F(UnlockPermissions,Download)666 TEST_F(UnlockPermissions, Download) {
667 std::vector<char> buf{'a', 'o', 's', 'p'};
668 EXPECT_EQ(fb->Download(buf), SUCCESS) << "Download 4-byte payload failed";
669 }
670
TEST_F(UnlockPermissions,DownloadFlash)671 TEST_F(UnlockPermissions, DownloadFlash) {
672 std::vector<char> buf{'a', 'o', 's', 'p'};
673 EXPECT_EQ(fb->Download(buf), SUCCESS) << "Download failed in unlocked mode";
674 ;
675 std::vector<std::tuple<std::string, uint64_t>> parts;
676 EXPECT_EQ(fb->Partitions(&parts), SUCCESS) << "getvar:all failed in unlocked mode";
677 }
678
TEST_F(LockPermissions,DownloadFlash)679 TEST_F(LockPermissions, DownloadFlash) {
680 std::vector<char> buf{'a', 'o', 's', 'p'};
681 EXPECT_EQ(fb->Download(buf), SUCCESS) << "Download failed in locked mode";
682 std::vector<std::tuple<std::string, uint64_t>> parts;
683 EXPECT_EQ(fb->Partitions(&parts), SUCCESS) << "getvar:all failed in locked mode";
684 std::string resp;
685 for (const auto& tup : parts) {
686 EXPECT_EQ(fb->Flash(std::get<0>(tup), &resp), DEVICE_FAIL)
687 << "Device did not respond with FAIL when trying to flash '" << std::get<0>(tup)
688 << "' in locked mode";
689 EXPECT_GT(resp.size(), 0)
690 << "Device sent empty error message after FAIL"; // meaningful error message
691 }
692 }
693
TEST_F(LockPermissions,Erase)694 TEST_F(LockPermissions, Erase) {
695 std::vector<std::tuple<std::string, uint64_t>> parts;
696 EXPECT_EQ(fb->Partitions(&parts), SUCCESS) << "getvar:all failed";
697 std::string resp;
698 for (const auto& tup : parts) {
699 EXPECT_EQ(fb->Erase(std::get<0>(tup), &resp), DEVICE_FAIL)
700 << "Device did not respond with FAIL when trying to erase '" << std::get<0>(tup)
701 << "' in locked mode";
702 EXPECT_GT(resp.size(), 0) << "Device sent empty error message after FAIL";
703 }
704 }
705
TEST_F(LockPermissions,SetActive)706 TEST_F(LockPermissions, SetActive) {
707 std::vector<std::tuple<std::string, uint64_t>> parts;
708 EXPECT_EQ(fb->Partitions(&parts), SUCCESS) << "getvar:all failed";
709
710 std::string resp;
711 EXPECT_EQ(fb->GetVar("slot-count", &resp), SUCCESS) << "getvar:slot-count failed";
712 int32_t num_slots = strtol(resp.c_str(), nullptr, 10);
713
714 for (const auto& tup : parts) {
715 std::string part(std::get<0>(tup));
716 std::regex reg("([[:graph:]]*)_([[:lower:]])");
717 std::smatch sm;
718
719 if (std::regex_match(part, sm, reg)) { // This partition has slots
720 std::string part_base(sm[1]);
721 for (char c = 'a'; c < 'a' + num_slots; c++) {
722 // We should not be able to SetActive any of these
723 EXPECT_EQ(fb->SetActive(part_base + '_' + c, &resp), DEVICE_FAIL)
724 << "set:active:" << part_base + '_' + c << " did not fail in locked mode";
725 }
726 }
727 }
728 }
729
TEST_F(LockPermissions,Boot)730 TEST_F(LockPermissions, Boot) {
731 std::vector<char> buf;
732 buf.resize(1000);
733 EXPECT_EQ(fb->Download(buf), SUCCESS) << "A 1000 byte download failed";
734 std::string resp;
735 ASSERT_EQ(fb->Boot(&resp), DEVICE_FAIL)
736 << "The device did not respond with failure for 'boot' when locked";
737 EXPECT_GT(resp.size(), 0) << "No error message was returned by device after FAIL";
738 }
739
TEST_F(Fuzz,DownloadSize)740 TEST_F(Fuzz, DownloadSize) {
741 std::string var;
742 EXPECT_EQ(fb->GetVar("max-download-size", &var), SUCCESS) << "getvar:max-download-size failed";
743 int64_t size = strtoll(var.c_str(), nullptr, 0);
744 EXPECT_GT(size, 0) << '\'' << var << "' is not a valid response for getvar:max-download-size";
745
746 EXPECT_EQ(DownloadCommand(size + 1), DEVICE_FAIL)
747 << "Device reported max-download-size as '" << size
748 << "' but did not reject a download of " << size + 1;
749
750 std::vector<char> buf(size);
751 EXPECT_EQ(fb->Download(buf), SUCCESS) << "Device reported max-download-size as '" << size
752 << "' but downloading a payload of this size failed";
753 ASSERT_TRUE(UsbStillAvailible()) << USB_PORT_GONE;
754 }
755
TEST_F(Fuzz,DownloadPartialBuf)756 TEST_F(Fuzz, DownloadPartialBuf) {
757 std::vector<char> buf{'a', 'o', 's', 'p'};
758 ASSERT_EQ(DownloadCommand(buf.size() + 1), SUCCESS)
759 << "Download command for " << buf.size() + 1 << " bytes failed";
760
761 std::string resp;
762 RetCode ret = SendBuffer(buf);
763 EXPECT_EQ(ret, SUCCESS) << "Device did not accept partial payload download";
764 // Send the partial buffer, then cancel it with a reset
765 EXPECT_EQ(transport->Reset(), 0) << "USB reset failed";
766
767 ASSERT_TRUE(UsbStillAvailible()) << USB_PORT_GONE;
768 // The device better still work after all that if we unplug and replug
769 EXPECT_EQ(fb->GetVar("product", &resp), SUCCESS) << "getvar:product failed";
770 }
771
TEST_F(Fuzz,DownloadOverRun)772 TEST_F(Fuzz, DownloadOverRun) {
773 std::vector<char> buf(1000, 'F');
774 ASSERT_EQ(DownloadCommand(10), SUCCESS) << "Device rejected download request for 10 bytes";
775 // There are two ways to handle this
776 // Accept download, but send error response
777 // Reject the download outright
778 std::string resp;
779 RetCode ret = SendBuffer(buf);
780 if (ret == SUCCESS) {
781 // If it accepts the buffer, it better send back an error response
782 EXPECT_EQ(HandleResponse(&resp), DEVICE_FAIL)
783 << "After sending too large of a payload for a download command, device accepted "
784 "payload and did not respond with FAIL";
785 } else {
786 EXPECT_EQ(ret, IO_ERROR) << "After sending too large of a payload for a download command, "
787 "device did not return error";
788 }
789
790 ASSERT_TRUE(UsbStillAvailible()) << USB_PORT_GONE;
791 // The device better still work after all that if we unplug and replug
792 EXPECT_EQ(transport->Reset(), 0) << "USB reset failed";
793 EXPECT_EQ(fb->GetVar("product", &resp), SUCCESS)
794 << "Device did not respond with SUCCESS to getvar:product.";
795 }
796
TEST_F(Fuzz,DownloadInvalid1)797 TEST_F(Fuzz, DownloadInvalid1) {
798 EXPECT_EQ(DownloadCommand(0), DEVICE_FAIL)
799 << "Device did not respond with FAIL for malformed download command 'download:0'";
800 }
801
TEST_F(Fuzz,DownloadInvalid2)802 TEST_F(Fuzz, DownloadInvalid2) {
803 std::string cmd("download:1");
804 EXPECT_EQ(fb->RawCommand("download:1"), DEVICE_FAIL)
805 << "Device did not respond with FAIL for malformed download command '" << cmd << "'";
806 }
807
TEST_F(Fuzz,DownloadInvalid3)808 TEST_F(Fuzz, DownloadInvalid3) {
809 std::string cmd("download:-1");
810 EXPECT_EQ(fb->RawCommand("download:-1"), DEVICE_FAIL)
811 << "Device did not respond with FAIL for malformed download command '" << cmd << "'";
812 }
813
TEST_F(Fuzz,DownloadInvalid4)814 TEST_F(Fuzz, DownloadInvalid4) {
815 std::string cmd("download:-01000000");
816 EXPECT_EQ(fb->RawCommand(cmd), DEVICE_FAIL)
817 << "Device did not respond with FAIL for malformed download command '" << cmd << "'";
818 }
819
TEST_F(Fuzz,DownloadInvalid5)820 TEST_F(Fuzz, DownloadInvalid5) {
821 std::string cmd("download:-0100000");
822 EXPECT_EQ(fb->RawCommand(cmd), DEVICE_FAIL)
823 << "Device did not respond with FAIL for malformed download command '" << cmd << "'";
824 }
825
TEST_F(Fuzz,DownloadInvalid6)826 TEST_F(Fuzz, DownloadInvalid6) {
827 std::string cmd("download:");
828 EXPECT_EQ(fb->RawCommand(cmd), DEVICE_FAIL)
829 << "Device did not respond with FAIL for malformed download command '" << cmd << "'";
830 }
831
TEST_F(Fuzz,DownloadInvalid7)832 TEST_F(Fuzz, DownloadInvalid7) {
833 std::string cmd("download:01000000\0999", sizeof("download:01000000\0999"));
834 EXPECT_EQ(fb->RawCommand(cmd), DEVICE_FAIL)
835 << "Device did not respond with FAIL for malformed download command '" << cmd << "'";
836 }
837
TEST_F(Fuzz,DownloadInvalid8)838 TEST_F(Fuzz, DownloadInvalid8) {
839 std::string cmd("download:01000000\0dkjfvijafdaiuybgidabgybr",
840 sizeof("download:01000000\0dkjfvijafdaiuybgidabgybr"));
841 EXPECT_EQ(fb->RawCommand(cmd), DEVICE_FAIL)
842 << "Device did not respond with FAIL for malformed download command '" << cmd << "'";
843 }
844
TEST_F(Fuzz,GetVarAllSpam)845 TEST_F(Fuzz, GetVarAllSpam) {
846 auto start = std::chrono::high_resolution_clock::now();
847 std::chrono::duration<double> elapsed;
848 unsigned i = 1;
849 do {
850 std::vector<std::string> vars;
851 ASSERT_EQ(fb->GetVarAll(&vars), SUCCESS) << "Device did not respond with success after "
852 << i << "getvar:all commands in a row";
853 ASSERT_GT(vars.size(), 0)
854 << "Device did not send any INFO responses after getvar:all command";
855 elapsed = std::chrono::high_resolution_clock::now() - start;
856 } while (i++, elapsed.count() < 5);
857 }
858
TEST_F(Fuzz,BadCommandTooLarge)859 TEST_F(Fuzz, BadCommandTooLarge) {
860 std::string s = RandomString(FB_COMMAND_SZ + 1, rand_legal);
861 EXPECT_EQ(fb->RawCommand(s), DEVICE_FAIL)
862 << "Device did not respond with failure after sending length " << s.size()
863 << " string of random ASCII chars";
864 std::string s1 = RandomString(1000, rand_legal);
865 EXPECT_EQ(fb->RawCommand(s1), DEVICE_FAIL)
866 << "Device did not respond with failure after sending length " << s1.size()
867 << " string of random ASCII chars";
868 std::string s2 = RandomString(1000, rand_illegal);
869 EXPECT_EQ(fb->RawCommand(s2), DEVICE_FAIL)
870 << "Device did not respond with failure after sending length " << s1.size()
871 << " string of random non-ASCII chars";
872 std::string s3 = RandomString(1000, rand_char);
873 EXPECT_EQ(fb->RawCommand(s3), DEVICE_FAIL)
874 << "Device did not respond with failure after sending length " << s1.size()
875 << " string of random chars";
876 }
877
TEST_F(Fuzz,CommandTooLarge)878 TEST_F(Fuzz, CommandTooLarge) {
879 for (const std::string& s : CMDS) {
880 std::string rs = RandomString(1000, rand_char);
881 EXPECT_EQ(fb->RawCommand(s + rs), DEVICE_FAIL)
882 << "Device did not respond with failure after '" << s + rs << "'";
883 ASSERT_TRUE(UsbStillAvailible()) << USB_PORT_GONE;
884 std::string resp;
885 EXPECT_EQ(fb->GetVar("product", &resp), SUCCESS)
886 << "Device is unresponsive to getvar command";
887 }
888 }
889
TEST_F(Fuzz,CommandMissingArgs)890 TEST_F(Fuzz, CommandMissingArgs) {
891 for (const std::string& s : CMDS) {
892 if (s.back() == ':') {
893 EXPECT_EQ(fb->RawCommand(s), DEVICE_FAIL)
894 << "Device did not respond with failure after '" << s << "'";
895 std::string sub(s.begin(), s.end() - 1);
896 EXPECT_EQ(fb->RawCommand(sub), DEVICE_FAIL)
897 << "Device did not respond with failure after '" << sub << "'";
898 } else {
899 std::string rs = RandomString(10, rand_illegal);
900 EXPECT_EQ(fb->RawCommand(rs + s), DEVICE_FAIL)
901 << "Device did not respond with failure after '" << rs + s << "'";
902 }
903 std::string resp;
904 EXPECT_EQ(fb->GetVar("product", &resp), SUCCESS)
905 << "Device is unresponsive to getvar command";
906 }
907 }
908
TEST_F(Fuzz,SparseZeroLength)909 TEST_F(Fuzz, SparseZeroLength) {
910 SparseWrapper sparse(4096, 0);
911 ASSERT_TRUE(*sparse) << "Sparse image creation failed";
912 RetCode ret = fb->Download(*sparse);
913 // Two ways to handle it
914 if (ret != DEVICE_FAIL) { // if lazily parsed it better fail on a flash
915 EXPECT_EQ(fb->Flash("userdata"), DEVICE_FAIL)
916 << "Flashing zero length sparse image did not fail: " << sparse.Rep();
917 }
918 ret = fb->Download(*sparse, true);
919 if (ret != DEVICE_FAIL) { // if lazily parsed it better fail on a flash
920 EXPECT_EQ(fb->Flash("userdata"), DEVICE_FAIL)
921 << "Flashing zero length sparse image did not fail " << sparse.Rep();
922 }
923 }
924
TEST_F(Fuzz,SparseTooManyChunks)925 TEST_F(Fuzz, SparseTooManyChunks) {
926 SparseWrapper sparse(4096, 4096); // 1 block, but we send two chunks that will use 2 blocks
927 ASSERT_TRUE(*sparse) << "Sparse image creation failed";
928 std::vector<char> buf = RandomBuf(4096);
929 ASSERT_EQ(sparse_file_add_data(*sparse, buf.data(), buf.size(), 0), 0)
930 << "Adding data failed to sparse file: " << sparse.Rep();
931 // We take advantage of the fact the sparse library does not check this
932 ASSERT_EQ(sparse_file_add_fill(*sparse, 0xdeadbeef, 4096, 1), 0)
933 << "Adding fill to sparse file failed: " << sparse.Rep();
934
935 RetCode ret = fb->Download(*sparse);
936 // Two ways to handle it
937 if (ret != DEVICE_FAIL) { // if lazily parsed it better fail on a flash
938 EXPECT_EQ(fb->Flash("userdata"), DEVICE_FAIL)
939 << "Flashing sparse image with 'total_blks' in header 1 too small did not fail "
940 << sparse.Rep();
941 }
942 ret = fb->Download(*sparse, true);
943 if (ret != DEVICE_FAIL) { // if lazily parsed it better fail on a flash
944 EXPECT_EQ(fb->Flash("userdata"), DEVICE_FAIL)
945 << "Flashing sparse image with 'total_blks' in header 1 too small did not fail "
946 << sparse.Rep();
947 }
948 }
949
TEST_F(Fuzz,USBResetSpam)950 TEST_F(Fuzz, USBResetSpam) {
951 auto start = std::chrono::high_resolution_clock::now();
952 std::chrono::duration<double> elapsed;
953 int i = 0;
954 do {
955 ASSERT_EQ(transport->Reset(), 0) << "USB Reset failed after " << i << " resets in a row";
956 elapsed = std::chrono::high_resolution_clock::now() - start;
957 } while (i++, elapsed.count() < 5);
958 std::string resp;
959 EXPECT_EQ(fb->GetVar("product", &resp), SUCCESS)
960 << "getvar failed after " << i << " USB reset(s) in a row";
961 }
962
TEST_F(Fuzz,USBResetCommandSpam)963 TEST_F(Fuzz, USBResetCommandSpam) {
964 auto start = std::chrono::high_resolution_clock::now();
965 std::chrono::duration<double> elapsed;
966 do {
967 std::string resp;
968 std::vector<std::string> all;
969 ASSERT_EQ(transport->Reset(), 0) << "USB Reset failed";
970 EXPECT_EQ(fb->GetVarAll(&all), SUCCESS) << "getvar:all failed after USB reset";
971 EXPECT_EQ(fb->GetVar("product", &resp), SUCCESS) << "getvar:product failed";
972 elapsed = std::chrono::high_resolution_clock::now() - start;
973 } while (elapsed.count() < 10);
974 }
975
TEST_F(Fuzz,USBResetAfterDownload)976 TEST_F(Fuzz, USBResetAfterDownload) {
977 std::vector<char> buf;
978 buf.resize(1000000);
979 EXPECT_EQ(DownloadCommand(buf.size()), SUCCESS) << "Download command failed";
980 EXPECT_EQ(transport->Reset(), 0) << "USB Reset failed";
981 std::vector<std::string> all;
982 EXPECT_EQ(fb->GetVarAll(&all), SUCCESS) << "getvar:all failed after USB reset.";
983 }
984
985 // Getvar XML tests
TEST_P(ExtensionsGetVarConformance,VarExists)986 TEST_P(ExtensionsGetVarConformance, VarExists) {
987 std::string resp;
988 EXPECT_EQ(fb->GetVar(GetParam().first, &resp), SUCCESS);
989 }
990
TEST_P(ExtensionsGetVarConformance,VarMatchesRegex)991 TEST_P(ExtensionsGetVarConformance, VarMatchesRegex) {
992 std::string resp;
993 ASSERT_EQ(fb->GetVar(GetParam().first, &resp), SUCCESS);
994 std::smatch sm;
995 std::regex_match(resp, sm, GetParam().second.regex);
996 EXPECT_FALSE(sm.empty()) << "The regex did not match";
997 }
998
999 INSTANTIATE_TEST_CASE_P(XMLGetVar, ExtensionsGetVarConformance,
1000 ::testing::ValuesIn(GETVAR_XML_TESTS));
1001
TEST_P(AnyPartition,ReportedGetVarAll)1002 TEST_P(AnyPartition, ReportedGetVarAll) {
1003 // As long as the partition is reported in INFO, it would be tested by generic Conformance
1004 std::vector<std::tuple<std::string, uint64_t>> parts;
1005 ASSERT_EQ(fb->Partitions(&parts), SUCCESS) << "getvar:all failed";
1006 const std::string name = GetParam().first;
1007 if (GetParam().second.slots) {
1008 auto matcher = [&](const std::tuple<std::string, uint32_t>& tup) {
1009 return std::get<0>(tup) == name + "_a";
1010 };
1011 EXPECT_NE(std::find_if(parts.begin(), parts.end(), matcher), parts.end())
1012 << "partition '" + name + "_a' not reported in getvar:all";
1013 } else {
1014 auto matcher = [&](const std::tuple<std::string, uint32_t>& tup) {
1015 return std::get<0>(tup) == name;
1016 };
1017 EXPECT_NE(std::find_if(parts.begin(), parts.end(), matcher), parts.end())
1018 << "partition '" + name + "' not reported in getvar:all";
1019 }
1020 }
1021
TEST_P(AnyPartition,Hashable)1022 TEST_P(AnyPartition, Hashable) {
1023 const std::string name = GetParam().first;
1024 if (!config.checksum.empty()) { // We can use hash to validate
1025 for (const auto& part_name : real_parts) {
1026 // Get hash
1027 std::string hash;
1028 int retcode;
1029 std::string err_msg;
1030 if (GetParam().second.hashable) {
1031 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash, &retcode, &err_msg))
1032 << err_msg;
1033 EXPECT_EQ(retcode, 0) << err_msg;
1034 } else { // Make sure it fails
1035 const std::string cmd = config.checksum + ' ' + part_name;
1036 EXPECT_EQ(fb->RawCommand(cmd), DEVICE_FAIL)
1037 << part_name + " is marked as non-hashable, but hashing did not fail";
1038 }
1039 }
1040 }
1041 }
1042
TEST_P(WriteablePartition,FlashCheck)1043 TEST_P(WriteablePartition, FlashCheck) {
1044 const std::string name = GetParam().first;
1045 auto part_info = GetParam().second;
1046
1047 for (const auto& part_name : real_parts) {
1048 std::vector<char> buf = RandomBuf(max_flash, rand_char);
1049 EXPECT_EQ(fb->FlashPartition(part_name, buf), part_info.parsed ? DEVICE_FAIL : SUCCESS)
1050 << "A partition with an image parsed by the bootloader should reject random "
1051 "garbage "
1052 "otherwise it should succeed";
1053 }
1054 }
1055
TEST_P(WriteablePartition,EraseCheck)1056 TEST_P(WriteablePartition, EraseCheck) {
1057 const std::string name = GetParam().first;
1058
1059 for (const auto& part_name : real_parts) {
1060 ASSERT_EQ(fb->Erase(part_name), SUCCESS) << "Erasing " + part_name + " failed";
1061 }
1062 }
1063
TEST_P(WriteHashNonParsedPartition,EraseZerosData)1064 TEST_P(WriteHashNonParsedPartition, EraseZerosData) {
1065 const std::string name = GetParam().first;
1066
1067 for (const auto& part_name : real_parts) {
1068 std::string err_msg;
1069 int retcode;
1070 const std::vector<char> buf = RandomBuf(max_flash, rand_char);
1071 // Partition is too big to write to entire thing
1072 // This can eventually be supported by using sparse images if too large
1073 if (max_flash < part_size) {
1074 std::string hash_before, hash_after;
1075 ASSERT_EQ(fb->FlashPartition(part_name, buf), SUCCESS);
1076 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_before, &retcode, &err_msg))
1077 << err_msg;
1078 ASSERT_EQ(retcode, 0) << err_msg;
1079 ASSERT_EQ(fb->Erase(part_name), SUCCESS) << "Erasing " + part_name + " failed";
1080 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_after, &retcode, &err_msg))
1081 << err_msg;
1082 ASSERT_EQ(retcode, 0) << err_msg;
1083 EXPECT_NE(hash_before, hash_after)
1084 << "The partition hash for " + part_name +
1085 " did not change after erasing a known value";
1086 } else {
1087 std::string hash_zeros, hash_ones, hash_middle, hash_after;
1088 const std::vector<char> buf_zeros(max_flash, 0);
1089 const std::vector<char> buf_ones(max_flash, -1); // All bits are set to 1
1090 ASSERT_EQ(fb->FlashPartition(part_name, buf_zeros), SUCCESS);
1091 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_zeros, &retcode, &err_msg))
1092 << err_msg;
1093 ASSERT_EQ(retcode, 0) << err_msg;
1094 ASSERT_EQ(fb->FlashPartition(part_name, buf_ones), SUCCESS);
1095 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_ones, &retcode, &err_msg))
1096 << err_msg;
1097 ASSERT_EQ(retcode, 0) << err_msg;
1098 ASSERT_NE(hash_zeros, hash_ones)
1099 << "Hashes of partion should not be the same when all bytes are 0xFF or 0x00";
1100 ASSERT_EQ(fb->FlashPartition(part_name, buf), SUCCESS);
1101 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_middle, &retcode, &err_msg))
1102 << err_msg;
1103 ASSERT_EQ(retcode, 0) << err_msg;
1104 ASSERT_NE(hash_zeros, hash_middle)
1105 << "Hashes of partion are the same when all bytes are 0x00 or test payload";
1106 ASSERT_NE(hash_ones, hash_middle)
1107 << "Hashes of partion are the same when all bytes are 0xFF or test payload";
1108 ASSERT_EQ(fb->Erase(part_name), SUCCESS) << "Erasing " + part_name + " failed";
1109 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_after, &retcode, &err_msg))
1110 << err_msg;
1111 ASSERT_EQ(retcode, 0) << err_msg;
1112 EXPECT_TRUE(hash_zeros == hash_after || hash_ones == hash_after)
1113 << "Erasing " + part_name + " should set all the bytes to 0xFF or 0x00";
1114 }
1115 }
1116 }
1117
1118 // Only partitions that we can write and hash (name, fixture), TEST_P is (Fixture, test_name)
1119 INSTANTIATE_TEST_CASE_P(XMLPartitionsWriteHashNonParsed, WriteHashNonParsedPartition,
1120 ::testing::ValuesIn(PARTITION_XML_WRITE_HASH_NONPARSED));
1121
1122 INSTANTIATE_TEST_CASE_P(XMLPartitionsWriteHashable, WriteHashablePartition,
1123 ::testing::ValuesIn(PARTITION_XML_WRITE_HASHABLE));
1124
1125 // only partitions writeable
1126 INSTANTIATE_TEST_CASE_P(XMLPartitionsWriteable, WriteablePartition,
1127 ::testing::ValuesIn(PARTITION_XML_WRITEABLE));
1128
1129 // Every partition
1130 INSTANTIATE_TEST_CASE_P(XMLPartitionsAll, AnyPartition, ::testing::ValuesIn(PARTITION_XML_TESTS));
1131
1132 // Partition Fuzz tests
TEST_P(FuzzWriteablePartition,BoundsCheck)1133 TEST_P(FuzzWriteablePartition, BoundsCheck) {
1134 const std::string name = GetParam().first;
1135 auto part_info = GetParam().second;
1136
1137 for (const auto& part_name : real_parts) {
1138 // try and flash +1 too large, first erase and get a hash, make sure it does not change
1139 std::vector<char> buf = RandomBuf(max_flash + 1); // One too large
1140 if (part_info.hashable) {
1141 std::string hash_before, hash_after, err_msg;
1142 int retcode;
1143 ASSERT_EQ(fb->Erase(part_name), SUCCESS) << "Erasing " + part_name + " failed";
1144 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_before, &retcode, &err_msg))
1145 << err_msg;
1146 ASSERT_EQ(retcode, 0) << err_msg;
1147 EXPECT_EQ(fb->FlashPartition(part_name, buf), DEVICE_FAIL)
1148 << "Flashing an image 1 byte too large to " + part_name + " did not fail";
1149 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_after, &retcode, &err_msg))
1150 << err_msg;
1151 ASSERT_EQ(retcode, 0) << err_msg;
1152 EXPECT_EQ(hash_before, hash_after)
1153 << "Flashing too large of an image resulted in a changed partition hash for " +
1154 part_name;
1155 } else {
1156 EXPECT_EQ(fb->FlashPartition(part_name, buf), DEVICE_FAIL)
1157 << "Flashing an image 1 byte too large to " + part_name + " did not fail";
1158 }
1159 }
1160 }
1161
1162 INSTANTIATE_TEST_CASE_P(XMLFuzzPartitionsWriteable, FuzzWriteablePartition,
1163 ::testing::ValuesIn(PARTITION_XML_WRITEABLE));
1164
1165 // A parsed partition should have magic and such that is checked by the bootloader
1166 // Attempting to flash a random single byte should definately fail
TEST_P(FuzzWriteableParsedPartition,FlashGarbageImageSmall)1167 TEST_P(FuzzWriteableParsedPartition, FlashGarbageImageSmall) {
1168 const std::string name = GetParam().first;
1169 auto part_info = GetParam().second;
1170
1171 for (const auto& part_name : real_parts) {
1172 std::vector<char> buf = RandomBuf(1);
1173 if (part_info.hashable) {
1174 std::string hash_before, hash_after, err_msg;
1175 int retcode;
1176 ASSERT_EQ(fb->Erase(part_name), SUCCESS) << "Erasing " + part_name + " failed";
1177 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_before, &retcode, &err_msg))
1178 << err_msg;
1179 ASSERT_EQ(retcode, 0) << err_msg;
1180 EXPECT_EQ(fb->FlashPartition(part_name, buf), DEVICE_FAIL)
1181 << "A parsed partition should fail on a single byte";
1182 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_after, &retcode, &err_msg))
1183 << err_msg;
1184 ASSERT_EQ(retcode, 0) << err_msg;
1185 EXPECT_EQ(hash_before, hash_after)
1186 << "Flashing a single byte to parsed partition " + part_name +
1187 " should fail and not change the partition hash";
1188 } else {
1189 EXPECT_EQ(fb->FlashPartition(part_name, buf), DEVICE_FAIL)
1190 << "Flashing a 1 byte image to a parsed partition should fail";
1191 }
1192 }
1193 }
1194
TEST_P(FuzzWriteableParsedPartition,FlashGarbageImageLarge)1195 TEST_P(FuzzWriteableParsedPartition, FlashGarbageImageLarge) {
1196 const std::string name = GetParam().first;
1197 auto part_info = GetParam().second;
1198
1199 for (const auto& part_name : real_parts) {
1200 std::vector<char> buf = RandomBuf(max_flash);
1201 if (part_info.hashable) {
1202 std::string hash_before, hash_after, err_msg;
1203 int retcode;
1204 ASSERT_EQ(fb->Erase(part_name), SUCCESS) << "Erasing " + part_name + " failed";
1205 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_before, &retcode, &err_msg))
1206 << err_msg;
1207 ASSERT_EQ(retcode, 0) << err_msg;
1208 EXPECT_EQ(fb->FlashPartition(part_name, buf), DEVICE_FAIL)
1209 << "A parsed partition should not accept randomly generated images";
1210 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_after, &retcode, &err_msg))
1211 << err_msg;
1212 ASSERT_EQ(retcode, 0) << err_msg;
1213 EXPECT_EQ(hash_before, hash_after)
1214 << "The hash of the partition has changed after attempting to flash garbage to "
1215 "a parsed partition";
1216 } else {
1217 EXPECT_EQ(fb->FlashPartition(part_name, buf), DEVICE_FAIL)
1218 << "A parsed partition should not accept randomly generated images";
1219 }
1220 }
1221 }
1222
TEST_P(FuzzWriteableParsedPartition,FlashGarbageImageLarge2)1223 TEST_P(FuzzWriteableParsedPartition, FlashGarbageImageLarge2) {
1224 const std::string name = GetParam().first;
1225 auto part_info = GetParam().second;
1226
1227 for (const auto& part_name : real_parts) {
1228 std::vector<char> buf(max_flash, -1); // All 1's
1229 if (part_info.hashable) {
1230 std::string hash_before, hash_after, err_msg;
1231 int retcode;
1232 ASSERT_EQ(fb->Erase(part_name), SUCCESS) << "Erasing " + part_name + " failed";
1233 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_before, &retcode, &err_msg))
1234 << err_msg;
1235 ASSERT_EQ(retcode, 0) << err_msg;
1236 EXPECT_EQ(fb->FlashPartition(part_name, buf), DEVICE_FAIL)
1237 << "A parsed partition should not accept a image of all 0xFF";
1238 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_after, &retcode, &err_msg))
1239 << err_msg;
1240 ASSERT_EQ(retcode, 0) << err_msg;
1241 EXPECT_EQ(hash_before, hash_after)
1242 << "The hash of the partition has changed after attempting to flash garbage to "
1243 "a parsed partition";
1244 } else {
1245 EXPECT_EQ(fb->FlashPartition(part_name, buf), DEVICE_FAIL)
1246 << "A parsed partition should not accept a image of all 0xFF";
1247 }
1248 }
1249 }
1250
TEST_P(FuzzWriteableParsedPartition,FlashGarbageImageLarge3)1251 TEST_P(FuzzWriteableParsedPartition, FlashGarbageImageLarge3) {
1252 const std::string name = GetParam().first;
1253 auto part_info = GetParam().second;
1254
1255 for (const auto& part_name : real_parts) {
1256 std::vector<char> buf(max_flash, 0); // All 0's
1257 if (part_info.hashable) {
1258 std::string hash_before, hash_after, err_msg;
1259 int retcode;
1260 ASSERT_EQ(fb->Erase(part_name), SUCCESS) << "Erasing " + part_name + " failed";
1261 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_before, &retcode, &err_msg))
1262 << err_msg;
1263 ASSERT_EQ(retcode, 0) << err_msg;
1264 EXPECT_EQ(fb->FlashPartition(part_name, buf), DEVICE_FAIL)
1265 << "A parsed partition should not accept a image of all 0x00";
1266 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_after, &retcode, &err_msg))
1267 << err_msg;
1268 ASSERT_EQ(retcode, 0) << err_msg;
1269 EXPECT_EQ(hash_before, hash_after)
1270 << "The hash of the partition has changed after attempting to flash garbage to "
1271 "a parsed partition";
1272 } else {
1273 EXPECT_EQ(fb->FlashPartition(part_name, buf), DEVICE_FAIL)
1274 << "A parsed partition should not accept a image of all 0x00";
1275 }
1276 }
1277 }
1278
1279 INSTANTIATE_TEST_CASE_P(XMLFuzzPartitionsWriteableParsed, FuzzWriteableParsedPartition,
1280 ::testing::ValuesIn(PARTITION_XML_WRITE_PARSED));
1281
1282 // Make sure all attempts to flash things are rejected
TEST_P(FuzzAnyPartitionLocked,RejectFlash)1283 TEST_P(FuzzAnyPartitionLocked, RejectFlash) {
1284 std::vector<char> buf = RandomBuf(5);
1285 for (const auto& part_name : real_parts) {
1286 ASSERT_EQ(fb->FlashPartition(part_name, buf), DEVICE_FAIL)
1287 << "Flashing a partition should always fail in locked mode";
1288 }
1289 }
1290
1291 INSTANTIATE_TEST_CASE_P(XMLFuzzAnyPartitionLocked, FuzzAnyPartitionLocked,
1292 ::testing::ValuesIn(PARTITION_XML_TESTS));
1293
1294 // Test flashing unlock erases userdata
TEST_P(UserdataPartition,UnlockErases)1295 TEST_P(UserdataPartition, UnlockErases) {
1296 // Get hash after an erase
1297 int retcode;
1298 std::string err_msg, hash_before, hash_buf, hash_after;
1299 ASSERT_EQ(fb->Erase("userdata"), SUCCESS) << "Erasing uesrdata failed";
1300 ASSERT_TRUE(PartitionHash(fb.get(), "userdata", &hash_before, &retcode, &err_msg)) << err_msg;
1301 ASSERT_EQ(retcode, 0) << err_msg;
1302
1303 // Write garbage
1304 std::vector<char> buf = RandomBuf(max_flash / 2);
1305 ASSERT_EQ(fb->FlashPartition("userdata", buf), SUCCESS);
1306 ASSERT_TRUE(PartitionHash(fb.get(), "userdata", &hash_buf, &retcode, &err_msg)) << err_msg;
1307 ASSERT_EQ(retcode, 0) << err_msg;
1308
1309 // Sanity check of hash
1310 EXPECT_NE(hash_before, hash_buf)
1311 << "Writing a random buffer to 'userdata' had the same hash as after erasing it";
1312 SetLockState(true); // Lock the device
1313
1314 SetLockState(false); // Unlock the device (should cause erase)
1315 ASSERT_TRUE(PartitionHash(fb.get(), "userdata", &hash_after, &retcode, &err_msg)) << err_msg;
1316 ASSERT_EQ(retcode, 0) << err_msg;
1317
1318 EXPECT_NE(hash_after, hash_buf) << "Unlocking the device did not cause the hash of userdata to "
1319 "change (i.e. it was not erased as required)";
1320 EXPECT_EQ(hash_after, hash_before) << "Unlocking the device did not produce the same hash of "
1321 "userdata as after doing an erase to userdata";
1322 }
1323
1324 // This is a hack to make this test disapeer if there is not a checsum, userdata is not hashable,
1325 // or userdata is not marked to be writeable in testing
1326 INSTANTIATE_TEST_CASE_P(XMLUserdataLocked, UserdataPartition,
1327 ::testing::ValuesIn(PARTITION_XML_USERDATA_CHECKSUM_WRITEABLE));
1328
1329 // Packed images test
TEST_P(ExtensionsPackedValid,TestDeviceUnpack)1330 TEST_P(ExtensionsPackedValid, TestDeviceUnpack) {
1331 const std::string& packed_name = GetParam().first;
1332 const std::string& packed_image = GetParam().second.packed_img;
1333 const std::string& unpacked = GetParam().second.unpacked_dir;
1334
1335 // First we need to check for existence of images
1336 const extension::Configuration::PackedInfo& info = config.packed[packed_name];
1337
1338 const auto flash_part = [&](const std::string fname, const std::string part_name) {
1339 FILE* to_flash = fopen((SEARCH_PATH + fname).c_str(), "rb");
1340 ASSERT_NE(to_flash, nullptr) << "'" << fname << "'"
1341 << " failed to open for flashing";
1342 int fd = fileno(to_flash);
1343 size_t fsize = lseek(fd, 0, SEEK_END);
1344 ASSERT_GT(fsize, 0) << fname + " appears to be an empty image";
1345 ASSERT_EQ(fb->FlashPartition(part_name, fd, fsize), SUCCESS);
1346 fclose(to_flash);
1347 };
1348
1349 // We first need to set the slot count
1350 std::string var;
1351 int num_slots = 1;
1352 if (info.slots) {
1353 ASSERT_EQ(fb->GetVar("slot-count", &var), SUCCESS) << "Getting slot count failed";
1354 num_slots = strtol(var.c_str(), nullptr, 10);
1355 } else {
1356 for (const auto& part : info.children) {
1357 EXPECT_FALSE(config.partitions[part].slots)
1358 << "A partition can not have slots if the packed image does not";
1359 }
1360 }
1361
1362 for (int i = 0; i < num_slots; i++) {
1363 std::unordered_map<std::string, std::string> initial_hashes;
1364 const std::string packed_suffix =
1365 info.slots ? android::base::StringPrintf("_%c", 'a' + i) : "";
1366
1367 // Flash the paritions manually and get hash
1368 for (const auto& part : info.children) {
1369 const extension::Configuration::PartitionInfo& part_info = config.partitions[part];
1370 const std::string suffix = part_info.slots ? packed_suffix : "";
1371 const std::string part_name = part + suffix;
1372
1373 ASSERT_EQ(fb->Erase(part_name), SUCCESS);
1374 const std::string fpath = unpacked + '/' + part + ".img";
1375 ASSERT_NO_FATAL_FAILURE(flash_part(fpath, part_name))
1376 << "Failed to flash '" + fpath + "'";
1377 // If the partition is hashable we store it
1378 if (part_info.hashable) {
1379 std::string hash, err_msg;
1380 int retcode;
1381 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash, &retcode, &err_msg))
1382 << err_msg;
1383 ASSERT_EQ(retcode, 0) << err_msg;
1384 initial_hashes[part] = hash;
1385 }
1386 }
1387
1388 // erase once at the end, to avoid false positives if flashing does nothing
1389 for (const auto& part : info.children) {
1390 const std::string suffix = config.partitions[part].slots ? packed_suffix : "";
1391 ASSERT_EQ(fb->Erase(part + suffix), SUCCESS);
1392 }
1393
1394 // Now we flash the packed image and compare our hashes
1395 ASSERT_NO_FATAL_FAILURE(flash_part(packed_image, packed_name + packed_suffix));
1396
1397 for (const auto& part : info.children) {
1398 const extension::Configuration::PartitionInfo& part_info = config.partitions[part];
1399 // If the partition is hashable we check it
1400 if (part_info.hashable) {
1401 const std::string suffix = part_info.slots ? packed_suffix : "";
1402 const std::string part_name = part + suffix;
1403 std::string hash, err_msg;
1404 int retcode;
1405 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash, &retcode, &err_msg))
1406 << err_msg;
1407 ASSERT_EQ(retcode, 0) << err_msg;
1408 std::string msg =
1409 "The hashes between flashing the packed image and directly flashing '" +
1410 part_name + "' does not match";
1411 EXPECT_EQ(hash, initial_hashes[part]) << msg;
1412 }
1413 }
1414 }
1415 }
1416
1417 INSTANTIATE_TEST_CASE_P(XMLTestPacked, ExtensionsPackedValid,
1418 ::testing::ValuesIn(PACKED_XML_SUCCESS_TESTS));
1419
1420 // Packed images test
TEST_P(ExtensionsPackedInvalid,TestDeviceUnpack)1421 TEST_P(ExtensionsPackedInvalid, TestDeviceUnpack) {
1422 const std::string& packed_name = GetParam().first;
1423 const std::string& packed_image = GetParam().second.packed_img;
1424
1425 // First we need to check for existence of images
1426 const extension::Configuration::PackedInfo& info = config.packed[packed_name];
1427
1428 // We first need to set the slot count
1429 std::string var;
1430 int num_slots = 1;
1431 if (info.slots) {
1432 ASSERT_EQ(fb->GetVar("slot-count", &var), SUCCESS) << "Getting slot count failed";
1433 num_slots = strtol(var.c_str(), nullptr, 10);
1434 } else {
1435 for (const auto& part : info.children) {
1436 EXPECT_FALSE(config.partitions[part].slots)
1437 << "A partition can not have slots if the packed image does not";
1438 }
1439 }
1440
1441 for (int i = 0; i < num_slots; i++) {
1442 std::unordered_map<std::string, std::string> initial_hashes;
1443 const std::string packed_suffix =
1444 info.slots ? android::base::StringPrintf("_%c", 'a' + i) : "";
1445
1446 // manually and get hash
1447 for (const auto& part : info.children) {
1448 const extension::Configuration::PartitionInfo& part_info = config.partitions[part];
1449 const std::string suffix = part_info.slots ? packed_suffix : "";
1450 const std::string part_name = part + suffix;
1451
1452 // If the partition is hashable we store it
1453 if (part_info.hashable) {
1454 std::string hash, err_msg;
1455 int retcode;
1456 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash, &retcode, &err_msg))
1457 << err_msg;
1458 ASSERT_EQ(retcode, 0) << err_msg;
1459 initial_hashes[part] = hash;
1460 }
1461 }
1462
1463 // Attempt to flash the invalid file
1464 FILE* to_flash = fopen((SEARCH_PATH + packed_image).c_str(), "rb");
1465 ASSERT_NE(to_flash, nullptr) << "'" << packed_image << "'"
1466 << " failed to open for flashing";
1467 int fd = fileno(to_flash);
1468 size_t fsize = lseek(fd, 0, SEEK_END);
1469 ASSERT_GT(fsize, 0) << packed_image + " appears to be an empty image";
1470 ASSERT_EQ(fb->FlashPartition(packed_name + packed_suffix, fd, fsize), DEVICE_FAIL)
1471 << "Expected flashing to fail for " + packed_image;
1472 fclose(to_flash);
1473
1474 for (const auto& part : info.children) {
1475 const extension::Configuration::PartitionInfo& part_info = config.partitions[part];
1476 // If the partition is hashable we check it
1477 if (part_info.hashable) {
1478 const std::string suffix = part_info.slots ? packed_suffix : "";
1479 const std::string part_name = part + suffix;
1480 std::string hash, err_msg;
1481 int retcode;
1482 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash, &retcode, &err_msg))
1483 << err_msg;
1484 ASSERT_EQ(retcode, 0) << err_msg;
1485 std::string msg = "Flashing an invalid image changed the hash of '" + part_name;
1486 EXPECT_EQ(hash, initial_hashes[part]) << msg;
1487 }
1488 }
1489 }
1490 }
1491
1492 INSTANTIATE_TEST_CASE_P(XMLTestPacked, ExtensionsPackedInvalid,
1493 ::testing::ValuesIn(PACKED_XML_FAIL_TESTS));
1494
1495 // OEM xml tests
TEST_P(ExtensionsOemConformance,RunOEMTest)1496 TEST_P(ExtensionsOemConformance, RunOEMTest) {
1497 const std::string& cmd = std::get<0>(GetParam());
1498 // bool restricted = std::get<1>(GetParam());
1499 const extension::Configuration::CommandTest& test = std::get<2>(GetParam());
1500
1501 const RetCode expect = (test.expect == extension::FAIL) ? DEVICE_FAIL : SUCCESS;
1502
1503 // Does the test require staging something?
1504 if (!test.input.empty()) { // Non-empty string
1505 FILE* to_stage = fopen((SEARCH_PATH + test.input).c_str(), "rb");
1506 ASSERT_NE(to_stage, nullptr) << "'" << test.input << "'"
1507 << " failed to open for staging";
1508 int fd = fileno(to_stage);
1509 size_t fsize = lseek(fd, 0, SEEK_END);
1510 std::string var;
1511 EXPECT_EQ(fb->GetVar("max-download-size", &var), SUCCESS);
1512 int64_t size = strtoll(var.c_str(), nullptr, 16);
1513 EXPECT_LT(fsize, size) << "'" << test.input << "'"
1514 << " is too large for staging";
1515 ASSERT_EQ(fb->Download(fd, fsize), SUCCESS) << "'" << test.input << "'"
1516 << " failed to download for staging";
1517 fclose(to_stage);
1518 }
1519 // Run the command
1520 int dsize = -1;
1521 std::string resp;
1522 const std::string full_cmd = "oem " + cmd + " " + test.arg;
1523 ASSERT_EQ(fb->RawCommand(full_cmd, &resp, nullptr, &dsize), expect);
1524
1525 // This is how we test if indeed data response
1526 if (test.expect == extension::DATA) {
1527 EXPECT_GT(dsize, 0);
1528 }
1529
1530 // Validate response if neccesary
1531 if (!test.regex_str.empty()) {
1532 std::smatch sm;
1533 std::regex_match(resp, sm, test.regex);
1534 EXPECT_FALSE(sm.empty()) << "The oem regex did not match";
1535 }
1536
1537 // If payload, we validate that as well
1538 const std::vector<std::string> args = SplitBySpace(test.validator);
1539 if (args.size()) {
1540 // Save output
1541 const std::string save_loc =
1542 OUTPUT_PATH + (test.output.empty() ? DEFAULT_OUPUT_NAME : test.output);
1543 std::string resp;
1544 ASSERT_EQ(fb->Upload(save_loc, &resp), SUCCESS)
1545 << "Saving output file failed with (" << fb->Error() << ") " << resp;
1546 // Build the arguments to the validator
1547 std::vector<std::string> prog_args(args.begin() + 1, args.end());
1548 prog_args.push_back(full_cmd); // Pass in the full command
1549 prog_args.push_back(save_loc); // Pass in the save location
1550 // Run the validation program
1551 int pipe;
1552 const pid_t pid = StartProgram(args[0], prog_args, &pipe);
1553 ASSERT_GT(pid, 0) << "Failed to launch validation program: " << args[0];
1554 std::string error_msg;
1555 int ret = WaitProgram(pid, pipe, &error_msg);
1556 EXPECT_EQ(ret, 0) << error_msg; // Program exited correctly
1557 }
1558 }
1559
1560 INSTANTIATE_TEST_CASE_P(XMLOEM, ExtensionsOemConformance, ::testing::ValuesIn(OEM_XML_TESTS));
1561
1562 // Sparse Tests
TEST_P(SparseTestPartition,SparseSingleBlock)1563 TEST_P(SparseTestPartition, SparseSingleBlock) {
1564 const std::string name = GetParam().first;
1565 auto part_info = GetParam().second;
1566 const std::string part_name = name + (part_info.slots ? "_a" : "");
1567 SparseWrapper sparse(4096, 4096);
1568 ASSERT_TRUE(*sparse) << "Sparse image creation failed";
1569 std::vector<char> buf = RandomBuf(4096);
1570 ASSERT_EQ(sparse_file_add_data(*sparse, buf.data(), buf.size(), 0), 0)
1571 << "Adding data failed to sparse file: " << sparse.Rep();
1572
1573 EXPECT_EQ(fb->Download(*sparse), SUCCESS) << "Download sparse failed: " << sparse.Rep();
1574 EXPECT_EQ(fb->Flash(part_name), SUCCESS) << "Flashing sparse failed: " << sparse.Rep();
1575 std::string hash, hash_new, err_msg;
1576 int retcode;
1577 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash, &retcode, &err_msg)) << err_msg;
1578 ASSERT_EQ(retcode, 0) << err_msg;
1579 // Now flash it the non-sparse way
1580 EXPECT_EQ(fb->FlashPartition(part_name, buf), SUCCESS) << "Flashing image failed: ";
1581 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_new, &retcode, &err_msg)) << err_msg;
1582 ASSERT_EQ(retcode, 0) << err_msg;
1583
1584 EXPECT_EQ(hash, hash_new) << "Flashing a random buffer of 4096 using sparse and non-sparse "
1585 "methods did not result in the same hash";
1586 }
1587
TEST_P(SparseTestPartition,SparseFill)1588 TEST_P(SparseTestPartition, SparseFill) {
1589 const std::string name = GetParam().first;
1590 auto part_info = GetParam().second;
1591 const std::string part_name = name + (part_info.slots ? "_a" : "");
1592 int64_t size = (max_dl / 4096) * 4096;
1593 SparseWrapper sparse(4096, size);
1594 ASSERT_TRUE(*sparse) << "Sparse image creation failed";
1595 ASSERT_EQ(sparse_file_add_fill(*sparse, 0xdeadbeef, size, 0), 0)
1596 << "Adding data failed to sparse file: " << sparse.Rep();
1597
1598 EXPECT_EQ(fb->Download(*sparse), SUCCESS) << "Download sparse failed: " << sparse.Rep();
1599 EXPECT_EQ(fb->Flash(part_name), SUCCESS) << "Flashing sparse failed: " << sparse.Rep();
1600 std::string hash, hash_new, err_msg;
1601 int retcode;
1602 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash, &retcode, &err_msg)) << err_msg;
1603 ASSERT_EQ(retcode, 0) << err_msg;
1604 // Now flash it the non-sparse way
1605 std::vector<char> buf(size);
1606 for (auto iter = buf.begin(); iter < buf.end(); iter += 4) {
1607 iter[0] = 0xef;
1608 iter[1] = 0xbe;
1609 iter[2] = 0xad;
1610 iter[3] = 0xde;
1611 }
1612 EXPECT_EQ(fb->FlashPartition(part_name, buf), SUCCESS) << "Flashing image failed: ";
1613 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_new, &retcode, &err_msg)) << err_msg;
1614 ASSERT_EQ(retcode, 0) << err_msg;
1615
1616 EXPECT_EQ(hash, hash_new) << "Flashing a random buffer of 4096 using sparse and non-sparse "
1617 "methods did not result in the same hash";
1618 }
1619
1620 // This tests to make sure it does not overwrite previous flashes
TEST_P(SparseTestPartition,SparseMultiple)1621 TEST_P(SparseTestPartition, SparseMultiple) {
1622 const std::string name = GetParam().first;
1623 auto part_info = GetParam().second;
1624 const std::string part_name = name + (part_info.slots ? "_a" : "");
1625 int64_t size = (max_dl / 4096) * 4096;
1626 SparseWrapper sparse(4096, size / 2);
1627 ASSERT_TRUE(*sparse) << "Sparse image creation failed";
1628 ASSERT_EQ(sparse_file_add_fill(*sparse, 0xdeadbeef, size / 2, 0), 0)
1629 << "Adding data failed to sparse file: " << sparse.Rep();
1630 EXPECT_EQ(fb->Download(*sparse), SUCCESS) << "Download sparse failed: " << sparse.Rep();
1631 EXPECT_EQ(fb->Flash(part_name), SUCCESS) << "Flashing sparse failed: " << sparse.Rep();
1632
1633 SparseWrapper sparse2(4096, size / 2);
1634 ASSERT_TRUE(*sparse) << "Sparse image creation failed";
1635 std::vector<char> buf = RandomBuf(size / 2);
1636 ASSERT_EQ(sparse_file_add_data(*sparse2, buf.data(), buf.size(), (size / 2) / 4096), 0)
1637 << "Adding data failed to sparse file: " << sparse2.Rep();
1638 EXPECT_EQ(fb->Download(*sparse2), SUCCESS) << "Download sparse failed: " << sparse2.Rep();
1639 EXPECT_EQ(fb->Flash(part_name), SUCCESS) << "Flashing sparse failed: " << sparse2.Rep();
1640
1641 std::string hash, hash_new, err_msg;
1642 int retcode;
1643 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash, &retcode, &err_msg)) << err_msg;
1644 ASSERT_EQ(retcode, 0) << err_msg;
1645 // Now flash it the non-sparse way
1646 std::vector<char> fbuf(size);
1647 for (auto iter = fbuf.begin(); iter < fbuf.begin() + size / 2; iter += 4) {
1648 iter[0] = 0xef;
1649 iter[1] = 0xbe;
1650 iter[2] = 0xad;
1651 iter[3] = 0xde;
1652 }
1653 fbuf.assign(buf.begin(), buf.end());
1654 EXPECT_EQ(fb->FlashPartition(part_name, fbuf), SUCCESS) << "Flashing image failed: ";
1655 ASSERT_TRUE(PartitionHash(fb.get(), part_name, &hash_new, &retcode, &err_msg)) << err_msg;
1656 ASSERT_EQ(retcode, 0) << err_msg;
1657
1658 EXPECT_EQ(hash, hash_new) << "Flashing a random buffer of 4096 using sparse and non-sparse "
1659 "methods did not result in the same hash";
1660 }
1661
1662 INSTANTIATE_TEST_CASE_P(XMLSparseTest, SparseTestPartition,
1663 ::testing::ValuesIn(SINGLE_PARTITION_XML_WRITE_HASHABLE));
1664
GenerateXmlTests(const extension::Configuration & config)1665 void GenerateXmlTests(const extension::Configuration& config) {
1666 // Build the getvar tests
1667 for (const auto& it : config.getvars) {
1668 GETVAR_XML_TESTS.push_back(std::make_pair(it.first, it.second));
1669 }
1670
1671 // Build the partition tests, to interface with gtest we need to do it this way
1672 for (const auto& it : config.partitions) {
1673 const auto tup = std::make_tuple(it.first, it.second);
1674 PARTITION_XML_TESTS.push_back(tup); // All partitions
1675
1676 if (it.second.test == it.second.YES) {
1677 PARTITION_XML_WRITEABLE.push_back(tup); // All writeable partitions
1678
1679 if (it.second.hashable) {
1680 PARTITION_XML_WRITE_HASHABLE.push_back(tup); // All write and hashable
1681 if (!it.second.parsed) {
1682 PARTITION_XML_WRITE_HASH_NONPARSED.push_back(
1683 tup); // All write hashed and non-parsed
1684 }
1685 }
1686 if (it.second.parsed) {
1687 PARTITION_XML_WRITE_PARSED.push_back(tup); // All write and parsed
1688 }
1689 }
1690 }
1691
1692 // Build the packed tests, only useful if we have a hash
1693 if (!config.checksum.empty()) {
1694 for (const auto& it : config.packed) {
1695 for (const auto& test : it.second.tests) {
1696 const auto tup = std::make_tuple(it.first, test);
1697 if (test.expect == extension::OKAY) { // only testing the success case
1698 PACKED_XML_SUCCESS_TESTS.push_back(tup);
1699 } else {
1700 PACKED_XML_FAIL_TESTS.push_back(tup);
1701 }
1702 }
1703 }
1704 }
1705
1706 // This is a hack to make this test disapeer if there is not a checksum, userdata is not
1707 // hashable, or userdata is not marked to be writeable in testing
1708 const auto part_info = config.partitions.find("userdata");
1709 if (!config.checksum.empty() && part_info != config.partitions.end() &&
1710 part_info->second.hashable &&
1711 part_info->second.test == extension::Configuration::PartitionInfo::YES) {
1712 PARTITION_XML_USERDATA_CHECKSUM_WRITEABLE.push_back(
1713 std::make_tuple(part_info->first, part_info->second));
1714 }
1715
1716 if (!PARTITION_XML_WRITE_HASHABLE.empty()) {
1717 SINGLE_PARTITION_XML_WRITE_HASHABLE.push_back(PARTITION_XML_WRITE_HASHABLE.front());
1718 }
1719
1720 // Build oem tests
1721 for (const auto& it : config.oem) {
1722 auto oem_cmd = it.second;
1723 for (const auto& t : oem_cmd.tests) {
1724 OEM_XML_TESTS.push_back(std::make_tuple(it.first, oem_cmd.restricted, t));
1725 }
1726 }
1727 }
1728
1729 } // namespace fastboot
1730
main(int argc,char ** argv)1731 int main(int argc, char** argv) {
1732 std::string err;
1733 // Parse the args
1734 const std::unordered_map<std::string, std::string> args = fastboot::ParseArgs(argc, argv, &err);
1735 if (!err.empty()) {
1736 printf("%s\n", err.c_str());
1737 return -1;
1738 }
1739
1740 if (args.find("config") != args.end()) {
1741 auto found = args.find("search_path");
1742 fastboot::SEARCH_PATH = (found != args.end()) ? found->second + "/" : "";
1743 found = args.find("output_path");
1744 fastboot::OUTPUT_PATH = (found != args.end()) ? found->second + "/" : "/tmp/";
1745 if (!fastboot::extension::ParseXml(fastboot::SEARCH_PATH + args.at("config"),
1746 &fastboot::config)) {
1747 printf("XML config parsing failed\n");
1748 return -1;
1749 }
1750 // To interface with gtest, must set global scope test variables
1751 fastboot::GenerateXmlTests(fastboot::config);
1752 }
1753
1754 if (args.find("serial") != args.end()) {
1755 fastboot::FastBootTest::device_serial = args.at("serial");
1756 }
1757
1758 setbuf(stdout, NULL); // no buffering
1759 printf("<Waiting for Device>\n");
1760 const auto matcher = [](usb_ifc_info* info) -> int {
1761 return fastboot::FastBootTest::MatchFastboot(info, fastboot::FastBootTest::device_serial);
1762 };
1763 Transport* transport = nullptr;
1764 while (!transport) {
1765 transport = usb_open(matcher);
1766 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1767 }
1768 transport->Close();
1769
1770 if (args.find("serial_port") != args.end()) {
1771 fastboot::FastBootTest::serial_port = fastboot::ConfigureSerial(args.at("serial_port"));
1772 }
1773
1774 ::testing::InitGoogleTest(&argc, argv);
1775 auto ret = RUN_ALL_TESTS();
1776 if (fastboot::FastBootTest::serial_port > 0) {
1777 close(fastboot::FastBootTest::serial_port);
1778 }
1779 return ret;
1780 }
1781