[PATCH] media: tw686x: avoid double free on video register failure

Guangshuo Li posted 1 patch 6 days, 18 hours ago
drivers/media/pci/tw686x/tw686x-video.c | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
[PATCH] media: tw686x: avoid double free on video register failure
Posted by Guangshuo Li 6 days, 18 hours ago
tw686x_video_init() allocates a video_device with video_device_alloc()
and releases it if video_register_device() fails.

This can double free the video_device when __video_register_device()
reaches device_register() and that call fails:

  video_register_device()
    -> __video_register_device()
       -> device_register() fails
          -> put_device(&vdev->dev)
             -> v4l2_device_release()
                -> vdev->release(vdev)
                   -> video_device_release(vdev)

  tw686x_video_init()
    -> video_device_release(vdev)

Use video_device_release_empty() while registering the device so that
registration failure paths do not free vdev through vdev->release().
tw686x_video_init() then releases vdev exactly once on failure. Restore
video_device_release() after successful registration so the registered
device keeps its normal lifetime handling.

Clear vc->device after releasing the failed video_device, since the
common error path tears down already initialized channels.

This issue was found by a static analysis tool I am developing.

Fixes: e0b212ec9d81 ("media: tw686x: Fix memory leak in tw686x_video_init")
Signed-off-by: Guangshuo Li <lgs201920130244@gmail.com>
---
 drivers/media/pci/tw686x/tw686x-video.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/drivers/media/pci/tw686x/tw686x-video.c b/drivers/media/pci/tw686x/tw686x-video.c
index 785dd797d921..7d121dba4f79 100644
--- a/drivers/media/pci/tw686x/tw686x-video.c
+++ b/drivers/media/pci/tw686x/tw686x-video.c
@@ -1266,7 +1266,7 @@ int tw686x_video_init(struct tw686x_dev *dev)
 		snprintf(vdev->name, sizeof(vdev->name), "%s video", dev->name);
 		vdev->fops = &tw686x_video_fops;
 		vdev->ioctl_ops = &tw686x_video_ioctl_ops;
-		vdev->release = video_device_release;
+		vdev->release = video_device_release_empty;
 		vdev->v4l2_dev = &dev->v4l2_dev;
 		vdev->queue = &vc->vidq;
 		vdev->tvnorms = V4L2_STD_525_60 | V4L2_STD_625_50;
@@ -1281,8 +1281,11 @@ int tw686x_video_init(struct tw686x_dev *dev)
 		err = video_register_device(vdev, VFL_TYPE_VIDEO, -1);
 		if (err < 0) {
 			video_device_release(vdev);
+			vc->device = NULL;
 			goto error;
 		}
+
+		vdev->release = video_device_release;
 		vc->num = vdev->num;
 	}
 
-- 
2.43.0