1#!/usr/bin/env python
2"""
3A script to generate FIT image source for rockchip boards
4with ARM Trusted Firmware
5and multiple device trees (given on the command line)
6
7usage: $0 <dt_name> [<dt_name> [<dt_name] ...]
8"""
9
10import os
11import sys
12import getopt
13
14# pip install pyelftools
15from elftools.elf.elffile import ELFFile
16
17ELF_SEG_P_TYPE='p_type'
18ELF_SEG_P_PADDR='p_paddr'
19ELF_SEG_P_VADDR='p_vaddr'
20ELF_SEG_P_OFFSET='p_offset'
21ELF_SEG_P_FILESZ='p_filesz'
22ELF_SEG_P_MEMSZ='p_memsz'
23
24DT_HEADER="""// SPDX-License-Identifier: GPL-2.0+ OR X11
25/*
26 * Copyright (C) 2017 Fuzhou Rockchip Electronics Co., Ltd
27 *
28 * Minimal dts for a SPL FIT image payload.
29 */
30/dts-v1/;
31
32/ {
33	description = "Configuration to load ATF before U-Boot";
34	#address-cells = <1>;
35
36	images {
37		uboot {
38			description = "U-Boot (64-bit)";
39			data = /incbin/("u-boot-nodtb.bin");
40			type = "standalone";
41			os = "U-Boot";
42			arch = "arm64";
43			compression = "none";
44			load = <0x%08x>;
45		};
46
47"""
48
49DT_IMAGES_NODE_END="""
50    };
51"""
52
53DT_END="""
54};
55"""
56
57def append_atf_node(file, atf_index, phy_addr, elf_entry):
58    """
59    Append ATF DT node to input FIT dts file.
60    """
61    data = 'bl31_0x%08x.bin' % phy_addr
62    file.write('\t\tatf_%d {\n' % atf_index)
63    file.write('\t\t\tdescription = \"ARM Trusted Firmware\";\n')
64    file.write('\t\t\tdata = /incbin/("%s");\n' % data)
65    file.write('\t\t\ttype = "firmware";\n')
66    file.write('\t\t\tarch = "arm64";\n')
67    file.write('\t\t\tos = "arm-trusted-firmware";\n')
68    file.write('\t\t\tcompression = "none";\n')
69    file.write('\t\t\tload = <0x%08x>;\n' % phy_addr)
70    if atf_index == 1:
71        file.write('\t\t\tentry = <0x%08x>;\n' % elf_entry)
72    file.write('\t\t};\n')
73    file.write('\n')
74
75def append_fdt_node(file, dtbs):
76    """
77    Append FDT nodes.
78    """
79    cnt = 1
80    for dtb in dtbs:
81        dtname = os.path.basename(dtb)
82        file.write('\t\tfdt_%d {\n' % cnt)
83        file.write('\t\t\tdescription = "%s";\n' % dtname)
84        file.write('\t\t\tdata = /incbin/("%s");\n' % dtb)
85        file.write('\t\t\ttype = "flat_dt";\n')
86        file.write('\t\t\tcompression = "none";\n')
87        file.write('\t\t};\n')
88        file.write('\n')
89        cnt = cnt + 1
90
91def append_conf_section(file, cnt, dtname, atf_cnt):
92    file.write('\t\tconfig_%d {\n' % cnt)
93    file.write('\t\t\tdescription = "%s";\n' % dtname)
94    file.write('\t\t\tfirmware = "atf_1";\n')
95    file.write('\t\t\tloadables = "uboot",')
96    for i in range(1, atf_cnt):
97        file.write('"atf_%d"' % (i+1))
98        if i != (atf_cnt - 1):
99            file.write(',')
100        else:
101            file.write(';\n')
102    file.write('\t\t\tfdt = "fdt_1";\n')
103    file.write('\t\t};\n')
104    file.write('\n')
105
106def append_conf_node(file, dtbs, atf_cnt):
107    """
108    Append configeration nodes.
109    """
110    cnt = 1
111    file.write('\tconfigurations {\n')
112    file.write('\t\tdefault = "config_1";\n')
113    for dtb in dtbs:
114        dtname = os.path.basename(dtb)
115        append_conf_section(file, cnt, dtname, atf_cnt)
116        cnt = cnt + 1
117    file.write('\t};\n')
118    file.write('\n')
119
120def generate_atf_fit_dts(fit_file_name, bl31_file_name, uboot_file_name, dtbs_file_name):
121    """
122    Generate FIT script for ATF image.
123    """
124    if fit_file_name != sys.stdout:
125        fit_file = open(fit_file_name, "wb")
126    else:
127        fit_file = sys.stdout
128
129    num_load_seg = 0
130    p_paddr = 0xFFFFFFFF
131    with open(uboot_file_name, 'rb') as uboot_file:
132        uboot = ELFFile(uboot_file)
133        for i in range(uboot.num_segments()):
134            seg = uboot.get_segment(i)
135            if ('PT_LOAD' == seg.__getitem__(ELF_SEG_P_TYPE)):
136                p_paddr = seg.__getitem__(ELF_SEG_P_PADDR)
137                num_load_seg = num_load_seg + 1
138
139    assert (p_paddr != 0xFFFFFFFF and num_load_seg == 1)
140
141    fit_file.write(DT_HEADER % p_paddr)
142
143    with open(bl31_file_name, 'rb') as bl31_file:
144        bl31 = ELFFile(bl31_file)
145        elf_entry = bl31.header['e_entry']
146        for i in range(bl31.num_segments()):
147            seg = bl31.get_segment(i)
148            if ('PT_LOAD' == seg.__getitem__(ELF_SEG_P_TYPE)):
149                paddr = seg.__getitem__(ELF_SEG_P_PADDR)
150                p= seg.__getitem__(ELF_SEG_P_PADDR)
151                append_atf_node(fit_file, i+1, paddr, elf_entry)
152    atf_cnt = i+1
153    append_fdt_node(fit_file, dtbs_file_name)
154    fit_file.write('%s\n' % DT_IMAGES_NODE_END)
155    append_conf_node(fit_file, dtbs_file_name, atf_cnt)
156    fit_file.write('%s\n' % DT_END)
157
158    if fit_file_name != sys.stdout:
159        fit_file.close()
160
161def generate_atf_binary(bl31_file_name):
162    with open(bl31_file_name, 'rb') as bl31_file:
163        bl31 = ELFFile(bl31_file)
164
165        num = bl31.num_segments()
166        for i in range(num):
167            seg = bl31.get_segment(i)
168            if ('PT_LOAD' == seg.__getitem__(ELF_SEG_P_TYPE)):
169                paddr = seg.__getitem__(ELF_SEG_P_PADDR)
170                file_name = 'bl31_0x%08x.bin' % paddr
171                with open(file_name, "wb") as atf:
172                    atf.write(seg.data());
173
174def get_bl31_segments_info(bl31_file_name):
175    """
176    Get load offset, physical offset, file size
177    from bl31 elf file program headers.
178    """
179    with open(bl31_file_name) as bl31_file:
180        bl31 = ELFFile(bl31_file)
181
182        num = bl31.num_segments()
183        print('Number of Segments : %d' % bl31.num_segments())
184        for i in range(num):
185            print('Segment %d' % i)
186            seg = bl31.get_segment(i)
187            ptype = seg[ELF_SEG_P_TYPE]
188            poffset = seg[ELF_SEG_P_OFFSET]
189            pmemsz = seg[ELF_SEG_P_MEMSZ]
190            pfilesz = seg[ELF_SEG_P_FILESZ]
191            print('type: %s\nfilesz: %08x\nmemsz: %08x\noffset: %08x' % (ptype, pfilesz, pmemsz, poffset))
192            paddr = seg[ELF_SEG_P_PADDR]
193            print('paddr: %08x' % paddr)
194
195def main():
196    uboot_elf="./u-boot"
197    bl31_elf="./bl31.elf"
198    FIT_ITS=sys.stdout
199
200    opts, args = getopt.getopt(sys.argv[1:], "o:u:b:h")
201    for opt, val in opts:
202        if opt == "-o":
203            FIT_ITS=val
204        elif opt == "-u":
205            uboot_elf=val
206        elif opt == "-b":
207            bl31_elf=val
208        elif opt == "-h":
209            print(__doc__)
210            sys.exit(2)
211
212    dtbs = args
213    #get_bl31_segments_info("u-boot")
214    #get_bl31_segments_info("bl31.elf")
215
216    generate_atf_fit_dts(FIT_ITS, bl31_elf, uboot_elf, dtbs)
217    generate_atf_binary(bl31_elf);
218
219if __name__ == "__main__":
220    main()
221