1 // Copyright 2018 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <lib/inspect/scanner.h>
6 #include <unittest/unittest.h>
7 #include <zircon/types.h>
8 
9 namespace {
10 
11 using inspect::BlockType;
12 using inspect::internal::Block;
13 using inspect::internal::BlockIndex;
14 using inspect::internal::ScanBlocks;
15 
ReadEmpty()16 bool ReadEmpty() {
17     BEGIN_TEST;
18 
19     uint8_t buf[1024];
20     memset(buf, 0, 1024);
21 
22     int count = 0;
23     EXPECT_TRUE(ZX_OK ==
24                 ScanBlocks(buf, 1024, [&count](BlockIndex index, const Block* block) { count++; }));
25     EXPECT_EQ(1024 / inspect::kMinOrderSize, count);
26 
27     END_TEST;
28 }
29 
ReadMisaligned()30 bool ReadMisaligned() {
31     BEGIN_TEST;
32 
33     uint8_t buf[1020];
34     memset(buf, 0, 1020);
35 
36     int count = 0;
37     EXPECT_TRUE(ZX_ERR_OUT_OF_RANGE ==
38                 ScanBlocks(buf, 1020, [&count](BlockIndex index, const Block* block) { count++; }));
39     EXPECT_EQ(1024 / inspect::kMinOrderSize - 1, count);
40 
41     END_TEST;
42 }
43 
ReadSingle()44 bool ReadSingle() {
45     BEGIN_TEST;
46 
47     uint8_t buf[inspect::kMinOrderSize];
48     memset(buf, 0, inspect::kMinOrderSize);
49 
50     int count = 0;
51     BlockIndex last_index = 0xFFFFFF;
52     EXPECT_TRUE(ZX_OK ==
53                 ScanBlocks(buf, inspect::kMinOrderSize, [&](BlockIndex index, const Block* block) {
54                     count++;
55                     last_index = index;
56                 }));
57     EXPECT_EQ(1, count);
58     EXPECT_EQ(0, last_index);
59 
60     END_TEST;
61 }
62 
ReadOutOfBounds()63 bool ReadOutOfBounds() {
64     BEGIN_TEST;
65 
66     uint8_t buf[inspect::kMinOrderSize];
67     memset(buf, 0, inspect::kMinOrderSize);
68     Block* block = reinterpret_cast<Block*>(buf);
69     block->header = inspect::internal::BlockFields::Order::Make(1);
70 
71     int count = 0;
72     EXPECT_TRUE(ZX_ERR_OUT_OF_RANGE ==
73                 ScanBlocks(buf, inspect::kMinOrderSize,
74                            [&count](BlockIndex index, const Block* block) { count++; }));
75     EXPECT_EQ(0, count);
76 
77     END_TEST;
78 }
79 
80 } // namespace
81 
82 BEGIN_TEST_CASE(ScannerTests)
83 RUN_TEST(ReadEmpty)
84 RUN_TEST(ReadMisaligned)
85 RUN_TEST(ReadSingle)
86 RUN_TEST(ReadOutOfBounds)
87 END_TEST_CASE(ScannerTests)
88