From ea06cc046bb96ae12bddb37b41eb9900d92183d3 Mon Sep 17 00:00:00 2001 From: dcz Date: Fri, 1 Apr 2022 12:48:27 +0000 Subject: [PATCH] openocd: Fix cleanup after exceptions This fixes unwinding resources after an exception. The old version would exit if the creation of the socket failed, raising an exception when trying to close the socket. The new version makes sure that only objects successfully created are cleaned up. Instead of nesting try..finally multiple times, this appends handlers onto an explicit list. --- tockloader/openocd.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/tockloader/openocd.py b/tockloader/openocd.py index 4008273..b32f565 100644 --- a/tockloader/openocd.py +++ b/tockloader/openocd.py @@ -396,6 +396,7 @@ def run_terminal(self): logging.debug('Running "{}".'.format(openocd_command.replace("$", "\$"))) + cleanup = [] try: # This won't print messages from OpenOCD, # to avoid interfering with the console. @@ -404,6 +405,8 @@ def run_terminal(self): stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) + cleanup.append(ocd_p.wait) + cleanup.append(ocd_p.kill) # Delay to give the connection time to start before running # the RTT listener. @@ -414,20 +417,18 @@ def run_terminal(self): logging.status("Listening for messages.") listener = socket.socket() listener.connect(("127.0.0.1", 9999)) + cleanup.append(listener.close) out = listener.makefile(mode="rb") + cleanup.append(out.close) for out_line in iter(out.readline, ""): l = out_line.decode("utf-8", errors="replace") if not l.startswith("###RTT Client: *"): print(l, end="") finally: logging.status("Stopping") - try: - out.close() - listener.close() - ocd_p.kill() - ocd_p.wait() - except UnboundLocalError: - pass + for f in reversed(cleanup): + f() + openocd_command, _ = self._gather_openocd_cmdline( [ "init",