add utilities for testing ELF files
[openpower-isa.git] / src / openpower / test / elf / __init__.py
1 # SPDX-License-Identifier: LGPLv3+
2 # Copyright (C) 2023 Jacob Lifshay <programmerjake@gmail.com>
3 # Funded by NLnet http://nlnet.nl
4 """ ELF test utilities
5
6 related bugs:
7
8 * https://bugs.libre-soc.org/show_bug.cgi?id=1169
9 """
10
11 from subprocess import run, PIPE
12 from tempfile import NamedTemporaryFile
13 from elftools.elf.elffile import ELFFile
14 from openpower.util import log, LogType
15
16 DEF_CC_ARGS = '-Os', '-ffreestanding', '-nostdlib', '-static', '-xc'
17 DEF_CC = 'powerpc64le-linux-gnu-gcc'
18
19 def compile_elf(src_code, compiler_args=DEF_CC_ARGS, compiler=DEF_CC):
20 if isinstance(compiler, str):
21 compiler = [compiler]
22 f = NamedTemporaryFile(suffix=".elf")
23 args = [*compiler, *compiler_args, '-', '-o', f.name]
24 cleanup = f.close
25 try:
26 run(args, input=src_code, check=True, encoding='utf-8')
27 dump_out = run([
28 'powerpc64le-linux-gnu-objdump', '-dfprsF', '-Mraw', f.name],
29 stdout=PIPE, check=True, encoding='utf-8').stdout
30 log(dump_out, kind=LogType.InstrInOuts)
31 f = ELFFile(f)
32 cleanup = None
33 return f
34 finally:
35 if cleanup is not None:
36 cleanup()