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