string_helpers.c 25 KB

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