xref: /linux-6.15/include/linux/string.h (revision e6584c39)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_STRING_H_
3 #define _LINUX_STRING_H_
4 
5 #include <linux/args.h>
6 #include <linux/array_size.h>
7 #include <linux/compiler.h>	/* for inline */
8 #include <linux/types.h>	/* for size_t */
9 #include <linux/stddef.h>	/* for NULL */
10 #include <linux/err.h>		/* for ERR_PTR() */
11 #include <linux/errno.h>	/* for E2BIG */
12 #include <linux/overflow.h>	/* for check_mul_overflow() */
13 #include <linux/stdarg.h>
14 #include <uapi/linux/string.h>
15 
16 extern char *strndup_user(const char __user *, long);
17 extern void *memdup_user(const void __user *, size_t);
18 extern void *vmemdup_user(const void __user *, size_t);
19 extern void *memdup_user_nul(const void __user *, size_t);
20 
21 /**
22  * memdup_array_user - duplicate array from user space
23  * @src: source address in user space
24  * @n: number of array members to copy
25  * @size: size of one array member
26  *
27  * Return: an ERR_PTR() on failure. Result is physically
28  * contiguous, to be freed by kfree().
29  */
30 static inline void *memdup_array_user(const void __user *src, size_t n, size_t size)
31 {
32 	size_t nbytes;
33 
34 	if (check_mul_overflow(n, size, &nbytes))
35 		return ERR_PTR(-EOVERFLOW);
36 
37 	return memdup_user(src, nbytes);
38 }
39 
40 /**
41  * vmemdup_array_user - duplicate array from user space
42  * @src: source address in user space
43  * @n: number of array members to copy
44  * @size: size of one array member
45  *
46  * Return: an ERR_PTR() on failure. Result may be not
47  * physically contiguous. Use kvfree() to free.
48  */
49 static inline void *vmemdup_array_user(const void __user *src, size_t n, size_t size)
50 {
51 	size_t nbytes;
52 
53 	if (check_mul_overflow(n, size, &nbytes))
54 		return ERR_PTR(-EOVERFLOW);
55 
56 	return vmemdup_user(src, nbytes);
57 }
58 
59 /*
60  * Include machine specific inline routines
61  */
62 #include <asm/string.h>
63 
64 #ifndef __HAVE_ARCH_STRCPY
65 extern char * strcpy(char *,const char *);
66 #endif
67 #ifndef __HAVE_ARCH_STRNCPY
68 extern char * strncpy(char *,const char *, __kernel_size_t);
69 #endif
70 ssize_t sized_strscpy(char *, const char *, size_t);
71 
72 /*
73  * The 2 argument style can only be used when dst is an array with a
74  * known size.
75  */
76 #define __strscpy0(dst, src, ...)	\
77 	sized_strscpy(dst, src, sizeof(dst) + __must_be_array(dst))
78 #define __strscpy1(dst, src, size)	sized_strscpy(dst, src, size)
79 
80 /**
81  * strscpy - Copy a C-string into a sized buffer
82  * @dst: Where to copy the string to
83  * @src: Where to copy the string from
84  * @...: Size of destination buffer (optional)
85  *
86  * Copy the source string @src, or as much of it as fits, into the
87  * destination @dst buffer. The behavior is undefined if the string
88  * buffers overlap. The destination @dst buffer is always NUL terminated,
89  * unless it's zero-sized.
90  *
91  * The size argument @... is only required when @dst is not an array, or
92  * when the copy needs to be smaller than sizeof(@dst).
93  *
94  * Preferred to strncpy() since it always returns a valid string, and
95  * doesn't unnecessarily force the tail of the destination buffer to be
96  * zero padded. If padding is desired please use strscpy_pad().
97  *
98  * Returns the number of characters copied in @dst (not including the
99  * trailing %NUL) or -E2BIG if @size is 0 or the copy from @src was
100  * truncated.
101  */
102 #define strscpy(dst, src, ...)	\
103 	CONCATENATE(__strscpy, COUNT_ARGS(__VA_ARGS__))(dst, src, __VA_ARGS__)
104 
105 /**
106  * strscpy_pad() - Copy a C-string into a sized buffer
107  * @dest: Where to copy the string to
108  * @src: Where to copy the string from
109  * @count: Size of destination buffer
110  *
111  * Copy the string, or as much of it as fits, into the dest buffer. The
112  * behavior is undefined if the string buffers overlap. The destination
113  * buffer is always %NUL terminated, unless it's zero-sized.
114  *
115  * If the source string is shorter than the destination buffer, the
116  * remaining bytes in the buffer will be filled with %NUL bytes.
117  *
118  * For full explanation of why you may want to consider using the
119  * 'strscpy' functions please see the function docstring for strscpy().
120  *
121  * Returns:
122  * * The number of characters copied (not including the trailing %NULs)
123  * * -E2BIG if count is 0 or @src was truncated.
124  */
125 #define strscpy_pad(dest, src, count)	({			\
126 	char *__dst = (dest);						\
127 	const char *__src = (src);					\
128 	const size_t __count = (count);					\
129 	ssize_t __wrote;						\
130 									\
131 	__wrote = strscpy(__dst, __src, __count);			\
132 	if (__wrote >= 0 && __wrote < __count)				\
133 		memset(__dst + __wrote + 1, 0, __count - __wrote - 1);	\
134 	__wrote;							\
135 })
136 
137 #ifndef __HAVE_ARCH_STRCAT
138 extern char * strcat(char *, const char *);
139 #endif
140 #ifndef __HAVE_ARCH_STRNCAT
141 extern char * strncat(char *, const char *, __kernel_size_t);
142 #endif
143 #ifndef __HAVE_ARCH_STRLCAT
144 extern size_t strlcat(char *, const char *, __kernel_size_t);
145 #endif
146 #ifndef __HAVE_ARCH_STRCMP
147 extern int strcmp(const char *,const char *);
148 #endif
149 #ifndef __HAVE_ARCH_STRNCMP
150 extern int strncmp(const char *,const char *,__kernel_size_t);
151 #endif
152 #ifndef __HAVE_ARCH_STRCASECMP
153 extern int strcasecmp(const char *s1, const char *s2);
154 #endif
155 #ifndef __HAVE_ARCH_STRNCASECMP
156 extern int strncasecmp(const char *s1, const char *s2, size_t n);
157 #endif
158 #ifndef __HAVE_ARCH_STRCHR
159 extern char * strchr(const char *,int);
160 #endif
161 #ifndef __HAVE_ARCH_STRCHRNUL
162 extern char * strchrnul(const char *,int);
163 #endif
164 extern char * strnchrnul(const char *, size_t, int);
165 #ifndef __HAVE_ARCH_STRNCHR
166 extern char * strnchr(const char *, size_t, int);
167 #endif
168 #ifndef __HAVE_ARCH_STRRCHR
169 extern char * strrchr(const char *,int);
170 #endif
171 extern char * __must_check skip_spaces(const char *);
172 
173 extern char *strim(char *);
174 
175 static inline __must_check char *strstrip(char *str)
176 {
177 	return strim(str);
178 }
179 
180 #ifndef __HAVE_ARCH_STRSTR
181 extern char * strstr(const char *, const char *);
182 #endif
183 #ifndef __HAVE_ARCH_STRNSTR
184 extern char * strnstr(const char *, const char *, size_t);
185 #endif
186 #ifndef __HAVE_ARCH_STRLEN
187 extern __kernel_size_t strlen(const char *);
188 #endif
189 #ifndef __HAVE_ARCH_STRNLEN
190 extern __kernel_size_t strnlen(const char *,__kernel_size_t);
191 #endif
192 #ifndef __HAVE_ARCH_STRPBRK
193 extern char * strpbrk(const char *,const char *);
194 #endif
195 #ifndef __HAVE_ARCH_STRSEP
196 extern char * strsep(char **,const char *);
197 #endif
198 #ifndef __HAVE_ARCH_STRSPN
199 extern __kernel_size_t strspn(const char *,const char *);
200 #endif
201 #ifndef __HAVE_ARCH_STRCSPN
202 extern __kernel_size_t strcspn(const char *,const char *);
203 #endif
204 
205 #ifndef __HAVE_ARCH_MEMSET
206 extern void * memset(void *,int,__kernel_size_t);
207 #endif
208 
209 #ifndef __HAVE_ARCH_MEMSET16
210 extern void *memset16(uint16_t *, uint16_t, __kernel_size_t);
211 #endif
212 
213 #ifndef __HAVE_ARCH_MEMSET32
214 extern void *memset32(uint32_t *, uint32_t, __kernel_size_t);
215 #endif
216 
217 #ifndef __HAVE_ARCH_MEMSET64
218 extern void *memset64(uint64_t *, uint64_t, __kernel_size_t);
219 #endif
220 
221 static inline void *memset_l(unsigned long *p, unsigned long v,
222 		__kernel_size_t n)
223 {
224 	if (BITS_PER_LONG == 32)
225 		return memset32((uint32_t *)p, v, n);
226 	else
227 		return memset64((uint64_t *)p, v, n);
228 }
229 
230 static inline void *memset_p(void **p, void *v, __kernel_size_t n)
231 {
232 	if (BITS_PER_LONG == 32)
233 		return memset32((uint32_t *)p, (uintptr_t)v, n);
234 	else
235 		return memset64((uint64_t *)p, (uintptr_t)v, n);
236 }
237 
238 extern void **__memcat_p(void **a, void **b);
239 #define memcat_p(a, b) ({					\
240 	BUILD_BUG_ON_MSG(!__same_type(*(a), *(b)),		\
241 			 "type mismatch in memcat_p()");	\
242 	(typeof(*a) *)__memcat_p((void **)(a), (void **)(b));	\
243 })
244 
245 #ifndef __HAVE_ARCH_MEMCPY
246 extern void * memcpy(void *,const void *,__kernel_size_t);
247 #endif
248 #ifndef __HAVE_ARCH_MEMMOVE
249 extern void * memmove(void *,const void *,__kernel_size_t);
250 #endif
251 #ifndef __HAVE_ARCH_MEMSCAN
252 extern void * memscan(void *,int,__kernel_size_t);
253 #endif
254 #ifndef __HAVE_ARCH_MEMCMP
255 extern int memcmp(const void *,const void *,__kernel_size_t);
256 #endif
257 #ifndef __HAVE_ARCH_BCMP
258 extern int bcmp(const void *,const void *,__kernel_size_t);
259 #endif
260 #ifndef __HAVE_ARCH_MEMCHR
261 extern void * memchr(const void *,int,__kernel_size_t);
262 #endif
263 #ifndef __HAVE_ARCH_MEMCPY_FLUSHCACHE
264 static inline void memcpy_flushcache(void *dst, const void *src, size_t cnt)
265 {
266 	memcpy(dst, src, cnt);
267 }
268 #endif
269 
270 void *memchr_inv(const void *s, int c, size_t n);
271 char *strreplace(char *str, char old, char new);
272 
273 extern void kfree_const(const void *x);
274 
275 extern char *kstrdup(const char *s, gfp_t gfp) __malloc;
276 extern const char *kstrdup_const(const char *s, gfp_t gfp);
277 extern char *kstrndup(const char *s, size_t len, gfp_t gfp);
278 extern void *kmemdup(const void *src, size_t len, gfp_t gfp) __realloc_size(2);
279 extern void *kvmemdup(const void *src, size_t len, gfp_t gfp) __realloc_size(2);
280 extern char *kmemdup_nul(const char *s, size_t len, gfp_t gfp);
281 
282 extern char **argv_split(gfp_t gfp, const char *str, int *argcp);
283 extern void argv_free(char **argv);
284 
285 extern bool sysfs_streq(const char *s1, const char *s2);
286 int match_string(const char * const *array, size_t n, const char *string);
287 int __sysfs_match_string(const char * const *array, size_t n, const char *s);
288 
289 /**
290  * sysfs_match_string - matches given string in an array
291  * @_a: array of strings
292  * @_s: string to match with
293  *
294  * Helper for __sysfs_match_string(). Calculates the size of @a automatically.
295  */
296 #define sysfs_match_string(_a, _s) __sysfs_match_string(_a, ARRAY_SIZE(_a), _s)
297 
298 #ifdef CONFIG_BINARY_PRINTF
299 int vbin_printf(u32 *bin_buf, size_t size, const char *fmt, va_list args);
300 int bstr_printf(char *buf, size_t size, const char *fmt, const u32 *bin_buf);
301 int bprintf(u32 *bin_buf, size_t size, const char *fmt, ...) __printf(3, 4);
302 #endif
303 
304 extern ssize_t memory_read_from_buffer(void *to, size_t count, loff_t *ppos,
305 				       const void *from, size_t available);
306 
307 int ptr_to_hashval(const void *ptr, unsigned long *hashval_out);
308 
309 /**
310  * strstarts - does @str start with @prefix?
311  * @str: string to examine
312  * @prefix: prefix to look for.
313  */
314 static inline bool strstarts(const char *str, const char *prefix)
315 {
316 	return strncmp(str, prefix, strlen(prefix)) == 0;
317 }
318 
319 size_t memweight(const void *ptr, size_t bytes);
320 
321 /**
322  * memzero_explicit - Fill a region of memory (e.g. sensitive
323  *		      keying data) with 0s.
324  * @s: Pointer to the start of the area.
325  * @count: The size of the area.
326  *
327  * Note: usually using memset() is just fine (!), but in cases
328  * where clearing out _local_ data at the end of a scope is
329  * necessary, memzero_explicit() should be used instead in
330  * order to prevent the compiler from optimising away zeroing.
331  *
332  * memzero_explicit() doesn't need an arch-specific version as
333  * it just invokes the one of memset() implicitly.
334  */
335 static inline void memzero_explicit(void *s, size_t count)
336 {
337 	memset(s, 0, count);
338 	barrier_data(s);
339 }
340 
341 /**
342  * kbasename - return the last part of a pathname.
343  *
344  * @path: path to extract the filename from.
345  */
346 static inline const char *kbasename(const char *path)
347 {
348 	const char *tail = strrchr(path, '/');
349 	return tail ? tail + 1 : path;
350 }
351 
352 #if !defined(__NO_FORTIFY) && defined(__OPTIMIZE__) && defined(CONFIG_FORTIFY_SOURCE)
353 #include <linux/fortify-string.h>
354 #endif
355 #ifndef unsafe_memcpy
356 #define unsafe_memcpy(dst, src, bytes, justification)		\
357 	memcpy(dst, src, bytes)
358 #endif
359 
360 void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count,
361 		    int pad);
362 
363 /**
364  * strtomem_pad - Copy NUL-terminated string to non-NUL-terminated buffer
365  *
366  * @dest: Pointer of destination character array (marked as __nonstring)
367  * @src: Pointer to NUL-terminated string
368  * @pad: Padding character to fill any remaining bytes of @dest after copy
369  *
370  * This is a replacement for strncpy() uses where the destination is not
371  * a NUL-terminated string, but with bounds checking on the source size, and
372  * an explicit padding character. If padding is not required, use strtomem().
373  *
374  * Note that the size of @dest is not an argument, as the length of @dest
375  * must be discoverable by the compiler.
376  */
377 #define strtomem_pad(dest, src, pad)	do {				\
378 	const size_t _dest_len = __builtin_object_size(dest, 1);	\
379 	const size_t _src_len = __builtin_object_size(src, 1);		\
380 									\
381 	BUILD_BUG_ON(!__builtin_constant_p(_dest_len) ||		\
382 		     _dest_len == (size_t)-1);				\
383 	memcpy_and_pad(dest, _dest_len, src,				\
384 		       strnlen(src, min(_src_len, _dest_len)), pad);	\
385 } while (0)
386 
387 /**
388  * strtomem - Copy NUL-terminated string to non-NUL-terminated buffer
389  *
390  * @dest: Pointer of destination character array (marked as __nonstring)
391  * @src: Pointer to NUL-terminated string
392  *
393  * This is a replacement for strncpy() uses where the destination is not
394  * a NUL-terminated string, but with bounds checking on the source size, and
395  * without trailing padding. If padding is required, use strtomem_pad().
396  *
397  * Note that the size of @dest is not an argument, as the length of @dest
398  * must be discoverable by the compiler.
399  */
400 #define strtomem(dest, src)	do {					\
401 	const size_t _dest_len = __builtin_object_size(dest, 1);	\
402 	const size_t _src_len = __builtin_object_size(src, 1);		\
403 									\
404 	BUILD_BUG_ON(!__builtin_constant_p(_dest_len) ||		\
405 		     _dest_len == (size_t)-1);				\
406 	memcpy(dest, src, strnlen(src, min(_src_len, _dest_len)));	\
407 } while (0)
408 
409 /**
410  * memset_after - Set a value after a struct member to the end of a struct
411  *
412  * @obj: Address of target struct instance
413  * @v: Byte value to repeatedly write
414  * @member: after which struct member to start writing bytes
415  *
416  * This is good for clearing padding following the given member.
417  */
418 #define memset_after(obj, v, member)					\
419 ({									\
420 	u8 *__ptr = (u8 *)(obj);					\
421 	typeof(v) __val = (v);						\
422 	memset(__ptr + offsetofend(typeof(*(obj)), member), __val,	\
423 	       sizeof(*(obj)) - offsetofend(typeof(*(obj)), member));	\
424 })
425 
426 /**
427  * memset_startat - Set a value starting at a member to the end of a struct
428  *
429  * @obj: Address of target struct instance
430  * @v: Byte value to repeatedly write
431  * @member: struct member to start writing at
432  *
433  * Note that if there is padding between the prior member and the target
434  * member, memset_after() should be used to clear the prior padding.
435  */
436 #define memset_startat(obj, v, member)					\
437 ({									\
438 	u8 *__ptr = (u8 *)(obj);					\
439 	typeof(v) __val = (v);						\
440 	memset(__ptr + offsetof(typeof(*(obj)), member), __val,		\
441 	       sizeof(*(obj)) - offsetof(typeof(*(obj)), member));	\
442 })
443 
444 /**
445  * str_has_prefix - Test if a string has a given prefix
446  * @str: The string to test
447  * @prefix: The string to see if @str starts with
448  *
449  * A common way to test a prefix of a string is to do:
450  *  strncmp(str, prefix, sizeof(prefix) - 1)
451  *
452  * But this can lead to bugs due to typos, or if prefix is a pointer
453  * and not a constant. Instead use str_has_prefix().
454  *
455  * Returns:
456  * * strlen(@prefix) if @str starts with @prefix
457  * * 0 if @str does not start with @prefix
458  */
459 static __always_inline size_t str_has_prefix(const char *str, const char *prefix)
460 {
461 	size_t len = strlen(prefix);
462 	return strncmp(str, prefix, len) == 0 ? len : 0;
463 }
464 
465 #endif /* _LINUX_STRING_H_ */
466