xref: /linux-6.15/include/linux/fortify-string.h (revision 605395cd)
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 	const 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 	const 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 	const 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 	const size_t p_size = __member_size(p);
195 	const 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 	const size_t p_size = __member_size(p);
237 	__kernel_size_t ret;
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 	const size_t p_size = __member_size(p);
271 	const 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 @q, or as much of it as fits, into the destination
303  * @p 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 	/* Use string size rather than possible enclosing struct size. */
322 	const size_t p_size = __member_size(p);
323 	const size_t q_size = __member_size(q);
324 	size_t len;
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 /* Defined after fortified strlen() to reuse it. */
375 extern size_t __real_strlcat(char *p, const char *q, size_t avail) __RENAME(strlcat);
376 /**
377  * strlcat - Append a string to an existing string
378  *
379  * @p: pointer to %NUL-terminated string to append to
380  * @q: pointer to %NUL-terminated string to append from
381  * @avail: Maximum bytes available in @p
382  *
383  * Appends %NUL-terminated string @q after the %NUL-terminated
384  * string at @p, but will not write beyond @avail bytes total,
385  * potentially truncating the copy from @q. @p will stay
386  * %NUL-terminated only if a %NUL already existed within
387  * the @avail bytes of @p. If so, the resulting number of
388  * bytes copied from @q will be at most "@avail - strlen(@p) - 1".
389  *
390  * Do not use this function. While FORTIFY_SOURCE tries to avoid
391  * read and write overflows, this is only possible when the sizes
392  * of @p and @q are known to the compiler. Prefer building the
393  * string with formatting, via scnprintf(), seq_buf, or similar.
394  *
395  * Returns total bytes that _would_ have been contained by @p
396  * regardless of truncation, similar to snprintf(). If return
397  * value is >= @avail, the string has been truncated.
398  *
399  */
400 __FORTIFY_INLINE
401 size_t strlcat(char * const POS p, const char * const POS q, size_t avail)
402 {
403 	const size_t p_size = __member_size(p);
404 	const size_t q_size = __member_size(q);
405 	size_t p_len, copy_len;
406 	size_t actual, wanted;
407 
408 	/* Give up immediately if both buffer sizes are unknown. */
409 	if (p_size == SIZE_MAX && q_size == SIZE_MAX)
410 		return __real_strlcat(p, q, avail);
411 
412 	p_len = strnlen(p, avail);
413 	copy_len = strlen(q);
414 	wanted = actual = p_len + copy_len;
415 
416 	/* Cannot append any more: report truncation. */
417 	if (avail <= p_len)
418 		return wanted;
419 
420 	/* Give up if string is already overflowed. */
421 	if (p_size <= p_len)
422 		fortify_panic(__func__);
423 
424 	if (actual >= avail) {
425 		copy_len = avail - p_len - 1;
426 		actual = p_len + copy_len;
427 	}
428 
429 	/* Give up if copy will overflow. */
430 	if (p_size <= actual)
431 		fortify_panic(__func__);
432 	__underlying_memcpy(p + p_len, q, copy_len);
433 	p[actual] = '\0';
434 
435 	return wanted;
436 }
437 
438 /**
439  * strncat - Append a string to an existing string
440  *
441  * @p: pointer to NUL-terminated string to append to
442  * @q: pointer to source string to append from
443  * @count: Maximum bytes to read from @q
444  *
445  * Appends at most @count bytes from @q (stopping at the first
446  * NUL byte) after the NUL-terminated string at @p. @p will be
447  * NUL-terminated.
448  *
449  * Do not use this function. While FORTIFY_SOURCE tries to avoid
450  * read and write overflows, this is only possible when the sizes
451  * of @p and @q are known to the compiler. Prefer building the
452  * string with formatting, via scnprintf() or similar.
453  *
454  * Returns @p.
455  *
456  */
457 /* Defined after fortified strlen() and strnlen() to reuse them. */
458 __FORTIFY_INLINE __diagnose_as(__builtin_strncat, 1, 2, 3)
459 char *strncat(char * const POS p, const char * const POS q, __kernel_size_t count)
460 {
461 	const size_t p_size = __member_size(p);
462 	const size_t q_size = __member_size(q);
463 	size_t p_len, copy_len;
464 
465 	if (p_size == SIZE_MAX && q_size == SIZE_MAX)
466 		return __underlying_strncat(p, q, count);
467 	p_len = strlen(p);
468 	copy_len = strnlen(q, count);
469 	if (p_size < p_len + copy_len + 1)
470 		fortify_panic(__func__);
471 	__underlying_memcpy(p + p_len, q, copy_len);
472 	p[p_len + copy_len] = '\0';
473 	return p;
474 }
475 
476 __FORTIFY_INLINE void fortify_memset_chk(__kernel_size_t size,
477 					 const size_t p_size,
478 					 const size_t p_size_field)
479 {
480 	if (__builtin_constant_p(size)) {
481 		/*
482 		 * Length argument is a constant expression, so we
483 		 * can perform compile-time bounds checking where
484 		 * buffer sizes are also known at compile time.
485 		 */
486 
487 		/* Error when size is larger than enclosing struct. */
488 		if (__compiletime_lessthan(p_size_field, p_size) &&
489 		    __compiletime_lessthan(p_size, size))
490 			__write_overflow();
491 
492 		/* Warn when write size is larger than dest field. */
493 		if (__compiletime_lessthan(p_size_field, size))
494 			__write_overflow_field(p_size_field, size);
495 	}
496 	/*
497 	 * At this point, length argument may not be a constant expression,
498 	 * so run-time bounds checking can be done where buffer sizes are
499 	 * known. (This is not an "else" because the above checks may only
500 	 * be compile-time warnings, and we want to still warn for run-time
501 	 * overflows.)
502 	 */
503 
504 	/*
505 	 * Always stop accesses beyond the struct that contains the
506 	 * field, when the buffer's remaining size is known.
507 	 * (The SIZE_MAX test is to optimize away checks where the buffer
508 	 * lengths are unknown.)
509 	 */
510 	if (p_size != SIZE_MAX && p_size < size)
511 		fortify_panic("memset");
512 }
513 
514 #define __fortify_memset_chk(p, c, size, p_size, p_size_field) ({	\
515 	size_t __fortify_size = (size_t)(size);				\
516 	fortify_memset_chk(__fortify_size, p_size, p_size_field),	\
517 	__underlying_memset(p, c, __fortify_size);			\
518 })
519 
520 /*
521  * __struct_size() vs __member_size() must be captured here to avoid
522  * evaluating argument side-effects further into the macro layers.
523  */
524 #ifndef CONFIG_KMSAN
525 #define memset(p, c, s) __fortify_memset_chk(p, c, s,			\
526 		__struct_size(p), __member_size(p))
527 #endif
528 
529 /*
530  * To make sure the compiler can enforce protection against buffer overflows,
531  * memcpy(), memmove(), and memset() must not be used beyond individual
532  * struct members. If you need to copy across multiple members, please use
533  * struct_group() to create a named mirror of an anonymous struct union.
534  * (e.g. see struct sk_buff.) Read overflow checking is currently only
535  * done when a write overflow is also present, or when building with W=1.
536  *
537  * Mitigation coverage matrix
538  *					Bounds checking at:
539  *					+-------+-------+-------+-------+
540  *					| Compile time  |   Run time    |
541  * memcpy() argument sizes:		| write | read  | write | read  |
542  *        dest     source   length      +-------+-------+-------+-------+
543  * memcpy(known,   known,   constant)	|   y   |   y   |  n/a  |  n/a  |
544  * memcpy(known,   unknown, constant)	|   y   |   n   |  n/a  |   V   |
545  * memcpy(known,   known,   dynamic)	|   n   |   n   |   B   |   B   |
546  * memcpy(known,   unknown, dynamic)	|   n   |   n   |   B   |   V   |
547  * memcpy(unknown, known,   constant)	|   n   |   y   |   V   |  n/a  |
548  * memcpy(unknown, unknown, constant)	|   n   |   n   |   V   |   V   |
549  * memcpy(unknown, known,   dynamic)	|   n   |   n   |   V   |   B   |
550  * memcpy(unknown, unknown, dynamic)	|   n   |   n   |   V   |   V   |
551  *					+-------+-------+-------+-------+
552  *
553  * y = perform deterministic compile-time bounds checking
554  * n = cannot perform deterministic compile-time bounds checking
555  * n/a = no run-time bounds checking needed since compile-time deterministic
556  * B = can perform run-time bounds checking (currently unimplemented)
557  * V = vulnerable to run-time overflow (will need refactoring to solve)
558  *
559  */
560 __FORTIFY_INLINE bool fortify_memcpy_chk(__kernel_size_t size,
561 					 const size_t p_size,
562 					 const size_t q_size,
563 					 const size_t p_size_field,
564 					 const size_t q_size_field,
565 					 const char *func)
566 {
567 	if (__builtin_constant_p(size)) {
568 		/*
569 		 * Length argument is a constant expression, so we
570 		 * can perform compile-time bounds checking where
571 		 * buffer sizes are also known at compile time.
572 		 */
573 
574 		/* Error when size is larger than enclosing struct. */
575 		if (__compiletime_lessthan(p_size_field, p_size) &&
576 		    __compiletime_lessthan(p_size, size))
577 			__write_overflow();
578 		if (__compiletime_lessthan(q_size_field, q_size) &&
579 		    __compiletime_lessthan(q_size, size))
580 			__read_overflow2();
581 
582 		/* Warn when write size argument larger than dest field. */
583 		if (__compiletime_lessthan(p_size_field, size))
584 			__write_overflow_field(p_size_field, size);
585 		/*
586 		 * Warn for source field over-read when building with W=1
587 		 * or when an over-write happened, so both can be fixed at
588 		 * the same time.
589 		 */
590 		if ((IS_ENABLED(KBUILD_EXTRA_WARN1) ||
591 		     __compiletime_lessthan(p_size_field, size)) &&
592 		    __compiletime_lessthan(q_size_field, size))
593 			__read_overflow2_field(q_size_field, size);
594 	}
595 	/*
596 	 * At this point, length argument may not be a constant expression,
597 	 * so run-time bounds checking can be done where buffer sizes are
598 	 * known. (This is not an "else" because the above checks may only
599 	 * be compile-time warnings, and we want to still warn for run-time
600 	 * overflows.)
601 	 */
602 
603 	/*
604 	 * Always stop accesses beyond the struct that contains the
605 	 * field, when the buffer's remaining size is known.
606 	 * (The SIZE_MAX test is to optimize away checks where the buffer
607 	 * lengths are unknown.)
608 	 */
609 	if ((p_size != SIZE_MAX && p_size < size) ||
610 	    (q_size != SIZE_MAX && q_size < size))
611 		fortify_panic(func);
612 
613 	/*
614 	 * Warn when writing beyond destination field size.
615 	 *
616 	 * We must ignore p_size_field == 0 for existing 0-element
617 	 * fake flexible arrays, until they are all converted to
618 	 * proper flexible arrays.
619 	 *
620 	 * The implementation of __builtin_*object_size() behaves
621 	 * like sizeof() when not directly referencing a flexible
622 	 * array member, which means there will be many bounds checks
623 	 * that will appear at run-time, without a way for them to be
624 	 * detected at compile-time (as can be done when the destination
625 	 * is specifically the flexible array member).
626 	 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101832
627 	 */
628 	if (p_size_field != 0 && p_size_field != SIZE_MAX &&
629 	    p_size != p_size_field && p_size_field < size)
630 		return true;
631 
632 	return false;
633 }
634 
635 #define __fortify_memcpy_chk(p, q, size, p_size, q_size,		\
636 			     p_size_field, q_size_field, op) ({		\
637 	const size_t __fortify_size = (size_t)(size);			\
638 	const size_t __p_size = (p_size);				\
639 	const size_t __q_size = (q_size);				\
640 	const size_t __p_size_field = (p_size_field);			\
641 	const size_t __q_size_field = (q_size_field);			\
642 	WARN_ONCE(fortify_memcpy_chk(__fortify_size, __p_size,		\
643 				     __q_size, __p_size_field,		\
644 				     __q_size_field, #op),		\
645 		  #op ": detected field-spanning write (size %zu) of single %s (size %zu)\n", \
646 		  __fortify_size,					\
647 		  "field \"" #p "\" at " __FILE__ ":" __stringify(__LINE__), \
648 		  __p_size_field);					\
649 	__underlying_##op(p, q, __fortify_size);			\
650 })
651 
652 /*
653  * Notes about compile-time buffer size detection:
654  *
655  * With these types...
656  *
657  *	struct middle {
658  *		u16 a;
659  *		u8 middle_buf[16];
660  *		int b;
661  *	};
662  *	struct end {
663  *		u16 a;
664  *		u8 end_buf[16];
665  *	};
666  *	struct flex {
667  *		int a;
668  *		u8 flex_buf[];
669  *	};
670  *
671  *	void func(TYPE *ptr) { ... }
672  *
673  * Cases where destination size cannot be currently detected:
674  * - the size of ptr's object (seemingly by design, gcc & clang fail):
675  *	__builtin_object_size(ptr, 1) == SIZE_MAX
676  * - the size of flexible arrays in ptr's obj (by design, dynamic size):
677  *	__builtin_object_size(ptr->flex_buf, 1) == SIZE_MAX
678  * - the size of ANY array at the end of ptr's obj (gcc and clang bug):
679  *	__builtin_object_size(ptr->end_buf, 1) == SIZE_MAX
680  *	https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101836
681  *
682  * Cases where destination size is currently detected:
683  * - the size of non-array members within ptr's object:
684  *	__builtin_object_size(ptr->a, 1) == 2
685  * - the size of non-flexible-array in the middle of ptr's obj:
686  *	__builtin_object_size(ptr->middle_buf, 1) == 16
687  *
688  */
689 
690 /*
691  * __struct_size() vs __member_size() must be captured here to avoid
692  * evaluating argument side-effects further into the macro layers.
693  */
694 #define memcpy(p, q, s)  __fortify_memcpy_chk(p, q, s,			\
695 		__struct_size(p), __struct_size(q),			\
696 		__member_size(p), __member_size(q),			\
697 		memcpy)
698 #define memmove(p, q, s)  __fortify_memcpy_chk(p, q, s,			\
699 		__struct_size(p), __struct_size(q),			\
700 		__member_size(p), __member_size(q),			\
701 		memmove)
702 
703 extern void *__real_memscan(void *, int, __kernel_size_t) __RENAME(memscan);
704 __FORTIFY_INLINE void *memscan(void * const POS0 p, int c, __kernel_size_t size)
705 {
706 	const size_t p_size = __struct_size(p);
707 
708 	if (__compiletime_lessthan(p_size, size))
709 		__read_overflow();
710 	if (p_size < size)
711 		fortify_panic(__func__);
712 	return __real_memscan(p, c, size);
713 }
714 
715 __FORTIFY_INLINE __diagnose_as(__builtin_memcmp, 1, 2, 3)
716 int memcmp(const void * const POS0 p, const void * const POS0 q, __kernel_size_t size)
717 {
718 	const size_t p_size = __struct_size(p);
719 	const size_t q_size = __struct_size(q);
720 
721 	if (__builtin_constant_p(size)) {
722 		if (__compiletime_lessthan(p_size, size))
723 			__read_overflow();
724 		if (__compiletime_lessthan(q_size, size))
725 			__read_overflow2();
726 	}
727 	if (p_size < size || q_size < size)
728 		fortify_panic(__func__);
729 	return __underlying_memcmp(p, q, size);
730 }
731 
732 __FORTIFY_INLINE __diagnose_as(__builtin_memchr, 1, 2, 3)
733 void *memchr(const void * const POS0 p, int c, __kernel_size_t size)
734 {
735 	const size_t p_size = __struct_size(p);
736 
737 	if (__compiletime_lessthan(p_size, size))
738 		__read_overflow();
739 	if (p_size < size)
740 		fortify_panic(__func__);
741 	return __underlying_memchr(p, c, size);
742 }
743 
744 void *__real_memchr_inv(const void *s, int c, size_t n) __RENAME(memchr_inv);
745 __FORTIFY_INLINE void *memchr_inv(const void * const POS0 p, int c, size_t size)
746 {
747 	const size_t p_size = __struct_size(p);
748 
749 	if (__compiletime_lessthan(p_size, size))
750 		__read_overflow();
751 	if (p_size < size)
752 		fortify_panic(__func__);
753 	return __real_memchr_inv(p, c, size);
754 }
755 
756 extern void *__real_kmemdup(const void *src, size_t len, gfp_t gfp) __RENAME(kmemdup)
757 								    __realloc_size(2);
758 __FORTIFY_INLINE void *kmemdup(const void * const POS0 p, size_t size, gfp_t gfp)
759 {
760 	const size_t p_size = __struct_size(p);
761 
762 	if (__compiletime_lessthan(p_size, size))
763 		__read_overflow();
764 	if (p_size < size)
765 		fortify_panic(__func__);
766 	return __real_kmemdup(p, size, gfp);
767 }
768 
769 /**
770  * strcpy - Copy a string into another string buffer
771  *
772  * @p: pointer to destination of copy
773  * @q: pointer to NUL-terminated source string to copy
774  *
775  * Do not use this function. While FORTIFY_SOURCE tries to avoid
776  * overflows, this is only possible when the sizes of @q and @p are
777  * known to the compiler. Prefer strscpy(), though note its different
778  * return values for detecting truncation.
779  *
780  * Returns @p.
781  *
782  */
783 /* Defined after fortified strlen to reuse it. */
784 __FORTIFY_INLINE __diagnose_as(__builtin_strcpy, 1, 2)
785 char *strcpy(char * const POS p, const char * const POS q)
786 {
787 	const size_t p_size = __member_size(p);
788 	const size_t q_size = __member_size(q);
789 	size_t size;
790 
791 	/* If neither buffer size is known, immediately give up. */
792 	if (__builtin_constant_p(p_size) &&
793 	    __builtin_constant_p(q_size) &&
794 	    p_size == SIZE_MAX && q_size == SIZE_MAX)
795 		return __underlying_strcpy(p, q);
796 	size = strlen(q) + 1;
797 	/* Compile-time check for const size overflow. */
798 	if (__compiletime_lessthan(p_size, size))
799 		__write_overflow();
800 	/* Run-time check for dynamic size overflow. */
801 	if (p_size < size)
802 		fortify_panic(__func__);
803 	__underlying_memcpy(p, q, size);
804 	return p;
805 }
806 
807 /* Don't use these outside the FORITFY_SOURCE implementation */
808 #undef __underlying_memchr
809 #undef __underlying_memcmp
810 #undef __underlying_strcat
811 #undef __underlying_strcpy
812 #undef __underlying_strlen
813 #undef __underlying_strncat
814 #undef __underlying_strncpy
815 
816 #undef POS
817 #undef POS0
818 
819 #endif /* _LINUX_FORTIFY_STRING_H_ */
820