From 9ff978155c523a391f5f1b4ce2441d533e53f3fb Mon Sep 17 00:00:00 2001 From: krzys-h Date: Sat, 23 Jan 2016 21:07:19 +0100 Subject: [PATCH] Fix crash with CBot string functions out of range (closes #704) --- src/CBot/stdlib/StringFunctions.cpp | 12 ++++++++++++ test/unit/CBot/CBot_test.cpp | 10 ++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/CBot/stdlib/StringFunctions.cpp b/src/CBot/stdlib/StringFunctions.cpp index f4ac5e8b..7b18057e 100644 --- a/src/CBot/stdlib/StringFunctions.cpp +++ b/src/CBot/stdlib/StringFunctions.cpp @@ -70,6 +70,9 @@ bool rStrLeft( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) // retrieves this number int n = pVar->GetValInt(); + if (n > static_cast(s.length())) n = s.length(); + if (n < 0) n = 0; + // no third parameter if ( pVar->GetNext() != nullptr ) { ex = CBotErrOverParam ; return true; } @@ -103,6 +106,9 @@ bool rStrRight( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) // retrieves this number int n = pVar->GetValInt(); + if (n > static_cast(s.length())) n = s.length(); + if (n < 0) n = 0; + // no third parameter if ( pVar->GetNext() != nullptr ) { ex = CBotErrOverParam ; return true; } @@ -136,6 +142,9 @@ bool rStrMid( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) // retrieves this number int n = pVar->GetValInt(); + if (n > static_cast(s.length())) n = s.length(); + if (n < 0) n = 0; + // third parameter optional if ( pVar->GetNext() != nullptr ) { @@ -147,6 +156,9 @@ bool rStrMid( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) // retrieves this number int l = pVar->GetValInt(); + if (l > static_cast(s.length())) l = s.length(); + if (l < 0) l = 0; + // but no fourth parameter if ( pVar->GetNext() != nullptr ){ ex = CBotErrOverParam ; return true; } diff --git a/test/unit/CBot/CBot_test.cpp b/test/unit/CBot/CBot_test.cpp index f7b25391..ff751821 100644 --- a/test/unit/CBot/CBot_test.cpp +++ b/test/unit/CBot/CBot_test.cpp @@ -969,6 +969,16 @@ TEST_F(CBotUT, StringFunctions) " ASSERT(strfind(s, \"o\") == 1);\n" " ASSERT(strval(\"2.5\") == 2.5);\n" "}\n" + "extern void StringFunctionsOutOfRange()\n" + "{\n" + " ASSERT(strmid(\"asdf\", 5, 1) == \"\");\n" + " ASSERT(strmid(\"asdf\", 0, 100) == \"asdf\");\n" + " ASSERT(strmid(\"asdf\", -500, 100) == \"asdf\");\n" + " ASSERT(strleft(\"asdf\", 15) == \"asdf\");\n" + " ASSERT(strleft(\"asdf\", -15) == \"\");\n" + " ASSERT(strright(\"asdf\", 15) == \"asdf\");\n" + " ASSERT(strright(\"asdf\", -15) == \"\");\n" + "}\n" ); }