forked from google/OpenSK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deploy.py
executable file
·990 lines (907 loc) · 34 KB
/
deploy.py
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
#!/usr/bin/env python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
# pylint: disable=C0111
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import collections
import copy
import os
import shutil
import subprocess
import sys
import colorama
from six.moves import input
import tockloader
from tockloader import tab
from tockloader import tbfh
from tockloader import tockloader as loader
from tockloader.exceptions import TockLoaderException
PROGRAMMERS = frozenset(("jlink", "openocd", "pyocd", "nordicdfu", "none"))
# This structure allows us to support out-of-tree boards as well as (in the
# future) more achitectures.
OpenSKBoard = collections.namedtuple(
"OpenSKBoard",
[
# Location of the Tock board (where the Makefile file is)
"path",
# Target architecture (e.g. thumbv7em-none-eabi)
"arch",
# Size of 1 page of flash memory
"page_size",
# Flash address at which the kernel will be written
"kernel_address",
# Set to None is padding is not required for the board.
# This creates a fake Tock OS application that starts at the
# address specified by this parameter (must match the `prog` value
# specified on the board's `layout.ld` file) and will end at
# `app_address`.
"padding_address",
# Linker script to produce a working app for this board
"app_ldscript",
# Flash address at which the app should be written
"app_address",
# Flash address of the storage
"storage_address",
# Size of the storage
"storage_size",
# Target name for flashing the board using pyOCD
"pyocd_target",
# The cfg file in OpenOCD board folder
"openocd_board",
# Options to tell Tockloader how to work with OpenOCD
# Default: []
"openocd_options",
# Dictionnary specifying custom commands for OpenOCD
# Default is an empty dict
# Valid keys are: program, read, erase
"openocd_commands",
# Interface to use with JLink (e.g. swd, jtag, etc.)
"jlink_if",
# Device name as supported by JLinkExe
"jlink_device",
# Whether Nordic DFU flashing method is supported
"nordic_dfu",
])
SUPPORTED_BOARDS = {
"nrf52840dk":
OpenSKBoard(
path="third_party/tock/boards/nordic/nrf52840dk",
arch="thumbv7em-none-eabi",
page_size=4096,
kernel_address=0,
padding_address=0x30000,
app_ldscript="nrf52840_layout.ld",
app_address=0x40000,
storage_address=0xC0000,
storage_size=0x40000,
pyocd_target="nrf52840",
openocd_board="nordic_nrf52840_dongle.cfg",
openocd_options=[],
openocd_commands={},
jlink_if="swd",
jlink_device="nrf52840_xxaa",
nordic_dfu=False,
),
"nrf52840_dongle":
OpenSKBoard(
path="third_party/tock/boards/nordic/nrf52840_dongle",
arch="thumbv7em-none-eabi",
page_size=4096,
kernel_address=0,
padding_address=0x30000,
app_ldscript="nrf52840_layout.ld",
app_address=0x40000,
storage_address=0xC0000,
storage_size=0x40000,
pyocd_target="nrf52840",
openocd_board="nordic_nrf52840_dongle.cfg",
openocd_options=[],
openocd_commands={},
jlink_if="swd",
jlink_device="nrf52840_xxaa",
nordic_dfu=False,
),
"nrf52840_dongle_dfu":
OpenSKBoard(
path="third_party/tock/boards/nordic/nrf52840_dongle_dfu",
arch="thumbv7em-none-eabi",
page_size=4096,
kernel_address=0x1000,
padding_address=0x30000,
app_ldscript="nrf52840_layout.ld",
app_address=0x40000,
storage_address=0xC0000,
storage_size=0x40000,
pyocd_target="nrf52840",
openocd_board="nordic_nrf52840_dongle.cfg",
openocd_options=[],
openocd_commands={},
jlink_if="swd",
jlink_device="nrf52840_xxaa",
nordic_dfu=True,
),
"nrf52840_mdk_dfu":
OpenSKBoard(
path="third_party/tock/boards/nordic/nrf52840_mdk_dfu",
arch="thumbv7em-none-eabi",
page_size=4096,
kernel_address=0x1000,
padding_address=0x30000,
app_ldscript="nrf52840_layout.ld",
app_address=0x40000,
storage_address=0xC0000,
storage_size=0x40000,
pyocd_target="nrf52840",
openocd_board="nordic_nrf52840_dongle.cfg",
openocd_options=[],
openocd_commands={},
jlink_if="swd",
jlink_device="nrf52840_xxaa",
nordic_dfu=True,
),
}
# The STACK_SIZE value below must match the one used in the linker script
# used by the board.
# e.g. for Nordic nRF52840 boards the file is `nrf52840_layout.ld`.
STACK_SIZE = 0x4000
# The following value must match the one used in the file
# `src/entry_point.rs`
APP_HEAP_SIZE = 90000
def get_supported_boards():
boards = []
for name, props in SUPPORTED_BOARDS.items():
if all((os.path.exists(os.path.join(props.path, "Cargo.toml")),
(props.app_ldscript and os.path.exists(props.app_ldscript)))):
boards.append(name)
return tuple(set(boards))
def fatal(msg):
print(f"{colorama.Fore.RED + colorama.Style.BRIGHT}fatal:"
f"{colorama.Style.RESET_ALL} {msg}")
sys.exit(1)
def error(msg):
print(f"{colorama.Fore.RED}error:{colorama.Style.RESET_ALL} {msg}")
def info(msg):
print(f"{colorama.Fore.GREEN + colorama.Style.BRIGHT}info:"
f"{colorama.Style.RESET_ALL} {msg}")
def assert_mandatory_binary(binary):
if not shutil.which(binary):
fatal((f"Couldn't find {binary} binary. Make sure it is installed and "
"that your PATH is set correctly."))
def assert_python_library(module):
try:
__import__(module)
except ModuleNotFoundError:
fatal((f"Couldn't load python3 module {module}. "
f"Try to run: pip3 install {module}"))
class RemoveConstAction(argparse.Action):
# pylint: disable=redefined-builtin
def __init__(self,
option_strings,
dest,
const,
default=None,
required=False,
help=None,
metavar=None):
super().__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
const=const,
default=default,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
# Code is simply a modified version of the AppendConstAction from argparse
# https://github.com/python/cpython/blob/master/Lib/argparse.py#L138-L147
# https://github.com/python/cpython/blob/master/Lib/argparse.py#L1028-L1052
items = getattr(namespace, self.dest, [])
if items is None:
items = []
if isinstance(items, list):
items = items[:]
else:
items = copy.copy(items)
if self.const in items:
items.remove(self.const)
setattr(namespace, self.dest, items)
class OpenSKInstaller:
def __init__(self, args):
self.args = args
# Where all the TAB files should go
self.tab_folder = os.path.join("target", "tab")
board = SUPPORTED_BOARDS[self.args.board]
self.tockloader_default_args = argparse.Namespace(
arch=board.arch,
board=self.args.board,
bundle_apps=False,
debug=False,
force=False,
jlink_cmd="JLinkExe",
jlink=self.args.programmer == "jlink",
jlink_device=board.jlink_device,
jlink_if=board.jlink_if,
jlink_speed=1200,
openocd=self.args.programmer == "openocd",
openocd_board=board.openocd_board,
openocd_cmd="openocd",
openocd_commands=copy.copy(board.openocd_commands),
openocd_options=copy.copy(board.openocd_options),
jtag=False,
no_bootloader_entry=False,
page_size=board.page_size,
port=None,
)
def checked_command(self, cmd, env=None, cwd=None):
stdout = None if self.args.verbose_build else subprocess.DEVNULL
try:
subprocess.run(
cmd, stdout=stdout, timeout=None, check=True, env=env, cwd=cwd)
except subprocess.CalledProcessError as e:
fatal(f"Failed to execute {cmd[0]}: {str(e)}")
def checked_command_output(self, cmd, env=None, cwd=None):
cmd_output = ""
try:
cmd_output = subprocess.run(
cmd,
stdout=subprocess.PIPE,
timeout=None,
check=True,
env=env,
cwd=cwd).stdout
except subprocess.CalledProcessError as e:
fatal(f"Failed to execute {cmd[0]}: {str(e)}")
# Unreachable because fatal() will exit
return cmd_output.decode()
def update_rustc_if_needed(self):
target_toolchain_fullstring = "stable"
with open("rust-toolchain", "r", encoding="utf-8") as f:
content = f.readlines()
if len(content) == 1:
# Old format, only the build is stored
target_toolchain_fullstring = content[0].strip()
else:
# New format
for line in content:
if line.startswith("channel"):
channel = line.strip().split("=", maxsplit=1)[1].strip()
target_toolchain_fullstring = channel.strip('"')
target_toolchain = target_toolchain_fullstring.split("-", maxsplit=1)
if len(target_toolchain) == 1:
# If we target the stable version of rust, we won't have a date
# associated to the version and split will only return 1 item.
# To avoid failing later when accessing the date, we insert an
# empty value.
target_toolchain.append("")
current_version = self.checked_command_output(["rustc", "--version"])
if not (target_toolchain[0] in current_version and
target_toolchain[1] in current_version):
info(f"Updating rust toolchain to {'-'.join(target_toolchain)}")
# Need to update
rustup_install = ["rustup"]
if self.args.verbose_build:
rustup_install.append("--verbose")
rustup_install.extend(["install", target_toolchain_fullstring])
self.checked_command(rustup_install)
rustup_target = ["rustup"]
if self.args.verbose_build:
rustup_target.append("--verbose")
rustup_target.extend(
["target", "add", SUPPORTED_BOARDS[self.args.board].arch])
self.checked_command(rustup_target)
info("Rust toolchain up-to-date")
def build_tockos(self):
info(f"Building Tock OS for board {self.args.board}")
props = SUPPORTED_BOARDS[self.args.board]
out_directory = os.path.join("third_party", "tock", "target", props.arch,
"release")
os.makedirs(out_directory, exist_ok=True)
env = os.environ.copy()
if self.args.verbose_build:
env["V"] = "1"
self.checked_command(["make"], cwd=props.path, env=env)
def build_example(self):
info(f"Building example {self.args.application}")
self._build_app_or_example(is_example=True)
def build_opensk(self):
info("Building OpenSK application")
self._build_app_or_example(is_example=False)
def _build_app_or_example(self, is_example):
assert self.args.application
# Ideally we would build a TAB file for all boards at once but depending on
# the chip on the board, the link script could be totally different.
# And elf2tab doesn't seem to let us set the boards a TAB file has been
# created for. So at the moment we only build for the selected board.
props = SUPPORTED_BOARDS[self.args.board]
rust_flags = [
"-C",
f"link-arg=-T{props.app_ldscript}",
"-C",
"relocation-model=static",
"-D",
"warnings",
f"--remap-path-prefix={os.getcwd()}=",
]
env = os.environ.copy()
env["RUSTFLAGS"] = " ".join(rust_flags)
env["APP_HEAP_SIZE"] = str(APP_HEAP_SIZE)
command = [
"cargo", "build", "--release", f"--target={props.arch}",
f"--features={','.join(self.args.features)}"
]
if is_example:
command.extend(["--example", self.args.application])
if self.args.verbose_build:
command.append("--verbose")
self.checked_command(command, env=env)
app_path = os.path.join("target", props.arch, "release")
if is_example:
app_path = os.path.join(app_path, "examples")
app_path = os.path.join(app_path, self.args.application)
# Create a TAB file
self.create_tab_file({props.arch: app_path})
def generate_crypto_materials(self, force_regenerate):
has_error = subprocess.call([
os.path.join("tools", "gen_key_materials.sh"),
"Y" if force_regenerate else "N",
])
if has_error:
error(("Something went wrong while trying to generate ECC "
"key and/or certificate for OpenSK"))
def create_tab_file(self, binaries):
assert binaries
assert self.args.application
info("Generating Tock TAB file for application/example "
f"{self.args.application}")
elf2tab_ver = self.checked_command_output(
["elf2tab/bin/elf2tab", "--version"]).split(
"\n", maxsplit=1)[0]
if elf2tab_ver != "elf2tab 0.6.0":
error(("Detected unsupported elf2tab version {elf2tab_ver!a}. The "
"following commands may fail. Please use 0.6.0 instead."))
os.makedirs(self.tab_folder, exist_ok=True)
tab_filename = os.path.join(self.tab_folder, f"{self.args.application}.tab")
elf2tab_args = [
"elf2tab/bin/elf2tab", "--deterministic", "--package-name",
self.args.application, "-o", tab_filename
]
if self.args.verbose_build:
elf2tab_args.append("--verbose")
for arch, app_file in binaries.items():
dest_file = os.path.join(self.tab_folder, f"{arch}.elf")
shutil.copyfile(app_file, dest_file)
elf2tab_args.append(dest_file)
elf2tab_args.extend([
f"--stack={STACK_SIZE}", f"--app-heap={APP_HEAP_SIZE}",
"--kernel-heap=1024", "--protected-region-size=64"
])
if self.args.elf2tab_output:
output = self.checked_command_output(elf2tab_args)
self.args.elf2tab_output.write(output)
else:
self.checked_command(elf2tab_args)
def install_tab_file(self, tab_filename):
assert self.args.application
info(f"Installing Tock application {self.args.application}")
board_props = SUPPORTED_BOARDS[self.args.board]
args = copy.copy(self.tockloader_default_args)
setattr(args, "app_address", board_props.app_address)
setattr(args, "erase", self.args.clear_apps)
setattr(args, "make", False)
setattr(args, "no_replace", False)
tock = loader.TockLoader(args)
tock.open()
tabs = [tab.TAB(tab_filename)]
try:
tock.install(tabs, replace="yes", erase=args.erase)
except TockLoaderException as e:
fatal("Couldn't install Tock application "
f"{self.args.application}: {str(e)}")
def get_padding(self):
padding = tbfh.TBFHeaderPadding(
SUPPORTED_BOARDS[self.args.board].app_address -
SUPPORTED_BOARDS[self.args.board].padding_address)
return padding.get_binary()
def install_tock_os(self):
board_props = SUPPORTED_BOARDS[self.args.board]
kernel_file = os.path.join("third_party", "tock", "target",
board_props.arch, "release",
f"{self.args.board}.bin")
info(f"Flashing file {kernel_file}.")
with open(kernel_file, "rb") as f:
kernel = f.read()
args = copy.copy(self.tockloader_default_args)
setattr(args, "address", board_props.app_address)
tock = loader.TockLoader(args)
tock.open()
try:
tock.flash_binary(kernel, board_props.kernel_address)
except TockLoaderException as e:
fatal(f"Couldn't install Tock OS: {str(e)}")
def install_padding(self):
padding = self.get_padding()
board_props = SUPPORTED_BOARDS[self.args.board]
info("Flashing padding application")
args = copy.copy(self.tockloader_default_args)
setattr(args, "address", board_props.padding_address)
tock = loader.TockLoader(args)
tock.open()
try:
tock.flash_binary(padding, args.address)
except TockLoaderException as e:
fatal(f"Couldn't install padding: {str(e)}")
def clear_apps(self):
args = copy.copy(self.tockloader_default_args)
board_props = SUPPORTED_BOARDS[self.args.board]
setattr(args, "app_address", board_props.app_address)
# Ensure we don't force erase all apps but only the apps starting
# at `board.app_address`. This makes sure we don't erase the padding.
setattr(args, "force", False)
info("Erasing all installed applications")
tock = loader.TockLoader(args)
tock.open()
try:
tock.erase_apps()
except TockLoaderException as e:
# Erasing apps is not critical
info(f"A non-critical error occurred while erasing apps: {str(e)}")
def clear_storage(self):
if self.args.programmer == "none":
return 0
info("Erasing the persistent storage")
board_props = SUPPORTED_BOARDS[self.args.board]
# Use tockloader if possible
if self.args.programmer in ("jlink", "openocd"):
storage = bytes([0xFF] * board_props.storage_size)
tock = loader.TockLoader(self.tockloader_default_args)
tock.open()
try:
tock.flash_binary(storage, board_props.storage_address)
except TockLoaderException as e:
fatal(f"Couldn't erase the persistent storage: {str(e)}")
return 0
if self.args.programmer == "pyocd":
self.checked_command([
"pyocd", "erase", f"--target={board_props.pyocd_target}", "--sector",
f"{board_props.storage_address}+{board_props.storage_size}"
])
return 0
fatal(f"Programmer {self.args.programmer} is not supported.")
# pylint: disable=protected-access
def verify_flashed_app(self, expected_app):
if self.args.programmer not in ("jlink", "openocd"):
return False
args = copy.copy(self.tockloader_default_args)
tock = loader.TockLoader(args)
tock.open()
app_found = False
with tock._start_communication_with_board():
apps = [app.get_name() for app in tock._extract_all_app_headers()]
app_found = expected_app in apps
return app_found
def create_hex_file(self, dest_file):
# We produce an intelhex file with everything in it
# https://en.wikipedia.org/wiki/Intel_HEX
# pylint: disable=g-import-not-at-top,import-outside-toplevel
import intelhex
board_props = SUPPORTED_BOARDS[self.args.board]
final_hex = intelhex.IntelHex()
if self.args.tockos:
# Process kernel
kernel_path = os.path.join("third_party", "tock", "target",
board_props.arch, "release",
f"{self.args.board}.bin")
with open(kernel_path, "rb") as kernel:
kern_hex = intelhex.IntelHex()
kern_hex.frombytes(kernel.read(), offset=board_props.kernel_address)
final_hex.merge(kern_hex, overlap="error")
if self.args.application:
# Add padding
if board_props.padding_address:
padding_hex = intelhex.IntelHex()
padding_hex.frombytes(
self.get_padding(), offset=board_props.padding_address)
final_hex.merge(padding_hex, overlap="error")
# Now we can add the application from the TAB file
app_tab_path = f"target/tab/{self.args.application}.tab"
assert os.path.exists(app_tab_path)
app_tab = tab.TAB(app_tab_path)
if board_props.arch not in app_tab.get_supported_architectures():
fatal(("It seems that the TAB file was not produced for the "
"architecture {board_props.arch}"))
app_hex = intelhex.IntelHex()
app_hex.frombytes(
app_tab.extract_app(board_props.arch).get_binary(
board_props.app_address),
offset=board_props.app_address)
final_hex.merge(app_hex)
info(f"Generating all-merged HEX file: {dest_file}")
final_hex.tofile(dest_file, format="hex")
def check_prerequisites(self):
if not tockloader.__version__.startswith("1.5."):
fatal(("Your version of tockloader seems incompatible: found "
f"{tockloader.__version__}, expected 1.5.x."))
if self.args.programmer == "jlink":
assert_mandatory_binary("JLinkExe")
if self.args.programmer == "openocd":
assert_mandatory_binary("openocd")
if self.args.programmer == "pyocd":
assert_mandatory_binary("pyocd")
assert_python_library("intelhex")
if not SUPPORTED_BOARDS[self.args.board].pyocd_target:
fatal("This board doesn't seem to support flashing through pyocd.")
if self.args.programmer == "nordicdfu":
assert_mandatory_binary("nrfutil")
assert_python_library("intelhex")
assert_python_library("nordicsemi.lister")
nrfutil_version = __import__("nordicsemi.version").version.NRFUTIL_VERSION
if not nrfutil_version.startswith("6."):
fatal(("You need to install nrfutil python3 package v6.0 or above. "
"Found: {nrfutil_version}"))
if not SUPPORTED_BOARDS[self.args.board].nordic_dfu:
fatal("This board doesn't support flashing over DFU.")
if self.args.programmer == "none":
assert_python_library("intelhex")
def run(self):
self.check_prerequisites()
self.update_rustc_if_needed()
if not (self.args.tockos or self.args.application or
self.args.clear_storage):
info("Nothing to do.")
return 0
# Compile what needs to be compiled
if self.args.tockos:
self.build_tockos()
if self.args.application == "ctap2":
self.generate_crypto_materials(self.args.regenerate_keys)
self.build_opensk()
elif self.args.application is None:
info("No application selected.")
else:
self.build_example()
# Erase persistent storage
if self.args.clear_storage:
self.clear_storage()
# Flashing
board_props = SUPPORTED_BOARDS[self.args.board]
if self.args.programmer in ("jlink", "openocd"):
# We rely on Tockloader to do the job
if self.args.clear_apps:
self.clear_apps()
if self.args.tockos:
# Install Tock OS
self.install_tock_os()
# Install padding and application if needed
if self.args.application:
self.install_padding()
self.install_tab_file(f"target/tab/{self.args.application}.tab")
if self.verify_flashed_app(self.args.application):
info("You're all set!")
return 0
error(
("It seems that something went wrong. App/example not found "
"on your board. Ensure the connections between the programmer and "
"the board are correct."))
return 1
return 0
if self.args.programmer in ("pyocd", "nordicdfu", "none"):
dest_file = f"target/{self.args.board}_merged.hex"
os.makedirs("target", exist_ok=True)
self.create_hex_file(dest_file)
if self.args.programmer == "pyocd":
info("Flashing HEX file")
self.checked_command([
"pyocd", "flash", f"--target={board_props.pyocd_target}",
"--format=hex", "--erase=auto", dest_file
])
if self.args.programmer == "nordicdfu":
info("Creating DFU package")
dfu_pkg_file = f"target/{self.args.board}_dfu.zip"
self.checked_command([
"nrfutil", "pkg", "generate", "--hw-version=52", "--sd-req=0",
"--application-version=1", f"--application={dest_file}",
dfu_pkg_file
])
info(
"Please insert the dongle and switch it to DFU mode by keeping the "
"button pressed while inserting...")
info("Press [ENTER] when ready.")
_ = input()
# Search for the DFU devices
serial_number = []
# pylint: disable=g-import-not-at-top,import-outside-toplevel
from nordicsemi.lister import device_lister
for device in device_lister.DeviceLister().enumerate():
if device.vendor_id == "1915" and device.product_id == "521F":
serial_number.append(device.serial_number)
if not serial_number:
fatal("Couldn't find any DFU device on your system.")
if len(serial_number) > 1:
fatal("Multiple DFU devices are detected. Please only connect one.")
# Run the command without capturing stdout so that we show progress
info("Flashing device using DFU...")
return subprocess.run(
[
"nrfutil", "dfu", "usb-serial", f"--package={dfu_pkg_file}",
f"--serial-number={serial_number[0]}"
],
check=False,
timeout=None,
).returncode
# Configure OpenSK through vendor specific command if needed
if any([
self.args.lock_device,
self.args.config_cert,
self.args.config_pkey,
]):
# pylint: disable=g-import-not-at-top,import-outside-toplevel
import tools.configure
tools.configure.main(
argparse.Namespace(
batch=False,
certificate=self.args.config_cert,
priv_key=self.args.config_pkey,
lock=self.args.lock_device,
))
return 0
def main(args):
colorama.init()
# Make sure the current working directory is the right one before running
os.chdir(os.path.realpath(os.path.dirname(__file__)))
if args.listing == "boards":
print(os.linesep.join(get_supported_boards()))
return 0
if args.listing == "programmers":
print(os.linesep.join(PROGRAMMERS))
return 0
if args.listing:
# Missing check?
fatal(f"Listing {args.listing} is not implemented.")
OpenSKInstaller(args).run()
if __name__ == "__main__":
main_parser = argparse.ArgumentParser()
action_group = main_parser.add_mutually_exclusive_group(required=True)
action_group.add_argument(
"--list",
metavar="WHAT",
choices=("boards", "programmers"),
default=None,
dest="listing",
help="List supported boards or programmers, 1 per line and then exit.",
)
action_group.add_argument(
"--board",
metavar="BOARD_NAME",
dest="board",
default=None,
choices=get_supported_boards(),
help="Indicates which board Tock OS will be compiled for.",
)
main_parser.add_argument(
"--dont-clear-apps",
action="store_false",
default=True,
dest="clear_apps",
help=("When installing an application, previously installed "
"applications won't be erased from the board."),
)
main_parser.add_argument(
"--clear-storage",
action="store_true",
default=False,
dest="clear_storage",
help=("Erases the persistent storage when installing an application. "
"All stored data will be permanently lost."),
)
main_parser.add_argument(
"--lock-device",
action="store_true",
default=False,
dest="lock_device",
help=("Try to disable JTAG at the end of the operations. This "
"operation may fail if the device is already locked or if "
"the certificate/private key are not programmed."),
)
main_parser.add_argument(
"--inject-certificate",
default=None,
metavar="PEM_FILE",
type=argparse.FileType("rb"),
dest="config_cert",
help=("If this option is set, the corresponding certificate "
"will be programmed into the key as the last operation."),
)
main_parser.add_argument(
"--inject-private-key",
default=None,
metavar="PEM_FILE",
type=argparse.FileType("rb"),
dest="config_pkey",
help=("If this option is set, the corresponding private key "
"will be programmed into the key as the last operation."),
)
main_parser.add_argument(
"--programmer",
metavar="METHOD",
dest="programmer",
choices=PROGRAMMERS,
default="jlink",
help=("Sets the method to be used to flash Tock OS or the application "
"on the target board."),
)
main_parser.add_argument(
"--no-tockos",
action="store_false",
default=True,
dest="tockos",
help=("Only compiles and flash the application/example. "
"Otherwise TockOS will also be bundled and flashed."),
)
main_parser.add_argument(
"--verbose-build",
action="store_true",
default=False,
dest="verbose_build",
help="Build everything in verbose mode.",
)
main_parser.add_argument(
"--panic-console",
action="append_const",
const="panic_console",
dest="features",
help=("In case of application panic, the console will be used to "
"output messages before starting blinking the LEDs on the "
"board."),
)
main_parser.add_argument(
"--debug",
action="append_const",
const="debug_ctap",
dest="features",
help=("Compiles and installs the OpenSK application in debug mode "
"(i.e. more debug messages will be sent over the console port "
"such as hexdumps of packets)."),
)
main_parser.add_argument(
"--debug-allocations",
action="append_const",
const="debug_allocations",
dest="features",
help=("The console will be used to output allocator statistics every "
"time an allocation/deallocation happens."),
)
main_parser.add_argument(
"--verbose",
action="append_const",
const="verbose",
dest="features",
help=("The console will be used to output verbose information about the "
"OpenSK application. This also automatically activates --debug."),
)
main_parser.add_argument(
"--no-u2f",
action=RemoveConstAction,
const="with_ctap1",
dest="features",
help=("Compiles the OpenSK application without backward compatible "
"support for U2F/CTAP1 protocol."),
)
main_parser.add_argument(
"--ctap2.1",
action="append_const",
const="with_ctap2_1",
dest="features",
help=("Compiles the OpenSK application with backward compatible "
"support for CTAP2.1 protocol."),
)
main_parser.add_argument(
"--nfc",
action="append_const",
const="with_nfc",
dest="features",
help=("Compiles the OpenSK application with support for nfc."),
)
main_parser.add_argument(
"--regen-keys",
action="store_true",
default=False,
dest="regenerate_keys",
help=("Forces the generation of files (certificates and private keys) "
"under the crypto_data/ directory. "
"This is useful to allow flashing multiple OpenSK authenticators "
"in a row without them being considered clones."),
)
main_parser.add_argument(
"--elf2tab-output",
metavar="FILE",
type=argparse.FileType("a"),
dest="elf2tab_output",
default=None,
help=("When set, the output of elf2tab is appended to this file."),
)
main_parser.set_defaults(features=["with_ctap1"])
# Start parsing to know if we're going to list things or not.
partial_args, _ = main_parser.parse_known_args()
# We only need the apps_group if we have a board set
apps_group = main_parser.add_mutually_exclusive_group(
required=(partial_args.board is not None))
apps_group.add_argument(
"--no-app",
dest="application",
action="store_const",
const=None,
help=("Doesn't compile nor install any application. Useful when you only "
"want to update Tock OS kernel."))
apps_group.add_argument(
"--opensk",
dest="application",
action="store_const",
const="ctap2",
help="Compiles and installs the OpenSK application.")
apps_group.add_argument(
"--crypto_bench",
dest="application",
action="store_const",
const="crypto_bench",
help=("Compiles and installs the crypto_bench example that benchmarks "
"the performance of the cryptographic algorithms on the board."))
apps_group.add_argument(
"--store_latency",
dest="application",
action="store_const",
const="store_latency",
help=("Compiles and installs the store_latency example which print "
"latency statistics of the persistent store library."))
apps_group.add_argument(
"--erase_storage",
dest="application",
action="store_const",
const="erase_storage",
help=("Compiles and installs the erase_storage example which erases "
"the storage. During operation the dongle red light is on. Once "
"the operation is completed the dongle green light is on."))
apps_group.add_argument(
"--panic_test",
dest="application",
action="store_const",
const="panic_test",
help=("Compiles and installs the panic_test example that immediately "
"triggers a panic."))
apps_group.add_argument(
"--oom_test",
dest="application",
action="store_const",
const="oom_test",
help=("Compiles and installs the oom_test example that tests the "
"allocator until an out-of-memory error occurs."))
apps_group.add_argument(
"--console_test",
dest="application",
action="store_const",
const="console_test",
help=("Compiles and installs the console_test example that tests the "
"console driver with messages of various lengths."))
apps_group.add_argument(
"--nfct_test",
dest="application",
action="store_const",
const="nfct_test",
help=("Compiles and installs the nfct_test example that tests the "
"NFC driver."))
main(main_parser.parse_args())