add utilities for testing ELF files
authorJacob Lifshay <programmerjake@gmail.com>
Fri, 1 Dec 2023 07:55:41 +0000 (23:55 -0800)
committerLuke Kenneth Casson Leighton <lkcl@lkcl.net>
Fri, 22 Dec 2023 19:26:21 +0000 (19:26 +0000)
src/openpower/test/elf/__init__.py [new file with mode: 0644]

diff --git a/src/openpower/test/elf/__init__.py b/src/openpower/test/elf/__init__.py
new file mode 100644 (file)
index 0000000..e99ff2d
--- /dev/null
@@ -0,0 +1,36 @@
+# SPDX-License-Identifier: LGPLv3+
+# Copyright (C) 2023 Jacob Lifshay <programmerjake@gmail.com>
+# Funded by NLnet http://nlnet.nl
+""" ELF test utilities
+
+related bugs:
+
+* https://bugs.libre-soc.org/show_bug.cgi?id=1169
+"""
+
+from subprocess import run, PIPE
+from tempfile import NamedTemporaryFile
+from elftools.elf.elffile import ELFFile
+from openpower.util import log, LogType
+
+DEF_CC_ARGS = '-Os', '-ffreestanding', '-nostdlib', '-static', '-xc'
+DEF_CC = 'powerpc64le-linux-gnu-gcc'
+
+def compile_elf(src_code, compiler_args=DEF_CC_ARGS, compiler=DEF_CC):
+    if isinstance(compiler, str):
+        compiler = [compiler]
+    f = NamedTemporaryFile(suffix=".elf")
+    args = [*compiler, *compiler_args, '-', '-o', f.name]
+    cleanup = f.close
+    try:
+        run(args, input=src_code, check=True, encoding='utf-8')
+        dump_out = run([
+            'powerpc64le-linux-gnu-objdump', '-dfprsF', '-Mraw', f.name],
+            stdout=PIPE, check=True, encoding='utf-8').stdout
+        log(dump_out, kind=LogType.InstrInOuts)
+        f = ELFFile(f)
+        cleanup = None
+        return f
+    finally:
+        if cleanup is not None:
+            cleanup()