elf.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2016 Google, Inc
  3. # Written by Simon Glass <sjg@chromium.org>
  4. #
  5. # Handle various things related to ELF images
  6. #
  7. from collections import namedtuple, OrderedDict
  8. import command
  9. import os
  10. import re
  11. import struct
  12. import tools
  13. # This is enabled from control.py
  14. debug = False
  15. Symbol = namedtuple('Symbol', ['section', 'address', 'size', 'weak'])
  16. def GetSymbols(fname, patterns):
  17. """Get the symbols from an ELF file
  18. Args:
  19. fname: Filename of the ELF file to read
  20. patterns: List of regex patterns to search for, each a string
  21. Returns:
  22. None, if the file does not exist, or Dict:
  23. key: Name of symbol
  24. value: Hex value of symbol
  25. """
  26. stdout = command.Output('objdump', '-t', fname, raise_on_error=False)
  27. lines = stdout.splitlines()
  28. if patterns:
  29. re_syms = re.compile('|'.join(patterns))
  30. else:
  31. re_syms = None
  32. syms = {}
  33. syms_started = False
  34. for line in lines:
  35. if not line or not syms_started:
  36. if 'SYMBOL TABLE' in line:
  37. syms_started = True
  38. line = None # Otherwise code coverage complains about 'continue'
  39. continue
  40. if re_syms and not re_syms.search(line):
  41. continue
  42. space_pos = line.find(' ')
  43. value, rest = line[:space_pos], line[space_pos + 1:]
  44. flags = rest[:7]
  45. parts = rest[7:].split()
  46. section, size = parts[:2]
  47. if len(parts) > 2:
  48. name = parts[2]
  49. syms[name] = Symbol(section, int(value, 16), int(size,16),
  50. flags[1] == 'w')
  51. return syms
  52. def GetSymbolAddress(fname, sym_name):
  53. """Get a value of a symbol from an ELF file
  54. Args:
  55. fname: Filename of the ELF file to read
  56. patterns: List of regex patterns to search for, each a string
  57. Returns:
  58. Symbol value (as an integer) or None if not found
  59. """
  60. syms = GetSymbols(fname, [sym_name])
  61. sym = syms.get(sym_name)
  62. if not sym:
  63. return None
  64. return sym.address
  65. def LookupAndWriteSymbols(elf_fname, entry, section):
  66. """Replace all symbols in an entry with their correct values
  67. The entry contents is updated so that values for referenced symbols will be
  68. visible at run time. This is done by finding out the symbols positions in
  69. the entry (using the ELF file) and replacing them with values from binman's
  70. data structures.
  71. Args:
  72. elf_fname: Filename of ELF image containing the symbol information for
  73. entry
  74. entry: Entry to process
  75. section: Section which can be used to lookup symbol values
  76. """
  77. fname = tools.GetInputFilename(elf_fname)
  78. syms = GetSymbols(fname, ['image', 'binman'])
  79. if not syms:
  80. return
  81. base = syms.get('__image_copy_start')
  82. if not base:
  83. return
  84. for name, sym in syms.iteritems():
  85. if name.startswith('_binman'):
  86. msg = ("Section '%s': Symbol '%s'\n in entry '%s'" %
  87. (section.GetPath(), name, entry.GetPath()))
  88. offset = sym.address - base.address
  89. if offset < 0 or offset + sym.size > entry.contents_size:
  90. raise ValueError('%s has offset %x (size %x) but the contents '
  91. 'size is %x' % (entry.GetPath(), offset,
  92. sym.size, entry.contents_size))
  93. if sym.size == 4:
  94. pack_string = '<I'
  95. elif sym.size == 8:
  96. pack_string = '<Q'
  97. else:
  98. raise ValueError('%s has size %d: only 4 and 8 are supported' %
  99. (msg, sym.size))
  100. # Look up the symbol in our entry tables.
  101. value = section.LookupSymbol(name, sym.weak, msg)
  102. if value is not None:
  103. value += base.address
  104. else:
  105. value = -1
  106. pack_string = pack_string.lower()
  107. value_bytes = struct.pack(pack_string, value)
  108. if debug:
  109. print('%s:\n insert %s, offset %x, value %x, length %d' %
  110. (msg, name, offset, value, len(value_bytes)))
  111. entry.data = (entry.data[:offset] + value_bytes +
  112. entry.data[offset + sym.size:])