xref: /rk3399_rockchip-uboot/lib/optee_clientApi/tabinary_to_img.py (revision ef3be6ac12a87b304d0a8eeff74cfcdbac906ec5)
1#!/usr/bin/env python3
2#
3# Copyright 2023, Rockchip Electronics Co., Ltd
4# hisping lin, <hisping.lin@rock-chips.com>
5#
6# SPDX-License-Identifier:	GPL-2.0+
7#
8
9def get_args():
10	import argparse
11
12	parser = argparse.ArgumentParser()
13
14	parser.add_argument('--out', required=True, \
15		help='Name of image for the TA')
16
17	parser.add_argument('--tadir', required=True, help='Path of TA director')
18
19	return parser.parse_args()
20
21def main():
22	import os
23	import array
24	import glob
25	import struct
26	import uuid
27	try:
28		from Cryptodome.Hash import SHA256
29	except ImportError:
30		from Crypto.Hash import SHA256
31
32	args = get_args();
33
34	path = args.tadir + "/*.ta"
35	files = glob.glob(path)
36	for f in files:
37		print(f)
38
39	fimg = open(args.out, 'wb')
40	magic = 0x524B5441 #RKTA
41	img_ver = 0x00000001
42	ta_num = len(files)
43	reserve = 0
44	header = struct.pack('<IIII', magic, img_ver, ta_num, reserve)
45	fimg.write(header)
46
47	g_offset = len(header) + (ta_num * 32)
48	for f in files:
49		fta = open(f, 'rb')
50		tadata = fta.read()
51		fta.close
52		ta_name = os.path.basename(f)
53		ta_name_without_extension = os.path.splitext(ta_name)[0]
54		ta_uuid = uuid.UUID(ta_name_without_extension)
55		ta_uuid_hex = bytes.fromhex(ta_uuid.hex)
56		fimg.write(ta_uuid_hex)
57		ta_offset = struct.pack('<I', g_offset)
58		fimg.write(ta_offset)
59		ta_len = struct.pack('<I', len(tadata))
60		fimg.write(ta_len)
61		ta_ver_num = len(ta_name_without_extension) - 34;
62		ta_ver = struct.pack('<I', ta_ver_num)
63		fimg.write(ta_ver)
64		ta_reserve = struct.pack('<I', reserve)
65		fimg.write(ta_reserve)
66		g_offset += len(tadata)
67
68	for f in files:
69		fta = open(f, 'rb')
70		tadata = fta.read()
71		fta.close
72		fimg.write(tadata)
73	fimg.close
74
75	fimg = open(args.out, 'rb+')
76	userta = fimg.read()
77	h = SHA256.new()
78	h.update(userta)
79	img_digest = h.digest()
80	fimg.write(img_digest)
81	fimg.close
82
83	print("pack ta binary success!")
84
85if __name__ == "__main__":
86	main()
87