Web lists-archives.com

[PATCH 01/11] sha1_file: do not leak `lock_file`




There is no longer any need to allocate and leak a `struct lock_file`.
Initialize it on the stack instead.

Instead of setting `lock = NULL` to signal that we have already rolled
back, and that we should not do any more work, check with
`is_lock_file_locked()`. Since we take the lock with
`LOCK_DIE_ON_ERROR`, it evaluates to false exactly when we have called
`rollback_lock_file()`.

Signed-off-by: Martin Ågren <martin.agren@xxxxxxxxx>
---
 sha1_file.c | 16 +++++++---------
 1 file changed, 7 insertions(+), 9 deletions(-)

diff --git a/sha1_file.c b/sha1_file.c
index 5a2014811..c50d6237e 100644
--- a/sha1_file.c
+++ b/sha1_file.c
@@ -456,12 +456,12 @@ struct alternate_object_database *alloc_alt_odb(const char *dir)
 
 void add_to_alternates_file(const char *reference)
 {
-	struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
+	struct lock_file lock = LOCK_INIT;
 	char *alts = git_pathdup("objects/info/alternates");
 	FILE *in, *out;
 
-	hold_lock_file_for_update(lock, alts, LOCK_DIE_ON_ERROR);
-	out = fdopen_lock_file(lock, "w");
+	hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
+	out = fdopen_lock_file(&lock, "w");
 	if (!out)
 		die_errno("unable to fdopen alternates lockfile");
 
@@ -481,17 +481,15 @@ void add_to_alternates_file(const char *reference)
 		strbuf_release(&line);
 		fclose(in);
 
-		if (found) {
-			rollback_lock_file(lock);
-			lock = NULL;
-		}
+		if (found)
+			rollback_lock_file(&lock);
 	}
 	else if (errno != ENOENT)
 		die_errno("unable to read alternates file");
 
-	if (lock) {
+	if (is_lock_file_locked(&lock)) {
 		fprintf_or_die(out, "%s\n", reference);
-		if (commit_lock_file(lock))
+		if (commit_lock_file(&lock))
 			die_errno("unable to move new alternates file into place");
 		if (alt_odb_tail)
 			link_alt_odb_entries(reference, '\n', NULL, 0);
-- 
2.14.1.727.g9ddaf86