elf.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # Copyright (c) 2016 Google, Inc
  2. # Written by Simon Glass <sjg@chromium.org>
  3. #
  4. # SPDX-License-Identifier: GPL-2.0+
  5. #
  6. # Handle various things related to ELF images
  7. #
  8. from collections import namedtuple, OrderedDict
  9. import command
  10. import os
  11. import re
  12. import struct
  13. import tools
  14. # This is enabled from control.py
  15. debug = False
  16. Symbol = namedtuple('Symbol', ['section', 'address', 'size', 'weak'])
  17. def GetSymbols(fname, patterns):
  18. """Get the symbols from an ELF file
  19. Args:
  20. fname: Filename of the ELF file to read
  21. patterns: List of regex patterns to search for, each a string
  22. Returns:
  23. None, if the file does not exist, or Dict:
  24. key: Name of symbol
  25. value: Hex value of symbol
  26. """
  27. stdout = command.Output('objdump', '-t', fname, raise_on_error=False)
  28. lines = stdout.splitlines()
  29. if patterns:
  30. re_syms = re.compile('|'.join(patterns))
  31. else:
  32. re_syms = None
  33. syms = {}
  34. syms_started = False
  35. for line in lines:
  36. if not line or not syms_started:
  37. if 'SYMBOL TABLE' in line:
  38. syms_started = True
  39. line = None # Otherwise code coverage complains about 'continue'
  40. continue
  41. if re_syms and not re_syms.search(line):
  42. continue
  43. space_pos = line.find(' ')
  44. value, rest = line[:space_pos], line[space_pos + 1:]
  45. flags = rest[:7]
  46. parts = rest[7:].split()
  47. section, size = parts[:2]
  48. if len(parts) > 2:
  49. name = parts[2]
  50. syms[name] = Symbol(section, int(value, 16), int(size,16),
  51. flags[1] == 'w')
  52. return syms
  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, image):
  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 positions in
  70. the entry (using the ELF file) and replacing them with values from binman's
  71. data structures.
  72. Args:
  73. elf_fname: Filename of ELF image containing the symbol information for
  74. entry
  75. entry: Entry to process
  76. image: Image 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 = ("Image '%s': Symbol '%s'\n in entry '%s'" %
  88. (image.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 = image.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:])