From 77e9e1ed91182cb8409d325e225a99decb49b3d5 Mon Sep 17 00:00:00 2001 From: Tuomas Tynkkynen Date: Mon, 19 Feb 2018 17:52:33 +0200 Subject: [PATCH] libexpr: Fix prim_replaceStrings() to work on an empty source string Otherwise, running e.g. nix-instantiate --eval -E --strict 'builtins.replaceStrings [""] ["X"] "abc"' would just hang in an infinite loop. Found by afl-fuzz. First attempt of this was reverted in e2d71bd1862cdda because it caused another infinite loop, which is fixed now and a test added. --- src/libexpr/primops.cc | 17 ++++++++++++++--- tests/lang/eval-okay-replacestrings.exp | 2 +- tests/lang/eval-okay-replacestrings.nix | 3 +++ 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index a800d2429..db258ea18 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -1913,21 +1913,32 @@ static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * ar auto s = state.forceString(*args[2], context, pos); string res; - for (size_t p = 0; p < s.size(); ) { + // Loops one past last character to handle the case where 'from' contains an empty string. + for (size_t p = 0; p <= s.size(); ) { bool found = false; auto i = from.begin(); auto j = to.begin(); for (; i != from.end(); ++i, ++j) if (s.compare(p, i->size(), *i) == 0) { found = true; - p += i->size(); res += j->first; + if (i->empty()) { + if (p < s.size()) + res += s[p]; + p++; + } else { + p += i->size(); + } for (auto& path : j->second) context.insert(path); j->second.clear(); break; } - if (!found) res += s[p++]; + if (!found) { + if (p < s.size()) + res += s[p]; + p++; + } } mkString(v, res, context); diff --git a/tests/lang/eval-okay-replacestrings.exp b/tests/lang/eval-okay-replacestrings.exp index a2add1b7b..72e8274d8 100644 --- a/tests/lang/eval-okay-replacestrings.exp +++ b/tests/lang/eval-okay-replacestrings.exp @@ -1 +1 @@ -[ "faabar" "fbar" "fubar" "faboor" "fubar" ] +[ "faabar" "fbar" "fubar" "faboor" "fubar" "XaXbXcX" "X" "a_b" ] diff --git a/tests/lang/eval-okay-replacestrings.nix b/tests/lang/eval-okay-replacestrings.nix index 6284a0e66..bd8031fc0 100644 --- a/tests/lang/eval-okay-replacestrings.nix +++ b/tests/lang/eval-okay-replacestrings.nix @@ -5,4 +5,7 @@ with builtins; (replaceStrings ["oo"] ["u"] "foobar") (replaceStrings ["oo" "a"] ["a" "oo"] "foobar") (replaceStrings ["oo" "oo"] ["u" "i"] "foobar") + (replaceStrings [""] ["X"] "abc") + (replaceStrings [""] ["X"] "") + (replaceStrings ["-"] ["_"] "a-b") ]