elf.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. # Sort dict by address
  52. return OrderedDict(sorted(syms.iteritems(), key=lambda x: x[1].address))
  53. def GetSymbolAddress(fname, sym_name):
  54. """Get a value of a symbol from an ELF file
  55. Args:
  56. fname: Filename of the ELF file to read
  57. patterns: List of regex patterns to search for, each a string
  58. Returns:
  59. Symbol value (as an integer) or None if not found
  60. """
  61. syms = GetSymbols(fname, [sym_name])
  62. sym = syms.get(sym_name)
  63. if not sym:
  64. return None
  65. return sym.address
  66. def LookupAndWriteSymbols(elf_fname, entry, section):
  67. """Replace all symbols in an entry with their correct values
  68. The entry contents is updated so that values for referenced symbols will be
  69. visible at run time. This is done by finding out the symbols offsets in the
  70. entry (using the ELF file) and replacing them with values from binman's data
  71. structures.
  72. Args:
  73. elf_fname: Filename of ELF image containing the symbol information for
  74. entry
  75. entry: Entry to process
  76. section: Section which can be used to lookup symbol values
  77. """
  78. fname = tools.GetInputFilename(elf_fname)
  79. syms = GetSymbols(fname, ['image', 'binman'])
  80. if not syms:
  81. return
  82. base = syms.get('__image_copy_start')
  83. if not base:
  84. return
  85. for name, sym in syms.iteritems():
  86. if name.startswith('_binman'):
  87. msg = ("Section '%s': Symbol '%s'\n in entry '%s'" %
  88. (section.GetPath(), name, entry.GetPath()))
  89. offset = sym.address - base.address
  90. if offset < 0 or offset + sym.size > entry.contents_size:
  91. raise ValueError('%s has offset %x (size %x) but the contents '
  92. 'size is %x' % (entry.GetPath(), offset,
  93. sym.size, entry.contents_size))
  94. if sym.size == 4:
  95. pack_string = '<I'
  96. elif sym.size == 8:
  97. pack_string = '<Q'
  98. else:
  99. raise ValueError('%s has size %d: only 4 and 8 are supported' %
  100. (msg, sym.size))
  101. # Look up the symbol in our entry tables.
  102. value = section.LookupSymbol(name, sym.weak, msg)
  103. if value is not None:
  104. value += base.address
  105. else:
  106. value = -1
  107. pack_string = pack_string.lower()
  108. value_bytes = struct.pack(pack_string, value)
  109. if debug:
  110. print('%s:\n insert %s, offset %x, value %x, length %d' %
  111. (msg, name, offset, value, len(value_bytes)))
  112. entry.data = (entry.data[:offset] + value_bytes +
  113. entry.data[offset + sym.size:])