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