xref: /openbmc/linux/lib/string_helpers.c (revision ecc23d0a422a3118fcf6e4f0a46e17a6c2047b02)
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>
213c9f3681SJames Bottomley 
223c9f3681SJames Bottomley /**
233c9f3681SJames Bottomley  * string_get_size - get the size in the specified units
24b9f28d86SJames Bottomley  * @size:	The size to be converted in blocks
25b9f28d86SJames Bottomley  * @blk_size:	Size of the block (use 1 for size in bytes)
263c9f3681SJames Bottomley  * @units:	units to use (powers of 1000 or 1024)
273c9f3681SJames Bottomley  * @buf:	buffer to format to
283c9f3681SJames Bottomley  * @len:	length of buffer
293c9f3681SJames Bottomley  *
303c9f3681SJames Bottomley  * This function returns a string formatted to 3 significant figures
31d1214c65SRasmus Villemoes  * giving the size in the required units.  @buf should have room for
32d1214c65SRasmus Villemoes  * at least 9 bytes and will always be zero terminated.
333c9f3681SJames Bottomley  *
343c9f3681SJames Bottomley  */
string_get_size(u64 size,u64 blk_size,const enum string_size_units units,char * buf,int len)35b9f28d86SJames Bottomley void string_get_size(u64 size, u64 blk_size, const enum string_size_units units,
363c9f3681SJames Bottomley 		     char *buf, int len)
373c9f3681SJames Bottomley {
38142cda5dSMathias Krause 	static const char *const units_10[] = {
39b9f28d86SJames Bottomley 		"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
40142cda5dSMathias Krause 	};
41142cda5dSMathias Krause 	static const char *const units_2[] = {
42b9f28d86SJames Bottomley 		"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"
43142cda5dSMathias Krause 	};
44142cda5dSMathias Krause 	static const char *const *const units_str[] = {
453c9f3681SJames Bottomley 		[STRING_UNITS_10] = units_10,
463c9f3681SJames Bottomley 		[STRING_UNITS_2] = units_2,
473c9f3681SJames Bottomley 	};
4868aecfb9SAndrew Morton 	static const unsigned int divisor[] = {
493c9f3681SJames Bottomley 		[STRING_UNITS_10] = 1000,
503c9f3681SJames Bottomley 		[STRING_UNITS_2] = 1024,
513c9f3681SJames Bottomley 	};
52564b026fSJames Bottomley 	static const unsigned int rounding[] = { 500, 50, 5 };
53564b026fSJames Bottomley 	int i = 0, j;
54564b026fSJames Bottomley 	u32 remainder = 0, sf_cap;
55*f7f33bb2SBartosz Golaszewski 	char tmp[12];
56b9f28d86SJames Bottomley 	const char *unit;
573c9f3681SJames Bottomley 
583c9f3681SJames Bottomley 	tmp[0] = '\0';
59564b026fSJames Bottomley 
60564b026fSJames Bottomley 	if (blk_size == 0)
61564b026fSJames Bottomley 		size = 0;
62564b026fSJames Bottomley 	if (size == 0)
63b9f28d86SJames Bottomley 		goto out;
64b9f28d86SJames Bottomley 
65564b026fSJames Bottomley 	/* This is Napier's algorithm.  Reduce the original block size to
66564b026fSJames Bottomley 	 *
67564b026fSJames Bottomley 	 * coefficient * divisor[units]^i
68564b026fSJames Bottomley 	 *
69564b026fSJames Bottomley 	 * we do the reduction so both coefficients are just under 32 bits so
70564b026fSJames Bottomley 	 * that multiplying them together won't overflow 64 bits and we keep
71564b026fSJames Bottomley 	 * as much precision as possible in the numbers.
72564b026fSJames Bottomley 	 *
73564b026fSJames Bottomley 	 * Note: it's safe to throw away the remainders here because all the
74564b026fSJames Bottomley 	 * precision is in the coefficients.
7562bef58aSVitaly Kuznetsov 	 */
76564b026fSJames Bottomley 	while (blk_size >> 32) {
77564b026fSJames Bottomley 		do_div(blk_size, divisor[units]);
78b9f28d86SJames Bottomley 		i++;
79b9f28d86SJames Bottomley 	}
80b9f28d86SJames Bottomley 
81564b026fSJames Bottomley 	while (size >> 32) {
82564b026fSJames Bottomley 		do_div(size, divisor[units]);
83564b026fSJames Bottomley 		i++;
84564b026fSJames Bottomley 	}
85b9f28d86SJames Bottomley 
86564b026fSJames Bottomley 	/* now perform the actual multiplication keeping i as the sum of the
87564b026fSJames Bottomley 	 * two logarithms */
88564b026fSJames Bottomley 	size *= blk_size;
89564b026fSJames Bottomley 
90564b026fSJames Bottomley 	/* and logarithmically reduce it until it's just under the divisor */
917eed8fdeSRasmus Villemoes 	while (size >= divisor[units]) {
923c9f3681SJames Bottomley 		remainder = do_div(size, divisor[units]);
93a8659597SH. Peter Anvin 		i++;
94a8659597SH. Peter Anvin 	}
953c9f3681SJames Bottomley 
96564b026fSJames Bottomley 	/* work out in j how many digits of precision we need from the
97564b026fSJames Bottomley 	 * remainder */
983c9f3681SJames Bottomley 	sf_cap = size;
993c9f3681SJames Bottomley 	for (j = 0; sf_cap*10 < 1000; j++)
1003c9f3681SJames Bottomley 		sf_cap *= 10;
1013c9f3681SJames Bottomley 
102564b026fSJames Bottomley 	if (units == STRING_UNITS_2) {
103564b026fSJames Bottomley 		/* express the remainder as a decimal.  It's currently the
104564b026fSJames Bottomley 		 * numerator of a fraction whose denominator is
105564b026fSJames Bottomley 		 * divisor[units], which is 1 << 10 for STRING_UNITS_2 */
1063c9f3681SJames Bottomley 		remainder *= 1000;
107564b026fSJames Bottomley 		remainder >>= 10;
108564b026fSJames Bottomley 	}
109564b026fSJames Bottomley 
110564b026fSJames Bottomley 	/* add a 5 to the digit below what will be printed to ensure
111564b026fSJames Bottomley 	 * an arithmetical round up and carry it through to size */
112564b026fSJames Bottomley 	remainder += rounding[j];
113564b026fSJames Bottomley 	if (remainder >= 1000) {
114564b026fSJames Bottomley 		remainder -= 1000;
115564b026fSJames Bottomley 		size += 1;
116564b026fSJames Bottomley 	}
117564b026fSJames Bottomley 
118564b026fSJames Bottomley 	if (j) {
11984b9fbedSRasmus Villemoes 		snprintf(tmp, sizeof(tmp), ".%03u", remainder);
1203c9f3681SJames Bottomley 		tmp[j+1] = '\0';
1213c9f3681SJames Bottomley 	}
122b9f28d86SJames Bottomley 
123b9f28d86SJames Bottomley  out:
124b9f28d86SJames Bottomley 	if (i >= ARRAY_SIZE(units_2))
125b9f28d86SJames Bottomley 		unit = "UNK";
126b9f28d86SJames Bottomley 	else
127b9f28d86SJames Bottomley 		unit = units_str[units][i];
1283c9f3681SJames Bottomley 
12984b9fbedSRasmus Villemoes 	snprintf(buf, len, "%u%s %s", (u32)size,
130b9f28d86SJames Bottomley 		 tmp, unit);
1313c9f3681SJames Bottomley }
1323c9f3681SJames Bottomley EXPORT_SYMBOL(string_get_size);
13316c7fa05SAndy Shevchenko 
134f0b93323SCezary Rojewski /**
135f0b93323SCezary Rojewski  * parse_int_array_user - Split string into a sequence of integers
136f0b93323SCezary Rojewski  * @from:	The user space buffer to read from
137f0b93323SCezary Rojewski  * @count:	The maximum number of bytes to read
138f0b93323SCezary Rojewski  * @array:	Returned pointer to sequence of integers
139f0b93323SCezary Rojewski  *
140f0b93323SCezary Rojewski  * On success @array is allocated and initialized with a sequence of
141f0b93323SCezary Rojewski  * integers extracted from the @from plus an additional element that
142f0b93323SCezary Rojewski  * begins the sequence and specifies the integers count.
143f0b93323SCezary Rojewski  *
144f0b93323SCezary Rojewski  * Caller takes responsibility for freeing @array when it is no longer
145f0b93323SCezary Rojewski  * needed.
146f0b93323SCezary Rojewski  */
parse_int_array_user(const char __user * from,size_t count,int ** array)147f0b93323SCezary Rojewski int parse_int_array_user(const char __user *from, size_t count, int **array)
148f0b93323SCezary Rojewski {
149f0b93323SCezary Rojewski 	int *ints, nints;
150f0b93323SCezary Rojewski 	char *buf;
151f0b93323SCezary Rojewski 	int ret = 0;
152f0b93323SCezary Rojewski 
153f0b93323SCezary Rojewski 	buf = memdup_user_nul(from, count);
154f0b93323SCezary Rojewski 	if (IS_ERR(buf))
155f0b93323SCezary Rojewski 		return PTR_ERR(buf);
156f0b93323SCezary Rojewski 
157f0b93323SCezary Rojewski 	get_options(buf, 0, &nints);
158f0b93323SCezary Rojewski 	if (!nints) {
159f0b93323SCezary Rojewski 		ret = -ENOENT;
160f0b93323SCezary Rojewski 		goto free_buf;
161f0b93323SCezary Rojewski 	}
162f0b93323SCezary Rojewski 
163f0b93323SCezary Rojewski 	ints = kcalloc(nints + 1, sizeof(*ints), GFP_KERNEL);
164f0b93323SCezary Rojewski 	if (!ints) {
165f0b93323SCezary Rojewski 		ret = -ENOMEM;
166f0b93323SCezary Rojewski 		goto free_buf;
167f0b93323SCezary Rojewski 	}
168f0b93323SCezary Rojewski 
169f0b93323SCezary Rojewski 	get_options(buf, nints + 1, ints);
170f0b93323SCezary Rojewski 	*array = ints;
171f0b93323SCezary Rojewski 
172f0b93323SCezary Rojewski free_buf:
173f0b93323SCezary Rojewski 	kfree(buf);
174f0b93323SCezary Rojewski 	return ret;
175f0b93323SCezary Rojewski }
176f0b93323SCezary Rojewski EXPORT_SYMBOL(parse_int_array_user);
177f0b93323SCezary Rojewski 
unescape_space(char ** src,char ** dst)17816c7fa05SAndy Shevchenko static bool unescape_space(char **src, char **dst)
17916c7fa05SAndy Shevchenko {
18016c7fa05SAndy Shevchenko 	char *p = *dst, *q = *src;
18116c7fa05SAndy Shevchenko 
18216c7fa05SAndy Shevchenko 	switch (*q) {
18316c7fa05SAndy Shevchenko 	case 'n':
18416c7fa05SAndy Shevchenko 		*p = '\n';
18516c7fa05SAndy Shevchenko 		break;
18616c7fa05SAndy Shevchenko 	case 'r':
18716c7fa05SAndy Shevchenko 		*p = '\r';
18816c7fa05SAndy Shevchenko 		break;
18916c7fa05SAndy Shevchenko 	case 't':
19016c7fa05SAndy Shevchenko 		*p = '\t';
19116c7fa05SAndy Shevchenko 		break;
19216c7fa05SAndy Shevchenko 	case 'v':
19316c7fa05SAndy Shevchenko 		*p = '\v';
19416c7fa05SAndy Shevchenko 		break;
19516c7fa05SAndy Shevchenko 	case 'f':
19616c7fa05SAndy Shevchenko 		*p = '\f';
19716c7fa05SAndy Shevchenko 		break;
19816c7fa05SAndy Shevchenko 	default:
19916c7fa05SAndy Shevchenko 		return false;
20016c7fa05SAndy Shevchenko 	}
20116c7fa05SAndy Shevchenko 	*dst += 1;
20216c7fa05SAndy Shevchenko 	*src += 1;
20316c7fa05SAndy Shevchenko 	return true;
20416c7fa05SAndy Shevchenko }
20516c7fa05SAndy Shevchenko 
unescape_octal(char ** src,char ** dst)20616c7fa05SAndy Shevchenko static bool unescape_octal(char **src, char **dst)
20716c7fa05SAndy Shevchenko {
20816c7fa05SAndy Shevchenko 	char *p = *dst, *q = *src;
20916c7fa05SAndy Shevchenko 	u8 num;
21016c7fa05SAndy Shevchenko 
21116c7fa05SAndy Shevchenko 	if (isodigit(*q) == 0)
21216c7fa05SAndy Shevchenko 		return false;
21316c7fa05SAndy Shevchenko 
21416c7fa05SAndy Shevchenko 	num = (*q++) & 7;
21516c7fa05SAndy Shevchenko 	while (num < 32 && isodigit(*q) && (q - *src < 3)) {
21616c7fa05SAndy Shevchenko 		num <<= 3;
21716c7fa05SAndy Shevchenko 		num += (*q++) & 7;
21816c7fa05SAndy Shevchenko 	}
21916c7fa05SAndy Shevchenko 	*p = num;
22016c7fa05SAndy Shevchenko 	*dst += 1;
22116c7fa05SAndy Shevchenko 	*src = q;
22216c7fa05SAndy Shevchenko 	return true;
22316c7fa05SAndy Shevchenko }
22416c7fa05SAndy Shevchenko 
unescape_hex(char ** src,char ** dst)22516c7fa05SAndy Shevchenko static bool unescape_hex(char **src, char **dst)
22616c7fa05SAndy Shevchenko {
22716c7fa05SAndy Shevchenko 	char *p = *dst, *q = *src;
22816c7fa05SAndy Shevchenko 	int digit;
22916c7fa05SAndy Shevchenko 	u8 num;
23016c7fa05SAndy Shevchenko 
23116c7fa05SAndy Shevchenko 	if (*q++ != 'x')
23216c7fa05SAndy Shevchenko 		return false;
23316c7fa05SAndy Shevchenko 
23416c7fa05SAndy Shevchenko 	num = digit = hex_to_bin(*q++);
23516c7fa05SAndy Shevchenko 	if (digit < 0)
23616c7fa05SAndy Shevchenko 		return false;
23716c7fa05SAndy Shevchenko 
23816c7fa05SAndy Shevchenko 	digit = hex_to_bin(*q);
23916c7fa05SAndy Shevchenko 	if (digit >= 0) {
24016c7fa05SAndy Shevchenko 		q++;
24116c7fa05SAndy Shevchenko 		num = (num << 4) | digit;
24216c7fa05SAndy Shevchenko 	}
24316c7fa05SAndy Shevchenko 	*p = num;
24416c7fa05SAndy Shevchenko 	*dst += 1;
24516c7fa05SAndy Shevchenko 	*src = q;
24616c7fa05SAndy Shevchenko 	return true;
24716c7fa05SAndy Shevchenko }
24816c7fa05SAndy Shevchenko 
unescape_special(char ** src,char ** dst)24916c7fa05SAndy Shevchenko static bool unescape_special(char **src, char **dst)
25016c7fa05SAndy Shevchenko {
25116c7fa05SAndy Shevchenko 	char *p = *dst, *q = *src;
25216c7fa05SAndy Shevchenko 
25316c7fa05SAndy Shevchenko 	switch (*q) {
25416c7fa05SAndy Shevchenko 	case '\"':
25516c7fa05SAndy Shevchenko 		*p = '\"';
25616c7fa05SAndy Shevchenko 		break;
25716c7fa05SAndy Shevchenko 	case '\\':
25816c7fa05SAndy Shevchenko 		*p = '\\';
25916c7fa05SAndy Shevchenko 		break;
26016c7fa05SAndy Shevchenko 	case 'a':
26116c7fa05SAndy Shevchenko 		*p = '\a';
26216c7fa05SAndy Shevchenko 		break;
26316c7fa05SAndy Shevchenko 	case 'e':
26416c7fa05SAndy Shevchenko 		*p = '\e';
26516c7fa05SAndy Shevchenko 		break;
26616c7fa05SAndy Shevchenko 	default:
26716c7fa05SAndy Shevchenko 		return false;
26816c7fa05SAndy Shevchenko 	}
26916c7fa05SAndy Shevchenko 	*dst += 1;
27016c7fa05SAndy Shevchenko 	*src += 1;
27116c7fa05SAndy Shevchenko 	return true;
27216c7fa05SAndy Shevchenko }
27316c7fa05SAndy Shevchenko 
274d295634eSAndy Shevchenko /**
275d295634eSAndy Shevchenko  * string_unescape - unquote characters in the given string
276d295634eSAndy Shevchenko  * @src:	source buffer (escaped)
277d295634eSAndy Shevchenko  * @dst:	destination buffer (unescaped)
278d295634eSAndy Shevchenko  * @size:	size of the destination buffer (0 to unlimit)
279b4658cddSJonathan Corbet  * @flags:	combination of the flags.
280d295634eSAndy Shevchenko  *
281d295634eSAndy Shevchenko  * Description:
282d295634eSAndy Shevchenko  * The function unquotes characters in the given string.
283d295634eSAndy Shevchenko  *
284d295634eSAndy Shevchenko  * Because the size of the output will be the same as or less than the size of
285d295634eSAndy Shevchenko  * the input, the transformation may be performed in place.
286d295634eSAndy Shevchenko  *
287d295634eSAndy Shevchenko  * Caller must provide valid source and destination pointers. Be aware that
288d295634eSAndy Shevchenko  * destination buffer will always be NULL-terminated. Source string must be
289b4658cddSJonathan Corbet  * NULL-terminated as well.  The supported flags are::
290b4658cddSJonathan Corbet  *
291b4658cddSJonathan Corbet  *	UNESCAPE_SPACE:
292b4658cddSJonathan Corbet  *		'\f' - form feed
293b4658cddSJonathan Corbet  *		'\n' - new line
294b4658cddSJonathan Corbet  *		'\r' - carriage return
295b4658cddSJonathan Corbet  *		'\t' - horizontal tab
296b4658cddSJonathan Corbet  *		'\v' - vertical tab
297b4658cddSJonathan Corbet  *	UNESCAPE_OCTAL:
298b4658cddSJonathan Corbet  *		'\NNN' - byte with octal value NNN (1 to 3 digits)
299b4658cddSJonathan Corbet  *	UNESCAPE_HEX:
300b4658cddSJonathan Corbet  *		'\xHH' - byte with hexadecimal value HH (1 to 2 digits)
301b4658cddSJonathan Corbet  *	UNESCAPE_SPECIAL:
302b4658cddSJonathan Corbet  *		'\"' - double quote
303b4658cddSJonathan Corbet  *		'\\' - backslash
304b4658cddSJonathan Corbet  *		'\a' - alert (BEL)
305b4658cddSJonathan Corbet  *		'\e' - escape
306b4658cddSJonathan Corbet  *	UNESCAPE_ANY:
307b4658cddSJonathan Corbet  *		all previous together
308d295634eSAndy Shevchenko  *
309d295634eSAndy Shevchenko  * Return:
310d295634eSAndy Shevchenko  * The amount of the characters processed to the destination buffer excluding
311d295634eSAndy Shevchenko  * trailing '\0' is returned.
312d295634eSAndy Shevchenko  */
string_unescape(char * src,char * dst,size_t size,unsigned int flags)31316c7fa05SAndy Shevchenko int string_unescape(char *src, char *dst, size_t size, unsigned int flags)
31416c7fa05SAndy Shevchenko {
31516c7fa05SAndy Shevchenko 	char *out = dst;
31616c7fa05SAndy Shevchenko 
31716c7fa05SAndy Shevchenko 	while (*src && --size) {
31816c7fa05SAndy Shevchenko 		if (src[0] == '\\' && src[1] != '\0' && size > 1) {
31916c7fa05SAndy Shevchenko 			src++;
32016c7fa05SAndy Shevchenko 			size--;
32116c7fa05SAndy Shevchenko 
32216c7fa05SAndy Shevchenko 			if (flags & UNESCAPE_SPACE &&
32316c7fa05SAndy Shevchenko 					unescape_space(&src, &out))
32416c7fa05SAndy Shevchenko 				continue;
32516c7fa05SAndy Shevchenko 
32616c7fa05SAndy Shevchenko 			if (flags & UNESCAPE_OCTAL &&
32716c7fa05SAndy Shevchenko 					unescape_octal(&src, &out))
32816c7fa05SAndy Shevchenko 				continue;
32916c7fa05SAndy Shevchenko 
33016c7fa05SAndy Shevchenko 			if (flags & UNESCAPE_HEX &&
33116c7fa05SAndy Shevchenko 					unescape_hex(&src, &out))
33216c7fa05SAndy Shevchenko 				continue;
33316c7fa05SAndy Shevchenko 
33416c7fa05SAndy Shevchenko 			if (flags & UNESCAPE_SPECIAL &&
33516c7fa05SAndy Shevchenko 					unescape_special(&src, &out))
33616c7fa05SAndy Shevchenko 				continue;
33716c7fa05SAndy Shevchenko 
33816c7fa05SAndy Shevchenko 			*out++ = '\\';
33916c7fa05SAndy Shevchenko 		}
34016c7fa05SAndy Shevchenko 		*out++ = *src++;
34116c7fa05SAndy Shevchenko 	}
34216c7fa05SAndy Shevchenko 	*out = '\0';
34316c7fa05SAndy Shevchenko 
34416c7fa05SAndy Shevchenko 	return out - dst;
34516c7fa05SAndy Shevchenko }
34616c7fa05SAndy Shevchenko EXPORT_SYMBOL(string_unescape);
347c8250381SAndy Shevchenko 
escape_passthrough(unsigned char c,char ** dst,char * end)3483aeddc7dSRasmus Villemoes static bool escape_passthrough(unsigned char c, char **dst, char *end)
349c8250381SAndy Shevchenko {
350c8250381SAndy Shevchenko 	char *out = *dst;
351c8250381SAndy Shevchenko 
3523aeddc7dSRasmus Villemoes 	if (out < end)
3533aeddc7dSRasmus Villemoes 		*out = c;
3543aeddc7dSRasmus Villemoes 	*dst = out + 1;
3553aeddc7dSRasmus Villemoes 	return true;
356c8250381SAndy Shevchenko }
357c8250381SAndy Shevchenko 
escape_space(unsigned char c,char ** dst,char * end)3583aeddc7dSRasmus Villemoes static bool escape_space(unsigned char c, char **dst, char *end)
359c8250381SAndy Shevchenko {
360c8250381SAndy Shevchenko 	char *out = *dst;
361c8250381SAndy Shevchenko 	unsigned char to;
362c8250381SAndy Shevchenko 
363c8250381SAndy Shevchenko 	switch (c) {
364c8250381SAndy Shevchenko 	case '\n':
365c8250381SAndy Shevchenko 		to = 'n';
366c8250381SAndy Shevchenko 		break;
367c8250381SAndy Shevchenko 	case '\r':
368c8250381SAndy Shevchenko 		to = 'r';
369c8250381SAndy Shevchenko 		break;
370c8250381SAndy Shevchenko 	case '\t':
371c8250381SAndy Shevchenko 		to = 't';
372c8250381SAndy Shevchenko 		break;
373c8250381SAndy Shevchenko 	case '\v':
374c8250381SAndy Shevchenko 		to = 'v';
375c8250381SAndy Shevchenko 		break;
376c8250381SAndy Shevchenko 	case '\f':
377c8250381SAndy Shevchenko 		to = 'f';
378c8250381SAndy Shevchenko 		break;
379c8250381SAndy Shevchenko 	default:
3803aeddc7dSRasmus Villemoes 		return false;
381c8250381SAndy Shevchenko 	}
382c8250381SAndy Shevchenko 
3833aeddc7dSRasmus Villemoes 	if (out < end)
3843aeddc7dSRasmus Villemoes 		*out = '\\';
3853aeddc7dSRasmus Villemoes 	++out;
3863aeddc7dSRasmus Villemoes 	if (out < end)
3873aeddc7dSRasmus Villemoes 		*out = to;
3883aeddc7dSRasmus Villemoes 	++out;
389c8250381SAndy Shevchenko 
390c8250381SAndy Shevchenko 	*dst = out;
3913aeddc7dSRasmus Villemoes 	return true;
392c8250381SAndy Shevchenko }
393c8250381SAndy Shevchenko 
escape_special(unsigned char c,char ** dst,char * end)3943aeddc7dSRasmus Villemoes static bool escape_special(unsigned char c, char **dst, char *end)
395c8250381SAndy Shevchenko {
396c8250381SAndy Shevchenko 	char *out = *dst;
397c8250381SAndy Shevchenko 	unsigned char to;
398c8250381SAndy Shevchenko 
399c8250381SAndy Shevchenko 	switch (c) {
400c8250381SAndy Shevchenko 	case '\\':
401c8250381SAndy Shevchenko 		to = '\\';
402c8250381SAndy Shevchenko 		break;
403c8250381SAndy Shevchenko 	case '\a':
404c8250381SAndy Shevchenko 		to = 'a';
405c8250381SAndy Shevchenko 		break;
406c8250381SAndy Shevchenko 	case '\e':
407c8250381SAndy Shevchenko 		to = 'e';
408c8250381SAndy Shevchenko 		break;
40991027d0aSChris Down 	case '"':
41091027d0aSChris Down 		to = '"';
41191027d0aSChris Down 		break;
412c8250381SAndy Shevchenko 	default:
4133aeddc7dSRasmus Villemoes 		return false;
414c8250381SAndy Shevchenko 	}
415c8250381SAndy Shevchenko 
4163aeddc7dSRasmus Villemoes 	if (out < end)
4173aeddc7dSRasmus Villemoes 		*out = '\\';
4183aeddc7dSRasmus Villemoes 	++out;
4193aeddc7dSRasmus Villemoes 	if (out < end)
4203aeddc7dSRasmus Villemoes 		*out = to;
4213aeddc7dSRasmus Villemoes 	++out;
422c8250381SAndy Shevchenko 
423c8250381SAndy Shevchenko 	*dst = out;
4243aeddc7dSRasmus Villemoes 	return true;
425c8250381SAndy Shevchenko }
426c8250381SAndy Shevchenko 
escape_null(unsigned char c,char ** dst,char * end)4273aeddc7dSRasmus Villemoes static bool escape_null(unsigned char c, char **dst, char *end)
428c8250381SAndy Shevchenko {
429c8250381SAndy Shevchenko 	char *out = *dst;
430c8250381SAndy Shevchenko 
431c8250381SAndy Shevchenko 	if (c)
4323aeddc7dSRasmus Villemoes 		return false;
433c8250381SAndy Shevchenko 
4343aeddc7dSRasmus Villemoes 	if (out < end)
4353aeddc7dSRasmus Villemoes 		*out = '\\';
4363aeddc7dSRasmus Villemoes 	++out;
4373aeddc7dSRasmus Villemoes 	if (out < end)
4383aeddc7dSRasmus Villemoes 		*out = '0';
4393aeddc7dSRasmus Villemoes 	++out;
4403aeddc7dSRasmus Villemoes 
4413aeddc7dSRasmus Villemoes 	*dst = out;
4423aeddc7dSRasmus Villemoes 	return true;
4433aeddc7dSRasmus Villemoes }
4443aeddc7dSRasmus Villemoes 
escape_octal(unsigned char c,char ** dst,char * end)4453aeddc7dSRasmus Villemoes static bool escape_octal(unsigned char c, char **dst, char *end)
446c8250381SAndy Shevchenko {
447c8250381SAndy Shevchenko 	char *out = *dst;
448c8250381SAndy Shevchenko 
4493aeddc7dSRasmus Villemoes 	if (out < end)
4503aeddc7dSRasmus Villemoes 		*out = '\\';
4513aeddc7dSRasmus Villemoes 	++out;
4523aeddc7dSRasmus Villemoes 	if (out < end)
4533aeddc7dSRasmus Villemoes 		*out = ((c >> 6) & 0x07) + '0';
4543aeddc7dSRasmus Villemoes 	++out;
4553aeddc7dSRasmus Villemoes 	if (out < end)
4563aeddc7dSRasmus Villemoes 		*out = ((c >> 3) & 0x07) + '0';
4573aeddc7dSRasmus Villemoes 	++out;
4583aeddc7dSRasmus Villemoes 	if (out < end)
4593aeddc7dSRasmus Villemoes 		*out = ((c >> 0) & 0x07) + '0';
4603aeddc7dSRasmus Villemoes 	++out;
4613aeddc7dSRasmus Villemoes 
4623aeddc7dSRasmus Villemoes 	*dst = out;
4633aeddc7dSRasmus Villemoes 	return true;
4643aeddc7dSRasmus Villemoes }
4653aeddc7dSRasmus Villemoes 
escape_hex(unsigned char c,char ** dst,char * end)4663aeddc7dSRasmus Villemoes static bool escape_hex(unsigned char c, char **dst, char *end)
467c8250381SAndy Shevchenko {
468c8250381SAndy Shevchenko 	char *out = *dst;
469c8250381SAndy Shevchenko 
4703aeddc7dSRasmus Villemoes 	if (out < end)
4713aeddc7dSRasmus Villemoes 		*out = '\\';
4723aeddc7dSRasmus Villemoes 	++out;
4733aeddc7dSRasmus Villemoes 	if (out < end)
4743aeddc7dSRasmus Villemoes 		*out = 'x';
4753aeddc7dSRasmus Villemoes 	++out;
4763aeddc7dSRasmus Villemoes 	if (out < end)
4773aeddc7dSRasmus Villemoes 		*out = hex_asc_hi(c);
4783aeddc7dSRasmus Villemoes 	++out;
4793aeddc7dSRasmus Villemoes 	if (out < end)
4803aeddc7dSRasmus Villemoes 		*out = hex_asc_lo(c);
4813aeddc7dSRasmus Villemoes 	++out;
482c8250381SAndy Shevchenko 
483c8250381SAndy Shevchenko 	*dst = out;
4843aeddc7dSRasmus Villemoes 	return true;
485c8250381SAndy Shevchenko }
486c8250381SAndy Shevchenko 
487c8250381SAndy Shevchenko /**
488c8250381SAndy Shevchenko  * string_escape_mem - quote characters in the given memory buffer
489c8250381SAndy Shevchenko  * @src:	source buffer (unescaped)
490c8250381SAndy Shevchenko  * @isz:	source buffer size
491c8250381SAndy Shevchenko  * @dst:	destination buffer (escaped)
492c8250381SAndy Shevchenko  * @osz:	destination buffer size
493b4658cddSJonathan Corbet  * @flags:	combination of the flags
494b4658cddSJonathan Corbet  * @only:	NULL-terminated string containing characters used to limit
495b4658cddSJonathan Corbet  *		the selected escape class. If characters are included in @only
496b4658cddSJonathan Corbet  *		that would not normally be escaped by the classes selected
497b4658cddSJonathan Corbet  *		in @flags, they will be copied to @dst unescaped.
498b4658cddSJonathan Corbet  *
499b4658cddSJonathan Corbet  * Description:
500b4658cddSJonathan Corbet  * The process of escaping byte buffer includes several parts. They are applied
501b4658cddSJonathan Corbet  * in the following sequence.
502b4658cddSJonathan Corbet  *
50362519b88SAndy Shevchenko  *	1. The character is not matched to the one from @only string and thus
504b4658cddSJonathan Corbet  *	   must go as-is to the output.
5050362c27fSAndy Shevchenko  *	2. The character is matched to the printable and ASCII classes, if asked,
506a0809783SAndy Shevchenko  *	   and in case of match it passes through to the output.
5070362c27fSAndy Shevchenko  *	3. The character is matched to the printable or ASCII class, if asked,
5080362c27fSAndy Shevchenko  *	   and in case of match it passes through to the output.
5090362c27fSAndy Shevchenko  *	4. The character is checked if it falls into the class given by @flags.
510b4658cddSJonathan Corbet  *	   %ESCAPE_OCTAL and %ESCAPE_HEX are going last since they cover any
511b4658cddSJonathan Corbet  *	   character. Note that they actually can't go together, otherwise
512b4658cddSJonathan Corbet  *	   %ESCAPE_HEX will be ignored.
513b4658cddSJonathan Corbet  *
514b4658cddSJonathan Corbet  * Caller must provide valid source and destination pointers. Be aware that
515b4658cddSJonathan Corbet  * destination buffer will not be NULL-terminated, thus caller have to append
516b4658cddSJonathan Corbet  * it if needs. The supported flags are::
517b4658cddSJonathan Corbet  *
518d89a3f73SKees Cook  *	%ESCAPE_SPACE: (special white space, not space itself)
519c8250381SAndy Shevchenko  *		'\f' - form feed
520c8250381SAndy Shevchenko  *		'\n' - new line
521c8250381SAndy Shevchenko  *		'\r' - carriage return
522c8250381SAndy Shevchenko  *		'\t' - horizontal tab
523c8250381SAndy Shevchenko  *		'\v' - vertical tab
524c8250381SAndy Shevchenko  *	%ESCAPE_SPECIAL:
52591027d0aSChris Down  *		'\"' - double quote
526c8250381SAndy Shevchenko  *		'\\' - backslash
527c8250381SAndy Shevchenko  *		'\a' - alert (BEL)
528c8250381SAndy Shevchenko  *		'\e' - escape
529c8250381SAndy Shevchenko  *	%ESCAPE_NULL:
530c8250381SAndy Shevchenko  *		'\0' - null
531c8250381SAndy Shevchenko  *	%ESCAPE_OCTAL:
532c8250381SAndy Shevchenko  *		'\NNN' - byte with octal value NNN (3 digits)
533c8250381SAndy Shevchenko  *	%ESCAPE_ANY:
534c8250381SAndy Shevchenko  *		all previous together
535c8250381SAndy Shevchenko  *	%ESCAPE_NP:
536a0809783SAndy Shevchenko  *		escape only non-printable characters, checked by isprint()
537c8250381SAndy Shevchenko  *	%ESCAPE_ANY_NP:
538c8250381SAndy Shevchenko  *		all previous together
539c8250381SAndy Shevchenko  *	%ESCAPE_HEX:
540c8250381SAndy Shevchenko  *		'\xHH' - byte with hexadecimal value HH (2 digits)
541a0809783SAndy Shevchenko  *	%ESCAPE_NA:
542a0809783SAndy Shevchenko  *		escape only non-ascii characters, checked by isascii()
5430362c27fSAndy Shevchenko  *	%ESCAPE_NAP:
5440362c27fSAndy Shevchenko  *		escape only non-printable or non-ascii characters
545aec0d096SAndy Shevchenko  *	%ESCAPE_APPEND:
546aec0d096SAndy Shevchenko  *		append characters from @only to be escaped by the given classes
547aec0d096SAndy Shevchenko  *
548aec0d096SAndy Shevchenko  * %ESCAPE_APPEND would help to pass additional characters to the escaped, when
549aec0d096SAndy Shevchenko  * one of %ESCAPE_NP, %ESCAPE_NA, or %ESCAPE_NAP is provided.
550a0809783SAndy Shevchenko  *
5510362c27fSAndy Shevchenko  * One notable caveat, the %ESCAPE_NAP, %ESCAPE_NP and %ESCAPE_NA have the
5520362c27fSAndy Shevchenko  * higher priority than the rest of the flags (%ESCAPE_NAP is the highest).
553a0809783SAndy Shevchenko  * It doesn't make much sense to use either of them without %ESCAPE_OCTAL
554a0809783SAndy Shevchenko  * or %ESCAPE_HEX, because they cover most of the other character classes.
5550362c27fSAndy Shevchenko  * %ESCAPE_NAP can utilize %ESCAPE_SPACE or %ESCAPE_SPECIAL in addition to
5560362c27fSAndy Shevchenko  * the above.
557c8250381SAndy Shevchenko  *
558c8250381SAndy Shevchenko  * Return:
55941416f23SRasmus Villemoes  * The total size of the escaped output that would be generated for
56041416f23SRasmus Villemoes  * the given input and flags. To check whether the output was
56141416f23SRasmus Villemoes  * truncated, compare the return value to osz. There is room left in
56241416f23SRasmus Villemoes  * dst for a '\0' terminator if and only if ret < osz.
563c8250381SAndy Shevchenko  */
string_escape_mem(const char * src,size_t isz,char * dst,size_t osz,unsigned int flags,const char * only)56441416f23SRasmus Villemoes int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
565b40bdb7fSKees Cook 		      unsigned int flags, const char *only)
566c8250381SAndy Shevchenko {
56741416f23SRasmus Villemoes 	char *p = dst;
5683aeddc7dSRasmus Villemoes 	char *end = p + osz;
569b40bdb7fSKees Cook 	bool is_dict = only && *only;
570aec0d096SAndy Shevchenko 	bool is_append = flags & ESCAPE_APPEND;
571c8250381SAndy Shevchenko 
572c8250381SAndy Shevchenko 	while (isz--) {
573c8250381SAndy Shevchenko 		unsigned char c = *src++;
574aec0d096SAndy Shevchenko 		bool in_dict = is_dict && strchr(only, c);
575c8250381SAndy Shevchenko 
576c8250381SAndy Shevchenko 		/*
577c8250381SAndy Shevchenko 		 * Apply rules in the following sequence:
578b40bdb7fSKees Cook 		 *	- the @only string is supplied and does not contain a
579c8250381SAndy Shevchenko 		 *	  character under question
5800362c27fSAndy Shevchenko 		 *	- the character is printable and ASCII, when @flags has
5810362c27fSAndy Shevchenko 		 *	  %ESCAPE_NAP bit set
58262519b88SAndy Shevchenko 		 *	- the character is printable, when @flags has
58362519b88SAndy Shevchenko 		 *	  %ESCAPE_NP bit set
584a0809783SAndy Shevchenko 		 *	- the character is ASCII, when @flags has
585a0809783SAndy Shevchenko 		 *	  %ESCAPE_NA bit set
586c8250381SAndy Shevchenko 		 *	- the character doesn't fall into a class of symbols
587c8250381SAndy Shevchenko 		 *	  defined by given @flags
588c8250381SAndy Shevchenko 		 * In these cases we just pass through a character to the
589c8250381SAndy Shevchenko 		 * output buffer.
590aec0d096SAndy Shevchenko 		 *
591aec0d096SAndy Shevchenko 		 * When %ESCAPE_APPEND is passed, the characters from @only
592aec0d096SAndy Shevchenko 		 * have been excluded from the %ESCAPE_NAP, %ESCAPE_NP, and
593aec0d096SAndy Shevchenko 		 * %ESCAPE_NA cases.
594c8250381SAndy Shevchenko 		 */
595aec0d096SAndy Shevchenko 		if (!(is_append || in_dict) && is_dict &&
5967e5969aeSAndy Shevchenko 					  escape_passthrough(c, &p, end))
5977e5969aeSAndy Shevchenko 			continue;
5987e5969aeSAndy Shevchenko 
599aec0d096SAndy Shevchenko 		if (!(is_append && in_dict) && isascii(c) && isprint(c) &&
6000362c27fSAndy Shevchenko 		    flags & ESCAPE_NAP && escape_passthrough(c, &p, end))
6010362c27fSAndy Shevchenko 			continue;
6020362c27fSAndy Shevchenko 
603aec0d096SAndy Shevchenko 		if (!(is_append && in_dict) && isprint(c) &&
60462519b88SAndy Shevchenko 		    flags & ESCAPE_NP && escape_passthrough(c, &p, end))
60562519b88SAndy Shevchenko 			continue;
60662519b88SAndy Shevchenko 
607aec0d096SAndy Shevchenko 		if (!(is_append && in_dict) && isascii(c) &&
608a0809783SAndy Shevchenko 		    flags & ESCAPE_NA && escape_passthrough(c, &p, end))
609a0809783SAndy Shevchenko 			continue;
610a0809783SAndy Shevchenko 
6113aeddc7dSRasmus Villemoes 		if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
612c8250381SAndy Shevchenko 			continue;
613c8250381SAndy Shevchenko 
6143aeddc7dSRasmus Villemoes 		if (flags & ESCAPE_SPECIAL && escape_special(c, &p, end))
615c8250381SAndy Shevchenko 			continue;
616c8250381SAndy Shevchenko 
6173aeddc7dSRasmus Villemoes 		if (flags & ESCAPE_NULL && escape_null(c, &p, end))
618c8250381SAndy Shevchenko 			continue;
619c8250381SAndy Shevchenko 
620c8250381SAndy Shevchenko 		/* ESCAPE_OCTAL and ESCAPE_HEX always go last */
6213aeddc7dSRasmus Villemoes 		if (flags & ESCAPE_OCTAL && escape_octal(c, &p, end))
6223aeddc7dSRasmus Villemoes 			continue;
6233aeddc7dSRasmus Villemoes 
6243aeddc7dSRasmus Villemoes 		if (flags & ESCAPE_HEX && escape_hex(c, &p, end))
625c8250381SAndy Shevchenko 			continue;
6263aeddc7dSRasmus Villemoes 
6273aeddc7dSRasmus Villemoes 		escape_passthrough(c, &p, end);
628c8250381SAndy Shevchenko 	}
629c8250381SAndy Shevchenko 
63041416f23SRasmus Villemoes 	return p - dst;
631c8250381SAndy Shevchenko }
632c8250381SAndy Shevchenko EXPORT_SYMBOL(string_escape_mem);
633b53f27e4SKees Cook 
634b53f27e4SKees Cook /*
635b53f27e4SKees Cook  * Return an allocated string that has been escaped of special characters
636b53f27e4SKees Cook  * and double quotes, making it safe to log in quotes.
637b53f27e4SKees Cook  */
kstrdup_quotable(const char * src,gfp_t gfp)638b53f27e4SKees Cook char *kstrdup_quotable(const char *src, gfp_t gfp)
639b53f27e4SKees Cook {
640b53f27e4SKees Cook 	size_t slen, dlen;
641b53f27e4SKees Cook 	char *dst;
642b53f27e4SKees Cook 	const int flags = ESCAPE_HEX;
643b53f27e4SKees Cook 	const char esc[] = "\f\n\r\t\v\a\e\\\"";
644b53f27e4SKees Cook 
645b53f27e4SKees Cook 	if (!src)
646b53f27e4SKees Cook 		return NULL;
647b53f27e4SKees Cook 	slen = strlen(src);
648b53f27e4SKees Cook 
649b53f27e4SKees Cook 	dlen = string_escape_mem(src, slen, NULL, 0, flags, esc);
650b53f27e4SKees Cook 	dst = kmalloc(dlen + 1, gfp);
651b53f27e4SKees Cook 	if (!dst)
652b53f27e4SKees Cook 		return NULL;
653b53f27e4SKees Cook 
654b53f27e4SKees Cook 	WARN_ON(string_escape_mem(src, slen, dst, dlen, flags, esc) != dlen);
655b53f27e4SKees Cook 	dst[dlen] = '\0';
656b53f27e4SKees Cook 
657b53f27e4SKees Cook 	return dst;
658b53f27e4SKees Cook }
659b53f27e4SKees Cook EXPORT_SYMBOL_GPL(kstrdup_quotable);
6600d044328SKees Cook 
6610d044328SKees Cook /*
6620d044328SKees Cook  * Returns allocated NULL-terminated string containing process
6630d044328SKees Cook  * command line, with inter-argument NULLs replaced with spaces,
6640d044328SKees Cook  * and other special characters escaped.
6650d044328SKees Cook  */
kstrdup_quotable_cmdline(struct task_struct * task,gfp_t gfp)6660d044328SKees Cook char *kstrdup_quotable_cmdline(struct task_struct *task, gfp_t gfp)
6670d044328SKees Cook {
6680d044328SKees Cook 	char *buffer, *quoted;
6690d044328SKees Cook 	int i, res;
6700d044328SKees Cook 
6710ee931c4SMichal Hocko 	buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
6720d044328SKees Cook 	if (!buffer)
6730d044328SKees Cook 		return NULL;
6740d044328SKees Cook 
6750d044328SKees Cook 	res = get_cmdline(task, buffer, PAGE_SIZE - 1);
6760d044328SKees Cook 	buffer[res] = '\0';
6770d044328SKees Cook 
6780d044328SKees Cook 	/* Collapse trailing NULLs, leave res pointing to last non-NULL. */
6790d044328SKees Cook 	while (--res >= 0 && buffer[res] == '\0')
6800d044328SKees Cook 		;
6810d044328SKees Cook 
6820d044328SKees Cook 	/* Replace inter-argument NULLs. */
6830d044328SKees Cook 	for (i = 0; i <= res; i++)
6840d044328SKees Cook 		if (buffer[i] == '\0')
6850d044328SKees Cook 			buffer[i] = ' ';
6860d044328SKees Cook 
6870d044328SKees Cook 	/* Make sure result is printable. */
6880d044328SKees Cook 	quoted = kstrdup_quotable(buffer, gfp);
6890d044328SKees Cook 	kfree(buffer);
6900d044328SKees Cook 	return quoted;
6910d044328SKees Cook }
6920d044328SKees Cook EXPORT_SYMBOL_GPL(kstrdup_quotable_cmdline);
69321985319SKees Cook 
69421985319SKees Cook /*
69521985319SKees Cook  * Returns allocated NULL-terminated string containing pathname,
69621985319SKees Cook  * with special characters escaped, able to be safely logged. If
69721985319SKees Cook  * there is an error, the leading character will be "<".
69821985319SKees Cook  */
kstrdup_quotable_file(struct file * file,gfp_t gfp)69921985319SKees Cook char *kstrdup_quotable_file(struct file *file, gfp_t gfp)
70021985319SKees Cook {
70121985319SKees Cook 	char *temp, *pathname;
70221985319SKees Cook 
70321985319SKees Cook 	if (!file)
70421985319SKees Cook 		return kstrdup("<unknown>", gfp);
70521985319SKees Cook 
70621985319SKees Cook 	/* We add 11 spaces for ' (deleted)' to be appended */
7070ee931c4SMichal Hocko 	temp = kmalloc(PATH_MAX + 11, GFP_KERNEL);
70821985319SKees Cook 	if (!temp)
70921985319SKees Cook 		return kstrdup("<no_memory>", gfp);
71021985319SKees Cook 
71121985319SKees Cook 	pathname = file_path(file, temp, PATH_MAX + 11);
71221985319SKees Cook 	if (IS_ERR(pathname))
71321985319SKees Cook 		pathname = kstrdup("<too_long>", gfp);
71421985319SKees Cook 	else
71521985319SKees Cook 		pathname = kstrdup_quotable(pathname, gfp);
71621985319SKees Cook 
71721985319SKees Cook 	kfree(temp);
71821985319SKees Cook 	return pathname;
71921985319SKees Cook }
72021985319SKees Cook EXPORT_SYMBOL_GPL(kstrdup_quotable_file);
7210fd16012SBartosz Golaszewski 
722045ad464SAndy Shevchenko /*
723045ad464SAndy Shevchenko  * Returns duplicate string in which the @old characters are replaced by @new.
724045ad464SAndy Shevchenko  */
kstrdup_and_replace(const char * src,char old,char new,gfp_t gfp)725045ad464SAndy Shevchenko char *kstrdup_and_replace(const char *src, char old, char new, gfp_t gfp)
726045ad464SAndy Shevchenko {
727045ad464SAndy Shevchenko 	char *dst;
728045ad464SAndy Shevchenko 
729045ad464SAndy Shevchenko 	dst = kstrdup(src, gfp);
730045ad464SAndy Shevchenko 	if (!dst)
731045ad464SAndy Shevchenko 		return NULL;
732045ad464SAndy Shevchenko 
733045ad464SAndy Shevchenko 	return strreplace(dst, old, new);
734045ad464SAndy Shevchenko }
735045ad464SAndy Shevchenko EXPORT_SYMBOL_GPL(kstrdup_and_replace);
736045ad464SAndy Shevchenko 
7370fd16012SBartosz Golaszewski /**
738418e0a35SAndy Shevchenko  * kasprintf_strarray - allocate and fill array of sequential strings
739418e0a35SAndy Shevchenko  * @gfp: flags for the slab allocator
740418e0a35SAndy Shevchenko  * @prefix: prefix to be used
741418e0a35SAndy Shevchenko  * @n: amount of lines to be allocated and filled
742418e0a35SAndy Shevchenko  *
743418e0a35SAndy Shevchenko  * Allocates and fills @n strings using pattern "%s-%zu", where prefix
744418e0a35SAndy Shevchenko  * is provided by caller. The caller is responsible to free them with
745418e0a35SAndy Shevchenko  * kfree_strarray() after use.
746418e0a35SAndy Shevchenko  *
747418e0a35SAndy Shevchenko  * Returns array of strings or NULL when memory can't be allocated.
748418e0a35SAndy Shevchenko  */
kasprintf_strarray(gfp_t gfp,const char * prefix,size_t n)749418e0a35SAndy Shevchenko char **kasprintf_strarray(gfp_t gfp, const char *prefix, size_t n)
750418e0a35SAndy Shevchenko {
751418e0a35SAndy Shevchenko 	char **names;
752418e0a35SAndy Shevchenko 	size_t i;
753418e0a35SAndy Shevchenko 
754418e0a35SAndy Shevchenko 	names = kcalloc(n + 1, sizeof(char *), gfp);
755418e0a35SAndy Shevchenko 	if (!names)
756418e0a35SAndy Shevchenko 		return NULL;
757418e0a35SAndy Shevchenko 
758418e0a35SAndy Shevchenko 	for (i = 0; i < n; i++) {
759418e0a35SAndy Shevchenko 		names[i] = kasprintf(gfp, "%s-%zu", prefix, i);
760418e0a35SAndy Shevchenko 		if (!names[i]) {
761418e0a35SAndy Shevchenko 			kfree_strarray(names, i);
762418e0a35SAndy Shevchenko 			return NULL;
763418e0a35SAndy Shevchenko 		}
764418e0a35SAndy Shevchenko 	}
765418e0a35SAndy Shevchenko 
766418e0a35SAndy Shevchenko 	return names;
767418e0a35SAndy Shevchenko }
768418e0a35SAndy Shevchenko EXPORT_SYMBOL_GPL(kasprintf_strarray);
769418e0a35SAndy Shevchenko 
770418e0a35SAndy Shevchenko /**
7710fd16012SBartosz Golaszewski  * kfree_strarray - free a number of dynamically allocated strings contained
7720fd16012SBartosz Golaszewski  *                  in an array and the array itself
7730fd16012SBartosz Golaszewski  *
7740fd16012SBartosz Golaszewski  * @array: Dynamically allocated array of strings to free.
7750fd16012SBartosz Golaszewski  * @n: Number of strings (starting from the beginning of the array) to free.
7760fd16012SBartosz Golaszewski  *
7770fd16012SBartosz Golaszewski  * Passing a non-NULL @array and @n == 0 as well as NULL @array are valid
7780fd16012SBartosz Golaszewski  * use-cases. If @array is NULL, the function does nothing.
7790fd16012SBartosz Golaszewski  */
kfree_strarray(char ** array,size_t n)7800fd16012SBartosz Golaszewski void kfree_strarray(char **array, size_t n)
7810fd16012SBartosz Golaszewski {
7820fd16012SBartosz Golaszewski 	unsigned int i;
7830fd16012SBartosz Golaszewski 
7840fd16012SBartosz Golaszewski 	if (!array)
7850fd16012SBartosz Golaszewski 		return;
7860fd16012SBartosz Golaszewski 
7870fd16012SBartosz Golaszewski 	for (i = 0; i < n; i++)
7880fd16012SBartosz Golaszewski 		kfree(array[i]);
7890fd16012SBartosz Golaszewski 	kfree(array);
7900fd16012SBartosz Golaszewski }
7910fd16012SBartosz Golaszewski EXPORT_SYMBOL_GPL(kfree_strarray);
792cfecea6eSKees Cook 
793acdb89b6SAndy Shevchenko struct strarray {
794acdb89b6SAndy Shevchenko 	char **array;
795acdb89b6SAndy Shevchenko 	size_t n;
796acdb89b6SAndy Shevchenko };
797acdb89b6SAndy Shevchenko 
devm_kfree_strarray(struct device * dev,void * res)798acdb89b6SAndy Shevchenko static void devm_kfree_strarray(struct device *dev, void *res)
799acdb89b6SAndy Shevchenko {
800acdb89b6SAndy Shevchenko 	struct strarray *array = res;
801acdb89b6SAndy Shevchenko 
802acdb89b6SAndy Shevchenko 	kfree_strarray(array->array, array->n);
803acdb89b6SAndy Shevchenko }
804acdb89b6SAndy Shevchenko 
devm_kasprintf_strarray(struct device * dev,const char * prefix,size_t n)805acdb89b6SAndy Shevchenko char **devm_kasprintf_strarray(struct device *dev, const char *prefix, size_t n)
806acdb89b6SAndy Shevchenko {
807acdb89b6SAndy Shevchenko 	struct strarray *ptr;
808acdb89b6SAndy Shevchenko 
809acdb89b6SAndy Shevchenko 	ptr = devres_alloc(devm_kfree_strarray, sizeof(*ptr), GFP_KERNEL);
810acdb89b6SAndy Shevchenko 	if (!ptr)
811acdb89b6SAndy Shevchenko 		return ERR_PTR(-ENOMEM);
812acdb89b6SAndy Shevchenko 
813acdb89b6SAndy Shevchenko 	ptr->array = kasprintf_strarray(GFP_KERNEL, prefix, n);
814acdb89b6SAndy Shevchenko 	if (!ptr->array) {
815acdb89b6SAndy Shevchenko 		devres_free(ptr);
816acdb89b6SAndy Shevchenko 		return ERR_PTR(-ENOMEM);
817acdb89b6SAndy Shevchenko 	}
818acdb89b6SAndy Shevchenko 
819cd290a98SPuyou Lu 	ptr->n = n;
820cd290a98SPuyou Lu 	devres_add(dev, ptr);
821cd290a98SPuyou Lu 
822acdb89b6SAndy Shevchenko 	return ptr->array;
823acdb89b6SAndy Shevchenko }
824acdb89b6SAndy Shevchenko EXPORT_SYMBOL_GPL(devm_kasprintf_strarray);
825acdb89b6SAndy Shevchenko 
826cfecea6eSKees Cook /**
827cfecea6eSKees Cook  * strscpy_pad() - Copy a C-string into a sized buffer
828cfecea6eSKees Cook  * @dest: Where to copy the string to
829cfecea6eSKees Cook  * @src: Where to copy the string from
830cfecea6eSKees Cook  * @count: Size of destination buffer
831cfecea6eSKees Cook  *
832cfecea6eSKees Cook  * Copy the string, or as much of it as fits, into the dest buffer.  The
833cfecea6eSKees Cook  * behavior is undefined if the string buffers overlap.  The destination
834cfecea6eSKees Cook  * buffer is always %NUL terminated, unless it's zero-sized.
835cfecea6eSKees Cook  *
836cfecea6eSKees Cook  * If the source string is shorter than the destination buffer, zeros
837cfecea6eSKees Cook  * the tail of the destination buffer.
838cfecea6eSKees Cook  *
839cfecea6eSKees Cook  * For full explanation of why you may want to consider using the
840cfecea6eSKees Cook  * 'strscpy' functions please see the function docstring for strscpy().
841cfecea6eSKees Cook  *
842cfecea6eSKees Cook  * Returns:
843cfecea6eSKees Cook  * * The number of characters copied (not including the trailing %NUL)
844cfecea6eSKees Cook  * * -E2BIG if count is 0 or @src was truncated.
845cfecea6eSKees Cook  */
strscpy_pad(char * dest,const char * src,size_t count)846cfecea6eSKees Cook ssize_t strscpy_pad(char *dest, const char *src, size_t count)
847cfecea6eSKees Cook {
848cfecea6eSKees Cook 	ssize_t written;
849cfecea6eSKees Cook 
850cfecea6eSKees Cook 	written = strscpy(dest, src, count);
851cfecea6eSKees Cook 	if (written < 0 || written == count - 1)
852cfecea6eSKees Cook 		return written;
853cfecea6eSKees Cook 
854cfecea6eSKees Cook 	memset(dest + written + 1, 0, count - written - 1);
855cfecea6eSKees Cook 
856cfecea6eSKees Cook 	return written;
857cfecea6eSKees Cook }
858cfecea6eSKees Cook EXPORT_SYMBOL(strscpy_pad);
859cfecea6eSKees Cook 
860cfecea6eSKees Cook /**
861cfecea6eSKees Cook  * skip_spaces - Removes leading whitespace from @str.
862cfecea6eSKees Cook  * @str: The string to be stripped.
863cfecea6eSKees Cook  *
864cfecea6eSKees Cook  * Returns a pointer to the first non-whitespace character in @str.
865cfecea6eSKees Cook  */
skip_spaces(const char * str)866cfecea6eSKees Cook char *skip_spaces(const char *str)
867cfecea6eSKees Cook {
868cfecea6eSKees Cook 	while (isspace(*str))
869cfecea6eSKees Cook 		++str;
870cfecea6eSKees Cook 	return (char *)str;
871cfecea6eSKees Cook }
872cfecea6eSKees Cook EXPORT_SYMBOL(skip_spaces);
873cfecea6eSKees Cook 
874cfecea6eSKees Cook /**
875cfecea6eSKees Cook  * strim - Removes leading and trailing whitespace from @s.
876cfecea6eSKees Cook  * @s: The string to be stripped.
877cfecea6eSKees Cook  *
878cfecea6eSKees Cook  * Note that the first trailing whitespace is replaced with a %NUL-terminator
879cfecea6eSKees Cook  * in the given string @s. Returns a pointer to the first non-whitespace
880cfecea6eSKees Cook  * character in @s.
881cfecea6eSKees Cook  */
strim(char * s)882cfecea6eSKees Cook char *strim(char *s)
883cfecea6eSKees Cook {
884cfecea6eSKees Cook 	size_t size;
885cfecea6eSKees Cook 	char *end;
886cfecea6eSKees Cook 
887cfecea6eSKees Cook 	size = strlen(s);
888cfecea6eSKees Cook 	if (!size)
889cfecea6eSKees Cook 		return s;
890cfecea6eSKees Cook 
891cfecea6eSKees Cook 	end = s + size - 1;
892cfecea6eSKees Cook 	while (end >= s && isspace(*end))
893cfecea6eSKees Cook 		end--;
894cfecea6eSKees Cook 	*(end + 1) = '\0';
895cfecea6eSKees Cook 
896cfecea6eSKees Cook 	return skip_spaces(s);
897cfecea6eSKees Cook }
898cfecea6eSKees Cook EXPORT_SYMBOL(strim);
899cfecea6eSKees Cook 
900cfecea6eSKees Cook /**
901cfecea6eSKees Cook  * sysfs_streq - return true if strings are equal, modulo trailing newline
902cfecea6eSKees Cook  * @s1: one string
903cfecea6eSKees Cook  * @s2: another string
904cfecea6eSKees Cook  *
905cfecea6eSKees Cook  * This routine returns true iff two strings are equal, treating both
906cfecea6eSKees Cook  * NUL and newline-then-NUL as equivalent string terminations.  It's
907cfecea6eSKees Cook  * geared for use with sysfs input strings, which generally terminate
908cfecea6eSKees Cook  * with newlines but are compared against values without newlines.
909cfecea6eSKees Cook  */
sysfs_streq(const char * s1,const char * s2)910cfecea6eSKees Cook bool sysfs_streq(const char *s1, const char *s2)
911cfecea6eSKees Cook {
912cfecea6eSKees Cook 	while (*s1 && *s1 == *s2) {
913cfecea6eSKees Cook 		s1++;
914cfecea6eSKees Cook 		s2++;
915cfecea6eSKees Cook 	}
916cfecea6eSKees Cook 
917cfecea6eSKees Cook 	if (*s1 == *s2)
918cfecea6eSKees Cook 		return true;
919cfecea6eSKees Cook 	if (!*s1 && *s2 == '\n' && !s2[1])
920cfecea6eSKees Cook 		return true;
921cfecea6eSKees Cook 	if (*s1 == '\n' && !s1[1] && !*s2)
922cfecea6eSKees Cook 		return true;
923cfecea6eSKees Cook 	return false;
924cfecea6eSKees Cook }
925cfecea6eSKees Cook EXPORT_SYMBOL(sysfs_streq);
926cfecea6eSKees Cook 
927cfecea6eSKees Cook /**
928cfecea6eSKees Cook  * match_string - matches given string in an array
929cfecea6eSKees Cook  * @array:	array of strings
930cfecea6eSKees Cook  * @n:		number of strings in the array or -1 for NULL terminated arrays
931cfecea6eSKees Cook  * @string:	string to match with
932cfecea6eSKees Cook  *
933cfecea6eSKees Cook  * This routine will look for a string in an array of strings up to the
934cfecea6eSKees Cook  * n-th element in the array or until the first NULL element.
935cfecea6eSKees Cook  *
936cfecea6eSKees Cook  * Historically the value of -1 for @n, was used to search in arrays that
937cfecea6eSKees Cook  * are NULL terminated. However, the function does not make a distinction
938cfecea6eSKees Cook  * when finishing the search: either @n elements have been compared OR
939cfecea6eSKees Cook  * the first NULL element was found.
940cfecea6eSKees Cook  *
941cfecea6eSKees Cook  * Return:
942cfecea6eSKees Cook  * index of a @string in the @array if matches, or %-EINVAL otherwise.
943cfecea6eSKees Cook  */
match_string(const char * const * array,size_t n,const char * string)944cfecea6eSKees Cook int match_string(const char * const *array, size_t n, const char *string)
945cfecea6eSKees Cook {
946cfecea6eSKees Cook 	int index;
947cfecea6eSKees Cook 	const char *item;
948cfecea6eSKees Cook 
949cfecea6eSKees Cook 	for (index = 0; index < n; index++) {
950cfecea6eSKees Cook 		item = array[index];
951cfecea6eSKees Cook 		if (!item)
952cfecea6eSKees Cook 			break;
953cfecea6eSKees Cook 		if (!strcmp(item, string))
954cfecea6eSKees Cook 			return index;
955cfecea6eSKees Cook 	}
956cfecea6eSKees Cook 
957cfecea6eSKees Cook 	return -EINVAL;
958cfecea6eSKees Cook }
959cfecea6eSKees Cook EXPORT_SYMBOL(match_string);
960cfecea6eSKees Cook 
961cfecea6eSKees Cook /**
962cfecea6eSKees Cook  * __sysfs_match_string - matches given string in an array
963cfecea6eSKees Cook  * @array: array of strings
964cfecea6eSKees Cook  * @n: number of strings in the array or -1 for NULL terminated arrays
965cfecea6eSKees Cook  * @str: string to match with
966cfecea6eSKees Cook  *
967cfecea6eSKees Cook  * Returns index of @str in the @array or -EINVAL, just like match_string().
968cfecea6eSKees Cook  * Uses sysfs_streq instead of strcmp for matching.
969cfecea6eSKees Cook  *
970cfecea6eSKees Cook  * This routine will look for a string in an array of strings up to the
971cfecea6eSKees Cook  * n-th element in the array or until the first NULL element.
972cfecea6eSKees Cook  *
973cfecea6eSKees Cook  * Historically the value of -1 for @n, was used to search in arrays that
974cfecea6eSKees Cook  * are NULL terminated. However, the function does not make a distinction
975cfecea6eSKees Cook  * when finishing the search: either @n elements have been compared OR
976cfecea6eSKees Cook  * the first NULL element was found.
977cfecea6eSKees Cook  */
__sysfs_match_string(const char * const * array,size_t n,const char * str)978cfecea6eSKees Cook int __sysfs_match_string(const char * const *array, size_t n, const char *str)
979cfecea6eSKees Cook {
980cfecea6eSKees Cook 	const char *item;
981cfecea6eSKees Cook 	int index;
982cfecea6eSKees Cook 
983cfecea6eSKees Cook 	for (index = 0; index < n; index++) {
984cfecea6eSKees Cook 		item = array[index];
985cfecea6eSKees Cook 		if (!item)
986cfecea6eSKees Cook 			break;
987cfecea6eSKees Cook 		if (sysfs_streq(item, str))
988cfecea6eSKees Cook 			return index;
989cfecea6eSKees Cook 	}
990cfecea6eSKees Cook 
991cfecea6eSKees Cook 	return -EINVAL;
992cfecea6eSKees Cook }
993cfecea6eSKees Cook EXPORT_SYMBOL(__sysfs_match_string);
994cfecea6eSKees Cook 
995cfecea6eSKees Cook /**
996cfecea6eSKees Cook  * strreplace - Replace all occurrences of character in string.
997d01a77afSAndy Shevchenko  * @str: The string to operate on.
998cfecea6eSKees Cook  * @old: The character being replaced.
999cfecea6eSKees Cook  * @new: The character @old is replaced with.
1000cfecea6eSKees Cook  *
1001d01a77afSAndy Shevchenko  * Replaces the each @old character with a @new one in the given string @str.
1002d01a77afSAndy Shevchenko  *
1003d01a77afSAndy Shevchenko  * Return: pointer to the string @str itself.
1004cfecea6eSKees Cook  */
strreplace(char * str,char old,char new)1005d01a77afSAndy Shevchenko char *strreplace(char *str, char old, char new)
1006cfecea6eSKees Cook {
1007d01a77afSAndy Shevchenko 	char *s = str;
1008d01a77afSAndy Shevchenko 
1009cfecea6eSKees Cook 	for (; *s; ++s)
1010cfecea6eSKees Cook 		if (*s == old)
1011cfecea6eSKees Cook 			*s = new;
1012d01a77afSAndy Shevchenko 	return str;
1013cfecea6eSKees Cook }
1014cfecea6eSKees Cook EXPORT_SYMBOL(strreplace);
1015cfecea6eSKees Cook 
10165c4e0a21SGuenter Roeck /**
10175c4e0a21SGuenter Roeck  * memcpy_and_pad - Copy one buffer to another with padding
10185c4e0a21SGuenter Roeck  * @dest: Where to copy to
10195c4e0a21SGuenter Roeck  * @dest_len: The destination buffer size
10205c4e0a21SGuenter Roeck  * @src: Where to copy from
10215c4e0a21SGuenter Roeck  * @count: The number of bytes to copy
10225c4e0a21SGuenter Roeck  * @pad: Character to use for padding if space is left in destination.
10235c4e0a21SGuenter Roeck  */
memcpy_and_pad(void * dest,size_t dest_len,const void * src,size_t count,int pad)10245c4e0a21SGuenter Roeck void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count,
10255c4e0a21SGuenter Roeck 		    int pad)
10265c4e0a21SGuenter Roeck {
10275c4e0a21SGuenter Roeck 	if (dest_len > count) {
10285c4e0a21SGuenter Roeck 		memcpy(dest, src, count);
10295c4e0a21SGuenter Roeck 		memset(dest + count, pad,  dest_len - count);
10305c4e0a21SGuenter Roeck 	} else {
10315c4e0a21SGuenter Roeck 		memcpy(dest, src, dest_len);
10325c4e0a21SGuenter Roeck 	}
10335c4e0a21SGuenter Roeck }
10345c4e0a21SGuenter Roeck EXPORT_SYMBOL(memcpy_and_pad);
10355c4e0a21SGuenter Roeck 
1036c430f600SKees Cook #ifdef CONFIG_FORTIFY_SOURCE
1037f68f2ff9SKees Cook /* These are placeholders for fortify compile-time warnings. */
__read_overflow2_field(size_t avail,size_t wanted)1038f68f2ff9SKees Cook void __read_overflow2_field(size_t avail, size_t wanted) { }
1039f68f2ff9SKees Cook EXPORT_SYMBOL(__read_overflow2_field);
__write_overflow_field(size_t avail,size_t wanted)1040f68f2ff9SKees Cook void __write_overflow_field(size_t avail, size_t wanted) { }
1041f68f2ff9SKees Cook EXPORT_SYMBOL(__write_overflow_field);
1042f68f2ff9SKees Cook 
fortify_panic(const char * name)1043cfecea6eSKees Cook void fortify_panic(const char *name)
1044cfecea6eSKees Cook {
1045cfecea6eSKees Cook 	pr_emerg("detected buffer overflow in %s\n", name);
1046cfecea6eSKees Cook 	BUG();
1047cfecea6eSKees Cook }
1048cfecea6eSKees Cook EXPORT_SYMBOL(fortify_panic);
1049c430f600SKees Cook #endif /* CONFIG_FORTIFY_SOURCE */
1050