Merge tag 'for_linus' of git://git.kernel.org/pub/scm/linux/kernel/git/mst/vhost
[linux-block.git] / include / linux / fortify-string.h
CommitLineData
a28a6e86
FL
1/* SPDX-License-Identifier: GPL-2.0 */
2#ifndef _LINUX_FORTIFY_STRING_H_
3#define _LINUX_FORTIFY_STRING_H_
4
54d9469b 5#include <linux/bug.h>
67ebc3ab 6#include <linux/const.h>
311fb40a 7#include <linux/limits.h>
67ebc3ab 8
281d0c96 9#define __FORTIFY_INLINE extern __always_inline __gnu_inline __overloadable
c430f600
KC
10#define __RENAME(x) __asm__(#x)
11
12void fortify_panic(const char *name) __noreturn __cold;
13void __read_overflow(void) __compiletime_error("detected read beyond size of object (1st parameter)");
14void __read_overflow2(void) __compiletime_error("detected read beyond size of object (2nd parameter)");
f68f2ff9 15void __read_overflow2_field(size_t avail, size_t wanted) __compiletime_warning("detected read beyond size of field (2nd parameter); maybe use struct_group()?");
c430f600 16void __write_overflow(void) __compiletime_error("detected write beyond size of object (1st parameter)");
f68f2ff9 17void __write_overflow_field(size_t avail, size_t wanted) __compiletime_warning("detected write beyond size of field (1st parameter); maybe use struct_group()?");
a28a6e86 18
95cadae3
QC
19#define __compiletime_strlen(p) \
20({ \
e9a40e15 21 char *__p = (char *)(p); \
311fb40a 22 size_t __ret = SIZE_MAX; \
9f7d69c5 23 size_t __p_size = __member_size(p); \
311fb40a 24 if (__p_size != SIZE_MAX && \
d07c0acb 25 __builtin_constant_p(*__p)) { \
95cadae3
QC
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; \
3009f891
KC
32})
33
a28a6e86
FL
34#if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
35extern void *__underlying_memchr(const void *p, int c, __kernel_size_t size) __RENAME(memchr);
36extern int __underlying_memcmp(const void *p, const void *q, __kernel_size_t size) __RENAME(memcmp);
37extern void *__underlying_memcpy(void *p, const void *q, __kernel_size_t size) __RENAME(memcpy);
38extern void *__underlying_memmove(void *p, const void *q, __kernel_size_t size) __RENAME(memmove);
39extern void *__underlying_memset(void *p, int c, __kernel_size_t size) __RENAME(memset);
40extern char *__underlying_strcat(char *p, const char *q) __RENAME(strcat);
41extern char *__underlying_strcpy(char *p, const char *q) __RENAME(strcpy);
42extern __kernel_size_t __underlying_strlen(const char *p) __RENAME(strlen);
43extern char *__underlying_strncat(char *p, const char *q, __kernel_size_t count) __RENAME(strncat);
44extern char *__underlying_strncpy(char *p, const char *q, __kernel_size_t size) __RENAME(strncpy);
45#else
78a498c3
AP
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
a28a6e86
FL
57#define __underlying_memcpy __builtin_memcpy
58#define __underlying_memmove __builtin_memmove
59#define __underlying_memset __builtin_memset
78a498c3
AP
60#endif
61
62#define __underlying_memchr __builtin_memchr
63#define __underlying_memcmp __builtin_memcmp
a28a6e86
FL
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
43213dae
KC
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
281d0c96 87/*
9f7d69c5
KC
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
281d0c96
KC
90 * size, rather than struct size), but there remain some stragglers using
91 * type 0 that will be converted in the future.
92 */
439a1bca
KC
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
9f7d69c5
KC
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)
439a1bca 103#endif
281d0c96 104
fa35198f
KC
105#define __compiletime_lessthan(bounds, length) ( \
106 __builtin_constant_p((bounds) < (length)) && \
107 (bounds) < (length) \
108)
109
dfbafa70
KC
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 *
03699f27
KC
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 * +--------------------+--------------------+------------+
dfbafa70
KC
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 */
92df138a 142__FORTIFY_INLINE __diagnose_as(__builtin_strncpy, 1, 2, 3)
281d0c96 143char *strncpy(char * const POS p, const char *q, __kernel_size_t size)
a28a6e86 144{
9f7d69c5 145 size_t p_size = __member_size(p);
a28a6e86 146
fa35198f 147 if (__compiletime_lessthan(p_size, size))
a28a6e86
FL
148 __write_overflow();
149 if (p_size < size)
150 fortify_panic(__func__);
151 return __underlying_strncpy(p, q, size);
152}
153
03699f27
KC
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 */
92df138a 169__FORTIFY_INLINE __diagnose_as(__builtin_strcat, 1, 2)
281d0c96 170char *strcat(char * const POS p, const char *q)
a28a6e86 171{
9f7d69c5 172 size_t p_size = __member_size(p);
a28a6e86 173
311fb40a 174 if (p_size == SIZE_MAX)
a28a6e86
FL
175 return __underlying_strcat(p, q);
176 if (strlcat(p, q, p_size) >= p_size)
177 fortify_panic(__func__);
178 return p;
179}
180
369cd216 181extern __kernel_size_t __real_strnlen(const char *, __kernel_size_t) __RENAME(strnlen);
03699f27
KC
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 */
281d0c96 192__FORTIFY_INLINE __kernel_size_t strnlen(const char * const POS p, __kernel_size_t maxlen)
369cd216 193{
9f7d69c5 194 size_t p_size = __member_size(p);
3009f891
KC
195 size_t p_len = __compiletime_strlen(p);
196 size_t ret;
197
198 /* We can take compile-time actions when maxlen is const. */
311fb40a 199 if (__builtin_constant_p(maxlen) && p_len != SIZE_MAX) {
3009f891
KC
200 /* If p is const, we can use its compile-time-known len. */
201 if (maxlen >= p_size)
202 return p_len;
203 }
369cd216 204
3009f891
KC
205 /* Do not check characters beyond the end of p. */
206 ret = __real_strnlen(p, maxlen < p_size ? maxlen : p_size);
369cd216
KC
207 if (p_size <= ret && maxlen != ret)
208 fortify_panic(__func__);
209 return ret;
210}
211
67ebc3ab
KC
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 */
03699f27
KC
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 */
67ebc3ab
KC
230#define strlen(p) \
231 __builtin_choose_expr(__is_constexpr(__builtin_strlen(p)), \
232 __builtin_strlen(p), __fortify_strlen(p))
92df138a 233__FORTIFY_INLINE __diagnose_as(__builtin_strlen, 1)
281d0c96 234__kernel_size_t __fortify_strlen(const char * const POS p)
a28a6e86
FL
235{
236 __kernel_size_t ret;
9f7d69c5 237 size_t p_size = __member_size(p);
a28a6e86 238
3009f891 239 /* Give up if we don't know how large p is. */
311fb40a 240 if (p_size == SIZE_MAX)
a28a6e86
FL
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
03699f27 248/* Defined after fortified strlen() to reuse it. */
a28a6e86 249extern size_t __real_strlcpy(char *, const char *, size_t) __RENAME(strlcpy);
03699f27
KC
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 */
281d0c96 268__FORTIFY_INLINE size_t strlcpy(char * const POS p, const char * const POS q, size_t size)
a28a6e86 269{
9f7d69c5
KC
270 size_t p_size = __member_size(p);
271 size_t q_size = __member_size(q);
3009f891
KC
272 size_t q_len; /* Full count of source string length. */
273 size_t len; /* Count of characters going into destination. */
a28a6e86 274
311fb40a 275 if (p_size == SIZE_MAX && q_size == SIZE_MAX)
a28a6e86 276 return __real_strlcpy(p, q, size);
3009f891
KC
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)
a28a6e86 282 __write_overflow();
3009f891
KC
283 }
284 if (size) {
a28a6e86
FL
285 if (len >= p_size)
286 fortify_panic(__func__);
287 __underlying_memcpy(p, q, len);
288 p[len] = '\0';
289 }
3009f891 290 return q_len;
a28a6e86
FL
291}
292
03699f27 293/* Defined after fortified strnlen() to reuse it. */
a28a6e86 294extern ssize_t __real_strscpy(char *, const char *, size_t) __RENAME(strscpy);
03699f27
KC
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 */
281d0c96 319__FORTIFY_INLINE ssize_t strscpy(char * const POS p, const char * const POS q, size_t size)
a28a6e86
FL
320{
321 size_t len;
322 /* Use string size rather than possible enclosing struct size. */
9f7d69c5
KC
323 size_t p_size = __member_size(p);
324 size_t q_size = __member_size(q);
a28a6e86
FL
325
326 /* If we cannot get size of p and q default to call strscpy. */
311fb40a 327 if (p_size == SIZE_MAX && q_size == SIZE_MAX)
a28a6e86
FL
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 */
fa35198f 334 if (__compiletime_lessthan(p_size, size))
a28a6e86
FL
335 __write_overflow();
336
62e1cbfc
KC
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
a28a6e86
FL
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
03699f27
KC
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. */
92df138a 394__FORTIFY_INLINE __diagnose_as(__builtin_strncat, 1, 2, 3)
281d0c96 395char *strncat(char * const POS p, const char * const POS q, __kernel_size_t count)
a28a6e86
FL
396{
397 size_t p_len, copy_len;
9f7d69c5
KC
398 size_t p_size = __member_size(p);
399 size_t q_size = __member_size(q);
a28a6e86 400
311fb40a 401 if (p_size == SIZE_MAX && q_size == SIZE_MAX)
a28a6e86
FL
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
28e77cc1
KC
412__FORTIFY_INLINE void fortify_memset_chk(__kernel_size_t size,
413 const size_t p_size,
414 const size_t p_size_field)
a28a6e86 415{
28e77cc1
KC
416 if (__builtin_constant_p(size)) {
417 /*
418 * Length argument is a constant expression, so we
419 * can perform compile-time bounds checking where
fa35198f 420 * buffer sizes are also known at compile time.
28e77cc1 421 */
a28a6e86 422
28e77cc1 423 /* Error when size is larger than enclosing struct. */
fa35198f
KC
424 if (__compiletime_lessthan(p_size_field, p_size) &&
425 __compiletime_lessthan(p_size, size))
28e77cc1
KC
426 __write_overflow();
427
428 /* Warn when write size is larger than dest field. */
fa35198f 429 if (__compiletime_lessthan(p_size_field, size))
28e77cc1
KC
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.
311fb40a 443 * (The SIZE_MAX test is to optimize away checks where the buffer
28e77cc1
KC
444 * lengths are unknown.)
445 */
311fb40a 446 if (p_size != SIZE_MAX && p_size < size)
28e77cc1 447 fortify_panic("memset");
a28a6e86
FL
448}
449
28e77cc1
KC
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/*
9f7d69c5
KC
457 * __struct_size() vs __member_size() must be captured here to avoid
458 * evaluating argument side-effects further into the macro layers.
28e77cc1 459 */
ff901d80 460#ifndef CONFIG_KMSAN
28e77cc1 461#define memset(p, c, s) __fortify_memset_chk(p, c, s, \
9f7d69c5 462 __struct_size(p), __member_size(p))
ff901d80 463#endif
28e77cc1 464
f68f2ff9
KC
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 */
54d9469b 496__FORTIFY_INLINE bool fortify_memcpy_chk(__kernel_size_t size,
f68f2ff9
KC
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)
a28a6e86 502{
a28a6e86 503 if (__builtin_constant_p(size)) {
f68f2ff9
KC
504 /*
505 * Length argument is a constant expression, so we
506 * can perform compile-time bounds checking where
fa35198f 507 * buffer sizes are also known at compile time.
f68f2ff9
KC
508 */
509
510 /* Error when size is larger than enclosing struct. */
fa35198f
KC
511 if (__compiletime_lessthan(p_size_field, p_size) &&
512 __compiletime_lessthan(p_size, size))
a28a6e86 513 __write_overflow();
fa35198f
KC
514 if (__compiletime_lessthan(q_size_field, q_size) &&
515 __compiletime_lessthan(q_size, size))
a28a6e86 516 __read_overflow2();
f68f2ff9
KC
517
518 /* Warn when write size argument larger than dest field. */
fa35198f 519 if (__compiletime_lessthan(p_size_field, size))
f68f2ff9
KC
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 */
fa35198f
KC
526 if ((IS_ENABLED(KBUILD_EXTRA_WARN1) ||
527 __compiletime_lessthan(p_size_field, size)) &&
528 __compiletime_lessthan(q_size_field, size))
f68f2ff9 529 __read_overflow2_field(q_size_field, size);
a28a6e86 530 }
f68f2ff9
KC
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.
311fb40a 542 * (The SIZE_MAX test is to optimize away checks where the buffer
f68f2ff9
KC
543 * lengths are unknown.)
544 */
311fb40a
KC
545 if ((p_size != SIZE_MAX && p_size < size) ||
546 (q_size != SIZE_MAX && q_size < size))
f68f2ff9 547 fortify_panic(func);
54d9469b
KC
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 *
9f7d69c5 556 * The implementation of __builtin_*object_size() behaves
54d9469b
KC
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;
a28a6e86
FL
569}
570
f68f2ff9
KC
571#define __fortify_memcpy_chk(p, q, size, p_size, q_size, \
572 p_size_field, q_size_field, op) ({ \
6f7630b1
KC
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), \
54d9469b
KC
581 #op ": detected field-spanning write (size %zu) of single %s (size %zu)\n", \
582 __fortify_size, \
583 "field \"" #p "\" at " __FILE__ ":" __stringify(__LINE__), \
6f7630b1 584 __p_size_field); \
f68f2ff9
KC
585 __underlying_##op(p, q, __fortify_size); \
586})
587
54d9469b
KC
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
f68f2ff9 626/*
9f7d69c5
KC
627 * __struct_size() vs __member_size() must be captured here to avoid
628 * evaluating argument side-effects further into the macro layers.
f68f2ff9
KC
629 */
630#define memcpy(p, q, s) __fortify_memcpy_chk(p, q, s, \
9f7d69c5
KC
631 __struct_size(p), __struct_size(q), \
632 __member_size(p), __member_size(q), \
f68f2ff9 633 memcpy)
938a000e 634#define memmove(p, q, s) __fortify_memcpy_chk(p, q, s, \
9f7d69c5
KC
635 __struct_size(p), __struct_size(q), \
636 __member_size(p), __member_size(q), \
938a000e 637 memmove)
a28a6e86
FL
638
639extern void *__real_memscan(void *, int, __kernel_size_t) __RENAME(memscan);
281d0c96 640__FORTIFY_INLINE void *memscan(void * const POS0 p, int c, __kernel_size_t size)
a28a6e86 641{
9f7d69c5 642 size_t p_size = __struct_size(p);
a28a6e86 643
fa35198f 644 if (__compiletime_lessthan(p_size, size))
a28a6e86
FL
645 __read_overflow();
646 if (p_size < size)
647 fortify_panic(__func__);
648 return __real_memscan(p, c, size);
649}
650
92df138a 651__FORTIFY_INLINE __diagnose_as(__builtin_memcmp, 1, 2, 3)
281d0c96 652int memcmp(const void * const POS0 p, const void * const POS0 q, __kernel_size_t size)
a28a6e86 653{
9f7d69c5
KC
654 size_t p_size = __struct_size(p);
655 size_t q_size = __struct_size(q);
a28a6e86
FL
656
657 if (__builtin_constant_p(size)) {
fa35198f 658 if (__compiletime_lessthan(p_size, size))
a28a6e86 659 __read_overflow();
fa35198f 660 if (__compiletime_lessthan(q_size, size))
a28a6e86
FL
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
92df138a 668__FORTIFY_INLINE __diagnose_as(__builtin_memchr, 1, 2, 3)
281d0c96 669void *memchr(const void * const POS0 p, int c, __kernel_size_t size)
a28a6e86 670{
9f7d69c5 671 size_t p_size = __struct_size(p);
a28a6e86 672
fa35198f 673 if (__compiletime_lessthan(p_size, size))
a28a6e86
FL
674 __read_overflow();
675 if (p_size < size)
676 fortify_panic(__func__);
677 return __underlying_memchr(p, c, size);
678}
679
680void *__real_memchr_inv(const void *s, int c, size_t n) __RENAME(memchr_inv);
281d0c96 681__FORTIFY_INLINE void *memchr_inv(const void * const POS0 p, int c, size_t size)
a28a6e86 682{
9f7d69c5 683 size_t p_size = __struct_size(p);
a28a6e86 684
fa35198f 685 if (__compiletime_lessthan(p_size, size))
a28a6e86
FL
686 __read_overflow();
687 if (p_size < size)
688 fortify_panic(__func__);
689 return __real_memchr_inv(p, c, size);
690}
691
9e4a6177
KC
692extern void *__real_kmemdup(const void *src, size_t len, gfp_t gfp) __RENAME(kmemdup)
693 __realloc_size(2);
281d0c96 694__FORTIFY_INLINE void *kmemdup(const void * const POS0 p, size_t size, gfp_t gfp)
a28a6e86 695{
9f7d69c5 696 size_t p_size = __struct_size(p);
a28a6e86 697
fa35198f 698 if (__compiletime_lessthan(p_size, size))
a28a6e86
FL
699 __read_overflow();
700 if (p_size < size)
701 fortify_panic(__func__);
702 return __real_kmemdup(p, size, gfp);
703}
704
03699f27
KC
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 */
f68f2ff9 719/* Defined after fortified strlen to reuse it. */
92df138a 720__FORTIFY_INLINE __diagnose_as(__builtin_strcpy, 1, 2)
281d0c96 721char *strcpy(char * const POS p, const char * const POS q)
a28a6e86 722{
9f7d69c5
KC
723 size_t p_size = __member_size(p);
724 size_t q_size = __member_size(q);
a28a6e86
FL
725 size_t size;
726
f68f2ff9 727 /* If neither buffer size is known, immediately give up. */
fa35198f
KC
728 if (__builtin_constant_p(p_size) &&
729 __builtin_constant_p(q_size) &&
730 p_size == SIZE_MAX && q_size == SIZE_MAX)
a28a6e86
FL
731 return __underlying_strcpy(p, q);
732 size = strlen(q) + 1;
072af0c6 733 /* Compile-time check for const size overflow. */
fa35198f 734 if (__compiletime_lessthan(p_size, size))
072af0c6
KC
735 __write_overflow();
736 /* Run-time check for dynamic size overflow. */
a28a6e86
FL
737 if (p_size < size)
738 fortify_panic(__func__);
f68f2ff9 739 __underlying_memcpy(p, q, size);
a28a6e86
FL
740 return p;
741}
742
743/* Don't use these outside the FORITFY_SOURCE implementation */
744#undef __underlying_memchr
745#undef __underlying_memcmp
a28a6e86
FL
746#undef __underlying_strcat
747#undef __underlying_strcpy
748#undef __underlying_strlen
749#undef __underlying_strncat
750#undef __underlying_strncpy
751
281d0c96
KC
752#undef POS
753#undef POS0
754
a28a6e86 755#endif /* _LINUX_FORTIFY_STRING_H_ */