chen
2024-11-01 631a90c1116fa33382a88a747c89bf761bc0fa9b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 
import sys
import os
import re
 
def extract_vectors_address(map_file):
    with open(map_file, 'r') as f:
        map_content = f.readlines()
    
    pattern = re.compile(r'^\s+__Vectors\s+([0-9a-fA-Fx]+)\s+.*$')
 
    for line in map_content:
        match = re.match(pattern, line)
        if match:
            return match.group(1)
 
    return None
 
def bin2carray(bin_file, c_file, array_name):
    with open(bin_file, 'rb') as infile:
        data = infile.read()
 
    with open(c_file, 'w') as outfile:
        outfile.write(f"static const unsigned char {array_name}[0x%x] = {{\n" % len(data))
 
        for i, byte in enumerate(data):
            if i % 16 == 0:
                if i != 0:
                    outfile.write("\n    ")
                else:
                    outfile.write("    ")
            outfile.write(f"0x{byte:02X}, ")
 
        outfile.write("\n};\n")
        
    return len(data)
    
def append_ss_address(bin_file, vectors_address, bin_len):
    with open(c_file, 'a') as outfile:
        outfile.write("\n#define _customboot_start_address " + vectors_address + "\n")
        outfile.write("\n#define _customboot_end_address 0x%x\n" % (int(vectors_address, 16) + bin_len))
    
if __name__ == "__main__":         
    bin_file = '../customboot/Output/customboot.bin'
    c_file = '../../src/secondboot/_customboot_image.c'
    array_name = '_customboot_image'
    
    try:
        os.remove(c_file)
    except:
        pass
    
    if os.path.exists(bin_file):
        bin_len = bin2carray(bin_file, c_file, array_name)
        print(f"Binary file '{bin_file}' converted to C array in '{c_file}' with array name '{array_name}'")
        
        map_file = '../customboot/Listings/customboot.map'
 
        vectors_address = extract_vectors_address(map_file)
        
        if vectors_address:
            print(f"Extracted customboot __Vectors address: {vectors_address}")
            append_ss_address(c_file, vectors_address, bin_len)
        else:
            print("No customboot __Vectors address found in the map file.")