elf_test.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2017 Google, Inc
  3. # Written by Simon Glass <sjg@chromium.org>
  4. #
  5. # Test for the elf module
  6. import os
  7. import shutil
  8. import sys
  9. import tempfile
  10. import unittest
  11. from binman import elf
  12. from patman import command
  13. from patman import test_util
  14. from patman import tools
  15. from patman import tout
  16. binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
  17. class FakeEntry:
  18. """A fake Entry object, usedfor testing
  19. This supports an entry with a given size.
  20. """
  21. def __init__(self, contents_size):
  22. self.contents_size = contents_size
  23. self.data = tools.GetBytes(ord('a'), contents_size)
  24. def GetPath(self):
  25. return 'entry_path'
  26. class FakeSection:
  27. """A fake Section object, used for testing
  28. This has the minimum feature set needed to support testing elf functions.
  29. A LookupSymbol() function is provided which returns a fake value for amu
  30. symbol requested.
  31. """
  32. def __init__(self, sym_value=1):
  33. self.sym_value = sym_value
  34. def GetPath(self):
  35. return 'section_path'
  36. def LookupImageSymbol(self, name, weak, msg, base_addr):
  37. """Fake implementation which returns the same value for all symbols"""
  38. return self.sym_value
  39. def GetImage(self):
  40. return self
  41. def BuildElfTestFiles(target_dir):
  42. """Build ELF files used for testing in binman
  43. This compiles and links the test files into the specified directory. It the
  44. Makefile and source files in the binman test/ directory.
  45. Args:
  46. target_dir: Directory to put the files into
  47. """
  48. if not os.path.exists(target_dir):
  49. os.mkdir(target_dir)
  50. testdir = os.path.join(binman_dir, 'test')
  51. # If binman is involved from the main U-Boot Makefile the -r and -R
  52. # flags are set in MAKEFLAGS. This prevents this Makefile from working
  53. # correctly. So drop any make flags here.
  54. if 'MAKEFLAGS' in os.environ:
  55. del os.environ['MAKEFLAGS']
  56. tools.Run('make', '-C', target_dir, '-f',
  57. os.path.join(testdir, 'Makefile'), 'SRC=%s/' % testdir)
  58. class TestElf(unittest.TestCase):
  59. @classmethod
  60. def setUpClass(cls):
  61. cls._indir = tempfile.mkdtemp(prefix='elf.')
  62. tools.SetInputDirs(['.'])
  63. BuildElfTestFiles(cls._indir)
  64. @classmethod
  65. def tearDownClass(cls):
  66. if cls._indir:
  67. shutil.rmtree(cls._indir)
  68. @classmethod
  69. def ElfTestFile(cls, fname):
  70. return os.path.join(cls._indir, fname)
  71. def testAllSymbols(self):
  72. """Test that we can obtain a symbol from the ELF file"""
  73. fname = self.ElfTestFile('u_boot_ucode_ptr')
  74. syms = elf.GetSymbols(fname, [])
  75. self.assertIn('.ucode', syms)
  76. def testRegexSymbols(self):
  77. """Test that we can obtain from the ELF file by regular expression"""
  78. fname = self.ElfTestFile('u_boot_ucode_ptr')
  79. syms = elf.GetSymbols(fname, ['ucode'])
  80. self.assertIn('.ucode', syms)
  81. syms = elf.GetSymbols(fname, ['missing'])
  82. self.assertNotIn('.ucode', syms)
  83. syms = elf.GetSymbols(fname, ['missing', 'ucode'])
  84. self.assertIn('.ucode', syms)
  85. def testMissingFile(self):
  86. """Test that a missing file is detected"""
  87. entry = FakeEntry(10)
  88. section = FakeSection()
  89. with self.assertRaises(ValueError) as e:
  90. syms = elf.LookupAndWriteSymbols('missing-file', entry, section)
  91. self.assertIn("Filename 'missing-file' not found in input path",
  92. str(e.exception))
  93. def testOutsideFile(self):
  94. """Test a symbol which extends outside the entry area is detected"""
  95. entry = FakeEntry(10)
  96. section = FakeSection()
  97. elf_fname = self.ElfTestFile('u_boot_binman_syms')
  98. with self.assertRaises(ValueError) as e:
  99. syms = elf.LookupAndWriteSymbols(elf_fname, entry, section)
  100. self.assertIn('entry_path has offset 4 (size 8) but the contents size '
  101. 'is a', str(e.exception))
  102. def testMissingImageStart(self):
  103. """Test that we detect a missing __image_copy_start symbol
  104. This is needed to mark the start of the image. Without it we cannot
  105. locate the offset of a binman symbol within the image.
  106. """
  107. entry = FakeEntry(10)
  108. section = FakeSection()
  109. elf_fname = self.ElfTestFile('u_boot_binman_syms_bad')
  110. self.assertEqual(elf.LookupAndWriteSymbols(elf_fname, entry, section),
  111. None)
  112. def testBadSymbolSize(self):
  113. """Test that an attempt to use an 8-bit symbol are detected
  114. Only 32 and 64 bits are supported, since we need to store an offset
  115. into the image.
  116. """
  117. entry = FakeEntry(10)
  118. section = FakeSection()
  119. elf_fname =self.ElfTestFile('u_boot_binman_syms_size')
  120. with self.assertRaises(ValueError) as e:
  121. syms = elf.LookupAndWriteSymbols(elf_fname, entry, section)
  122. self.assertIn('has size 1: only 4 and 8 are supported',
  123. str(e.exception))
  124. def testNoValue(self):
  125. """Test the case where we have no value for the symbol
  126. This should produce -1 values for all thress symbols, taking up the
  127. first 16 bytes of the image.
  128. """
  129. entry = FakeEntry(24)
  130. section = FakeSection(sym_value=None)
  131. elf_fname = self.ElfTestFile('u_boot_binman_syms')
  132. syms = elf.LookupAndWriteSymbols(elf_fname, entry, section)
  133. self.assertEqual(tools.GetBytes(255, 20) + tools.GetBytes(ord('a'), 4),
  134. entry.data)
  135. def testDebug(self):
  136. """Check that enabling debug in the elf module produced debug output"""
  137. try:
  138. tout.Init(tout.DEBUG)
  139. entry = FakeEntry(20)
  140. section = FakeSection()
  141. elf_fname = self.ElfTestFile('u_boot_binman_syms')
  142. with test_util.capture_sys_output() as (stdout, stderr):
  143. syms = elf.LookupAndWriteSymbols(elf_fname, entry, section)
  144. self.assertTrue(len(stdout.getvalue()) > 0)
  145. finally:
  146. tout.Init(tout.WARNING)
  147. def testMakeElf(self):
  148. """Test for the MakeElf function"""
  149. outdir = tempfile.mkdtemp(prefix='elf.')
  150. expected_text = b'1234'
  151. expected_data = b'wxyz'
  152. elf_fname = os.path.join(outdir, 'elf')
  153. bin_fname = os.path.join(outdir, 'bin')
  154. # Make an Elf file and then convert it to a fkat binary file. This
  155. # should produce the original data.
  156. elf.MakeElf(elf_fname, expected_text, expected_data)
  157. objcopy, args = tools.GetTargetCompileTool('objcopy')
  158. args += ['-O', 'binary', elf_fname, bin_fname]
  159. stdout = command.Output(objcopy, *args)
  160. with open(bin_fname, 'rb') as fd:
  161. data = fd.read()
  162. self.assertEqual(expected_text + expected_data, data)
  163. shutil.rmtree(outdir)
  164. def testDecodeElf(self):
  165. """Test for the MakeElf function"""
  166. if not elf.ELF_TOOLS:
  167. self.skipTest('Python elftools not available')
  168. outdir = tempfile.mkdtemp(prefix='elf.')
  169. expected_text = b'1234'
  170. expected_data = b'wxyz'
  171. elf_fname = os.path.join(outdir, 'elf')
  172. elf.MakeElf(elf_fname, expected_text, expected_data)
  173. data = tools.ReadFile(elf_fname)
  174. load = 0xfef20000
  175. entry = load + 2
  176. expected = expected_text + expected_data
  177. self.assertEqual(elf.ElfInfo(expected, load, entry, len(expected)),
  178. elf.DecodeElf(data, 0))
  179. self.assertEqual(elf.ElfInfo(b'\0\0' + expected[2:],
  180. load, entry, len(expected)),
  181. elf.DecodeElf(data, load + 2))
  182. shutil.rmtree(outdir)
  183. if __name__ == '__main__':
  184. unittest.main()