Skip to content

Commit 7d65f89

Browse files
committed
Check for multiplication overflow in sfconvert
Checks that a multiplication doesn't overflow when calculating the buffer size, and if it overflows, reduce the buffer size instead of failing. This fixes the 00192-audiofile-signintoverflow-sfconvert case in mpruett#41
1 parent beacc44 commit 7d65f89

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

Diff for: sfcommands/sfconvert.c

+32-2
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,33 @@ void printusage (void);
4545
void usageerror (void);
4646
bool copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid);
4747

48+
int firstBitSet(int x)
49+
{
50+
int position=0;
51+
while (x!=0)
52+
{
53+
x>>=1;
54+
++position;
55+
}
56+
return position;
57+
}
58+
59+
#ifndef __has_builtin
60+
#define __has_builtin(x) 0
61+
#endif
62+
63+
int multiplyCheckOverflow(int a, int b, int *result)
64+
{
65+
#if (defined __GNUC__ && __GNUC__ >= 5) || ( __clang__ && __has_builtin(__builtin_mul_overflow))
66+
return __builtin_mul_overflow(a, b, result);
67+
#else
68+
if (firstBitSet(a)+firstBitSet(b)>31) // int is signed, so we can't use 32 bits
69+
return true;
70+
*result = a * b;
71+
return false;
72+
#endif
73+
}
74+
4875
int main (int argc, char **argv)
4976
{
5077
if (argc == 2)
@@ -323,8 +350,11 @@ bool copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid)
323350
{
324351
int frameSize = afGetVirtualFrameSize(infile, trackid, 1);
325352

326-
const int kBufferFrameCount = 65536;
327-
void *buffer = malloc(kBufferFrameCount * frameSize);
353+
int kBufferFrameCount = 65536;
354+
int bufferSize;
355+
while (multiplyCheckOverflow(kBufferFrameCount, frameSize, &bufferSize))
356+
kBufferFrameCount /= 2;
357+
void *buffer = malloc(bufferSize);
328358

329359
AFframecount totalFrames = afGetFrameCount(infile, AF_DEFAULT_TRACK);
330360
AFframecount totalFramesWritten = 0;

0 commit comments

Comments
 (0)