binman: Correct path for fip_util
[platform/kernel/u-boot.git] / tools / binman / fip_util_test.py
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: GPL-2.0+
3 # Copyright 2021 Google LLC
4 # Written by Simon Glass <sjg@chromium.org>
5
6 """Tests for fip_util
7
8 This tests a few features of fip_util which are not covered by binman's ftest.py
9 """
10
11 import os
12 import shutil
13 import sys
14 import tempfile
15 import unittest
16
17 # Bring in the patman and dtoc libraries (but don't override the first path
18 # in PYTHONPATH)
19 OUR_PATH = os.path.dirname(os.path.realpath(__file__))
20 sys.path.insert(2, os.path.join(OUR_PATH, '..'))
21
22 # pylint: disable=C0413
23 from patman import test_util
24 from patman import tools
25 from binman import fip_util
26
27 HAVE_FIPTOOL = True
28 try:
29     tools.Run('which', 'fiptool')
30 except ValueError:
31     HAVE_FIPTOOL = False
32
33 # pylint: disable=R0902,R0904
34 class TestFip(unittest.TestCase):
35     """Test of fip_util classes"""
36     #pylint: disable=W0212
37     def setUp(self):
38         # Create a temporary directory for test files
39         self._indir = tempfile.mkdtemp(prefix='fip_util.')
40         tools.SetInputDirs([self._indir])
41
42         # Set up a temporary output directory, used by the tools library when
43         # compressing files
44         tools.PrepareOutputDir(None)
45
46         self.src_file = os.path.join(self._indir, 'orig.py')
47         self.outname = tools.GetOutputFilename('out.py')
48         self.args = ['-D', '-s', self._indir, '-o', self.outname]
49         self.readme = os.path.join(self._indir, 'readme.rst')
50         self.macro_dir = os.path.join(self._indir, 'include/tools_share')
51         self.macro_fname = os.path.join(self.macro_dir,
52                                         'firmware_image_package.h')
53         self.name_dir = os.path.join(self._indir, 'tools/fiptool')
54         self.name_fname = os.path.join(self.name_dir, 'tbbr_config.c')
55
56     macro_contents = '''
57
58 /* ToC Entry UUIDs */
59 #define UUID_TRUSTED_UPDATE_FIRMWARE_SCP_BL2U \\
60         {{0x65, 0x92, 0x27, 0x03}, {0x2f, 0x74}, {0xe6, 0x44}, 0x8d, 0xff, {0x57, 0x9a, 0xc1, 0xff, 0x06, 0x10} }
61 #define UUID_TRUSTED_UPDATE_FIRMWARE_BL2U \\
62         {{0x60, 0xb3, 0xeb, 0x37}, {0xc1, 0xe5}, {0xea, 0x41}, 0x9d, 0xf3, {0x19, 0xed, 0xa1, 0x1f, 0x68, 0x01} }
63
64 '''
65
66     name_contents = '''
67
68 toc_entry_t toc_entries[] = {
69         {
70                 .name = "SCP Firmware Updater Configuration FWU SCP_BL2U",
71                 .uuid = UUID_TRUSTED_UPDATE_FIRMWARE_SCP_BL2U,
72                 .cmdline_name = "scp-fwu-cfg"
73         },
74         {
75                 .name = "AP Firmware Updater Configuration BL2U",
76                 .uuid = UUID_TRUSTED_UPDATE_FIRMWARE_BL2U,
77                 .cmdline_name = "ap-fwu-cfg"
78         },
79 '''
80
81     def setup_readme(self):
82         """Set up the readme.txt file"""
83         tools.WriteFile(self.readme, 'Trusted Firmware-A\n==================',
84                         binary=False)
85
86     def setup_macro(self, data=macro_contents):
87         """Set up the tbbr_config.c file"""
88         os.makedirs(self.macro_dir)
89         tools.WriteFile(self.macro_fname, data, binary=False)
90
91     def setup_name(self, data=name_contents):
92         """Set up the firmware_image_package.h file"""
93         os.makedirs(self.name_dir)
94         tools.WriteFile(self.name_fname, data, binary=False)
95
96     def tearDown(self):
97         """Remove the temporary input directory and its contents"""
98         if self._indir:
99             shutil.rmtree(self._indir)
100         self._indir = None
101         tools.FinaliseOutputDir()
102
103     def test_no_readme(self):
104         """Test handling of a missing readme.rst"""
105         with self.assertRaises(Exception) as err:
106             fip_util.main(self.args, self.src_file)
107         self.assertIn('Expected file', str(err.exception))
108
109     def test_invalid_readme(self):
110         """Test that an invalid readme.rst is detected"""
111         tools.WriteFile(self.readme, 'blah', binary=False)
112         with self.assertRaises(Exception) as err:
113             fip_util.main(self.args, self.src_file)
114         self.assertIn('does not start with', str(err.exception))
115
116     def test_no_fip_h(self):
117         """Check handling of missing firmware_image_package.h"""
118         self.setup_readme()
119         with self.assertRaises(Exception) as err:
120             fip_util.main(self.args, self.src_file)
121         self.assertIn('No such file or directory', str(err.exception))
122
123     def test_invalid_fip_h(self):
124         """Check failure to parse firmware_image_package.h"""
125         self.setup_readme()
126         self.setup_macro('blah')
127         with self.assertRaises(Exception) as err:
128             fip_util.main(self.args, self.src_file)
129         self.assertIn('Cannot parse file', str(err.exception))
130
131     def test_parse_fip_h(self):
132         """Check parsing of firmware_image_package.h"""
133         self.setup_readme()
134         # Check parsing the header file
135         self.setup_macro()
136         macros = fip_util.parse_macros(self._indir)
137         expected_macros = {
138             'UUID_TRUSTED_UPDATE_FIRMWARE_SCP_BL2U':
139                 ('ToC Entry UUIDs', 'UUID_TRUSTED_UPDATE_FIRMWARE_SCP_BL2U',
140                  bytes([0x65, 0x92, 0x27, 0x03, 0x2f, 0x74, 0xe6, 0x44,
141                         0x8d, 0xff, 0x57, 0x9a, 0xc1, 0xff, 0x06, 0x10])),
142             'UUID_TRUSTED_UPDATE_FIRMWARE_BL2U':
143                 ('ToC Entry UUIDs', 'UUID_TRUSTED_UPDATE_FIRMWARE_BL2U',
144                  bytes([0x60, 0xb3, 0xeb, 0x37, 0xc1, 0xe5, 0xea, 0x41,
145                         0x9d, 0xf3, 0x19, 0xed, 0xa1, 0x1f, 0x68, 0x01])),
146             }
147         self.assertEqual(expected_macros, macros)
148
149     def test_missing_tbbr_c(self):
150         """Check handlinh of missing tbbr_config.c"""
151         self.setup_readme()
152         self.setup_macro()
153
154         # Still need the .c file
155         with self.assertRaises(Exception) as err:
156             fip_util.main(self.args, self.src_file)
157         self.assertIn('tbbr_config.c', str(err.exception))
158
159     def test_invalid_tbbr_c(self):
160         """Check failure to parse tbbr_config.c"""
161         self.setup_readme()
162         self.setup_macro()
163         # Check invalid format for C file
164         self.setup_name('blah')
165         with self.assertRaises(Exception) as err:
166             fip_util.main(self.args, self.src_file)
167         self.assertIn('Cannot parse file', str(err.exception))
168
169     def test_inconsistent_tbbr_c(self):
170         """Check tbbr_config.c in a format we don't expect"""
171         self.setup_readme()
172         # This is missing a hex value
173         self.setup_macro('''
174
175 /* ToC Entry UUIDs */
176 #define UUID_TRUSTED_UPDATE_FIRMWARE_SCP_BL2U \\
177         {{0x65, 0x92, 0x27,}, {0x2f, 0x74}, {0xe6, 0x44}, 0x8d, 0xff, {0x57, 0x9a, 0xc1, 0xff, 0x06, 0x10} }
178 #define UUID_TRUSTED_UPDATE_FIRMWARE_BL2U \\
179         {{0x60, 0xb3, 0xeb, 0x37}, {0xc1, 0xe5}, {0xea, 0x41}, 0x9d, 0xf3, {0x19, 0xed, 0xa1, 0x1f, 0x68, 0x01} }
180
181 ''')
182         # Check invalid format for C file
183         self.setup_name('blah')
184         with self.assertRaises(Exception) as err:
185             fip_util.main(self.args, self.src_file)
186         self.assertIn('Cannot parse UUID line 5', str(err.exception))
187
188     def test_parse_tbbr_c(self):
189         """Check parsing tbbr_config.c"""
190         self.setup_readme()
191         self.setup_macro()
192         self.setup_name()
193
194         names = fip_util.parse_names(self._indir)
195
196         expected_names = {
197             'UUID_TRUSTED_UPDATE_FIRMWARE_SCP_BL2U': (
198                 'SCP Firmware Updater Configuration FWU SCP_BL2U',
199                 'UUID_TRUSTED_UPDATE_FIRMWARE_SCP_BL2U',
200                 'scp-fwu-cfg'),
201             'UUID_TRUSTED_UPDATE_FIRMWARE_BL2U': (
202                 'AP Firmware Updater Configuration BL2U',
203                 'UUID_TRUSTED_UPDATE_FIRMWARE_BL2U',
204                 'ap-fwu-cfg'),
205             }
206         self.assertEqual(expected_names, names)
207
208     def test_uuid_not_in_tbbr_config_c(self):
209         """Check handling a UUID in the header file that's not in the .c file"""
210         self.setup_readme()
211         self.setup_macro(self.macro_contents + '''
212 #define UUID_TRUSTED_OS_FW_KEY_CERT \\
213         {{0x94,  0x77, 0xd6, 0x03}, {0xfb, 0x60}, {0xe4, 0x11}, 0x85, 0xdd, {0xb7, 0x10, 0x5b, 0x8c, 0xee, 0x04} }
214
215 ''')
216         self.setup_name()
217
218         macros = fip_util.parse_macros(self._indir)
219         names = fip_util.parse_names(self._indir)
220         with test_util.capture_sys_output() as (stdout, _):
221             fip_util.create_code_output(macros, names)
222         self.assertIn(
223             "UUID 'UUID_TRUSTED_OS_FW_KEY_CERT' is not mentioned in tbbr_config.c file",
224             stdout.getvalue())
225
226     def test_changes(self):
227         """Check handling of a source file that does/doesn't need changes"""
228         self.setup_readme()
229         self.setup_macro()
230         self.setup_name()
231
232         # Check generating the file when changes are needed
233         tools.WriteFile(self.src_file, '''
234
235 # This is taken from tbbr_config.c in ARM Trusted Firmware
236 FIP_TYPE_LIST = [
237     # ToC Entry UUIDs
238     FipType('scp-fwu-cfg', 'SCP Firmware Updater Configuration FWU SCP_BL2U',
239             [0x65, 0x92, 0x27, 0x03, 0x2f, 0x74, 0xe6, 0x44,
240              0x8d, 0xff, 0x57, 0x9a, 0xc1, 0xff, 0x06, 0x10]),
241     ] # end
242 blah de blah
243                         ''', binary=False)
244         with test_util.capture_sys_output() as (stdout, _):
245             fip_util.main(self.args, self.src_file)
246         self.assertIn('Needs update', stdout.getvalue())
247
248         # Check generating the file when no changes are needed
249         tools.WriteFile(self.src_file, '''
250 # This is taken from tbbr_config.c in ARM Trusted Firmware
251 FIP_TYPE_LIST = [
252     # ToC Entry UUIDs
253     FipType('scp-fwu-cfg', 'SCP Firmware Updater Configuration FWU SCP_BL2U',
254             [0x65, 0x92, 0x27, 0x03, 0x2f, 0x74, 0xe6, 0x44,
255              0x8d, 0xff, 0x57, 0x9a, 0xc1, 0xff, 0x06, 0x10]),
256     FipType('ap-fwu-cfg', 'AP Firmware Updater Configuration BL2U',
257             [0x60, 0xb3, 0xeb, 0x37, 0xc1, 0xe5, 0xea, 0x41,
258              0x9d, 0xf3, 0x19, 0xed, 0xa1, 0x1f, 0x68, 0x01]),
259     ] # end
260 blah blah''', binary=False)
261         with test_util.capture_sys_output() as (stdout, _):
262             fip_util.main(self.args, self.src_file)
263         self.assertIn('is up-to-date', stdout.getvalue())
264
265     def test_no_debug(self):
266         """Test running without the -D flag"""
267         self.setup_readme()
268         self.setup_macro()
269         self.setup_name()
270
271         args = self.args.copy()
272         args.remove('-D')
273         tools.WriteFile(self.src_file, '', binary=False)
274         with test_util.capture_sys_output():
275             fip_util.main(args, self.src_file)
276
277     @unittest.skipIf(not HAVE_FIPTOOL, 'No fiptool available')
278     def test_fiptool_list(self):
279         """Create a FIP and check that fiptool can read it"""
280         fwu = b'my data'
281         tb_fw = b'some more data'
282         fip = fip_util.FipWriter(0x123, 0x10)
283         fip.add_entry('fwu', fwu, 0x456)
284         fip.add_entry('tb-fw', tb_fw, 0)
285         fip.add_entry(bytes(range(16)), tb_fw, 0)
286         data = fip.get_data()
287         fname = tools.GetOutputFilename('data.fip')
288         tools.WriteFile(fname, data)
289         result = fip_util.fiptool('info', fname)
290         self.assertEqual(
291             '''Firmware Updater NS_BL2U: offset=0xB0, size=0x7, cmdline="--fwu"
292 Trusted Boot Firmware BL2: offset=0xC0, size=0xE, cmdline="--tb-fw"
293 00010203-0405-0607-0809-0A0B0C0D0E0F: offset=0xD0, size=0xE, cmdline="--blob"
294 ''',
295             result.stdout)
296
297     fwu_data = b'my data'
298     tb_fw_data = b'some more data'
299     other_fw_data = b'even more'
300
301     def create_fiptool_image(self):
302         """Create an image with fiptool which we can use for testing
303
304         Returns:
305             FipReader: reader for the image
306         """
307         fwu = os.path.join(self._indir, 'fwu')
308         tools.WriteFile(fwu, self.fwu_data)
309
310         tb_fw = os.path.join(self._indir, 'tb_fw')
311         tools.WriteFile(tb_fw, self.tb_fw_data)
312
313         other_fw = os.path.join(self._indir, 'other_fw')
314         tools.WriteFile(other_fw, self.other_fw_data)
315
316         fname = tools.GetOutputFilename('data.fip')
317         uuid = 'e3b78d9e-4a64-11ec-b45c-fba2b9b49788'
318         fip_util.fiptool('create', '--align', '8', '--plat-toc-flags', '0x123',
319                          '--fwu', fwu,
320                          '--tb-fw', tb_fw,
321                          '--blob', f'uuid={uuid},file={other_fw}',
322                           fname)
323
324         return fip_util.FipReader(tools.ReadFile(fname))
325
326     @unittest.skipIf(not HAVE_FIPTOOL, 'No fiptool available')
327     def test_fiptool_create(self):
328         """Create a FIP with fiptool and check that fip_util can read it"""
329         reader = self.create_fiptool_image()
330
331         header = reader.header
332         fents = reader.fents
333
334         self.assertEqual(0x123 << 32, header.flags)
335         self.assertEqual(fip_util.HEADER_MAGIC, header.name)
336         self.assertEqual(fip_util.HEADER_SERIAL, header.serial)
337
338         self.assertEqual(3, len(fents))
339         fent = fents[0]
340         self.assertEqual(
341             bytes([0x4f, 0x51, 0x1d, 0x11, 0x2b, 0xe5, 0x4e, 0x49,
342                    0xb4, 0xc5, 0x83, 0xc2, 0xf7, 0x15, 0x84, 0x0a]), fent.uuid)
343         self.assertEqual(0xb0, fent.offset)
344         self.assertEqual(len(self.fwu_data), fent.size)
345         self.assertEqual(0, fent.flags)
346         self.assertEqual(self.fwu_data, fent.data)
347
348         fent = fents[1]
349         self.assertEqual(
350             bytes([0x5f, 0xf9, 0xec, 0x0b, 0x4d, 0x22, 0x3e, 0x4d,
351              0xa5, 0x44, 0xc3, 0x9d, 0x81, 0xc7, 0x3f, 0x0a]), fent.uuid)
352         self.assertEqual(0xb8, fent.offset)
353         self.assertEqual(len(self.tb_fw_data), fent.size)
354         self.assertEqual(0, fent.flags)
355         self.assertEqual(self.tb_fw_data, fent.data)
356
357         fent = fents[2]
358         self.assertEqual(
359             bytes([0xe3, 0xb7, 0x8d, 0x9e, 0x4a, 0x64, 0x11, 0xec,
360                    0xb4, 0x5c, 0xfb, 0xa2, 0xb9, 0xb4, 0x97, 0x88]), fent.uuid)
361         self.assertEqual(0xc8, fent.offset)
362         self.assertEqual(len(self.other_fw_data), fent.size)
363         self.assertEqual(0, fent.flags)
364         self.assertEqual(self.other_fw_data, fent.data)
365
366     @unittest.skipIf(not HAVE_FIPTOOL, 'No fiptool available')
367     def test_reader_get_entry(self):
368         """Test get_entry() by name and UUID"""
369         reader = self.create_fiptool_image()
370         fents = reader.fents
371         fent = reader.get_entry('fwu')
372         self.assertEqual(fent, fents[0])
373
374         fent = reader.get_entry(
375             bytes([0x5f, 0xf9, 0xec, 0x0b, 0x4d, 0x22, 0x3e, 0x4d,
376                    0xa5, 0x44, 0xc3, 0x9d, 0x81, 0xc7, 0x3f, 0x0a]))
377         self.assertEqual(fent, fents[1])
378
379         # Try finding entries that don't exist
380         with self.assertRaises(Exception) as err:
381             fent = reader.get_entry('scp-fwu-cfg')
382         self.assertIn("Cannot find FIP entry 'scp-fwu-cfg'", str(err.exception))
383
384         with self.assertRaises(Exception) as err:
385             fent = reader.get_entry(bytes(list(range(16))))
386         self.assertIn(
387             "Cannot find FIP entry '00010203-0405-0607-0809-0a0b0c0d0e0f'",
388             str(err.exception))
389
390         with self.assertRaises(Exception) as err:
391             fent = reader.get_entry('blah')
392         self.assertIn("Unknown FIP entry type 'blah'", str(err.exception))
393
394     @unittest.skipIf(not HAVE_FIPTOOL, 'No fiptool available')
395     def test_fiptool_errors(self):
396         """Check some error reporting from fiptool"""
397         with self.assertRaises(Exception) as err:
398             with test_util.capture_sys_output():
399                 fip_util.fiptool('create', '--fred')
400         self.assertIn("Failed to run (error 1): 'fiptool create --fred'",
401                       str(err.exception))
402
403
404 if __name__ == '__main__':
405     unittest.main()