tempfile: handle NULL tempfile pointers gracefully

The tempfile functions all take pointers to tempfile objects, but do not check whether the argument is NULL. This isn't a big deal in practice, since the lifetime of any tempfile object is defined to last for the whole program. So even if we try to call delete_tempfile() on an already-deleted tempfile, our "active" check will tell us that it's a noop. In preparation for transitioning to a new system that loosens the "tempfile objects can never be freed" rule, let's tighten up our active checks: 1. A NULL pointer is now defined as "inactive" (so it will BUG for most functions, but works as a silent noop for things like delete_tempfile). 2. Functions should always do the "active" check before looking at any of the struct fields. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Sep 5, 2017 at 08:14 UTC f5b4dc7668b6c8d71432af9f9ddad6f7c62d284e
2 files changed +8 -6
tempfile.c
+7 -5
@@ -236,13 +236,15 @@ FILE *get_tempfile_fp(struct tempfile *tempfile)
236
237 int close_tempfile_gently(struct tempfile *tempfile)
238 {
239 - int fd = tempfile->fd;
240 - FILE *fp = tempfile->fp;
239 + int fd;
240 + FILE *fp;
241 int err;
242
243 - if (fd < 0)
243 + if (!is_tempfile_active(tempfile) || tempfile->fd < 0)
244 return 0;
245
246 + fd = tempfile->fd;
247 + fp = tempfile->fp;
248 tempfile->fd = -1;
249 if (fp) {
250 tempfile->fp = NULL;
@@ -262,10 +264,10 @@ int close_tempfile_gently(struct tempfile *tempfile)
264
265 int reopen_tempfile(struct tempfile *tempfile)
266 {
265 - if (0 <= tempfile->fd)
266 - die("BUG: reopen_tempfile called for an open object");
267 if (!is_tempfile_active(tempfile))
268 die("BUG: reopen_tempfile called for an inactive object");
269 + if (0 <= tempfile->fd)
270 + die("BUG: reopen_tempfile called for an open object");
271 tempfile->fd = open(tempfile->filename.buf, O_WRONLY);
272 return tempfile->fd;
273 }
tempfile.h
+1 -1
@@ -211,7 +211,7 @@ extern FILE *fdopen_tempfile(struct tempfile *tempfile, const char *mode);
211
212 static inline int is_tempfile_active(struct tempfile *tempfile)
213 {
214 - return tempfile->active;
214 + return tempfile && tempfile->active;
215 }
216
217 /*