Merge tag 'linux-watchdog-6.3-rc1' of git://www.linux-watchdog.org/linux-watchdog
[linux-block.git] / include / linux / fortify-string.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_FORTIFY_STRING_H_
3 #define _LINUX_FORTIFY_STRING_H_
4
5 #include <linux/bug.h>
6 #include <linux/const.h>
7 #include <linux/limits.h>
8
9 #define __FORTIFY_INLINE extern __always_inline __gnu_inline __overloadable
10 #define __RENAME(x) __asm__(#x)
11
12 void fortify_panic(const char *name) __noreturn __cold;
13 void __read_overflow(void) __compiletime_error("detected read beyond size of object (1st parameter)");
14 void __read_overflow2(void) __compiletime_error("detected read beyond size of object (2nd parameter)");
15 void __read_overflow2_field(size_t avail, size_t wanted) __compiletime_warning("detected read beyond size of field (2nd parameter); maybe use struct_group()?");
16 void __write_overflow(void) __compiletime_error("detected write beyond size of object (1st parameter)");
17 void __write_overflow_field(size_t avail, size_t wanted) __compiletime_warning("detected write beyond size of field (1st parameter); maybe use struct_group()?");
18
19 #define __compiletime_strlen(p)                                 \
20 ({                                                              \
21         char *__p = (char *)(p);                                \
22         size_t __ret = SIZE_MAX;                                \
23         size_t __p_size = __member_size(p);                     \
24         if (__p_size != SIZE_MAX &&                             \
25             __builtin_constant_p(*__p)) {                       \
26                 size_t __p_len = __p_size - 1;                  \
27                 if (__builtin_constant_p(__p[__p_len]) &&       \
28                     __p[__p_len] == '\0')                       \
29                         __ret = __builtin_strlen(__p);          \
30         }                                                       \
31         __ret;                                                  \
32 })
33
34 #if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
35 extern void *__underlying_memchr(const void *p, int c, __kernel_size_t size) __RENAME(memchr);
36 extern int __underlying_memcmp(const void *p, const void *q, __kernel_size_t size) __RENAME(memcmp);
37 extern void *__underlying_memcpy(void *p, const void *q, __kernel_size_t size) __RENAME(memcpy);
38 extern void *__underlying_memmove(void *p, const void *q, __kernel_size_t size) __RENAME(memmove);
39 extern void *__underlying_memset(void *p, int c, __kernel_size_t size) __RENAME(memset);
40 extern char *__underlying_strcat(char *p, const char *q) __RENAME(strcat);
41 extern char *__underlying_strcpy(char *p, const char *q) __RENAME(strcpy);
42 extern __kernel_size_t __underlying_strlen(const char *p) __RENAME(strlen);
43 extern char *__underlying_strncat(char *p, const char *q, __kernel_size_t count) __RENAME(strncat);
44 extern char *__underlying_strncpy(char *p, const char *q, __kernel_size_t size) __RENAME(strncpy);
45 #else
46
47 #if defined(__SANITIZE_MEMORY__)
48 /*
49  * For KMSAN builds all memcpy/memset/memmove calls should be replaced by the
50  * corresponding __msan_XXX functions.
51  */
52 #include <linux/kmsan_string.h>
53 #define __underlying_memcpy     __msan_memcpy
54 #define __underlying_memmove    __msan_memmove
55 #define __underlying_memset     __msan_memset
56 #else
57 #define __underlying_memcpy     __builtin_memcpy
58 #define __underlying_memmove    __builtin_memmove
59 #define __underlying_memset     __builtin_memset
60 #endif
61
62 #define __underlying_memchr     __builtin_memchr
63 #define __underlying_memcmp     __builtin_memcmp
64 #define __underlying_strcat     __builtin_strcat
65 #define __underlying_strcpy     __builtin_strcpy
66 #define __underlying_strlen     __builtin_strlen
67 #define __underlying_strncat    __builtin_strncat
68 #define __underlying_strncpy    __builtin_strncpy
69 #endif
70
71 /**
72  * unsafe_memcpy - memcpy implementation with no FORTIFY bounds checking
73  *
74  * @dst: Destination memory address to write to
75  * @src: Source memory address to read from
76  * @bytes: How many bytes to write to @dst from @src
77  * @justification: Free-form text or comment describing why the use is needed
78  *
79  * This should be used for corner cases where the compiler cannot do the
80  * right thing, or during transitions between APIs, etc. It should be used
81  * very rarely, and includes a place for justification detailing where bounds
82  * checking has happened, and why existing solutions cannot be employed.
83  */
84 #define unsafe_memcpy(dst, src, bytes, justification)           \
85         __underlying_memcpy(dst, src, bytes)
86
87 /*
88  * Clang's use of __builtin_*object_size() within inlines needs hinting via
89  * __pass_*object_size(). The preference is to only ever use type 1 (member
90  * size, rather than struct size), but there remain some stragglers using
91  * type 0 that will be converted in the future.
92  */
93 #if __has_builtin(__builtin_dynamic_object_size)
94 #define POS                     __pass_dynamic_object_size(1)
95 #define POS0                    __pass_dynamic_object_size(0)
96 #define __struct_size(p)        __builtin_dynamic_object_size(p, 0)
97 #define __member_size(p)        __builtin_dynamic_object_size(p, 1)
98 #else
99 #define POS                     __pass_object_size(1)
100 #define POS0                    __pass_object_size(0)
101 #define __struct_size(p)        __builtin_object_size(p, 0)
102 #define __member_size(p)        __builtin_object_size(p, 1)
103 #endif
104
105 #define __compiletime_lessthan(bounds, length)  (       \
106         __builtin_constant_p((bounds) < (length)) &&    \
107         (bounds) < (length)                             \
108 )
109
110 /**
111  * strncpy - Copy a string to memory with non-guaranteed NUL padding
112  *
113  * @p: pointer to destination of copy
114  * @q: pointer to NUL-terminated source string to copy
115  * @size: bytes to write at @p
116  *
117  * If strlen(@q) >= @size, the copy of @q will stop after @size bytes,
118  * and @p will NOT be NUL-terminated
119  *
120  * If strlen(@q) < @size, following the copy of @q, trailing NUL bytes
121  * will be written to @p until @size total bytes have been written.
122  *
123  * Do not use this function. While FORTIFY_SOURCE tries to avoid
124  * over-reads of @q, it cannot defend against writing unterminated
125  * results to @p. Using strncpy() remains ambiguous and fragile.
126  * Instead, please choose an alternative, so that the expectation
127  * of @p's contents is unambiguous:
128  *
129  * +--------------------+--------------------+------------+
130  * | **p** needs to be: | padded to **size** | not padded |
131  * +====================+====================+============+
132  * |     NUL-terminated | strscpy_pad()      | strscpy()  |
133  * +--------------------+--------------------+------------+
134  * | not NUL-terminated | strtomem_pad()     | strtomem() |
135  * +--------------------+--------------------+------------+
136  *
137  * Note strscpy*()'s differing return values for detecting truncation,
138  * and strtomem*()'s expectation that the destination is marked with
139  * __nonstring when it is a character array.
140  *
141  */
142 __FORTIFY_INLINE __diagnose_as(__builtin_strncpy, 1, 2, 3)
143 char *strncpy(char * const POS p, const char *q, __kernel_size_t size)
144 {
145         size_t p_size = __member_size(p);
146
147         if (__compiletime_lessthan(p_size, size))
148                 __write_overflow();
149         if (p_size < size)
150                 fortify_panic(__func__);
151         return __underlying_strncpy(p, q, size);
152 }
153
154 /**
155  * strcat - Append a string to an existing string
156  *
157  * @p: pointer to NUL-terminated string to append to
158  * @q: pointer to NUL-terminated source string to append from
159  *
160  * Do not use this function. While FORTIFY_SOURCE tries to avoid
161  * read and write overflows, this is only possible when the
162  * destination buffer size is known to the compiler. Prefer
163  * building the string with formatting, via scnprintf() or similar.
164  * At the very least, use strncat().
165  *
166  * Returns @p.
167  *
168  */
169 __FORTIFY_INLINE __diagnose_as(__builtin_strcat, 1, 2)
170 char *strcat(char * const POS p, const char *q)
171 {
172         size_t p_size = __member_size(p);
173
174         if (p_size == SIZE_MAX)
175                 return __underlying_strcat(p, q);
176         if (strlcat(p, q, p_size) >= p_size)
177                 fortify_panic(__func__);
178         return p;
179 }
180
181 extern __kernel_size_t __real_strnlen(const char *, __kernel_size_t) __RENAME(strnlen);
182 /**
183  * strnlen - Return bounded count of characters in a NUL-terminated string
184  *
185  * @p: pointer to NUL-terminated string to count.
186  * @maxlen: maximum number of characters to count.
187  *
188  * Returns number of characters in @p (NOT including the final NUL), or
189  * @maxlen, if no NUL has been found up to there.
190  *
191  */
192 __FORTIFY_INLINE __kernel_size_t strnlen(const char * const POS p, __kernel_size_t maxlen)
193 {
194         size_t p_size = __member_size(p);
195         size_t p_len = __compiletime_strlen(p);
196         size_t ret;
197
198         /* We can take compile-time actions when maxlen is const. */
199         if (__builtin_constant_p(maxlen) && p_len != SIZE_MAX) {
200                 /* If p is const, we can use its compile-time-known len. */
201                 if (maxlen >= p_size)
202                         return p_len;
203         }
204
205         /* Do not check characters beyond the end of p. */
206         ret = __real_strnlen(p, maxlen < p_size ? maxlen : p_size);
207         if (p_size <= ret && maxlen != ret)
208                 fortify_panic(__func__);
209         return ret;
210 }
211
212 /*
213  * Defined after fortified strnlen to reuse it. However, it must still be
214  * possible for strlen() to be used on compile-time strings for use in
215  * static initializers (i.e. as a constant expression).
216  */
217 /**
218  * strlen - Return count of characters in a NUL-terminated string
219  *
220  * @p: pointer to NUL-terminated string to count.
221  *
222  * Do not use this function unless the string length is known at
223  * compile-time. When @p is unterminated, this function may crash
224  * or return unexpected counts that could lead to memory content
225  * exposures. Prefer strnlen().
226  *
227  * Returns number of characters in @p (NOT including the final NUL).
228  *
229  */
230 #define strlen(p)                                                       \
231         __builtin_choose_expr(__is_constexpr(__builtin_strlen(p)),      \
232                 __builtin_strlen(p), __fortify_strlen(p))
233 __FORTIFY_INLINE __diagnose_as(__builtin_strlen, 1)
234 __kernel_size_t __fortify_strlen(const char * const POS p)
235 {
236         __kernel_size_t ret;
237         size_t p_size = __member_size(p);
238
239         /* Give up if we don't know how large p is. */
240         if (p_size == SIZE_MAX)
241                 return __underlying_strlen(p);
242         ret = strnlen(p, p_size);
243         if (p_size <= ret)
244                 fortify_panic(__func__);
245         return ret;
246 }
247
248 /* Defined after fortified strlen() to reuse it. */
249 extern size_t __real_strlcpy(char *, const char *, size_t) __RENAME(strlcpy);
250 /**
251  * strlcpy - Copy a string into another string buffer
252  *
253  * @p: pointer to destination of copy
254  * @q: pointer to NUL-terminated source string to copy
255  * @size: maximum number of bytes to write at @p
256  *
257  * If strlen(@q) >= @size, the copy of @q will be truncated at
258  * @size - 1 bytes. @p will always be NUL-terminated.
259  *
260  * Do not use this function. While FORTIFY_SOURCE tries to avoid
261  * over-reads when calculating strlen(@q), it is still possible.
262  * Prefer strscpy(), though note its different return values for
263  * detecting truncation.
264  *
265  * Returns total number of bytes written to @p, including terminating NUL.
266  *
267  */
268 __FORTIFY_INLINE size_t strlcpy(char * const POS p, const char * const POS q, size_t size)
269 {
270         size_t p_size = __member_size(p);
271         size_t q_size = __member_size(q);
272         size_t q_len;   /* Full count of source string length. */
273         size_t len;     /* Count of characters going into destination. */
274
275         if (p_size == SIZE_MAX && q_size == SIZE_MAX)
276                 return __real_strlcpy(p, q, size);
277         q_len = strlen(q);
278         len = (q_len >= size) ? size - 1 : q_len;
279         if (__builtin_constant_p(size) && __builtin_constant_p(q_len) && size) {
280                 /* Write size is always larger than destination. */
281                 if (len >= p_size)
282                         __write_overflow();
283         }
284         if (size) {
285                 if (len >= p_size)
286                         fortify_panic(__func__);
287                 __underlying_memcpy(p, q, len);
288                 p[len] = '\0';
289         }
290         return q_len;
291 }
292
293 /* Defined after fortified strnlen() to reuse it. */
294 extern ssize_t __real_strscpy(char *, const char *, size_t) __RENAME(strscpy);
295 /**
296  * strscpy - Copy a C-string into a sized buffer
297  *
298  * @p: Where to copy the string to
299  * @q: Where to copy the string from
300  * @size: Size of destination buffer
301  *
302  * Copy the source string @p, or as much of it as fits, into the destination
303  * @q buffer. The behavior is undefined if the string buffers overlap. The
304  * destination @p buffer is always NUL terminated, unless it's zero-sized.
305  *
306  * Preferred to strlcpy() since the API doesn't require reading memory
307  * from the source @q string beyond the specified @size bytes, and since
308  * the return value is easier to error-check than strlcpy()'s.
309  * In addition, the implementation is robust to the string changing out
310  * from underneath it, unlike the current strlcpy() implementation.
311  *
312  * Preferred to strncpy() since it always returns a valid string, and
313  * doesn't unnecessarily force the tail of the destination buffer to be
314  * zero padded. If padding is desired please use strscpy_pad().
315  *
316  * Returns the number of characters copied in @p (not including the
317  * trailing %NUL) or -E2BIG if @size is 0 or the copy of @q was truncated.
318  */
319 __FORTIFY_INLINE ssize_t strscpy(char * const POS p, const char * const POS q, size_t size)
320 {
321         size_t len;
322         /* Use string size rather than possible enclosing struct size. */
323         size_t p_size = __member_size(p);
324         size_t q_size = __member_size(q);
325
326         /* If we cannot get size of p and q default to call strscpy. */
327         if (p_size == SIZE_MAX && q_size == SIZE_MAX)
328                 return __real_strscpy(p, q, size);
329
330         /*
331          * If size can be known at compile time and is greater than
332          * p_size, generate a compile time write overflow error.
333          */
334         if (__compiletime_lessthan(p_size, size))
335                 __write_overflow();
336
337         /* Short-circuit for compile-time known-safe lengths. */
338         if (__compiletime_lessthan(p_size, SIZE_MAX)) {
339                 len = __compiletime_strlen(q);
340
341                 if (len < SIZE_MAX && __compiletime_lessthan(len, size)) {
342                         __underlying_memcpy(p, q, len + 1);
343                         return len;
344                 }
345         }
346
347         /*
348          * This call protects from read overflow, because len will default to q
349          * length if it smaller than size.
350          */
351         len = strnlen(q, size);
352         /*
353          * If len equals size, we will copy only size bytes which leads to
354          * -E2BIG being returned.
355          * Otherwise we will copy len + 1 because of the final '\O'.
356          */
357         len = len == size ? size : len + 1;
358
359         /*
360          * Generate a runtime write overflow error if len is greater than
361          * p_size.
362          */
363         if (len > p_size)
364                 fortify_panic(__func__);
365
366         /*
367          * We can now safely call vanilla strscpy because we are protected from:
368          * 1. Read overflow thanks to call to strnlen().
369          * 2. Write overflow thanks to above ifs.
370          */
371         return __real_strscpy(p, q, len);
372 }
373
374 /**
375  * strncat - Append a string to an existing string
376  *
377  * @p: pointer to NUL-terminated string to append to
378  * @q: pointer to source string to append from
379  * @count: Maximum bytes to read from @q
380  *
381  * Appends at most @count bytes from @q (stopping at the first
382  * NUL byte) after the NUL-terminated string at @p. @p will be
383  * NUL-terminated.
384  *
385  * Do not use this function. While FORTIFY_SOURCE tries to avoid
386  * read and write overflows, this is only possible when the sizes
387  * of @p and @q are known to the compiler. Prefer building the
388  * string with formatting, via scnprintf() or similar.
389  *
390  * Returns @p.
391  *
392  */
393 /* Defined after fortified strlen() and strnlen() to reuse them. */
394 __FORTIFY_INLINE __diagnose_as(__builtin_strncat, 1, 2, 3)
395 char *strncat(char * const POS p, const char * const POS q, __kernel_size_t count)
396 {
397         size_t p_len, copy_len;
398         size_t p_size = __member_size(p);
399         size_t q_size = __member_size(q);
400
401         if (p_size == SIZE_MAX && q_size == SIZE_MAX)
402                 return __underlying_strncat(p, q, count);
403         p_len = strlen(p);
404         copy_len = strnlen(q, count);
405         if (p_size < p_len + copy_len + 1)
406                 fortify_panic(__func__);
407         __underlying_memcpy(p + p_len, q, copy_len);
408         p[p_len + copy_len] = '\0';
409         return p;
410 }
411
412 __FORTIFY_INLINE void fortify_memset_chk(__kernel_size_t size,
413                                          const size_t p_size,
414                                          const size_t p_size_field)
415 {
416         if (__builtin_constant_p(size)) {
417                 /*
418                  * Length argument is a constant expression, so we
419                  * can perform compile-time bounds checking where
420                  * buffer sizes are also known at compile time.
421                  */
422
423                 /* Error when size is larger than enclosing struct. */
424                 if (__compiletime_lessthan(p_size_field, p_size) &&
425                     __compiletime_lessthan(p_size, size))
426                         __write_overflow();
427
428                 /* Warn when write size is larger than dest field. */
429                 if (__compiletime_lessthan(p_size_field, size))
430                         __write_overflow_field(p_size_field, size);
431         }
432         /*
433          * At this point, length argument may not be a constant expression,
434          * so run-time bounds checking can be done where buffer sizes are
435          * known. (This is not an "else" because the above checks may only
436          * be compile-time warnings, and we want to still warn for run-time
437          * overflows.)
438          */
439
440         /*
441          * Always stop accesses beyond the struct that contains the
442          * field, when the buffer's remaining size is known.
443          * (The SIZE_MAX test is to optimize away checks where the buffer
444          * lengths are unknown.)
445          */
446         if (p_size != SIZE_MAX && p_size < size)
447                 fortify_panic("memset");
448 }
449
450 #define __fortify_memset_chk(p, c, size, p_size, p_size_field) ({       \
451         size_t __fortify_size = (size_t)(size);                         \
452         fortify_memset_chk(__fortify_size, p_size, p_size_field),       \
453         __underlying_memset(p, c, __fortify_size);                      \
454 })
455
456 /*
457  * __struct_size() vs __member_size() must be captured here to avoid
458  * evaluating argument side-effects further into the macro layers.
459  */
460 #ifndef CONFIG_KMSAN
461 #define memset(p, c, s) __fortify_memset_chk(p, c, s,                   \
462                 __struct_size(p), __member_size(p))
463 #endif
464
465 /*
466  * To make sure the compiler can enforce protection against buffer overflows,
467  * memcpy(), memmove(), and memset() must not be used beyond individual
468  * struct members. If you need to copy across multiple members, please use
469  * struct_group() to create a named mirror of an anonymous struct union.
470  * (e.g. see struct sk_buff.) Read overflow checking is currently only
471  * done when a write overflow is also present, or when building with W=1.
472  *
473  * Mitigation coverage matrix
474  *                                      Bounds checking at:
475  *                                      +-------+-------+-------+-------+
476  *                                      | Compile time  |   Run time    |
477  * memcpy() argument sizes:             | write | read  | write | read  |
478  *        dest     source   length      +-------+-------+-------+-------+
479  * memcpy(known,   known,   constant)   |   y   |   y   |  n/a  |  n/a  |
480  * memcpy(known,   unknown, constant)   |   y   |   n   |  n/a  |   V   |
481  * memcpy(known,   known,   dynamic)    |   n   |   n   |   B   |   B   |
482  * memcpy(known,   unknown, dynamic)    |   n   |   n   |   B   |   V   |
483  * memcpy(unknown, known,   constant)   |   n   |   y   |   V   |  n/a  |
484  * memcpy(unknown, unknown, constant)   |   n   |   n   |   V   |   V   |
485  * memcpy(unknown, known,   dynamic)    |   n   |   n   |   V   |   B   |
486  * memcpy(unknown, unknown, dynamic)    |   n   |   n   |   V   |   V   |
487  *                                      +-------+-------+-------+-------+
488  *
489  * y = perform deterministic compile-time bounds checking
490  * n = cannot perform deterministic compile-time bounds checking
491  * n/a = no run-time bounds checking needed since compile-time deterministic
492  * B = can perform run-time bounds checking (currently unimplemented)
493  * V = vulnerable to run-time overflow (will need refactoring to solve)
494  *
495  */
496 __FORTIFY_INLINE bool fortify_memcpy_chk(__kernel_size_t size,
497                                          const size_t p_size,
498                                          const size_t q_size,
499                                          const size_t p_size_field,
500                                          const size_t q_size_field,
501                                          const char *func)
502 {
503         if (__builtin_constant_p(size)) {
504                 /*
505                  * Length argument is a constant expression, so we
506                  * can perform compile-time bounds checking where
507                  * buffer sizes are also known at compile time.
508                  */
509
510                 /* Error when size is larger than enclosing struct. */
511                 if (__compiletime_lessthan(p_size_field, p_size) &&
512                     __compiletime_lessthan(p_size, size))
513                         __write_overflow();
514                 if (__compiletime_lessthan(q_size_field, q_size) &&
515                     __compiletime_lessthan(q_size, size))
516                         __read_overflow2();
517
518                 /* Warn when write size argument larger than dest field. */
519                 if (__compiletime_lessthan(p_size_field, size))
520                         __write_overflow_field(p_size_field, size);
521                 /*
522                  * Warn for source field over-read when building with W=1
523                  * or when an over-write happened, so both can be fixed at
524                  * the same time.
525                  */
526                 if ((IS_ENABLED(KBUILD_EXTRA_WARN1) ||
527                      __compiletime_lessthan(p_size_field, size)) &&
528                     __compiletime_lessthan(q_size_field, size))
529                         __read_overflow2_field(q_size_field, size);
530         }
531         /*
532          * At this point, length argument may not be a constant expression,
533          * so run-time bounds checking can be done where buffer sizes are
534          * known. (This is not an "else" because the above checks may only
535          * be compile-time warnings, and we want to still warn for run-time
536          * overflows.)
537          */
538
539         /*
540          * Always stop accesses beyond the struct that contains the
541          * field, when the buffer's remaining size is known.
542          * (The SIZE_MAX test is to optimize away checks where the buffer
543          * lengths are unknown.)
544          */
545         if ((p_size != SIZE_MAX && p_size < size) ||
546             (q_size != SIZE_MAX && q_size < size))
547                 fortify_panic(func);
548
549         /*
550          * Warn when writing beyond destination field size.
551          *
552          * We must ignore p_size_field == 0 for existing 0-element
553          * fake flexible arrays, until they are all converted to
554          * proper flexible arrays.
555          *
556          * The implementation of __builtin_*object_size() behaves
557          * like sizeof() when not directly referencing a flexible
558          * array member, which means there will be many bounds checks
559          * that will appear at run-time, without a way for them to be
560          * detected at compile-time (as can be done when the destination
561          * is specifically the flexible array member).
562          * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101832
563          */
564         if (p_size_field != 0 && p_size_field != SIZE_MAX &&
565             p_size != p_size_field && p_size_field < size)
566                 return true;
567
568         return false;
569 }
570
571 #define __fortify_memcpy_chk(p, q, size, p_size, q_size,                \
572                              p_size_field, q_size_field, op) ({         \
573         const size_t __fortify_size = (size_t)(size);                   \
574         const size_t __p_size = (p_size);                               \
575         const size_t __q_size = (q_size);                               \
576         const size_t __p_size_field = (p_size_field);                   \
577         const size_t __q_size_field = (q_size_field);                   \
578         WARN_ONCE(fortify_memcpy_chk(__fortify_size, __p_size,          \
579                                      __q_size, __p_size_field,          \
580                                      __q_size_field, #op),              \
581                   #op ": detected field-spanning write (size %zu) of single %s (size %zu)\n", \
582                   __fortify_size,                                       \
583                   "field \"" #p "\" at " __FILE__ ":" __stringify(__LINE__), \
584                   __p_size_field);                                      \
585         __underlying_##op(p, q, __fortify_size);                        \
586 })
587
588 /*
589  * Notes about compile-time buffer size detection:
590  *
591  * With these types...
592  *
593  *      struct middle {
594  *              u16 a;
595  *              u8 middle_buf[16];
596  *              int b;
597  *      };
598  *      struct end {
599  *              u16 a;
600  *              u8 end_buf[16];
601  *      };
602  *      struct flex {
603  *              int a;
604  *              u8 flex_buf[];
605  *      };
606  *
607  *      void func(TYPE *ptr) { ... }
608  *
609  * Cases where destination size cannot be currently detected:
610  * - the size of ptr's object (seemingly by design, gcc & clang fail):
611  *      __builtin_object_size(ptr, 1) == SIZE_MAX
612  * - the size of flexible arrays in ptr's obj (by design, dynamic size):
613  *      __builtin_object_size(ptr->flex_buf, 1) == SIZE_MAX
614  * - the size of ANY array at the end of ptr's obj (gcc and clang bug):
615  *      __builtin_object_size(ptr->end_buf, 1) == SIZE_MAX
616  *      https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101836
617  *
618  * Cases where destination size is currently detected:
619  * - the size of non-array members within ptr's object:
620  *      __builtin_object_size(ptr->a, 1) == 2
621  * - the size of non-flexible-array in the middle of ptr's obj:
622  *      __builtin_object_size(ptr->middle_buf, 1) == 16
623  *
624  */
625
626 /*
627  * __struct_size() vs __member_size() must be captured here to avoid
628  * evaluating argument side-effects further into the macro layers.
629  */
630 #define memcpy(p, q, s)  __fortify_memcpy_chk(p, q, s,                  \
631                 __struct_size(p), __struct_size(q),                     \
632                 __member_size(p), __member_size(q),                     \
633                 memcpy)
634 #define memmove(p, q, s)  __fortify_memcpy_chk(p, q, s,                 \
635                 __struct_size(p), __struct_size(q),                     \
636                 __member_size(p), __member_size(q),                     \
637                 memmove)
638
639 extern void *__real_memscan(void *, int, __kernel_size_t) __RENAME(memscan);
640 __FORTIFY_INLINE void *memscan(void * const POS0 p, int c, __kernel_size_t size)
641 {
642         size_t p_size = __struct_size(p);
643
644         if (__compiletime_lessthan(p_size, size))
645                 __read_overflow();
646         if (p_size < size)
647                 fortify_panic(__func__);
648         return __real_memscan(p, c, size);
649 }
650
651 __FORTIFY_INLINE __diagnose_as(__builtin_memcmp, 1, 2, 3)
652 int memcmp(const void * const POS0 p, const void * const POS0 q, __kernel_size_t size)
653 {
654         size_t p_size = __struct_size(p);
655         size_t q_size = __struct_size(q);
656
657         if (__builtin_constant_p(size)) {
658                 if (__compiletime_lessthan(p_size, size))
659                         __read_overflow();
660                 if (__compiletime_lessthan(q_size, size))
661                         __read_overflow2();
662         }
663         if (p_size < size || q_size < size)
664                 fortify_panic(__func__);
665         return __underlying_memcmp(p, q, size);
666 }
667
668 __FORTIFY_INLINE __diagnose_as(__builtin_memchr, 1, 2, 3)
669 void *memchr(const void * const POS0 p, int c, __kernel_size_t size)
670 {
671         size_t p_size = __struct_size(p);
672
673         if (__compiletime_lessthan(p_size, size))
674                 __read_overflow();
675         if (p_size < size)
676                 fortify_panic(__func__);
677         return __underlying_memchr(p, c, size);
678 }
679
680 void *__real_memchr_inv(const void *s, int c, size_t n) __RENAME(memchr_inv);
681 __FORTIFY_INLINE void *memchr_inv(const void * const POS0 p, int c, size_t size)
682 {
683         size_t p_size = __struct_size(p);
684
685         if (__compiletime_lessthan(p_size, size))
686                 __read_overflow();
687         if (p_size < size)
688                 fortify_panic(__func__);
689         return __real_memchr_inv(p, c, size);
690 }
691
692 extern void *__real_kmemdup(const void *src, size_t len, gfp_t gfp) __RENAME(kmemdup)
693                                                                     __realloc_size(2);
694 __FORTIFY_INLINE void *kmemdup(const void * const POS0 p, size_t size, gfp_t gfp)
695 {
696         size_t p_size = __struct_size(p);
697
698         if (__compiletime_lessthan(p_size, size))
699                 __read_overflow();
700         if (p_size < size)
701                 fortify_panic(__func__);
702         return __real_kmemdup(p, size, gfp);
703 }
704
705 /**
706  * strcpy - Copy a string into another string buffer
707  *
708  * @p: pointer to destination of copy
709  * @q: pointer to NUL-terminated source string to copy
710  *
711  * Do not use this function. While FORTIFY_SOURCE tries to avoid
712  * overflows, this is only possible when the sizes of @q and @p are
713  * known to the compiler. Prefer strscpy(), though note its different
714  * return values for detecting truncation.
715  *
716  * Returns @p.
717  *
718  */
719 /* Defined after fortified strlen to reuse it. */
720 __FORTIFY_INLINE __diagnose_as(__builtin_strcpy, 1, 2)
721 char *strcpy(char * const POS p, const char * const POS q)
722 {
723         size_t p_size = __member_size(p);
724         size_t q_size = __member_size(q);
725         size_t size;
726
727         /* If neither buffer size is known, immediately give up. */
728         if (__builtin_constant_p(p_size) &&
729             __builtin_constant_p(q_size) &&
730             p_size == SIZE_MAX && q_size == SIZE_MAX)
731                 return __underlying_strcpy(p, q);
732         size = strlen(q) + 1;
733         /* Compile-time check for const size overflow. */
734         if (__compiletime_lessthan(p_size, size))
735                 __write_overflow();
736         /* Run-time check for dynamic size overflow. */
737         if (p_size < size)
738                 fortify_panic(__func__);
739         __underlying_memcpy(p, q, size);
740         return p;
741 }
742
743 /* Don't use these outside the FORITFY_SOURCE implementation */
744 #undef __underlying_memchr
745 #undef __underlying_memcmp
746 #undef __underlying_strcat
747 #undef __underlying_strcpy
748 #undef __underlying_strlen
749 #undef __underlying_strncat
750 #undef __underlying_strncpy
751
752 #undef POS
753 #undef POS0
754
755 #endif /* _LINUX_FORTIFY_STRING_H_ */