2 * Copyright 2013-present Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/FileUtil.h>
18 #include <folly/experimental/TestUtil.h>
19 #include <folly/experimental/symbolizer/Elf.h>
20 #include <folly/portability/GTest.h>
22 using folly::symbolizer::ElfFile;
24 // Add some symbols for testing. Note that we have to be careful with type
25 // signatures here to prevent name mangling
26 uint64_t kIntegerValue = 1234567890UL;
27 const char* kStringValue = "coconuts";
29 class ElfTest : public ::testing::Test {
31 ElfFile elfFile_{"/proc/self/exe"};
34 TEST_F(ElfTest, IntegerValue) {
35 auto sym = elfFile_.getSymbolByName("kIntegerValue");
36 EXPECT_NE(nullptr, sym.first) << "Failed to look up symbol kIntegerValue";
37 EXPECT_EQ(kIntegerValue, elfFile_.getSymbolValue<uint64_t>(sym.second));
40 TEST_F(ElfTest, PointerValue) {
41 auto sym = elfFile_.getSymbolByName("kStringValue");
42 EXPECT_NE(nullptr, sym.first) << "Failed to look up symbol kStringValue";
43 ElfW(Addr) addr = elfFile_.getSymbolValue<ElfW(Addr)>(sym.second);
44 const char* str = &elfFile_.getAddressValue<const char>(addr);
45 EXPECT_STREQ(kStringValue, str);
48 TEST_F(ElfTest, iterateProgramHeaders) {
49 auto phdr = elfFile_.iterateProgramHeaders(
50 [](auto& h) { return h.p_type == PT_LOAD; });
51 EXPECT_NE(nullptr, phdr);
52 EXPECT_GE(phdr->p_filesz, 0);
55 TEST_F(ElfTest, TinyNonElfFile) {
56 folly::test::TemporaryFile tmpFile;
57 const static folly::StringPiece contents = "!";
58 folly::writeFull(tmpFile.fd(), contents.data(), contents.size());
61 const char* msg = nullptr;
62 auto res = elfFile.openNoThrow(tmpFile.path().c_str(), true, &msg);
63 EXPECT_EQ(ElfFile::kInvalidElfFile, res);
64 EXPECT_STREQ("not an ELF file (too short)", msg);
67 TEST_F(ElfTest, NonElfScript) {
68 folly::test::TemporaryFile tmpFile;
69 const static folly::StringPiece contents =
70 "#!/bin/sh\necho I'm small non-ELF executable\n";
71 folly::writeFull(tmpFile.fd(), contents.data(), contents.size());
74 const char* msg = nullptr;
75 auto res = elfFile.openNoThrow(tmpFile.path().c_str(), true, &msg);
76 EXPECT_EQ(ElfFile::kInvalidElfFile, res);
77 EXPECT_STREQ("invalid ELF magic", msg);