xref: /linux/lib/string_helpers.c (revision 3a39d672e7f48b8d6b91a09afa4b55352773b4b5)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
23c9f3681SJames Bottomley /*
33c9f3681SJames Bottomley  * Helpers for formatting and printing strings
43c9f3681SJames Bottomley  *
53c9f3681SJames Bottomley  * Copyright 31 August 2008 James Bottomley
616c7fa05SAndy Shevchenko  * Copyright (C) 2013, Intel Corporation
73c9f3681SJames Bottomley  */
8b9f28d86SJames Bottomley #include <linux/bug.h>
93c9f3681SJames Bottomley #include <linux/kernel.h>
103c9f3681SJames Bottomley #include <linux/math64.h>
118bc3bcc9SPaul Gortmaker #include <linux/export.h>
1216c7fa05SAndy Shevchenko #include <linux/ctype.h>
13acdb89b6SAndy Shevchenko #include <linux/device.h>
14c8250381SAndy Shevchenko #include <linux/errno.h>
1521985319SKees Cook #include <linux/fs.h>
1621985319SKees Cook #include <linux/limits.h>
170d044328SKees Cook #include <linux/mm.h>
18b53f27e4SKees Cook #include <linux/slab.h>
19c8250381SAndy Shevchenko #include <linux/string.h>
203c9f3681SJames Bottomley #include <linux/string_helpers.h>
214ce615e7SKees Cook #include <kunit/test.h>
224ce615e7SKees Cook #include <kunit/test-bug.h>
233c9f3681SJames Bottomley 
243c9f3681SJames Bottomley /**
253c9f3681SJames Bottomley  * string_get_size - get the size in the specified units
26b9f28d86SJames Bottomley  * @size:	The size to be converted in blocks
27b9f28d86SJames Bottomley  * @blk_size:	Size of the block (use 1 for size in bytes)
28f0b7f8adSAndy Shevchenko  * @units:	Units to use (powers of 1000 or 1024), whether to include space separator
293c9f3681SJames Bottomley  * @buf:	buffer to format to
303c9f3681SJames Bottomley  * @len:	length of buffer
313c9f3681SJames Bottomley  *
323c9f3681SJames Bottomley  * This function returns a string formatted to 3 significant figures
33d1214c65SRasmus Villemoes  * giving the size in the required units.  @buf should have room for
34d1214c65SRasmus Villemoes  * at least 9 bytes and will always be zero terminated.
353c9f3681SJames Bottomley  *
3683feeb19SKent Overstreet  * Return value: number of characters of output that would have been written
3783feeb19SKent Overstreet  * (which may be greater than len, if output was truncated).
383c9f3681SJames Bottomley  */
string_get_size(u64 size,u64 blk_size,const enum string_size_units units,char * buf,int len)3983feeb19SKent Overstreet int string_get_size(u64 size, u64 blk_size, const enum string_size_units units,
403c9f3681SJames Bottomley 		    char *buf, int len)
413c9f3681SJames Bottomley {
42f0b7f8adSAndy Shevchenko 	enum string_size_units units_base = units & STRING_UNITS_MASK;
43142cda5dSMathias Krause 	static const char *const units_10[] = {
44f0b7f8adSAndy Shevchenko 		"", "k", "M", "G", "T", "P", "E", "Z", "Y",
45142cda5dSMathias Krause 	};
46142cda5dSMathias Krause 	static const char *const units_2[] = {
47f0b7f8adSAndy Shevchenko 		"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi",
48142cda5dSMathias Krause 	};
49142cda5dSMathias Krause 	static const char *const *const units_str[] = {
503c9f3681SJames Bottomley 		[STRING_UNITS_10] = units_10,
513c9f3681SJames Bottomley 		[STRING_UNITS_2] = units_2,
523c9f3681SJames Bottomley 	};
5368aecfb9SAndrew Morton 	static const unsigned int divisor[] = {
543c9f3681SJames Bottomley 		[STRING_UNITS_10] = 1000,
553c9f3681SJames Bottomley 		[STRING_UNITS_2] = 1024,
563c9f3681SJames Bottomley 	};
57564b026fSJames Bottomley 	static const unsigned int rounding[] = { 500, 50, 5 };
58564b026fSJames Bottomley 	int i = 0, j;
59564b026fSJames Bottomley 	u32 remainder = 0, sf_cap;
603c9f3681SJames Bottomley 	char tmp[8];
61b9f28d86SJames Bottomley 	const char *unit;
623c9f3681SJames Bottomley 
633c9f3681SJames Bottomley 	tmp[0] = '\0';
64564b026fSJames Bottomley 
65564b026fSJames Bottomley 	if (blk_size == 0)
66564b026fSJames Bottomley 		size = 0;
67564b026fSJames Bottomley 	if (size == 0)
68b9f28d86SJames Bottomley 		goto out;
69b9f28d86SJames Bottomley 
70564b026fSJames Bottomley 	/* This is Napier's algorithm.  Reduce the original block size to
71564b026fSJames Bottomley 	 *
72f0b7f8adSAndy Shevchenko 	 * coefficient * divisor[units_base]^i
73564b026fSJames Bottomley 	 *
74564b026fSJames Bottomley 	 * we do the reduction so both coefficients are just under 32 bits so
75564b026fSJames Bottomley 	 * that multiplying them together won't overflow 64 bits and we keep
76564b026fSJames Bottomley 	 * as much precision as possible in the numbers.
77564b026fSJames Bottomley 	 *
78564b026fSJames Bottomley 	 * Note: it's safe to throw away the remainders here because all the
79564b026fSJames Bottomley 	 * precision is in the coefficients.
8062bef58aSVitaly Kuznetsov 	 */
81564b026fSJames Bottomley 	while (blk_size >> 32) {
82f0b7f8adSAndy Shevchenko 		do_div(blk_size, divisor[units_base]);
83b9f28d86SJames Bottomley 		i++;
84b9f28d86SJames Bottomley 	}
85b9f28d86SJames Bottomley 
86564b026fSJames Bottomley 	while (size >> 32) {
87f0b7f8adSAndy Shevchenko 		do_div(size, divisor[units_base]);
88564b026fSJames Bottomley 		i++;
89564b026fSJames Bottomley 	}
90b9f28d86SJames Bottomley 
91564b026fSJames Bottomley 	/* now perform the actual multiplication keeping i as the sum of the
92564b026fSJames Bottomley 	 * two logarithms */
93564b026fSJames Bottomley 	size *= blk_size;
94564b026fSJames Bottomley 
95564b026fSJames Bottomley 	/* and logarithmically reduce it until it's just under the divisor */
96f0b7f8adSAndy Shevchenko 	while (size >= divisor[units_base]) {
97f0b7f8adSAndy Shevchenko 		remainder = do_div(size, divisor[units_base]);
98a8659597SH. Peter Anvin 		i++;
99a8659597SH. Peter Anvin 	}
1003c9f3681SJames Bottomley 
101564b026fSJames Bottomley 	/* work out in j how many digits of precision we need from the
102564b026fSJames Bottomley 	 * remainder */
1033c9f3681SJames Bottomley 	sf_cap = size;
1043c9f3681SJames Bottomley 	for (j = 0; sf_cap*10 < 1000; j++)
1053c9f3681SJames Bottomley 		sf_cap *= 10;
1063c9f3681SJames Bottomley 
107f0b7f8adSAndy Shevchenko 	if (units_base == STRING_UNITS_2) {
108564b026fSJames Bottomley 		/* express the remainder as a decimal.  It's currently the
109564b026fSJames Bottomley 		 * numerator of a fraction whose denominator is
110f0b7f8adSAndy Shevchenko 		 * divisor[units_base], which is 1 << 10 for STRING_UNITS_2 */
1113c9f3681SJames Bottomley 		remainder *= 1000;
112564b026fSJames Bottomley 		remainder >>= 10;
113564b026fSJames Bottomley 	}
114564b026fSJames Bottomley 
115564b026fSJames Bottomley 	/* add a 5 to the digit below what will be printed to ensure
116564b026fSJames Bottomley 	 * an arithmetical round up and carry it through to size */
117564b026fSJames Bottomley 	remainder += rounding[j];
118564b026fSJames Bottomley 	if (remainder >= 1000) {
119564b026fSJames Bottomley 		remainder -= 1000;
120564b026fSJames Bottomley 		size += 1;
121564b026fSJames Bottomley 	}
122564b026fSJames Bottomley 
123564b026fSJames Bottomley 	if (j) {
12484b9fbedSRasmus Villemoes 		snprintf(tmp, sizeof(tmp), ".%03u", remainder);
1253c9f3681SJames Bottomley 		tmp[j+1] = '\0';
1263c9f3681SJames Bottomley 	}
127b9f28d86SJames Bottomley 
128b9f28d86SJames Bottomley  out:
129b9f28d86SJames Bottomley 	if (i >= ARRAY_SIZE(units_2))
130b9f28d86SJames Bottomley 		unit = "UNK";
131b9f28d86SJames Bottomley 	else
132f0b7f8adSAndy Shevchenko 		unit = units_str[units_base][i];
1333c9f3681SJames Bottomley 
134f0b7f8adSAndy Shevchenko 	return snprintf(buf, len, "%u%s%s%s%s", (u32)size, tmp,
135f0b7f8adSAndy Shevchenko 			(units & STRING_UNITS_NO_SPACE) ? "" : " ",
136f0b7f8adSAndy Shevchenko 			unit,
137f0b7f8adSAndy Shevchenko 			(units & STRING_UNITS_NO_BYTES) ? "" : "B");
1383c9f3681SJames Bottomley }
1393c9f3681SJames Bottomley EXPORT_SYMBOL(string_get_size);
14016c7fa05SAndy Shevchenko 
141f0b93323SCezary Rojewski /**
142f0b93323SCezary Rojewski  * parse_int_array_user - Split string into a sequence of integers
143f0b93323SCezary Rojewski  * @from:	The user space buffer to read from
144f0b93323SCezary Rojewski  * @count:	The maximum number of bytes to read
145f0b93323SCezary Rojewski  * @array:	Returned pointer to sequence of integers
146f0b93323SCezary Rojewski  *
147f0b93323SCezary Rojewski  * On success @array is allocated and initialized with a sequence of
148f0b93323SCezary Rojewski  * integers extracted from the @from plus an additional element that
149f0b93323SCezary Rojewski  * begins the sequence and specifies the integers count.
150f0b93323SCezary Rojewski  *
151f0b93323SCezary Rojewski  * Caller takes responsibility for freeing @array when it is no longer
152f0b93323SCezary Rojewski  * needed.
153f0b93323SCezary Rojewski  */
parse_int_array_user(const char __user * from,size_t count,int ** array)154f0b93323SCezary Rojewski int parse_int_array_user(const char __user *from, size_t count, int **array)
155f0b93323SCezary Rojewski {
156f0b93323SCezary Rojewski 	int *ints, nints;
157f0b93323SCezary Rojewski 	char *buf;
158f0b93323SCezary Rojewski 	int ret = 0;
159f0b93323SCezary Rojewski 
160f0b93323SCezary Rojewski 	buf = memdup_user_nul(from, count);
161f0b93323SCezary Rojewski 	if (IS_ERR(buf))
162f0b93323SCezary Rojewski 		return PTR_ERR(buf);
163f0b93323SCezary Rojewski 
164f0b93323SCezary Rojewski 	get_options(buf, 0, &nints);
165f0b93323SCezary Rojewski 	if (!nints) {
166f0b93323SCezary Rojewski 		ret = -ENOENT;
167f0b93323SCezary Rojewski 		goto free_buf;
168f0b93323SCezary Rojewski 	}
169f0b93323SCezary Rojewski 
170f0b93323SCezary Rojewski 	ints = kcalloc(nints + 1, sizeof(*ints), GFP_KERNEL);
171f0b93323SCezary Rojewski 	if (!ints) {
172f0b93323SCezary Rojewski 		ret = -ENOMEM;
173f0b93323SCezary Rojewski 		goto free_buf;
174f0b93323SCezary Rojewski 	}
175f0b93323SCezary Rojewski 
176f0b93323SCezary Rojewski 	get_options(buf, nints + 1, ints);
177f0b93323SCezary Rojewski 	*array = ints;
178f0b93323SCezary Rojewski 
179f0b93323SCezary Rojewski free_buf:
180f0b93323SCezary Rojewski 	kfree(buf);
181f0b93323SCezary Rojewski 	return ret;
182f0b93323SCezary Rojewski }
183f0b93323SCezary Rojewski EXPORT_SYMBOL(parse_int_array_user);
184f0b93323SCezary Rojewski 
unescape_space(char ** src,char ** dst)18516c7fa05SAndy Shevchenko static bool unescape_space(char **src, char **dst)
18616c7fa05SAndy Shevchenko {
18716c7fa05SAndy Shevchenko 	char *p = *dst, *q = *src;
18816c7fa05SAndy Shevchenko 
18916c7fa05SAndy Shevchenko 	switch (*q) {
19016c7fa05SAndy Shevchenko 	case 'n':
19116c7fa05SAndy Shevchenko 		*p = '\n';
19216c7fa05SAndy Shevchenko 		break;
19316c7fa05SAndy Shevchenko 	case 'r':
19416c7fa05SAndy Shevchenko 		*p = '\r';
19516c7fa05SAndy Shevchenko 		break;
19616c7fa05SAndy Shevchenko 	case 't':
19716c7fa05SAndy Shevchenko 		*p = '\t';
19816c7fa05SAndy Shevchenko 		break;
19916c7fa05SAndy Shevchenko 	case 'v':
20016c7fa05SAndy Shevchenko 		*p = '\v';
20116c7fa05SAndy Shevchenko 		break;
20216c7fa05SAndy Shevchenko 	case 'f':
20316c7fa05SAndy Shevchenko 		*p = '\f';
20416c7fa05SAndy Shevchenko 		break;
20516c7fa05SAndy Shevchenko 	default:
20616c7fa05SAndy Shevchenko 		return false;
20716c7fa05SAndy Shevchenko 	}
20816c7fa05SAndy Shevchenko 	*dst += 1;
20916c7fa05SAndy Shevchenko 	*src += 1;
21016c7fa05SAndy Shevchenko 	return true;
21116c7fa05SAndy Shevchenko }
21216c7fa05SAndy Shevchenko 
unescape_octal(char ** src,char ** dst)21316c7fa05SAndy Shevchenko static bool unescape_octal(char **src, char **dst)
21416c7fa05SAndy Shevchenko {
21516c7fa05SAndy Shevchenko 	char *p = *dst, *q = *src;
21616c7fa05SAndy Shevchenko 	u8 num;
21716c7fa05SAndy Shevchenko 
21816c7fa05SAndy Shevchenko 	if (isodigit(*q) == 0)
21916c7fa05SAndy Shevchenko 		return false;
22016c7fa05SAndy Shevchenko 
22116c7fa05SAndy Shevchenko 	num = (*q++) & 7;
22216c7fa05SAndy Shevchenko 	while (num < 32 && isodigit(*q) && (q - *src < 3)) {
22316c7fa05SAndy Shevchenko 		num <<= 3;
22416c7fa05SAndy Shevchenko 		num += (*q++) & 7;
22516c7fa05SAndy Shevchenko 	}
22616c7fa05SAndy Shevchenko 	*p = num;
22716c7fa05SAndy Shevchenko 	*dst += 1;
22816c7fa05SAndy Shevchenko 	*src = q;
22916c7fa05SAndy Shevchenko 	return true;
23016c7fa05SAndy Shevchenko }
23116c7fa05SAndy Shevchenko 
unescape_hex(char ** src,char ** dst)23216c7fa05SAndy Shevchenko static bool unescape_hex(char **src, char **dst)
23316c7fa05SAndy Shevchenko {
23416c7fa05SAndy Shevchenko 	char *p = *dst, *q = *src;
23516c7fa05SAndy Shevchenko 	int digit;
23616c7fa05SAndy Shevchenko 	u8 num;
23716c7fa05SAndy Shevchenko 
23816c7fa05SAndy Shevchenko 	if (*q++ != 'x')
23916c7fa05SAndy Shevchenko 		return false;
24016c7fa05SAndy Shevchenko 
24116c7fa05SAndy Shevchenko 	num = digit = hex_to_bin(*q++);
24216c7fa05SAndy Shevchenko 	if (digit < 0)
24316c7fa05SAndy Shevchenko 		return false;
24416c7fa05SAndy Shevchenko 
24516c7fa05SAndy Shevchenko 	digit = hex_to_bin(*q);
24616c7fa05SAndy Shevchenko 	if (digit >= 0) {
24716c7fa05SAndy Shevchenko 		q++;
24816c7fa05SAndy Shevchenko 		num = (num << 4) | digit;
24916c7fa05SAndy Shevchenko 	}
25016c7fa05SAndy Shevchenko 	*p = num;
25116c7fa05SAndy Shevchenko 	*dst += 1;
25216c7fa05SAndy Shevchenko 	*src = q;
25316c7fa05SAndy Shevchenko 	return true;
25416c7fa05SAndy Shevchenko }
25516c7fa05SAndy Shevchenko 
unescape_special(char ** src,char ** dst)25616c7fa05SAndy Shevchenko static bool unescape_special(char **src, char **dst)
25716c7fa05SAndy Shevchenko {
25816c7fa05SAndy Shevchenko 	char *p = *dst, *q = *src;
25916c7fa05SAndy Shevchenko 
26016c7fa05SAndy Shevchenko 	switch (*q) {
26116c7fa05SAndy Shevchenko 	case '\"':
26216c7fa05SAndy Shevchenko 		*p = '\"';
26316c7fa05SAndy Shevchenko 		break;
26416c7fa05SAndy Shevchenko 	case '\\':
26516c7fa05SAndy Shevchenko 		*p = '\\';
26616c7fa05SAndy Shevchenko 		break;
26716c7fa05SAndy Shevchenko 	case 'a':
26816c7fa05SAndy Shevchenko 		*p = '\a';
26916c7fa05SAndy Shevchenko 		break;
27016c7fa05SAndy Shevchenko 	case 'e':
27116c7fa05SAndy Shevchenko 		*p = '\e';
27216c7fa05SAndy Shevchenko 		break;
27316c7fa05SAndy Shevchenko 	default:
27416c7fa05SAndy Shevchenko 		return false;
27516c7fa05SAndy Shevchenko 	}
27616c7fa05SAndy Shevchenko 	*dst += 1;
27716c7fa05SAndy Shevchenko 	*src += 1;
27816c7fa05SAndy Shevchenko 	return true;
27916c7fa05SAndy Shevchenko }
28016c7fa05SAndy Shevchenko 
281d295634eSAndy Shevchenko /**
282d295634eSAndy Shevchenko  * string_unescape - unquote characters in the given string
283d295634eSAndy Shevchenko  * @src:	source buffer (escaped)
284d295634eSAndy Shevchenko  * @dst:	destination buffer (unescaped)
285d295634eSAndy Shevchenko  * @size:	size of the destination buffer (0 to unlimit)
286b4658cddSJonathan Corbet  * @flags:	combination of the flags.
287d295634eSAndy Shevchenko  *
288d295634eSAndy Shevchenko  * Description:
289d295634eSAndy Shevchenko  * The function unquotes characters in the given string.
290d295634eSAndy Shevchenko  *
291d295634eSAndy Shevchenko  * Because the size of the output will be the same as or less than the size of
292d295634eSAndy Shevchenko  * the input, the transformation may be performed in place.
293d295634eSAndy Shevchenko  *
294d295634eSAndy Shevchenko  * Caller must provide valid source and destination pointers. Be aware that
295d295634eSAndy Shevchenko  * destination buffer will always be NULL-terminated. Source string must be
296b4658cddSJonathan Corbet  * NULL-terminated as well.  The supported flags are::
297b4658cddSJonathan Corbet  *
298b4658cddSJonathan Corbet  *	UNESCAPE_SPACE:
299b4658cddSJonathan Corbet  *		'\f' - form feed
300b4658cddSJonathan Corbet  *		'\n' - new line
301b4658cddSJonathan Corbet  *		'\r' - carriage return
302b4658cddSJonathan Corbet  *		'\t' - horizontal tab
303b4658cddSJonathan Corbet  *		'\v' - vertical tab
304b4658cddSJonathan Corbet  *	UNESCAPE_OCTAL:
305b4658cddSJonathan Corbet  *		'\NNN' - byte with octal value NNN (1 to 3 digits)
306b4658cddSJonathan Corbet  *	UNESCAPE_HEX:
307b4658cddSJonathan Corbet  *		'\xHH' - byte with hexadecimal value HH (1 to 2 digits)
308b4658cddSJonathan Corbet  *	UNESCAPE_SPECIAL:
309b4658cddSJonathan Corbet  *		'\"' - double quote
310b4658cddSJonathan Corbet  *		'\\' - backslash
311b4658cddSJonathan Corbet  *		'\a' - alert (BEL)
312b4658cddSJonathan Corbet  *		'\e' - escape
313b4658cddSJonathan Corbet  *	UNESCAPE_ANY:
314b4658cddSJonathan Corbet  *		all previous together
315d295634eSAndy Shevchenko  *
316d295634eSAndy Shevchenko  * Return:
317d295634eSAndy Shevchenko  * The amount of the characters processed to the destination buffer excluding
318d295634eSAndy Shevchenko  * trailing '\0' is returned.
319d295634eSAndy Shevchenko  */
string_unescape(char * src,char * dst,size_t size,unsigned int flags)32016c7fa05SAndy Shevchenko int string_unescape(char *src, char *dst, size_t size, unsigned int flags)
32116c7fa05SAndy Shevchenko {
32216c7fa05SAndy Shevchenko 	char *out = dst;
32316c7fa05SAndy Shevchenko 
324*bbf3c7ffSJustin Stitt 	if (!size)
325*bbf3c7ffSJustin Stitt 		size = SIZE_MAX;
326*bbf3c7ffSJustin Stitt 
32716c7fa05SAndy Shevchenko 	while (*src && --size) {
32816c7fa05SAndy Shevchenko 		if (src[0] == '\\' && src[1] != '\0' && size > 1) {
32916c7fa05SAndy Shevchenko 			src++;
33016c7fa05SAndy Shevchenko 			size--;
33116c7fa05SAndy Shevchenko 
33216c7fa05SAndy Shevchenko 			if (flags & UNESCAPE_SPACE &&
33316c7fa05SAndy Shevchenko 					unescape_space(&src, &out))
33416c7fa05SAndy Shevchenko 				continue;
33516c7fa05SAndy Shevchenko 
33616c7fa05SAndy Shevchenko 			if (flags & UNESCAPE_OCTAL &&
33716c7fa05SAndy Shevchenko 					unescape_octal(&src, &out))
33816c7fa05SAndy Shevchenko 				continue;
33916c7fa05SAndy Shevchenko 
34016c7fa05SAndy Shevchenko 			if (flags & UNESCAPE_HEX &&
34116c7fa05SAndy Shevchenko 					unescape_hex(&src, &out))
34216c7fa05SAndy Shevchenko 				continue;
34316c7fa05SAndy Shevchenko 
34416c7fa05SAndy Shevchenko 			if (flags & UNESCAPE_SPECIAL &&
34516c7fa05SAndy Shevchenko 					unescape_special(&src, &out))
34616c7fa05SAndy Shevchenko 				continue;
34716c7fa05SAndy Shevchenko 
34816c7fa05SAndy Shevchenko 			*out++ = '\\';
34916c7fa05SAndy Shevchenko 		}
35016c7fa05SAndy Shevchenko 		*out++ = *src++;
35116c7fa05SAndy Shevchenko 	}
35216c7fa05SAndy Shevchenko 	*out = '\0';
35316c7fa05SAndy Shevchenko 
35416c7fa05SAndy Shevchenko 	return out - dst;
35516c7fa05SAndy Shevchenko }
35616c7fa05SAndy Shevchenko EXPORT_SYMBOL(string_unescape);
357c8250381SAndy Shevchenko 
escape_passthrough(unsigned char c,char ** dst,char * end)3583aeddc7dSRasmus Villemoes static bool escape_passthrough(unsigned char c, char **dst, char *end)
359c8250381SAndy Shevchenko {
360c8250381SAndy Shevchenko 	char *out = *dst;
361c8250381SAndy Shevchenko 
3623aeddc7dSRasmus Villemoes 	if (out < end)
3633aeddc7dSRasmus Villemoes 		*out = c;
3643aeddc7dSRasmus Villemoes 	*dst = out + 1;
3653aeddc7dSRasmus Villemoes 	return true;
366c8250381SAndy Shevchenko }
367c8250381SAndy Shevchenko 
escape_space(unsigned char c,char ** dst,char * end)3683aeddc7dSRasmus Villemoes static bool escape_space(unsigned char c, char **dst, char *end)
369c8250381SAndy Shevchenko {
370c8250381SAndy Shevchenko 	char *out = *dst;
371c8250381SAndy Shevchenko 	unsigned char to;
372c8250381SAndy Shevchenko 
373c8250381SAndy Shevchenko 	switch (c) {
374c8250381SAndy Shevchenko 	case '\n':
375c8250381SAndy Shevchenko 		to = 'n';
376c8250381SAndy Shevchenko 		break;
377c8250381SAndy Shevchenko 	case '\r':
378c8250381SAndy Shevchenko 		to = 'r';
379c8250381SAndy Shevchenko 		break;
380c8250381SAndy Shevchenko 	case '\t':
381c8250381SAndy Shevchenko 		to = 't';
382c8250381SAndy Shevchenko 		break;
383c8250381SAndy Shevchenko 	case '\v':
384c8250381SAndy Shevchenko 		to = 'v';
385c8250381SAndy Shevchenko 		break;
386c8250381SAndy Shevchenko 	case '\f':
387c8250381SAndy Shevchenko 		to = 'f';
388c8250381SAndy Shevchenko 		break;
389c8250381SAndy Shevchenko 	default:
3903aeddc7dSRasmus Villemoes 		return false;
391c8250381SAndy Shevchenko 	}
392c8250381SAndy Shevchenko 
3933aeddc7dSRasmus Villemoes 	if (out < end)
3943aeddc7dSRasmus Villemoes 		*out = '\\';
3953aeddc7dSRasmus Villemoes 	++out;
3963aeddc7dSRasmus Villemoes 	if (out < end)
3973aeddc7dSRasmus Villemoes 		*out = to;
3983aeddc7dSRasmus Villemoes 	++out;
399c8250381SAndy Shevchenko 
400c8250381SAndy Shevchenko 	*dst = out;
4013aeddc7dSRasmus Villemoes 	return true;
402c8250381SAndy Shevchenko }
403c8250381SAndy Shevchenko 
escape_special(unsigned char c,char ** dst,char * end)4043aeddc7dSRasmus Villemoes static bool escape_special(unsigned char c, char **dst, char *end)
405c8250381SAndy Shevchenko {
406c8250381SAndy Shevchenko 	char *out = *dst;
407c8250381SAndy Shevchenko 	unsigned char to;
408c8250381SAndy Shevchenko 
409c8250381SAndy Shevchenko 	switch (c) {
410c8250381SAndy Shevchenko 	case '\\':
411c8250381SAndy Shevchenko 		to = '\\';
412c8250381SAndy Shevchenko 		break;
413c8250381SAndy Shevchenko 	case '\a':
414c8250381SAndy Shevchenko 		to = 'a';
415c8250381SAndy Shevchenko 		break;
416c8250381SAndy Shevchenko 	case '\e':
417c8250381SAndy Shevchenko 		to = 'e';
418c8250381SAndy Shevchenko 		break;
41991027d0aSChris Down 	case '"':
42091027d0aSChris Down 		to = '"';
42191027d0aSChris Down 		break;
422c8250381SAndy Shevchenko 	default:
4233aeddc7dSRasmus Villemoes 		return false;
424c8250381SAndy Shevchenko 	}
425c8250381SAndy Shevchenko 
4263aeddc7dSRasmus Villemoes 	if (out < end)
4273aeddc7dSRasmus Villemoes 		*out = '\\';
4283aeddc7dSRasmus Villemoes 	++out;
4293aeddc7dSRasmus Villemoes 	if (out < end)
4303aeddc7dSRasmus Villemoes 		*out = to;
4313aeddc7dSRasmus Villemoes 	++out;
432c8250381SAndy Shevchenko 
433c8250381SAndy Shevchenko 	*dst = out;
4343aeddc7dSRasmus Villemoes 	return true;
435c8250381SAndy Shevchenko }
436c8250381SAndy Shevchenko 
escape_null(unsigned char c,char ** dst,char * end)4373aeddc7dSRasmus Villemoes static bool escape_null(unsigned char c, char **dst, char *end)
438c8250381SAndy Shevchenko {
439c8250381SAndy Shevchenko 	char *out = *dst;
440c8250381SAndy Shevchenko 
441c8250381SAndy Shevchenko 	if (c)
4423aeddc7dSRasmus Villemoes 		return false;
443c8250381SAndy Shevchenko 
4443aeddc7dSRasmus Villemoes 	if (out < end)
4453aeddc7dSRasmus Villemoes 		*out = '\\';
4463aeddc7dSRasmus Villemoes 	++out;
4473aeddc7dSRasmus Villemoes 	if (out < end)
4483aeddc7dSRasmus Villemoes 		*out = '0';
4493aeddc7dSRasmus Villemoes 	++out;
4503aeddc7dSRasmus Villemoes 
4513aeddc7dSRasmus Villemoes 	*dst = out;
4523aeddc7dSRasmus Villemoes 	return true;
4533aeddc7dSRasmus Villemoes }
4543aeddc7dSRasmus Villemoes 
escape_octal(unsigned char c,char ** dst,char * end)4553aeddc7dSRasmus Villemoes static bool escape_octal(unsigned char c, char **dst, char *end)
456c8250381SAndy Shevchenko {
457c8250381SAndy Shevchenko 	char *out = *dst;
458c8250381SAndy Shevchenko 
4593aeddc7dSRasmus Villemoes 	if (out < end)
4603aeddc7dSRasmus Villemoes 		*out = '\\';
4613aeddc7dSRasmus Villemoes 	++out;
4623aeddc7dSRasmus Villemoes 	if (out < end)
4633aeddc7dSRasmus Villemoes 		*out = ((c >> 6) & 0x07) + '0';
4643aeddc7dSRasmus Villemoes 	++out;
4653aeddc7dSRasmus Villemoes 	if (out < end)
4663aeddc7dSRasmus Villemoes 		*out = ((c >> 3) & 0x07) + '0';
4673aeddc7dSRasmus Villemoes 	++out;
4683aeddc7dSRasmus Villemoes 	if (out < end)
4693aeddc7dSRasmus Villemoes 		*out = ((c >> 0) & 0x07) + '0';
4703aeddc7dSRasmus Villemoes 	++out;
4713aeddc7dSRasmus Villemoes 
4723aeddc7dSRasmus Villemoes 	*dst = out;
4733aeddc7dSRasmus Villemoes 	return true;
4743aeddc7dSRasmus Villemoes }
4753aeddc7dSRasmus Villemoes 
escape_hex(unsigned char c,char ** dst,char * end)4763aeddc7dSRasmus Villemoes static bool escape_hex(unsigned char c, char **dst, char *end)
477c8250381SAndy Shevchenko {
478c8250381SAndy Shevchenko 	char *out = *dst;
479c8250381SAndy Shevchenko 
4803aeddc7dSRasmus Villemoes 	if (out < end)
4813aeddc7dSRasmus Villemoes 		*out = '\\';
4823aeddc7dSRasmus Villemoes 	++out;
4833aeddc7dSRasmus Villemoes 	if (out < end)
4843aeddc7dSRasmus Villemoes 		*out = 'x';
4853aeddc7dSRasmus Villemoes 	++out;
4863aeddc7dSRasmus Villemoes 	if (out < end)
4873aeddc7dSRasmus Villemoes 		*out = hex_asc_hi(c);
4883aeddc7dSRasmus Villemoes 	++out;
4893aeddc7dSRasmus Villemoes 	if (out < end)
4903aeddc7dSRasmus Villemoes 		*out = hex_asc_lo(c);
4913aeddc7dSRasmus Villemoes 	++out;
492c8250381SAndy Shevchenko 
493c8250381SAndy Shevchenko 	*dst = out;
4943aeddc7dSRasmus Villemoes 	return true;
495c8250381SAndy Shevchenko }
496c8250381SAndy Shevchenko 
497c8250381SAndy Shevchenko /**
498c8250381SAndy Shevchenko  * string_escape_mem - quote characters in the given memory buffer
499c8250381SAndy Shevchenko  * @src:	source buffer (unescaped)
500c8250381SAndy Shevchenko  * @isz:	source buffer size
501c8250381SAndy Shevchenko  * @dst:	destination buffer (escaped)
502c8250381SAndy Shevchenko  * @osz:	destination buffer size
503b4658cddSJonathan Corbet  * @flags:	combination of the flags
504b4658cddSJonathan Corbet  * @only:	NULL-terminated string containing characters used to limit
505b4658cddSJonathan Corbet  *		the selected escape class. If characters are included in @only
506b4658cddSJonathan Corbet  *		that would not normally be escaped by the classes selected
507b4658cddSJonathan Corbet  *		in @flags, they will be copied to @dst unescaped.
508b4658cddSJonathan Corbet  *
509b4658cddSJonathan Corbet  * Description:
510b4658cddSJonathan Corbet  * The process of escaping byte buffer includes several parts. They are applied
511b4658cddSJonathan Corbet  * in the following sequence.
512b4658cddSJonathan Corbet  *
51362519b88SAndy Shevchenko  *	1. The character is not matched to the one from @only string and thus
514b4658cddSJonathan Corbet  *	   must go as-is to the output.
5150362c27fSAndy Shevchenko  *	2. The character is matched to the printable and ASCII classes, if asked,
516a0809783SAndy Shevchenko  *	   and in case of match it passes through to the output.
5170362c27fSAndy Shevchenko  *	3. The character is matched to the printable or ASCII class, if asked,
5180362c27fSAndy Shevchenko  *	   and in case of match it passes through to the output.
5190362c27fSAndy Shevchenko  *	4. The character is checked if it falls into the class given by @flags.
520b4658cddSJonathan Corbet  *	   %ESCAPE_OCTAL and %ESCAPE_HEX are going last since they cover any
521b4658cddSJonathan Corbet  *	   character. Note that they actually can't go together, otherwise
522b4658cddSJonathan Corbet  *	   %ESCAPE_HEX will be ignored.
523b4658cddSJonathan Corbet  *
524b4658cddSJonathan Corbet  * Caller must provide valid source and destination pointers. Be aware that
525b4658cddSJonathan Corbet  * destination buffer will not be NULL-terminated, thus caller have to append
526b4658cddSJonathan Corbet  * it if needs. The supported flags are::
527b4658cddSJonathan Corbet  *
528d89a3f73SKees Cook  *	%ESCAPE_SPACE: (special white space, not space itself)
529c8250381SAndy Shevchenko  *		'\f' - form feed
530c8250381SAndy Shevchenko  *		'\n' - new line
531c8250381SAndy Shevchenko  *		'\r' - carriage return
532c8250381SAndy Shevchenko  *		'\t' - horizontal tab
533c8250381SAndy Shevchenko  *		'\v' - vertical tab
534c8250381SAndy Shevchenko  *	%ESCAPE_SPECIAL:
53591027d0aSChris Down  *		'\"' - double quote
536c8250381SAndy Shevchenko  *		'\\' - backslash
537c8250381SAndy Shevchenko  *		'\a' - alert (BEL)
538c8250381SAndy Shevchenko  *		'\e' - escape
539c8250381SAndy Shevchenko  *	%ESCAPE_NULL:
540c8250381SAndy Shevchenko  *		'\0' - null
541c8250381SAndy Shevchenko  *	%ESCAPE_OCTAL:
542c8250381SAndy Shevchenko  *		'\NNN' - byte with octal value NNN (3 digits)
543c8250381SAndy Shevchenko  *	%ESCAPE_ANY:
544c8250381SAndy Shevchenko  *		all previous together
545c8250381SAndy Shevchenko  *	%ESCAPE_NP:
546a0809783SAndy Shevchenko  *		escape only non-printable characters, checked by isprint()
547c8250381SAndy Shevchenko  *	%ESCAPE_ANY_NP:
548c8250381SAndy Shevchenko  *		all previous together
549c8250381SAndy Shevchenko  *	%ESCAPE_HEX:
550c8250381SAndy Shevchenko  *		'\xHH' - byte with hexadecimal value HH (2 digits)
551a0809783SAndy Shevchenko  *	%ESCAPE_NA:
552a0809783SAndy Shevchenko  *		escape only non-ascii characters, checked by isascii()
5530362c27fSAndy Shevchenko  *	%ESCAPE_NAP:
5540362c27fSAndy Shevchenko  *		escape only non-printable or non-ascii characters
555aec0d096SAndy Shevchenko  *	%ESCAPE_APPEND:
556aec0d096SAndy Shevchenko  *		append characters from @only to be escaped by the given classes
557aec0d096SAndy Shevchenko  *
558aec0d096SAndy Shevchenko  * %ESCAPE_APPEND would help to pass additional characters to the escaped, when
559aec0d096SAndy Shevchenko  * one of %ESCAPE_NP, %ESCAPE_NA, or %ESCAPE_NAP is provided.
560a0809783SAndy Shevchenko  *
5610362c27fSAndy Shevchenko  * One notable caveat, the %ESCAPE_NAP, %ESCAPE_NP and %ESCAPE_NA have the
5620362c27fSAndy Shevchenko  * higher priority than the rest of the flags (%ESCAPE_NAP is the highest).
563a0809783SAndy Shevchenko  * It doesn't make much sense to use either of them without %ESCAPE_OCTAL
564a0809783SAndy Shevchenko  * or %ESCAPE_HEX, because they cover most of the other character classes.
5650362c27fSAndy Shevchenko  * %ESCAPE_NAP can utilize %ESCAPE_SPACE or %ESCAPE_SPECIAL in addition to
5660362c27fSAndy Shevchenko  * the above.
567c8250381SAndy Shevchenko  *
568c8250381SAndy Shevchenko  * Return:
56941416f23SRasmus Villemoes  * The total size of the escaped output that would be generated for
57041416f23SRasmus Villemoes  * the given input and flags. To check whether the output was
57141416f23SRasmus Villemoes  * truncated, compare the return value to osz. There is room left in
57241416f23SRasmus Villemoes  * dst for a '\0' terminator if and only if ret < osz.
573c8250381SAndy Shevchenko  */
string_escape_mem(const char * src,size_t isz,char * dst,size_t osz,unsigned int flags,const char * only)57441416f23SRasmus Villemoes int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
575b40bdb7fSKees Cook 		      unsigned int flags, const char *only)
576c8250381SAndy Shevchenko {
57741416f23SRasmus Villemoes 	char *p = dst;
5783aeddc7dSRasmus Villemoes 	char *end = p + osz;
579b40bdb7fSKees Cook 	bool is_dict = only && *only;
580aec0d096SAndy Shevchenko 	bool is_append = flags & ESCAPE_APPEND;
581c8250381SAndy Shevchenko 
582c8250381SAndy Shevchenko 	while (isz--) {
583c8250381SAndy Shevchenko 		unsigned char c = *src++;
584aec0d096SAndy Shevchenko 		bool in_dict = is_dict && strchr(only, c);
585c8250381SAndy Shevchenko 
586c8250381SAndy Shevchenko 		/*
587c8250381SAndy Shevchenko 		 * Apply rules in the following sequence:
588b40bdb7fSKees Cook 		 *	- the @only string is supplied and does not contain a
589c8250381SAndy Shevchenko 		 *	  character under question
5900362c27fSAndy Shevchenko 		 *	- the character is printable and ASCII, when @flags has
5910362c27fSAndy Shevchenko 		 *	  %ESCAPE_NAP bit set
59262519b88SAndy Shevchenko 		 *	- the character is printable, when @flags has
59362519b88SAndy Shevchenko 		 *	  %ESCAPE_NP bit set
594a0809783SAndy Shevchenko 		 *	- the character is ASCII, when @flags has
595a0809783SAndy Shevchenko 		 *	  %ESCAPE_NA bit set
596c8250381SAndy Shevchenko 		 *	- the character doesn't fall into a class of symbols
597c8250381SAndy Shevchenko 		 *	  defined by given @flags
598c8250381SAndy Shevchenko 		 * In these cases we just pass through a character to the
599c8250381SAndy Shevchenko 		 * output buffer.
600aec0d096SAndy Shevchenko 		 *
601aec0d096SAndy Shevchenko 		 * When %ESCAPE_APPEND is passed, the characters from @only
602aec0d096SAndy Shevchenko 		 * have been excluded from the %ESCAPE_NAP, %ESCAPE_NP, and
603aec0d096SAndy Shevchenko 		 * %ESCAPE_NA cases.
604c8250381SAndy Shevchenko 		 */
605aec0d096SAndy Shevchenko 		if (!(is_append || in_dict) && is_dict &&
6067e5969aeSAndy Shevchenko 					  escape_passthrough(c, &p, end))
6077e5969aeSAndy Shevchenko 			continue;
6087e5969aeSAndy Shevchenko 
609aec0d096SAndy Shevchenko 		if (!(is_append && in_dict) && isascii(c) && isprint(c) &&
6100362c27fSAndy Shevchenko 		    flags & ESCAPE_NAP && escape_passthrough(c, &p, end))
6110362c27fSAndy Shevchenko 			continue;
6120362c27fSAndy Shevchenko 
613aec0d096SAndy Shevchenko 		if (!(is_append && in_dict) && isprint(c) &&
61462519b88SAndy Shevchenko 		    flags & ESCAPE_NP && escape_passthrough(c, &p, end))
61562519b88SAndy Shevchenko 			continue;
61662519b88SAndy Shevchenko 
617aec0d096SAndy Shevchenko 		if (!(is_append && in_dict) && isascii(c) &&
618a0809783SAndy Shevchenko 		    flags & ESCAPE_NA && escape_passthrough(c, &p, end))
619a0809783SAndy Shevchenko 			continue;
620a0809783SAndy Shevchenko 
6213aeddc7dSRasmus Villemoes 		if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
622c8250381SAndy Shevchenko 			continue;
623c8250381SAndy Shevchenko 
6243aeddc7dSRasmus Villemoes 		if (flags & ESCAPE_SPECIAL && escape_special(c, &p, end))
625c8250381SAndy Shevchenko 			continue;
626c8250381SAndy Shevchenko 
6273aeddc7dSRasmus Villemoes 		if (flags & ESCAPE_NULL && escape_null(c, &p, end))
628c8250381SAndy Shevchenko 			continue;
629c8250381SAndy Shevchenko 
630c8250381SAndy Shevchenko 		/* ESCAPE_OCTAL and ESCAPE_HEX always go last */
6313aeddc7dSRasmus Villemoes 		if (flags & ESCAPE_OCTAL && escape_octal(c, &p, end))
6323aeddc7dSRasmus Villemoes 			continue;
6333aeddc7dSRasmus Villemoes 
6343aeddc7dSRasmus Villemoes 		if (flags & ESCAPE_HEX && escape_hex(c, &p, end))
635c8250381SAndy Shevchenko 			continue;
6363aeddc7dSRasmus Villemoes 
6373aeddc7dSRasmus Villemoes 		escape_passthrough(c, &p, end);
638c8250381SAndy Shevchenko 	}
639c8250381SAndy Shevchenko 
64041416f23SRasmus Villemoes 	return p - dst;
641c8250381SAndy Shevchenko }
642c8250381SAndy Shevchenko EXPORT_SYMBOL(string_escape_mem);
643b53f27e4SKees Cook 
644b53f27e4SKees Cook /*
645b53f27e4SKees Cook  * Return an allocated string that has been escaped of special characters
646b53f27e4SKees Cook  * and double quotes, making it safe to log in quotes.
647b53f27e4SKees Cook  */
kstrdup_quotable(const char * src,gfp_t gfp)648b53f27e4SKees Cook char *kstrdup_quotable(const char *src, gfp_t gfp)
649b53f27e4SKees Cook {
650b53f27e4SKees Cook 	size_t slen, dlen;
651b53f27e4SKees Cook 	char *dst;
652b53f27e4SKees Cook 	const int flags = ESCAPE_HEX;
653b53f27e4SKees Cook 	const char esc[] = "\f\n\r\t\v\a\e\\\"";
654b53f27e4SKees Cook 
655b53f27e4SKees Cook 	if (!src)
656b53f27e4SKees Cook 		return NULL;
657b53f27e4SKees Cook 	slen = strlen(src);
658b53f27e4SKees Cook 
659b53f27e4SKees Cook 	dlen = string_escape_mem(src, slen, NULL, 0, flags, esc);
660b53f27e4SKees Cook 	dst = kmalloc(dlen + 1, gfp);
661b53f27e4SKees Cook 	if (!dst)
662b53f27e4SKees Cook 		return NULL;
663b53f27e4SKees Cook 
664b53f27e4SKees Cook 	WARN_ON(string_escape_mem(src, slen, dst, dlen, flags, esc) != dlen);
665b53f27e4SKees Cook 	dst[dlen] = '\0';
666b53f27e4SKees Cook 
667b53f27e4SKees Cook 	return dst;
668b53f27e4SKees Cook }
669b53f27e4SKees Cook EXPORT_SYMBOL_GPL(kstrdup_quotable);
6700d044328SKees Cook 
6710d044328SKees Cook /*
6720d044328SKees Cook  * Returns allocated NULL-terminated string containing process
6730d044328SKees Cook  * command line, with inter-argument NULLs replaced with spaces,
6740d044328SKees Cook  * and other special characters escaped.
6750d044328SKees Cook  */
kstrdup_quotable_cmdline(struct task_struct * task,gfp_t gfp)6760d044328SKees Cook char *kstrdup_quotable_cmdline(struct task_struct *task, gfp_t gfp)
6770d044328SKees Cook {
6780d044328SKees Cook 	char *buffer, *quoted;
6790d044328SKees Cook 	int i, res;
6800d044328SKees Cook 
6810ee931c4SMichal Hocko 	buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
6820d044328SKees Cook 	if (!buffer)
6830d044328SKees Cook 		return NULL;
6840d044328SKees Cook 
6850d044328SKees Cook 	res = get_cmdline(task, buffer, PAGE_SIZE - 1);
6860d044328SKees Cook 	buffer[res] = '\0';
6870d044328SKees Cook 
6880d044328SKees Cook 	/* Collapse trailing NULLs, leave res pointing to last non-NULL. */
6890d044328SKees Cook 	while (--res >= 0 && buffer[res] == '\0')
6900d044328SKees Cook 		;
6910d044328SKees Cook 
6920d044328SKees Cook 	/* Replace inter-argument NULLs. */
6930d044328SKees Cook 	for (i = 0; i <= res; i++)
6940d044328SKees Cook 		if (buffer[i] == '\0')
6950d044328SKees Cook 			buffer[i] = ' ';
6960d044328SKees Cook 
6970d044328SKees Cook 	/* Make sure result is printable. */
6980d044328SKees Cook 	quoted = kstrdup_quotable(buffer, gfp);
6990d044328SKees Cook 	kfree(buffer);
7000d044328SKees Cook 	return quoted;
7010d044328SKees Cook }
7020d044328SKees Cook EXPORT_SYMBOL_GPL(kstrdup_quotable_cmdline);
70321985319SKees Cook 
70421985319SKees Cook /*
70521985319SKees Cook  * Returns allocated NULL-terminated string containing pathname,
70621985319SKees Cook  * with special characters escaped, able to be safely logged. If
70721985319SKees Cook  * there is an error, the leading character will be "<".
70821985319SKees Cook  */
kstrdup_quotable_file(struct file * file,gfp_t gfp)70921985319SKees Cook char *kstrdup_quotable_file(struct file *file, gfp_t gfp)
71021985319SKees Cook {
71121985319SKees Cook 	char *temp, *pathname;
71221985319SKees Cook 
71321985319SKees Cook 	if (!file)
71421985319SKees Cook 		return kstrdup("<unknown>", gfp);
71521985319SKees Cook 
71621985319SKees Cook 	/* We add 11 spaces for ' (deleted)' to be appended */
7170ee931c4SMichal Hocko 	temp = kmalloc(PATH_MAX + 11, GFP_KERNEL);
71821985319SKees Cook 	if (!temp)
71921985319SKees Cook 		return kstrdup("<no_memory>", gfp);
72021985319SKees Cook 
72121985319SKees Cook 	pathname = file_path(file, temp, PATH_MAX + 11);
72221985319SKees Cook 	if (IS_ERR(pathname))
72321985319SKees Cook 		pathname = kstrdup("<too_long>", gfp);
72421985319SKees Cook 	else
72521985319SKees Cook 		pathname = kstrdup_quotable(pathname, gfp);
72621985319SKees Cook 
72721985319SKees Cook 	kfree(temp);
72821985319SKees Cook 	return pathname;
72921985319SKees Cook }
73021985319SKees Cook EXPORT_SYMBOL_GPL(kstrdup_quotable_file);
7310fd16012SBartosz Golaszewski 
732045ad464SAndy Shevchenko /*
733045ad464SAndy Shevchenko  * Returns duplicate string in which the @old characters are replaced by @new.
734045ad464SAndy Shevchenko  */
kstrdup_and_replace(const char * src,char old,char new,gfp_t gfp)735045ad464SAndy Shevchenko char *kstrdup_and_replace(const char *src, char old, char new, gfp_t gfp)
736045ad464SAndy Shevchenko {
737045ad464SAndy Shevchenko 	char *dst;
738045ad464SAndy Shevchenko 
739045ad464SAndy Shevchenko 	dst = kstrdup(src, gfp);
740045ad464SAndy Shevchenko 	if (!dst)
741045ad464SAndy Shevchenko 		return NULL;
742045ad464SAndy Shevchenko 
743045ad464SAndy Shevchenko 	return strreplace(dst, old, new);
744045ad464SAndy Shevchenko }
745045ad464SAndy Shevchenko EXPORT_SYMBOL_GPL(kstrdup_and_replace);
746045ad464SAndy Shevchenko 
7470fd16012SBartosz Golaszewski /**
748418e0a35SAndy Shevchenko  * kasprintf_strarray - allocate and fill array of sequential strings
749418e0a35SAndy Shevchenko  * @gfp: flags for the slab allocator
750418e0a35SAndy Shevchenko  * @prefix: prefix to be used
751418e0a35SAndy Shevchenko  * @n: amount of lines to be allocated and filled
752418e0a35SAndy Shevchenko  *
753418e0a35SAndy Shevchenko  * Allocates and fills @n strings using pattern "%s-%zu", where prefix
754418e0a35SAndy Shevchenko  * is provided by caller. The caller is responsible to free them with
755418e0a35SAndy Shevchenko  * kfree_strarray() after use.
756418e0a35SAndy Shevchenko  *
757418e0a35SAndy Shevchenko  * Returns array of strings or NULL when memory can't be allocated.
758418e0a35SAndy Shevchenko  */
kasprintf_strarray(gfp_t gfp,const char * prefix,size_t n)759418e0a35SAndy Shevchenko char **kasprintf_strarray(gfp_t gfp, const char *prefix, size_t n)
760418e0a35SAndy Shevchenko {
761418e0a35SAndy Shevchenko 	char **names;
762418e0a35SAndy Shevchenko 	size_t i;
763418e0a35SAndy Shevchenko 
764418e0a35SAndy Shevchenko 	names = kcalloc(n + 1, sizeof(char *), gfp);
765418e0a35SAndy Shevchenko 	if (!names)
766418e0a35SAndy Shevchenko 		return NULL;
767418e0a35SAndy Shevchenko 
768418e0a35SAndy Shevchenko 	for (i = 0; i < n; i++) {
769418e0a35SAndy Shevchenko 		names[i] = kasprintf(gfp, "%s-%zu", prefix, i);
770418e0a35SAndy Shevchenko 		if (!names[i]) {
771418e0a35SAndy Shevchenko 			kfree_strarray(names, i);
772418e0a35SAndy Shevchenko 			return NULL;
773418e0a35SAndy Shevchenko 		}
774418e0a35SAndy Shevchenko 	}
775418e0a35SAndy Shevchenko 
776418e0a35SAndy Shevchenko 	return names;
777418e0a35SAndy Shevchenko }
778418e0a35SAndy Shevchenko EXPORT_SYMBOL_GPL(kasprintf_strarray);
779418e0a35SAndy Shevchenko 
780418e0a35SAndy Shevchenko /**
7810fd16012SBartosz Golaszewski  * kfree_strarray - free a number of dynamically allocated strings contained
7820fd16012SBartosz Golaszewski  *                  in an array and the array itself
7830fd16012SBartosz Golaszewski  *
7840fd16012SBartosz Golaszewski  * @array: Dynamically allocated array of strings to free.
7850fd16012SBartosz Golaszewski  * @n: Number of strings (starting from the beginning of the array) to free.
7860fd16012SBartosz Golaszewski  *
7870fd16012SBartosz Golaszewski  * Passing a non-NULL @array and @n == 0 as well as NULL @array are valid
7880fd16012SBartosz Golaszewski  * use-cases. If @array is NULL, the function does nothing.
7890fd16012SBartosz Golaszewski  */
kfree_strarray(char ** array,size_t n)7900fd16012SBartosz Golaszewski void kfree_strarray(char **array, size_t n)
7910fd16012SBartosz Golaszewski {
7920fd16012SBartosz Golaszewski 	unsigned int i;
7930fd16012SBartosz Golaszewski 
7940fd16012SBartosz Golaszewski 	if (!array)
7950fd16012SBartosz Golaszewski 		return;
7960fd16012SBartosz Golaszewski 
7970fd16012SBartosz Golaszewski 	for (i = 0; i < n; i++)
7980fd16012SBartosz Golaszewski 		kfree(array[i]);
7990fd16012SBartosz Golaszewski 	kfree(array);
8000fd16012SBartosz Golaszewski }
8010fd16012SBartosz Golaszewski EXPORT_SYMBOL_GPL(kfree_strarray);
802cfecea6eSKees Cook 
803acdb89b6SAndy Shevchenko struct strarray {
804acdb89b6SAndy Shevchenko 	char **array;
805acdb89b6SAndy Shevchenko 	size_t n;
806acdb89b6SAndy Shevchenko };
807acdb89b6SAndy Shevchenko 
devm_kfree_strarray(struct device * dev,void * res)808acdb89b6SAndy Shevchenko static void devm_kfree_strarray(struct device *dev, void *res)
809acdb89b6SAndy Shevchenko {
810acdb89b6SAndy Shevchenko 	struct strarray *array = res;
811acdb89b6SAndy Shevchenko 
812acdb89b6SAndy Shevchenko 	kfree_strarray(array->array, array->n);
813acdb89b6SAndy Shevchenko }
814acdb89b6SAndy Shevchenko 
devm_kasprintf_strarray(struct device * dev,const char * prefix,size_t n)815acdb89b6SAndy Shevchenko char **devm_kasprintf_strarray(struct device *dev, const char *prefix, size_t n)
816acdb89b6SAndy Shevchenko {
817acdb89b6SAndy Shevchenko 	struct strarray *ptr;
818acdb89b6SAndy Shevchenko 
819acdb89b6SAndy Shevchenko 	ptr = devres_alloc(devm_kfree_strarray, sizeof(*ptr), GFP_KERNEL);
820acdb89b6SAndy Shevchenko 	if (!ptr)
821acdb89b6SAndy Shevchenko 		return ERR_PTR(-ENOMEM);
822acdb89b6SAndy Shevchenko 
823acdb89b6SAndy Shevchenko 	ptr->array = kasprintf_strarray(GFP_KERNEL, prefix, n);
824acdb89b6SAndy Shevchenko 	if (!ptr->array) {
825acdb89b6SAndy Shevchenko 		devres_free(ptr);
826acdb89b6SAndy Shevchenko 		return ERR_PTR(-ENOMEM);
827acdb89b6SAndy Shevchenko 	}
828acdb89b6SAndy Shevchenko 
829cd290a98SPuyou Lu 	ptr->n = n;
830cd290a98SPuyou Lu 	devres_add(dev, ptr);
831cd290a98SPuyou Lu 
832acdb89b6SAndy Shevchenko 	return ptr->array;
833acdb89b6SAndy Shevchenko }
834acdb89b6SAndy Shevchenko EXPORT_SYMBOL_GPL(devm_kasprintf_strarray);
835acdb89b6SAndy Shevchenko 
836cfecea6eSKees Cook /**
837cfecea6eSKees Cook  * skip_spaces - Removes leading whitespace from @str.
838cfecea6eSKees Cook  * @str: The string to be stripped.
839cfecea6eSKees Cook  *
840cfecea6eSKees Cook  * Returns a pointer to the first non-whitespace character in @str.
841cfecea6eSKees Cook  */
skip_spaces(const char * str)842cfecea6eSKees Cook char *skip_spaces(const char *str)
843cfecea6eSKees Cook {
844cfecea6eSKees Cook 	while (isspace(*str))
845cfecea6eSKees Cook 		++str;
846cfecea6eSKees Cook 	return (char *)str;
847cfecea6eSKees Cook }
848cfecea6eSKees Cook EXPORT_SYMBOL(skip_spaces);
849cfecea6eSKees Cook 
850cfecea6eSKees Cook /**
851cfecea6eSKees Cook  * strim - Removes leading and trailing whitespace from @s.
852cfecea6eSKees Cook  * @s: The string to be stripped.
853cfecea6eSKees Cook  *
854cfecea6eSKees Cook  * Note that the first trailing whitespace is replaced with a %NUL-terminator
855cfecea6eSKees Cook  * in the given string @s. Returns a pointer to the first non-whitespace
856cfecea6eSKees Cook  * character in @s.
857cfecea6eSKees Cook  */
strim(char * s)858cfecea6eSKees Cook char *strim(char *s)
859cfecea6eSKees Cook {
860cfecea6eSKees Cook 	size_t size;
861cfecea6eSKees Cook 	char *end;
862cfecea6eSKees Cook 
863cfecea6eSKees Cook 	size = strlen(s);
864cfecea6eSKees Cook 	if (!size)
865cfecea6eSKees Cook 		return s;
866cfecea6eSKees Cook 
867cfecea6eSKees Cook 	end = s + size - 1;
868cfecea6eSKees Cook 	while (end >= s && isspace(*end))
869cfecea6eSKees Cook 		end--;
870cfecea6eSKees Cook 	*(end + 1) = '\0';
871cfecea6eSKees Cook 
872cfecea6eSKees Cook 	return skip_spaces(s);
873cfecea6eSKees Cook }
874cfecea6eSKees Cook EXPORT_SYMBOL(strim);
875cfecea6eSKees Cook 
876cfecea6eSKees Cook /**
877cfecea6eSKees Cook  * sysfs_streq - return true if strings are equal, modulo trailing newline
878cfecea6eSKees Cook  * @s1: one string
879cfecea6eSKees Cook  * @s2: another string
880cfecea6eSKees Cook  *
881cfecea6eSKees Cook  * This routine returns true iff two strings are equal, treating both
882cfecea6eSKees Cook  * NUL and newline-then-NUL as equivalent string terminations.  It's
883cfecea6eSKees Cook  * geared for use with sysfs input strings, which generally terminate
884cfecea6eSKees Cook  * with newlines but are compared against values without newlines.
885cfecea6eSKees Cook  */
sysfs_streq(const char * s1,const char * s2)886cfecea6eSKees Cook bool sysfs_streq(const char *s1, const char *s2)
887cfecea6eSKees Cook {
888cfecea6eSKees Cook 	while (*s1 && *s1 == *s2) {
889cfecea6eSKees Cook 		s1++;
890cfecea6eSKees Cook 		s2++;
891cfecea6eSKees Cook 	}
892cfecea6eSKees Cook 
893cfecea6eSKees Cook 	if (*s1 == *s2)
894cfecea6eSKees Cook 		return true;
895cfecea6eSKees Cook 	if (!*s1 && *s2 == '\n' && !s2[1])
896cfecea6eSKees Cook 		return true;
897cfecea6eSKees Cook 	if (*s1 == '\n' && !s1[1] && !*s2)
898cfecea6eSKees Cook 		return true;
899cfecea6eSKees Cook 	return false;
900cfecea6eSKees Cook }
901cfecea6eSKees Cook EXPORT_SYMBOL(sysfs_streq);
902cfecea6eSKees Cook 
903cfecea6eSKees Cook /**
904cfecea6eSKees Cook  * match_string - matches given string in an array
905cfecea6eSKees Cook  * @array:	array of strings
906cfecea6eSKees Cook  * @n:		number of strings in the array or -1 for NULL terminated arrays
907cfecea6eSKees Cook  * @string:	string to match with
908cfecea6eSKees Cook  *
909cfecea6eSKees Cook  * This routine will look for a string in an array of strings up to the
910cfecea6eSKees Cook  * n-th element in the array or until the first NULL element.
911cfecea6eSKees Cook  *
912cfecea6eSKees Cook  * Historically the value of -1 for @n, was used to search in arrays that
913cfecea6eSKees Cook  * are NULL terminated. However, the function does not make a distinction
914cfecea6eSKees Cook  * when finishing the search: either @n elements have been compared OR
915cfecea6eSKees Cook  * the first NULL element was found.
916cfecea6eSKees Cook  *
917cfecea6eSKees Cook  * Return:
918cfecea6eSKees Cook  * index of a @string in the @array if matches, or %-EINVAL otherwise.
919cfecea6eSKees Cook  */
match_string(const char * const * array,size_t n,const char * string)920cfecea6eSKees Cook int match_string(const char * const *array, size_t n, const char *string)
921cfecea6eSKees Cook {
922cfecea6eSKees Cook 	int index;
923cfecea6eSKees Cook 	const char *item;
924cfecea6eSKees Cook 
925cfecea6eSKees Cook 	for (index = 0; index < n; index++) {
926cfecea6eSKees Cook 		item = array[index];
927cfecea6eSKees Cook 		if (!item)
928cfecea6eSKees Cook 			break;
929cfecea6eSKees Cook 		if (!strcmp(item, string))
930cfecea6eSKees Cook 			return index;
931cfecea6eSKees Cook 	}
932cfecea6eSKees Cook 
933cfecea6eSKees Cook 	return -EINVAL;
934cfecea6eSKees Cook }
935cfecea6eSKees Cook EXPORT_SYMBOL(match_string);
936cfecea6eSKees Cook 
937cfecea6eSKees Cook /**
938cfecea6eSKees Cook  * __sysfs_match_string - matches given string in an array
939cfecea6eSKees Cook  * @array: array of strings
940cfecea6eSKees Cook  * @n: number of strings in the array or -1 for NULL terminated arrays
941cfecea6eSKees Cook  * @str: string to match with
942cfecea6eSKees Cook  *
943cfecea6eSKees Cook  * Returns index of @str in the @array or -EINVAL, just like match_string().
944cfecea6eSKees Cook  * Uses sysfs_streq instead of strcmp for matching.
945cfecea6eSKees Cook  *
946cfecea6eSKees Cook  * This routine will look for a string in an array of strings up to the
947cfecea6eSKees Cook  * n-th element in the array or until the first NULL element.
948cfecea6eSKees Cook  *
949cfecea6eSKees Cook  * Historically the value of -1 for @n, was used to search in arrays that
950cfecea6eSKees Cook  * are NULL terminated. However, the function does not make a distinction
951cfecea6eSKees Cook  * when finishing the search: either @n elements have been compared OR
952cfecea6eSKees Cook  * the first NULL element was found.
953cfecea6eSKees Cook  */
__sysfs_match_string(const char * const * array,size_t n,const char * str)954cfecea6eSKees Cook int __sysfs_match_string(const char * const *array, size_t n, const char *str)
955cfecea6eSKees Cook {
956cfecea6eSKees Cook 	const char *item;
957cfecea6eSKees Cook 	int index;
958cfecea6eSKees Cook 
959cfecea6eSKees Cook 	for (index = 0; index < n; index++) {
960cfecea6eSKees Cook 		item = array[index];
961cfecea6eSKees Cook 		if (!item)
962cfecea6eSKees Cook 			break;
963cfecea6eSKees Cook 		if (sysfs_streq(item, str))
964cfecea6eSKees Cook 			return index;
965cfecea6eSKees Cook 	}
966cfecea6eSKees Cook 
967cfecea6eSKees Cook 	return -EINVAL;
968cfecea6eSKees Cook }
969cfecea6eSKees Cook EXPORT_SYMBOL(__sysfs_match_string);
970cfecea6eSKees Cook 
971cfecea6eSKees Cook /**
972cfecea6eSKees Cook  * strreplace - Replace all occurrences of character in string.
973d01a77afSAndy Shevchenko  * @str: The string to operate on.
974cfecea6eSKees Cook  * @old: The character being replaced.
975cfecea6eSKees Cook  * @new: The character @old is replaced with.
976cfecea6eSKees Cook  *
977d01a77afSAndy Shevchenko  * Replaces the each @old character with a @new one in the given string @str.
978d01a77afSAndy Shevchenko  *
979d01a77afSAndy Shevchenko  * Return: pointer to the string @str itself.
980cfecea6eSKees Cook  */
strreplace(char * str,char old,char new)981d01a77afSAndy Shevchenko char *strreplace(char *str, char old, char new)
982cfecea6eSKees Cook {
983d01a77afSAndy Shevchenko 	char *s = str;
984d01a77afSAndy Shevchenko 
985cfecea6eSKees Cook 	for (; *s; ++s)
986cfecea6eSKees Cook 		if (*s == old)
987cfecea6eSKees Cook 			*s = new;
988d01a77afSAndy Shevchenko 	return str;
989cfecea6eSKees Cook }
990cfecea6eSKees Cook EXPORT_SYMBOL(strreplace);
991cfecea6eSKees Cook 
9925c4e0a21SGuenter Roeck /**
9935c4e0a21SGuenter Roeck  * memcpy_and_pad - Copy one buffer to another with padding
9945c4e0a21SGuenter Roeck  * @dest: Where to copy to
9955c4e0a21SGuenter Roeck  * @dest_len: The destination buffer size
9965c4e0a21SGuenter Roeck  * @src: Where to copy from
9975c4e0a21SGuenter Roeck  * @count: The number of bytes to copy
9985c4e0a21SGuenter Roeck  * @pad: Character to use for padding if space is left in destination.
9995c4e0a21SGuenter Roeck  */
memcpy_and_pad(void * dest,size_t dest_len,const void * src,size_t count,int pad)10005c4e0a21SGuenter Roeck void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count,
10015c4e0a21SGuenter Roeck 		    int pad)
10025c4e0a21SGuenter Roeck {
10035c4e0a21SGuenter Roeck 	if (dest_len > count) {
10045c4e0a21SGuenter Roeck 		memcpy(dest, src, count);
10055c4e0a21SGuenter Roeck 		memset(dest + count, pad,  dest_len - count);
10065c4e0a21SGuenter Roeck 	} else {
10075c4e0a21SGuenter Roeck 		memcpy(dest, src, dest_len);
10085c4e0a21SGuenter Roeck 	}
10095c4e0a21SGuenter Roeck }
10105c4e0a21SGuenter Roeck EXPORT_SYMBOL(memcpy_and_pad);
10115c4e0a21SGuenter Roeck 
1012c430f600SKees Cook #ifdef CONFIG_FORTIFY_SOURCE
1013f68f2ff9SKees Cook /* These are placeholders for fortify compile-time warnings. */
__read_overflow2_field(size_t avail,size_t wanted)1014f68f2ff9SKees Cook void __read_overflow2_field(size_t avail, size_t wanted) { }
1015f68f2ff9SKees Cook EXPORT_SYMBOL(__read_overflow2_field);
__write_overflow_field(size_t avail,size_t wanted)1016f68f2ff9SKees Cook void __write_overflow_field(size_t avail, size_t wanted) { }
1017f68f2ff9SKees Cook EXPORT_SYMBOL(__write_overflow_field);
1018f68f2ff9SKees Cook 
1019475ddf1fSKees Cook static const char * const fortify_func_name[] = {
1020475ddf1fSKees Cook #define MAKE_FORTIFY_FUNC_NAME(func)	[MAKE_FORTIFY_FUNC(func)] = #func
1021475ddf1fSKees Cook 	EACH_FORTIFY_FUNC(MAKE_FORTIFY_FUNC_NAME)
1022475ddf1fSKees Cook #undef  MAKE_FORTIFY_FUNC_NAME
1023475ddf1fSKees Cook };
1024475ddf1fSKees Cook 
__fortify_report(const u8 reason,const size_t avail,const size_t size)10253d965b33SKees Cook void __fortify_report(const u8 reason, const size_t avail, const size_t size)
1026cfecea6eSKees Cook {
1027475ddf1fSKees Cook 	const u8 func = FORTIFY_REASON_FUNC(reason);
1028475ddf1fSKees Cook 	const bool write = FORTIFY_REASON_DIR(reason);
1029475ddf1fSKees Cook 	const char *name;
1030475ddf1fSKees Cook 
1031475ddf1fSKees Cook 	name = fortify_func_name[umin(func, FORTIFY_FUNC_UNKNOWN)];
10323d965b33SKees Cook 	WARN(1, "%s: detected buffer overflow: %zu byte %s of buffer size %zu\n",
10333d965b33SKees Cook 		 name, size, str_read_write(!write), avail);
1034475ddf1fSKees Cook }
1035475ddf1fSKees Cook EXPORT_SYMBOL(__fortify_report);
1036475ddf1fSKees Cook 
__fortify_panic(const u8 reason,const size_t avail,const size_t size)10373d965b33SKees Cook void __fortify_panic(const u8 reason, const size_t avail, const size_t size)
1038475ddf1fSKees Cook {
10393d965b33SKees Cook 	__fortify_report(reason, avail, size);
1040cfecea6eSKees Cook 	BUG();
1041cfecea6eSKees Cook }
1042475ddf1fSKees Cook EXPORT_SYMBOL(__fortify_panic);
1043c430f600SKees Cook #endif /* CONFIG_FORTIFY_SOURCE */
1044