rockchip: make_fit_atf.py: Eliminate pyelftools dependency
[oweals/u-boot.git] / arch / arm / mach-rockchip / make_fit_atf.py
1 #!/usr/bin/env python
2 """
3 # SPDX-License-Identifier: GPL-2.0+
4 #
5 # A script to generate FIT image source for rockchip boards
6 # with ARM Trusted Firmware
7 # and multiple device trees (given on the command line)
8 #
9 # usage: $0 <dt_name> [<dt_name> [<dt_name] ...]
10 """
11
12 import os
13 import sys
14 import getopt
15 import logging
16 import struct
17
18 DT_HEADER = """
19 /*
20  * This is a generated file.
21  */
22 /dts-v1/;
23
24 / {
25         description = "FIT image for U-Boot with bl31 (TF-A)";
26         #address-cells = <1>;
27
28         images {
29 """
30
31 DT_UBOOT = """
32                 uboot {
33                         description = "U-Boot (64-bit)";
34                         data = /incbin/("u-boot-nodtb.bin");
35                         type = "standalone";
36                         os = "U-Boot";
37                         arch = "arm64";
38                         compression = "none";
39                         load = <0x%08x>;
40                 };
41
42 """
43
44 DT_IMAGES_NODE_END = """        };
45
46 """
47
48 DT_END = "};"
49
50 def append_bl31_node(file, atf_index, phy_addr, elf_entry):
51     # Append BL31 DT node to input FIT dts file.
52     data = 'bl31_0x%08x.bin' % phy_addr
53     file.write('\t\tatf_%d {\n' % atf_index)
54     file.write('\t\t\tdescription = \"ARM Trusted Firmware\";\n')
55     file.write('\t\t\tdata = /incbin/("%s");\n' % data)
56     file.write('\t\t\ttype = "firmware";\n')
57     file.write('\t\t\tarch = "arm64";\n')
58     file.write('\t\t\tos = "arm-trusted-firmware";\n')
59     file.write('\t\t\tcompression = "none";\n')
60     file.write('\t\t\tload = <0x%08x>;\n' % phy_addr)
61     if atf_index == 1:
62         file.write('\t\t\tentry = <0x%08x>;\n' % elf_entry)
63     file.write('\t\t};\n')
64     file.write('\n')
65
66 def append_fdt_node(file, dtbs):
67     # Append FDT nodes.
68     cnt = 1
69     for dtb in dtbs:
70         dtname = os.path.basename(dtb)
71         file.write('\t\tfdt_%d {\n' % cnt)
72         file.write('\t\t\tdescription = "%s";\n' % dtname)
73         file.write('\t\t\tdata = /incbin/("%s");\n' % dtb)
74         file.write('\t\t\ttype = "flat_dt";\n')
75         file.write('\t\t\tcompression = "none";\n')
76         file.write('\t\t};\n')
77         file.write('\n')
78         cnt = cnt + 1
79
80 def append_conf_section(file, cnt, dtname, segments):
81     file.write('\t\tconfig_%d {\n' % cnt)
82     file.write('\t\t\tdescription = "%s";\n' % dtname)
83     file.write('\t\t\tfirmware = "atf_1";\n')
84     file.write('\t\t\tloadables = "uboot"')
85     if segments != 0:
86         file.write(',')
87     for i in range(1, segments):
88         file.write('"atf_%d"' % (i + 1))
89         if i != (segments - 1):
90             file.write(',')
91         else:
92             file.write(';\n')
93     if segments == 0:
94         file.write(';\n')
95     file.write('\t\t\tfdt = "fdt_1";\n')
96     file.write('\t\t};\n')
97     file.write('\n')
98
99 def append_conf_node(file, dtbs, segments):
100     # Append configeration nodes.
101     cnt = 1
102     file.write('\tconfigurations {\n')
103     file.write('\t\tdefault = "config_1";\n')
104     for dtb in dtbs:
105         dtname = os.path.basename(dtb)
106         append_conf_section(file, cnt, dtname, segments)
107         cnt = cnt + 1
108     file.write('\t};\n')
109     file.write('\n')
110
111 def generate_atf_fit_dts_uboot(fit_file, uboot_file_name):
112     segments = unpack_elf(uboot_file_name)
113     if len(segments) != 1:
114         raise ValueError("Invalid u-boot ELF image '%s'" % uboot_file_name)
115     index, entry, p_paddr, data = segments[0]
116     fit_file.write(DT_UBOOT % p_paddr)
117
118 def generate_atf_fit_dts_bl31(fit_file, bl31_file_name, dtbs_file_name):
119     segments = unpack_elf(bl31_file_name)
120     for index, entry, paddr, data in segments:
121         append_bl31_node(fit_file, index + 1, paddr, entry)
122     append_fdt_node(fit_file, dtbs_file_name)
123     fit_file.write(DT_IMAGES_NODE_END)
124     append_conf_node(fit_file, dtbs_file_name, len(segments))
125
126 def generate_atf_fit_dts(fit_file_name, bl31_file_name, uboot_file_name, dtbs_file_name):
127     # Generate FIT script for ATF image.
128     if fit_file_name != sys.stdout:
129         fit_file = open(fit_file_name, "wb")
130     else:
131         fit_file = sys.stdout
132
133     fit_file.write(DT_HEADER)
134     generate_atf_fit_dts_uboot(fit_file, uboot_file_name)
135     generate_atf_fit_dts_bl31(fit_file, bl31_file_name, dtbs_file_name)
136     fit_file.write(DT_END)
137
138     if fit_file_name != sys.stdout:
139         fit_file.close()
140
141 def generate_atf_binary(bl31_file_name):
142     for index, entry, paddr, data in unpack_elf(bl31_file_name):
143         file_name = 'bl31_0x%08x.bin' % paddr
144         with open(file_name, "wb") as atf:
145             atf.write(data)
146
147 def unpack_elf(filename):
148     with open(filename, 'rb') as file:
149         elf = file.read()
150     if elf[0:7] != b'\x7fELF\x02\x01\x01' or elf[18:20] != b'\xb7\x00':
151         raise ValueError("Invalid arm64 ELF file '%s'" % filename)
152
153     e_entry, e_phoff = struct.unpack_from('<2Q', elf, 0x18)
154     e_phentsize, e_phnum = struct.unpack_from('<2H', elf, 0x36)
155     segments = []
156
157     for index in range(e_phnum):
158         offset = e_phoff + e_phentsize * index
159         p_type, p_flags, p_offset = struct.unpack_from('<LLQ', elf, offset)
160         if p_type == 1: # PT_LOAD
161             p_paddr, p_filesz = struct.unpack_from('<2Q', elf, offset + 0x18)
162             p_data = elf[p_offset:p_offset + p_filesz]
163             segments.append((index, e_entry, p_paddr, p_data))
164     return segments
165
166 def main():
167     uboot_elf = "./u-boot"
168     fit_its = sys.stdout
169     if "BL31" in os.environ:
170         bl31_elf=os.getenv("BL31");
171     elif os.path.isfile("./bl31.elf"):
172         bl31_elf = "./bl31.elf"
173     else:
174         os.system("echo 'int main(){}' > bl31.c")
175         os.system("${CROSS_COMPILE}gcc -c bl31.c -o bl31.elf")
176         bl31_elf = "./bl31.elf"
177         logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
178         logging.warning(' BL31 file bl31.elf NOT found, resulting binary is non-functional')
179         logging.warning(' Please read Building section in doc/README.rockchip')
180
181     opts, args = getopt.getopt(sys.argv[1:], "o:u:b:h")
182     for opt, val in opts:
183         if opt == "-o":
184             fit_its = val
185         elif opt == "-u":
186             uboot_elf = val
187         elif opt == "-b":
188             bl31_elf = val
189         elif opt == "-h":
190             print(__doc__)
191             sys.exit(2)
192
193     dtbs = args
194
195     generate_atf_fit_dts(fit_its, bl31_elf, uboot_elf, dtbs)
196     generate_atf_binary(bl31_elf)
197
198 if __name__ == "__main__":
199     main()