Skip to content

Commit 9b0820d

Browse files
jchodorCompute-Runtime-Automation
authored andcommitted
Fixing potential buffer overflow in simple_sprintf
Change-Id: I67d92073d05049740b4a1bf9783fe8dede7c3c0a
1 parent 8316021 commit 9b0820d

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

runtime/os_interface/windows/print.cpp

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ size_t simple_sprintf(char *output, size_t outputSize, const char *format, T val
5353
_set_output_format(_TWO_DIGIT_EXPONENT);
5454
#endif
5555
size_t len = strlen(format);
56+
if (len == 0) {
57+
output[0] = '\0';
58+
return 0;
59+
}
5660

5761
if (len > 3 && *(format + len - 2) == 'h' && *(format + len - 3) == 'h') {
5862
if (*(format + len - 1) == 'i' || *(format + len - 1) == 'd') {
@@ -63,11 +67,10 @@ size_t simple_sprintf(char *output, size_t outputSize, const char *format, T val
6367
return sprintf_s(output, outputSize, format, fixedValue);
6468
}
6569
} else if (format[len - 1] == 'F') {
66-
char formatCopy[1024];
67-
strcpy_s(formatCopy, 1024, format);
68-
formatCopy[len - 1] = 'f';
70+
std::string formatCopy = format;
71+
*formatCopy.rbegin() = 'f';
6972

70-
size_t returnValue = sprintf_s(output, outputSize, formatCopy, value);
73+
size_t returnValue = sprintf_s(output, outputSize, formatCopy.c_str(), value);
7174
for (size_t i = 0; i < returnValue; i++)
7275
output[i] = std::toupper(output[i]);
7376
return returnValue;

unit_tests/program/printf_helper_tests.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -841,3 +841,11 @@ TEST(printToSTDOUTTest, GivenStringWhenPrintingToSTDOUTThenExpectOutput) {
841841
std::string output = testing::internal::GetCapturedStdout();
842842
EXPECT_STREQ("test", output.c_str());
843843
}
844+
845+
TEST(simpleSprintf, GivenEmptyFormatStringWhenSimpleSprintfIsCalledThenBailOutWith0) {
846+
char out[1024] = {7, 0};
847+
auto ret = simple_sprintf<float>(out, sizeof(out), "", 3.0f);
848+
EXPECT_EQ(0U, ret);
849+
EXPECT_EQ(0, out[0]);
850+
EXPECT_EQ(0, out[1]);
851+
}

0 commit comments

Comments
 (0)