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

Side by Side Diff: base/debug/format.h

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: Added missing test, more clean ups requested by jln, more comments, support for octals 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 #ifndef BASE_DEBUG_FORMAT_H_
8 #define BASE_DEBUG_FORMAT_H_
9
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <stdlib.h>
13
14 #if defined(__unix__)
15 // For ssize_t
16 #include <unistd.h>
17 #endif
18
19 #include "base/base_export.h"
20 #include "base/basictypes.h"
21
22 namespace base {
23 namespace debug {
24
25 #if defined(_MSC_VER)
26 // Define ssize_t inside of our namespace.
27 #if defined(_WIN64)
28 typedef __int64 ssize_t;
29 #else
30 typedef long ssize_t;
31 #endif
32 #endif
33
34 // Format() is a type-safe and async-signal-safe version of snprintf().
35 //
36 // FormatN() is an alternative function signature that can be used when
37 // not dealing with fixed-sized buffers. When possible, Format() should always
38 // be used instead of FormatN()
39 //
40 // These functions allow for formatting complicated messages from contexts that
41 // require strict async-signal-safety. In fact, it is safe to call them from
42 // any low-level execution context; even from contexts that have stricter
43 // requirements than just async-signal-safety.
44 //
45 // The code currently only supports a subset of format characters:
46 // %c, %o, %d, %x, %X, %p, and %s.
47 //
48 // Format() aims to be as liberal as reasonably possible. Integer-like values
49 // of arbitrary width can be passed to all of the format characters that expect
50 // integers. Thus, it is explicitly legal to pass an "int" to "%c", and output
51 // will automatically look at the LSB only. It is also explicitly legal to
52 // pass either signed or unsigned values, and the format characters will
53 // automatically interpret the arguments accordingly.
54 //
55 // It is still not legal to mix-and-match integer-like values with pointer
56 // values. For instance, you cannot pass a pointer to %x, nor can you pass an
57 // integer to %p.
58 //
59 // The one exception is "0" zero being accepted by "%p". This works-around
60 // the problem of C++ defining NULL as an integer-like value.
61 //
62 // All format characters take an optional width parameter. This must be a
63 // positive integer. For %d, %o, %x, %X and %p, if the width starts with
64 // a leading '0', padding is done with '0' instead of ' ' characters.
65 //
66 // There are a few features of snprintf()-style format strings, that Format()
67 // does not support at this time.
68 //
69 // If an actual user showed up, there is no particularly strong reason they
70 // couldn't be added. But that assumes that the trade-offs between complexity
71 // and utility are favorable.
72 //
73 // For example, adding support for negative padding widths, and for %n are all
74 // likely to be viewed positively. They are all clearly useful, low-risk, easy
75 // to test, don't jeopardize the async-signal-safety of the code, and overall
76 // have little impact on other parts of Format() function.
77 //
78 // On the other hands, adding support for alternate forms, positional
79 // arguments, grouping, wide characters, localization or floating point numbers
80 // are all unlikely to ever be added.
81 //
82 // Format() and FormatN() mimic the behavior of snprintf() and they return
83 // the number of bytes needed to store the untruncated output. This does *not*
84 // include the terminating NUL byte.
85 //
86 // They return -1, iff a fatal error happened. This typically can only happen,
87 // if the buffer size is a) negative, or b) zero (i.e. not even the NUL byte
88 // can be written). The return value can never be larger than SSIZE_MAX-1.
89 // This ensures that the caller can always add one to the signed return code
90 // in order to determine the amount of storage that needs to be allocated.
91 //
92 // While the code supports type checking and while it is generally very careful
93 // to avoid printing incorrect values, it tends to be conservative in printing
94 // as much as possible, even when given incorrect parameters. Typically, in
95 // case of an error, the format string will not be expanded. (i.e. something
96 // like Format(buf, "%p %d", 1, 2) results in "%p 2").
97 //
98 // The pre-C++11 version cannot handle more than ten arguments.
99 //
100 // Basic example:
101 // char buf[20];
102 // base::debug::Format(buf, "The answer: %2d", 42);
103 //
104 // Example with dynamically sized buffer (async-signal-safe). This code won't
105 // work on Visual studio, as it requires dynamically allocating arrays on the
106 // stack. Consider picking a smaller value for |kMaxSize| if stack size is
107 // limited and known. On the other hand, if the parameters to FormatN() are
108 // trusted and not controllable by the user, you can consider eliminating the
109 // check for |kMaxSize| altogether. The current value of SSIZE_MAX is
110 // essentially a no-op that just illustrates how to implement an upper bound:
111 // const size_t kInitialSize = 128;
112 // const size_t kMaxSize = std::numeric_limits<ssize_t>::max();
113 // size_t sz = kInitialSize;
114 // for (;;) {
115 // char buf[sz];
116 // sz = FormatN(buf, sz, "Error message \"%s\"\n", err) + 1;
117 // if (sizeof(buf) < kMaxSize && sz > kMaxSize) {
118 // sz = kMaxSize;
119 // continue;
120 // } else if (sz > sizeof(buf))
121 // continue;
122 // write(2, buf, sz-1);
123 // break;
124 // }
125
126 namespace internal {
127 // Helpers that use C++ overloading, templates, and specializations to deduce
128 // and record type information from function arguments. This allows us to
129 // later write a type-safe version of snprintf().
130
131 struct Arg {
132 enum Type { INT, UINT, STRING, POINTER };
133
134 // Any integer-like value.
135 Arg(signed char c) : i_(c), width_(sizeof(char)), type_(INT) { }
136 Arg(unsigned char c) : i_(c), width_(sizeof(char)), type_(UINT) { }
137 Arg(signed short i) : i_(i), width_(sizeof(short)), type_(INT) { }
138 Arg(unsigned short i) : i_(i), width_(sizeof(short)), type_(UINT) { }
139 Arg(signed int i) : i_(i), width_(sizeof(int)), type_(INT) { }
140 Arg(unsigned int i) : i_(i), width_(sizeof(int)), type_(UINT) { }
141 Arg(signed long i) : i_(i), width_(sizeof(long)), type_(INT) { }
142 Arg(unsigned long i) : i_(i), width_(sizeof(long)), type_(UINT) { }
143 Arg(signed long long i) : i_(i), width_(sizeof(long long)),
144 type_(INT) { }
145 Arg(unsigned long long i) : i_(i), width_(sizeof(long long)),
146 type_(UINT) { }
147
148 // A C-style text string.
149 Arg(const char* s) : s_(s), type_(STRING) { }
150 Arg(char* s) : s_(s), type_(STRING) { }
151
152 // Any pointer value that can be cast to a "void*".
153 template<class T> Arg(T* ptr) : ptr_((void*)ptr), type_(POINTER) { }
154
155 union {
156 // An integer-like value.
157 struct {
158 int64_t i_;
159 unsigned char width_;
160 };
161
162 // A C-style text string.
163 const char* s_;
164
165 // A pointer to an arbitrary object.
166 const void* ptr_;
167 };
168 const enum Type type_;
169 };
170
171 // This is the internal function that performs the actual formatting of
172 // an snprintf()-style format string.
173 BASE_EXPORT ssize_t FormatN(char* buf, size_t sz, const char* fmt,
174 const Arg* args, size_t max_args);
175
176 #if !defined(NDEBUG)
177 // In debug builds, allow unit tests to artificially lower the kSSizeMax
178 // constant that is used as a hard upper-bound for all buffers. In normal
179 // use, this constant should always be std::numeric_limits<ssize_t>::max().
180 BASE_EXPORT void SetFormatSSizeMax(size_t max);
181 BASE_EXPORT size_t GetFormatSSizeMax();
182 #endif
183
184 } // namespace internal
185
186 #if __cplusplus >= 201103 // C++11
187
188 template<typename... Args>
189 ssize_t FormatN(char* buf, size_t N, const char* fmt, Args... args) {
190 // Use Arg() object to record type information and then copy arguments to an
191 // array to make it easier to iterate over them.
192 const internal::Arg arg_array[] = { args... };
193 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
194 }
195
196 template<size_t N, typename... Args>
197 ssize_t Format(char (&buf)[N], const char* fmt, Args... args) {
198 // Use Arg() object to record type information and then copy arguments to an
199 // array to make it easier to iterate over them.
200 const internal::Arg arg_array[] = { args... };
201 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
202 }
203
204 #else // Pre-C++11
205
206 // TODO(markus): C++11 has a much more concise and readable solution for
207 // expressing what we are doing here. Delete the fall-back code for older
208 // compilers as soon as we have fully switched to C++11.
209
210 template<class T0, class T1, class T2, class T3, class T4,
211 class T5, class T6, class T7, class T8, class T9>
212 ssize_t FormatN(char* buf, size_t N, const char* fmt,
213 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
214 T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) {
215 // Use Arg() object to record type information and then copy arguments to an
216 // array to make it easier to iterate over them.
217 const internal::Arg arg_array[] = {
218 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9
219 };
220 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
221 }
222
223 template<size_t N,
224 class T0, class T1, class T2, class T3, class T4,
225 class T5, class T6, class T7, class T8, class T9>
226 ssize_t Format(char (&buf)[N], const char* fmt,
227 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
228 T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) {
229 // Use Arg() object to record type information and then copy arguments to an
230 // array to make it easier to iterate over them.
231 const internal::Arg arg_array[] = {
232 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9
233 };
234 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
235 }
236
237 template<class T0, class T1, class T2, class T3, class T4,
238 class T5, class T6, class T7, class T8>
239 ssize_t FormatN(char* buf, size_t N, const char* fmt,
240 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
241 T5 arg5, T6 arg6, T7 arg7, T8 arg8) {
242 // Use Arg() object to record type information and then copy arguments to an
243 // array to make it easier to iterate over them.
244 const internal::Arg arg_array[] = {
245 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8
246 };
247 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
248 }
249
250 template<size_t N,
251 class T0, class T1, class T2, class T3, class T4, class T5,
252 class T6, class T7, class T8>
253 ssize_t Format(char (&buf)[N], const char* fmt,
254 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
255 T5 arg5, T6 arg6, T7 arg7, T8 arg8) {
256 // Use Arg() object to record type information and then copy arguments to an
257 // array to make it easier to iterate over them.
258 const internal::Arg arg_array[] = {
259 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8
260 };
261 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
262 }
263
264 template<class T0, class T1, class T2, class T3, class T4, class T5,
265 class T6, class T7>
266 ssize_t FormatN(char* buf, size_t N, const char* fmt,
267 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
268 T5 arg5, T6 arg6, T7 arg7) {
269 // Use Arg() object to record type information and then copy arguments to an
270 // array to make it easier to iterate over them.
271 const internal::Arg arg_array[] = {
272 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7
273 };
274 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
275 }
276
277 template<size_t N,
278 class T0, class T1, class T2, class T3, class T4, class T5,
279 class T6, class T7>
280 ssize_t Format(char (&buf)[N], const char* fmt,
281 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
282 T5 arg5, T6 arg6, T7 arg7) {
283 // Use Arg() object to record type information and then copy arguments to an
284 // array to make it easier to iterate over them.
285 const internal::Arg arg_array[] = {
286 arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7
287 };
288 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
289 }
290
291 template<class T0, class T1, class T2, class T3, class T4, class T5,
292 class T6>
293 ssize_t FormatN(char* buf, size_t N, const char* fmt,
294 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
295 T5 arg5, T6 arg6) {
296 // Use Arg() object to record type information and then copy arguments to an
297 // array to make it easier to iterate over them.
298 const internal::Arg arg_array[] = {
299 arg0, arg1, arg2, arg3, arg4, arg5, arg6
300 };
301 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
302 }
303
304 template<size_t N,
305 class T0, class T1, class T2, class T3, class T4, class T5,
306 class T6>
307 ssize_t Format(char (&buf)[N], const char* fmt,
308 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) {
309 // Use Arg() object to record type information and then copy arguments to an
310 // array to make it easier to iterate over them.
311 const internal::Arg arg_array[] = {
312 arg0, arg1, arg2, arg3, arg4, arg5, arg6
313 };
314 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
315 }
316
317 template<class T0, class T1, class T2, class T3, class T4, class T5>
318 ssize_t FormatN(char* buf, size_t N, const char* fmt,
319 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) {
320 // Use Arg() object to record type information and then copy arguments to an
321 // array to make it easier to iterate over them.
322 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4, arg5 };
323 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
324 }
325
326 template<size_t N,
327 class T0, class T1, class T2, class T3, class T4, class T5>
328 ssize_t Format(char (&buf)[N], const char* fmt,
329 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) {
330 // Use Arg() object to record type information and then copy arguments to an
331 // array to make it easier to iterate over them.
332 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4, arg5 };
333 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
334 }
335
336 template<class T0, class T1, class T2, class T3, class T4>
337 ssize_t FormatN(char* buf, size_t N, const char* fmt,
338 T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) {
339 // Use Arg() object to record type information and then copy arguments to an
340 // array to make it easier to iterate over them.
341 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4 };
342 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
343 }
344
345 template<size_t N, class T0, class T1, class T2, class T3, class T4>
346 ssize_t Format(char (&buf)[N], const char* fmt, T0 arg0, T1 arg1,
347 T2 arg2, T3 arg3, T4 arg4) {
348 // Use Arg() object to record type information and then copy arguments to an
349 // array to make it easier to iterate over them.
350 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4 };
351 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
352 }
353
354 template<class T0, class T1, class T2, class T3>
355 ssize_t FormatN(char* buf, size_t N, const char* fmt,
356 T0 arg0, T1 arg1, T2 arg2, T3 arg3) {
357 // Use Arg() object to record type information and then copy arguments to an
358 // array to make it easier to iterate over them.
359 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3 };
360 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
361 }
362
363 template<size_t N, class T0, class T1, class T2, class T3>
364 ssize_t Format(char (&buf)[N], const char* fmt,
365 T0 arg0, T1 arg1, T2 arg2, T3 arg3) {
366 // Use Arg() object to record type information and then copy arguments to an
367 // array to make it easier to iterate over them.
368 const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3 };
369 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
370 }
371
372 template<class T0, class T1, class T2>
373 ssize_t FormatN(char* buf, size_t N, const char* fmt,
374 T0 arg0, T1 arg1, T2 arg2) {
375 // Use Arg() object to record type information and then copy arguments to an
376 // array to make it easier to iterate over them.
377 const internal::Arg arg_array[] = { arg0, arg1, arg2 };
378 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
379 }
380
381 template<size_t N, class T0, class T1, class T2>
382 ssize_t Format(char (&buf)[N], const char* fmt, 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::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
387 }
388
389 template<class T0, class T1>
390 ssize_t FormatN(char* buf, size_t N, const char* fmt, T0 arg0, T1 arg1) {
391 // Use Arg() object to record type information and then copy arguments to an
392 // array to make it easier to iterate over them.
393 const internal::Arg arg_array[] = { arg0, arg1 };
394 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
395 }
396
397 template<size_t N, class T0, class T1>
398 ssize_t Format(char (&buf)[N], const char* fmt, T0 arg0, T1 arg1) {
399 // Use Arg() object to record type information and then copy arguments to an
400 // array to make it easier to iterate over them.
401 const internal::Arg arg_array[] = { arg0, arg1 };
402 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
403 }
404
405 template<class T0>
406 ssize_t FormatN(char* buf, size_t N, const char* fmt, T0 arg0) {
407 // Use Arg() object to record type information and then copy arguments to an
408 // array to make it easier to iterate over them.
409 const internal::Arg arg_array[] = { arg0 };
410 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
411 }
412
413 template<size_t N, class T0>
414 ssize_t Format(char (&buf)[N], const char* fmt, T0 arg0) {
415 // Use Arg() object to record type information and then copy arguments to an
416 // array to make it easier to iterate over them.
417 const internal::Arg arg_array[] = { arg0 };
418 return internal::FormatN(buf, N, fmt, arg_array, arraysize(arg_array));
419 }
420 #endif
421
422 // Fast-path when we don't actually need to substitute any arguments.
423 BASE_EXPORT ssize_t FormatN(char* buf, size_t N, const char* fmt);
424 template<size_t N>
425 inline ssize_t Format(char (&buf)[N], const char* fmt) {
426 return FormatN(buf, N, fmt);
427 }
428
429 } // namespace debug
430 } // namespace base
431
432 #endif // BASE_DEBUG_FORMAT_H_
OLDNEW
« no previous file with comments | « base/base.gypi ('k') | base/debug/format.cc » ('j') | base/debug/format.cc » ('J')

Powered by Google App Engine
This is Rietveld 408576698