From 976e55e4a3680c13c1ccc2c308324b3e489bacf7 Mon Sep 17 00:00:00 2001 From: Carter Davis Date: Mon, 11 Aug 2025 21:01:12 +0000 Subject: [PATCH] model loading error handling in denoise.c --- src/denoise.c | 41 ++++++++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/src/denoise.c b/src/denoise.c index b6fc3d4a..ce58e448 100644 --- a/src/denoise.c +++ b/src/denoise.c @@ -35,6 +35,7 @@ #include #include "kiss_fft.h" #include "common.h" +#include #include "denoise.h" #include #include "rnnoise.h" @@ -235,6 +236,8 @@ struct RNNModel { RNNModel *rnnoise_model_from_buffer(const void *ptr, int len) { RNNModel *model; model = malloc(sizeof(*model)); + if (model == NULL) return NULL; + model->blob = NULL; model->const_blob = ptr; model->blob_len = len; @@ -244,28 +247,40 @@ RNNModel *rnnoise_model_from_buffer(const void *ptr, int len) { RNNModel *rnnoise_model_from_filename(const char *filename) { RNNModel *model; FILE *f = fopen(filename, "rb"); + if (f == NULL) return NULL; + model = rnnoise_model_from_file(f); + if (model == NULL) { + fclose(f); + return NULL; + } + model->file = f; return model; } RNNModel *rnnoise_model_from_file(FILE *f) { + if (f == NULL) return NULL; RNNModel *model; - model = malloc(sizeof(*model)); - model->file = NULL; - - fseek(f, 0, SEEK_END); - model->blob_len = ftell(f); - fseek(f, 0, SEEK_SET); - - model->const_blob = NULL; + model = calloc(1, sizeof(*model)); + if (model == NULL) return NULL; + + if (fseek(f, 0, SEEK_END) != 0) goto cleanup; + long sz = ftell(f); + if (sz < 0 || sz > INT_MAX) goto cleanup; + if (fseek(f, 0, SEEK_SET) != 0) goto cleanup; + + model->blob_len = (int)sz; + // malloc(0) is implementation-defined + if (sz == 0) goto cleanup; model->blob = malloc(model->blob_len); - if (fread(model->blob, model->blob_len, 1, f) != 1) - { - rnnoise_model_free(model); - return NULL; - } + if (model->blob == NULL) goto cleanup; + if (fread(model->blob, model->blob_len, 1, f) != 1) goto cleanup; return model; + +cleanup: + rnnoise_model_free(model); + return NULL; } void rnnoise_model_free(RNNModel *model) {