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