forked from commaai/panda
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSConscript
More file actions
253 lines (219 loc) · 9.21 KB
/
Copy pathSConscript
File metadata and controls
253 lines (219 loc) · 9.21 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import os
import hashlib
import opendbc
import subprocess
PREFIX = "arm-none-eabi-"
BUILDER = "DEV"
common_flags = []
if os.getenv("RELEASE"):
BUILD_TYPE = "RELEASE"
cert_fn = os.getenv("CERT")
assert cert_fn is not None, 'No certificate file specified. Please set CERT env variable'
assert os.path.exists(cert_fn), 'Certificate file not found. Please specify absolute path'
else:
BUILD_TYPE = "DEBUG"
cert_fn = File("./board/certs/debug").srcnode().relpath
common_flags += ["-DALLOW_DEBUG"]
if os.getenv("DEBUG"):
common_flags += ["-DDEBUG"]
def objcopy(source, target, env, for_signature):
return '$OBJCOPY -O binary %s %s' % (source[0], target[0])
def get_version(builder, build_type):
try:
git = subprocess.check_output(["git", "rev-parse", "--short=8", "HEAD"], encoding='utf8').strip()
except subprocess.CalledProcessError:
git = "unknown"
return f"{builder}-{git}-{build_type}"
def get_key_header(name):
from Crypto.PublicKey import RSA
public_fn = File(f'./board/certs/{name}.pub').srcnode().get_path()
with open(public_fn) as f:
rsa = RSA.importKey(f.read())
assert(rsa.size_in_bits() == 1024)
rr = pow(2**1024, 2, rsa.n)
n0inv = 2**32 - pow(rsa.n, -1, 2**32)
r = [
f"RSAPublicKey {name}_rsa_key = {{",
f" .len = 0x20,",
f" .n0inv = {n0inv}U,",
f" .n = {to_c_uint32(rsa.n)},",
f" .rr = {to_c_uint32(rr)},",
f" .exponent = {rsa.e},",
f"}};",
]
return r
def to_c_uint32(x):
nums = []
for _ in range(0x20):
nums.append(x % (2**32))
x //= (2**32)
return "{" + 'U,'.join(map(str, nums)) + "U}"
def build_project(project_name, project, main, extra_flags):
project_dir = Dir(f'./board/obj/{project_name}/')
flags = project["FLAGS"] + extra_flags + common_flags + [
"-Wall",
"-Wextra",
"-Wstrict-prototypes",
"-Werror",
"-mlittle-endian",
"-mthumb",
"-nostdlib",
"-fno-builtin",
"-std=gnu11",
"-fmax-errors=1",
f"-T{File(project['LINKER_SCRIPT']).srcnode().relpath}",
"-fsingle-precision-constant",
"-Os",
"-g",
]
env = Environment(
ENV=os.environ,
CC=PREFIX + 'gcc',
AS=PREFIX + 'gcc',
OBJCOPY=PREFIX + 'objcopy',
OBJDUMP=PREFIX + 'objdump',
OBJPREFIX=project_dir,
CFLAGS=flags,
ASFLAGS=flags,
LINKFLAGS=flags,
CPPPATH=[Dir("./"), "./board/stm32h7/inc", opendbc.INCLUDE_PATH],
ASCOM="$AS $ASFLAGS -o $TARGET -c $SOURCES",
BUILDERS={
'Objcopy': Builder(generator=objcopy, suffix='.bin', src_suffix='.elf')
},
tools=["default", "compilation_db"],
)
startup = env.Object(project["STARTUP_FILE"])
# Build bootstub
bs_env = env.Clone()
bs_env.Append(CFLAGS="-DBOOTSTUB", ASFLAGS="-DBOOTSTUB", LINKFLAGS="-DBOOTSTUB")
bs_elf = bs_env.Program(f"{project_dir}/bootstub.elf", [
startup,
"./board/crypto/rsa.c",
"./board/crypto/sha.c",
"./board/bootstub.c",
])
bs_env.Objcopy(f"./board/obj/bootstub.{project_name}.bin", bs_elf)
# Build + sign main (aka app)
main_elf = env.Program(f"{project_dir}/main.elf", [
startup,
main
], LINKFLAGS=[f"-Wl,--section-start,.isr_vector={project['APP_START_ADDRESS']}"] + flags)
main_bin = env.Objcopy(f"{project_dir}/main.bin", main_elf)
sign_py = File(f"./board/crypto/sign.py").srcnode().relpath
env.Command(f"./board/obj/{project_name}.bin.signed", main_bin, f"SETLEN=1 {sign_py} $SOURCE $TARGET {cert_fn}")
base_project_h7 = {
"STARTUP_FILE": "./board/stm32h7/startup_stm32h7x5xx.s",
"LINKER_SCRIPT": "./board/stm32h7/stm32h7x5_flash.ld",
"APP_START_ADDRESS": "0x8020000",
"FLAGS": [
"-mcpu=cortex-m7",
"-mhard-float",
"-DSTM32H7",
"-DSTM32H725xx",
"-Iboard/stm32h7/inc",
"-mfpu=fpv5-d16",
],
}
# Common autogenerated includes
with open("board/obj/gitversion.h", "w") as f:
version = get_version(BUILDER, BUILD_TYPE)
f.write(f'extern const uint8_t gitversion[{len(version)+1}];\n')
f.write(f'const uint8_t gitversion[{len(version)+1}] = "{version}";\n')
with open("board/obj/version", "w") as f:
f.write(f'{get_version(BUILDER, BUILD_TYPE)}')
certs = [get_key_header(n) for n in ["debug", "release"]]
with open("board/obj/cert.h", "w") as f:
for cert in certs:
f.write("\n".join(cert) + "\n")
# Packet version defines: SHA hash of the struct header files
def version_hash(path):
with open(path, "rb") as f:
# Normalize line endings on Windows
return int.from_bytes(hashlib.sha256(f.read().replace(b'\r', b'')).digest()[:4], 'little')
hh, ch, jh = version_hash("board/health.h"), version_hash(os.path.join(opendbc.INCLUDE_PATH, "opendbc/safety/can.h")), version_hash("board/jungle/jungle_health.h")
common_flags += [f"-DHEALTH_PACKET_VERSION=0x{hh:08X}U", f"-DCAN_PACKET_VERSION_HASH=0x{ch:08X}U",
f"-DJUNGLE_HEALTH_PACKET_VERSION=0x{jh:08X}U"]
# panda fw
build_project("panda_h7", base_project_h7, "./board/main.c", [])
# panda jungle fw
flags = [
"-DPANDA_JUNGLE",
]
build_project("panda_jungle_h7", base_project_h7, "./board/jungle/main.c", flags)
# body fw
build_project("body_h7", base_project_h7, "./board/body/main.c", ["-DPANDA_BODY"])
# RoadStud USB-NCM bridge fw (board/bridge/) — only if sources are vendored.
_bridge_vendor = "board/bridge/vendor"
if os.path.exists(f"{_bridge_vendor}/tinyusb/src") and os.path.exists(f"{_bridge_vendor}/lwip/src"):
_bdir = Dir("./board/obj/panda_bridge/")
_bflags = base_project_h7["FLAGS"] + common_flags + [
"-mlittle-endian", "-mthumb", "-nostdlib", "-fno-builtin", "-std=gnu11",
f"-T{File(base_project_h7['LINKER_SCRIPT']).srcnode().relpath}",
"-fsingle-precision-constant", "-Os", "-g",
]
_bcpp = [
Dir("./"), "./board/stm32h7/inc", opendbc.INCLUDE_PATH,
"board/bridge",
f"{_bridge_vendor}/tinyusb/src",
f"{_bridge_vendor}/tinyusb/networking",
f"{_bridge_vendor}/lwip/src/include",
]
# strict env for our own code (unity TU); relaxed env for vendored + glue.
benv = Environment(
ENV=os.environ, CC=PREFIX + 'gcc', AS=PREFIX + 'gcc',
OBJCOPY=PREFIX + 'objcopy', OBJDUMP=PREFIX + 'objdump',
CFLAGS=_bflags + ["-Wall", "-Wextra", "-Wstrict-prototypes", "-Werror", "-fmax-errors=1"],
ASFLAGS=_bflags, LINKFLAGS=_bflags, CPPPATH=_bcpp,
ASCOM="$AS $ASFLAGS -o $TARGET -c $SOURCES",
BUILDERS={'Objcopy': Builder(generator=objcopy, suffix='.bin', src_suffix='.elf')},
tools=["default"],
)
renv = benv.Clone()
renv['CFLAGS'] = _bflags + ["-Wno-error", "-Wno-unused-parameter"]
_tusb = [
f"{_bridge_vendor}/tinyusb/src/tusb.c",
f"{_bridge_vendor}/tinyusb/src/common/tusb_fifo.c",
f"{_bridge_vendor}/tinyusb/src/device/usbd.c",
f"{_bridge_vendor}/tinyusb/src/class/net/ncm_device.c",
f"{_bridge_vendor}/tinyusb/src/portable/synopsys/dwc2/dcd_dwc2.c",
f"{_bridge_vendor}/tinyusb/src/portable/synopsys/dwc2/dwc2_common.c",
f"{_bridge_vendor}/tinyusb/networking/dhserver.c",
f"{_bridge_vendor}/tinyusb/networking/dnserver.c",
]
_lwip = Glob(f"{_bridge_vendor}/lwip/src/core/*.c") + \
Glob(f"{_bridge_vendor}/lwip/src/core/ipv4/*.c") + \
[f"{_bridge_vendor}/lwip/src/netif/ethernet.c"]
_glue = ["board/bridge/usb_descriptors.c", "board/bridge/lwip_glue.c",
"board/bridge/bridge_can.c", "board/bridge/bridge_libc.c",
"board/bridge/tusb_shim.c"]
_vobjs = [renv.Object(s) for s in (_tusb + _lwip + _glue)]
_bstartup = benv.Object(base_project_h7["STARTUP_FILE"])
# main_bridge pulls panda driver headers written for the full main.c context, so
# some statics are unused here -> build it relaxed too.
_bmain = renv.Object("board/bridge/main_bridge.c")
_belf = benv.Program(f"{_bdir}/main.elf", [_bstartup, _bmain] + _vobjs,
LINKFLAGS=[f"-Wl,--section-start,.isr_vector={base_project_h7['APP_START_ADDRESS']}"] + _bflags)
_bbin = benv.Objcopy(f"{_bdir}/main.bin", _belf)
# Sign the app so the bootstub will accept it and jump to 0x8020000. Mirrors
# build_project: SETLEN=1 prepends the length + appends the VERS tag + RSA sig.
# In a source (non-RELEASE) build cert_fn is board/certs/debug, which matches the
# debug key compiled into any -DALLOW_DEBUG bootstub. No bridge-specific bootstub
# is built: the bootstub is app-agnostic (it only sig-checks + jumps to the app
# address), so the stock debug bootstub.panda_h7.bin — installed by the panda
# library's recover() — is what runs this signed image. See board/bridge/README.md.
_bsign_py = File("./board/crypto/sign.py").srcnode().relpath
benv.Command("./board/obj/panda_bridge.bin.signed", _bbin,
f"SETLEN=1 {_bsign_py} $SOURCE $TARGET {cert_fn}")
# Dev bootstub: the stock bootstub plus an always-on boot-time flash window
# (-DBRIDGE_DEV_FLASH_WINDOW) so a wedged NCM app is always recoverable over USB —
# red has no button / exposed BOOT0. DFU it with PandaDFU; see board/bridge/README.md.
# The stock bootstub.panda_h7.bin is unchanged (no flag), so production is unaffected.
_bs_env = benv.Clone()
_bs_env.Append(CFLAGS=["-DBOOTSTUB", "-DBRIDGE_DEV_FLASH_WINDOW"],
ASFLAGS=["-DBOOTSTUB"], LINKFLAGS=["-DBOOTSTUB"])
_bs_elf = _bs_env.Program(f"{_bdir}/bootstub.elf",
[_bstartup, "./board/crypto/rsa.c", "./board/crypto/sha.c", "./board/bootstub.c"])
_bs_env.Objcopy("./board/obj/bootstub.panda_bridge.bin", _bs_elf)
# test files
SConscript('tests/libpanda/SConscript')