diff --git a/.github/workflows/build_test.yaml b/.github/workflows/build_test.yaml index 5e8963f96e8b8..5aa4cf23bea80 100644 --- a/.github/workflows/build_test.yaml +++ b/.github/workflows/build_test.yaml @@ -3,6 +3,7 @@ # QEMU OpenTitan CI # # Copyright (c) 2023-2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache License 2.0 #------------------------------------------------------------------------------ @@ -86,18 +87,20 @@ jobs: lint-python: runs-on: ubuntu-latest steps: + - name: Check out QEMU + uses: actions/checkout@v4 - name: Install tools run: | sudo apt-get update && sudo apt-get install -y python3-pip # ubuntu "latest" is too old to require --break-system-packages ... - pip3 install pylint==3.3.3 - - name: Check out QEMU - uses: actions/checkout@v4 + pip3 install -r scripts/opentitan/requirements.txt - name: Lint Python code run: | + flake8 --config scripts/opentitan/.flake8 scripts/opentitan/*.py \ + python/qemu/jtagtools python/qemu/ot pylint --rcfile scripts/opentitan/.pylintrc -d 'duplicate-code' -d 'fixme' \ - scripts/opentitan/*.py python/qemu/jtagtools python/qemu/ot + scripts/opentitan/*.py python/qemu/jtagtools python/qemu/ot lint-clang: runs-on: ubuntu-24.04 diff --git a/.gitlab-ci.d/opentitan/pylint-ot.yml b/.gitlab-ci.d/opentitan/python-ot.yml similarity index 65% rename from .gitlab-ci.d/opentitan/pylint-ot.yml rename to .gitlab-ci.d/opentitan/python-ot.yml index 0f485d539226c..fb0cc173e82c3 100644 --- a/.gitlab-ci.d/opentitan/pylint-ot.yml +++ b/.gitlab-ci.d/opentitan/python-ot.yml @@ -1,4 +1,4 @@ -pylint-ot: +python-ot: tags: - qemu_ot stage: build @@ -9,4 +9,6 @@ pylint-ot: - . .venv/bin/activate - pip3 install -r scripts/opentitan/requirements.txt - pylint --rcfile scripts/opentitan/.pylintrc -d 'duplicate-code' -d 'fixme' - scripts/opentitan/*.py python/qemu/jtagtools python/qemu/ot + scripts/opentitan/*.py python/qemu/jtagtools python/qemu/ot + - flake8 --config scripts/opentitan/.flake8 + scripts/opentitan/*.py python/qemu/jtagtools python/qemu/ot diff --git a/.gitlab-ci.d/opentitan/qemu-ot.yml b/.gitlab-ci.d/opentitan/qemu-ot.yml index 9dbe80bd6442a..54a62fd0a73a6 100644 --- a/.gitlab-ci.d/opentitan/qemu-ot.yml +++ b/.gitlab-ci.d/opentitan/qemu-ot.yml @@ -4,6 +4,6 @@ variables: include: - local: '/.gitlab-ci.d/opentitan/build.yml' - - local: '/.gitlab-ci.d/opentitan/pylint-ot.yml' + - local: '/.gitlab-ci.d/opentitan/python-ot.yml' - local: '/.gitlab-ci.d/opentitan/ot-smoke.yml' - local: '/.gitlab-ci.d/opentitan/ot-bmtests.yml' diff --git a/python/qemu/jtagtools/jtag/__init__.py b/python/qemu/jtagtools/jtag/__init__.py index 9114df3dd7e18..ee213f2d6884d 100644 --- a/python/qemu/jtagtools/jtag/__init__.py +++ b/python/qemu/jtagtools/jtag/__init__.py @@ -1,11 +1,12 @@ # Copyright (c) 2024 Rivos Inc. Emmanuel Blot # Copyright (c) 2010-2024, Emmanuel Blot +# Copyright (c) 2025 lowRISC contributors. # All rights reserved. # # SPDX-License-Identifier: Apache2 """JTAG Tools.""" -from .controller import JtagController -from .engine import JtagEngine -from .error import JtagError +from .controller import JtagController # noqa: F401 +from .engine import JtagEngine # noqa: F401 +from .error import JtagError # noqa: F401 diff --git a/python/qemu/jtagtools/jtag/error.py b/python/qemu/jtagtools/jtag/error.py index dcf1732430974..9c9c0840d7f69 100644 --- a/python/qemu/jtagtools/jtag/error.py +++ b/python/qemu/jtagtools/jtag/error.py @@ -1,11 +1,13 @@ # Copyright (c) 2024 Rivos Inc. Emmanuel Blot # Copyright (c) 2010-2024, Emmanuel Blot +# Copyright (c) 2025 lowRISC contributors. # All rights reserved. # # SPDX-License-Identifier: Apache2 """JTAG Errors""" + class JtagError(Exception): """Generic JTAG error.""" diff --git a/python/qemu/jtagtools/rbb/__init__.py b/python/qemu/jtagtools/rbb/__init__.py index e85ca18fb4113..452dee860cd2f 100644 --- a/python/qemu/jtagtools/rbb/__init__.py +++ b/python/qemu/jtagtools/rbb/__init__.py @@ -1,8 +1,9 @@ # Copyright (c) 2024 Rivos Inc. Emmanuel Blot +# Copyright (c) 2025 lowRISC contributors. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """JTAG Remote BitBang Controller""" -from .bitbang import JtagBitbangController +from .bitbang import JtagBitbangController # noqa: F401 diff --git a/python/qemu/ot/devproxy.py b/python/qemu/ot/devproxy.py index b9e095f86f36c..4880556b122bc 100644 --- a/python/qemu/ot/devproxy.py +++ b/python/qemu/ot/devproxy.py @@ -1,4 +1,5 @@ # Copyright (c) 2023-2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """Device proxy for OpenTitan devices and peripherals @@ -1663,7 +1664,7 @@ def _receive(self): continue packet = bytes(buffer[:length]) self._log.debug('RX payload:%s%s', self.to_str(packet)[:80], - '...' if len(packet) > 80 else '') + '...' if len(packet) > 80 else '') buffer = buffer[length:] if resp: if self._tx_uid != uid: diff --git a/python/qemu/ot/dtm/__init__.py b/python/qemu/ot/dtm/__init__.py index 7304c878e4d92..6c8c430b5c2ee 100644 --- a/python/qemu/ot/dtm/__init__.py +++ b/python/qemu/ot/dtm/__init__.py @@ -1,4 +1,5 @@ # Copyright (c) 2024 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """Debug Module tools. @@ -6,4 +7,4 @@ :author: Emmanuel Blot """ -from .dtm import DebugTransportModule +from .dtm import DebugTransportModule # noqa: F401 diff --git a/python/qemu/ot/dtm/dtm.py b/python/qemu/ot/dtm/dtm.py index 15531b03c7ce0..06cae9be3681e 100644 --- a/python/qemu/ot/dtm/dtm.py +++ b/python/qemu/ot/dtm/dtm.py @@ -1,4 +1,5 @@ # Copyright (c) 2024 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """Debug Module tools. @@ -214,7 +215,7 @@ def _build_dmi(self, address: int) -> int: self._log.debug('DMI width: %d bits', self._abits) if address >= (1 << self._abits): raise ValueError(f'Address 0x{address:x} too large, ' - f'max 0x{(1 << self._abits) -1:x}') + f'max 0x{(1 << self._abits) - 1:x}') return address << (32 + 2) def _check_error(self) -> None: diff --git a/python/qemu/ot/km/__init__.py b/python/qemu/ot/km/__init__.py index 93ce568e53b61..28bf2ac2c3547 100644 --- a/python/qemu/ot/km/__init__.py +++ b/python/qemu/ot/km/__init__.py @@ -1,6 +1,7 @@ # Copyright (c) 2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """KeyManager tools.""" -from .dpe import KeyManagerDpe +from .dpe import KeyManagerDpe # noqa: F401 diff --git a/python/qemu/ot/km/dpe.py b/python/qemu/ot/km/dpe.py index 195250d2f9642..23e4f097dab53 100644 --- a/python/qemu/ot/km/dpe.py +++ b/python/qemu/ot/km/dpe.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 # Copyright (c) 2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """QEMU OT tool to generate Key Manager DPE keys. @@ -100,7 +101,7 @@ def from_args(cls, args: Namespace) -> 'KeyManagerDpe': if salt_len > cls.SALT_WIDTH: raise ArgError('Invalid salt length') - if not 0<= args.key_version < 1<<32: + if not 0 <= args.key_version < 1 << 32: raise ArgError('Invalid key version value') kmd = cls.create(args.otp_map, args.ecc, args.vmem, args.raw, diff --git a/python/qemu/ot/km/engine.py b/python/qemu/ot/km/engine.py index d83c9f3fe0ea3..472aaedbc3c34 100644 --- a/python/qemu/ot/km/engine.py +++ b/python/qemu/ot/km/engine.py @@ -1,4 +1,5 @@ # Copyright (c) 2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """QEMU OT tool to verify Key Manager DPE test execution @@ -165,7 +166,6 @@ def _parse_bytes(cls, value: str) -> bytes: return ivalue.to_bytes((ivalue.bit_length() + 7) // 8, 'big') raise ValueError(f'invalid bytes: {value}') - def _build_steps_from_seq(self, seq: ConfigParser) -> \ dict[str, KeyManagerDpeStep]: module = sys.modules[__name__] @@ -279,7 +279,7 @@ def _build_steps_from_log(self, itlog: Iterator[str]) -> \ def _enumerate_steps_from_log(self, itlog: Iterator[str]) -> \ Iterator[tuple[str, dict[str, Union[str, int, bytes, bool]], - Optional[bytes]]]: + Optional[bytes]]]: step = None values: dict[str, Union[str, int, bytes, bool]] = {} result: Optional[bytes] = None diff --git a/python/qemu/ot/lc_ctrl/__init__.py b/python/qemu/ot/lc_ctrl/__init__.py index eab046554bd88..bdcf1b69c330c 100644 --- a/python/qemu/ot/lc_ctrl/__init__.py +++ b/python/qemu/ot/lc_ctrl/__init__.py @@ -1,7 +1,9 @@ # Copyright (c) 2024 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """LifeCycle tools.""" + class LifeCycleError(RuntimeError): """Life Cycle Error""" diff --git a/python/qemu/ot/lc_ctrl/const.py b/python/qemu/ot/lc_ctrl/const.py index 5310ade046c63..ef719a01e87b3 100644 --- a/python/qemu/ot/lc_ctrl/const.py +++ b/python/qemu/ot/lc_ctrl/const.py @@ -1,4 +1,5 @@ # Copyright (c) 2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """Lifecycle helpers. @@ -21,7 +22,7 @@ def __init__(self): self._log = getLogger('lc.const') self._states: dict[str, tuple[str, str]] = {} self._tokens: dict[str, str] = {} - self._diversifiers: dict [str, str] = {} + self._diversifiers: dict[str, str] = {} def load_sv(self, svp: TextIO) -> None: """Decode LC information from a System Verilog file. diff --git a/python/qemu/ot/lc_ctrl/lcdmi.py b/python/qemu/ot/lc_ctrl/lcdmi.py index 8b03e1f7eabff..b878d279b4276 100644 --- a/python/qemu/ot/lc_ctrl/lcdmi.py +++ b/python/qemu/ot/lc_ctrl/lcdmi.py @@ -1,4 +1,5 @@ # Copyright (c) 2024 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """LifeCycle DMI. @@ -188,7 +189,8 @@ def transition_token(self) -> bytes: return token @transition_token.setter - def transition_token(self, token: Union[bytes, bytearray, str, None]) -> None: + def transition_token(self, + token: Union[bytes, bytearray, str, None]) -> None: """Define the transition token as a 16-byte token. :param token: if None, use an empty zeroed token, diff --git a/python/qemu/ot/otp/const.py b/python/qemu/ot/otp/const.py index 8f72f44d10f05..ed4b979d2a3f4 100644 --- a/python/qemu/ot/otp/const.py +++ b/python/qemu/ot/otp/const.py @@ -1,4 +1,5 @@ # Copyright (c) 2023-2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """Lifecycle helpers. @@ -141,17 +142,17 @@ def load_secrets(self, secrets: dict[str, Any]) -> bool: self._consts['key'] = [ hexlify(kv.to_bytes(sizes['key'], 'big')).decode() for kd in scrambling['keys'] - for kn, kv in kd.items() if kn =='value' + for kn, kv in kd.items() if kn == 'value' ] self._consts['digest_const'] = [ hexlify(kv.to_bytes(sizes['cnst'], 'big')).decode() for kd in scrambling['digests'] - for kn, kv in kd.items() if kn =='cnst_value' + for kn, kv in kd.items() if kn == 'cnst_value' ] self._consts['digest_iv'] = [ hexlify(kv.to_bytes(sizes['iv'], 'big')).decode() for kd in scrambling['digests'] - for kn, kv in kd.items() if kn =='iv_value' + for kn, kv in kd.items() if kn == 'iv_value' ] offset = 0 diff --git a/python/qemu/ot/otp/descriptor.py b/python/qemu/ot/otp/descriptor.py index 68fc818f2b171..856d257c017aa 100644 --- a/python/qemu/ot/otp/descriptor.py +++ b/python/qemu/ot/otp/descriptor.py @@ -1,4 +1,5 @@ # Copyright (c) 2023-2024 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """OTP descriptors. @@ -228,7 +229,7 @@ def save(self, kind: str, topname: Optional[str], hjname: str, slots.append(OtpSlotDescriptor(f'{part.name}_DIGEST', offset, OtpPartition.DIGEST_SIZE, True)) if zeroizable: - offset = part.offset + part.size - OtpPartition.DIGEST_SIZE + offset = part.offset + part.size - OtpPartition.DIGEST_SIZE slots.append(OtpSlotDescriptor(f'{part.name}_ZER', offset, OtpPartition.ZER_SIZE, True)) @@ -264,7 +265,7 @@ def _save_qemu(self, topname: Optional[str], hjname: str, scriptname: str, part_names.extend(( 'OTP_PART_COUNT', 'OTP_ENTRY_DAI = OTP_PART_COUNT, ' - '/* Fake partitions for error (...) */', + '/* Fake partitions for error (...) */', 'OTP_ENTRY_KDI, /* Key derivation issue, not really OTP */', 'OTP_ENTRY_COUNT')) print('typedef enum {', file=cfp) diff --git a/python/qemu/ot/otp/image.py b/python/qemu/ot/otp/image.py index f569da83597b6..9be74a1558f84 100644 --- a/python/qemu/ot/otp/image.py +++ b/python/qemu/ot/otp/image.py @@ -1,4 +1,5 @@ # Copyright (c) 2023-2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """OTP QEMU image. @@ -386,7 +387,7 @@ def decode(self, decode: bool = True, wide: int = 0, for partname in partnames: if not re.match(part_re, partname, re.IGNORECASE): continue - if not partname in part_filters: + if partname not in part_filters: part_filters[partname] = set() if field == '*': # any field would match, discard any existing one diff --git a/python/qemu/ot/otp/lifecycle.py b/python/qemu/ot/otp/lifecycle.py index dff2a14a7e83a..f81f70164004f 100644 --- a/python/qemu/ot/otp/lifecycle.py +++ b/python/qemu/ot/otp/lifecycle.py @@ -1,4 +1,5 @@ # Copyright (c) 2023-2024 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """Lifecycle helpers. @@ -82,8 +83,8 @@ def load(self, svp: TextIO): self._sequences = sequences svp.seek(0) for tmo in re.finditer(r"\s+parameter\s+lc_token_t\s+(\w+)\s+=" - r"\s+\{\s+128'h([0-9A-F]+)\s+\};", - svp.getvalue()): + r"\s+\{\s+128'h([0-9A-F]+)\s+\};", + svp.getvalue()): token, value = tmo.group(1), tmo.group(2) if token in self._tokens: raise ValueError(f'Multiple definitions of token {token}') diff --git a/python/qemu/ot/pyot/qemu/wrapper.py b/python/qemu/ot/pyot/qemu/wrapper.py index b2924e32a2d65..e67cc0d754ad1 100644 --- a/python/qemu/ot/pyot/qemu/wrapper.py +++ b/python/qemu/ot/pyot/qemu/wrapper.py @@ -1,4 +1,5 @@ # Copyright (c) 2023-2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """QEMU executer wrapper for OpentTitan unit test sequencer. @@ -10,6 +11,7 @@ from ..wrapper import Wrapper + class QEMUWrapper(Wrapper): """Test execution wrapper using a QEMU virtual machine """ diff --git a/python/qemu/ot/util/arg.py b/python/qemu/ot/util/arg.py index 209b85b62ae01..0ad2fa844788d 100644 --- a/python/qemu/ot/util/arg.py +++ b/python/qemu/ot/util/arg.py @@ -1,4 +1,5 @@ # Copyright (c) 2024-2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """ArgumentParser extension. @@ -8,7 +9,7 @@ # pylint: disable=unused-import # ruff: noqa: F401 -from argparse import ArgumentParser as _ArgumentParser, FileType +from argparse import ArgumentParser as _ArgumentParser from sys import stderr diff --git a/python/qemu/ot/util/file.py b/python/qemu/ot/util/file.py index 788221a12edd7..d4b25727f19aa 100644 --- a/python/qemu/ot/util/file.py +++ b/python/qemu/ot/util/file.py @@ -1,4 +1,5 @@ # Copyright (c) 2023-2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """File utilities. @@ -106,7 +107,8 @@ def make_vmem_from_elf(elf_file: Union[str, BinaryIO], is_path = isinstance(vmem_file, str) with open(vmem_file, 'wt') if is_path else vmem_file as vfp: print(f'// name: {elfname}', file=vfp) - print(f'// built: {strftime("%Y/%m/%d %H:%M:%S", elftime)}', file=vfp) + print(f'// built: {strftime("%Y/%m/%d %H:%M:%S", elftime)}', + file=vfp) print(f'// size: {elfstat.st_size}', file=vfp) print(f'// rawsize: {elf.size}', file=vfp) print(f'// entrypoint: 0x{elf.entry_point:08x}', file=vfp) diff --git a/python/qemu/ot/util/log.py b/python/qemu/ot/util/log.py index d2d26937fb0df..fd881ad06a5d9 100644 --- a/python/qemu/ot/util/log.py +++ b/python/qemu/ot/util/log.py @@ -1,4 +1,5 @@ # Copyright (c) 2023-2024 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """Logging helpers. @@ -218,7 +219,7 @@ def handle(self): if len(buffer) < self.HEADER_SIZE: continue header, buffer = (buffer[:self.HEADER_SIZE], - buffer[self.HEADER_SIZE:]) + buffer[self.HEADER_SIZE:]) record_len, = sunpack(self.HEADER_FMT, header) while len(buffer) < record_len: data = self.rfile.read(4096) diff --git a/python/qemu/ot/util/prince.py b/python/qemu/ot/util/prince.py index d5ecf480b8b9c..3ceef81dfe35d 100644 --- a/python/qemu/ot/util/prince.py +++ b/python/qemu/ot/util/prince.py @@ -8,6 +8,7 @@ # pylint: disable=missing-docstring + class PrinceCipher: SBOX4 = [ @@ -120,8 +121,8 @@ def inv_round(cls, rc: int, key: int, data: int) -> int: # Run the PRINCE cipher. # This uses the new keyschedule proposed by Dinur in "Cryptanalytic - # Time-Memory-Data Tradeoffs for FX-Constructions with Applications to PRINCE - # and PRIDE". + # Time-Memory-Data Tradeoffs for FX-Constructions with Applications to + # PRINCE and PRIDE". @classmethod def run(cls, data: int, khi: int, klo: int, num_rounds_half: int) -> int: khi_rot1 = ((khi & 1) << 63) | (khi >> 1) diff --git a/python/qemu/ot/verilator/executer.py b/python/qemu/ot/verilator/executer.py index 53a46a6828cbb..11478e5ff1acb 100644 --- a/python/qemu/ot/verilator/executer.py +++ b/python/qemu/ot/verilator/executer.py @@ -1,6 +1,7 @@ """Verilator wrapper.""" # Copyright (c) 2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 from collections import deque @@ -714,7 +715,7 @@ def _convert_rom_file(self, file_kind: str, file_path: str, size: int, with open(hex_path, 'wb') as hfp: rom.save(hfp, 'svmem') self._log.debug('ROM#%d: using temp scrambled as ROM file %s, %d bytes', - rom_idx, basename(hex_path), size) + rom_idx, basename(hex_path), size) return hex_path def _convert_app_file(self, file_kind: str, file_path: str) -> str: diff --git a/scripts/opentitan/autoreg.py b/scripts/opentitan/autoreg.py index 247c1d86a0af9..3c47dc7b60a7f 100755 --- a/scripts/opentitan/autoreg.py +++ b/scripts/opentitan/autoreg.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 # Copyright (c) 2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """Generate device definitions for OpenTitan device. @@ -346,7 +347,7 @@ def _parse_interrupts(self, hjson: dict[str, Any], address: int, registers.append(AutoRegister(**regargs)) return registers - def _parse_alerts(self, hjson:dict[str, Any], address: int) \ + def _parse_alerts(self, hjson: dict[str, Any], address: int) \ -> list[AutoRegister]: fields: list[AutoField] = [] if hjson.get('no_auto_alert_regs', False): @@ -419,7 +420,7 @@ def _parse_reg_fields(self, reg: dict[str, Any]) -> list[AutoField]: bitfield |= bitmask try: access = getattr(AutoAccess, - field.get('swaccess', reg_swaccess).upper()) + field.get('swaccess', reg_swaccess).upper()) except KeyError as exc: raise RuntimeError(f'Cannot find swaccess for {name}') from exc resval = field.get('resval') @@ -439,7 +440,7 @@ def _parse_reg_fields(self, reg: dict[str, Any]) -> list[AutoField]: fieldargs = [fname, desc, offset, width, access, reset] fields.append(AutoField(*fieldargs)) bitmask = (1 << self._regwidth) - 1 - if bitfield &~ bitmask: + if bitfield & ~bitmask: raise ValueError(f'Bitfield {name} out of range: ' f'0x{bitfield:0{nibcount}x}, mask ' f'0x{bitmask:0{nibcount}x}') @@ -554,7 +555,7 @@ def generate_header(self, tfp: TextIO) -> None: #include "hw/sysbus.h" #include "trace.h" - ''' + ''' # noqa: E501 print(redent(code), file=tfp) def generate_struct(self, tfp: TextIO) -> None: @@ -828,7 +829,7 @@ def _generate_mask(self, regs: list[AutoRegister], tfp: TextIO) -> None: print(f'#define {name}_WMASK \\\n ({maskstr})', file=tfp) # special cast for interrupt testing with mixed fields if (reg.name == 'INTR_STATE' and reg.shared_fields and - reg.access == AutoAccess.UNDEF): + reg.access == AutoAccess.UNDEF): masks: list[str] = [ f'{name}_{field.name}_MASK' for field in reg.fields ] @@ -961,7 +962,7 @@ def _generate_io(self, group: str, regs: list[AutoRegister], write: bool, lines.append(redent(''' qemu_log_mask(LOG_GUEST_ERROR, "%s: %s: Bad offset 0x%" HWADDR_PRIx "\\n", __func__, s->ot_id, addr); - ''', 4, True)) + ''', 4, True)) # noqa: E501 if not write: lines.append(' val32 = 0;') lines.append(' break;') @@ -988,7 +989,8 @@ def _generate_reg_wrappers(self, group: Optional[str], sep = f'_{group}_' if group else '_' lines = [] if last.count > 1: - lines.append(f'#define R_LAST{sep}REG (R_{last.name}_{last.count-1})') + lines.append(f'#define R_LAST{sep}REG ' + f'(R_{last.name}_{last.count-1})') else: lines.append(f'#define R_LAST{sep}REG (R_{last.name})') lines.append(f'#define REGS{sep}COUNT (R_LAST{sep}REG + 1u)') @@ -1241,7 +1243,7 @@ def generate_header(self, tfp: TextIO) -> None: use tock_registers::interfaces::{{ReadWriteable, Readable, Writeable}}; use tock_registers::registers::{{ReadOnly, ReadWrite, WriteOnly}}; use tock_registers::{{register_bitfields, register_structs}}; - ''' + ''' # noqa: E501 # @todo ideally RW/RO/WO use should depend on the actual register # definitions. This is not yet supported. print(redent(code), file=tfp) @@ -1305,8 +1307,9 @@ def _generate_registers(self, tfp: TextIO) -> None: print('];\n', file=tfp) def _generate_register(self, reg: AutoRegister, - shfields: dict[str, tuple[list[AutoField], set[str]]], - nibcount: int, repcount:int, tfp: TextIO) -> None: + shfields: dict[str, tuple[list[AutoField], + set[str]]], + nibcount: int, repcount: int, tfp: TextIO) -> None: regtype = { AutoAccess.RO: 'ReadOnly', AutoAccess.WO: 'WriteOnly', diff --git a/scripts/opentitan/autotop.py b/scripts/opentitan/autotop.py index c68f616ab485f..67a6a8d2683d0 100755 --- a/scripts/opentitan/autotop.py +++ b/scripts/opentitan/autotop.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 # Copyright (c) 2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """Generate machine definitions for OpenTitan top. @@ -154,7 +155,7 @@ def _load_devices(self, topdir: str) -> None: continue for genfile in listdir(gendir): if (not genfile.endswith('.gen.hjson') or - not genfile.startswith('xbar_')): + not genfile.startswith('xbar_')): continue xbarcfg = joinpath(gendir, genfile) if not isfile(xbarcfg): @@ -203,7 +204,7 @@ def _load_xbar(self, xbarcfg: str) -> None: self._devices[uname][subname] = dev def _load_all_interrupts(self, hjson: dict[str, Any]) -> None: - interrupts = self._load_interrupts( hjson.get('interrupt', [])) + interrupts = self._load_interrupts(hjson.get('interrupt', [])) irq_num = 0 for dev, name in interrupts: if dev not in self._interrupts: @@ -347,7 +348,7 @@ def _generate_qemu_devices(self, prefix: str, dev: str, tfp: TextIO) \ except KeyError: # temporary alert = QEMUSignal("missing", -1) - mbox_map = {'MBX_JTAG' : 'DEBUG'} + mbox_map = {'MBX_JTAG': 'DEBUG'} if mmo.group(1) not in mbox_map: lines.append(f' {uprefix}_DEV_MBX({mbxidx}, {addr}u, ' f'"ot-mbx.sram", {irq.index}, {alert.index}),') @@ -497,9 +498,9 @@ def main(): assert len(outkinds) > 0 top = argparser.add_argument_group(title='Top') top.add_argument('opentitan', nargs='?', metavar='OTDIR', - help='OpenTitan root directory') + help='OpenTitan root directory') top.add_argument('-T', '--top', required=True, - help='OpenTitan top name') + help='OpenTitan top name') files = argparser.add_argument_group(title='Files') files.add_argument('-o', '--output', type=FileType('wt'), metavar='FILE', @@ -507,9 +508,9 @@ def main(): files.add_argument('-p', '--prefix', default='ot_dj_soc', help='constant prefix (default: ot_dj_soc)') files.add_argument('-k', '--out-kind', choices=outkinds, - default=outkinds[0], - help=f'output file format ' - f'(default: {outkinds[0]})') + default=outkinds[0], + help=f'output file format ' + f'(default: {outkinds[0]})') extra = argparser.add_argument_group(title='Extras') extra.add_argument('-v', '--verbose', action='count', help='increase verbosity') diff --git a/scripts/opentitan/cfggen.py b/scripts/opentitan/cfggen.py index bea7ca85d3e9b..498d464bc0e94 100755 --- a/scripts/opentitan/cfggen.py +++ b/scripts/opentitan/cfggen.py @@ -447,7 +447,7 @@ def _generate_key_mgr(self, cfg: ConfigParser, cfg[f'ot_device "{kmname}"'] = kmdata def _generate_ast(self, cfg: ConfigParser, variant: str, - socid: Optional[str] = None) -> None: + socid: Optional[str] = None) -> None: nameargs = [f'ot-ast-{variant}'] if socid: nameargs.append(socid) @@ -493,9 +493,9 @@ def _generate_clkmgr(self, cfg: ConfigParser, groupstr = ','.join(f'{g.name}:{"+".join(sorted(g.sources))}' for g in self._clock_groups.values()) swcgstr = ','.join(g.name for g in self._clock_groups.values() - if g.sw_cg) + if g.sw_cg) hintstr = ','.join(g.name for g in self._clock_groups.values() - if g.hint) + if g.hint) self.add_pair(clkname, clkdata, 'topclocks', topclockstr) if clkrefname: self.add_pair(clkname, clkdata, 'refclock', clkrefname) @@ -513,7 +513,7 @@ def _generate_pwrmgr(self, cfg: ConfigParser, pwrname = '.'.join(nameargs) pwrdata = {} clockstr = ','.join(c.name for c in self._top_clocks.values() - if not c.aon) + if not c.aon) self.add_pair(pwrname, pwrdata, 'clocks', clockstr) cfg[f'ot_device "{pwrname}"'] = pwrdata diff --git a/scripts/opentitan/keymgr-dpe.py b/scripts/opentitan/keymgr-dpe.py index e613c6835838b..e4ae9d1fb2115 100755 --- a/scripts/opentitan/keymgr-dpe.py +++ b/scripts/opentitan/keymgr-dpe.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 # Copyright (c) 2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """QEMU OT tool to generate Key Manager DPE keys. @@ -56,8 +57,9 @@ def main(): params = argparser.add_argument_group(title='Parameters') params.add_argument('-e', '--ecc', type=int, default=OtpImage.DEFAULT_ECC_BITS, - metavar='BITS', help=f'ECC bit count (default: ' - f'{OtpImage.DEFAULT_ECC_BITS})') + metavar='BITS', + help=f'ECC bit count (default: ' + f'{OtpImage.DEFAULT_ECC_BITS})') params.add_argument('-z', '--rom-size', metavar='SIZE', type=HexInt.xparse, action='append', default=[], @@ -74,23 +76,23 @@ def main(): genparser = subparsers.add_parser('generate', help='generate a key') genparser.add_argument('-b', '--swbindings', action='append', - default=[], metavar='HEXSTR', - help='SW bindings, may be repeated') + default=[], metavar='HEXSTR', + help='SW bindings, may be repeated') genparser.add_argument('-g', '--gen-out', choices=KeyManagerDpe.OUTPUTS, - help='generation output (default: auto)') + help='generation output (default: auto)') genparser.add_argument('-k', '--key-version', metavar='HEXSTR', - type=HexInt, required=True, - help='Key version') + type=HexInt, required=True, + help='Key version') genparser.add_argument('-o', '--output', - help='output file with generated key') + help='output file with generated key') genparser.add_argument('-R', '--rust-const', metavar='NAME', - help='Rust constant name for the generated key') + help='Rust constant name for the generated key') genparser.add_argument('-s', '--salt', default=[], metavar='HEXSTR', - required=True, - help='Salt') + required=True, + help='Salt') genparser.add_argument('-t', '--target', - choices=KeyManagerDpe.TARGETS, required=True, - help='destination device') + choices=KeyManagerDpe.TARGETS, required=True, + help='destination device') exeparser = subparsers.add_parser('execute', help='execute sequence') exeparser.add_argument('-s', '--sequence', metavar='INI', required=True, diff --git a/scripts/opentitan/requirements.txt b/scripts/opentitan/requirements.txt index 46cd967cf2154..8877b67bbb7ec 100644 --- a/scripts/opentitan/requirements.txt +++ b/scripts/opentitan/requirements.txt @@ -1,6 +1,7 @@ # Python requirements pylint>=3.3.3, <4.0 +flake8>=7.3.0, <8.0 pyyaml>=6 hjson>=3.1 pyelftools>=0.30 -pycryptodome >= 3.12 +pycryptodome>=3.12 diff --git a/scripts/opentitan/spiflashpat.py b/scripts/opentitan/spiflashpat.py index c2151924e4791..9fde89e95bedd 100755 --- a/scripts/opentitan/spiflashpat.py +++ b/scripts/opentitan/spiflashpat.py @@ -6,6 +6,7 @@ """ # Copyright (c) 2024 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 from argparse import ArgumentParser @@ -147,7 +148,8 @@ def main(): if bitwidth > length * 8: argparser.error('Pattern width larger than slot size') - flasher = SpiFlashPatternGenerator(args.size, args.file, args.big_endian) + flasher = SpiFlashPatternGenerator(args.size, args.file, + args.big_endian) flasher.resize(args.reset) flasher.generate(args.address, args.count, args.inc, length, bitwidth) diff --git a/scripts/opentitan/tktool.py b/scripts/opentitan/tktool.py index abf22fb280238..815179f80f4b5 100755 --- a/scripts/opentitan/tktool.py +++ b/scripts/opentitan/tktool.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 # Copyright (c) 2025 Rivos, Inc. +# Copyright (c) 2025 lowRISC contributors. # SPDX-License-Identifier: Apache2 """LifeCycle Controller tiny token tools @@ -23,10 +24,10 @@ # ruff: noqa: E402 from ot.util.log import configure_loggers -_IEXC: Optional[Exception] = None +_IEXC: Optional[Exception] = None # noqa: F841 try: from ot.lc_ctrl.tools import LifeCycleTokenEngine -except ImportError as _IEXC: +except ImportError as _IEXC: # noqa: F841 pass @@ -37,9 +38,9 @@ def main(): desc = sys.modules[__name__].__doc__.split('.', 1)[0].strip() argparser = ArgumentParser(description=f'{desc}.') argparser.add_argument('-s', '--hash', metavar='TOKEN', - help='hash the submitted token') + help='hash the submitted token') argparser.add_argument('-g', '--generate', metavar='TOKEN_NAME', - help='generate a new token pair') + help='generate a new token pair') argparser.add_argument('-r', '--parse-rust', metavar='FILE', type=FileType('rt'), help='parse token from a Rust file')