From 14030f215ff1c74beec4e75b4f6c48d0daaea8f2 Mon Sep 17 00:00:00 2001 From: Kamil Dudka Date: Mon, 6 Dec 2010 20:22:24 +0100 Subject: [PATCH] check stat's result and avoid calling stat on a NULL pointer --- src/files.c | 33 +++++++++++++++++++++++++-------- 1 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/files.c b/src/files.c index 8ae3cef..1d41eeb 100644 --- a/src/files.c +++ b/src/files.c @@ -103,6 +103,24 @@ void initialize_buffer_text(void) openfile->totsize = 0; } +#ifndef NANO_TINY +/* If *pstat is NULL, perform a stat call with the given file name. On success, + * *pstat points to a newly allocated buffer that contains the stat's result. + * On stat's failure, the NULL pointer in *pstat is left intact. */ +static void stat_if_needed(const char *filename, struct stat **pstat) +{ + struct stat *tmp; + if (*pstat) + return; + + tmp = nmalloc(sizeof(*tmp)); + if (stat(filename, tmp) == 0) + *pstat = tmp; + else + free(tmp); +} +#endif + /* If it's not "", filename is a file to open. We make a new buffer, if * necessary, and then open and read the file, if applicable. */ void open_buffer(const char *filename, bool undoable) @@ -148,11 +166,7 @@ void open_buffer(const char *filename, bool undoable) if (rc > 0) { read_file(f, rc, filename, undoable, new_buffer); #ifndef NANO_TINY - if (openfile->current_stat == NULL) { - openfile->current_stat = - (struct stat *)nmalloc(sizeof(struct stat)); - stat(filename, openfile->current_stat); - } + stat_if_needed(filename, &openfile->current_stat); #endif } @@ -1511,8 +1525,8 @@ bool write_file(const char *name, FILE *f_open, bool tmp, append_type * specified it interactively), stat and save the value * or else we will chase null pointers when we do * modtime checks, preserve file times, etc. during backup */ - if (openfile->current_stat == NULL && !tmp && realexists) - stat(realname, openfile->current_stat); + if (!tmp && realexists) + stat_if_needed(realname, &openfile->current_stat); /* We backup only if the backup toggle is set, the file isn't * temporary, and the file already exists. Furthermore, if we @@ -1894,7 +1908,10 @@ bool write_file(const char *name, FILE *f_open, bool tmp, append_type if (openfile->current_stat == NULL) openfile->current_stat = (struct stat *)nmalloc(sizeof(struct stat)); - stat(realname, openfile->current_stat); + if (stat(realname, openfile->current_stat)) { + free(openfile->current_stat); + openfile->current_stat = NULL; + } #endif statusbar(P_("Wrote %lu line", "Wrote %lu lines", -- 1.7.3.2