From 16546269aa2a725d5fd187eef2dc812bbba43b7a Mon Sep 17 00:00:00 2001
From: Suhrid Subramaniam <suhrid.subramaniam@mediatek.com>
Date: Thu, 2 Mar 2023 11:06:29 -0800
Subject: libcamera: converter: Check converter validity

The ConverterFactoryBase::create() function returns a nullptr when no
converter is found. The only caller, SimpleCameraData::init(), checks if
the converter is valid with isValid(), but doesn't check if the pointer
is null, which can lead to a crash.

We could check both pointer validity and converter validity in the
caller, but to limit the complexity in callers, it is better to check
the converter validity in the create() function and return a null
pointer when no valid converter is found.

Signed-off-by: Suhrid Subramaniam <suhrid.subramaniam@mediatek.com>
Reviewed-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
---
 src/libcamera/converter.cpp              | 4 +++-
 src/libcamera/pipeline/simple/simple.cpp | 2 +-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/libcamera/converter.cpp b/src/libcamera/converter.cpp
index 3de39cff..fa0f1ec8 100644
--- a/src/libcamera/converter.cpp
+++ b/src/libcamera/converter.cpp
@@ -227,7 +227,9 @@ std::unique_ptr<Converter> ConverterFactoryBase::create(MediaDevice *media)
 			<< factory->name_ << " factory with "
 			<< (it == compatibles.end() ? "no" : media->driver()) << " alias.";
 
-		return factory->createInstance(media);
+		std::unique_ptr<Converter> converter = factory->createInstance(media);
+		if (converter->isValid())
+			return converter;
 	}
 
 	return nullptr;
diff --git a/src/libcamera/pipeline/simple/simple.cpp b/src/libcamera/pipeline/simple/simple.cpp
index 24ded4db..2423ec10 100644
--- a/src/libcamera/pipeline/simple/simple.cpp
+++ b/src/libcamera/pipeline/simple/simple.cpp
@@ -493,7 +493,7 @@ int SimpleCameraData::init()
 	MediaDevice *converter = pipe->converter();
 	if (converter) {
 		converter_ = ConverterFactoryBase::create(converter);
-		if (!converter_->isValid()) {
+		if (!converter_) {
 			LOG(SimplePipeline, Warning)
 				<< "Failed to create converter, disabling format conversion";
 			converter_.reset();
-- 
cgit v1.2.1