[Toybox] [PATCH 1/2] basename: fix segfault on null input; add tests
samuel at sholland.org
samuel at sholland.org
Sun Mar 20 11:13:21 PDT 2016
From: Samuel Holland <samuel at sholland.org>
When passed an empty string, glibc's basename() returns a pointer to the
string "." in read-only memory. If an empty suffix is given, it fits
the condition of being shorter than the path, so we try to overwrite the
null byte and crash. Fix this by just ignoring empty suffixes; they
don't do anything anyway.
---
tests/basename.test | 3 +++
toys/posix/basename.c | 2 +-
2 files changed, 4 insertions(+), 1 deletion(-)
diff --git a/tests/basename.test b/tests/basename.test
index 9d3b296..ab2cc20 100755
--- a/tests/basename.test
+++ b/tests/basename.test
@@ -21,3 +21,6 @@ testing "reappearing suffix 2" "basename a.txt.old .txt" "a.txt.old\n" "" ""
# A suffix should be a real suffix, only a the end.
testing "invalid suffix" "basename isthisasuffix? suffix" "isthisasuffix?\n" "" ""
+
+# Zero-length suffix
+testing "zero-length suffix" "basename a/b/c ''" "c\n" "" ""
diff --git a/toys/posix/basename.c b/toys/posix/basename.c
index 1a27a23..c123cc7 100644
--- a/toys/posix/basename.c
+++ b/toys/posix/basename.c
@@ -23,7 +23,7 @@ void basename_main(void)
char *base = basename(*toys.optargs), *suffix = toys.optargs[1];
// chop off the suffix if provided
- if (suffix) {
+ if (suffix && *suffix) {
long bl = strlen(base), sl = strlen(suffix);
char *s = base + bl - sl;
--
2.7.3
1458497601.0
More information about the Toybox
mailing list