Skip to contentSkip to conversation

Off-by-one error in get_path_prefix(), found by Valgrind

PATCH In review Pavel Roskin 3 participants 4 messages Jun 15, 2016

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 Off-by-one error in get_path_prefix(), found by Valgrind

From: Pavel Roskin <[email protected]>

---

 builtin-tar-tree.c |    4 ++--
 1 files changed, 2 insertions(+), 2 deletions(-)
builtin-tar-tree.c +2 -2
index 5f740cf..05da1f2 100644
@@ -166,8 +166,8 @@ static unsigned int ustar_header_chksum(
 static int get_path_prefix(const struct strbuf *path, int maxlen)
 {
 	int i = path->len;
-	if (i > maxlen)
-		i = maxlen;
+	if (i >= maxlen)
+		i = maxlen - 1;
 	while (i > 0 && path->buf[i] != '/')
 		i--;
 	return i;
#1 lore raw
Quoted 13 lines · Pavel Roskin

From: Pavel Roskin <[email protected]>

---

 builtin-tar-tree.c |    4 ++--
 1 files changed, 2 insertions(+), 2 deletions(-)
builtin-tar-tree.c +0 -0
index 5f740cf..05da1f2 100644

builtin-tar-tree.c static unsigned int ustar_header_chksum( · line 173

Quoted 10 lines
builtin-tar-tree.c +2 -2
@@ -166,8 +166,8 @@ static unsigned int ustar_header_chksum(
 static int get_path_prefix(const struct strbuf *path, int maxlen)
 {
 	int i = path->len;
-	if (i > maxlen)
-		i = maxlen;
+	if (i >= maxlen)
+		i = maxlen - 1;
 	while (i > 0 && path->buf[i] != '/')
 		i--;
 	return i;

Argh, yes. Thanks, Pavel! However, the other branch is incorrect, too:
accessing path->buf[path->len] is wrong, even if it's within the buffer. In order to use a length variable to point to the end of some string we need to subtract 1. *sigh* So, how about this one instead?

builtin-tar-tree.c +2 -1
index 5f740cf..7663b9b 100644
@@ -168,8 +168,9 @@ static int get_path_prefix(const struct 
 	int i = path->len;
 	if (i > maxlen)
 		i = maxlen;
-	while (i > 0 && path->buf[i] != '/')
+	do {
 		i--;
+	} while (i > 0 && path->buf[i] != '/');
 	return i;
 }
 
#2 lore raw
Quoted 1 line · Rene Scharfe

Argh, yes. Thanks, Pavel!

Actually, thanks to Julian Seward for Valgrind.

Quoted 4 lines

However, the other branch is incorrect, too:
accessing path->buf[path->len] is wrong, even if it's within the buffer. In order to use a length variable to point to the end of some string we need to subtract 1. *sigh* So, how about this one instead?

Fine with me. Thank you for noticing!

Signature · 2 lines
Regards,
Pavel Roskin
#3 lore raw
Quoted 11 lines · Pavel Roskin
Quoted 1 line · Rene Scharfe

Argh, yes. Thanks, Pavel!

Actually, thanks to Julian Seward for Valgrind.

Quoted 4 lines

However, the other branch is incorrect, too:
accessing path->buf[path->len] is wrong, even if it's within the buffer. In order to use a length variable to point to the end of some string we need to subtract 1. *sigh* So, how about this one instead?

Fine with me. Thank you for noticing!

Thanks both. Applied.