string_helpers.c 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Helpers for formatting and printing strings
  4. *
  5. * Copyright 31 August 2008 James Bottomley
  6. * Copyright (C) 2013, Intel Corporation
  7. */
  8. #include <linux/bug.h>
  9. #include <linux/kernel.h>
  10. #include <linux/math64.h>
  11. #include <linux/export.h>
  12. #include <linux/ctype.h>
  13. #include <linux/device.h>
  14. #include <linux/errno.h>
  15. #include <linux/fs.h>
  16. #include <linux/limits.h>
  17. #include <linux/mm.h>
  18. #include <linux/slab.h>
  19. #include <linux/string.h>
  20. #include <linux/string_helpers.h>
  21. /**
  22. * string_get_size - get the size in the specified units
  23. * @size: The size to be converted in blocks
  24. * @blk_size: Size of the block (use 1 for size in bytes)
  25. * @units: units to use (powers of 1000 or 1024)
  26. * @buf: buffer to format to
  27. * @len: length of buffer
  28. *
  29. * This function returns a string formatted to 3 significant figures
  30. * giving the size in the required units. @buf should have room for
  31. * at least 9 bytes and will always be zero terminated.
  32. *
  33. */
  34. void string_get_size(u64 size, u64 blk_size, const enum string_size_units units,
  35. char *buf, int len)
  36. {
  37. static const char *const units_10[] = {
  38. "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
  39. };
  40. static const char *const units_2[] = {
  41. "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"
  42. };
  43. static const char *const *const units_str[] = {
  44. [STRING_UNITS_10] = units_10,
  45. [STRING_UNITS_2] = units_2,
  46. };
  47. static const unsigned int divisor[] = {
  48. [STRING_UNITS_10] = 1000,
  49. [STRING_UNITS_2] = 1024,
  50. };
  51. static const unsigned int rounding[] = { 500, 50, 5 };
  52. int i = 0, j;
  53. u32 remainder = 0, sf_cap;
  54. char tmp[8];
  55. const char *unit;
  56. tmp[0] = '\0';
  57. if (blk_size == 0)
  58. size = 0;
  59. if (size == 0)
  60. goto out;
  61. /* This is Napier's algorithm. Reduce the original block size to
  62. *
  63. * coefficient * divisor[units]^i
  64. *
  65. * we do the reduction so both coefficients are just under 32 bits so
  66. * that multiplying them together won't overflow 64 bits and we keep
  67. * as much precision as possible in the numbers.
  68. *
  69. * Note: it's safe to throw away the remainders here because all the
  70. * precision is in the coefficients.
  71. */
  72. while (blk_size >> 32) {
  73. do_div(blk_size, divisor[units]);
  74. i++;
  75. }
  76. while (size >> 32) {
  77. do_div(size, divisor[units]);
  78. i++;
  79. }
  80. /* now perform the actual multiplication keeping i as the sum of the
  81. * two logarithms */
  82. size *= blk_size;
  83. /* and logarithmically reduce it until it's just under the divisor */
  84. while (size >= divisor[units]) {
  85. remainder = do_div(size, divisor[units]);
  86. i++;
  87. }
  88. /* work out in j how many digits of precision we need from the
  89. * remainder */
  90. sf_cap = size;
  91. for (j = 0; sf_cap*10 < 1000; j++)
  92. sf_cap *= 10;
  93. if (units == STRING_UNITS_2) {
  94. /* express the remainder as a decimal. It's currently the
  95. * numerator of a fraction whose denominator is
  96. * divisor[units], which is 1 << 10 for STRING_UNITS_2 */
  97. remainder *= 1000;
  98. remainder >>= 10;
  99. }
  100. /* add a 5 to the digit below what will be printed to ensure
  101. * an arithmetical round up and carry it through to size */
  102. remainder += rounding[j];
  103. if (remainder >= 1000) {
  104. remainder -= 1000;
  105. size += 1;
  106. }
  107. if (j) {
  108. snprintf(tmp, sizeof(tmp), ".%03u", remainder);
  109. tmp[j+1] = '\0';
  110. }
  111. out:
  112. if (i >= ARRAY_SIZE(units_2))
  113. unit = "UNK";
  114. else
  115. unit = units_str[units][i];
  116. snprintf(buf, len, "%u%s %s", (u32)size,
  117. tmp, unit);
  118. }
  119. EXPORT_SYMBOL(string_get_size);
  120. /**
  121. * parse_int_array_user - Split string into a sequence of integers
  122. * @from: The user space buffer to read from
  123. * @count: The maximum number of bytes to read
  124. * @array: Returned pointer to sequence of integers
  125. *
  126. * On success @array is allocated and initialized with a sequence of
  127. * integers extracted from the @from plus an additional element that
  128. * begins the sequence and specifies the integers count.
  129. *
  130. * Caller takes responsibility for freeing @array when it is no longer
  131. * needed.
  132. */
  133. int parse_int_array_user(const char __user *from, size_t count, int **array)
  134. {
  135. int *ints, nints;
  136. char *buf;
  137. int ret = 0;
  138. buf = memdup_user_nul(from, count);
  139. if (IS_ERR(buf))
  140. return PTR_ERR(buf);
  141. get_options(buf, 0, &nints);
  142. if (!nints) {
  143. ret = -ENOENT;
  144. goto free_buf;
  145. }
  146. ints = kcalloc(nints + 1, sizeof(*ints), GFP_KERNEL);
  147. if (!ints) {
  148. ret = -ENOMEM;
  149. goto free_buf;
  150. }
  151. get_options(buf, nints + 1, ints);
  152. *array = ints;
  153. free_buf:
  154. kfree(buf);
  155. return ret;
  156. }
  157. EXPORT_SYMBOL(parse_int_array_user);
  158. static bool unescape_space(char **src, char **dst)
  159. {
  160. char *p = *dst, *q = *src;
  161. switch (*q) {
  162. case 'n':
  163. *p = '\n';
  164. break;
  165. case 'r':
  166. *p = '\r';
  167. break;
  168. case 't':
  169. *p = '\t';
  170. break;
  171. case 'v':
  172. *p = '\v';
  173. break;
  174. case 'f':
  175. *p = '\f';
  176. break;
  177. default:
  178. return false;
  179. }
  180. *dst += 1;
  181. *src += 1;
  182. return true;
  183. }
  184. static bool unescape_octal(char **src, char **dst)
  185. {
  186. char *p = *dst, *q = *src;
  187. u8 num;
  188. if (isodigit(*q) == 0)
  189. return false;
  190. num = (*q++) & 7;
  191. while (num < 32 && isodigit(*q) && (q - *src < 3)) {
  192. num <<= 3;
  193. num += (*q++) & 7;
  194. }
  195. *p = num;
  196. *dst += 1;
  197. *src = q;
  198. return true;
  199. }
  200. static bool unescape_hex(char **src, char **dst)
  201. {
  202. char *p = *dst, *q = *src;
  203. int digit;
  204. u8 num;
  205. if (*q++ != 'x')
  206. return false;
  207. num = digit = hex_to_bin(*q++);
  208. if (digit < 0)
  209. return false;
  210. digit = hex_to_bin(*q);
  211. if (digit >= 0) {
  212. q++;
  213. num = (num << 4) | digit;
  214. }
  215. *p = num;
  216. *dst += 1;
  217. *src = q;
  218. return true;
  219. }
  220. static bool unescape_special(char **src, char **dst)
  221. {
  222. char *p = *dst, *q = *src;
  223. switch (*q) {
  224. case '\"':
  225. *p = '\"';
  226. break;
  227. case '\\':
  228. *p = '\\';
  229. break;
  230. case 'a':
  231. *p = '\a';
  232. break;
  233. case 'e':
  234. *p = '\e';
  235. break;
  236. default:
  237. return false;
  238. }
  239. *dst += 1;
  240. *src += 1;
  241. return true;
  242. }
  243. /**
  244. * string_unescape - unquote characters in the given string
  245. * @src: source buffer (escaped)
  246. * @dst: destination buffer (unescaped)
  247. * @size: size of the destination buffer (0 to unlimit)
  248. * @flags: combination of the flags.
  249. *
  250. * Description:
  251. * The function unquotes characters in the given string.
  252. *
  253. * Because the size of the output will be the same as or less than the size of
  254. * the input, the transformation may be performed in place.
  255. *
  256. * Caller must provide valid source and destination pointers. Be aware that
  257. * destination buffer will always be NULL-terminated. Source string must be
  258. * NULL-terminated as well. The supported flags are::
  259. *
  260. * UNESCAPE_SPACE:
  261. * '\f' - form feed
  262. * '\n' - new line
  263. * '\r' - carriage return
  264. * '\t' - horizontal tab
  265. * '\v' - vertical tab
  266. * UNESCAPE_OCTAL:
  267. * '\NNN' - byte with octal value NNN (1 to 3 digits)
  268. * UNESCAPE_HEX:
  269. * '\xHH' - byte with hexadecimal value HH (1 to 2 digits)
  270. * UNESCAPE_SPECIAL:
  271. * '\"' - double quote
  272. * '\\' - backslash
  273. * '\a' - alert (BEL)
  274. * '\e' - escape
  275. * UNESCAPE_ANY:
  276. * all previous together
  277. *
  278. * Return:
  279. * The amount of the characters processed to the destination buffer excluding
  280. * trailing '\0' is returned.
  281. */
  282. int string_unescape(char *src, char *dst, size_t size, unsigned int flags)
  283. {
  284. char *out = dst;
  285. while (*src && --size) {
  286. if (src[0] == '\\' && src[1] != '\0' && size > 1) {
  287. src++;
  288. size--;
  289. if (flags & UNESCAPE_SPACE &&
  290. unescape_space(&src, &out))
  291. continue;
  292. if (flags & UNESCAPE_OCTAL &&
  293. unescape_octal(&src, &out))
  294. continue;
  295. if (flags & UNESCAPE_HEX &&
  296. unescape_hex(&src, &out))
  297. continue;
  298. if (flags & UNESCAPE_SPECIAL &&
  299. unescape_special(&src, &out))
  300. continue;
  301. *out++ = '\\';
  302. }
  303. *out++ = *src++;
  304. }
  305. *out = '\0';
  306. return out - dst;
  307. }
  308. EXPORT_SYMBOL(string_unescape);
  309. static bool escape_passthrough(unsigned char c, char **dst, char *end)
  310. {
  311. char *out = *dst;
  312. if (out < end)
  313. *out = c;
  314. *dst = out + 1;
  315. return true;
  316. }
  317. static bool escape_space(unsigned char c, char **dst, char *end)
  318. {
  319. char *out = *dst;
  320. unsigned char to;
  321. switch (c) {
  322. case '\n':
  323. to = 'n';
  324. break;
  325. case '\r':
  326. to = 'r';
  327. break;
  328. case '\t':
  329. to = 't';
  330. break;
  331. case '\v':
  332. to = 'v';
  333. break;
  334. case '\f':
  335. to = 'f';
  336. break;
  337. default:
  338. return false;
  339. }
  340. if (out < end)
  341. *out = '\\';
  342. ++out;
  343. if (out < end)
  344. *out = to;
  345. ++out;
  346. *dst = out;
  347. return true;
  348. }
  349. static bool escape_special(unsigned char c, char **dst, char *end)
  350. {
  351. char *out = *dst;
  352. unsigned char to;
  353. switch (c) {
  354. case '\\':
  355. to = '\\';
  356. break;
  357. case '\a':
  358. to = 'a';
  359. break;
  360. case '\e':
  361. to = 'e';
  362. break;
  363. case '"':
  364. to = '"';
  365. break;
  366. default:
  367. return false;
  368. }
  369. if (out < end)
  370. *out = '\\';
  371. ++out;
  372. if (out < end)
  373. *out = to;
  374. ++out;
  375. *dst = out;
  376. return true;
  377. }
  378. static bool escape_null(unsigned char c, char **dst, char *end)
  379. {
  380. char *out = *dst;
  381. if (c)
  382. return false;
  383. if (out < end)
  384. *out = '\\';
  385. ++out;
  386. if (out < end)
  387. *out = '0';
  388. ++out;
  389. *dst = out;
  390. return true;
  391. }
  392. static bool escape_octal(unsigned char c, char **dst, char *end)
  393. {
  394. char *out = *dst;
  395. if (out < end)
  396. *out = '\\';
  397. ++out;
  398. if (out < end)
  399. *out = ((c >> 6) & 0x07) + '0';
  400. ++out;
  401. if (out < end)
  402. *out = ((c >> 3) & 0x07) + '0';
  403. ++out;
  404. if (out < end)
  405. *out = ((c >> 0) & 0x07) + '0';
  406. ++out;
  407. *dst = out;
  408. return true;
  409. }
  410. static bool escape_hex(unsigned char c, char **dst, char *end)
  411. {
  412. char *out = *dst;
  413. if (out < end)
  414. *out = '\\';
  415. ++out;
  416. if (out < end)
  417. *out = 'x';
  418. ++out;
  419. if (out < end)
  420. *out = hex_asc_hi(c);
  421. ++out;
  422. if (out < end)
  423. *out = hex_asc_lo(c);
  424. ++out;
  425. *dst = out;
  426. return true;
  427. }
  428. /**
  429. * string_escape_mem - quote characters in the given memory buffer
  430. * @src: source buffer (unescaped)
  431. * @isz: source buffer size
  432. * @dst: destination buffer (escaped)
  433. * @osz: destination buffer size
  434. * @flags: combination of the flags
  435. * @only: NULL-terminated string containing characters used to limit
  436. * the selected escape class. If characters are included in @only
  437. * that would not normally be escaped by the classes selected
  438. * in @flags, they will be copied to @dst unescaped.
  439. *
  440. * Description:
  441. * The process of escaping byte buffer includes several parts. They are applied
  442. * in the following sequence.
  443. *
  444. * 1. The character is not matched to the one from @only string and thus
  445. * must go as-is to the output.
  446. * 2. The character is matched to the printable and ASCII classes, if asked,
  447. * and in case of match it passes through to the output.
  448. * 3. The character is matched to the printable or ASCII class, if asked,
  449. * and in case of match it passes through to the output.
  450. * 4. The character is checked if it falls into the class given by @flags.
  451. * %ESCAPE_OCTAL and %ESCAPE_HEX are going last since they cover any
  452. * character. Note that they actually can't go together, otherwise
  453. * %ESCAPE_HEX will be ignored.
  454. *
  455. * Caller must provide valid source and destination pointers. Be aware that
  456. * destination buffer will not be NULL-terminated, thus caller have to append
  457. * it if needs. The supported flags are::
  458. *
  459. * %ESCAPE_SPACE: (special white space, not space itself)
  460. * '\f' - form feed
  461. * '\n' - new line
  462. * '\r' - carriage return
  463. * '\t' - horizontal tab
  464. * '\v' - vertical tab
  465. * %ESCAPE_SPECIAL:
  466. * '\"' - double quote
  467. * '\\' - backslash
  468. * '\a' - alert (BEL)
  469. * '\e' - escape
  470. * %ESCAPE_NULL:
  471. * '\0' - null
  472. * %ESCAPE_OCTAL:
  473. * '\NNN' - byte with octal value NNN (3 digits)
  474. * %ESCAPE_ANY:
  475. * all previous together
  476. * %ESCAPE_NP:
  477. * escape only non-printable characters, checked by isprint()
  478. * %ESCAPE_ANY_NP:
  479. * all previous together
  480. * %ESCAPE_HEX:
  481. * '\xHH' - byte with hexadecimal value HH (2 digits)
  482. * %ESCAPE_NA:
  483. * escape only non-ascii characters, checked by isascii()
  484. * %ESCAPE_NAP:
  485. * escape only non-printable or non-ascii characters
  486. * %ESCAPE_APPEND:
  487. * append characters from @only to be escaped by the given classes
  488. *
  489. * %ESCAPE_APPEND would help to pass additional characters to the escaped, when
  490. * one of %ESCAPE_NP, %ESCAPE_NA, or %ESCAPE_NAP is provided.
  491. *
  492. * One notable caveat, the %ESCAPE_NAP, %ESCAPE_NP and %ESCAPE_NA have the
  493. * higher priority than the rest of the flags (%ESCAPE_NAP is the highest).
  494. * It doesn't make much sense to use either of them without %ESCAPE_OCTAL
  495. * or %ESCAPE_HEX, because they cover most of the other character classes.
  496. * %ESCAPE_NAP can utilize %ESCAPE_SPACE or %ESCAPE_SPECIAL in addition to
  497. * the above.
  498. *
  499. * Return:
  500. * The total size of the escaped output that would be generated for
  501. * the given input and flags. To check whether the output was
  502. * truncated, compare the return value to osz. There is room left in
  503. * dst for a '\0' terminator if and only if ret < osz.
  504. */
  505. int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
  506. unsigned int flags, const char *only)
  507. {
  508. char *p = dst;
  509. char *end = p + osz;
  510. bool is_dict = only && *only;
  511. bool is_append = flags & ESCAPE_APPEND;
  512. while (isz--) {
  513. unsigned char c = *src++;
  514. bool in_dict = is_dict && strchr(only, c);
  515. /*
  516. * Apply rules in the following sequence:
  517. * - the @only string is supplied and does not contain a
  518. * character under question
  519. * - the character is printable and ASCII, when @flags has
  520. * %ESCAPE_NAP bit set
  521. * - the character is printable, when @flags has
  522. * %ESCAPE_NP bit set
  523. * - the character is ASCII, when @flags has
  524. * %ESCAPE_NA bit set
  525. * - the character doesn't fall into a class of symbols
  526. * defined by given @flags
  527. * In these cases we just pass through a character to the
  528. * output buffer.
  529. *
  530. * When %ESCAPE_APPEND is passed, the characters from @only
  531. * have been excluded from the %ESCAPE_NAP, %ESCAPE_NP, and
  532. * %ESCAPE_NA cases.
  533. */
  534. if (!(is_append || in_dict) && is_dict &&
  535. escape_passthrough(c, &p, end))
  536. continue;
  537. if (!(is_append && in_dict) && isascii(c) && isprint(c) &&
  538. flags & ESCAPE_NAP && escape_passthrough(c, &p, end))
  539. continue;
  540. if (!(is_append && in_dict) && isprint(c) &&
  541. flags & ESCAPE_NP && escape_passthrough(c, &p, end))
  542. continue;
  543. if (!(is_append && in_dict) && isascii(c) &&
  544. flags & ESCAPE_NA && escape_passthrough(c, &p, end))
  545. continue;
  546. if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
  547. continue;
  548. if (flags & ESCAPE_SPECIAL && escape_special(c, &p, end))
  549. continue;
  550. if (flags & ESCAPE_NULL && escape_null(c, &p, end))
  551. continue;
  552. /* ESCAPE_OCTAL and ESCAPE_HEX always go last */
  553. if (flags & ESCAPE_OCTAL && escape_octal(c, &p, end))
  554. continue;
  555. if (flags & ESCAPE_HEX && escape_hex(c, &p, end))
  556. continue;
  557. escape_passthrough(c, &p, end);
  558. }
  559. return p - dst;
  560. }
  561. EXPORT_SYMBOL(string_escape_mem);
  562. /*
  563. * Return an allocated string that has been escaped of special characters
  564. * and double quotes, making it safe to log in quotes.
  565. */
  566. char *kstrdup_quotable(const char *src, gfp_t gfp)
  567. {
  568. size_t slen, dlen;
  569. char *dst;
  570. const int flags = ESCAPE_HEX;
  571. const char esc[] = "\f\n\r\t\v\a\e\\\"";
  572. if (!src)
  573. return NULL;
  574. slen = strlen(src);
  575. dlen = string_escape_mem(src, slen, NULL, 0, flags, esc);
  576. dst = kmalloc(dlen + 1, gfp);
  577. if (!dst)
  578. return NULL;
  579. WARN_ON(string_escape_mem(src, slen, dst, dlen, flags, esc) != dlen);
  580. dst[dlen] = '\0';
  581. return dst;
  582. }
  583. EXPORT_SYMBOL_GPL(kstrdup_quotable);
  584. /*
  585. * Returns allocated NULL-terminated string containing process
  586. * command line, with inter-argument NULLs replaced with spaces,
  587. * and other special characters escaped.
  588. */
  589. char *kstrdup_quotable_cmdline(struct task_struct *task, gfp_t gfp)
  590. {
  591. char *buffer, *quoted;
  592. int i, res;
  593. buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
  594. if (!buffer)
  595. return NULL;
  596. res = get_cmdline(task, buffer, PAGE_SIZE - 1);
  597. buffer[res] = '\0';
  598. /* Collapse trailing NULLs, leave res pointing to last non-NULL. */
  599. while (--res >= 0 && buffer[res] == '\0')
  600. ;
  601. /* Replace inter-argument NULLs. */
  602. for (i = 0; i <= res; i++)
  603. if (buffer[i] == '\0')
  604. buffer[i] = ' ';
  605. /* Make sure result is printable. */
  606. quoted = kstrdup_quotable(buffer, gfp);
  607. kfree(buffer);
  608. return quoted;
  609. }
  610. EXPORT_SYMBOL_GPL(kstrdup_quotable_cmdline);
  611. /*
  612. * Returns allocated NULL-terminated string containing pathname,
  613. * with special characters escaped, able to be safely logged. If
  614. * there is an error, the leading character will be "<".
  615. */
  616. char *kstrdup_quotable_file(struct file *file, gfp_t gfp)
  617. {
  618. char *temp, *pathname;
  619. if (!file)
  620. return kstrdup("<unknown>", gfp);
  621. /* We add 11 spaces for ' (deleted)' to be appended */
  622. temp = kmalloc(PATH_MAX + 11, GFP_KERNEL);
  623. if (!temp)
  624. return kstrdup("<no_memory>", gfp);
  625. pathname = file_path(file, temp, PATH_MAX + 11);
  626. if (IS_ERR(pathname))
  627. pathname = kstrdup("<too_long>", gfp);
  628. else
  629. pathname = kstrdup_quotable(pathname, gfp);
  630. kfree(temp);
  631. return pathname;
  632. }
  633. EXPORT_SYMBOL_GPL(kstrdup_quotable_file);
  634. /**
  635. * kasprintf_strarray - allocate and fill array of sequential strings
  636. * @gfp: flags for the slab allocator
  637. * @prefix: prefix to be used
  638. * @n: amount of lines to be allocated and filled
  639. *
  640. * Allocates and fills @n strings using pattern "%s-%zu", where prefix
  641. * is provided by caller. The caller is responsible to free them with
  642. * kfree_strarray() after use.
  643. *
  644. * Returns array of strings or NULL when memory can't be allocated.
  645. */
  646. char **kasprintf_strarray(gfp_t gfp, const char *prefix, size_t n)
  647. {
  648. char **names;
  649. size_t i;
  650. names = kcalloc(n + 1, sizeof(char *), gfp);
  651. if (!names)
  652. return NULL;
  653. for (i = 0; i < n; i++) {
  654. names[i] = kasprintf(gfp, "%s-%zu", prefix, i);
  655. if (!names[i]) {
  656. kfree_strarray(names, i);
  657. return NULL;
  658. }
  659. }
  660. return names;
  661. }
  662. EXPORT_SYMBOL_GPL(kasprintf_strarray);
  663. /**
  664. * kfree_strarray - free a number of dynamically allocated strings contained
  665. * in an array and the array itself
  666. *
  667. * @array: Dynamically allocated array of strings to free.
  668. * @n: Number of strings (starting from the beginning of the array) to free.
  669. *
  670. * Passing a non-NULL @array and @n == 0 as well as NULL @array are valid
  671. * use-cases. If @array is NULL, the function does nothing.
  672. */
  673. void kfree_strarray(char **array, size_t n)
  674. {
  675. unsigned int i;
  676. if (!array)
  677. return;
  678. for (i = 0; i < n; i++)
  679. kfree(array[i]);
  680. kfree(array);
  681. }
  682. EXPORT_SYMBOL_GPL(kfree_strarray);
  683. struct strarray {
  684. char **array;
  685. size_t n;
  686. };
  687. static void devm_kfree_strarray(struct device *dev, void *res)
  688. {
  689. struct strarray *array = res;
  690. kfree_strarray(array->array, array->n);
  691. }
  692. char **devm_kasprintf_strarray(struct device *dev, const char *prefix, size_t n)
  693. {
  694. struct strarray *ptr;
  695. ptr = devres_alloc(devm_kfree_strarray, sizeof(*ptr), GFP_KERNEL);
  696. if (!ptr)
  697. return ERR_PTR(-ENOMEM);
  698. ptr->array = kasprintf_strarray(GFP_KERNEL, prefix, n);
  699. if (!ptr->array) {
  700. devres_free(ptr);
  701. return ERR_PTR(-ENOMEM);
  702. }
  703. ptr->n = n;
  704. devres_add(dev, ptr);
  705. return ptr->array;
  706. }
  707. EXPORT_SYMBOL_GPL(devm_kasprintf_strarray);
  708. /**
  709. * strscpy_pad() - Copy a C-string into a sized buffer
  710. * @dest: Where to copy the string to
  711. * @src: Where to copy the string from
  712. * @count: Size of destination buffer
  713. *
  714. * Copy the string, or as much of it as fits, into the dest buffer. The
  715. * behavior is undefined if the string buffers overlap. The destination
  716. * buffer is always %NUL terminated, unless it's zero-sized.
  717. *
  718. * If the source string is shorter than the destination buffer, zeros
  719. * the tail of the destination buffer.
  720. *
  721. * For full explanation of why you may want to consider using the
  722. * 'strscpy' functions please see the function docstring for strscpy().
  723. *
  724. * Returns:
  725. * * The number of characters copied (not including the trailing %NUL)
  726. * * -E2BIG if count is 0 or @src was truncated.
  727. */
  728. ssize_t strscpy_pad(char *dest, const char *src, size_t count)
  729. {
  730. ssize_t written;
  731. written = strscpy(dest, src, count);
  732. if (written < 0 || written == count - 1)
  733. return written;
  734. memset(dest + written + 1, 0, count - written - 1);
  735. return written;
  736. }
  737. EXPORT_SYMBOL(strscpy_pad);
  738. /**
  739. * skip_spaces - Removes leading whitespace from @str.
  740. * @str: The string to be stripped.
  741. *
  742. * Returns a pointer to the first non-whitespace character in @str.
  743. */
  744. char *skip_spaces(const char *str)
  745. {
  746. while (isspace(*str))
  747. ++str;
  748. return (char *)str;
  749. }
  750. EXPORT_SYMBOL(skip_spaces);
  751. /**
  752. * strim - Removes leading and trailing whitespace from @s.
  753. * @s: The string to be stripped.
  754. *
  755. * Note that the first trailing whitespace is replaced with a %NUL-terminator
  756. * in the given string @s. Returns a pointer to the first non-whitespace
  757. * character in @s.
  758. */
  759. char *strim(char *s)
  760. {
  761. size_t size;
  762. char *end;
  763. size = strlen(s);
  764. if (!size)
  765. return s;
  766. end = s + size - 1;
  767. while (end >= s && isspace(*end))
  768. end--;
  769. *(end + 1) = '\0';
  770. return skip_spaces(s);
  771. }
  772. EXPORT_SYMBOL(strim);
  773. /**
  774. * sysfs_streq - return true if strings are equal, modulo trailing newline
  775. * @s1: one string
  776. * @s2: another string
  777. *
  778. * This routine returns true iff two strings are equal, treating both
  779. * NUL and newline-then-NUL as equivalent string terminations. It's
  780. * geared for use with sysfs input strings, which generally terminate
  781. * with newlines but are compared against values without newlines.
  782. */
  783. bool sysfs_streq(const char *s1, const char *s2)
  784. {
  785. while (*s1 && *s1 == *s2) {
  786. s1++;
  787. s2++;
  788. }
  789. if (*s1 == *s2)
  790. return true;
  791. if (!*s1 && *s2 == '\n' && !s2[1])
  792. return true;
  793. if (*s1 == '\n' && !s1[1] && !*s2)
  794. return true;
  795. return false;
  796. }
  797. EXPORT_SYMBOL(sysfs_streq);
  798. /**
  799. * match_string - matches given string in an array
  800. * @array: array of strings
  801. * @n: number of strings in the array or -1 for NULL terminated arrays
  802. * @string: string to match with
  803. *
  804. * This routine will look for a string in an array of strings up to the
  805. * n-th element in the array or until the first NULL element.
  806. *
  807. * Historically the value of -1 for @n, was used to search in arrays that
  808. * are NULL terminated. However, the function does not make a distinction
  809. * when finishing the search: either @n elements have been compared OR
  810. * the first NULL element was found.
  811. *
  812. * Return:
  813. * index of a @string in the @array if matches, or %-EINVAL otherwise.
  814. */
  815. int match_string(const char * const *array, size_t n, const char *string)
  816. {
  817. int index;
  818. const char *item;
  819. for (index = 0; index < n; index++) {
  820. item = array[index];
  821. if (!item)
  822. break;
  823. if (!strcmp(item, string))
  824. return index;
  825. }
  826. return -EINVAL;
  827. }
  828. EXPORT_SYMBOL(match_string);
  829. /**
  830. * __sysfs_match_string - matches given string in an array
  831. * @array: array of strings
  832. * @n: number of strings in the array or -1 for NULL terminated arrays
  833. * @str: string to match with
  834. *
  835. * Returns index of @str in the @array or -EINVAL, just like match_string().
  836. * Uses sysfs_streq instead of strcmp for matching.
  837. *
  838. * This routine will look for a string in an array of strings up to the
  839. * n-th element in the array or until the first NULL element.
  840. *
  841. * Historically the value of -1 for @n, was used to search in arrays that
  842. * are NULL terminated. However, the function does not make a distinction
  843. * when finishing the search: either @n elements have been compared OR
  844. * the first NULL element was found.
  845. */
  846. int __sysfs_match_string(const char * const *array, size_t n, const char *str)
  847. {
  848. const char *item;
  849. int index;
  850. for (index = 0; index < n; index++) {
  851. item = array[index];
  852. if (!item)
  853. break;
  854. if (sysfs_streq(item, str))
  855. return index;
  856. }
  857. return -EINVAL;
  858. }
  859. EXPORT_SYMBOL(__sysfs_match_string);
  860. /**
  861. * strreplace - Replace all occurrences of character in string.
  862. * @s: The string to operate on.
  863. * @old: The character being replaced.
  864. * @new: The character @old is replaced with.
  865. *
  866. * Returns pointer to the nul byte at the end of @s.
  867. */
  868. char *strreplace(char *s, char old, char new)
  869. {
  870. for (; *s; ++s)
  871. if (*s == old)
  872. *s = new;
  873. return s;
  874. }
  875. EXPORT_SYMBOL(strreplace);
  876. /**
  877. * memcpy_and_pad - Copy one buffer to another with padding
  878. * @dest: Where to copy to
  879. * @dest_len: The destination buffer size
  880. * @src: Where to copy from
  881. * @count: The number of bytes to copy
  882. * @pad: Character to use for padding if space is left in destination.
  883. */
  884. void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count,
  885. int pad)
  886. {
  887. if (dest_len > count) {
  888. memcpy(dest, src, count);
  889. memset(dest + count, pad, dest_len - count);
  890. } else {
  891. memcpy(dest, src, dest_len);
  892. }
  893. }
  894. EXPORT_SYMBOL(memcpy_and_pad);
  895. #ifdef CONFIG_FORTIFY_SOURCE
  896. /* These are placeholders for fortify compile-time warnings. */
  897. void __read_overflow2_field(size_t avail, size_t wanted) { }
  898. EXPORT_SYMBOL(__read_overflow2_field);
  899. void __write_overflow_field(size_t avail, size_t wanted) { }
  900. EXPORT_SYMBOL(__write_overflow_field);
  901. void fortify_panic(const char *name)
  902. {
  903. pr_emerg("detected buffer overflow in %s\n", name);
  904. BUG();
  905. }
  906. EXPORT_SYMBOL(fortify_panic);
  907. #endif /* CONFIG_FORTIFY_SOURCE */