[elbe-devel] [PATCH 2/2] hdimg: clean up losetup() when exceptions are thrown

Torben Hohn torben.hohn at linutronix.de
Wed Jun 16 10:01:59 CEST 2021


"losetup -d" is not called for some error paths.

Add try: finally: to make sure "losetup -d" is called.

Signed-off-by: Torben Hohn <torben.hohn at linutronix.de>
---
 elbepack/hdimg.py | 53 +++++++++++++++++++++++++++--------------------
 1 file changed, 30 insertions(+), 23 deletions(-)

diff --git a/elbepack/hdimg.py b/elbepack/hdimg.py
index f1a72c783..d1cc2e28b 100644
--- a/elbepack/hdimg.py
+++ b/elbepack/hdimg.py
@@ -358,20 +358,26 @@ def create_label(disk, part, ppart, fslabel, target, grub):
     grub.add_fs_entry(entry)
 
     loopdev = entry.losetup()
-    do('mkfs.%s %s %s %s' %
-       (entry.fstype,
-        entry.mkfsopt,
-        entry.get_label_opt(),
-        loopdev))
-
-    do('mount %s %s' % (loopdev, os.path.join(target, "imagemnt")))
-    do('cp -a "%s/." "%s/"' %
-       (os.path.join(target, "filesystems", entry.id),
-        os.path.join(target, "imagemnt")),
-       allow_fail=True)
-    do('umount %s' % loopdev)
-    entry.tuning(loopdev)
-    do('losetup -d %s' % loopdev)
+
+    try:
+        do('mkfs.%s %s %s %s' %
+           (entry.fstype,
+            entry.mkfsopt,
+            entry.get_label_opt(),
+            loopdev))
+
+        do('mount %s %s' % (loopdev, os.path.join(target, "imagemnt")))
+
+        try:
+            do('cp -a "%s/." "%s/"' %
+               (os.path.join(target, "filesystems", entry.id),
+                os.path.join(target, "imagemnt")),
+               allow_fail=True)
+        finally:
+            do('umount %s' % loopdev)
+        entry.tuning(loopdev)
+    finally:
+        do('losetup -d %s' % loopdev)
 
     return ppart
 
@@ -382,16 +388,17 @@ def create_binary(disk, part, ppart, target):
 
     loopdev = entry.losetup()
 
-    # copy from buildenv if path starts with /
-    if part.text("binary")[0] == '/':
-        tmp = target + "/" + "chroot" + part.text("binary")
-    # copy from project directory
-    else:
-        tmp = target + "/" + part.text("binary")
-
-    do(f'dd if="{tmp}" of="{loopdev}"')
+    try:
+        # copy from buildenv if path starts with /
+        if part.text("binary")[0] == '/':
+            tmp = target + "/" + "chroot" + part.text("binary")
+        # copy from project directory
+        else:
+            tmp = target + "/" + part.text("binary")
 
-    do(f'losetup -d "{loopdev}"')
+        do(f'dd if="{tmp}" of="{loopdev}"')
+    finally:
+        do(f'losetup -d "{loopdev}"')
 
 def create_logical_partitions(disk,
                               extended,
-- 
2.20.1



More information about the elbe-devel mailing list