[PATCH 4/5] hwlatdetect: Add bounds checking and improve code readability
John Kacur <[email protected]>
| Newsgroups | org.kernel.vger.linux-rt-users |
|---|---|
| Message-ID | <[email protected]> |
Add defensive checks to the Sample.__init__ method to prevent IndexError on malformed trace input: - Verify fields array has at least 8 elements - Check cpu_field is non-empty before accessing first character - Add comments explaining the two different trace formats - Improve code readability by using a named variable for cpu_field Assisted-by: Claude Sonnet 4.5 <[email protected]> Signed-off-by: John Kacur <[email protected]> --- src/hwlatdetect/hwlatdetect.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/hwlatdetect/hwlatdetect.py b/src/hwlatdetect/hwlatdetect.py index 865f62196c26..38671724f3e3 100755 --- a/src/hwlatdetect/hwlatdetect.py +++ b/src/hwlatdetect/hwlatdetect.py @@ -257,8 +257,22 @@ class Tracer(Detector): def __init__(self, line): fields = line.split() + if len(fields) < 8: + raise ValueError(f"Unexpected trace format: {line}") + kv = key_values(fields) - self.cpu = int(fields[1][1:-1]) if fields[1][0] == '[' else int(fields[1][:-5]) + + # Parse CPU number from either [NNN] or NNd.... format + cpu_field = fields[1] + if not cpu_field: + raise ValueError(f"Empty CPU field in: {line}") + + if cpu_field[0] == '[': + # nolatency-format: [007] + self.cpu = int(cpu_field[1:-1]) + else: + # latency-format: 13d.... + self.cpu = int(cpu_field[:-5]) i, o = fields[6].split('/') ts = fields[7][3:] self.timestamp = str(ts) -- 2.53.0