From 9f097e492a07c96e3b250d6ac0044499f64f6cea Mon Sep 17 00:00:00 2001
From: Alex Stewart <alex.stewart@ni.com>
Date: Tue, 17 Oct 2023 12:19:12 -0400
Subject: [PATCH 17/17] ima_adpcm: fix int overflow in ima_reader_init()

When calculating sf.frames, pre-cast samplesperblock to sf_count_t, to
provide the calculation with enough numeric space to avoid overflows.

Other changes in this commit are syntactic, and only to satisfy the git
pre-commit syntax checker.

CVE: CVE-2022-33065
Fixes: https://github.com/libsndfile/libsndfile/issues/833

Signed-off-by: Alex Stewart <alex.stewart@ni.com>

Upstream-Status: Backport [import from ubuntu https://git.launchpad.net/ubuntu/+source/libsndfile/tree/debian/patches/CVE-2022-33065/CVE-2022-33065-13.patch?h=ubuntu/jammy-security
Upstream commit https://github.com/libsndfile/libsndfile/commit/9f097e492a07c96e3b250d6ac0044499f64f6cea]
CVE: CVE-2022-33065
Signed-off-by: Vijay Anusuri <vanusuri@mvista.com>
---
 src/ima_adpcm.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

--- libsndfile-1.0.31.orig/src/ima_adpcm.c
+++ libsndfile-1.0.31/src/ima_adpcm.c
@@ -182,7 +182,12 @@ ima_reader_init (SF_PRIVATE *psf, int bl
 	if (psf->file.mode != SFM_READ)
 		return SFE_BAD_MODE_RW ;
 
-	pimasize = sizeof (IMA_ADPCM_PRIVATE) + blockalign * psf->sf.channels + 3 * psf->sf.channels * samplesperblock ;
+	/*
+	**	Allocate enough space for 1 more than a multiple of 8 samples
+	**	to avoid having to branch when pulling apart the nibbles.
+	*/
+	count = ((samplesperblock - 2) | 7) + 2 ;
+	pimasize = sizeof (IMA_ADPCM_PRIVATE) + psf->sf.channels * (blockalign + samplesperblock + sizeof (short) * count) ;
 
 	if (! (pima = calloc (1, pimasize)))
 		return SFE_MALLOC_FAILED ;
@@ -233,7 +238,7 @@ ima_reader_init (SF_PRIVATE *psf, int bl
 		case SF_FORMAT_AIFF :
 				psf_log_printf (psf, "still need to check block count\n") ;
 				pima->decode_block = aiff_ima_decode_block ;
-				psf->sf.frames = pima->samplesperblock * pima->blocks / pima->channels ;
+				psf->sf.frames = (sf_count_t) pima->samplesperblock * pima->blocks / pima->channels ;
 				break ;
 
 		default :
@@ -386,7 +391,7 @@ aiff_ima_encode_block (SF_PRIVATE *psf,
 static int
 wavlike_ima_decode_block (SF_PRIVATE *psf, IMA_ADPCM_PRIVATE *pima)
 {	int		chan, k, predictor, blockindx, indx, indxstart, diff ;
-	short	step, bytecode, stepindx [2] ;
+	short	step, bytecode, stepindx [2] = { 0 } ;
 
 	pima->blockcount ++ ;
 	pima->samplecount = 0 ;
