From 3d7457aaf37834637ac776d1ce51fbb2cac75ebf Mon Sep 17 00:00:00 2001 From: Martin Teichmann <martin.teichmann@gmail.com> Date: Wed, 8 Feb 2023 08:14:48 +0000 Subject: [PATCH] new way to define Else statements --- ebpfcat/ebpf.py | 16 +++++++++++++++- ebpfcat/ebpf_test.py | 25 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/ebpfcat/ebpf.py b/ebpfcat/ebpf.py index b487b9b..3ff0073 100644 --- a/ebpfcat/ebpf.py +++ b/ebpfcat/ebpf.py @@ -273,6 +273,20 @@ def comparison(uposop, unegop, sposop, snegop): return ret +class Elser: + def __init__(self, comp): + self.comp = comp + + def __enter__(self): + return self.comp.Else() + + def __exit__(self, exc_type, exc, tb): + self.comp.__exit__(exc_type, exc, tb) + + def Else(self): + return self.comp.Else() + + class Comparison(ABC): """Base class for all logical operations""" @@ -283,7 +297,7 @@ class Comparison(ABC): def __enter__(self): if self.else_origin is None: self.compare(True) - return self + return Elser(self) def __exit__(self, exc_type, exc, tb): if self.else_origin is None: diff --git a/ebpfcat/ebpf_test.py b/ebpfcat/ebpf_test.py index c8ee9f8..366725e 100644 --- a/ebpfcat/ebpf_test.py +++ b/ebpfcat/ebpf_test.py @@ -391,6 +391,31 @@ class Tests(TestCase): Instruction(opcode=O.JMP, dst=0, src=0, off=1, imm=0), Instruction(opcode=O.MOV+O.LONG, dst=7, src=0, off=0, imm=8)]) + def test_with_new(self): + e = EBPF() + e.owners = set(range(11)) + with e.r2 > 3 as Else: + e.r2 = 5 + with Else: + e.r6 = 7 + with e.r2: + e.r3 = 2 + with e.r4 > 3 as Else: + e.r5 = 7 + with Else: + e.r7 = 8 + self.assertEqual(e.opcodes, + [Instruction(opcode=0xb5, dst=2, src=0, off=2, imm=3), + Instruction(opcode=0xb7, dst=2, src=0, off=0, imm=5), + Instruction(opcode=0x5, dst=0, src=0, off=1, imm=0), + Instruction(opcode=O.MOV+O.LONG, dst=6, src=0, off=0, imm=7), + Instruction(opcode=O.JEQ, dst=2, src=0, off=1, imm=0), + Instruction(opcode=O.MOV+O.LONG, dst=3, src=0, off=0, imm=2), + Instruction(opcode=O.JLE, dst=4, src=0, off=2, imm=3), + Instruction(opcode=O.MOV+O.LONG, dst=5, src=0, off=0, imm=7), + Instruction(opcode=O.JMP, dst=0, src=0, off=1, imm=0), + Instruction(opcode=O.MOV+O.LONG, dst=7, src=0, off=0, imm=8)]) + def test_with_inversion(self): e = EBPF() with e.r1 & 1 as cond: -- GitLab