1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/strings/safe_sprintf.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9 #include <stdio.h>
10 #include <string.h>
11
12 #include <limits>
13 #include <memory>
14
15 #include "base/check_op.h"
16 #include "base/types/fixed_array.h"
17 #include "build/build_config.h"
18 #include "partition_alloc/partition_alloc_config.h"
19 #include "testing/gtest/include/gtest/gtest.h"
20
21 // Death tests on Android are currently very flaky. No need to add more flaky
22 // tests, as they just make it hard to spot real problems.
23 // TODO(markus): See if the restrictions on Android can eventually be lifted.
24 #if defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID)
25 #define ALLOW_DEATH_TEST
26 #endif
27
28 namespace base {
29 namespace strings {
30
TEST(SafeSPrintfTest,Empty)31 TEST(SafeSPrintfTest, Empty) {
32 char buf[2] = { 'X', 'X' };
33
34 // Negative buffer size should always result in an error.
35 EXPECT_EQ(-1, SafeSNPrintf(buf, static_cast<size_t>(-1), ""));
36 EXPECT_EQ('X', buf[0]);
37 EXPECT_EQ('X', buf[1]);
38
39 // Zero buffer size should always result in an error.
40 EXPECT_EQ(-1, SafeSNPrintf(buf, 0, ""));
41 EXPECT_EQ('X', buf[0]);
42 EXPECT_EQ('X', buf[1]);
43
44 // A one-byte buffer should always print a single NUL byte.
45 EXPECT_EQ(0, SafeSNPrintf(buf, 1, ""));
46 EXPECT_EQ(0, buf[0]);
47 EXPECT_EQ('X', buf[1]);
48 buf[0] = 'X';
49
50 // A larger buffer should leave the trailing bytes unchanged.
51 EXPECT_EQ(0, SafeSNPrintf(buf, 2, ""));
52 EXPECT_EQ(0, buf[0]);
53 EXPECT_EQ('X', buf[1]);
54 buf[0] = 'X';
55
56 // The same test using SafeSPrintf() instead of SafeSNPrintf().
57 EXPECT_EQ(0, SafeSPrintf(buf, ""));
58 EXPECT_EQ(0, buf[0]);
59 EXPECT_EQ('X', buf[1]);
60 buf[0] = 'X';
61 }
62
TEST(SafeSPrintfTest,NoArguments)63 TEST(SafeSPrintfTest, NoArguments) {
64 // Output a text message that doesn't require any substitutions. This
65 // is roughly equivalent to calling strncpy() (but unlike strncpy(), it does
66 // always add a trailing NUL; it always deduplicates '%' characters).
67 static const char text[] = "hello world";
68 char ref[20], buf[20];
69 memset(ref, 'X', sizeof(ref));
70 memcpy(buf, ref, sizeof(buf));
71
72 // A negative buffer size should always result in an error.
73 EXPECT_EQ(-1, SafeSNPrintf(buf, static_cast<size_t>(-1), text));
74 EXPECT_TRUE(!memcmp(buf, ref, sizeof(buf)));
75
76 // Zero buffer size should always result in an error.
77 EXPECT_EQ(-1, SafeSNPrintf(buf, 0, text));
78 EXPECT_TRUE(!memcmp(buf, ref, sizeof(buf)));
79
80 // A one-byte buffer should always print a single NUL byte.
81 EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1, SafeSNPrintf(buf, 1, text));
82 EXPECT_EQ(0, buf[0]);
83 EXPECT_TRUE(!memcmp(buf+1, ref+1, sizeof(buf)-1));
84 memcpy(buf, ref, sizeof(buf));
85
86 // A larger (but limited) buffer should always leave the trailing bytes
87 // unchanged.
88 EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1, SafeSNPrintf(buf, 2, text));
89 EXPECT_EQ(text[0], buf[0]);
90 EXPECT_EQ(0, buf[1]);
91 EXPECT_TRUE(!memcmp(buf+2, ref+2, sizeof(buf)-2));
92 memcpy(buf, ref, sizeof(buf));
93
94 // A unrestricted buffer length should always leave the trailing bytes
95 // unchanged.
96 EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1,
97 SafeSNPrintf(buf, sizeof(buf), text));
98 EXPECT_EQ(std::string(text), std::string(buf));
99 EXPECT_TRUE(!memcmp(buf + sizeof(text), ref + sizeof(text),
100 sizeof(buf) - sizeof(text)));
101 memcpy(buf, ref, sizeof(buf));
102
103 // The same test using SafeSPrintf() instead of SafeSNPrintf().
104 EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1, SafeSPrintf(buf, text));
105 EXPECT_EQ(std::string(text), std::string(buf));
106 EXPECT_TRUE(!memcmp(buf + sizeof(text), ref + sizeof(text),
107 sizeof(buf) - sizeof(text)));
108 memcpy(buf, ref, sizeof(buf));
109
110 // Check for deduplication of '%' percent characters.
111 EXPECT_EQ(1, SafeSPrintf(buf, "%%"));
112 EXPECT_EQ(2, SafeSPrintf(buf, "%%%%"));
113 EXPECT_EQ(2, SafeSPrintf(buf, "%%X"));
114 EXPECT_EQ(3, SafeSPrintf(buf, "%%%%X"));
115 #if defined(NDEBUG)
116 EXPECT_EQ(1, SafeSPrintf(buf, "%"));
117 EXPECT_EQ(2, SafeSPrintf(buf, "%%%"));
118 EXPECT_EQ(2, SafeSPrintf(buf, "%X"));
119 EXPECT_EQ(3, SafeSPrintf(buf, "%%%X"));
120 #elif defined(ALLOW_DEATH_TEST)
121 EXPECT_DEATH(SafeSPrintf(buf, "%"), "src.1. == '%'");
122 EXPECT_DEATH(SafeSPrintf(buf, "%%%"), "src.1. == '%'");
123 EXPECT_DEATH(SafeSPrintf(buf, "%X"), "src.1. == '%'");
124 EXPECT_DEATH(SafeSPrintf(buf, "%%%X"), "src.1. == '%'");
125 #endif
126 }
127
TEST(SafeSPrintfTest,OneArgument)128 TEST(SafeSPrintfTest, OneArgument) {
129 // Test basic single-argument single-character substitution.
130 const char text[] = "hello world";
131 const char fmt[] = "hello%cworld";
132 char ref[20], buf[20];
133 memset(ref, 'X', sizeof(buf));
134 memcpy(buf, ref, sizeof(buf));
135
136 // A negative buffer size should always result in an error.
137 EXPECT_EQ(-1, SafeSNPrintf(buf, static_cast<size_t>(-1), fmt, ' '));
138 EXPECT_TRUE(!memcmp(buf, ref, sizeof(buf)));
139
140 // Zero buffer size should always result in an error.
141 EXPECT_EQ(-1, SafeSNPrintf(buf, 0, fmt, ' '));
142 EXPECT_TRUE(!memcmp(buf, ref, sizeof(buf)));
143
144 // A one-byte buffer should always print a single NUL byte.
145 EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1,
146 SafeSNPrintf(buf, 1, fmt, ' '));
147 EXPECT_EQ(0, buf[0]);
148 EXPECT_TRUE(!memcmp(buf+1, ref+1, sizeof(buf)-1));
149 memcpy(buf, ref, sizeof(buf));
150
151 // A larger (but limited) buffer should always leave the trailing bytes
152 // unchanged.
153 EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1,
154 SafeSNPrintf(buf, 2, fmt, ' '));
155 EXPECT_EQ(text[0], buf[0]);
156 EXPECT_EQ(0, buf[1]);
157 EXPECT_TRUE(!memcmp(buf+2, ref+2, sizeof(buf)-2));
158 memcpy(buf, ref, sizeof(buf));
159
160 // A unrestricted buffer length should always leave the trailing bytes
161 // unchanged.
162 EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1,
163 SafeSNPrintf(buf, sizeof(buf), fmt, ' '));
164 EXPECT_EQ(std::string(text), std::string(buf));
165 EXPECT_TRUE(!memcmp(buf + sizeof(text), ref + sizeof(text),
166 sizeof(buf) - sizeof(text)));
167 memcpy(buf, ref, sizeof(buf));
168
169 // The same test using SafeSPrintf() instead of SafeSNPrintf().
170 EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1, SafeSPrintf(buf, fmt, ' '));
171 EXPECT_EQ(std::string(text), std::string(buf));
172 EXPECT_TRUE(!memcmp(buf + sizeof(text), ref + sizeof(text),
173 sizeof(buf) - sizeof(text)));
174 memcpy(buf, ref, sizeof(buf));
175
176 // Check for deduplication of '%' percent characters.
177 EXPECT_EQ(1, SafeSPrintf(buf, "%%", 0));
178 EXPECT_EQ(2, SafeSPrintf(buf, "%%%%", 0));
179 EXPECT_EQ(2, SafeSPrintf(buf, "%Y", 0));
180 EXPECT_EQ(2, SafeSPrintf(buf, "%%Y", 0));
181 EXPECT_EQ(3, SafeSPrintf(buf, "%%%Y", 0));
182 EXPECT_EQ(3, SafeSPrintf(buf, "%%%%Y", 0));
183 #if defined(NDEBUG)
184 EXPECT_EQ(1, SafeSPrintf(buf, "%", 0));
185 EXPECT_EQ(2, SafeSPrintf(buf, "%%%", 0));
186 #elif defined(ALLOW_DEATH_TEST)
187 EXPECT_DEATH(SafeSPrintf(buf, "%", 0), "ch");
188 EXPECT_DEATH(SafeSPrintf(buf, "%%%", 0), "ch");
189 #endif
190 }
191
TEST(SafeSPrintfTest,MissingArg)192 TEST(SafeSPrintfTest, MissingArg) {
193 #if defined(NDEBUG)
194 char buf[20];
195 EXPECT_EQ(3, SafeSPrintf(buf, "%c%c", 'A'));
196 EXPECT_EQ("A%c", std::string(buf));
197 #elif defined(ALLOW_DEATH_TEST)
198 char buf[20];
199 EXPECT_DEATH(SafeSPrintf(buf, "%c%c", 'A'), "cur_arg < max_args");
200 #endif
201 }
202
TEST(SafeSPrintfTest,ASANFriendlyBufferTest)203 TEST(SafeSPrintfTest, ASANFriendlyBufferTest) {
204 // Print into a buffer that is sized exactly to size. ASAN can verify that
205 // nobody attempts to write past the end of the buffer.
206 // There is a more complicated test in PrintLongString() that covers a lot
207 // more edge case, but it is also harder to debug in case of a failure.
208 const char kTestString[] = "This is a test";
209 base::FixedArray<char> buf(sizeof(kTestString));
210 memcpy(buf.data(), kTestString, sizeof(kTestString));
211 EXPECT_EQ(static_cast<ssize_t>(sizeof(kTestString) - 1),
212 SafeSNPrintf(buf.data(), buf.size(), kTestString));
213 EXPECT_EQ(std::string(kTestString), std::string(buf.data()));
214 EXPECT_EQ(static_cast<ssize_t>(buf.size() - 1),
215 SafeSNPrintf(buf.data(), buf.size(), "%s", kTestString));
216 EXPECT_EQ(std::string(kTestString), std::string(buf.data()));
217 }
218
TEST(SafeSPrintfTest,NArgs)219 TEST(SafeSPrintfTest, NArgs) {
220 // Pre-C++11 compilers have a different code path, that can only print
221 // up to ten distinct arguments.
222 // We test both SafeSPrintf() and SafeSNPrintf(). This makes sure we don't
223 // have typos in the copy-n-pasted code that is needed to deal with various
224 // numbers of arguments.
225 char buf[12];
226 EXPECT_EQ(1, SafeSPrintf(buf, "%c", 1));
227 EXPECT_EQ("\1", std::string(buf));
228 EXPECT_EQ(2, SafeSPrintf(buf, "%c%c", 1, 2));
229 EXPECT_EQ("\1\2", std::string(buf));
230 EXPECT_EQ(3, SafeSPrintf(buf, "%c%c%c", 1, 2, 3));
231 EXPECT_EQ("\1\2\3", std::string(buf));
232 EXPECT_EQ(4, SafeSPrintf(buf, "%c%c%c%c", 1, 2, 3, 4));
233 EXPECT_EQ("\1\2\3\4", std::string(buf));
234 EXPECT_EQ(5, SafeSPrintf(buf, "%c%c%c%c%c", 1, 2, 3, 4, 5));
235 EXPECT_EQ("\1\2\3\4\5", std::string(buf));
236 EXPECT_EQ(6, SafeSPrintf(buf, "%c%c%c%c%c%c", 1, 2, 3, 4, 5, 6));
237 EXPECT_EQ("\1\2\3\4\5\6", std::string(buf));
238 EXPECT_EQ(7, SafeSPrintf(buf, "%c%c%c%c%c%c%c", 1, 2, 3, 4, 5, 6, 7));
239 EXPECT_EQ("\1\2\3\4\5\6\7", std::string(buf));
240 EXPECT_EQ(8, SafeSPrintf(buf, "%c%c%c%c%c%c%c%c", 1, 2, 3, 4, 5, 6, 7, 8));
241 EXPECT_EQ("\1\2\3\4\5\6\7\10", std::string(buf));
242 EXPECT_EQ(9, SafeSPrintf(buf, "%c%c%c%c%c%c%c%c%c",
243 1, 2, 3, 4, 5, 6, 7, 8, 9));
244 EXPECT_EQ("\1\2\3\4\5\6\7\10\11", std::string(buf));
245 EXPECT_EQ(10, SafeSPrintf(buf, "%c%c%c%c%c%c%c%c%c%c",
246 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
247
248 // Repeat all the tests with SafeSNPrintf() instead of SafeSPrintf().
249 EXPECT_EQ("\1\2\3\4\5\6\7\10\11\12", std::string(buf));
250 EXPECT_EQ(1, SafeSNPrintf(buf, 11, "%c", 1));
251 EXPECT_EQ("\1", std::string(buf));
252 EXPECT_EQ(2, SafeSNPrintf(buf, 11, "%c%c", 1, 2));
253 EXPECT_EQ("\1\2", std::string(buf));
254 EXPECT_EQ(3, SafeSNPrintf(buf, 11, "%c%c%c", 1, 2, 3));
255 EXPECT_EQ("\1\2\3", std::string(buf));
256 EXPECT_EQ(4, SafeSNPrintf(buf, 11, "%c%c%c%c", 1, 2, 3, 4));
257 EXPECT_EQ("\1\2\3\4", std::string(buf));
258 EXPECT_EQ(5, SafeSNPrintf(buf, 11, "%c%c%c%c%c", 1, 2, 3, 4, 5));
259 EXPECT_EQ("\1\2\3\4\5", std::string(buf));
260 EXPECT_EQ(6, SafeSNPrintf(buf, 11, "%c%c%c%c%c%c", 1, 2, 3, 4, 5, 6));
261 EXPECT_EQ("\1\2\3\4\5\6", std::string(buf));
262 EXPECT_EQ(7, SafeSNPrintf(buf, 11, "%c%c%c%c%c%c%c", 1, 2, 3, 4, 5, 6, 7));
263 EXPECT_EQ("\1\2\3\4\5\6\7", std::string(buf));
264 EXPECT_EQ(8, SafeSNPrintf(buf, 11, "%c%c%c%c%c%c%c%c",
265 1, 2, 3, 4, 5, 6, 7, 8));
266 EXPECT_EQ("\1\2\3\4\5\6\7\10", std::string(buf));
267 EXPECT_EQ(9, SafeSNPrintf(buf, 11, "%c%c%c%c%c%c%c%c%c",
268 1, 2, 3, 4, 5, 6, 7, 8, 9));
269 EXPECT_EQ("\1\2\3\4\5\6\7\10\11", std::string(buf));
270 EXPECT_EQ(10, SafeSNPrintf(buf, 11, "%c%c%c%c%c%c%c%c%c%c",
271 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
272 EXPECT_EQ("\1\2\3\4\5\6\7\10\11\12", std::string(buf));
273
274 EXPECT_EQ(11, SafeSPrintf(buf, "%c%c%c%c%c%c%c%c%c%c%c",
275 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
276 EXPECT_EQ("\1\2\3\4\5\6\7\10\11\12\13", std::string(buf));
277 EXPECT_EQ(11, SafeSNPrintf(buf, 12, "%c%c%c%c%c%c%c%c%c%c%c",
278 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
279 EXPECT_EQ("\1\2\3\4\5\6\7\10\11\12\13", std::string(buf));
280 }
281
TEST(SafeSPrintfTest,DataTypes)282 TEST(SafeSPrintfTest, DataTypes) {
283 char buf[40];
284
285 // Bytes
286 EXPECT_EQ(1, SafeSPrintf(buf, "%d", (uint8_t)1));
287 EXPECT_EQ("1", std::string(buf));
288 EXPECT_EQ(3, SafeSPrintf(buf, "%d", (uint8_t)-1));
289 EXPECT_EQ("255", std::string(buf));
290 EXPECT_EQ(1, SafeSPrintf(buf, "%d", (int8_t)1));
291 EXPECT_EQ("1", std::string(buf));
292 EXPECT_EQ(2, SafeSPrintf(buf, "%d", (int8_t)-1));
293 EXPECT_EQ("-1", std::string(buf));
294 EXPECT_EQ(4, SafeSPrintf(buf, "%d", (int8_t)-128));
295 EXPECT_EQ("-128", std::string(buf));
296
297 // Half-words
298 EXPECT_EQ(1, SafeSPrintf(buf, "%d", (uint16_t)1));
299 EXPECT_EQ("1", std::string(buf));
300 EXPECT_EQ(5, SafeSPrintf(buf, "%d", (uint16_t)-1));
301 EXPECT_EQ("65535", std::string(buf));
302 EXPECT_EQ(1, SafeSPrintf(buf, "%d", (int16_t)1));
303 EXPECT_EQ("1", std::string(buf));
304 EXPECT_EQ(2, SafeSPrintf(buf, "%d", (int16_t)-1));
305 EXPECT_EQ("-1", std::string(buf));
306 EXPECT_EQ(6, SafeSPrintf(buf, "%d", (int16_t)-32768));
307 EXPECT_EQ("-32768", std::string(buf));
308
309 // Words
310 EXPECT_EQ(1, SafeSPrintf(buf, "%d", (uint32_t)1));
311 EXPECT_EQ("1", std::string(buf));
312 EXPECT_EQ(10, SafeSPrintf(buf, "%d", (uint32_t)-1));
313 EXPECT_EQ("4294967295", std::string(buf));
314 EXPECT_EQ(1, SafeSPrintf(buf, "%d", (int32_t)1));
315 EXPECT_EQ("1", std::string(buf));
316 EXPECT_EQ(2, SafeSPrintf(buf, "%d", (int32_t)-1));
317 EXPECT_EQ("-1", std::string(buf));
318 // Work-around for an limitation of C90
319 EXPECT_EQ(11, SafeSPrintf(buf, "%d", (int32_t)-2147483647-1));
320 EXPECT_EQ("-2147483648", std::string(buf));
321
322 // Quads
323 EXPECT_EQ(1, SafeSPrintf(buf, "%d", (uint64_t)1));
324 EXPECT_EQ("1", std::string(buf));
325 EXPECT_EQ(20, SafeSPrintf(buf, "%d", (uint64_t)-1));
326 EXPECT_EQ("18446744073709551615", std::string(buf));
327 EXPECT_EQ(1, SafeSPrintf(buf, "%d", (int64_t)1));
328 EXPECT_EQ("1", std::string(buf));
329 EXPECT_EQ(2, SafeSPrintf(buf, "%d", (int64_t)-1));
330 EXPECT_EQ("-1", std::string(buf));
331 // Work-around for an limitation of C90
332 EXPECT_EQ(20, SafeSPrintf(buf, "%d", (int64_t)-9223372036854775807LL-1));
333 EXPECT_EQ("-9223372036854775808", std::string(buf));
334
335 // Strings (both const and mutable).
336 EXPECT_EQ(4, SafeSPrintf(buf, "test"));
337 EXPECT_EQ("test", std::string(buf));
338 EXPECT_EQ(4, SafeSPrintf(buf, buf));
339 EXPECT_EQ("test", std::string(buf));
340
341 // Pointer
342 char addr[20];
343 snprintf(addr, sizeof(addr), "0x%llX", (unsigned long long)(uintptr_t)buf);
344 SafeSPrintf(buf, "%p", buf);
345 EXPECT_EQ(std::string(addr), std::string(buf));
346 SafeSPrintf(buf, "%p", (const char *)buf);
347 EXPECT_EQ(std::string(addr), std::string(buf));
348 snprintf(addr, sizeof(addr), "0x%llX",
349 (unsigned long long)(uintptr_t)snprintf);
350 SafeSPrintf(buf, "%p", snprintf);
351 EXPECT_EQ(std::string(addr), std::string(buf));
352
353 // Padding for pointers is a little more complicated because of the "0x"
354 // prefix. Padding with '0' zeros is relatively straight-forward, but
355 // padding with ' ' spaces requires more effort.
356 snprintf(addr, sizeof(addr), "0x%017llX", (unsigned long long)(uintptr_t)buf);
357 SafeSPrintf(buf, "%019p", buf);
358 EXPECT_EQ(std::string(addr), std::string(buf));
359 snprintf(addr, sizeof(addr), "0x%llX", (unsigned long long)(uintptr_t)buf);
360 memset(addr, ' ',
361 (char*)memmove(addr + sizeof(addr) - strlen(addr) - 1,
362 addr, strlen(addr)+1) - addr);
363 SafeSPrintf(buf, "%19p", buf);
364 EXPECT_EQ(std::string(addr), std::string(buf));
365 }
366
367 namespace {
PrintLongString(char * buf,size_t sz)368 void PrintLongString(char* buf, size_t sz) {
369 // Output a reasonably complex expression into a limited-size buffer.
370 // At least one byte is available for writing the NUL character.
371 CHECK_GT(sz, static_cast<size_t>(0));
372
373 // Allocate slightly more space, so that we can verify that SafeSPrintf()
374 // never writes past the end of the buffer.
375 base::FixedArray<char> tmp(sz + 2);
376 tmp.fill('X');
377
378 // Use SafeSPrintf() to output a complex list of arguments:
379 // - test padding and truncating %c single characters.
380 // - test truncating %s simple strings.
381 // - test mismatching arguments and truncating (for %d != %s).
382 // - test zero-padding and truncating %x hexadecimal numbers.
383 // - test outputting and truncating %d MININT.
384 // - test outputting and truncating %p arbitrary pointer values.
385 // - test outputting, padding and truncating NULL-pointer %s strings.
386 char* out = tmp.data();
387 size_t out_sz = sz;
388 size_t len;
389 for (std::unique_ptr<char[]> perfect_buf;;) {
390 size_t needed =
391 SafeSNPrintf(out, out_sz,
392 #if defined(NDEBUG)
393 "A%2cong %s: %d %010X %d %p%7s", 'l', "string", "",
394 #else
395 "A%2cong %s: %%d %010X %d %p%7s", 'l', "string",
396 #endif
397 0xDEADBEEF, std::numeric_limits<intptr_t>::min(),
398 PrintLongString, static_cast<char*>(nullptr)) +
399 1;
400
401 // Various sanity checks:
402 // The numbered of characters needed to print the full string should always
403 // be bigger or equal to the bytes that have actually been output.
404 len = strlen(tmp.data());
405 CHECK_GE(needed, len+1);
406
407 // The number of characters output should always fit into the buffer that
408 // was passed into SafeSPrintf().
409 CHECK_LT(len, out_sz);
410
411 // The output is always terminated with a NUL byte (actually, this test is
412 // always going to pass, as strlen() already verified this)
413 EXPECT_FALSE(tmp[len]);
414
415 // ASAN can check that we are not overwriting buffers, iff we make sure the
416 // buffer is exactly the size that we are expecting to be written. After
417 // running SafeSNPrintf() the first time, it is possible to compute the
418 // correct buffer size for this test. So, allocate a second buffer and run
419 // the exact same SafeSNPrintf() command again.
420 if (!perfect_buf.get()) {
421 out_sz = std::min(needed, sz);
422 out = new char[out_sz];
423 perfect_buf.reset(out);
424 } else {
425 break;
426 }
427 }
428
429 // All trailing bytes are unchanged.
430 for (size_t i = len+1; i < sz+2; ++i)
431 EXPECT_EQ('X', tmp[i]);
432
433 // The text that was generated by SafeSPrintf() should always match the
434 // equivalent text generated by snprintf(). Please note that the format
435 // string for snprintf() is not complicated, as it does not have the
436 // benefit of getting type information from the C++ compiler.
437 //
438 // N.B.: It would be so much cleaner to use snprintf(). But unfortunately,
439 // Visual Studio doesn't support this function, and the work-arounds
440 // are all really awkward.
441 char ref[256];
442 CHECK_LE(sz, sizeof(ref));
443 snprintf(ref, sizeof(ref), "A long string: %%d 00DEADBEEF %lld 0x%llX <NULL>",
444 static_cast<long long>(std::numeric_limits<intptr_t>::min()),
445 static_cast<unsigned long long>(
446 reinterpret_cast<uintptr_t>(PrintLongString)));
447 ref[sz-1] = '\000';
448
449 #if defined(NDEBUG)
450 const size_t kSSizeMax = std::numeric_limits<ssize_t>::max();
451 #else
452 const size_t kSSizeMax = internal::GetSafeSPrintfSSizeMaxForTest();
453 #endif
454
455 // Compare the output from SafeSPrintf() to the one from snprintf().
456 EXPECT_EQ(std::string(ref).substr(0, kSSizeMax - 1), std::string(tmp.data()));
457
458 // We allocated a slightly larger buffer, so that we could perform some
459 // extra sanity checks. Now that the tests have all passed, we copy the
460 // data to the output buffer that the caller provided.
461 memcpy(buf, tmp.data(), len + 1);
462 }
463
464 #if !defined(NDEBUG)
465 class ScopedSafeSPrintfSSizeMaxSetter {
466 public:
ScopedSafeSPrintfSSizeMaxSetter(size_t sz)467 ScopedSafeSPrintfSSizeMaxSetter(size_t sz) {
468 old_ssize_max_ = internal::GetSafeSPrintfSSizeMaxForTest();
469 internal::SetSafeSPrintfSSizeMaxForTest(sz);
470 }
471
472 ScopedSafeSPrintfSSizeMaxSetter(const ScopedSafeSPrintfSSizeMaxSetter&) =
473 delete;
474 ScopedSafeSPrintfSSizeMaxSetter& operator=(
475 const ScopedSafeSPrintfSSizeMaxSetter&) = delete;
476
~ScopedSafeSPrintfSSizeMaxSetter()477 ~ScopedSafeSPrintfSSizeMaxSetter() {
478 internal::SetSafeSPrintfSSizeMaxForTest(old_ssize_max_);
479 }
480
481 private:
482 size_t old_ssize_max_;
483 };
484 #endif
485
486 } // anonymous namespace
487
TEST(SafeSPrintfTest,Truncation)488 TEST(SafeSPrintfTest, Truncation) {
489 // We use PrintLongString() to print a complex long string and then
490 // truncate to all possible lengths. This ends up exercising a lot of
491 // different code paths in SafeSPrintf() and IToASCII(), as truncation can
492 // happen in a lot of different states.
493 char ref[256];
494 PrintLongString(ref, sizeof(ref));
495 for (size_t i = strlen(ref)+1; i; --i) {
496 char buf[sizeof(ref)];
497 PrintLongString(buf, i);
498 EXPECT_EQ(std::string(ref, i - 1), std::string(buf));
499 }
500
501 // When compiling in debug mode, we have the ability to fake a small
502 // upper limit for the maximum value that can be stored in an ssize_t.
503 // SafeSPrintf() uses this upper limit to determine how many bytes it will
504 // write to the buffer, even if the caller claimed a bigger buffer size.
505 // Repeat the truncation test and verify that this other code path in
506 // SafeSPrintf() works correctly, too.
507 #if !defined(NDEBUG)
508 for (size_t i = strlen(ref)+1; i > 1; --i) {
509 ScopedSafeSPrintfSSizeMaxSetter ssize_max_setter(i);
510 char buf[sizeof(ref)];
511 PrintLongString(buf, sizeof(buf));
512 EXPECT_EQ(std::string(ref, i - 1), std::string(buf));
513 }
514
515 // kSSizeMax is also used to constrain the maximum amount of padding, before
516 // SafeSPrintf() detects an error in the format string.
517 ScopedSafeSPrintfSSizeMaxSetter ssize_max_setter(100);
518 char buf[256];
519 EXPECT_EQ(99, SafeSPrintf(buf, "%99c", ' '));
520 EXPECT_EQ(std::string(99, ' '), std::string(buf));
521 *buf = '\000';
522 #if defined(ALLOW_DEATH_TEST)
523 EXPECT_DEATH(SafeSPrintf(buf, "%100c", ' '), "padding <= max_padding");
524 #endif
525 EXPECT_EQ(0, *buf);
526 #endif
527 }
528
TEST(SafeSPrintfTest,Padding)529 TEST(SafeSPrintfTest, Padding) {
530 char buf[40], fmt[40];
531
532 // Chars %c
533 EXPECT_EQ(1, SafeSPrintf(buf, "%c", 'A'));
534 EXPECT_EQ("A", std::string(buf));
535 EXPECT_EQ(2, SafeSPrintf(buf, "%2c", 'A'));
536 EXPECT_EQ(" A", std::string(buf));
537 EXPECT_EQ(2, SafeSPrintf(buf, "%02c", 'A'));
538 EXPECT_EQ(" A", std::string(buf));
539 EXPECT_EQ(4, SafeSPrintf(buf, "%-2c", 'A'));
540 EXPECT_EQ("%-2c", std::string(buf));
541 SafeSPrintf(fmt, "%%%dc", std::numeric_limits<ssize_t>::max() - 1);
542 EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1, SafeSPrintf(buf, fmt, 'A'));
543 SafeSPrintf(fmt, "%%%dc",
544 static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
545 #if defined(NDEBUG)
546 EXPECT_EQ(2, SafeSPrintf(buf, fmt, 'A'));
547 EXPECT_EQ("%c", std::string(buf));
548 #elif defined(ALLOW_DEATH_TEST)
549 EXPECT_DEATH(SafeSPrintf(buf, fmt, 'A'), "padding <= max_padding");
550 #endif
551
552 // Octal %o
553 EXPECT_EQ(1, SafeSPrintf(buf, "%o", 1));
554 EXPECT_EQ("1", std::string(buf));
555 EXPECT_EQ(2, SafeSPrintf(buf, "%2o", 1));
556 EXPECT_EQ(" 1", std::string(buf));
557 EXPECT_EQ(2, SafeSPrintf(buf, "%02o", 1));
558 EXPECT_EQ("01", std::string(buf));
559 EXPECT_EQ(12, SafeSPrintf(buf, "%12o", -1));
560 EXPECT_EQ(" 37777777777", std::string(buf));
561 EXPECT_EQ(12, SafeSPrintf(buf, "%012o", -1));
562 EXPECT_EQ("037777777777", std::string(buf));
563 EXPECT_EQ(23, SafeSPrintf(buf, "%23o", -1LL));
564 EXPECT_EQ(" 1777777777777777777777", std::string(buf));
565 EXPECT_EQ(23, SafeSPrintf(buf, "%023o", -1LL));
566 EXPECT_EQ("01777777777777777777777", std::string(buf));
567 EXPECT_EQ(3, SafeSPrintf(buf, "%2o", 0111));
568 EXPECT_EQ("111", std::string(buf));
569 EXPECT_EQ(4, SafeSPrintf(buf, "%-2o", 1));
570 EXPECT_EQ("%-2o", std::string(buf));
571 SafeSPrintf(fmt, "%%%do", std::numeric_limits<ssize_t>::max()-1);
572 EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
573 SafeSNPrintf(buf, 4, fmt, 1));
574 EXPECT_EQ(" ", std::string(buf));
575 SafeSPrintf(fmt, "%%0%do", std::numeric_limits<ssize_t>::max()-1);
576 EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
577 SafeSNPrintf(buf, 4, fmt, 1));
578 EXPECT_EQ("000", std::string(buf));
579 SafeSPrintf(fmt, "%%%do",
580 static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
581 #if defined(NDEBUG)
582 EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
583 EXPECT_EQ("%o", std::string(buf));
584 #elif defined(ALLOW_DEATH_TEST)
585 EXPECT_DEATH(SafeSPrintf(buf, fmt, 1), "padding <= max_padding");
586 #endif
587
588 // Decimals %d
589 EXPECT_EQ(1, SafeSPrintf(buf, "%d", 1));
590 EXPECT_EQ("1", std::string(buf));
591 EXPECT_EQ(2, SafeSPrintf(buf, "%2d", 1));
592 EXPECT_EQ(" 1", std::string(buf));
593 EXPECT_EQ(2, SafeSPrintf(buf, "%02d", 1));
594 EXPECT_EQ("01", std::string(buf));
595 EXPECT_EQ(3, SafeSPrintf(buf, "%3d", -1));
596 EXPECT_EQ(" -1", std::string(buf));
597 EXPECT_EQ(3, SafeSPrintf(buf, "%03d", -1));
598 EXPECT_EQ("-01", std::string(buf));
599 EXPECT_EQ(3, SafeSPrintf(buf, "%2d", 111));
600 EXPECT_EQ("111", std::string(buf));
601 EXPECT_EQ(4, SafeSPrintf(buf, "%2d", -111));
602 EXPECT_EQ("-111", std::string(buf));
603 EXPECT_EQ(4, SafeSPrintf(buf, "%-2d", 1));
604 EXPECT_EQ("%-2d", std::string(buf));
605 SafeSPrintf(fmt, "%%%dd", std::numeric_limits<ssize_t>::max()-1);
606 EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
607 SafeSNPrintf(buf, 4, fmt, 1));
608 EXPECT_EQ(" ", std::string(buf));
609 SafeSPrintf(fmt, "%%0%dd", std::numeric_limits<ssize_t>::max()-1);
610 EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
611 SafeSNPrintf(buf, 4, fmt, 1));
612 EXPECT_EQ("000", std::string(buf));
613 SafeSPrintf(fmt, "%%%dd",
614 static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
615 #if defined(NDEBUG)
616 EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
617 EXPECT_EQ("%d", std::string(buf));
618 #elif defined(ALLOW_DEATH_TEST)
619 EXPECT_DEATH(SafeSPrintf(buf, fmt, 1), "padding <= max_padding");
620 #endif
621
622 // Hex %X
623 EXPECT_EQ(1, SafeSPrintf(buf, "%X", 1));
624 EXPECT_EQ("1", std::string(buf));
625 EXPECT_EQ(2, SafeSPrintf(buf, "%2X", 1));
626 EXPECT_EQ(" 1", std::string(buf));
627 EXPECT_EQ(2, SafeSPrintf(buf, "%02X", 1));
628 EXPECT_EQ("01", std::string(buf));
629 EXPECT_EQ(9, SafeSPrintf(buf, "%9X", -1));
630 EXPECT_EQ(" FFFFFFFF", std::string(buf));
631 EXPECT_EQ(9, SafeSPrintf(buf, "%09X", -1));
632 EXPECT_EQ("0FFFFFFFF", std::string(buf));
633 EXPECT_EQ(17, SafeSPrintf(buf, "%17X", -1LL));
634 EXPECT_EQ(" FFFFFFFFFFFFFFFF", std::string(buf));
635 EXPECT_EQ(17, SafeSPrintf(buf, "%017X", -1LL));
636 EXPECT_EQ("0FFFFFFFFFFFFFFFF", std::string(buf));
637 EXPECT_EQ(3, SafeSPrintf(buf, "%2X", 0x111));
638 EXPECT_EQ("111", std::string(buf));
639 EXPECT_EQ(4, SafeSPrintf(buf, "%-2X", 1));
640 EXPECT_EQ("%-2X", std::string(buf));
641 SafeSPrintf(fmt, "%%%dX", std::numeric_limits<ssize_t>::max()-1);
642 EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
643 SafeSNPrintf(buf, 4, fmt, 1));
644 EXPECT_EQ(" ", std::string(buf));
645 SafeSPrintf(fmt, "%%0%dX", std::numeric_limits<ssize_t>::max()-1);
646 EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
647 SafeSNPrintf(buf, 4, fmt, 1));
648 EXPECT_EQ("000", std::string(buf));
649 SafeSPrintf(fmt, "%%%dX",
650 static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
651 #if defined(NDEBUG)
652 EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
653 EXPECT_EQ("%X", std::string(buf));
654 #elif defined(ALLOW_DEATH_TEST)
655 EXPECT_DEATH(SafeSPrintf(buf, fmt, 1), "padding <= max_padding");
656 #endif
657
658 // Pointer %p
659 EXPECT_EQ(3, SafeSPrintf(buf, "%p", (void*)1));
660 EXPECT_EQ("0x1", std::string(buf));
661 EXPECT_EQ(4, SafeSPrintf(buf, "%4p", (void*)1));
662 EXPECT_EQ(" 0x1", std::string(buf));
663 EXPECT_EQ(4, SafeSPrintf(buf, "%04p", (void*)1));
664 EXPECT_EQ("0x01", std::string(buf));
665 EXPECT_EQ(5, SafeSPrintf(buf, "%4p", (void*)0x111));
666 EXPECT_EQ("0x111", std::string(buf));
667 EXPECT_EQ(4, SafeSPrintf(buf, "%-2p", (void*)1));
668 EXPECT_EQ("%-2p", std::string(buf));
669 SafeSPrintf(fmt, "%%%dp", std::numeric_limits<ssize_t>::max()-1);
670 EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
671 SafeSNPrintf(buf, 4, fmt, (void*)1));
672 EXPECT_EQ(" ", std::string(buf));
673 SafeSPrintf(fmt, "%%0%dp", std::numeric_limits<ssize_t>::max()-1);
674 EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
675 SafeSNPrintf(buf, 4, fmt, (void*)1));
676 EXPECT_EQ("0x0", std::string(buf));
677 SafeSPrintf(fmt, "%%%dp",
678 static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
679 #if defined(NDEBUG)
680 EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
681 EXPECT_EQ("%p", std::string(buf));
682 #elif defined(ALLOW_DEATH_TEST)
683 EXPECT_DEATH(SafeSPrintf(buf, fmt, 1), "padding <= max_padding");
684 #endif
685
686 // String
687 EXPECT_EQ(1, SafeSPrintf(buf, "%s", "A"));
688 EXPECT_EQ("A", std::string(buf));
689 EXPECT_EQ(2, SafeSPrintf(buf, "%2s", "A"));
690 EXPECT_EQ(" A", std::string(buf));
691 EXPECT_EQ(2, SafeSPrintf(buf, "%02s", "A"));
692 EXPECT_EQ(" A", std::string(buf));
693 EXPECT_EQ(3, SafeSPrintf(buf, "%2s", "AAA"));
694 EXPECT_EQ("AAA", std::string(buf));
695 EXPECT_EQ(4, SafeSPrintf(buf, "%-2s", "A"));
696 EXPECT_EQ("%-2s", std::string(buf));
697 SafeSPrintf(fmt, "%%%ds", std::numeric_limits<ssize_t>::max()-1);
698 EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
699 SafeSNPrintf(buf, 4, fmt, "A"));
700 EXPECT_EQ(" ", std::string(buf));
701 SafeSPrintf(fmt, "%%0%ds", std::numeric_limits<ssize_t>::max()-1);
702 EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
703 SafeSNPrintf(buf, 4, fmt, "A"));
704 EXPECT_EQ(" ", std::string(buf));
705 SafeSPrintf(fmt, "%%%ds",
706 static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
707 #if defined(NDEBUG)
708 EXPECT_EQ(2, SafeSPrintf(buf, fmt, "A"));
709 EXPECT_EQ("%s", std::string(buf));
710 #elif defined(ALLOW_DEATH_TEST)
711 EXPECT_DEATH(SafeSPrintf(buf, fmt, "A"), "padding <= max_padding");
712 #endif
713 }
714
TEST(SafeSPrintfTest,EmbeddedNul)715 TEST(SafeSPrintfTest, EmbeddedNul) {
716 char buf[] = { 'X', 'X', 'X', 'X' };
717 EXPECT_EQ(2, SafeSPrintf(buf, "%3c", 0));
718 EXPECT_EQ(' ', buf[0]);
719 EXPECT_EQ(' ', buf[1]);
720 EXPECT_EQ(0, buf[2]);
721 EXPECT_EQ('X', buf[3]);
722
723 // Check handling of a NUL format character. N.B. this takes two different
724 // code paths depending on whether we are actually passing arguments. If
725 // we don't have any arguments, we are running in the fast-path code, that
726 // looks (almost) like a strncpy().
727 #if defined(NDEBUG)
728 EXPECT_EQ(2, SafeSPrintf(buf, "%%%"));
729 EXPECT_EQ("%%", std::string(buf));
730 EXPECT_EQ(2, SafeSPrintf(buf, "%%%", 0));
731 EXPECT_EQ("%%", std::string(buf));
732 #elif defined(ALLOW_DEATH_TEST)
733 EXPECT_DEATH(SafeSPrintf(buf, "%%%"), "src.1. == '%'");
734 EXPECT_DEATH(SafeSPrintf(buf, "%%%", 0), "ch");
735 #endif
736 }
737
TEST(SafeSPrintfTest,EmitNULL)738 TEST(SafeSPrintfTest, EmitNULL) {
739 char buf[40];
740 #if defined(__GNUC__)
741 #pragma GCC diagnostic push
742 #pragma GCC diagnostic ignored "-Wconversion-null"
743 #endif
744 EXPECT_EQ(1, SafeSPrintf(buf, "%d", NULL));
745 EXPECT_EQ("0", std::string(buf));
746 EXPECT_EQ(3, SafeSPrintf(buf, "%p", NULL));
747 EXPECT_EQ("0x0", std::string(buf));
748 EXPECT_EQ(6, SafeSPrintf(buf, "%s", NULL));
749 EXPECT_EQ("<NULL>", std::string(buf));
750 #if defined(__GCC__)
751 #pragma GCC diagnostic pop
752 #endif
753 }
754
TEST(SafeSPrintfTest,PointerSize)755 TEST(SafeSPrintfTest, PointerSize) {
756 // The internal data representation is a 64bit value, independent of the
757 // native word size. We want to perform sign-extension for signed integers,
758 // but we want to avoid doing so for pointer types. This could be a
759 // problem on systems, where pointers are only 32bit. This tests verifies
760 // that there is no such problem.
761 char *str = reinterpret_cast<char *>(0x80000000u);
762 void *ptr = str;
763 char buf[40];
764 EXPECT_EQ(10, SafeSPrintf(buf, "%p", str));
765 EXPECT_EQ("0x80000000", std::string(buf));
766 EXPECT_EQ(10, SafeSPrintf(buf, "%p", ptr));
767 EXPECT_EQ("0x80000000", std::string(buf));
768 }
769
770 } // namespace strings
771 } // namespace base
772