Skip to content

Commit 10bee0d

Browse files
committed
Merge #11284: Fix invalid memory access in CScript::operator+= (guidovranken, ajtowns)
d601f16 Fix invalid memory access in CScript::operator+= (Anthony Towns) Pull request description: This is a fix for #11114 -- invoking "s += s" gets turned into "s.insert(s.end(), s.begin(), s.end())" which can result in an invalid memory access is s.capacity() < 2*s.size() (because s gets resized and possibly moved, so s.begin() and s.end() become invalid references when reading the values to be appended). The fix is straightforward: reserve enough space in advance, so that insert() doesn't need to resize and thus its arguments remain valid. A simple test case is added as well; though you probably need to run it via valgrind to actually catch the problem when it's not fixed... Tree-SHA512: 4720d0c17463fdc43b344c45fe603423d20b30d48da1b9d85eeedc505d7f34db1ed5495ef1556459ae962a94717e3c6e8fc441763771901efea210d01322b7ef
2 parents c641cca + d601f16 commit 10bee0d

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/script/script.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,7 @@ class CScript : public CScriptBase
420420

421421
CScript& operator+=(const CScript& b)
422422
{
423+
reserve(size() + b.size());
423424
insert(end(), b.begin(), b.end());
424425
return *this;
425426
}

src/test/script_tests.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1451,4 +1451,21 @@ BOOST_AUTO_TEST_CASE(script_HasValidOps)
14511451
BOOST_CHECK(!script.HasValidOps());
14521452
}
14531453

1454+
BOOST_AUTO_TEST_CASE(script_can_append_self)
1455+
{
1456+
CScript s, d;
1457+
1458+
s = ScriptFromHex("00");
1459+
s += s;
1460+
d = ScriptFromHex("0000");
1461+
BOOST_CHECK(s == d);
1462+
1463+
// check doubling a script that's large enough to require reallocation
1464+
static const char hex[] = "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f";
1465+
s = CScript() << ParseHex(hex) << OP_CHECKSIG;
1466+
d = CScript() << ParseHex(hex) << OP_CHECKSIG << ParseHex(hex) << OP_CHECKSIG;
1467+
s += s;
1468+
BOOST_CHECK(s == d);
1469+
}
1470+
14541471
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)