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