Merge pull request #89 from sethml/feature/improved-DWARFv4
[pyelftools.git] / test / test_get_symbol_by_name.py
1 # Tests the functionality of the ELF file function `get_symbol_by_name`.
2
3 try:
4 import unittest2 as unittest
5 except ImportError:
6 import unittest
7 import os
8
9 from utils import setup_syspath; setup_syspath()
10 from elftools.elf.elffile import ELFFile
11
12 class TestGetSymbolByName(unittest.TestCase):
13 def test_existing_symbol(self):
14 with open(os.path.join('test', 'testfiles_for_unittests',
15 'simple_gcc.elf.arm'), 'rb') as f:
16 elf = ELFFile(f)
17
18 # Find the symbol table.
19 symtab = elf.get_section_by_name('.symtab')
20 self.assertIsNotNone(symtab)
21
22 # Test we can find a symbol by its name.
23 mains = symtab.get_symbol_by_name('main')
24 self.assertIsNotNone(mains)
25
26 # Test it is actually the symbol we expect.
27 self.assertIsInstance(mains, list)
28 self.assertEqual(len(mains), 1)
29 main = mains[0]
30 self.assertEqual(main.name, 'main')
31 self.assertEqual(main['st_value'], 0x8068)
32 self.assertEqual(main['st_size'], 0x28)
33
34 def test_missing_symbol(self):
35 with open(os.path.join('test', 'testfiles_for_unittests',
36 'simple_gcc.elf.arm'), 'rb') as f:
37 elf = ELFFile(f)
38
39 # Find the symbol table.
40 symtab = elf.get_section_by_name('.symtab')
41 self.assertIsNotNone(symtab)
42
43 # Test we get None when we look up a symbol that doesn't exist.
44 undef = symtab.get_symbol_by_name('non-existent symbol')
45 self.assertIsNone(undef)
46
47 def test_duplicated_symbol(self):
48 with open(os.path.join('test', 'testfiles_for_unittests',
49 'simple_gcc.elf.arm'), 'rb') as f:
50 elf = ELFFile(f)
51
52 # Find the symbol table.
53 symtab = elf.get_section_by_name('.symtab')
54 self.assertIsNotNone(symtab)
55
56 # The '$a' symbols that are present in the test file.
57 expected_symbols = [0x8000, 0x8034, 0x8090, 0x800c, 0x809c, 0x8018,
58 0x8068]
59
60 # Test we get all expected instances of the symbol '$a'.
61 arm_markers = symtab.get_symbol_by_name('$a')
62 self.assertIsNotNone(arm_markers)
63 self.assertIsInstance(arm_markers, list)
64 self.assertEqual(len(arm_markers), len(expected_symbols))
65 for symbol in arm_markers:
66 self.assertEqual(symbol.name, '$a')
67 self.assertIn(symbol['st_value'], expected_symbols)
68
69 if __name__ == '__main__':
70 unittest.main()