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

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

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: Addressed jln's comments 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 #include "base/debug/format.h"
8
9 #include <limits>
10
11 #if !defined(NDEBUG)
12 // In debug builds, we use RAW_CHECK() to print useful error messages, if
13 // Format() is called with broken arguments.
14 // As our contract promises that Format() can be called from any restricted
15 // run-time context, it is not actually safe to call logging functions from it;
16 // and we only ever do so for debug builds and hope for the best.
17 // We should _never_ call any logging function other than RAW_CHECK(), and
18 // we should _never_ include any logging code that is active in production
19 // builds. Most notably, we should not include these logging functions in
20 // unofficial release builds, even though those builds would otherwise have
21 // DCHECKS() enabled.
22 // In other words; please do not remove the #ifdef around this #include.
23 // Instead, in production builds we opt for returning a degraded result,
24 // whenever an error is encountered.
25 // E.g. The broken function call
26 // Format("errno = %d (%x)", errno, strerror(errno))
27 // will print something like
28 // errno = 13, (%x)
29 // instead of
30 // errno = 13 (Access denied)
31 // In most of the anticipated use cases, that's probably the preferred
32 // behavior.
33 #include "base/logging.h"
34 #define DEBUG_CHECK RAW_CHECK
35 #else
36 #define DEBUG_CHECK(x) do { if (x) { } } while (0)
37 #endif
38
39 namespace base {
40 namespace debug {
41
42 // The code in this file is extremely careful to be async-signal-safe.
43 //
44 // Most obviously, we avoid calling any code that could dynamically allocate
45 // memory. Doing so would almost certainly result in bugs and dead-locks.
46 // We also avoid calling any other STL functions that could have unintended
47 // side-effects involving memory allocation or access to other shared
48 // resources.
49 //
50 // But on top of that, we also avoid calling other library functions, as many
51 // of them have the side-effect of calling getenv() (in order to deal with
52 // localization) or accessing errno. The latter sounds benign, but there are
53 // several execution contexts where it isn't even possible to safely read let
54 // alone write errno.
55 //
56 // The stated design goal of the Format() function is that it can be called
57 // from any context that can safely call C or C++ code (i.e. anything that
58 // doesn't require assembly code).
59 //
60 // For a brief overview of some but not all of the issues with async-signal-
61 // safety, refer to:
62 // http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html
63
64 namespace {
65 const size_t kSSizeMaxConst = ((size_t)(ssize_t)-1) >> 1;
66
67 const char kUpCaseHexDigits[] = "0123456789ABCDEF";
68 const char kDownCaseHexDigits[] = "0123456789abcdef";
69 }
70
71 #if defined(NDEBUG)
72 // We would like to define kSSizeMax as std::numeric_limits<ssize_t>::max(),
73 // but C++ doesn't allow us to do that for constants. Instead, we have to
74 // use careful casting and shifting. We later use a COMPILE_ASSERT to
75 // verify that this worked correctly.
76 namespace {
77 const size_t kSSizeMax = kSSizeMaxConst;
78 }
79 #else // defined(NDEBUG)
80 // For efficiency, we really need kSSizeMax to be a constant. But for unit
81 // tests, it should be adjustable. This allows us to verify edge cases without
82 // having to fill the entire available address space. As a compromise, we make
83 // kSSizeMax adjustable in debug builds, and then only compile that particular
84 // part of the unit test in debug builds.
85 namespace {
86 static size_t kSSizeMax = kSSizeMaxConst;
87 }
88
89 namespace internal {
90 void SetFormatSSizeMax(size_t max) {
91 kSSizeMax = max;
92 }
93
94 size_t GetFormatSSizeMax() {
95 return kSSizeMax;
96 }
97 }
98 #endif // defined(NDEBUG)
99
100 namespace {
101 class Buffer {
102 public:
103 // |buffer| is caller-allocated storage that Format() writes to. It
104 // has |size| bytes of writable storage. It is the caller's responsibility
105 // to ensure that the buffer is at least one byte in size, so that it fits
106 // the trailing NUL that will be added by the destructor. The buffer also
107 // must be smaller or equal to kSSizeMax in size.
108 Buffer(char* buffer, size_t size)
109 : buffer_(buffer),
110 size_(size - 1), // Account for trailing NUL byte
111 count_(0) {
112 // This test should work on all C++11 compilers, but apparently something is
113 // not working on all versions of clang just yet (e.g. on Mac, IOS, and
114 // Android). We are conservative and exclude all of clang for the time being.
115 // TODO(markus): Check if this restriction can be lifted.
116 #if __cplusplus >= 201103 && !defined(__clang__)
117 COMPILE_ASSERT(kSSizeMaxConst == std::numeric_limits<ssize_t>::max(),
118 kSSizeMax_is_the_max_value_of_an_ssize_t);
119 #endif
120 DEBUG_CHECK(size > 0);
121 DEBUG_CHECK(size <= kSSizeMax);
122 }
123
124 ~Buffer() {
125 // The caller guaranteed that there was enough space to store a trailing
jln (very slow on Chromium) 2013/08/14 04:18:06 // The constructor guaranteed that... (or rephras
126 // NUL -- and in debug builds, we are actually verifying this with
127 // DEBUG_CHECK()s. So, we can always unconditionally write the NUL byte
128 // in the destructor.
129 // We do not need to adjust the count_, as Format() copies snprintf() in
130 // not including the NUL byte in its return code.
131 *GetInsertionPoint() = '\000';
132 }
133
134 // Returns true, iff the buffer is filled all the way to |kSSizeMax-1|. The
135 // caller can now stop adding more data, as GetCount() has reached its
136 // maximum possible value.
137 inline bool OutOfAddressableSpace() const {
138 return count_ == static_cast<size_t>(kSSizeMax - 1);
139 }
140
141 // Returns the number of bytes that would have been emitted to |buffer_|
142 // if it was sized sufficiently large. This number can be larger than
143 // |size_|, if the caller provided an insufficiently large output buffer.
144 // But it will never be bigger than |kSSizeMax-1|.
145 inline ssize_t GetCount() const {
146 DEBUG_CHECK(count_ < kSSizeMax);
147 return static_cast<ssize_t>(count_);
148 }
149
150 // Emits one |ch| character into the |buffer_| and updates the |count_| of
151 // characters that are currently supposed to be in the buffer.
152 // Returns "false", iff the buffer was already full.
153 // N.B. |count_| increases even if no characters have been written. This is
154 // needed so that GetCount() can return the number of bytes that should
155 // have been allocated for the |buffer_|.
156 inline bool Out(char ch) {
157 if (size_ >= 1 && count_ < size_) {
158 buffer_[count_] = ch;
159 return IncrementCountByOne();
160 }
161 // |count_| still needs to be updated, even if the buffer has been
162 // filled completely. This allows Format() to return the number of bytes
163 // that should have been emitted.
164 IncrementCountByOne();
165 return false;
166 }
167
168 // Inserts |padding|-|len| bytes worth of padding into the |buffer_|.
169 // |count_| will also be incremented by the number of bytes that were meant
170 // to be emitted. The |pad| character is typically either a ' ' space
171 // or a '0' zero, but other non-NUL values are legal.
172 // Returns "false", iff the the |buffer_| filled up (i.e. |count_|
173 // overflowed |size_|) at any time during padding.
174 inline bool Pad(char pad, size_t padding, size_t len) {
175 DEBUG_CHECK(pad);
176 DEBUG_CHECK(padding >= 0 && padding <= kSSizeMax);
177 DEBUG_CHECK(len >= 0 && len);
178 for (; padding > len; --padding) {
179 if (!Out(pad)) {
180 if (--padding) {
181 IncrementCount(padding-len);
182 }
183 return false;
184 }
185 }
186 return true;
187 }
188
189 // POSIX doesn't define any async-signal-safe function for converting
190 // an integer to ASCII. Define our own version.
191 //
192 // This also gives us the ability to make the function a little more
193 // powerful and have it deal with |padding|, with truncation, and with
194 // predicting the length of the untruncated output.
195 //
196 // IToASCII() converts an integer |i| to ASCII.
197 //
198 // Unlike similar functions in the standard C library, it never appends a
199 // NUL character. This is left for the caller to do.
200 //
201 // While the function signature takes a signed int64_t, the code decides at
202 // run-time whether to treat the argument as signed or assigned based on the
203 // value of |sign|.
204 //
205 // It supports |base|s 2 through 16. Only a |base| of 10 is allowed to have
206 // a |sign|. Otherwise, |i| is treated as unsigned.
207 //
208 // For bases larger than 10, |upcase| decides whether lower-case or upper-
209 // case letters should be used to designate digits greater than 10.
210 //
211 // Padding can be done with either '0' zeros or ' ' spaces. Padding has to
212 // be positive and will always be applied to the left of the output.
213 //
214 // Prepends a |prefix| to the number (e.g. "0x"). This prefix goes to
215 // the left of |padding|, if |pad| is '0'; and to the right of |padding|
216 // if |pad| is ' '.
217 //
218 // Returns "false", if the |buffer_| overflowed at any time.
219 bool IToASCII(bool sign, bool upcase, int64_t i, int base,
220 char pad, size_t padding, const char* prefix);
221
222 private:
223 // Increments |count_| by |inc| unless this would cause |count_| to
224 // overflow |kSSizeMax-1|. Returns "false", iff an overflow was detected;
225 // it then clamps |count_| to |kSSizeMax-1|.
226 inline bool IncrementCount(size_t inc) {
227 // "inc" is either 1 or a "padding" value. Padding is clamped at
228 // run-time to at most kSSizeMax-1. So, we know that "inc" is always in
229 // the range 1..kSSizeMax-1.
230 // This allows us to compute "kSSizeMax - 1 - inc" without incurring any
231 // integer overflows.
232 DEBUG_CHECK(inc <= kSSizeMax - 1);
233 if (count_ > kSSizeMax - 1 - inc) {
234 count_ = kSSizeMax - 1;
235 return false;
236 } else {
237 count_ += inc;
238 return true;
239 }
240 }
241
242 // Convenience method for the common case of incrementing |count_| by one.
243 inline bool IncrementCountByOne() {
244 return IncrementCount(1);
245 }
246
247 // Return the current insertion point into the buffer. This is typically
248 // at |buffer_| + |count_|, but could be before that if truncation
249 // happened. It always points to one byte past the last byte that was
250 // successfully placed into the |buffer_|.
251 inline char* GetInsertionPoint() const {
252 size_t idx = count_;
253 if (idx > size_) {
254 idx = size_;
255 }
256 return buffer_ + idx;
257 }
258
259 // User-provided buffer that will receive the fully formatted output string.
260 char* buffer_;
261
262 // Number of bytes that are available in the buffer excluding the trailing
263 // NUL byte that will be added by the destructor.
264 const size_t size_;
265
266 // Number of bytes that would have been emitted to the buffer, if the buffer
267 // was sufficiently big. This number always excludes the trailing NUL byte
268 // and it is guaranteed to never grow bigger than kSSizeMax-1.
269 size_t count_;
270
271 DISALLOW_COPY_AND_ASSIGN(Buffer);
272 };
273
274
275 bool Buffer::IToASCII(bool sign, bool upcase, int64_t i, int base,
276 char pad, size_t padding, const char* prefix) {
277 // Sanity check for parameters. None of these should ever fail, but see
278 // above for the rationale why we can't call CHECK().
279 DEBUG_CHECK(base >= 2);
280 DEBUG_CHECK(base <= 16);
281 DEBUG_CHECK(!sign || base == 10);
282 DEBUG_CHECK(pad == '0' || pad == ' ');
283 DEBUG_CHECK(padding >= 0);
284 DEBUG_CHECK(padding <= kSSizeMax);
285 DEBUG_CHECK(!(sign && prefix && *prefix));
286
287 // Handle negative numbers, if requested by caller.
288 int minint = 0;
289 uint64_t num;
290 if (sign && i < 0) {
291 prefix = "-";
292
293 // Turn our number positive.
294 if (i == std::numeric_limits<int64_t>::min()) {
295 // The most negative integer needs special treatment.
296 minint = 1;
297 num = static_cast<uint64_t>(-(i + 1));
298 } else {
299 // "Normal" negative numbers are easy.
300 num = static_cast<uint64_t>(-i);
301 }
302 } else {
303 num = static_cast<uint64_t>(i);
jln (very slow on Chromium) 2013/08/14 04:18:06 Please, document this cast. Explaining that the si
304 }
305
306 // If padding with '0' zero, emit the prefix or '-' character now. Otherwise,
307 // make the prefix accessible in reverse order, so that we can later output
308 // it right between padding and the number.
309 // We cannot choose the easier approach of just reversing the number, as that
310 // fails in situations where we need to truncate numbers that have padding
311 // and/or prefixes.
312 const char* reverse_prefix = NULL;
313 if (prefix && *prefix) {
314 if (pad == '0') {
315 while (*prefix) {
316 if (padding) {
317 --padding;
318 }
319 Out(*prefix++);
320 }
321 prefix = NULL;
322 } else {
323 for (reverse_prefix = prefix; *reverse_prefix; ++reverse_prefix) {
324 }
325 }
326 } else
327 prefix = NULL;
328 const size_t prefix_length = reverse_prefix - prefix;
329
330 // Loop until we have converted the entire number. Output at least one
331 // character (i.e. '0').
332 size_t start = count_;
333 size_t discarded = 0;
334 bool started = false;
335 do {
336 // Make sure there is still enough space left in our output buffer.
337 if (count_ >= size_) {
338 if (start < size_) {
339 // It is rare that we need to output a partial number. But if asked
340 // to do so, we will still make sure we output the correct number of
341 // leading digits.
342 // Since we are generating the digits in reverse order, we actually
343 // have to discard digits in the order that we have already emitted
344 // them. This is essentially equivalent to:
345 // memmove(buffer_ + start, buffer_ + start + 1, size_ - start - 1)
346 for (char* move = buffer_ + start, *end = buffer_ + size_ - 1;
347 move < end;
348 ++move) {
349 *move = move[1];
350 }
351 ++discarded;
352 --count_;
353 } else if (count_ - size_ > 1) {
354 // Need to increment either |count_| or |discarded| to make progress.
355 // The latter is more efficient, as it eventually triggers fast
356 // handling of padding. But we have to ensure we don't accidentally
357 // change the overall state (i.e. switch the state-machine from
358 // discarding to non-discarding). |count_| needs to always stay
359 // bigger than |size_|.
360 --count_;
361 ++discarded;
362 }
363 }
364
365 // Output the next digit and (if necessary) compensate for the most
366 // negative integer needing special treatment. This works because,
367 // no matter the bit width of the integer, the lowest-most decimal
368 // integer always ends in 2, 4, 6, or 8.
369 if (!num && started) {
370 if (reverse_prefix > prefix) {
371 Out(*--reverse_prefix);
372 } else {
373 Out(pad);
374 }
375 } else {
376 started = true;
377 Out((upcase ? kUpCaseHexDigits : kDownCaseHexDigits)[num%base + minint]);
378 }
379
380 minint = 0;
381 num /= base;
382
383 // Add padding, if requested.
384 if (padding > 0) {
385 --padding;
386
387 // Performance optimization for when we are asked to output excessive
388 // padding, but our output buffer is limited in size. Even if we output
389 // a 64bit number in binary, we would never write more than 64 plus
390 // prefix non-padding characters. So, once this limit has been passed,
391 // any further state change can be computed arithmetically; we know that
392 // by this time, our entire final output consists of padding characters
393 // that have all already been output.
394 if (discarded > 8*sizeof(num) + prefix_length) {
395 IncrementCount(padding);
396 padding = 0;
397 }
398 }
399 } while (num || padding || (reverse_prefix > prefix));
400
401 // Conversion to ASCII actually resulted in the digits being in reverse
402 // order. We can't easily generate them in forward order, as we can't tell
403 // the number of characters needed until we are done converting.
404 // So, now, we reverse the string (except for the possible '-' sign).
405 char* front = buffer_ + start;
406 char* back = GetInsertionPoint();
407 while (--back > front) {
408 char ch = *back;
409 *back = *front;
410 *front++ = ch;
411 }
412
413 IncrementCount(discarded);
414 return !discarded;
415 }
416
417 } // anonymous namespace
418
419 ssize_t internal::FormatN(char* buf, size_t sz, const char* fmt,
420 const Arg* args, const size_t max_args) {
421 // Make sure that at least one NUL byte can be written, and that the buffer
422 // never overflows kSSizeMax. Not only does that use up most or all of the
423 // address space, it also would result in a return code that cannot be
424 // represented.
425 if (static_cast<ssize_t>(sz) < 1) {
426 return -1;
427 } else if (sz > kSSizeMax) {
428 sz = kSSizeMax;
429 }
430
431 // Iterate over format string and interpret '%' arguments as they are
432 // encountered.
433 Buffer buffer(buf, sz);
434 size_t padding;
435 char pad;
436 for (unsigned int cur_arg = 0; *fmt && !buffer.OutOfAddressableSpace(); ) {
437 if (*fmt++ == '%') {
438 padding = 0;
439 pad = ' ';
440 char ch = *fmt++;
441 format_character_found:
442 switch (ch) {
443 case '0': case '1': case '2': case '3': case '4':
444 case '5': case '6': case '7': case '8': case '9':
445 // Found a width parameter. Convert to an integer value and store in
446 // "padding". If the leading digit is a zero, change the padding
447 // character from a space ' ' to a zero '0'.
448 pad = ch == '0' ? '0' : ' ';
449 for (;;) {
450 // The maximum allowed padding fills all the available address
451 // space and leaves just enough space to insert the trailing NUL.
452 const size_t max_padding = kSSizeMax - 1;
453 if (padding > max_padding/10 ||
454 10*padding > max_padding - (ch - '0')) {
455 DEBUG_CHECK(padding <= max_padding/10 &&
456 10*padding <= max_padding - (ch - '0'));
457 // Integer overflow detected. Skip the rest of the width until
458 // we find the format character, then do the normal error handling.
459 padding_overflow:
460 padding = max_padding;
461 while ((ch = *fmt++) >= '0' && ch <= '9') {
462 }
463 if (cur_arg < max_args) {
464 ++cur_arg;
465 }
466 goto fail_to_expand;
467 }
468 padding = 10*padding + ch - '0';
469 if (padding > max_padding) {
470 // This doesn't happen for "sane" values of kSSizeMax. But once
471 // kSSizeMax gets smaller than about 10, our earlier range checks
472 // are incomplete. Unittests do trigger this artificial corner
473 // case.
474 DEBUG_CHECK(padding <= max_padding);
475 goto padding_overflow;
476 }
477 ch = *fmt++;
478 if (ch < '0' || ch > '9') {
479 // Reached the end of the width parameter. This is where the format
480 // character is found.
481 goto format_character_found;
482 }
483 }
484 break;
485 case 'c': { // Output an ASCII character.
486 // Check that there are arguments left to be inserted.
487 if (cur_arg >= max_args) {
488 DEBUG_CHECK(cur_arg < max_args);
489 goto fail_to_expand;
490 }
491
492 // Check that the argument has the expected type.
493 const Arg& arg = args[cur_arg++];
494 if (arg.type_ != Arg::INT &&
495 arg.type_ != Arg::UINT) {
496 DEBUG_CHECK(arg.type_ == Arg::INT ||
497 arg.type_ == Arg::UINT);
498 goto fail_to_expand;
499 }
500
501 // Apply padding, if needed.
502 buffer.Pad(' ', padding, 1);
503
504 // Convert the argument to an ASCII character and output it.
505 char ch = static_cast<char>(arg.i_);
506 if (!ch) {
507 goto end_of_output_buffer;
508 }
509 buffer.Out(ch);
510 break; }
511 case 'd': // Output a possibly signed decimal value.
512 case 'o': // Output an unsigned octal value.
513 case 'x': // Output an unsigned hexadecimal value.
514 case 'X':
515 case 'p': { // Output a pointer value.
516 // Check that there are arguments left to be inserted.
517 if (cur_arg >= max_args) {
518 DEBUG_CHECK(cur_arg < max_args);
519 goto fail_to_expand;
520 }
521
522 const Arg& arg = args[cur_arg++];
523 int64_t i;
524 const char* prefix = NULL;
525 if (ch != 'p') {
526 // Check that the argument has the expected type.
527 if (arg.type_ != Arg::INT &&
528 arg.type_ != Arg::UINT) {
529 DEBUG_CHECK(arg.type_ == Arg::INT ||
530 arg.type_ == Arg::UINT);
531 goto fail_to_expand;
532 }
533 i = arg.i_;
534
535 if (ch != 'd') {
536 // The Arg() constructor automatically performed sign expansion on
537 // signed parameters. This is great when outputting a %d decimal
538 // number, but can result in unexpected leading 0xFF bytes when
539 // outputting a %x hexadecimal number. Mask bits, if necessary.
540 // We have to do this here, instead of in the Arg() constructor, as
541 // the Arg() constructor cannot tell whether we will output a %d
542 // or a %x. Only the latter should experience masking.
543 if (arg.width_ < sizeof(int64_t)) {
544 i &= (1LL << (8*arg.width_)) - 1;
545 }
546 }
547 } else {
548 // Pointer values require an actual pointer or a string.
549 if (arg.type_ == Arg::POINTER) {
550 i = reinterpret_cast<uintptr_t>(arg.ptr_);
551 } else if (arg.type_ == Arg::STRING) {
552 i = reinterpret_cast<uintptr_t>(arg.s_);
553 } else if (arg.type_ == Arg::INT && arg.width_ == sizeof(void *) &&
554 arg.i_ == 0) { // Allow C++'s version of NULL
555 i = 0;
556 } else {
557 DEBUG_CHECK(arg.type_ == Arg::POINTER ||
558 arg.type_ == Arg::STRING);
559 goto fail_to_expand;
560 }
561
562 // Pointers always include the "0x" prefix.
563 prefix = "0x";
564 }
565
566 // Use IToASCII() to convert to ASCII representation. For decimal
567 // numbers, optionally print a sign. For hexadecimal numbers,
568 // distinguish between upper and lower case. %p addresses are always
569 // printed as upcase. Supports base 8, 10, and 16. Prints padding
570 // and/or prefixes, if so requested.
571 buffer.IToASCII(ch == 'd' && arg.type_ == Arg::INT,
572 ch != 'x', i,
573 ch == 'o' ? 8 : ch == 'd' ? 10 : 16,
574 pad, padding, prefix);
575 break; }
576 case 's': {
577 // Check that there are arguments left to be inserted.
578 if (cur_arg >= max_args) {
579 DEBUG_CHECK(cur_arg < max_args);
580 goto fail_to_expand;
581 }
582
583 // Check that the argument has the expected type.
584 const Arg& arg = args[cur_arg++];
585 const char *s;
586 if (arg.type_ == Arg::STRING)
587 s = arg.s_ ? arg.s_ : "<NULL>";
588 else if (arg.type_ == Arg::INT && arg.width_ == sizeof(void *) &&
589 arg.i_ == 0) { // Allow C++'s version of NULL
590 s = "<NULL>";
591 } else {
592 DEBUG_CHECK(arg.type_ == Arg::STRING);
593 goto fail_to_expand;
594 }
595
596 // Apply padding, if needed. This requires us to first check the
597 // length of the string that we are outputting.
598 if (padding) {
599 size_t len = 0;
600 for (const char* src = s; *src++; ) {
601 ++len;
602 }
603 buffer.Pad(' ', padding, len);
604 }
605
606 // Printing a string involves nothing more than copying it into the
607 // output buffer and making sure we don't output more bytes than
608 // available space; Out() takes care of doing that.
609 for (const char* src = s; *src; ) {
610 buffer.Out(*src++);
611 }
612 break; }
613 case '%':
614 // Quoted percent '%' character.
615 goto copy_verbatim;
616 fail_to_expand:
617 // C++ gives us tools to do type checking -- something that snprintf()
618 // could never really do. So, whenever we see arguments that don't
619 // match up with the format string, we refuse to output them. But
620 // since we have to be extremely conservative about being async-
621 // signal-safe, we are limited in the type of error handling that we
622 // can do in production builds (in debug builds we can use
623 // DEBUG_CHECK() and hope for the best). So, all we do is pass the
624 // format string unchanged. That should eventually get the user's
625 // attention; and in the meantime, it hopefully doesn't lose too much
626 // data.
627 default:
628 // Unknown or unsupported format character. Just copy verbatim to
629 // output.
630 buffer.Out('%');
631 DEBUG_CHECK(ch);
632 if (!ch) {
633 goto end_of_format_string;
634 }
635 buffer.Out(ch);
636 break;
637 }
638 } else {
639 copy_verbatim:
640 buffer.Out(fmt[-1]);
641 }
642 }
643 end_of_format_string:
644 end_of_output_buffer:
645 return buffer.GetCount();
646 }
647
648 ssize_t FormatN(char* buf, size_t sz, const char* fmt) {
649 // Make sure that at least one NUL byte can be written, and that the buffer
650 // never overflows kSSizeMax. Not only does that use up most or all of the
651 // address space, it also would result in a return code that cannot be
652 // represented.
653 if (static_cast<ssize_t>(sz) < 1) {
654 return -1;
655 } else if (sz > kSSizeMax) {
656 sz = kSSizeMax;
657 }
658
659 Buffer buffer(buf, sz);
660
661 // In the slow-path, we deal with errors by copying the contents of
662 // "fmt" unexpanded. This means, if there are no arguments passed, the
663 // Format() function always degenerates to a version of strncpy() that
664 // de-duplicates '%' characters.
665 const char* src = fmt;
666 for (; *src; ++src) {
667 buffer.Out(*src);
668 DEBUG_CHECK(src[0] != '%' || src[1] == '%');
669 if (src[0] == '%' && src[1] == '%') {
670 ++src;
671 }
672 }
673 return buffer.GetCount();
674 }
675
676 } // namespace debug
677 } // namespace base
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698