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