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