1import os
2import sys
3import rtconfig
4from esptool.bin_image import ELFFile, ImageSegment, LoadFirmwareImage
5from esptool.targets import CHIP_DEFS, CHIP_LIST, ROM_LIST
6
7def elf2image(target, source, env):
8    e = ELFFile("rtthread.elf")
9
10    print("Creating esp32c3 image...")
11
12    image = CHIP_DEFS["esp32c3"].BOOTLOADER_IMAGE()
13    image.min_rev = 3
14    image.entrypoint = e.entrypoint
15    image.flash_mode = 2 # flash_mode: dio
16
17    # ELFSection is a subclass of ImageSegment, so can use interchangeably
18    image.segments = e.sections
19    image.flash_size_freq = image.ROM_LOADER.parse_flash_size_arg("4MB")
20    image.flash_size_freq += image.ROM_LOADER.parse_flash_freq_arg("80m")
21
22    image.elf_sha256 = e.sha256()
23    image.elf_sha256_offset = 0xb0
24
25    before = len(image.segments)
26    image.merge_adjacent_segments()
27    if len(image.segments) != before:
28        delta = before - len(image.segments)
29        print("Merged %d ELF section%s" % (delta, "s" if delta > 1 else ""))
30
31    image.verify()
32
33    image.save("rtthread.bin")
34
35    print("Successfully created esp32c3 image.")
36
37if os.getenv('RTT_ROOT'):
38    RTT_ROOT = os.getenv('RTT_ROOT')
39else:
40    RTT_ROOT = os.path.join(os.getcwd(), '..', '..')
41
42sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')]
43from building import *
44
45TARGET = 'rtthread.' + rtconfig.TARGET_EXT
46
47DefaultEnvironment(tools=[])
48env = Environment(tools = ['mingw'],
49    AS   = rtconfig.AS, ASFLAGS = rtconfig.AFLAGS,
50    CC   = rtconfig.CC, CFLAGS = rtconfig.CFLAGS,
51    CXX  = rtconfig.CXX, CXXFLAGS = rtconfig.CXXFLAGS,
52    AR   = rtconfig.AR, ARFLAGS = '-rc',
53    LINK = rtconfig.LINK, LINKFLAGS = rtconfig.LFLAGS)
54env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
55env['ASCOM'] = env['ASPPCOM']
56
57Export('RTT_ROOT')
58Export('rtconfig')
59
60# prepare building environment
61objs = PrepareBuilding(env, RTT_ROOT, remove_components = ['libc'])
62
63# make a building
64DoBuilding(TARGET, objs)
65
66# 添加构建后的钩子函数
67env.AddPostAction(TARGET, elf2image)
68