From fc87b0a32c130a2b3ab37e614d4a1c6c8e5d70e7 Mon Sep 17 00:00:00 2001
From: Kamil Dudka <kdudka@redhat.com>
Date: Thu, 19 Aug 2010 13:58:12 +0200
Subject: [PATCH 1/2] 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 f6efbf1..99cc1b8 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. */
+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)
@@ -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
     }
 
@@ -1532,8 +1546,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
@@ -1924,7 +1938,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.4

