1#-------------------------------------------------------------------------------
2# Copyright (c) 2021, Arm Limited. All rights reserved.
3#
4# SPDX-License-Identifier: BSD-3-Clause
5#
6#-------------------------------------------------------------------------------
7
8import argparse
9import hashlib
10import os
11import sys
12sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../../bl2/ext/mcuboot/scripts"))
13import macro_parser
14import struct
15
16def hash_binary_blob(blob):
17   hash = hashlib.sha256()
18   hash.update(blob)
19   return hash.digest()
20
21def struct_pack(objects, pad_to=0):
22    defstring = "<"
23    for obj in objects:
24        defstring += str(len(obj)) + "s"
25
26    size = struct.calcsize(defstring)
27    if size < pad_to:
28        defstring += str(pad_to - size) + "x"
29
30    return (bytes(struct.pack(defstring, *objects)))
31
32
33parser = argparse.ArgumentParser()
34parser.add_argument("--input_file", help="the image to process", required=True)
35parser.add_argument("--img_output_file", help="image output file", required=True)
36parser.add_argument("--hash_output_file", help="hash output file", required=True)
37parser.add_argument("--signing_layout_file", help="signing layout file", required=True)
38args = parser.parse_args()
39
40with open(args.input_file, "rb") as in_file:
41    bl1_2_code = in_file.read()
42
43bl1_2_partition_size = macro_parser.evaluate_macro(args.signing_layout_file,
44                                    ".*(RE_BL1_2_BIN_SIZE) = *(.*)",
45                                    1, 2, True)['RE_BL1_2_BIN_SIZE']
46
47image = struct_pack([bl1_2_code], pad_to=bl1_2_partition_size)
48hash = hash_binary_blob(image)
49
50with open(args.img_output_file, "wb") as img_out_file:
51    img_out_file.write(image)
52
53with open(args.hash_output_file, "wb") as hash_out_file:
54    hash_out_file.write(hash)
55