From fb49d59902d6e43762b926bab73b1afb0700788c Mon Sep 17 00:00:00 2001
From: Mirela Rabulea <mirela.rabulea@nxp.com>
Date: Fri, 12 Oct 2018 13:23:44 +0300
Subject: [PATCH] MLK-19605: mxc-jpeg: RGB format in jpeg can't be decoded by
 mxc-jpeg driver

Validate the component ID's when parsing the jpeg headers,
print error and don't continue the decoding, avoid getting stuck.

Signed-off-by: Mirela Rabulea <mirela.rabulea@nxp.com>
---
 drivers/media/platform/imx8/mxc-jpeg.c | 26 ++++++++++++++++++++++++++
 drivers/media/platform/imx8/mxc-jpeg.h |  3 ++-
 2 files changed, 28 insertions(+), 1 deletion(-)

diff --git a/drivers/media/platform/imx8/mxc-jpeg.c b/drivers/media/platform/imx8/mxc-jpeg.c
index ab0f81757c43a7..a1d515a95eab4f 100644
--- a/drivers/media/platform/imx8/mxc-jpeg.c
+++ b/drivers/media/platform/imx8/mxc-jpeg.c
@@ -692,6 +692,23 @@ static u8 get_sof(struct device *dev,
 	return 0;
 }
 
+static int mxc_jpeg_valid_comp_id(
+	struct device *dev,
+	const struct mxc_jpeg_sof *sof)
+{
+	int valid = 1;
+	int i;
+
+	for (i = 0; i < sof->components_no; i++)
+		if (sof->comp[i].id > MXC_JPEG_MAX_COMPONENTS) {
+			valid = 0;
+			dev_err(dev, "Component %d has invalid ID: %d",
+				i, sof->comp[i].id);
+		}
+
+	return valid;
+}
+
 static enum mxc_jpeg_image_format mxc_jpeg_get_image_format(
 	struct device *dev,
 	const struct mxc_jpeg_sof *sof)
@@ -825,6 +842,15 @@ static int mxc_jpeg_parse(struct mxc_jpeg_ctx *ctx,
 			sof.width, sof.height);
 		return -EINVAL;
 	}
+	if (sof.components_no > MXC_JPEG_MAX_COMPONENTS) {
+		dev_err(dev, "JPEG number of components should be <=%d",
+			MXC_JPEG_MAX_COMPONENTS);
+		return -EINVAL;
+	}
+	if (!mxc_jpeg_valid_comp_id(dev, &sof)) {
+		dev_err(dev, "JPEG component identifiers should be 0-3 or 1-4");
+		return -EINVAL;
+	}
 	desc->imgsize = sof.width << 16 | sof.height;
 	dev_dbg(dev, "JPEG imgsize = 0x%x (%dx%d)\n", desc->imgsize,
 		sof.width, sof.height);
diff --git a/drivers/media/platform/imx8/mxc-jpeg.h b/drivers/media/platform/imx8/mxc-jpeg.h
index f3e987e7d39b20..5b5fdd25275cd1 100644
--- a/drivers/media/platform/imx8/mxc-jpeg.h
+++ b/drivers/media/platform/imx8/mxc-jpeg.h
@@ -123,6 +123,7 @@ struct mxc_jpeg_dev {
 	struct mxc_jpeg_slot_data slot_data[MXC_MAX_SLOTS];
 };
 
+#define MXC_JPEG_MAX_COMPONENTS 4
 /* JPEG Start Of Frame marker fields*/
 struct mxc_jpeg_sof_comp {
 	u8 id; /*component id*/
@@ -136,7 +137,7 @@ struct mxc_jpeg_sof {
 	u8 precision;
 	u16 height, width;
 	u8 components_no;
-	struct mxc_jpeg_sof_comp comp[4];
+	struct mxc_jpeg_sof_comp comp[MXC_JPEG_MAX_COMPONENTS];
 } __packed;
 
 #endif
-- 
GitLab