Subject: [PATCH v2 09/27] upload-pack: make check_non_tip() clean things up on error

From: Nguyễn Thái Ngọc Duy <[email-masked]>
Date: Sun, 12 Jun 2016 17:53:51 +0700

On error check_non_tip() will die and not closing file descriptors is no
big deal. The next patch will split the majority of this function out
for reuse in other cases, where die() may not be the only outcome. Same
story for popping SIGPIPE out of the signal chain. So let's make sure we
clean things up properly first.

Signed-off-by: Nguyễn Thái Ngọc Duy <[email-masked]>
---
 upload-pack.c | 23 ++++++++++++++++-------
 1 file changed, 16 insertions(+), 7 deletions(-)

diff --git a/upload-pack.c b/upload-pack.c
index 8f4d7f4..7ce97ec 100644
--- a/upload-pack.c
+++ b/upload-pack.c
@@ -475,16 +475,16 @@ static void check_non_tip(void)
 	cmd.in = -1;
 	cmd.out = -1;
 
-	if (start_command(&cmd))
-		goto error;
-
 	/*
-	 * If rev-list --stdin encounters an unknown commit, it
-	 * terminates, which will cause SIGPIPE in the write loop
+	 * If the next rev-list --stdin encounters an unknown commit,
+	 * it terminates, which will cause SIGPIPE in the write loop
 	 * below.
 	 */
 	sigchain_push(SIGPIPE, SIG_IGN);
 
+	if (start_command(&cmd))
+		goto error;
+
 	namebuf[0] = '^';
 	namebuf[41] = '\n';
 	for (i = get_max_object_index(); 0 < i; ) {
@@ -507,8 +507,7 @@ static void check_non_tip(void)
 			goto error;
 	}
 	close(cmd.in);
-
-	sigchain_pop(SIGPIPE);
+	cmd.in = -1;
 
 	/*
 	 * The commits out of the rev-list are not ancestors of
@@ -518,6 +517,7 @@ static void check_non_tip(void)
 	if (i)
 		goto error;
 	close(cmd.out);
+	cmd.out = -1;
 
 	/*
 	 * rev-list may have died by encountering a bad commit
@@ -527,10 +527,19 @@ static void check_non_tip(void)
 	if (finish_command(&cmd))
 		goto error;
 
+	sigchain_pop(SIGPIPE);
+
 	/* All the non-tip ones are ancestors of what we advertised */
 	return;
 
 error:
+	sigchain_pop(SIGPIPE);
+
+	if (cmd.in >= 0)
+		close(cmd.in);
+	if (cmd.out >= 0)
+		close(cmd.out);
+
 	/* Pick one of them (we know there at least is one) */
 	for (i = 0; i < want_obj.nr; i++) {
 		o = want_obj.objects[i].item;
-- 
2.8.2.524.g6ff3d78