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.
5 #ifndef BASE_STRINGS_SAFE_SPRINTF_H_
6 #define BASE_STRINGS_SAFE_SPRINTF_H_
8 #include "build/build_config.h"
19 #include "base/base_export.h"
20 #include "base/basictypes.h"
26 // Define ssize_t inside of our namespace.
28 typedef __int64 ssize_t;
34 // SafeSPrintf() is a type-safe and completely self-contained version of
37 // SafeSNPrintf() is an alternative function signature that can be used when
38 // not dealing with fixed-sized buffers. When possible, SafeSPrintf() should
39 // always be used instead of SafeSNPrintf()
41 // These functions allow for formatting complicated messages from contexts that
42 // require strict async-signal-safety. In fact, it is safe to call them from
43 // any low-level execution context, as they are guaranteed to make no library
44 // or system calls. It deliberately never touches "errno", either.
46 // The only exception to this rule is that in debug builds the code calls
47 // RAW_CHECK() to help diagnose problems when the format string does not
48 // match the rest of the arguments. In release builds, no CHECK()s are used,
49 // and SafeSPrintf() instead returns an output string that expands only
50 // those arguments that match their format characters. Mismatched arguments
53 // The code currently only supports a subset of format characters:
54 // %c, %o, %d, %x, %X, %p, and %s.
56 // SafeSPrintf() aims to be as liberal as reasonably possible. Integer-like
57 // values of arbitrary width can be passed to all of the format characters
58 // that expect integers. Thus, it is explicitly legal to pass an "int" to
59 // "%c", and output will automatically look at the LSB only. It is also
60 // explicitly legal to pass either signed or unsigned values, and the format
61 // characters will automatically interpret the arguments accordingly.
63 // It is still not legal to mix-and-match integer-like values with pointer
64 // values. For instance, you cannot pass a pointer to %x, nor can you pass an
67 // The one exception is "0" zero being accepted by "%p". This works-around
68 // the problem of C++ defining NULL as an integer-like value.
70 // All format characters take an optional width parameter. This must be a
71 // positive integer. For %d, %o, %x, %X and %p, if the width starts with
72 // a leading '0', padding is done with '0' instead of ' ' characters.
74 // There are a few features of snprintf()-style format strings, that
75 // SafeSPrintf() does not support at this time.
77 // If an actual user showed up, there is no particularly strong reason they
78 // couldn't be added. But that assumes that the trade-offs between complexity
79 // and utility are favorable.
81 // For example, adding support for negative padding widths, and for %n are all
82 // likely to be viewed positively. They are all clearly useful, low-risk, easy
83 // to test, don't jeopardize the async-signal-safety of the code, and overall
84 // have little impact on other parts of SafeSPrintf() function.
86 // On the other hands, adding support for alternate forms, positional
87 // arguments, grouping, wide characters, localization or floating point numbers
88 // are all unlikely to ever be added.
90 // SafeSPrintf() and SafeSNPrintf() mimic the behavior of snprintf() and they
91 // return the number of bytes needed to store the untruncated output. This
92 // does *not* include the terminating NUL byte.
94 // They return -1, iff a fatal error happened. This typically can only happen,
95 // if the buffer size is a) negative, or b) zero (i.e. not even the NUL byte
96 // can be written). The return value can never be larger than SSIZE_MAX-1.
97 // This ensures that the caller can always add one to the signed return code
98 // in order to determine the amount of storage that needs to be allocated.
100 // While the code supports type checking and while it is generally very careful
101 // to avoid printing incorrect values, it tends to be conservative in printing
102 // as much as possible, even when given incorrect parameters. Typically, in
103 // case of an error, the format string will not be expanded. (i.e. something
104 // like SafeSPrintf(buf, "%p %d", 1, 2) results in "%p 2"). See above for
105 // the use of RAW_CHECK() in debug builds, though.
107 // The pre-C++11 version cannot handle more than ten arguments.
111 // base::strings::SafeSPrintf(buf, "The answer: %2d", 42);
113 // Example with dynamically sized buffer (async-signal-safe). This code won't
114 // work on Visual studio, as it requires dynamically allocating arrays on the
115 // stack. Consider picking a smaller value for |kMaxSize| if stack size is
116 // limited and known. On the other hand, if the parameters to SafeSNPrintf()
117 // are trusted and not controllable by the user, you can consider eliminating
118 // the check for |kMaxSize| altogether. The current value of SSIZE_MAX is
119 // essentially a no-op that just illustrates how to implement an upper bound:
120 // const size_t kInitialSize = 128;
121 // const size_t kMaxSize = std::numeric_limits<ssize_t>::max();
122 // size_t size = kInitialSize;
125 // size = SafeSNPrintf(buf, size, "Error message \"%s\"\n", err) + 1;
126 // if (sizeof(buf) < kMaxSize && size > kMaxSize) {
129 // } else if (size > sizeof(buf))
131 // write(2, buf, size-1);
136 // Helpers that use C++ overloading, templates, and specializations to deduce
137 // and record type information from function arguments. This allows us to
138 // later write a type-safe version of snprintf().
141 enum Type { INT, UINT, STRING, POINTER };
143 // Any integer-like value.
144 Arg(signed char c) : i(c), width(sizeof(char)), type(INT) { }
145 Arg(unsigned char c) : i(c), width(sizeof(char)), type(UINT) { }
146 Arg(signed short j) : i(j), width(sizeof(short)), type(INT) { }
147 Arg(unsigned short j) : i(j), width(sizeof(short)), type(UINT) { }
148 Arg(signed int j) : i(j), width(sizeof(int)), type(INT) { }
149 Arg(unsigned int j) : i(j), width(sizeof(int)), type(UINT) { }
150 Arg(signed long j) : i(j), width(sizeof(long)), type(INT) { }
151 Arg(unsigned long j) : i(j), width(sizeof(long)), type(UINT) { }
152 Arg(signed long long j) : i(j), width(sizeof(long long)), type(INT) { }
153 Arg(unsigned long long j) : i(j), width(sizeof(long long)), type(UINT) { }
155 // A C-style text string.
156 Arg(const char* s) : str(s), type(STRING) { }
157 Arg(char* s) : str(s), type(STRING) { }
159 // Any pointer value that can be cast to a "void*".
160 template<class T> Arg(T* p) : ptr((void*)p), type(POINTER) { }
163 // An integer-like value.
169 // A C-style text string.
172 // A pointer to an arbitrary object.
175 const enum Type type;
178 // This is the internal function that performs the actual formatting of
179 // an snprintf()-style format string.
180 BASE_EXPORT ssize_t SafeSNPrintf(char* buf, size_t sz, const char* fmt,
181 const Arg* args, size_t max_args);
184 // In debug builds, allow unit tests to artificially lower the kSSizeMax
185 // constant that is used as a hard upper-bound for all buffers. In normal
186 // use, this constant should always be std::numeric_limits<ssize_t>::max().
187 BASE_EXPORT void SetSafeSPrintfSSizeMaxForTest(size_t max);
188 BASE_EXPORT size_t GetSafeSPrintfSSizeMaxForTest();
191 } // namespace internal
193 #if __cplusplus >= 201103 // C++11
195 template<typename... Args>
196 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt, Args... args) {
197 // Use Arg() object to record type information and then copy arguments to an
198 // array to make it easier to iterate over them.
199 const internal::Arg arg_array[] = { args... };
200 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
203 template<size_t N, typename... Args>
204 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, Args... args) {
205 // Use Arg() object to record type information and then copy arguments to an
206 // array to make it easier to iterate over them.
207 const internal::Arg arg_array[] = { args... };
208 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
213 // TODO(markus): C++11 has a much more concise and readable solution for
214 // expressing what we are doing here. Delete the fall-back code for older
215 // compilers as soon as we have fully switched to C++11.
217 template<class T0, class T1, class T2, class T3, class T4,
218 class T5, class T6, class T7, class T8, class T9>
219 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
220 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
221 T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) {
222 // Use Arg() object to record type information and then copy arguments to an
223 // array to make it easier to iterate over them.
224 const internal::Arg arg_array[] = {
225 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9
227 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
231 class T0, class T1, class T2, class T3, class T4,
232 class T5, class T6, class T7, class T8, class T9>
233 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
234 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
235 T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) {
236 // Use Arg() object to record type information and then copy arguments to an
237 // array to make it easier to iterate over them.
238 const internal::Arg arg_array[] = {
239 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9
241 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
244 template<class T0, class T1, class T2, class T3, class T4,
245 class T5, class T6, class T7, class T8>
246 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
247 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
248 T5 arg5, T6 arg6, T7 arg7, T8 arg8) {
249 // Use Arg() object to record type information and then copy arguments to an
250 // array to make it easier to iterate over them.
251 const internal::Arg arg_array[] = {
252 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8
254 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
258 class T0, class T1, class T2, class T3, class T4, class T5,
259 class T6, class T7, class T8>
260 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
261 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
262 T5 arg5, T6 arg6, T7 arg7, T8 arg8) {
263 // Use Arg() object to record type information and then copy arguments to an
264 // array to make it easier to iterate over them.
265 const internal::Arg arg_array[] = {
266 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8
268 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
271 template<class T0, class T1, class T2, class T3, class T4, class T5,
273 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
274 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
275 T5 arg5, T6 arg6, T7 arg7) {
276 // Use Arg() object to record type information and then copy arguments to an
277 // array to make it easier to iterate over them.
278 const internal::Arg arg_array[] = {
279 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7
281 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
285 class T0, class T1, class T2, class T3, class T4, class T5,
287 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
288 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
289 T5 arg5, T6 arg6, T7 arg7) {
290 // Use Arg() object to record type information and then copy arguments to an
291 // array to make it easier to iterate over them.
292 const internal::Arg arg_array[] = {
293 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7
295 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
298 template<class T0, class T1, class T2, class T3, class T4, class T5,
300 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
301 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
303 // Use Arg() object to record type information and then copy arguments to an
304 // array to make it easier to iterate over them.
305 const internal::Arg arg_array[] = {
306 arg0, arg1, arg2, arg3, arg4, arg5, arg6
308 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
312 class T0, class T1, class T2, class T3, class T4, class T5,
314 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
315 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5,
317 // Use Arg() object to record type information and then copy arguments to an
318 // array to make it easier to iterate over them.
319 const internal::Arg arg_array[] = {
320 arg0, arg1, arg2, arg3, arg4, arg5, arg6
322 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
325 template<class T0, class T1, class T2, class T3, class T4, class T5>
326 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
327 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) {
328 // Use Arg() object to record type information and then copy arguments to an
329 // array to make it easier to iterate over them.
330 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4, arg5 };
331 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
335 class T0, class T1, class T2, class T3, class T4, class T5>
336 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
337 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) {
338 // Use Arg() object to record type information and then copy arguments to an
339 // array to make it easier to iterate over them.
340 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4, arg5 };
341 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
344 template<class T0, class T1, class T2, class T3, class T4>
345 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
346 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) {
347 // Use Arg() object to record type information and then copy arguments to an
348 // array to make it easier to iterate over them.
349 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4 };
350 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
353 template<size_t N, class T0, class T1, class T2, class T3, class T4>
354 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, T0 arg0, T1 arg1,
355 T2 arg2, T3 arg3, T4 arg4) {
356 // Use Arg() object to record type information and then copy arguments to an
357 // array to make it easier to iterate over them.
358 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4 };
359 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
362 template<class T0, class T1, class T2, class T3>
363 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
364 T0 arg0, T1 arg1, T2 arg2, T3 arg3) {
365 // Use Arg() object to record type information and then copy arguments to an
366 // array to make it easier to iterate over them.
367 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3 };
368 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
371 template<size_t N, class T0, class T1, class T2, class T3>
372 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
373 T0 arg0, T1 arg1, T2 arg2, T3 arg3) {
374 // Use Arg() object to record type information and then copy arguments to an
375 // array to make it easier to iterate over them.
376 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3 };
377 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
380 template<class T0, class T1, class T2>
381 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
382 T0 arg0, T1 arg1, T2 arg2) {
383 // Use Arg() object to record type information and then copy arguments to an
384 // array to make it easier to iterate over them.
385 const internal::Arg arg_array[] = { arg0, arg1, arg2 };
386 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
389 template<size_t N, class T0, class T1, class T2>
390 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, T0 arg0, T1 arg1,
392 // Use Arg() object to record type information and then copy arguments to an
393 // array to make it easier to iterate over them.
394 const internal::Arg arg_array[] = { arg0, arg1, arg2 };
395 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
398 template<class T0, class T1>
399 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt, T0 arg0, T1 arg1) {
400 // Use Arg() object to record type information and then copy arguments to an
401 // array to make it easier to iterate over them.
402 const internal::Arg arg_array[] = { arg0, arg1 };
403 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
406 template<size_t N, class T0, class T1>
407 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, T0 arg0, T1 arg1) {
408 // Use Arg() object to record type information and then copy arguments to an
409 // array to make it easier to iterate over them.
410 const internal::Arg arg_array[] = { arg0, arg1 };
411 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
415 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt, T0 arg0) {
416 // Use Arg() object to record type information and then copy arguments to an
417 // array to make it easier to iterate over them.
418 const internal::Arg arg_array[] = { arg0 };
419 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
422 template<size_t N, class T0>
423 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, T0 arg0) {
424 // Use Arg() object to record type information and then copy arguments to an
425 // array to make it easier to iterate over them.
426 const internal::Arg arg_array[] = { arg0 };
427 return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
431 // Fast-path when we don't actually need to substitute any arguments.
432 BASE_EXPORT ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt);
434 inline ssize_t SafeSPrintf(char (&buf)[N], const char* fmt) {
435 return SafeSNPrintf(buf, N, fmt);
438 } // namespace strings
441 #endif // BASE_STRINGS_SAFE_SPRINTF_H_