gtest-printers.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. // Copyright 2007, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // Google Test - The Google C++ Testing and Mocking Framework
  30. //
  31. // This file implements a universal value printer that can print a
  32. // value of any type T:
  33. //
  34. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  35. //
  36. // It uses the << operator when possible, and prints the bytes in the
  37. // object otherwise. A user can override its behavior for a class
  38. // type Foo by defining either operator<<(::std::ostream&, const Foo&)
  39. // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
  40. // defines Foo.
  41. #include "gtest/gtest-printers.h"
  42. #include <stdio.h>
  43. #include <cctype>
  44. #include <cstdint>
  45. #include <cwchar>
  46. #include <ostream> // NOLINT
  47. #include <string>
  48. #include <type_traits>
  49. #include "gtest/internal/gtest-port.h"
  50. #include "src/gtest-internal-inl.h"
  51. namespace testing {
  52. namespace {
  53. using ::std::ostream;
  54. // Prints a segment of bytes in the given object.
  55. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  56. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  57. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  58. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  59. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
  60. size_t count, ostream* os) {
  61. char text[5] = "";
  62. for (size_t i = 0; i != count; i++) {
  63. const size_t j = start + i;
  64. if (i != 0) {
  65. // Organizes the bytes into groups of 2 for easy parsing by
  66. // human.
  67. if ((j % 2) == 0)
  68. *os << ' ';
  69. else
  70. *os << '-';
  71. }
  72. GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
  73. *os << text;
  74. }
  75. }
  76. // Prints the bytes in the given value to the given ostream.
  77. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
  78. ostream* os) {
  79. // Tells the user how big the object is.
  80. *os << count << "-byte object <";
  81. const size_t kThreshold = 132;
  82. const size_t kChunkSize = 64;
  83. // If the object size is bigger than kThreshold, we'll have to omit
  84. // some details by printing only the first and the last kChunkSize
  85. // bytes.
  86. if (count < kThreshold) {
  87. PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  88. } else {
  89. PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
  90. *os << " ... ";
  91. // Rounds up to 2-byte boundary.
  92. const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2;
  93. PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  94. }
  95. *os << ">";
  96. }
  97. // Helpers for widening a character to char32_t. Since the standard does not
  98. // specify if char / wchar_t is signed or unsigned, it is important to first
  99. // convert it to the unsigned type of the same width before widening it to
  100. // char32_t.
  101. template <typename CharType>
  102. char32_t ToChar32(CharType in) {
  103. return static_cast<char32_t>(
  104. static_cast<typename std::make_unsigned<CharType>::type>(in));
  105. }
  106. } // namespace
  107. namespace internal {
  108. // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
  109. // given object. The delegation simplifies the implementation, which
  110. // uses the << operator and thus is easier done outside of the
  111. // ::testing::internal namespace, which contains a << operator that
  112. // sometimes conflicts with the one in STL.
  113. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
  114. ostream* os) {
  115. PrintBytesInObjectToImpl(obj_bytes, count, os);
  116. }
  117. // Depending on the value of a char (or wchar_t), we print it in one
  118. // of three formats:
  119. // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
  120. // - as a hexadecimal escape sequence (e.g. '\x7F'), or
  121. // - as a special escape sequence (e.g. '\r', '\n').
  122. enum CharFormat { kAsIs, kHexEscape, kSpecialEscape };
  123. // Returns true if c is a printable ASCII character. We test the
  124. // value of c directly instead of calling isprint(), which is buggy on
  125. // Windows Mobile.
  126. inline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }
  127. // Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a
  128. // character literal without the quotes, escaping it when necessary; returns how
  129. // c was formatted.
  130. template <typename Char>
  131. static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
  132. const char32_t u_c = ToChar32(c);
  133. switch (u_c) {
  134. case L'\0':
  135. *os << "\\0";
  136. break;
  137. case L'\'':
  138. *os << "\\'";
  139. break;
  140. case L'\\':
  141. *os << "\\\\";
  142. break;
  143. case L'\a':
  144. *os << "\\a";
  145. break;
  146. case L'\b':
  147. *os << "\\b";
  148. break;
  149. case L'\f':
  150. *os << "\\f";
  151. break;
  152. case L'\n':
  153. *os << "\\n";
  154. break;
  155. case L'\r':
  156. *os << "\\r";
  157. break;
  158. case L'\t':
  159. *os << "\\t";
  160. break;
  161. case L'\v':
  162. *os << "\\v";
  163. break;
  164. default:
  165. if (IsPrintableAscii(u_c)) {
  166. *os << static_cast<char>(c);
  167. return kAsIs;
  168. } else {
  169. ostream::fmtflags flags = os->flags();
  170. *os << "\\x" << std::hex << std::uppercase << static_cast<int>(u_c);
  171. os->flags(flags);
  172. return kHexEscape;
  173. }
  174. }
  175. return kSpecialEscape;
  176. }
  177. // Prints a char32_t c as if it's part of a string literal, escaping it when
  178. // necessary; returns how c was formatted.
  179. static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
  180. switch (c) {
  181. case L'\'':
  182. *os << "'";
  183. return kAsIs;
  184. case L'"':
  185. *os << "\\\"";
  186. return kSpecialEscape;
  187. default:
  188. return PrintAsCharLiteralTo(c, os);
  189. }
  190. }
  191. static const char* GetCharWidthPrefix(char) { return ""; }
  192. static const char* GetCharWidthPrefix(signed char) { return ""; }
  193. static const char* GetCharWidthPrefix(unsigned char) { return ""; }
  194. #ifdef __cpp_char8_t
  195. static const char* GetCharWidthPrefix(char8_t) { return "u8"; }
  196. #endif
  197. static const char* GetCharWidthPrefix(char16_t) { return "u"; }
  198. static const char* GetCharWidthPrefix(char32_t) { return "U"; }
  199. static const char* GetCharWidthPrefix(wchar_t) { return "L"; }
  200. // Prints a char c as if it's part of a string literal, escaping it when
  201. // necessary; returns how c was formatted.
  202. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
  203. return PrintAsStringLiteralTo(ToChar32(c), os);
  204. }
  205. #ifdef __cpp_char8_t
  206. static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
  207. return PrintAsStringLiteralTo(ToChar32(c), os);
  208. }
  209. #endif
  210. static CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {
  211. return PrintAsStringLiteralTo(ToChar32(c), os);
  212. }
  213. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
  214. return PrintAsStringLiteralTo(ToChar32(c), os);
  215. }
  216. // Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)
  217. // and its code. '\0' is printed as "'\\0'", other unprintable characters are
  218. // also properly escaped using the standard C++ escape sequence.
  219. template <typename Char>
  220. void PrintCharAndCodeTo(Char c, ostream* os) {
  221. // First, print c as a literal in the most readable form we can find.
  222. *os << GetCharWidthPrefix(c) << "'";
  223. const CharFormat format = PrintAsCharLiteralTo(c, os);
  224. *os << "'";
  225. // To aid user debugging, we also print c's code in decimal, unless
  226. // it's 0 (in which case c was printed as '\\0', making the code
  227. // obvious).
  228. if (c == 0) return;
  229. *os << " (" << static_cast<int>(c);
  230. // For more convenience, we print c's code again in hexadecimal,
  231. // unless c was already printed in the form '\x##' or the code is in
  232. // [1, 9].
  233. if (format == kHexEscape || (1 <= c && c <= 9)) {
  234. // Do nothing.
  235. } else {
  236. *os << ", 0x" << String::FormatHexInt(static_cast<int>(c));
  237. }
  238. *os << ")";
  239. }
  240. void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
  241. void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
  242. // Prints a wchar_t as a symbol if it is printable or as its internal
  243. // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
  244. void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }
  245. // TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.
  246. void PrintTo(char32_t c, ::std::ostream* os) {
  247. *os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4)
  248. << static_cast<uint32_t>(c);
  249. }
  250. // gcc/clang __{u,}int128_t
  251. #if defined(__SIZEOF_INT128__)
  252. void PrintTo(__uint128_t v, ::std::ostream* os) {
  253. if (v == 0) {
  254. *os << "0";
  255. return;
  256. }
  257. // Buffer large enough for ceil(log10(2^128))==39 and the null terminator
  258. char buf[40];
  259. char* p = buf + sizeof(buf);
  260. // Some configurations have a __uint128_t, but no support for built in
  261. // division. Do manual long division instead.
  262. uint64_t high = static_cast<uint64_t>(v >> 64);
  263. uint64_t low = static_cast<uint64_t>(v);
  264. *--p = 0;
  265. while (high != 0 || low != 0) {
  266. uint64_t high_mod = high % 10;
  267. high = high / 10;
  268. // This is the long division algorithm specialized for a divisor of 10 and
  269. // only two elements.
  270. // Notable values:
  271. // 2^64 / 10 == 1844674407370955161
  272. // 2^64 % 10 == 6
  273. const uint64_t carry = 6 * high_mod + low % 10;
  274. low = low / 10 + high_mod * 1844674407370955161 + carry / 10;
  275. char digit = static_cast<char>(carry % 10);
  276. *--p = '0' + digit;
  277. }
  278. *os << p;
  279. }
  280. void PrintTo(__int128_t v, ::std::ostream* os) {
  281. __uint128_t uv = static_cast<__uint128_t>(v);
  282. if (v < 0) {
  283. *os << "-";
  284. uv = -uv;
  285. }
  286. PrintTo(uv, os);
  287. }
  288. #endif // __SIZEOF_INT128__
  289. // Prints the given array of characters to the ostream. CharType must be either
  290. // char, char8_t, char16_t, char32_t, or wchar_t.
  291. // The array starts at begin, the length is len, it may include '\0' characters
  292. // and may not be NUL-terminated.
  293. template <typename CharType>
  294. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  295. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  296. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static CharFormat
  297. PrintCharsAsStringTo(const CharType* begin, size_t len, ostream* os) {
  298. const char* const quote_prefix = GetCharWidthPrefix(*begin);
  299. *os << quote_prefix << "\"";
  300. bool is_previous_hex = false;
  301. CharFormat print_format = kAsIs;
  302. for (size_t index = 0; index < len; ++index) {
  303. const CharType cur = begin[index];
  304. if (is_previous_hex && IsXDigit(cur)) {
  305. // Previous character is of '\x..' form and this character can be
  306. // interpreted as another hexadecimal digit in its number. Break string to
  307. // disambiguate.
  308. *os << "\" " << quote_prefix << "\"";
  309. }
  310. is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
  311. // Remember if any characters required hex escaping.
  312. if (is_previous_hex) {
  313. print_format = kHexEscape;
  314. }
  315. }
  316. *os << "\"";
  317. return print_format;
  318. }
  319. // Prints a (const) char/wchar_t array of 'len' elements, starting at address
  320. // 'begin'. CharType must be either char or wchar_t.
  321. template <typename CharType>
  322. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  323. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  324. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void
  325. UniversalPrintCharArray(const CharType* begin, size_t len,
  326. ostream* os) {
  327. // The code
  328. // const char kFoo[] = "foo";
  329. // generates an array of 4, not 3, elements, with the last one being '\0'.
  330. //
  331. // Therefore when printing a char array, we don't print the last element if
  332. // it's '\0', such that the output matches the string literal as it's
  333. // written in the source code.
  334. if (len > 0 && begin[len - 1] == '\0') {
  335. PrintCharsAsStringTo(begin, len - 1, os);
  336. return;
  337. }
  338. // If, however, the last element in the array is not '\0', e.g.
  339. // const char kFoo[] = { 'f', 'o', 'o' };
  340. // we must print the entire array. We also print a message to indicate
  341. // that the array is not NUL-terminated.
  342. PrintCharsAsStringTo(begin, len, os);
  343. *os << " (no terminating NUL)";
  344. }
  345. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
  346. void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  347. UniversalPrintCharArray(begin, len, os);
  348. }
  349. #ifdef __cpp_char8_t
  350. // Prints a (const) char8_t array of 'len' elements, starting at address
  351. // 'begin'.
  352. void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
  353. UniversalPrintCharArray(begin, len, os);
  354. }
  355. #endif
  356. // Prints a (const) char16_t array of 'len' elements, starting at address
  357. // 'begin'.
  358. void UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {
  359. UniversalPrintCharArray(begin, len, os);
  360. }
  361. // Prints a (const) char32_t array of 'len' elements, starting at address
  362. // 'begin'.
  363. void UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {
  364. UniversalPrintCharArray(begin, len, os);
  365. }
  366. // Prints a (const) wchar_t array of 'len' elements, starting at address
  367. // 'begin'.
  368. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
  369. UniversalPrintCharArray(begin, len, os);
  370. }
  371. namespace {
  372. // Prints a null-terminated C-style string to the ostream.
  373. template <typename Char>
  374. void PrintCStringTo(const Char* s, ostream* os) {
  375. if (s == nullptr) {
  376. *os << "NULL";
  377. } else {
  378. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  379. PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os);
  380. }
  381. }
  382. } // anonymous namespace
  383. void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }
  384. #ifdef __cpp_char8_t
  385. void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
  386. #endif
  387. void PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }
  388. void PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }
  389. // MSVC compiler can be configured to define whar_t as a typedef
  390. // of unsigned short. Defining an overload for const wchar_t* in that case
  391. // would cause pointers to unsigned shorts be printed as wide strings,
  392. // possibly accessing more memory than intended and causing invalid
  393. // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
  394. // wchar_t is implemented as a native type.
  395. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  396. // Prints the given wide C string to the ostream.
  397. void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
  398. #endif // wchar_t is native
  399. namespace {
  400. bool ContainsUnprintableControlCodes(const char* str, size_t length) {
  401. const unsigned char* s = reinterpret_cast<const unsigned char*>(str);
  402. for (size_t i = 0; i < length; i++) {
  403. unsigned char ch = *s++;
  404. if (std::iscntrl(ch)) {
  405. switch (ch) {
  406. case '\t':
  407. case '\n':
  408. case '\r':
  409. break;
  410. default:
  411. return true;
  412. }
  413. }
  414. }
  415. return false;
  416. }
  417. bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t <= 0xbf; }
  418. bool IsValidUTF8(const char* str, size_t length) {
  419. const unsigned char* s = reinterpret_cast<const unsigned char*>(str);
  420. for (size_t i = 0; i < length;) {
  421. unsigned char lead = s[i++];
  422. if (lead <= 0x7f) {
  423. continue; // single-byte character (ASCII) 0..7F
  424. }
  425. if (lead < 0xc2) {
  426. return false; // trail byte or non-shortest form
  427. } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
  428. ++i; // 2-byte character
  429. } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
  430. IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
  431. // check for non-shortest form and surrogate
  432. (lead != 0xe0 || s[i] >= 0xa0) &&
  433. (lead != 0xed || s[i] < 0xa0)) {
  434. i += 2; // 3-byte character
  435. } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
  436. IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
  437. IsUTF8TrailByte(s[i + 2]) &&
  438. // check for non-shortest form
  439. (lead != 0xf0 || s[i] >= 0x90) &&
  440. (lead != 0xf4 || s[i] < 0x90)) {
  441. i += 3; // 4-byte character
  442. } else {
  443. return false;
  444. }
  445. }
  446. return true;
  447. }
  448. void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
  449. if (!ContainsUnprintableControlCodes(str, length) &&
  450. IsValidUTF8(str, length)) {
  451. *os << "\n As Text: \"" << str << "\"";
  452. }
  453. }
  454. } // anonymous namespace
  455. void PrintStringTo(const ::std::string& s, ostream* os) {
  456. if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
  457. if (GTEST_FLAG_GET(print_utf8)) {
  458. ConditionalPrintAsText(s.data(), s.size(), os);
  459. }
  460. }
  461. }
  462. #ifdef __cpp_char8_t
  463. void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
  464. PrintCharsAsStringTo(s.data(), s.size(), os);
  465. }
  466. #endif
  467. void PrintU16StringTo(const ::std::u16string& s, ostream* os) {
  468. PrintCharsAsStringTo(s.data(), s.size(), os);
  469. }
  470. void PrintU32StringTo(const ::std::u32string& s, ostream* os) {
  471. PrintCharsAsStringTo(s.data(), s.size(), os);
  472. }
  473. #if GTEST_HAS_STD_WSTRING
  474. void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  475. PrintCharsAsStringTo(s.data(), s.size(), os);
  476. }
  477. #endif // GTEST_HAS_STD_WSTRING
  478. } // namespace internal
  479. } // namespace testing