| File: | root/firefox-clang/security/sandbox/chromium/base/strings/safe_sprintf.cc |
| Warning: | line 501, column 15 Value stored to 'padding' is never read |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
| 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 "base/strings/safe_sprintf.h" |
| 6 | |
| 7 | #include <errno(*__errno_location ()).h> |
| 8 | #include <string.h> |
| 9 | |
| 10 | #include <algorithm> |
| 11 | #include <limits> |
| 12 | |
| 13 | #include "base/compiler_specific.h" |
| 14 | #include "base/memory/raw_ptr.h" |
| 15 | #include "build/build_config.h" |
| 16 | |
| 17 | #if !defined(NDEBUG1) |
| 18 | // In debug builds, we use RAW_CHECK() to print useful error messages, if |
| 19 | // SafeSPrintf() is called with broken arguments. |
| 20 | // As our contract promises that SafeSPrintf() can be called from any |
| 21 | // restricted run-time context, it is not actually safe to call logging |
| 22 | // functions from it; and we only ever do so for debug builds and hope for the |
| 23 | // best. We should _never_ call any logging function other than RAW_CHECK(), |
| 24 | // and we should _never_ include any logging code that is active in production |
| 25 | // builds. Most notably, we should not include these logging functions in |
| 26 | // unofficial release builds, even though those builds would otherwise have |
| 27 | // DCHECKS() enabled. |
| 28 | // In other words; please do not remove the #ifdef around this #include. |
| 29 | // Instead, in production builds we opt for returning a degraded result, |
| 30 | // whenever an error is encountered. |
| 31 | // E.g. The broken function call |
| 32 | // SafeSPrintf("errno = %d (%x)", errno, strerror(errno)) |
| 33 | // will print something like |
| 34 | // errno = 13, (%x) |
| 35 | // instead of |
| 36 | // errno = 13 (Access denied) |
| 37 | // In most of the anticipated use cases, that's probably the preferred |
| 38 | // behavior. |
| 39 | #include "base/check.h" |
| 40 | #define DEBUG_CHECK RAW_CHECK |
| 41 | #else |
| 42 | #define DEBUG_CHECK(x)do { if (x) { } } while (0) \ |
| 43 | do { \ |
| 44 | if (x) { \ |
| 45 | } \ |
| 46 | } while (0) |
| 47 | #endif |
| 48 | |
| 49 | namespace base::strings { |
| 50 | |
| 51 | // The code in this file is extremely careful to be async-signal-safe. |
| 52 | // |
| 53 | // Most obviously, we avoid calling any code that could dynamically allocate |
| 54 | // memory. Doing so would almost certainly result in bugs and dead-locks. |
| 55 | // We also avoid calling any other STL functions that could have unintended |
| 56 | // side-effects involving memory allocation or access to other shared |
| 57 | // resources. |
| 58 | // |
| 59 | // But on top of that, we also avoid calling other library functions, as many |
| 60 | // of them have the side-effect of calling getenv() (in order to deal with |
| 61 | // localization) or accessing errno. The latter sounds benign, but there are |
| 62 | // several execution contexts where it isn't even possible to safely read let |
| 63 | // alone write errno. |
| 64 | // |
| 65 | // The stated design goal of the SafeSPrintf() function is that it can be |
| 66 | // called from any context that can safely call C or C++ code (i.e. anything |
| 67 | // that doesn't require assembly code). |
| 68 | // |
| 69 | // For a brief overview of some but not all of the issues with async-signal- |
| 70 | // safety, refer to: |
| 71 | // http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html |
| 72 | |
| 73 | namespace { |
| 74 | const size_t kSSizeMaxConst = ((size_t)(ssize_t)-1) >> 1; |
| 75 | |
| 76 | const char kUpCaseHexDigits[] = "0123456789ABCDEF"; |
| 77 | const char kDownCaseHexDigits[] = "0123456789abcdef"; |
| 78 | } // namespace |
| 79 | |
| 80 | #if defined(NDEBUG1) |
| 81 | // We would like to define kSSizeMax as std::numeric_limits<ssize_t>::max(), |
| 82 | // but C++ doesn't allow us to do that for constants. Instead, we have to |
| 83 | // use careful casting and shifting. We later use a static_assert to |
| 84 | // verify that this worked correctly. |
| 85 | namespace { |
| 86 | const size_t kSSizeMax = kSSizeMaxConst; |
| 87 | } |
| 88 | #else // defined(NDEBUG) |
| 89 | // For efficiency, we really need kSSizeMax to be a constant. But for unit |
| 90 | // tests, it should be adjustable. This allows us to verify edge cases without |
| 91 | // having to fill the entire available address space. As a compromise, we make |
| 92 | // kSSizeMax adjustable in debug builds, and then only compile that particular |
| 93 | // part of the unit test in debug builds. |
| 94 | namespace { |
| 95 | static size_t kSSizeMax = kSSizeMaxConst; |
| 96 | } |
| 97 | |
| 98 | namespace internal { |
| 99 | void SetSafeSPrintfSSizeMaxForTest(size_t max) { |
| 100 | kSSizeMax = max; |
| 101 | } |
| 102 | |
| 103 | size_t GetSafeSPrintfSSizeMaxForTest() { |
| 104 | return kSSizeMax; |
| 105 | } |
| 106 | } // namespace internal |
| 107 | #endif // defined(NDEBUG) |
| 108 | |
| 109 | namespace { |
| 110 | class Buffer { |
| 111 | public: |
| 112 | // |buffer| is caller-allocated storage that SafeSPrintf() writes to. It |
| 113 | // has |size| bytes of writable storage. It is the caller's responsibility |
| 114 | // to ensure that the buffer is at least one byte in size, so that it fits |
| 115 | // the trailing NUL that will be added by the destructor. The buffer also |
| 116 | // must be smaller or equal to kSSizeMax in size. |
| 117 | Buffer(char* buffer, size_t size) : buffer_(buffer), size_(size - 1) { |
| 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 __cplusplus202002L >= 201103 && !(defined(__clang__1) && BUILDFLAG(IS_WIN)((0))) |
| 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)do { if (size > 0) { } } while (0); |
| 127 | DEBUG_CHECK(size <= kSSizeMax)do { if (size <= kSSizeMax) { } } while (0); |
| 128 | } |
| 129 | |
| 130 | Buffer(const Buffer&) = delete; |
| 131 | Buffer& operator=(const Buffer&) = delete; |
| 132 | |
| 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. |
| 146 | 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|. |
| 154 | inline ssize_t GetCount() const { |
| 155 | DEBUG_CHECK(count_ < kSSizeMax)do { if (count_ < kSSizeMax) { } } while (0); |
| 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_|. |
| 165 | inline bool Out(char ch) { |
| 166 | if (size_ >= 1 && count_ < size_) { |
| 167 | UNSAFE_TODO(buffer_[count_] = ch)clang unsafe_buffer_usage begin
buffer_[count_] = ch clang unsafe_buffer_usage end ; |
| 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. |
| 183 | inline bool Pad(char pad, size_t padding, size_t len) { |
| 184 | DEBUG_CHECK(pad)do { if (pad) { } } while (0); |
| 185 | DEBUG_CHECK(padding <= kSSizeMax)do { if (padding <= kSSizeMax) { } } while (0); |
| 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|. |
| 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)do { if (inc <= kSSizeMax - 1) { } } while (0); |
| 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. |
| 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_|. |
| 261 | inline char* GetInsertionPoint() const { |
| 262 | size_t idx = count_; |
| 263 | if (idx > size_) { |
| 264 | idx = size_; |
| 265 | } |
| 266 | // SAFETY: idx checked against size_ above. |
| 267 | return UNSAFE_BUFFERS(buffer_ + idx)clang unsafe_buffer_usage begin
buffer_ + idx clang unsafe_buffer_usage end ; |
| 268 | } |
| 269 | |
| 270 | // User-provided buffer that will receive the fully formatted output string. |
| 271 | raw_ptr<char, AllowPtrArithmetic> 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_ = 0; |
| 281 | }; |
| 282 | |
| 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)do { if (base >= 2) { } } while (0); |
| 293 | DEBUG_CHECK(base <= 16)do { if (base <= 16) { } } while (0); |
| 294 | DEBUG_CHECK(!sign || base == 10)do { if (!sign || base == 10) { } } while (0); |
| 295 | DEBUG_CHECK(pad == '0' || pad == ' ')do { if (pad == '0' || pad == ' ') { } } while (0); |
| 296 | DEBUG_CHECK(padding <= kSSizeMax)do { if (padding <= kSSizeMax) { } } while (0); |
| 297 | DEBUG_CHECK(!(sign && prefix && *prefix))do { if (!(sign && prefix && *prefix)) { } } while (0); |
| 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 | UNSAFE_TODO(Out(*prefix++))clang unsafe_buffer_usage begin
Out(*prefix++) clang unsafe_buffer_usage end ; |
| 339 | } |
| 340 | prefix = nullptr; |
| 341 | } else { |
| 342 | for (reverse_prefix = prefix; *reverse_prefix; |
| 343 | UNSAFE_TODO(++reverse_prefix)clang unsafe_buffer_usage begin
++reverse_prefix clang unsafe_buffer_usage end ) { |
| 344 | } |
| 345 | } |
| 346 | } else { |
| 347 | prefix = nullptr; |
| 348 | } |
| 349 | const size_t prefix_length = static_cast<size_t>(reverse_prefix - prefix); |
| 350 | |
| 351 | // Loop until we have converted the entire number. Output at least one |
| 352 | // character (i.e. '0'). |
| 353 | size_t start = count_; |
| 354 | size_t discarded = 0; |
| 355 | bool started = false; |
| 356 | do { |
| 357 | // Make sure there is still enough space left in our output buffer. |
| 358 | if (count_ >= size_) { |
| 359 | if (start < size_) { |
| 360 | // It is rare that we need to output a partial number. But if asked |
| 361 | // to do so, we will still make sure we output the correct number of |
| 362 | // leading digits. |
| 363 | // Since we are generating the digits in reverse order, we actually |
| 364 | // have to discard digits in the order that we have already emitted |
| 365 | // them. This is essentially equivalent to: |
| 366 | // memmove(buffer_ + start, buffer_ + start + 1, size_ - start - 1) |
| 367 | // SAFETY: start checked against size_ above. |
| 368 | for (char *move = UNSAFE_BUFFERS(buffer_ + start)clang unsafe_buffer_usage begin
buffer_ + start clang unsafe_buffer_usage end , |
| 369 | *end = UNSAFE_BUFFERS(buffer_ + size_ - 1)clang unsafe_buffer_usage begin
buffer_ + size_ - 1 clang unsafe_buffer_usage end ; |
| 370 | move < end; UNSAFE_TODO(++move)clang unsafe_buffer_usage begin
++move clang unsafe_buffer_usage end ) { |
| 371 | *move = UNSAFE_TODO(move[1])clang unsafe_buffer_usage begin
move[1] clang unsafe_buffer_usage end ; |
| 372 | } |
| 373 | ++discarded; |
| 374 | --count_; |
| 375 | } else if (count_ - size_ > 1) { |
| 376 | // Need to increment either |count_| or |discarded| to make progress. |
| 377 | // The latter is more efficient, as it eventually triggers fast |
| 378 | // handling of padding. But we have to ensure we don't accidentally |
| 379 | // change the overall state (i.e. switch the state-machine from |
| 380 | // discarding to non-discarding). |count_| needs to always stay |
| 381 | // bigger than |size_|. |
| 382 | --count_; |
| 383 | ++discarded; |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | // Output the next digit and (if necessary) compensate for the most |
| 388 | // negative integer needing special treatment. This works because, |
| 389 | // no matter the bit width of the integer, the lowest-most decimal |
| 390 | // integer always ends in 2, 4, 6, or 8. |
| 391 | if (!num && started) { |
| 392 | if (reverse_prefix > prefix) { |
| 393 | UNSAFE_TODO(Out(*--reverse_prefix))clang unsafe_buffer_usage begin
Out(*--reverse_prefix) clang unsafe_buffer_usage end ; |
| 394 | } else { |
| 395 | Out(pad); |
| 396 | } |
| 397 | } else { |
| 398 | started = true; |
| 399 | UNSAFE_TODO(Out((upcase ? kUpCaseHexDigitsclang unsafe_buffer_usage begin
Out((upcase ? kUpCaseHexDigits : kDownCaseHexDigits)[num % base + minint]) clang unsafe_buffer_usage end |
| 400 | : kDownCaseHexDigits)[num % base + minint]))clang unsafe_buffer_usage begin
Out((upcase ? kUpCaseHexDigits : kDownCaseHexDigits)[num % base + minint]) clang unsafe_buffer_usage end ; |
| 401 | } |
| 402 | |
| 403 | minint = 0; |
| 404 | num /= base; |
| 405 | |
| 406 | // Add padding, if requested. |
| 407 | if (padding > 0) { |
| 408 | --padding; |
| 409 | |
| 410 | // Performance optimization for when we are asked to output excessive |
| 411 | // padding, but our output buffer is limited in size. Even if we output |
| 412 | // a 64bit number in binary, we would never write more than 64 plus |
| 413 | // prefix non-padding characters. So, once this limit has been passed, |
| 414 | // any further state change can be computed arithmetically; we know that |
| 415 | // by this time, our entire final output consists of padding characters |
| 416 | // that have all already been output. |
| 417 | if (discarded > 8 * sizeof(num) + prefix_length) { |
| 418 | IncrementCount(padding); |
| 419 | padding = 0; |
| 420 | } |
| 421 | } |
| 422 | } while (num || padding || (reverse_prefix > prefix)); |
| 423 | |
| 424 | if (start < size_) { |
| 425 | // Conversion to ASCII actually resulted in the digits being in reverse |
| 426 | // order. We can't easily generate them in forward order, as we can't tell |
| 427 | // the number of characters needed until we are done converting. |
| 428 | // So, now, we reverse the string (except for the possible '-' sign). |
| 429 | // SAFETY: start checked against size_ above. |
| 430 | char* front = UNSAFE_BUFFERS(buffer_ + start)clang unsafe_buffer_usage begin
buffer_ + start clang unsafe_buffer_usage end ; |
| 431 | char* back = GetInsertionPoint(); |
| 432 | UNSAFE_TODO({clang unsafe_buffer_usage begin
{ while (--back > front) { char ch = *back; *back = *front; *front++ = ch; } } clang unsafe_buffer_usage end |
| 433 | while (--back > front) {clang unsafe_buffer_usage begin
{ while (--back > front) { char ch = *back; *back = *front; *front++ = ch; } } clang unsafe_buffer_usage end |
| 434 | char ch = *back;clang unsafe_buffer_usage begin
{ while (--back > front) { char ch = *back; *back = *front; *front++ = ch; } } clang unsafe_buffer_usage end |
| 435 | *back = *front;clang unsafe_buffer_usage begin
{ while (--back > front) { char ch = *back; *back = *front; *front++ = ch; } } clang unsafe_buffer_usage end |
| 436 | *front++ = ch;clang unsafe_buffer_usage begin
{ while (--back > front) { char ch = *back; *back = *front; *front++ = ch; } } clang unsafe_buffer_usage end |
| 437 | }clang unsafe_buffer_usage begin
{ while (--back > front) { char ch = *back; *back = *front; *front++ = ch; } } clang unsafe_buffer_usage end |
| 438 | })clang unsafe_buffer_usage begin
{ while (--back > front) { char ch = *back; *back = *front; *front++ = ch; } } clang unsafe_buffer_usage end ; |
| 439 | } |
| 440 | IncrementCount(discarded); |
| 441 | return !discarded; |
| 442 | } |
| 443 | |
| 444 | } // anonymous namespace |
| 445 | |
| 446 | namespace internal { |
| 447 | |
| 448 | ssize_t SafeSNPrintf(char* buf, |
| 449 | size_t sz, |
| 450 | const char* fmt, |
| 451 | const Arg* args, |
| 452 | const size_t max_args) { |
| 453 | // Make sure that at least one NUL byte can be written, and that the buffer |
| 454 | // never overflows kSSizeMax. Not only does that use up most or all of the |
| 455 | // address space, it also would result in a return code that cannot be |
| 456 | // represented. |
| 457 | if (static_cast<ssize_t>(sz) < 1) { |
| 458 | return -1; |
| 459 | } |
| 460 | sz = std::min(sz, kSSizeMax); |
| 461 | |
| 462 | // Iterate over format string and interpret '%' arguments as they are |
| 463 | // encountered. |
| 464 | Buffer buffer(buf, sz); |
| 465 | size_t padding; |
| 466 | char pad; |
| 467 | for (unsigned int cur_arg = 0; *fmt && !buffer.OutOfAddressableSpace();) { |
| 468 | if (UNSAFE_TODO(*fmt++)clang unsafe_buffer_usage begin
*fmt++ clang unsafe_buffer_usage end == '%') { |
| 469 | padding = 0; |
| 470 | pad = ' '; |
| 471 | char ch = UNSAFE_TODO(*fmt++)clang unsafe_buffer_usage begin
*fmt++ clang unsafe_buffer_usage end ; |
| 472 | format_character_found: |
| 473 | switch (ch) { |
| 474 | case '0': |
| 475 | case '1': |
| 476 | case '2': |
| 477 | case '3': |
| 478 | case '4': |
| 479 | case '5': |
| 480 | case '6': |
| 481 | case '7': |
| 482 | case '8': |
| 483 | case '9': |
| 484 | // Found a width parameter. Convert to an integer value and store in |
| 485 | // "padding". If the leading digit is a zero, change the padding |
| 486 | // character from a space ' ' to a zero '0'. |
| 487 | pad = ch == '0' ? '0' : ' '; |
| 488 | for (;;) { |
| 489 | const size_t digit = static_cast<size_t>(ch - '0'); |
| 490 | // The maximum allowed padding fills all the available address |
| 491 | // space and leaves just enough space to insert the trailing NUL. |
| 492 | const size_t max_padding = kSSizeMax - 1; |
| 493 | if (padding > max_padding / 10 || |
| 494 | 10 * padding > max_padding - digit) { |
| 495 | DEBUG_CHECK(padding <= max_padding / 10 &&do { if (padding <= max_padding / 10 && 10 * padding <= max_padding - digit) { } } while (0) |
| 496 | 10 * padding <= max_padding - digit)do { if (padding <= max_padding / 10 && 10 * padding <= max_padding - digit) { } } while (0); |
| 497 | // Integer overflow detected. Skip the rest of the width until |
| 498 | // we find the format character, then do the normal error |
| 499 | // handling. |
| 500 | padding_overflow: |
| 501 | padding = max_padding; |
Value stored to 'padding' is never read | |
| 502 | while ((ch = UNSAFE_TODO(*fmt++)clang unsafe_buffer_usage begin
*fmt++ clang unsafe_buffer_usage end ) >= '0' && ch <= '9') { |
| 503 | } |
| 504 | if (cur_arg < max_args) { |
| 505 | ++cur_arg; |
| 506 | } |
| 507 | goto fail_to_expand; |
| 508 | } |
| 509 | padding = 10 * padding + digit; |
| 510 | if (padding > max_padding) { |
| 511 | // This doesn't happen for "sane" values of kSSizeMax. But once |
| 512 | // kSSizeMax gets smaller than about 10, our earlier range checks |
| 513 | // are incomplete. Unittests do trigger this artificial corner |
| 514 | // case. |
| 515 | DEBUG_CHECK(padding <= max_padding)do { if (padding <= max_padding) { } } while (0); |
| 516 | goto padding_overflow; |
| 517 | } |
| 518 | ch = UNSAFE_TODO(*fmt++)clang unsafe_buffer_usage begin
*fmt++ clang unsafe_buffer_usage end ; |
| 519 | if (ch < '0' || ch > '9') { |
| 520 | // Reached the end of the width parameter. This is where the |
| 521 | // format character is found. |
| 522 | goto format_character_found; |
| 523 | } |
| 524 | } |
| 525 | case 'c': { // Output an ASCII character. |
| 526 | // Check that there are arguments left to be inserted. |
| 527 | if (cur_arg >= max_args) { |
| 528 | DEBUG_CHECK(cur_arg < max_args)do { if (cur_arg < max_args) { } } while (0); |
| 529 | goto fail_to_expand; |
| 530 | } |
| 531 | |
| 532 | // Check that the argument has the expected type. |
| 533 | const Arg& arg = UNSAFE_TODO(args[cur_arg++])clang unsafe_buffer_usage begin
args[cur_arg++] clang unsafe_buffer_usage end ; |
| 534 | if (arg.type != Arg::INT && arg.type != Arg::UINT) { |
| 535 | DEBUG_CHECK(arg.type == Arg::INT || arg.type == Arg::UINT)do { if (arg.type == Arg::INT || arg.type == Arg::UINT) { } } while (0); |
| 536 | goto fail_to_expand; |
| 537 | } |
| 538 | |
| 539 | // Apply padding, if needed. |
| 540 | buffer.Pad(' ', padding, 1); |
| 541 | |
| 542 | // Convert the argument to an ASCII character and output it. |
| 543 | char as_char = static_cast<char>(arg.integer.i); |
| 544 | if (!as_char) { |
| 545 | goto end_of_output_buffer; |
| 546 | } |
| 547 | buffer.Out(as_char); |
| 548 | break; |
| 549 | } |
| 550 | case 'd': // Output a possibly signed decimal value. |
| 551 | case 'o': // Output an unsigned octal value. |
| 552 | case 'x': // Output an unsigned hexadecimal value. |
| 553 | case 'X': |
| 554 | case 'p': { // Output a pointer value. |
| 555 | // Check that there are arguments left to be inserted. |
| 556 | if (cur_arg >= max_args) { |
| 557 | DEBUG_CHECK(cur_arg < max_args)do { if (cur_arg < max_args) { } } while (0); |
| 558 | goto fail_to_expand; |
| 559 | } |
| 560 | |
| 561 | const Arg& arg = UNSAFE_TODO(args[cur_arg++])clang unsafe_buffer_usage begin
args[cur_arg++] clang unsafe_buffer_usage end ; |
| 562 | int64_t i; |
| 563 | const char* prefix = nullptr; |
| 564 | if (ch != 'p') { |
| 565 | // Check that the argument has the expected type. |
| 566 | if (arg.type != Arg::INT && arg.type != Arg::UINT) { |
| 567 | DEBUG_CHECK(arg.type == Arg::INT || arg.type == Arg::UINT)do { if (arg.type == Arg::INT || arg.type == Arg::UINT) { } } while (0); |
| 568 | goto fail_to_expand; |
| 569 | } |
| 570 | i = arg.integer.i; |
| 571 | |
| 572 | if (ch != 'd') { |
| 573 | // The Arg() constructor automatically performed sign expansion on |
| 574 | // signed parameters. This is great when outputting a %d decimal |
| 575 | // number, but can result in unexpected leading 0xFF bytes when |
| 576 | // outputting a %x hexadecimal number. Mask bits, if necessary. |
| 577 | // We have to do this here, instead of in the Arg() constructor, |
| 578 | // as the Arg() constructor cannot tell whether we will output a |
| 579 | // %d or a %x. Only the latter should experience masking. |
| 580 | if (arg.integer.width < sizeof(int64_t)) { |
| 581 | i &= (1LL << (8 * arg.integer.width)) - 1; |
| 582 | } |
| 583 | } |
| 584 | } else { |
| 585 | // Pointer values require an actual pointer or a string. |
| 586 | if (arg.type == Arg::POINTER) { |
| 587 | i = static_cast<int64_t>(reinterpret_cast<uintptr_t>(arg.ptr)); |
| 588 | } else if (arg.type == Arg::STRING) { |
| 589 | i = static_cast<int64_t>(reinterpret_cast<uintptr_t>(arg.str)); |
| 590 | } else if (arg.type == Arg::INT && |
| 591 | arg.integer.width == sizeof(NULL__null) && |
| 592 | arg.integer.i == 0) { // Allow C++'s version of NULL |
| 593 | i = 0; |
| 594 | } else { |
| 595 | DEBUG_CHECK(arg.type == Arg::POINTER || arg.type == Arg::STRING)do { if (arg.type == Arg::POINTER || arg.type == Arg::STRING) { } } while (0); |
| 596 | goto fail_to_expand; |
| 597 | } |
| 598 | |
| 599 | // Pointers always include the "0x" prefix. |
| 600 | prefix = "0x"; |
| 601 | } |
| 602 | |
| 603 | // Use IToASCII() to convert to ASCII representation. For decimal |
| 604 | // numbers, optionally print a sign. For hexadecimal numbers, |
| 605 | // distinguish between upper and lower case. %p addresses are always |
| 606 | // printed as upcase. Supports base 8, 10, and 16. Prints padding |
| 607 | // and/or prefixes, if so requested. |
| 608 | buffer.IToASCII(ch == 'd' && arg.type == Arg::INT, ch != 'x', i, |
| 609 | ch == 'o' ? 8 |
| 610 | : ch == 'd' ? 10 |
| 611 | : 16, |
| 612 | pad, padding, prefix); |
| 613 | break; |
| 614 | } |
| 615 | case 's': { |
| 616 | // Check that there are arguments left to be inserted. |
| 617 | if (cur_arg >= max_args) { |
| 618 | DEBUG_CHECK(cur_arg < max_args)do { if (cur_arg < max_args) { } } while (0); |
| 619 | goto fail_to_expand; |
| 620 | } |
| 621 | |
| 622 | // Check that the argument has the expected type. |
| 623 | const Arg& arg = UNSAFE_TODO(args[cur_arg++])clang unsafe_buffer_usage begin
args[cur_arg++] clang unsafe_buffer_usage end ; |
| 624 | const char* s; |
| 625 | if (arg.type == Arg::STRING) { |
| 626 | s = arg.str ? arg.str : "<NULL>"; |
| 627 | } else if (arg.type == Arg::INT && |
| 628 | arg.integer.width == sizeof(NULL__null) && |
| 629 | arg.integer.i == 0) { // Allow C++'s version of NULL |
| 630 | s = "<NULL>"; |
| 631 | } else { |
| 632 | DEBUG_CHECK(arg.type == Arg::STRING)do { if (arg.type == Arg::STRING) { } } while (0); |
| 633 | goto fail_to_expand; |
| 634 | } |
| 635 | |
| 636 | // Apply padding, if needed. This requires us to first check the |
| 637 | // length of the string that we are outputting. |
| 638 | if (padding) { |
| 639 | size_t len = 0; |
| 640 | for (const char* src = s; UNSAFE_TODO(*src++)clang unsafe_buffer_usage begin
*src++ clang unsafe_buffer_usage end ;) { |
| 641 | ++len; |
| 642 | } |
| 643 | buffer.Pad(' ', padding, len); |
| 644 | } |
| 645 | |
| 646 | // Printing a string involves nothing more than copying it into the |
| 647 | // output buffer and making sure we don't output more bytes than |
| 648 | // available space; Out() takes care of doing that. |
| 649 | for (const char* src = s; *src;) { |
| 650 | buffer.Out(UNSAFE_TODO(*src++)clang unsafe_buffer_usage begin
*src++ clang unsafe_buffer_usage end ); |
| 651 | } |
| 652 | break; |
| 653 | } |
| 654 | case '%': |
| 655 | // Quoted percent '%' character. |
| 656 | goto copy_verbatim; |
| 657 | fail_to_expand: |
| 658 | // C++ gives us tools to do type checking -- something that snprintf() |
| 659 | // could never really do. So, whenever we see arguments that don't |
| 660 | // match up with the format string, we refuse to output them. But |
| 661 | // since we have to be extremely conservative about being async- |
| 662 | // signal-safe, we are limited in the type of error handling that we |
| 663 | // can do in production builds (in debug builds we can use |
| 664 | // DEBUG_CHECK() and hope for the best). So, all we do is pass the |
| 665 | // format string unchanged. That should eventually get the user's |
| 666 | // attention; and in the meantime, it hopefully doesn't lose too much |
| 667 | // data. |
| 668 | default: |
| 669 | // Unknown or unsupported format character. Just copy verbatim to |
| 670 | // output. |
| 671 | buffer.Out('%'); |
| 672 | DEBUG_CHECK(ch)do { if (ch) { } } while (0); |
| 673 | if (!ch) { |
| 674 | goto end_of_format_string; |
| 675 | } |
| 676 | buffer.Out(ch); |
| 677 | break; |
| 678 | } |
| 679 | } else { |
| 680 | copy_verbatim: |
| 681 | buffer.Out(UNSAFE_TODO(fmt[-1])clang unsafe_buffer_usage begin
fmt[-1] clang unsafe_buffer_usage end ); |
| 682 | } |
| 683 | } |
| 684 | end_of_format_string: |
| 685 | end_of_output_buffer: |
| 686 | return buffer.GetCount(); |
| 687 | } |
| 688 | |
| 689 | } // namespace internal |
| 690 | |
| 691 | ssize_t SafeSNPrintf(char* buf, size_t sz, const char* fmt) { |
| 692 | // Make sure that at least one NUL byte can be written, and that the buffer |
| 693 | // never overflows kSSizeMax. Not only does that use up most or all of the |
| 694 | // address space, it also would result in a return code that cannot be |
| 695 | // represented. |
| 696 | if (static_cast<ssize_t>(sz) < 1) { |
| 697 | return -1; |
| 698 | } |
| 699 | sz = std::min(sz, kSSizeMax); |
| 700 | |
| 701 | Buffer buffer(buf, sz); |
| 702 | |
| 703 | // In the slow-path, we deal with errors by copying the contents of |
| 704 | // "fmt" unexpanded. This means, if there are no arguments passed, the |
| 705 | // SafeSPrintf() function always degenerates to a version of strncpy() that |
| 706 | // de-duplicates '%' characters. |
| 707 | const char* src = fmt; |
| 708 | UNSAFE_TODO({clang unsafe_buffer_usage begin
{ for (; *src; ++src) { buffer .Out(*src); do { if (src[0] != '%' || src[1] == '%') { } } while (0); if (src[0] == '%' && src[1] == '%') { ++src; } } } clang unsafe_buffer_usage end |
| 709 | for (; *src; ++src) {clang unsafe_buffer_usage begin
{ for (; *src; ++src) { buffer .Out(*src); do { if (src[0] != '%' || src[1] == '%') { } } while (0); if (src[0] == '%' && src[1] == '%') { ++src; } } } clang unsafe_buffer_usage end |
| 710 | buffer.Out(*src);clang unsafe_buffer_usage begin
{ for (; *src; ++src) { buffer .Out(*src); do { if (src[0] != '%' || src[1] == '%') { } } while (0); if (src[0] == '%' && src[1] == '%') { ++src; } } } clang unsafe_buffer_usage end |
| 711 | DEBUG_CHECK(src[0] != '%' || src[1] == '%');clang unsafe_buffer_usage begin
{ for (; *src; ++src) { buffer .Out(*src); do { if (src[0] != '%' || src[1] == '%') { } } while (0); if (src[0] == '%' && src[1] == '%') { ++src; } } } clang unsafe_buffer_usage end |
| 712 | if (src[0] == '%' && src[1] == '%') {clang unsafe_buffer_usage begin
{ for (; *src; ++src) { buffer .Out(*src); do { if (src[0] != '%' || src[1] == '%') { } } while (0); if (src[0] == '%' && src[1] == '%') { ++src; } } } clang unsafe_buffer_usage end |
| 713 | ++src;clang unsafe_buffer_usage begin
{ for (; *src; ++src) { buffer .Out(*src); do { if (src[0] != '%' || src[1] == '%') { } } while (0); if (src[0] == '%' && src[1] == '%') { ++src; } } } clang unsafe_buffer_usage end |
| 714 | }clang unsafe_buffer_usage begin
{ for (; *src; ++src) { buffer .Out(*src); do { if (src[0] != '%' || src[1] == '%') { } } while (0); if (src[0] == '%' && src[1] == '%') { ++src; } } } clang unsafe_buffer_usage end |
| 715 | }clang unsafe_buffer_usage begin
{ for (; *src; ++src) { buffer .Out(*src); do { if (src[0] != '%' || src[1] == '%') { } } while (0); if (src[0] == '%' && src[1] == '%') { ++src; } } } clang unsafe_buffer_usage end |
| 716 | })clang unsafe_buffer_usage begin
{ for (; *src; ++src) { buffer .Out(*src); do { if (src[0] != '%' || src[1] == '%') { } } while (0); if (src[0] == '%' && src[1] == '%') { ++src; } } } clang unsafe_buffer_usage end ; |
| 717 | return buffer.GetCount(); |
| 718 | } |
| 719 | |
| 720 | } // namespace base::strings |