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