From 3c2a287eeab43d87a10b4acd52508f87e4e11e2c Mon Sep 17 00:00:00 2001 From: Leah Rowe Date: Sun, 4 Jun 2023 15:12:14 +0100 Subject: util/spkmodem-recv: handle sample errors correctly when calling fread(), errno may be set to EOVEFLOW if the range being read will cause an integer overflow if end-of-file is reached, errno may not be set. when calling this function, you must check errno or check feof() - ferror() should also be checked, so this check is added immediately afterwards in the code ferror() does not set errno, so ERR() is used to set errno to ECANCELED as program exit status further separate reading of frames into a new function Signed-off-by: Leah Rowe --- util/spkmodem_recv/spkmodem-recv.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) (limited to 'util/spkmodem_recv') diff --git a/util/spkmodem_recv/spkmodem-recv.c b/util/spkmodem_recv/spkmodem-recv.c index 1dcf5f18..93afd95a 100644 --- a/util/spkmodem_recv/spkmodem-recv.c +++ b/util/spkmodem_recv/spkmodem-recv.c @@ -21,6 +21,7 @@ #define DEBUG 0 #define FLUSH_TIMEOUT 1 +#define ERR() (errno = errno ? errno : ECANCELED) signed short frame[2 * SAMPLES_PER_FRAME]; signed short pulse[2 * SAMPLES_PER_FRAME]; @@ -30,6 +31,7 @@ char ascii = 0; void handle_audio(void); void print_char(void); void fetch_sample(void); +void read_frame(int ringpos); int main(int argc, char *argv[]) @@ -94,9 +96,7 @@ fetch_sample(void) f1 -= pulse[ringpos]; f1 += pulse[(ringpos + SAMPLES_PER_FRAME) % (2 * SAMPLES_PER_FRAME)]; f2 -= pulse[(ringpos + SAMPLES_PER_FRAME) % (2 * SAMPLES_PER_FRAME)]; - if (fread(frame + ringpos, 1, sizeof(frame[0]), stdin) - != sizeof(frame[0])) - err(errno = ECANCELED, "Could not read frame."); + read_frame(ringpos); pulse[ringpos] = (abs(frame[ringpos]) > THRESHOLD) ? 1 : 0; if (pulse[ringpos++]) @@ -105,6 +105,16 @@ fetch_sample(void) ++lp; } +void +read_frame(int ringpos) +{ + if (fread(frame + ringpos, 1, sizeof(frame[0]), stdin) + != sizeof(frame[0])) + err(ERR(), "Could not read from frame."); + if (ferror(stdin) != 0) + err(ERR(), "Could not read from frame"); +} + void print_char(void) { -- cgit v1.2.1