51d8531db9baff7e8546278d6c5da9dc13c57b45
[folly.git] / folly / experimental / symbolizer / test / ElfTests.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/experimental/symbolizer/Elf.h>
18 #include <folly/portability/GTest.h>
19
20 using folly::symbolizer::ElfFile;
21
22 // Add some symbols for testing. Note that we have to be careful with type
23 // signatures here to prevent name mangling
24 uint64_t kIntegerValue = 1234567890UL;
25 const char* kStringValue = "coconuts";
26
27 class ElfTest : public ::testing::Test {
28  public:
29   // Path to the test binary itself; set by main()
30   static std::string binaryPath;
31
32   ElfTest() : elfFile_(binaryPath.c_str()) {}
33   ~ElfTest() override {}
34
35  protected:
36   ElfFile elfFile_;
37 };
38
39 std::string ElfTest::binaryPath;
40
41 TEST_F(ElfTest, IntegerValue) {
42   auto sym = elfFile_.getSymbolByName("kIntegerValue");
43   EXPECT_NE(nullptr, sym.first) << "Failed to look up symbol kIntegerValue";
44   EXPECT_EQ(kIntegerValue, elfFile_.getSymbolValue<uint64_t>(sym.second));
45 }
46
47 TEST_F(ElfTest, PointerValue) {
48   auto sym = elfFile_.getSymbolByName("kStringValue");
49   EXPECT_NE(nullptr, sym.first) << "Failed to look up symbol kStringValue";
50   ElfW(Addr) addr = elfFile_.getSymbolValue<ElfW(Addr)>(sym.second);
51   const char* str = &elfFile_.getAddressValue<const char>(addr);
52   EXPECT_STREQ(kStringValue, str);
53 }
54
55 TEST_F(ElfTest, iterateProgramHeaders) {
56   auto phdr = elfFile_.iterateProgramHeaders(
57       [](auto& h) { return h.p_type == PT_LOAD; });
58   EXPECT_NE(nullptr, phdr);
59   EXPECT_GE(phdr->p_filesz, 0);
60 }
61
62 int main(int argc, char** argv) {
63   testing::InitGoogleTest(&argc, argv);
64   gflags::ParseCommandLineFlags(&argc, &argv, true);
65   ElfTest::binaryPath = argv[0];
66   return RUN_ALL_TESTS();
67 }