• 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 #ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_SRC_PARTITION_ALLOC_PARTITION_ALLOC_BASE_STRINGS_SAFE_SPRINTF_H_
6 #define BASE_ALLOCATOR_PARTITION_ALLOCATOR_SRC_PARTITION_ALLOC_PARTITION_ALLOC_BASE_STRINGS_SAFE_SPRINTF_H_
7 
8 #include <stdint.h>
9 #include <stdlib.h>
10 
11 #include <cstddef>
12 
13 #include "build/build_config.h"
14 
15 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
16 // For ssize_t
17 #include <unistd.h>
18 #endif
19 
20 #include "partition_alloc/partition_alloc_base/component_export.h"
21 
22 namespace partition_alloc::internal::base::strings {
23 
24 #if defined(COMPILER_MSVC)
25 // Define ssize_t inside of our namespace.
26 #if defined(_WIN64)
27 typedef __int64 ssize_t;
28 #else
29 typedef long ssize_t;
30 #endif
31 #endif
32 
33 // SafeSPrintf() is a type-safe and completely self-contained version of
34 // snprintf().
35 //
36 // SafeSNPrintf() is an alternative function signature that can be used when
37 // not dealing with fixed-sized buffers. When possible, SafeSPrintf() should
38 // always be used instead of SafeSNPrintf()
39 //
40 // These functions allow for formatting complicated messages from contexts that
41 // require strict async-signal-safety. In fact, it is safe to call them from
42 // any low-level execution context, as they are guaranteed to make no library
43 // or system calls. It deliberately never touches "errno", either.
44 //
45 // The only exception to this rule is that in debug builds the code calls
46 // RAW_CHECK() to help diagnose problems when the format string does not
47 // match the rest of the arguments. In release builds, no CHECK()s are used,
48 // and SafeSPrintf() instead returns an output string that expands only
49 // those arguments that match their format characters. Mismatched arguments
50 // are ignored.
51 //
52 // The code currently only supports a subset of format characters:
53 //   %c, %o, %d, %x, %X, %p, and %s.
54 //
55 // SafeSPrintf() aims to be as liberal as reasonably possible. Integer-like
56 // values of arbitrary width can be passed to all of the format characters
57 // that expect integers. Thus, it is explicitly legal to pass an "int" to
58 // "%c", and output will automatically look at the LSB only. It is also
59 // explicitly legal to pass either signed or unsigned values, and the format
60 // characters will automatically interpret the arguments accordingly.
61 //
62 // It is still not legal to mix-and-match integer-like values with pointer
63 // values. For instance, you cannot pass a pointer to %x, nor can you pass an
64 // integer to %p.
65 //
66 // The one exception is "0" zero being accepted by "%p". This works-around
67 // the problem of C++ defining NULL as an integer-like value.
68 //
69 // All format characters take an optional width parameter. This must be a
70 // positive integer. For %d, %o, %x, %X and %p, if the width starts with
71 // a leading '0', padding is done with '0' instead of ' ' characters.
72 //
73 // There are a few features of snprintf()-style format strings, that
74 // SafeSPrintf() does not support at this time.
75 //
76 // If an actual user showed up, there is no particularly strong reason they
77 // couldn't be added. But that assumes that the trade-offs between complexity
78 // and utility are favorable.
79 //
80 // For example, adding support for negative padding widths, and for %n are all
81 // likely to be viewed positively. They are all clearly useful, low-risk, easy
82 // to test, don't jeopardize the async-signal-safety of the code, and overall
83 // have little impact on other parts of SafeSPrintf() function.
84 //
85 // On the other hands, adding support for alternate forms, positional
86 // arguments, grouping, wide characters, localization or floating point numbers
87 // are all unlikely to ever be added.
88 //
89 // SafeSPrintf() and SafeSNPrintf() mimic the behavior of snprintf() and they
90 // return the number of bytes needed to store the untruncated output. This
91 // does *not* include the terminating NUL byte.
92 //
93 // They return -1, iff a fatal error happened. This typically can only happen,
94 // if the buffer size is a) negative, or b) zero (i.e. not even the NUL byte
95 // can be written). The return value can never be larger than SSIZE_MAX-1.
96 // This ensures that the caller can always add one to the signed return code
97 // in order to determine the amount of storage that needs to be allocated.
98 //
99 // While the code supports type checking and while it is generally very careful
100 // to avoid printing incorrect values, it tends to be conservative in printing
101 // as much as possible, even when given incorrect parameters. Typically, in
102 // case of an error, the format string will not be expanded. (i.e. something
103 // like SafeSPrintf(buf, "%p %d", 1, 2) results in "%p 2"). See above for
104 // the use of RAW_CHECK() in debug builds, though.
105 //
106 // Basic example:
107 //   char buf[20];
108 //   base::strings::SafeSPrintf(buf, "The answer: %2d", 42);
109 //
110 // Example with dynamically sized buffer (async-signal-safe). This code won't
111 // work on Visual studio, as it requires dynamically allocating arrays on the
112 // stack. Consider picking a smaller value for |kMaxSize| if stack size is
113 // limited and known. On the other hand, if the parameters to SafeSNPrintf()
114 // are trusted and not controllable by the user, you can consider eliminating
115 // the check for |kMaxSize| altogether. The current value of SSIZE_MAX is
116 // essentially a no-op that just illustrates how to implement an upper bound:
117 //   const size_t kInitialSize = 128;
118 //   const size_t kMaxSize = std::numeric_limits<ssize_t>::max();
119 //   size_t size = kInitialSize;
120 //   for (;;) {
121 //     char buf[size];
122 //     size = SafeSNPrintf(buf, size, "Error message \"%s\"\n", err) + 1;
123 //     if (sizeof(buf) < kMaxSize && size > kMaxSize) {
124 //       size = kMaxSize;
125 //       continue;
126 //     } else if (size > sizeof(buf))
127 //       continue;
128 //     write(2, buf, size-1);
129 //     break;
130 //   }
131 
132 namespace internal {
133 // Helpers that use C++ overloading, templates, and specializations to deduce
134 // and record type information from function arguments. This allows us to
135 // later write a type-safe version of snprintf().
136 
137 struct Arg {
138   enum Type { INT, UINT, STRING, POINTER };
139 
140   // Any integer-like value.
ArgArg141   Arg(signed char c) : type(INT) {
142     integer.i = c;
143     integer.width = sizeof(char);
144   }
ArgArg145   Arg(unsigned char c) : type(UINT) {
146     integer.i = c;
147     integer.width = sizeof(char);
148   }
ArgArg149   Arg(signed short j) : type(INT) {
150     integer.i = j;
151     integer.width = sizeof(short);
152   }
ArgArg153   Arg(unsigned short j) : type(UINT) {
154     integer.i = j;
155     integer.width = sizeof(short);
156   }
ArgArg157   Arg(signed int j) : type(INT) {
158     integer.i = j;
159     integer.width = sizeof(int);
160   }
ArgArg161   Arg(unsigned int j) : type(UINT) {
162     integer.i = j;
163     integer.width = sizeof(int);
164   }
ArgArg165   Arg(signed long j) : type(INT) {
166     integer.i = j;
167     integer.width = sizeof(long);
168   }
ArgArg169   Arg(unsigned long j) : type(UINT) {
170     integer.i = static_cast<int64_t>(j);
171     integer.width = sizeof(long);
172   }
ArgArg173   Arg(signed long long j) : type(INT) {
174     integer.i = j;
175     integer.width = sizeof(long long);
176   }
ArgArg177   Arg(unsigned long long j) : type(UINT) {
178     integer.i = static_cast<int64_t>(j);
179     integer.width = sizeof(long long);
180   }
181 
182   // std::nullptr_t would be ambiguous between char* and const char*; to get
183   // consistent behavior with NULL, which prints with all three of %d, %p, and
184   // %s, treat it as an integer zero internally.
185   //
186   // Warning: don't just do Arg(NULL) here because in some libcs, NULL is an
187   // alias for std::nullptr!
188   //
189   // NOLINTNEXTLINE(runtime/explicit)
ArgArg190   Arg(std::nullptr_t p) : type(INT) {
191     integer.i = 0;
192     // Internally, SafeSprintf expects to represent nulls as integers whose
193     // width is equal to sizeof(NULL), which is not necessarily equal to
194     // sizeof(std::nullptr_t) - eg, on Windows, NULL is defined to 0 (with size
195     // 4) while std::nullptr_t is of size 8.
196     integer.width = sizeof(NULL);
197   }
198 
199   // A C-style text string.
ArgArg200   Arg(const char* s) : str(s), type(STRING) {}
ArgArg201   Arg(char* s) : str(s), type(STRING) {}
202 
203   // Any pointer value that can be cast to a "void*".
204   template <class T>
ArgArg205   Arg(T* p) : ptr((void*)p), type(POINTER) {}
206 
207   struct Integer {
208     int64_t i;
209     unsigned char width;
210   };
211 
212   union {
213     // An integer-like value.
214     Integer integer;
215 
216     // A C-style text string.
217     const char* str;
218 
219     // A pointer to an arbitrary object.
220     const void* ptr;
221   };
222   const enum Type type;
223 };
224 
225 // This is the internal function that performs the actual formatting of
226 // an snprintf()-style format string.
227 PA_COMPONENT_EXPORT(PARTITION_ALLOC_BASE)
228 ssize_t SafeSNPrintf(char* buf,
229                      size_t sz,
230                      const char* fmt,
231                      const Arg* args,
232                      size_t max_args);
233 
234 #if !defined(NDEBUG)
235 // In debug builds, allow unit tests to artificially lower the kSSizeMax
236 // constant that is used as a hard upper-bound for all buffers. In normal
237 // use, this constant should always be std::numeric_limits<ssize_t>::max().
238 PA_COMPONENT_EXPORT(PARTITION_ALLOC_BASE)
239 void SetSafeSPrintfSSizeMaxForTest(size_t max);
240 PA_COMPONENT_EXPORT(PARTITION_ALLOC_BASE)
241 size_t GetSafeSPrintfSSizeMaxForTest();
242 #endif
243 
244 }  // namespace internal
245 
246 template <typename... Args>
SafeSNPrintf(char * buf,size_t N,const char * fmt,Args...args)247 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt, Args... args) {
248   // Use Arg() object to record type information and then copy arguments to an
249   // array to make it easier to iterate over them.
250   const internal::Arg arg_array[] = {args...};
251   return internal::SafeSNPrintf(buf, N, fmt, arg_array, sizeof...(args));
252 }
253 
254 template <size_t N, typename... Args>
SafeSPrintf(char (& buf)[N],const char * fmt,Args...args)255 ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, Args... args) {
256   // Use Arg() object to record type information and then copy arguments to an
257   // array to make it easier to iterate over them.
258   const internal::Arg arg_array[] = {args...};
259   return internal::SafeSNPrintf(buf, N, fmt, arg_array, sizeof...(args));
260 }
261 
262 // Fast-path when we don't actually need to substitute any arguments.
263 PA_COMPONENT_EXPORT(PARTITION_ALLOC_BASE)
264 ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt);
265 template <size_t N>
SafeSPrintf(char (& buf)[N],const char * fmt)266 inline ssize_t SafeSPrintf(char (&buf)[N], const char* fmt) {
267   return SafeSNPrintf(buf, N, fmt);
268 }
269 
270 }  // namespace partition_alloc::internal::base::strings
271 
272 #endif  // BASE_ALLOCATOR_PARTITION_ALLOCATOR_SRC_PARTITION_ALLOC_PARTITION_ALLOC_BASE_STRINGS_SAFE_SPRINTF_H_
273