Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(547)

Side by Side Diff: base/strings/safe_string_printf_unittest.cc

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

Powered by Google App Engine
This is Rietveld 408576698