Skip to content

Commit 33d8ffb

Browse files
committed
[ot] scripts/opentitan/ot: move OpenTitan Python modules to python/qemu/ot
Signed-off-by: Emmanuel Blot <eblot@rivosinc.com>
1 parent 11334be commit 33d8ffb

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+264
-203
lines changed

docs/opentitan/pymod.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ to access the devices from the local host (or also from a remote host when the C
55
using a TCP socket).
66

77
* `python/qemu/jtag`: JTAG / TAP controller client, using the _Remote BitBang Protocol_
8-
* `scripts/opentitan/ot`: OpenTitan tools
8+
* `python/qemu/ot`: OpenTitan tools
99
* `dtm`: Debug Transport Module support,
1010
* `dm`: RISC-V Debug Module support,
1111
* `lc_ctrl`: [Life Cycle controller](lc_ctrl_dmi.md) over JTAG/DMI support,

python/qemu/ot/.flake8

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[flake8]
2+
max-line-length = 80

python/qemu/ot/.pylintrc

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
[MESSAGES CONTROL]
2+
3+
disable=
4+
import-error,
5+
too-few-public-methods,
6+
too-many-arguments,
7+
too-many-branches,
8+
too-many-function-args,
9+
too-many-instance-attributes,
10+
too-many-lines,
11+
too-many-locals,
12+
too-many-nested-blocks,
13+
too-many-public-methods,
14+
too-many-statements,
15+
unspecified-encoding
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

scripts/opentitan/ot/dtm/dtm.py renamed to python/qemu/ot/dtm/dtm.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,8 @@
1111
from sys import modules
1212
from typing import Optional
1313

14-
# pylint: disable=import-error
15-
from jtag.bits import BitSequence # noqa: E402
16-
from jtag.jtag import JtagEngine # noqa: E402
14+
from jtag.bits import BitSequence
15+
from jtag.jtag import JtagEngine
1716

1817

1918
class DMIError(RuntimeError):
File renamed without changes.

scripts/opentitan/ot/mailbox/jtag.py renamed to python/qemu/ot/mailbox/jtag.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,6 @@
88

99
from logging import getLogger
1010

11-
# see scripts/jtag
12-
# pylint: disable=import-error
13-
# pylint: disable=unused-import
14-
from jtag.jtag import JtagError # noqa: F401
1511
from .sysmbox import SysMbox
1612
from ..dtm import DebugTransportModule
1713

File renamed without changes.

scripts/opentitan/ot/otp/const.py renamed to python/qemu/ot/otp/const.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
"""
88

99
from logging import getLogger
10-
from re import finditer
1110
from typing import TextIO
11+
import re
1212

1313
from ot.util.misc import camel_to_snake_case
1414

@@ -28,19 +28,19 @@ def load(self, svp: TextIO):
2828
:param svp: System Verilog stream with OTP definitions.
2929
"""
3030
svdata = svp.read()
31-
for smo in finditer(r"\stypedef\s+enum\s+logic\s+\[[^]]+\]\s"
32-
r"{((?:\s+\w+,?)+)\s*}\s(\w+)_sel_e;", svdata):
31+
for smo in re.finditer(r"\stypedef\s+enum\s+logic\s+\[[^]]+\]\s"
32+
r"{((?:\s+\w+,?)+)\s*}\s(\w+)_sel_e;", svdata):
3333
values, name = smo.groups()
3434
if name in self._consts:
3535
raise ValueError(f'Multiple definitions of enumeration {name}')
3636
enums = self._enums[name] = {}
37-
for emo in finditer(r"\s+(\w+),?", values):
37+
for emo in re.finditer(r"\s+(\w+),?", values):
3838
vname = camel_to_snake_case(emo.group(1))
3939
enums[vname] = len(enums)
4040

41-
for amo in finditer(r"\s+parameter\s+(\w+)_array_t\s+(\w+)\s+=\s+"
42-
r"{(\s+(?:(?:64|128)'h[0-9A-F]+,?\s+)+)};",
43-
svdata):
41+
for amo in re.finditer(r"\s+parameter\s+(\w+)_array_t\s+(\w+)\s+=\s+"
42+
r"{(\s+(?:(?:64|128)'h[0-9A-F]+,?\s+)+)};",
43+
svdata):
4444
_type, name, values = amo.groups()
4545
sc_name = camel_to_snake_case(name)
4646
sc_parts = sc_name.split('_')
@@ -52,7 +52,7 @@ def load(self, svp: TextIO):
5252
if name in self._consts:
5353
raise ValueError(f'Multiple definitions of constant {name}')
5454
consts = self._consts[name] = []
55-
for cmo in finditer(r"(64|128)'h([0-9A-F]+),?", values):
55+
for cmo in re.finditer(r"(64|128)'h([0-9A-F]+),?", values):
5656
consts.append(cmo.group(2).lower())
5757
# RTL order in array is reversed
5858
consts.reverse()

scripts/opentitan/ot/otp/image.py renamed to python/qemu/ot/otp/image.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@
1010
from configparser import ConfigParser, NoOptionError
1111
from io import BytesIO
1212
from logging import getLogger
13-
from re import match as re_match, sub as re_sub
1413
from struct import calcsize as scalc, pack as spack, unpack as sunpack
1514
from typing import Any, BinaryIO, Optional, Sequence, TextIO, Union
15+
import re
1616

1717
from .map import OtpMap
1818
from .partition import OtpPartition, OtpLifecycleExtension
@@ -142,18 +142,18 @@ def load_vmem(self, vfp: TextIO, vmem_kind: Optional[str] = None,
142142
raise ValueError(f"Unknown VMEM file kind '{vmem_kind}'")
143143
for lno, line in enumerate(vfp, start=1):
144144
if vkind is None:
145-
kmo = re_match(self.RE_VMEMDESC, line)
145+
kmo = re.match(self.RE_VMEMDESC, line)
146146
if kmo:
147147
vkind = kmo.group(1)
148148
row_count = int(kmo.group(2))
149149
bits = int(kmo.group(3))
150150
byte_count = bits // 8
151151
continue
152-
line = re_sub(r'//.*', '', line)
152+
line = re.sub(r'//.*', '', line)
153153
line = line.strip()
154154
if not line:
155155
continue
156-
lmo = re_match(self.RE_VMEMLOC, line)
156+
lmo = re.match(self.RE_VMEMLOC, line)
157157
if not lmo:
158158
self._log.error('Unexpected line @ %d: %s', lno, line)
159159
continue

scripts/opentitan/ot/otp/lifecycle.py renamed to python/qemu/ot/otp/lifecycle.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@
1010
from io import StringIO
1111
from logging import getLogger
1212
from os.path import basename
13-
from re import finditer, match, sub
1413
from textwrap import fill
1514
from typing import TextIO
15+
import re
1616

1717
from ot.util.misc import camel_to_snake_case, group
1818

@@ -53,7 +53,7 @@ def load(self, svp: TextIO):
5353
if cmt >= 0:
5454
line = line[:cmt]
5555
line = line.strip()
56-
abmo = match(ab_re, line)
56+
abmo = re.match(ab_re, line)
5757
if not sequences and abmo:
5858
name = abmo.group(1)
5959
sval = abmo.group(2)
@@ -64,7 +64,7 @@ def load(self, svp: TextIO):
6464
continue
6565
codes[name] = val
6666
continue
67-
smo = match(tbl_re, line)
67+
smo = re.match(tbl_re, line)
6868
if smo:
6969
kind = smo.group(1).lower()
7070
name = smo.group(2)
@@ -79,7 +79,7 @@ def load(self, svp: TextIO):
7979
continue
8080
self._sequences = sequences
8181
svp.seek(0)
82-
for tmo in finditer(r"\s+parameter\s+lc_token_t\s+(\w+)\s+="
82+
for tmo in re.finditer(r"\s+parameter\s+lc_token_t\s+(\w+)\s+="
8383
r"\s+\{\s+128'h([0-9A-F]+)\s+\};",
8484
svp.getvalue()):
8585
token, value = tmo.group(1), tmo.group(2)
@@ -150,7 +150,7 @@ def _save_template(self, cfp: TextIO) -> None:
150150
for stname, stwords in states.items():
151151
print(f' [LC_STATE_{stname.upper()}] = {{', file=cfp)
152152
for wgrp in group(stwords, len(stwords)//2):
153-
items = (sub(r'(\d+)', r'(\1)', wg) for wg in wgrp)
153+
items = (re.sub(r'(\d+)', r'(\1)', wg) for wg in wgrp)
154154
stws = ' '.join(f'{w:<6s}' for w in (f'{i},' for i in items))
155155
print(f' {stws.rstrip()}', file=cfp)
156156
print(' },', file=cfp)
File renamed without changes.
File renamed without changes.

scripts/opentitan/ot/util/elf.py renamed to python/qemu/ot/util/elf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
from io import BytesIO
1010
from logging import getLogger
1111
from os.path import basename
12-
from re import compile as re_compile
1312
from typing import BinaryIO, Iterator, NamedTuple, Optional
13+
import re
1414

1515
try:
1616
_ELF_ERROR = None
@@ -52,7 +52,7 @@ class ElfBlob:
5252
RUST_ERROR = _RUST_ERROR
5353
"""Report whether Rust tools have been loaded."""
5454

55-
RUST_TRAIL_CRE = re_compile(r'::h[0-9a-f]{16}$')
55+
RUST_TRAIL_CRE = re.compile(r'::h[0-9a-f]{16}$')
5656
"""Regex to get rid of Rust trailing symbol string."""
5757

5858
def __init__(self):
File renamed without changes.
File renamed without changes.

scripts/opentitan/ot/util/misc.py renamed to python/qemu/ot/util/misc.py

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

99
from io import BytesIO
10-
from re import sub
1110
from sys import stdout
1211
from typing import Any, Iterable, Optional, TextIO
12+
import re
1313

1414
try:
1515
# only available from Python 3.12+
@@ -109,4 +109,4 @@ def round_up(value: int, rnd: int) -> int:
109109
def camel_to_snake_case(camel: str) -> str:
110110
"""Convert CamelString string into snake_case lower string."""
111111
pattern = r'(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])'
112-
return sub(pattern, '_', camel).lower()
112+
return re.sub(pattern, '_', camel).lower()

scripts/opentitan/.flake8

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
[flake8]
22
max-line-length = 80
3+
extend-ignore = E402

scripts/opentitan/.pylintrc

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
[MESSAGES CONTROL]
22

33
disable=
4+
import-error,
45
too-few-public-methods,
56
too-many-arguments,
67
too-many-branches,
@@ -11,4 +12,6 @@ disable=
1112
too-many-nested-blocks,
1213
too-many-public-methods,
1314
too-many-statements,
14-
unspecified-encoding
15+
unspecified-encoding,
16+
wrong-import-order,
17+
wrong-import-position,

scripts/opentitan/cfggen.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,15 @@
1111
from argparse import ArgumentParser
1212
from configparser import ConfigParser
1313
from logging import getLogger
14-
from os.path import isdir, isfile, join as joinpath, normpath
15-
from re import match, search
16-
from sys import exit as sysexit, modules, stderr, stdout
14+
from os.path import dirname, isdir, isfile, join as joinpath, normpath
1715
from traceback import format_exc
1816
from typing import Optional
17+
import re
18+
import sys
19+
20+
QEMU_PYPATH = joinpath(dirname(dirname(dirname(normpath(__file__)))),
21+
'python', 'qemu')
22+
sys.path.append(QEMU_PYPATH)
1923

2024
try:
2125
_HJSON_ERROR = None
@@ -26,10 +30,10 @@ def hjload(*_, **__): # noqa: E301
2630
"""dummy func if HJSON module is not available"""
2731
return {}
2832

29-
from ot.util.log import configure_loggers
30-
from ot.util.misc import camel_to_snake_case
3133
from ot.otp.const import OtpConstants
3234
from ot.otp.lifecycle import OtpLifecycle
35+
from ot.util.log import configure_loggers
36+
from ot.util.misc import camel_to_snake_case
3337

3438

3539
OtParamRegex = str
@@ -130,7 +134,7 @@ def save(self, socid: Optional[str], count: Optional[int],
130134
with open(outpath, 'wt') as ofp:
131135
cfg.write(ofp)
132136
else:
133-
cfg.write(stdout)
137+
cfg.write(sys.stdout)
134138

135139
@classmethod
136140
def add_pair(cls, data: dict[str, str], kname: str, value: str) -> None:
@@ -147,7 +151,7 @@ def _load_top_values(self, module: dict, odict: dict, multi: bool,
147151
if not isinstance(params, dict):
148152
continue
149153
for regex in regexes:
150-
pmo = match(regex, params['name'])
154+
pmo = re.match(regex, params['name'])
151155
if not pmo:
152156
continue
153157
value = params.get('default')
@@ -157,7 +161,7 @@ def _load_top_values(self, module: dict, odict: dict, multi: bool,
157161
value = value[2:]
158162
kname = camel_to_snake_case(pmo.group(1))
159163
if multi:
160-
imo = search(r'(\d+)$', modname)
164+
imo = re.search(r'(\d+)$', modname)
161165
idx = int(imo.group(1)) if imo else 'None'
162166
if idx not in odict:
163167
odict[idx] = {}
@@ -221,7 +225,7 @@ def main():
221225
debug = True
222226
default_top = 'darjeeling'
223227
try:
224-
desc = modules[__name__].__doc__.split('.', 1)[0].strip()
228+
desc = sys.modules[__name__].__doc__.split('.', 1)[0].strip()
225229
argparser = ArgumentParser(description=f'{desc}.')
226230
files = argparser.add_argument_group(title='Files')
227231
files.add_argument('opentitan', nargs=1, metavar='TOPDIR',
@@ -289,12 +293,12 @@ def main():
289293
cfg.save(args.socid, args.count, args.out)
290294

291295
except (IOError, ValueError, ImportError) as exc:
292-
print(f'\nError: {exc}', file=stderr)
296+
print(f'\nError: {exc}', file=sys.stderr)
293297
if debug:
294-
print(format_exc(chain=False), file=stderr)
295-
sysexit(1)
298+
print(format_exc(chain=False), file=sys.stderr)
299+
sys.exit(1)
296300
except KeyboardInterrupt:
297-
sysexit(2)
301+
sys.exit(2)
298302

299303

300304
if __name__ == '__main__':

0 commit comments

Comments
 (0)