From fc87b0a32c130a2b3ab37e614d4a1c6c8e5d70e7 Mon Sep 17 00:00:00 2001 From: Kamil Dudka Date: Thu, 19 Aug 2010 13:58:12 +0200 Subject: [PATCH 2/3] check stat's result and avoid calling stat on a NULL pointer --- src/files.c | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/src/files.c b/src/files.c index f6efbf1..99cc1b8 100644 --- a/src/files.c +++ b/src/files.c @@ -310,6 +310,24 @@ int do_lockfile(const char *filename) } #endif /* !NANO_TINY */ +#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. */ +void stat_if_needed(const char *filename, struct stat **pstat) +{ + struct stat *tmp; + if (*pstat) + return; + + tmp = (struct stat *)nmalloc(sizeof(struct stat)); + if (0 == stat(filename, tmp)) + *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) @@ -355,11 +373,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 } @@ -1753,10 +1767,8 @@ bool write_file(const char *name, FILE *f_open, bool tmp, append_type * specified it interactively), stat and save the value now, * or else we will chase null pointers when we do modtime checks, * preserve file times, and so on, during backup. */ - if (openfile->current_stat == NULL && !tmp && realexists) { - openfile->current_stat = (struct stat *)nmalloc(sizeof(struct stat)); - 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 @@ -2149,8 +2161,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)); - if (!openfile->mark_set) - stat(realname, openfile->current_stat); + if (!openfile->mark_set && 0 != stat(realname, openfile->current_stat)) { + free(openfile->current_stat); + openfile->current_stat = NULL; + } #endif statusbar(P_("Wrote %lu line", "Wrote %lu lines", -- 1.7.4