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