Skip to content

Commit babcd21

Browse files
committed
toolkit: Allow tools to run from any location.
Signed-off-by: Damien George <[email protected]>
1 parent 552bc72 commit babcd21

31 files changed

+230
-166
lines changed

toolkit/app-gen-toc.py

Lines changed: 78 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,26 @@
2222
from pathlib import Path
2323
import zlib
2424
import json
25-
from utils import toc_common
26-
from utils.config import *
27-
from utils.toc_common import *
28-
from json.decoder import JSONDecodeError
25+
import utils
26+
from utils.config import load_global_config, read_global_config
2927
from utils.device_config import gen_device_config
3028
from utils.sign_image_util import sign_image
31-
from printInfo import *
32-
from utils.gen_fw_cfg import *
29+
from utils.printInfo import printInfo, verboseModeSet
30+
from utils import paths
31+
from utils.toc_common import (
32+
addContentCertificate,
33+
cleanBuild,
34+
compressImage,
35+
createContentCerts,
36+
getBlob,
37+
getCPUID,
38+
getImageSize,
39+
getObjectFlags,
40+
getObjectType,
41+
getObjectVersion,
42+
read_json_file,
43+
validateOptions,
44+
)
3345

3446
# Define Version constant for each separate tool
3547
# 0.30.000 includes image signing
@@ -80,9 +92,6 @@
8092
cpuid_switcher = {"A32_0": 0, "A32_1": 1, "M55_HP": 2, "M55_HE": 3}
8193

8294

83-
certPath = Path("cert/")
84-
imagePath = Path("build/images")
85-
8695
# sizes of Certificates
8796
CERT_CHAIN_SIZE = utils.toc_common.CERT_CHAIN_SIZE
8897
CONT_CERT_SIZE = utils.toc_common.CONT_CERT_SIZE
@@ -102,6 +111,8 @@ def createOemTocPackage(fwsections, outputFile):
102111
global otocStartAddress
103112
global unmanaged
104113

114+
certPath = paths.CERT_INPUT_DIR
115+
105116
print("Creating APP TOC Package...")
106117
# Start by loading the Key1/Key2 Certificates for later on
107118
printInfo("Loading Key1 Cert...")
@@ -113,7 +124,7 @@ def createOemTocPackage(fwsections, outputFile):
113124
outf = open(outputFile, "wb")
114125

115126
# create a memory layout map for debugging
116-
mapf = open("build/app-package-map.txt", "w")
127+
mapf = open(paths.OUTPUT_DIR / "app-package-map.txt", "w")
117128
mapf.write("* * * User managed MRAM locations* * * \n")
118129

119130
debugScript = ""
@@ -128,8 +139,8 @@ def createOemTocPackage(fwsections, outputFile):
128139

129140
printInfo(img)
130141
mapf.write(f"{img[1]}\t{hex(img[2])}\t{img[2]}\t{img[3]}\t{imgFile}\n")
131-
debugScript += "../build/images/" + imgFile + " " + img[1] + " "
132-
sign_image("build/images/" + imgFile, int(img[1], 16), 0xFFFFFFFF, "OEM")
142+
debugScript += imgFile + " " + img[1] + " "
143+
sign_image(imgFile, int(img[1], 16), 0xFFFFFFFF, "OEM")
133144

134145
# create a pointer to keep track addresses of components (object_address in OTOC)
135146
mPointer = oemManagedAreaStartAddress
@@ -161,7 +172,9 @@ def createOemTocPackage(fwsections, outputFile):
161172
mPointer += CERT_CHAIN_SIZE - CONT_CERT_SIZE
162173
# print(f'mPointer KC un: {mPointer - oemManagedAreaStartAddress}')
163174
# copy the Content Certificate (for signed or unsigned images)
164-
addContentCertificate(outf, sec["binary"] + "_" + str(sec["mramAddress"]))
175+
addContentCertificate(
176+
outf, os.path.basename(sec["binary"]) + "_" + str(sec["mramAddress"])
177+
)
165178
# mapf.write(f"{hostAddress(mPointer)}\t{hex(CONT_CERT_SIZE)}\t{(CONT_CERT_SIZE)}\tSB" + sec['binary'] + ".crt\n")
166179
mapf.write(
167180
f"{hex(mPointer)}\t{hex(CONT_CERT_SIZE)}\t{(CONT_CERT_SIZE)}\tSB"
@@ -198,7 +211,9 @@ def createOemTocPackage(fwsections, outputFile):
198211
mPointer += CERT_CHAIN_SIZE - CONT_CERT_SIZE
199212
# print(f'mPointer - KCs: {mPointer - oemManagedAreaStartAddress}')
200213
# copy the Content Certificate (for signed or unsigned images)
201-
addContentCertificate(outf, sec["binary"] + "_" + str(sec["mramAddress"]))
214+
addContentCertificate(
215+
outf, os.path.basename(sec["binary"]) + "_" + str(sec["mramAddress"])
216+
)
202217
# mapf.write(f"{hostAddress(mPointer)}\t{hex(CONT_CERT_SIZE)}\t{(CONT_CERT_SIZE)}\tSB" + sec['binary'] + ".crt\n")
203218
mapf.write(
204219
f"{hex(mPointer)}\t{hex(CONT_CERT_SIZE)}\t{(CONT_CERT_SIZE)}\tSB"
@@ -216,7 +231,7 @@ def createOemTocPackage(fwsections, outputFile):
216231
binFile += ".lzf"
217232

218233
# print("Copying: " + binFile)
219-
outf.write(getBlob(imagePath / binFile))
234+
outf.write(getBlob(binFile))
220235
# mapf.write(f"{hostAddress(mPointer)}\t{hex(sec['size'])}\t{sec['size']}\t" + binFile + "\n")
221236
mapf.write(
222237
f"{hex(mPointer)}\t{hex(sec['size'])}\t{sec['size']}\t" + binFile + "\n"
@@ -358,15 +373,15 @@ def createOemTocPackage(fwsections, outputFile):
358373

359374
mapf.write("\n* * * END of APP Package * * * \n")
360375

361-
debugScript += "../" + outputFile + " " + hex(oemManagedAreaStartAddress)
376+
debugScript += outputFile + " " + hex(oemManagedAreaStartAddress)
362377

363378
# close the file
364379
outf.close()
365380

366381
mapf.close()
367382

368383
# generate debug script file
369-
dsFile = "bin/application_package.ds" # Was bin/oempackage.ds
384+
dsFile = paths.OUTPUT_DIR / "application_package.ds" # Was bin/oempackage.ds
370385
try:
371386
ds = open(dsFile, "w")
372387
# f.write('reset system\n')
@@ -410,7 +425,7 @@ def calcOemManagedArea(fwsections):
410425
numImages += 1
411426

412427
# determine the size of file and if padding is needed
413-
fsize, padlen = getImageSize("build/images/" + sec["binary"])
428+
fsize, padlen = getImageSize(sec["binary"])
414429
# update the size and padding information
415430
sec["size"] = fsize
416431
sec["padlen"] = padlen
@@ -420,11 +435,11 @@ def calcOemManagedArea(fwsections):
420435
compressLabel = "uncompressed"
421436
if "COMPRESS" in sec["flags"]:
422437
compressLabel = "compressed"
423-
compressImage("build/images/" + sec["binary"])
438+
compressImage(sec["binary"])
424439
# we should have the (new) compressed file, so we will check if this is the case...
425440

426441
# determine the size of (compressed) file and if padding is needed
427-
fsize, padlen = getImageSize("build/images/" + sec["binary"] + ".lzf")
442+
fsize, padlen = getImageSize(sec["binary"] + ".lzf")
428443
# add compressed file size and update padding information
429444
# (the compressed image will be included in the package so pad should be calculated for
430445
# compressed file size)
@@ -601,16 +616,25 @@ def validateVersAttr(version):
601616

602617

603618
def updateDeviceConfig(file):
619+
file = paths.CONFIG_INPUT_DIR / file
604620
# print('*** updateDeviceConfig: ', file)
605621
# Update the firewall configuration in the OEM DEVICE config file
606-
update_fw_cfg_oem(file)
622+
# This doesn't do anything except format the json file.
623+
# update_fw_cfg_oem(file)
607624

608-
cfg = read_global_config("build/config/" + file)
625+
cfg = read_global_config(file)
609626
if "miscellaneous" in cfg:
627+
unwanted_item = False
610628
for item in cfg["miscellaneous"]:
611-
item.pop("sdesc", None)
612-
item.pop("ldesc", None)
613-
item.pop("options", None)
629+
if "sdesc" in item or "ldesc" in item or "options" in item:
630+
unwanted_item = True
631+
if unwanted_item:
632+
print(
633+
"[ERROR] File '" + file + "' should not contain 'miscellaneous' entry"
634+
)
635+
sys.exit(EXIT_WITH_ERROR)
636+
# Don't write out the json file, because it didn't change.
637+
return
614638
with open("build/config/" + file, "w") as json_file:
615639
json.dump(cfg, json_file, indent=2)
616640

@@ -658,9 +682,34 @@ def main():
658682
action="store_true",
659683
)
660684
parser.add_argument("-v", "--verbose", help="verbosity mode", action="store_true")
685+
parser.add_argument(
686+
"--config-dir",
687+
type=str,
688+
default="",
689+
help="directory with configuration files",
690+
)
691+
parser.add_argument(
692+
"--output-dir",
693+
type=str,
694+
default="",
695+
help="directory to place output files",
696+
)
697+
parser.add_argument(
698+
"--firmware-dir",
699+
type=str,
700+
default="",
701+
help="directory contianing firmware files",
702+
)
661703

662704
args = parser.parse_args()
663705

706+
# Set paths given on command line.
707+
paths.TOOLKIT_DIR = Path(os.path.dirname(__file__))
708+
paths.CERT_INPUT_DIR = paths.TOOLKIT_DIR / "cert"
709+
paths.CONFIG_INPUT_DIR = Path(args.config_dir)
710+
paths.FIRMWARE_INPUT_DIR = Path(args.firmware_dir)
711+
paths.OUTPUT_DIR = Path(args.output_dir)
712+
664713
if args.version:
665714
print(TOOL_VERSION)
666715
sys.exit()
@@ -715,12 +764,15 @@ def main():
715764

716765
# update the size and padding information
717766
if sec["identifier"].strip("\0") != "DEVICE":
767+
sec["binary"] = (paths.FIRMWARE_INPUT_DIR / sec["binary"]).as_posix()
718768
continue
719769

720770
print("Generating Device Configuration for: " + sec["binary"])
721771
updateDeviceConfig(sec["binary"])
722772
gen_device_config(sec["binary"], False)
723-
sec["binary"] = sec["binary"][:-5] + ".bin"
773+
sec["binary"] = (
774+
(paths.OUTPUT_DIR / sec["binary"]).with_suffix(".bin").as_posix()
775+
)
724776

725777
# also check unmanaged images (mramAddress != 0) are between boundaries (OEM_BASE_ADDRESS - only in Rev_A as in Rev_B will be 0)
726778
# and images don't overlap... Also, advice is GAPs (big ones) exist - especially if tool can't create the layout...
@@ -746,7 +798,6 @@ def main():
746798

747799
sign_image(args.output, oemManagedAreaStartAddress, 0xFFFFFFFF, "OEM")
748800

749-
print("Done!")
750801
return 0
751802

752803

toolkit/app-provision.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
import signal
1515
import argparse
1616

17-
sys.path.append("./isp")
1817
import subprocess
1918
from serialport import serialPort
2019
import utils.config

toolkit/app-secure-debug.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
import signal
1515
import argparse
1616

17-
sys.path.append("./isp")
1817
import subprocess
1918
from serialport import serialPort
2019
import utils.config

toolkit/app-write-mram.py

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,29 @@
1414

1515
import os
1616
import sys
17-
import signal
1817
import argparse
19-
from utils.discover import getValues, getJlinkSN
18+
from utils.discover import getJlinkSN
2019
import utils.config
21-
from utils.config import *
20+
from utils.config import load_global_config, getPartDescription
2221
from utils.user_validations import validateArgList
2322

24-
sys.path.append("./isp")
25-
from serialport import serialPort
26-
from serialport import COM_BAUD_RATE_MAXIMUM
23+
from isp.serialport import serialPort
24+
from isp.serialport import COM_BAUD_RATE_MAXIMUM
25+
from utils.toc_common import globalToLocalAddress
2726

2827
# import ispcommands
29-
from isp_core import *
30-
from isp_util import *
31-
import device_probe
32-
import pylink
28+
from isp.isp_core import (
29+
CtrlCHandler,
30+
isp_get_maintenance_status,
31+
isp_mram_erase,
32+
isp_reset,
33+
isp_set_baud_rate,
34+
isp_show_maintenance_mode,
35+
isp_start,
36+
isp_stop,
37+
)
38+
from isp.isp_util import put_target_in_maintenance_mode, burn_mram_isp
39+
from isp import device_probe
3340
import datetime
3441
# from array import array
3542

@@ -132,13 +139,7 @@ def main():
132139
parser = argparse.ArgumentParser(
133140
description="NVM Burner for Application TOC Package"
134141
)
135-
parser.add_argument(
136-
"-d",
137-
"--discover",
138-
action="store_true",
139-
default=False,
140-
help="COM port discovery",
141-
)
142+
parser.add_argument("-d", "--device", type=str, help="serial port device")
142143
parser.add_argument("-b", "--baudrate", help="serial port baud rate", type=int)
143144
parser.add_argument(
144145
"-e",
@@ -267,11 +268,14 @@ def main():
267268
print("[ERROR] erase arguments are empty")
268269
sys.exit(EXIT_WITH_ERROR)
269270
argList += args.erase
270-
elif args.images != "Application TOC Package":
271-
argList = args.images
272-
else:
273-
dsFile = "bin/application_package.ds"
271+
elif args.images == "Application TOC Package" or args.images.startswith("file:"):
272+
if args.images.startswith("file:"):
273+
dsFile = args.images.removeprefix("file:")
274+
else:
275+
dsFile = "bin/application_package.ds"
274276
argList = readImageList(dsFile)
277+
else:
278+
argList = args.images
275279

276280
if args.skip:
277281
idx = argList.find("../build/AppTocPackage.bin 0x")
@@ -286,6 +290,8 @@ def main():
286290
print("[INFO]", action + argList)
287291

288292
if method == "jtag" and not args.erase: # erase via jtag not yet supported!
293+
import pylink
294+
289295
jlinkSN = getJlinkSN()
290296
if jlinkSN == -1:
291297
print("J-Link device not found!")
@@ -355,10 +361,12 @@ def main():
355361
handler = CtrlCHandler()
356362
isp = serialPort(baud_rate) # Serial dabbling open up port.
357363

364+
"""
358365
if args.discover: # discover the COM ports if requested
359366
isp.discoverSerialPorts()
367+
"""
360368

361-
errorCode = isp.openSerial()
369+
errorCode = isp.openSerial(args.device)
362370
if errorCode is False:
363371
print("[ERROR] isp openSerial failed for %s" % isp.getPort())
364372
sys.exit(EXIT_WITH_ERROR)

toolkit/isp/clock_decode.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
# pylint: disable=unused-argument, invalid-name, consider-using-f-string
99
import struct
1010
import ctypes
11-
from isp_print import isp_print_color
11+
from isp.isp_print import isp_print_color
1212

1313
c_uint32 = ctypes.c_uint32
1414

toolkit/isp/cpu_decode.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77

88
# pylint: disable=unused-argument, invalid-name, consider-using-f-string
99
import struct
10-
from isp_print import isp_print_color
11-
from toc_decode import format_hex, format_cpu
12-
from toc_decode import TOC_IMAGE_CPU_LAST
10+
from isp.isp_print import isp_print_color
11+
from isp.toc_decode import format_hex, format_cpu
12+
from isp.toc_decode import TOC_IMAGE_CPU_LAST
1313

1414

1515
def display_cpu_info(message):

0 commit comments

Comments
 (0)