git@vger.kernel.org mailing list mirror (one of many)
 help / color / mirror / code / Atom feed
* [PATCH] run-command: avoid undefined behavior in exists_in_PATH
@ 2020-01-07  1:36 brian m. carlson
  2020-01-07  2:04 ` Jonathan Nieder
  2020-01-07 11:01 ` Jeff King
  0 siblings, 2 replies; 11+ messages in thread
From: brian m. carlson @ 2020-01-07  1:36 UTC (permalink / raw)
  To: git; +Cc: Jeff King, Junio C Hamano, Miriam R.

In this function, we free the pointer we get from locate_in_PATH and
then check whether it's NULL.  However, this is undefined behavior if
the pointer is non-NULL, since the C standard no longer permits us to
use a valid pointer after freeing it.

The only case in which the C standard would permit this to be defined
behavior is if r were NULL, since it states that in such a case "no
action occurs" as a result of calling free.

It's easy to suggest that this is not likely to be a problem, but we
know that GCC does aggressively exploit the fact that undefined
behavior can never occur to optimize and rewrite code, even when that's
contrary to the expectations of the programmer.  It is, in fact, very
common for it to omit NULL pointer checks, just as we have here.

Since it's easy to fix, let's do so, and avoid a potential headache in
the future.

Noticed-by: Miriam R. <mirucam@gmail.com>
Signed-off-by: brian m. carlson <sandals@crustytoothpaste.net>
---
 run-command.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/run-command.c b/run-command.c
index 9942f120a9..f5e1149f9b 100644
--- a/run-command.c
+++ b/run-command.c
@@ -213,8 +213,9 @@ static char *locate_in_PATH(const char *file)
 static int exists_in_PATH(const char *file)
 {
 	char *r = locate_in_PATH(file);
+	int found = r != NULL;
 	free(r);
-	return r != NULL;
+	return found;
 }
 
 int sane_execvp(const char *file, char * const argv[])

^ permalink raw reply related	[flat|nested] 11+ messages in thread

end of thread, other threads:[~2020-01-08 10:29 UTC | newest]

Thread overview: 11+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2020-01-07  1:36 [PATCH] run-command: avoid undefined behavior in exists_in_PATH brian m. carlson
2020-01-07  2:04 ` Jonathan Nieder
2020-01-07  2:16   ` brian m. carlson
2020-01-07  3:40   ` Bryan Turner
2020-01-07  3:41     ` Bryan Turner
2020-01-07 11:08   ` Jeff King
2020-01-07 11:01 ` Jeff King
2020-01-07 16:58   ` Junio C Hamano
2020-01-08  2:47   ` brian m. carlson
2020-01-08  9:15     ` Miriam R.
2020-01-08 10:28       ` Christian Couder

Code repositories for project(s) associated with this public inbox

	https://80x24.org/mirrors/git.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).