From 0b0c575e3c6e0279d2466deb4d2d0a20a6444f41 Mon Sep 17 00:00:00 2001 From: jvoisin Date: Wed, 17 Jul 2024 01:38:32 +0200 Subject: [PATCH] Simplify a bit the detect_arch function - Use a regex to extract the arch instead of doing the extraction "by hand". - Reduce nested indentation. - Reduce the amount of code in the loop. - Remove a forceful `re.compile`: python will cache regex in a compiled form if necessary. --- kernel_hardening_checker/__init__.py | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/kernel_hardening_checker/__init__.py b/kernel_hardening_checker/__init__.py index 6f551e5..19636d9 100755 --- a/kernel_hardening_checker/__init__.py +++ b/kernel_hardening_checker/__init__.py @@ -36,21 +36,23 @@ def _open(file: str) -> TextIO: sys.exit(f'[!] ERROR: unable to open {file}, are you sure it exists?') -def detect_arch(fname: str, archs: List[str]) -> Tuple[StrOrNone, str]: +def detect_arch(fname: str, supported_archs: List[str]) -> Tuple[StrOrNone, str]: + arch = None + with _open(fname) as f: - arch_pattern = re.compile(r"CONFIG_[a-zA-Z0-9_]+=y$") - arch = None for line in f.readlines(): - if arch_pattern.match(line): - option, _ = line[7:].split('=', 1) - if option in archs: - if arch is None: - arch = option - else: - return None, 'detected more than one microarchitecture' - if arch is None: - return None, 'failed to detect microarchitecture' - return arch, 'OK' + if m := re.search("CONFIG_([A-Z0-9_]+)=y$", line): + option = m.group(1) + if option not in supported_archs: + continue + if arch is None: + arch = option + else: + return None, 'detected more than one microarchitecture' + + if arch is None: + return None, 'failed to detect microarchitecture' + return arch, 'OK' def detect_kernel_version(fname: str) -> Tuple[TupleOrNone, str]: -- 2.31.1