blob: 9ac00ed9ccf1fa00878cfd04b96db9fce3bc671d [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass24ad3652017-11-13 18:54:54 -07002# Copyright (c) 2016 Google, Inc
3# Written by Simon Glass <sjg@chromium.org>
4#
Simon Glass24ad3652017-11-13 18:54:54 -07005# Handle various things related to ELF images
6#
7
8from collections import namedtuple, OrderedDict
Simon Glass567b6822019-07-08 13:18:35 -06009import io
Simon Glass24ad3652017-11-13 18:54:54 -070010import os
11import re
Simon Glass4f379ea2019-07-08 13:18:34 -060012import shutil
Simon Glass24ad3652017-11-13 18:54:54 -070013import struct
Simon Glass4f379ea2019-07-08 13:18:34 -060014import tempfile
Simon Glass24ad3652017-11-13 18:54:54 -070015
Simon Glassa997ea52020-04-17 18:09:04 -060016from patman import command
17from patman import tools
18from patman import tout
Simon Glass24ad3652017-11-13 18:54:54 -070019
Simon Glass567b6822019-07-08 13:18:35 -060020ELF_TOOLS = True
21try:
22 from elftools.elf.elffile import ELFFile
Simon Glass571adc82022-02-08 11:49:55 -070023 from elftools.elf.elffile import ELFError
Simon Glass567b6822019-07-08 13:18:35 -060024 from elftools.elf.sections import SymbolTableSection
25except: # pragma: no cover
26 ELF_TOOLS = False
27
Alper Nebi Yasak9634dc92022-06-18 15:13:11 +030028# BSYM in little endian, keep in sync with include/binman_sym.h
29BINMAN_SYM_MAGIC_VALUE = 0x4d595342
30
Simon Glassa4e259e2021-11-03 21:09:16 -060031# Information about an EFL symbol:
32# section (str): Name of the section containing this symbol
33# address (int): Address of the symbol (its value)
34# size (int): Size of the symbol in bytes
35# weak (bool): True if the symbol is weak
36# offset (int or None): Offset of the symbol's data in the ELF file, or None if
37# not known
38Symbol = namedtuple('Symbol', ['section', 'address', 'size', 'weak', 'offset'])
Simon Glass24ad3652017-11-13 18:54:54 -070039
Simon Glass567b6822019-07-08 13:18:35 -060040# Information about an ELF file:
41# data: Extracted program contents of ELF file (this would be loaded by an
42# ELF loader when reading this file
43# load: Load address of code
44# entry: Entry address of code
45# memsize: Number of bytes in memory occupied by loading this ELF file
46ElfInfo = namedtuple('ElfInfo', ['data', 'load', 'entry', 'memsize'])
47
Simon Glass24ad3652017-11-13 18:54:54 -070048
49def GetSymbols(fname, patterns):
50 """Get the symbols from an ELF file
51
52 Args:
53 fname: Filename of the ELF file to read
54 patterns: List of regex patterns to search for, each a string
55
56 Returns:
57 None, if the file does not exist, or Dict:
58 key: Name of symbol
59 value: Hex value of symbol
60 """
Simon Glass80025522022-01-29 14:14:04 -070061 stdout = tools.run('objdump', '-t', fname)
Simon Glass24ad3652017-11-13 18:54:54 -070062 lines = stdout.splitlines()
63 if patterns:
64 re_syms = re.compile('|'.join(patterns))
65 else:
66 re_syms = None
67 syms = {}
68 syms_started = False
69 for line in lines:
70 if not line or not syms_started:
71 if 'SYMBOL TABLE' in line:
72 syms_started = True
73 line = None # Otherwise code coverage complains about 'continue'
74 continue
75 if re_syms and not re_syms.search(line):
76 continue
77
78 space_pos = line.find(' ')
79 value, rest = line[:space_pos], line[space_pos + 1:]
80 flags = rest[:7]
81 parts = rest[7:].split()
82 section, size = parts[:2]
83 if len(parts) > 2:
Simon Glassc29a85d2019-08-24 07:22:46 -060084 name = parts[2] if parts[2] != '.hidden' else parts[3]
Simon Glassa4e259e2021-11-03 21:09:16 -060085 syms[name] = Symbol(section, int(value, 16), int(size, 16),
86 flags[1] == 'w', None)
87
88 # Sort dict by address
89 return OrderedDict(sorted(syms.items(), key=lambda x: x[1].address))
90
Simon Glassbea8ef12022-03-04 08:42:59 -070091def _GetFileOffset(elf, addr):
92 """Get the file offset for an address
93
94 Args:
95 elf (ELFFile): ELF file to check
96 addr (int): Address to search for
97
98 Returns
99 int: Offset of that address in the ELF file, or None if not valid
100 """
101 for seg in elf.iter_segments():
102 seg_end = seg['p_vaddr'] + seg['p_filesz']
103 if seg.header['p_type'] == 'PT_LOAD':
104 if addr >= seg['p_vaddr'] and addr < seg_end:
105 return addr - seg['p_vaddr'] + seg['p_offset']
106
107def GetFileOffset(fname, addr):
108 """Get the file offset for an address
109
110 Args:
111 fname (str): Filename of ELF file to check
112 addr (int): Address to search for
113
114 Returns
115 int: Offset of that address in the ELF file, or None if not valid
116 """
117 if not ELF_TOOLS:
Simon Glassea64c022022-03-18 19:19:49 -0600118 raise ValueError("Python: No module named 'elftools'")
Simon Glassbea8ef12022-03-04 08:42:59 -0700119 with open(fname, 'rb') as fd:
120 elf = ELFFile(fd)
121 return _GetFileOffset(elf, addr)
122
123def GetSymbolFromAddress(fname, addr):
124 """Get the symbol at a particular address
125
126 Args:
127 fname (str): Filename of ELF file to check
128 addr (int): Address to search for
129
130 Returns:
131 str: Symbol name, or None if no symbol at that address
132 """
133 if not ELF_TOOLS:
Simon Glassea64c022022-03-18 19:19:49 -0600134 raise ValueError("Python: No module named 'elftools'")
Simon Glassbea8ef12022-03-04 08:42:59 -0700135 with open(fname, 'rb') as fd:
136 elf = ELFFile(fd)
137 syms = GetSymbols(fname, None)
138 for name, sym in syms.items():
139 if sym.address == addr:
140 return name
141
Simon Glassa4e259e2021-11-03 21:09:16 -0600142def GetSymbolFileOffset(fname, patterns):
143 """Get the symbols from an ELF file
144
145 Args:
146 fname: Filename of the ELF file to read
147 patterns: List of regex patterns to search for, each a string
148
149 Returns:
150 None, if the file does not exist, or Dict:
151 key: Name of symbol
152 value: Hex value of symbol
153 """
Simon Glassa4e259e2021-11-03 21:09:16 -0600154 if not ELF_TOOLS:
Simon Glassacc03752022-03-05 20:18:57 -0700155 raise ValueError("Python: No module named 'elftools'")
Simon Glassa4e259e2021-11-03 21:09:16 -0600156
157 syms = {}
158 with open(fname, 'rb') as fd:
159 elf = ELFFile(fd)
160
161 re_syms = re.compile('|'.join(patterns))
162 for section in elf.iter_sections():
163 if isinstance(section, SymbolTableSection):
164 for symbol in section.iter_symbols():
165 if not re_syms or re_syms.search(symbol.name):
166 addr = symbol.entry['st_value']
167 syms[symbol.name] = Symbol(
168 section.name, addr, symbol.entry['st_size'],
169 symbol.entry['st_info']['bind'] == 'STB_WEAK',
170 _GetFileOffset(elf, addr))
Simon Glasse6854aa2018-07-17 13:25:24 -0600171
172 # Sort dict by address
Simon Glass5f3645b2019-05-14 15:53:41 -0600173 return OrderedDict(sorted(syms.items(), key=lambda x: x[1].address))
Simon Glass24ad3652017-11-13 18:54:54 -0700174
175def GetSymbolAddress(fname, sym_name):
176 """Get a value of a symbol from an ELF file
177
178 Args:
179 fname: Filename of the ELF file to read
180 patterns: List of regex patterns to search for, each a string
181
182 Returns:
183 Symbol value (as an integer) or None if not found
184 """
185 syms = GetSymbols(fname, [sym_name])
186 sym = syms.get(sym_name)
187 if not sym:
188 return None
189 return sym.address
Simon Glass4ca8e042017-11-13 18:55:01 -0700190
Simon Glasscb452b02022-10-20 18:22:44 -0600191def GetPackString(sym, msg):
192 """Get the struct.pack/unpack string to use with a given symbol
193
194 Args:
195 sym (Symbol): Symbol to check. Only the size member is checked
196 @msg (str): String which indicates the entry being processed, used for
197 errors
198
199 Returns:
200 str: struct string to use, .e.g. '<I'
201
202 Raises:
203 ValueError: Symbol has an unexpected size
204 """
205 if sym.size == 4:
206 return '<I'
207 elif sym.size == 8:
208 return '<Q'
209 else:
210 raise ValueError('%s has size %d: only 4 and 8 are supported' %
211 (msg, sym.size))
212
Simon Glasse0035c92023-01-11 16:10:17 -0700213def LookupAndWriteSymbols(elf_fname, entry, section, is_elf=False,
214 base_sym=None):
Simon Glass4ca8e042017-11-13 18:55:01 -0700215 """Replace all symbols in an entry with their correct values
216
217 The entry contents is updated so that values for referenced symbols will be
Simon Glasse8561af2018-08-01 15:22:37 -0600218 visible at run time. This is done by finding out the symbols offsets in the
219 entry (using the ELF file) and replacing them with values from binman's data
220 structures.
Simon Glass4ca8e042017-11-13 18:55:01 -0700221
222 Args:
223 elf_fname: Filename of ELF image containing the symbol information for
224 entry
225 entry: Entry to process
Simon Glass8a6f56e2018-06-01 09:38:13 -0600226 section: Section which can be used to lookup symbol values
Simon Glasse0035c92023-01-11 16:10:17 -0700227 base_sym: Base symbol marking the start of the image
Simon Glass4ca8e042017-11-13 18:55:01 -0700228 """
Simon Glasse0035c92023-01-11 16:10:17 -0700229 if not base_sym:
230 base_sym = '__image_copy_start'
Simon Glass80025522022-01-29 14:14:04 -0700231 fname = tools.get_input_filename(elf_fname)
Simon Glass4ca8e042017-11-13 18:55:01 -0700232 syms = GetSymbols(fname, ['image', 'binman'])
Simon Glass37f85de2022-10-20 18:22:47 -0600233 if is_elf:
234 if not ELF_TOOLS:
235 msg = ("Section '%s': entry '%s'" %
236 (section.GetPath(), entry.GetPath()))
237 raise ValueError(f'{msg}: Cannot write symbols to an ELF file without Python elftools')
238 new_syms = {}
239 with open(fname, 'rb') as fd:
240 elf = ELFFile(fd)
241 for name, sym in syms.items():
242 offset = _GetFileOffset(elf, sym.address)
243 new_syms[name] = Symbol(sym.section, sym.address, sym.size,
244 sym.weak, offset)
245 syms = new_syms
246
Simon Glass4ca8e042017-11-13 18:55:01 -0700247 if not syms:
Simon Glass37f85de2022-10-20 18:22:47 -0600248 tout.debug('LookupAndWriteSymbols: no syms')
Simon Glass4ca8e042017-11-13 18:55:01 -0700249 return
Simon Glasse0035c92023-01-11 16:10:17 -0700250 base = syms.get(base_sym)
Simon Glass37f85de2022-10-20 18:22:47 -0600251 if not base and not is_elf:
252 tout.debug('LookupAndWriteSymbols: no base')
Simon Glass4ca8e042017-11-13 18:55:01 -0700253 return
Simon Glass37f85de2022-10-20 18:22:47 -0600254 base_addr = 0 if is_elf else base.address
Simon Glass5f3645b2019-05-14 15:53:41 -0600255 for name, sym in syms.items():
Simon Glass4ca8e042017-11-13 18:55:01 -0700256 if name.startswith('_binman'):
Simon Glass8a6f56e2018-06-01 09:38:13 -0600257 msg = ("Section '%s': Symbol '%s'\n in entry '%s'" %
258 (section.GetPath(), name, entry.GetPath()))
Simon Glass37f85de2022-10-20 18:22:47 -0600259 if is_elf:
260 # For ELF files, use the file offset
261 offset = sym.offset
262 else:
263 # For blobs use the offset of the symbol, calculated by
264 # subtracting the base address which by definition is at the
265 # start
266 offset = sym.address - base.address
267 if offset < 0 or offset + sym.size > entry.contents_size:
268 raise ValueError('%s has offset %x (size %x) but the contents '
269 'size is %x' % (entry.GetPath(), offset,
270 sym.size,
271 entry.contents_size))
Simon Glasscb452b02022-10-20 18:22:44 -0600272 pack_string = GetPackString(sym, msg)
Alper Nebi Yasak9634dc92022-06-18 15:13:11 +0300273 if name == '_binman_sym_magic':
274 value = BINMAN_SYM_MAGIC_VALUE
275 else:
276 # Look up the symbol in our entry tables.
277 value = section.GetImage().LookupImageSymbol(name, sym.weak,
Simon Glass37f85de2022-10-20 18:22:47 -0600278 msg, base_addr)
Simon Glass33778202019-10-20 21:31:34 -0600279 if value is None:
Simon Glass4ca8e042017-11-13 18:55:01 -0700280 value = -1
281 pack_string = pack_string.lower()
282 value_bytes = struct.pack(pack_string, value)
Simon Glass011f1b32022-01-29 14:14:15 -0700283 tout.debug('%s:\n insert %s, offset %x, value %x, length %d' %
Simon Glassb6dff4c2019-07-20 12:23:36 -0600284 (msg, name, offset, value, len(value_bytes)))
Simon Glass4ca8e042017-11-13 18:55:01 -0700285 entry.data = (entry.data[:offset] + value_bytes +
286 entry.data[offset + sym.size:])
Simon Glass4f379ea2019-07-08 13:18:34 -0600287
Simon Glasscb452b02022-10-20 18:22:44 -0600288def GetSymbolValue(sym, data, msg):
289 """Get the value of a symbol
290
291 This can only be used on symbols with an integer value.
292
293 Args:
294 sym (Symbol): Symbol to check
295 data (butes): Data for the ELF file - the symbol data appears at offset
296 sym.offset
297 @msg (str): String which indicates the entry being processed, used for
298 errors
299
300 Returns:
301 int: Value of the symbol
302
303 Raises:
304 ValueError: Symbol has an unexpected size
305 """
306 pack_string = GetPackString(sym, msg)
307 value = struct.unpack(pack_string, data[sym.offset:sym.offset + sym.size])
308 return value[0]
309
Simon Glass4f379ea2019-07-08 13:18:34 -0600310def MakeElf(elf_fname, text, data):
311 """Make an elf file with the given data in a single section
312
313 The output file has a several section including '.text' and '.data',
314 containing the info provided in arguments.
315
316 Args:
317 elf_fname: Output filename
318 text: Text (code) to put in the file's .text section
319 data: Data to put in the file's .data section
320 """
321 outdir = tempfile.mkdtemp(prefix='binman.elf.')
322 s_file = os.path.join(outdir, 'elf.S')
323
324 # Spilt the text into two parts so that we can make the entry point two
325 # bytes after the start of the text section
Simon Glassc27ee7c2020-11-08 20:36:19 -0700326 text_bytes1 = ['\t.byte\t%#x' % byte for byte in text[:2]]
327 text_bytes2 = ['\t.byte\t%#x' % byte for byte in text[2:]]
328 data_bytes = ['\t.byte\t%#x' % byte for byte in data]
Simon Glass4f379ea2019-07-08 13:18:34 -0600329 with open(s_file, 'w') as fd:
330 print('''/* Auto-generated C program to produce an ELF file for testing */
331
332.section .text
333.code32
334.globl _start
335.type _start, @function
336%s
337_start:
338%s
339.ident "comment"
340
341.comm fred,8,4
342
343.section .empty
344.globl _empty
345_empty:
346.byte 1
347
348.globl ernie
349.data
350.type ernie, @object
351.size ernie, 4
352ernie:
353%s
354''' % ('\n'.join(text_bytes1), '\n'.join(text_bytes2), '\n'.join(data_bytes)),
355 file=fd)
356 lds_file = os.path.join(outdir, 'elf.lds')
357
358 # Use a linker script to set the alignment and text address.
359 with open(lds_file, 'w') as fd:
360 print('''/* Auto-generated linker script to produce an ELF file for testing */
361
362PHDRS
363{
364 text PT_LOAD ;
365 data PT_LOAD ;
366 empty PT_LOAD FLAGS ( 6 ) ;
367 note PT_NOTE ;
368}
369
370SECTIONS
371{
372 . = 0xfef20000;
373 ENTRY(_start)
374 .text . : SUBALIGN(0)
375 {
376 *(.text)
377 } :text
378 .data : {
379 *(.data)
380 } :data
381 _bss_start = .;
382 .empty : {
383 *(.empty)
384 } :empty
Simon Glassd349ada2019-08-24 07:22:45 -0600385 /DISCARD/ : {
386 *(.note.gnu.property)
387 }
Simon Glass4f379ea2019-07-08 13:18:34 -0600388 .note : {
389 *(.comment)
390 } :note
391 .bss _bss_start (OVERLAY) : {
392 *(.bss)
393 }
394}
395''', file=fd)
396 # -static: Avoid requiring any shared libraries
397 # -nostdlib: Don't link with C library
398 # -Wl,--build-id=none: Don't generate a build ID, so that we just get the
399 # text section at the start
400 # -m32: Build for 32-bit x86
401 # -T...: Specifies the link script, which sets the start address
Simon Glass80025522022-01-29 14:14:04 -0700402 cc, args = tools.get_target_compile_tool('cc')
Alper Nebi Yasak5cd321d2020-09-06 14:46:05 +0300403 args += ['-static', '-nostdlib', '-Wl,--build-id=none', '-m32', '-T',
404 lds_file, '-o', elf_fname, s_file]
Simon Glass840be732022-01-29 14:14:05 -0700405 stdout = command.output(cc, *args)
Simon Glass4f379ea2019-07-08 13:18:34 -0600406 shutil.rmtree(outdir)
Simon Glass567b6822019-07-08 13:18:35 -0600407
408def DecodeElf(data, location):
409 """Decode an ELF file and return information about it
410
411 Args:
412 data: Data from ELF file
413 location: Start address of data to return
414
415 Returns:
416 ElfInfo object containing information about the decoded ELF file
417 """
418 file_size = len(data)
419 with io.BytesIO(data) as fd:
420 elf = ELFFile(fd)
421 data_start = 0xffffffff;
422 data_end = 0;
423 mem_end = 0;
424 virt_to_phys = 0;
425
426 for i in range(elf.num_segments()):
427 segment = elf.get_segment(i)
428 if segment['p_type'] != 'PT_LOAD' or not segment['p_memsz']:
429 skipped = 1 # To make code-coverage see this line
430 continue
431 start = segment['p_paddr']
432 mend = start + segment['p_memsz']
433 rend = start + segment['p_filesz']
434 data_start = min(data_start, start)
435 data_end = max(data_end, rend)
436 mem_end = max(mem_end, mend)
437 if not virt_to_phys:
438 virt_to_phys = segment['p_paddr'] - segment['p_vaddr']
439
440 output = bytearray(data_end - data_start)
441 for i in range(elf.num_segments()):
442 segment = elf.get_segment(i)
443 if segment['p_type'] != 'PT_LOAD' or not segment['p_memsz']:
444 skipped = 1 # To make code-coverage see this line
445 continue
446 start = segment['p_paddr']
447 offset = 0
448 if start < location:
449 offset = location - start
450 start = location
451 # A legal ELF file can have a program header with non-zero length
452 # but zero-length file size and a non-zero offset which, added
453 # together, are greater than input->size (i.e. the total file size).
454 # So we need to not even test in the case that p_filesz is zero.
455 # Note: All of this code is commented out since we don't have a test
456 # case for it.
457 size = segment['p_filesz']
458 #if not size:
459 #continue
460 #end = segment['p_offset'] + segment['p_filesz']
461 #if end > file_size:
462 #raise ValueError('Underflow copying out the segment. File has %#x bytes left, segment end is %#x\n',
463 #file_size, end)
464 output[start - data_start:start - data_start + size] = (
465 segment.data()[offset:])
466 return ElfInfo(output, data_start, elf.header['e_entry'] + virt_to_phys,
467 mem_end - data_start)
Simon Glassadfb8492021-11-03 21:09:18 -0600468
469def UpdateFile(infile, outfile, start_sym, end_sym, insert):
Simon Glass011f1b32022-01-29 14:14:15 -0700470 tout.notice("Creating file '%s' with data length %#x (%d) between symbols '%s' and '%s'" %
Simon Glassadfb8492021-11-03 21:09:18 -0600471 (outfile, len(insert), len(insert), start_sym, end_sym))
472 syms = GetSymbolFileOffset(infile, [start_sym, end_sym])
473 if len(syms) != 2:
474 raise ValueError("Expected two symbols '%s' and '%s': got %d: %s" %
475 (start_sym, end_sym, len(syms),
476 ','.join(syms.keys())))
477
478 size = syms[end_sym].offset - syms[start_sym].offset
479 if len(insert) > size:
480 raise ValueError("Not enough space in '%s' for data length %#x (%d); size is %#x (%d)" %
481 (infile, len(insert), len(insert), size, size))
482
Simon Glass80025522022-01-29 14:14:04 -0700483 data = tools.read_file(infile)
Simon Glassadfb8492021-11-03 21:09:18 -0600484 newdata = data[:syms[start_sym].offset]
Simon Glass80025522022-01-29 14:14:04 -0700485 newdata += insert + tools.get_bytes(0, size - len(insert))
Simon Glassadfb8492021-11-03 21:09:18 -0600486 newdata += data[syms[end_sym].offset:]
Simon Glass80025522022-01-29 14:14:04 -0700487 tools.write_file(outfile, newdata)
Simon Glass011f1b32022-01-29 14:14:15 -0700488 tout.info('Written to offset %#x' % syms[start_sym].offset)
Simon Glass571adc82022-02-08 11:49:55 -0700489
Simon Glassacc03752022-03-05 20:18:57 -0700490def read_loadable_segments(data):
Simon Glass571adc82022-02-08 11:49:55 -0700491 """Read segments from an ELF file
492
493 Args:
494 data (bytes): Contents of file
495
496 Returns:
497 tuple:
498 list of segments, each:
499 int: Segment number (0 = first)
500 int: Start address of segment in memory
501 bytes: Contents of segment
502 int: entry address for image
503
504 Raises:
505 ValueError: elftools is not available
506 """
507 if not ELF_TOOLS:
Simon Glassacc03752022-03-05 20:18:57 -0700508 raise ValueError("Python: No module named 'elftools'")
Simon Glass571adc82022-02-08 11:49:55 -0700509 with io.BytesIO(data) as inf:
510 try:
511 elf = ELFFile(inf)
512 except ELFError as err:
513 raise ValueError(err)
514 entry = elf.header['e_entry']
515 segments = []
516 for i in range(elf.num_segments()):
517 segment = elf.get_segment(i)
518 if segment['p_type'] != 'PT_LOAD' or not segment['p_memsz']:
519 skipped = 1 # To make code-coverage see this line
520 continue
521 start = segment['p_offset']
522 rend = start + segment['p_filesz']
523 segments.append((i, segment['p_paddr'], data[start:rend]))
524 return segments, entry
Simon Glass6e657f62023-01-07 14:07:13 -0700525
526def is_valid(data):
527 """Check if some binary data is a valid ELF file
528
529 Args:
530 data (bytes): Bytes to check
531
532 Returns:
533 bool: True if a valid Elf file, False if not
534 """
535 try:
536 DecodeElf(data, 0)
537 return True
538 except ELFError:
539 return False