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