From 9d3893459f34b6ada2dad2d9d27216c774a7c4bd Mon Sep 17 00:00:00 2001 From: Colin Snover Date: Sat, 26 Nov 2016 12:56:25 -0600 Subject: COMMON: Add strnlen for safer C string length reads This API is intended for use in cases where C strings come from untrusted sources like game files, where malformed data missing the null terminator would cause strlen to read out of bounds. --- test/common/str.h | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'test') diff --git a/test/common/str.h b/test/common/str.h index c59c5a5efd..b6080fe3be 100644 --- a/test/common/str.h +++ b/test/common/str.h @@ -403,6 +403,29 @@ class StringTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS(strcmp(test4, resultString), 0); } + void test_strnlen() { + static const char * const testString = "123"; + TS_ASSERT_EQUALS(Common::strnlen(testString, 0), 0); + TS_ASSERT_EQUALS(Common::strnlen(testString, 1), 1); + TS_ASSERT_EQUALS(Common::strnlen(testString, 2), 2); + TS_ASSERT_EQUALS(Common::strnlen(testString, 3), 3); + TS_ASSERT_EQUALS(Common::strnlen(testString, 4), 3); + + const char testArray[4] = { '1', '2', '3', '4' }; + TS_ASSERT_EQUALS(Common::strnlen(testArray, 0), 0); + TS_ASSERT_EQUALS(Common::strnlen(testArray, 1), 1); + TS_ASSERT_EQUALS(Common::strnlen(testArray, 2), 2); + TS_ASSERT_EQUALS(Common::strnlen(testArray, 3), 3); + TS_ASSERT_EQUALS(Common::strnlen(testArray, 4), 4); + + const char testArray2[4] = { '1', '\0', '3', '4' }; + TS_ASSERT_EQUALS(Common::strnlen(testArray2, 0), 0); + TS_ASSERT_EQUALS(Common::strnlen(testArray2, 1), 1); + TS_ASSERT_EQUALS(Common::strnlen(testArray2, 2), 1); + TS_ASSERT_EQUALS(Common::strnlen(testArray2, 3), 1); + TS_ASSERT_EQUALS(Common::strnlen(testArray2, 4), 1); + } + void test_scumm_stricmp() { TS_ASSERT_EQUALS(scumm_stricmp("abCd", "abCd"), 0); TS_ASSERT_EQUALS(scumm_stricmp("abCd", "ABCd"), 0); -- cgit v1.2.3