From b74962c92b2d8d9b957934e0aefcf4983169ae1e Mon Sep 17 00:00:00 2001 From: Sergei Trofimovich Date: Mon, 14 Aug 2023 22:07:37 +0100 Subject: [PATCH] src/libexpr/search-path.cc: avoid out-of-bounds read on string_view Without the change build with `-D_GLIBCXX_ASSERTIONS` exposes testsuite assertion: $ gdb src/libexpr/tests/libnixexpr-tests Reading symbols from src/libexpr/tests/libnixexpr-tests... (gdb) break __glibcxx_assert_fail (gdb) run (gdb) bt in std::__glibcxx_assert_fail(char const*, int, char const*, char const*)@plt () from /mnt/archive/big/git/nix/src/libexpr/libnixexpr.so in std::basic_string_view >::operator[] (this=0x7fffffff56c0, __pos=4) at /nix/store/r74fw2j8rx5idb0w8s1s6ynwwgs0qmh9-gcc-14.0.0/include/c++/14.0.0/string_view:258 in nix::SearchPath::Prefix::suffixIfPotentialMatch (this=0x7fffffff5780, path=...) at src/libexpr/search-path.cc:15 in nix::SearchPathElem_suffixIfPotentialMatch_partialPrefix_Test::TestBody (this=0x555555a17540) at src/libexpr/tests/search-path.cc:62 As string sizes are usigned types `(a - b) > 0` effectively means `a != b`. While the intention should be `a > b`. The change fixes test suite pass. --- src/libexpr/search-path.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libexpr/search-path.cc b/src/libexpr/search-path.cc index 36bb4c3a5..180d5f8b1 100644 --- a/src/libexpr/search-path.cc +++ b/src/libexpr/search-path.cc @@ -10,7 +10,7 @@ std::optional SearchPath::Prefix::suffixIfPotentialMatch( /* Non-empty prefix and suffix must be separated by a /, or the prefix is not a valid path prefix. */ - bool needSeparator = n > 0 && (path.size() - n) > 0; + bool needSeparator = n > 0 && n < path.size(); if (needSeparator && path[n] != '/') { return std::nullopt;