diff mbox series

media: v4l2-core: v4l2-ctrls: check for handler_new_ref misuse

Message ID 1c5dc406-2875-4c0e-8155-7766df428f49@xs4all.nl (mailing list archive)
State New
Headers show
Series media: v4l2-core: v4l2-ctrls: check for handler_new_ref misuse | expand

Commit Message

Hans Verkuil Oct. 28, 2024, 8:34 a.m. UTC
An out-of-tree driver created a control handler, added controls, then called
v4l2_ctrl_add_handler to add references to controls from another handler, and
finally added another control that happened to have the same control ID as one
of the controls from that other handler.

This caused a NULL pointer crash when an attempt was made to use that last
control.

Besides the fact that two out-of-tree drivers used the same control ID for
different (private) controls, which is obviously a bug, this specific scenario
should have been caught. The root cause is the 'duplicate ID' check in
handler_new_ref(): it expects that drivers will first add all controls to a
control handler before calling v4l2_ctrl_add_handler. That way the local
controls will always override references to controls from another handler.

It never considered the case where new local controls were added after calling
v4l2_ctrl_add_handler. Add a check to handler_new_ref() to return an error in
the case that a new local control is added with the same ID as an existing
control reference. Also use WARN_ON since this is a driver bug.

This situation can only happen when out-of-tree drivers are used or during
driver development, since mainlined drivers all have their own control ranges
reserved in v4l2-controls.h, thus preventing duplicate control IDs.

Signed-off-by: Hans Verkuil <hverkuil@xs4all.nl>
---
diff mbox series

Patch

diff --git a/drivers/media/v4l2-core/v4l2-ctrls-core.c b/drivers/media/v4l2-core/v4l2-ctrls-core.c
index eeab6a5eb7ba..947a9ee1535e 100644
--- a/drivers/media/v4l2-core/v4l2-ctrls-core.c
+++ b/drivers/media/v4l2-core/v4l2-ctrls-core.c
@@ -1676,6 +1676,7 @@  int handler_new_ref(struct v4l2_ctrl_handler *hdl,
 	u32 class_ctrl = V4L2_CTRL_ID2WHICH(id) | 1;
 	int bucket = id % hdl->nr_of_buckets;	/* which bucket to use */
 	unsigned int size_extra_req = 0;
+	int ret = 0;

 	if (ctrl_ref)
 		*ctrl_ref = NULL;
@@ -1722,6 +1723,13 @@  int handler_new_ref(struct v4l2_ctrl_handler *hdl,
 		/* Don't add duplicates */
 		if (ref->ctrl->id == id) {
 			kfree(new_ref);
+			/*
+			 * Either the driver creates the same control twice,
+			 * or the same control is present in an added control
+			 * handler.
+			 */
+			if (WARN_ON(hdl == ctrl->handler))
+				ret = -EEXIST;
 			goto unlock;
 		}
 		list_add(&new_ref->node, ref->node.prev);
@@ -1746,6 +1754,8 @@  int handler_new_ref(struct v4l2_ctrl_handler *hdl,

 unlock:
 	mutex_unlock(hdl->lock);
+	if (ret)
+		return handler_set_err(hdl, ret);
 	return 0;
 }