blob: 89b152b1e0e8d704831b9a9e8d80f2aaed7546e8 [file] [log] [blame]
Leandro Pereiraf5a8d492017-07-24 10:19:49 -07001#!/usr/bin/env python3
2#
3# Copyright (c) 2017 Intel Corporation.
4#
5# SPDX-License-Identifier: Apache-2.0
6#
7
8from elftools.elf.elffile import ELFFile
9from elftools.elf.sections import SymbolTableSection
10import argparse
11import sys
12
Anas Nashif72565532017-12-12 08:19:25 -050013
Leandro Pereiraf5a8d492017-07-24 10:19:49 -070014def get_symbol_table(obj):
15 for section in obj.iter_sections():
16 if isinstance(section, SymbolTableSection):
17 return section
18
19 raise LookupError("Could not find symbol table")
20
Anas Nashif72565532017-12-12 08:19:25 -050021
Leandro Pereiraf5a8d492017-07-24 10:19:49 -070022def gen_offset_header(input_name, input_file, output_file):
Anas Nashif08ed5602017-08-01 14:33:09 -040023 include_guard = "__GEN_OFFSETS_H__"
Leandro Pereiraf5a8d492017-07-24 10:19:49 -070024 output_file.write("""/* THIS FILE IS AUTO GENERATED. PLEASE DO NOT EDIT.
25 *
26 * This header file provides macros for the offsets of various structure
27 * members. These offset macros are primarily intended to be used in
28 * assembly code.
29 */
30
31#ifndef %s
32#define %s\n\n""" % (include_guard, include_guard))
33
34 obj = ELFFile(input_file)
35 for sym in get_symbol_table(obj).iter_symbols():
36 if isinstance(sym.name, bytes):
37 sym.name = str(sym.name, 'ascii')
38
39 if not sym.name.endswith(('_OFFSET', '_SIZEOF')):
40 continue
41 if sym.entry['st_shndx'] != 'SHN_ABS':
42 continue
43 if sym.entry['st_info']['bind'] != 'STB_GLOBAL':
44 continue
45
Anas Nashif72565532017-12-12 08:19:25 -050046 output_file.write(
47 "#define %s 0x%x\n" %
48 (sym.name, sym.entry['st_value']))
Leandro Pereiraf5a8d492017-07-24 10:19:49 -070049
50 output_file.write("\n#endif /* %s */\n" % include_guard)
51
52 return 0
53
Anas Nashif72565532017-12-12 08:19:25 -050054
Leandro Pereiraf5a8d492017-07-24 10:19:49 -070055if __name__ == '__main__':
56 parser = argparse.ArgumentParser(
Anas Nashif72565532017-12-12 08:19:25 -050057 formatter_class=argparse.RawDescriptionHelpFormatter)
Leandro Pereiraf5a8d492017-07-24 10:19:49 -070058
Anas Nashif72565532017-12-12 08:19:25 -050059 parser.add_argument(
60 "-i",
61 "--input",
62 required=True,
63 help="Input object file")
64 parser.add_argument(
65 "-o",
66 "--output",
67 required=True,
68 help="Output header file")
Leandro Pereiraf5a8d492017-07-24 10:19:49 -070069
70 args = parser.parse_args()
71
72 input_file = open(args.input, 'rb')
73 output_file = open(args.output, 'w')
74
75 ret = gen_offset_header(args.input, input_file, output_file)
76 sys.exit(ret)