1 | // Copyright 2002 and onwards Google Inc. |
2 | |
3 | #include <stdarg.h> // For va_list and related operations |
4 | #include <stdio.h> // MSVC requires this for _vsnprintf |
5 | #include <vector> |
6 | using std::vector; |
7 | |
8 | #include <string> |
9 | using std::string; |
10 | #include "stringprintf.h" |
11 | #include "base/logging.h" |
12 | // Max arguments supported by StringPrintVector |
13 | const int kStringPrintfVectorMaxArgs = 32; |
14 | |
15 | // An empty block of zero for filler arguments. This is const so that if |
16 | // printf tries to write to it (via %n) then the program gets a SIGSEGV |
17 | // and we can fix the problem or protect against an attack. |
18 | static const char string_printf_empty_block [256] = { '\0' }; |
19 | |
20 | string StringPrintfVector(const char* format, const vector<string>& v) { |
21 | CHECK_LE(v.size(), kStringPrintfVectorMaxArgs) |
22 | << "StringPrintfVector currently only supports up to " |
23 | << kStringPrintfVectorMaxArgs << " arguments. " |
24 | << "Feel free to add support for more if you need it." ; |
25 | |
26 | // Add filler arguments so that bogus format+args have a harder time |
27 | // crashing the program, corrupting the program (%n), |
28 | // or displaying random chunks of memory to users. |
29 | |
30 | const char* cstr[kStringPrintfVectorMaxArgs]; |
31 | for (int i = 0; i < v.size(); ++i) { |
32 | cstr[i] = v[i].c_str(); |
33 | } |
34 | for (int i = v.size(); i < arraysize(cstr); ++i) { |
35 | cstr[i] = &string_printf_empty_block[0]; |
36 | } |
37 | |
38 | // I do not know any way to pass kStringPrintfVectorMaxArgs arguments, |
39 | // or any way to build a va_list by hand, or any API for printf |
40 | // that accepts an array of arguments. The best I can do is stick |
41 | // this COMPILE_ASSERT right next to the actual statement. |
42 | |
43 | COMPILE_ASSERT(kStringPrintfVectorMaxArgs == 32, arg_count_mismatch); |
44 | return StringPrintf(format, |
45 | cstr[0], cstr[1], cstr[2], cstr[3], cstr[4], |
46 | cstr[5], cstr[6], cstr[7], cstr[8], cstr[9], |
47 | cstr[10], cstr[11], cstr[12], cstr[13], cstr[14], |
48 | cstr[15], cstr[16], cstr[17], cstr[18], cstr[19], |
49 | cstr[20], cstr[21], cstr[22], cstr[23], cstr[24], |
50 | cstr[25], cstr[26], cstr[27], cstr[28], cstr[29], |
51 | cstr[30], cstr[31]); |
52 | } |
53 | |