safe_sprintf_unittest.cc 30 KB

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