string_helpers.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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/errno.h>
  14. #include <linux/fs.h>
  15. #include <linux/limits.h>
  16. #include <linux/mm.h>
  17. #include <linux/slab.h>
  18. #include <linux/string.h>
  19. #include <linux/string_helpers.h>
  20. /**
  21. * string_get_size - get the size in the specified units
  22. * @size: The size to be converted in blocks
  23. * @blk_size: Size of the block (use 1 for size in bytes)
  24. * @units: units to use (powers of 1000 or 1024)
  25. * @buf: buffer to format to
  26. * @len: length of buffer
  27. *
  28. * This function returns a string formatted to 3 significant figures
  29. * giving the size in the required units. @buf should have room for
  30. * at least 9 bytes and will always be zero terminated.
  31. *
  32. */
  33. void string_get_size(u64 size, u64 blk_size, const enum string_size_units units,
  34. char *buf, int len)
  35. {
  36. static const char *const units_10[] = {
  37. "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
  38. };
  39. static const char *const units_2[] = {
  40. "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"
  41. };
  42. static const char *const *const units_str[] = {
  43. [STRING_UNITS_10] = units_10,
  44. [STRING_UNITS_2] = units_2,
  45. };
  46. static const unsigned int divisor[] = {
  47. [STRING_UNITS_10] = 1000,
  48. [STRING_UNITS_2] = 1024,
  49. };
  50. static const unsigned int rounding[] = { 500, 50, 5 };
  51. int i = 0, j;
  52. u32 remainder = 0, sf_cap;
  53. char tmp[8];
  54. const char *unit;
  55. tmp[0] = '\0';
  56. if (blk_size == 0)
  57. size = 0;
  58. if (size == 0)
  59. goto out;
  60. /* This is Napier's algorithm. Reduce the original block size to
  61. *
  62. * coefficient * divisor[units]^i
  63. *
  64. * we do the reduction so both coefficients are just under 32 bits so
  65. * that multiplying them together won't overflow 64 bits and we keep
  66. * as much precision as possible in the numbers.
  67. *
  68. * Note: it's safe to throw away the remainders here because all the
  69. * precision is in the coefficients.
  70. */
  71. while (blk_size >> 32) {
  72. do_div(blk_size, divisor[units]);
  73. i++;
  74. }
  75. while (size >> 32) {
  76. do_div(size, divisor[units]);
  77. i++;
  78. }
  79. /* now perform the actual multiplication keeping i as the sum of the
  80. * two logarithms */
  81. size *= blk_size;
  82. /* and logarithmically reduce it until it's just under the divisor */
  83. while (size >= divisor[units]) {
  84. remainder = do_div(size, divisor[units]);
  85. i++;
  86. }
  87. /* work out in j how many digits of precision we need from the
  88. * remainder */
  89. sf_cap = size;
  90. for (j = 0; sf_cap*10 < 1000; j++)
  91. sf_cap *= 10;
  92. if (units == STRING_UNITS_2) {
  93. /* express the remainder as a decimal. It's currently the
  94. * numerator of a fraction whose denominator is
  95. * divisor[units], which is 1 << 10 for STRING_UNITS_2 */
  96. remainder *= 1000;
  97. remainder >>= 10;
  98. }
  99. /* add a 5 to the digit below what will be printed to ensure
  100. * an arithmetical round up and carry it through to size */
  101. remainder += rounding[j];
  102. if (remainder >= 1000) {
  103. remainder -= 1000;
  104. size += 1;
  105. }
  106. if (j) {
  107. snprintf(tmp, sizeof(tmp), ".%03u", remainder);
  108. tmp[j+1] = '\0';
  109. }
  110. out:
  111. if (i >= ARRAY_SIZE(units_2))
  112. unit = "UNK";
  113. else
  114. unit = units_str[units][i];
  115. snprintf(buf, len, "%u%s %s", (u32)size,
  116. tmp, unit);
  117. }
  118. EXPORT_SYMBOL(string_get_size);
  119. static bool unescape_space(char **src, char **dst)
  120. {
  121. char *p = *dst, *q = *src;
  122. switch (*q) {
  123. case 'n':
  124. *p = '\n';
  125. break;
  126. case 'r':
  127. *p = '\r';
  128. break;
  129. case 't':
  130. *p = '\t';
  131. break;
  132. case 'v':
  133. *p = '\v';
  134. break;
  135. case 'f':
  136. *p = '\f';
  137. break;
  138. default:
  139. return false;
  140. }
  141. *dst += 1;
  142. *src += 1;
  143. return true;
  144. }
  145. static bool unescape_octal(char **src, char **dst)
  146. {
  147. char *p = *dst, *q = *src;
  148. u8 num;
  149. if (isodigit(*q) == 0)
  150. return false;
  151. num = (*q++) & 7;
  152. while (num < 32 && isodigit(*q) && (q - *src < 3)) {
  153. num <<= 3;
  154. num += (*q++) & 7;
  155. }
  156. *p = num;
  157. *dst += 1;
  158. *src = q;
  159. return true;
  160. }
  161. static bool unescape_hex(char **src, char **dst)
  162. {
  163. char *p = *dst, *q = *src;
  164. int digit;
  165. u8 num;
  166. if (*q++ != 'x')
  167. return false;
  168. num = digit = hex_to_bin(*q++);
  169. if (digit < 0)
  170. return false;
  171. digit = hex_to_bin(*q);
  172. if (digit >= 0) {
  173. q++;
  174. num = (num << 4) | digit;
  175. }
  176. *p = num;
  177. *dst += 1;
  178. *src = q;
  179. return true;
  180. }
  181. static bool unescape_special(char **src, char **dst)
  182. {
  183. char *p = *dst, *q = *src;
  184. switch (*q) {
  185. case '\"':
  186. *p = '\"';
  187. break;
  188. case '\\':
  189. *p = '\\';
  190. break;
  191. case 'a':
  192. *p = '\a';
  193. break;
  194. case 'e':
  195. *p = '\e';
  196. break;
  197. default:
  198. return false;
  199. }
  200. *dst += 1;
  201. *src += 1;
  202. return true;
  203. }
  204. /**
  205. * string_unescape - unquote characters in the given string
  206. * @src: source buffer (escaped)
  207. * @dst: destination buffer (unescaped)
  208. * @size: size of the destination buffer (0 to unlimit)
  209. * @flags: combination of the flags.
  210. *
  211. * Description:
  212. * The function unquotes characters in the given string.
  213. *
  214. * Because the size of the output will be the same as or less than the size of
  215. * the input, the transformation may be performed in place.
  216. *
  217. * Caller must provide valid source and destination pointers. Be aware that
  218. * destination buffer will always be NULL-terminated. Source string must be
  219. * NULL-terminated as well. The supported flags are::
  220. *
  221. * UNESCAPE_SPACE:
  222. * '\f' - form feed
  223. * '\n' - new line
  224. * '\r' - carriage return
  225. * '\t' - horizontal tab
  226. * '\v' - vertical tab
  227. * UNESCAPE_OCTAL:
  228. * '\NNN' - byte with octal value NNN (1 to 3 digits)
  229. * UNESCAPE_HEX:
  230. * '\xHH' - byte with hexadecimal value HH (1 to 2 digits)
  231. * UNESCAPE_SPECIAL:
  232. * '\"' - double quote
  233. * '\\' - backslash
  234. * '\a' - alert (BEL)
  235. * '\e' - escape
  236. * UNESCAPE_ANY:
  237. * all previous together
  238. *
  239. * Return:
  240. * The amount of the characters processed to the destination buffer excluding
  241. * trailing '\0' is returned.
  242. */
  243. int string_unescape(char *src, char *dst, size_t size, unsigned int flags)
  244. {
  245. char *out = dst;
  246. while (*src && --size) {
  247. if (src[0] == '\\' && src[1] != '\0' && size > 1) {
  248. src++;
  249. size--;
  250. if (flags & UNESCAPE_SPACE &&
  251. unescape_space(&src, &out))
  252. continue;
  253. if (flags & UNESCAPE_OCTAL &&
  254. unescape_octal(&src, &out))
  255. continue;
  256. if (flags & UNESCAPE_HEX &&
  257. unescape_hex(&src, &out))
  258. continue;
  259. if (flags & UNESCAPE_SPECIAL &&
  260. unescape_special(&src, &out))
  261. continue;
  262. *out++ = '\\';
  263. }
  264. *out++ = *src++;
  265. }
  266. *out = '\0';
  267. return out - dst;
  268. }
  269. EXPORT_SYMBOL(string_unescape);
  270. static bool escape_passthrough(unsigned char c, char **dst, char *end)
  271. {
  272. char *out = *dst;
  273. if (out < end)
  274. *out = c;
  275. *dst = out + 1;
  276. return true;
  277. }
  278. static bool escape_space(unsigned char c, char **dst, char *end)
  279. {
  280. char *out = *dst;
  281. unsigned char to;
  282. switch (c) {
  283. case '\n':
  284. to = 'n';
  285. break;
  286. case '\r':
  287. to = 'r';
  288. break;
  289. case '\t':
  290. to = 't';
  291. break;
  292. case '\v':
  293. to = 'v';
  294. break;
  295. case '\f':
  296. to = 'f';
  297. break;
  298. default:
  299. return false;
  300. }
  301. if (out < end)
  302. *out = '\\';
  303. ++out;
  304. if (out < end)
  305. *out = to;
  306. ++out;
  307. *dst = out;
  308. return true;
  309. }
  310. static bool escape_special(unsigned char c, char **dst, char *end)
  311. {
  312. char *out = *dst;
  313. unsigned char to;
  314. switch (c) {
  315. case '\\':
  316. to = '\\';
  317. break;
  318. case '\a':
  319. to = 'a';
  320. break;
  321. case '\e':
  322. to = 'e';
  323. break;
  324. default:
  325. return false;
  326. }
  327. if (out < end)
  328. *out = '\\';
  329. ++out;
  330. if (out < end)
  331. *out = to;
  332. ++out;
  333. *dst = out;
  334. return true;
  335. }
  336. static bool escape_null(unsigned char c, char **dst, char *end)
  337. {
  338. char *out = *dst;
  339. if (c)
  340. return false;
  341. if (out < end)
  342. *out = '\\';
  343. ++out;
  344. if (out < end)
  345. *out = '0';
  346. ++out;
  347. *dst = out;
  348. return true;
  349. }
  350. static bool escape_octal(unsigned char c, char **dst, char *end)
  351. {
  352. char *out = *dst;
  353. if (out < end)
  354. *out = '\\';
  355. ++out;
  356. if (out < end)
  357. *out = ((c >> 6) & 0x07) + '0';
  358. ++out;
  359. if (out < end)
  360. *out = ((c >> 3) & 0x07) + '0';
  361. ++out;
  362. if (out < end)
  363. *out = ((c >> 0) & 0x07) + '0';
  364. ++out;
  365. *dst = out;
  366. return true;
  367. }
  368. static bool escape_hex(unsigned char c, char **dst, char *end)
  369. {
  370. char *out = *dst;
  371. if (out < end)
  372. *out = '\\';
  373. ++out;
  374. if (out < end)
  375. *out = 'x';
  376. ++out;
  377. if (out < end)
  378. *out = hex_asc_hi(c);
  379. ++out;
  380. if (out < end)
  381. *out = hex_asc_lo(c);
  382. ++out;
  383. *dst = out;
  384. return true;
  385. }
  386. /**
  387. * string_escape_mem - quote characters in the given memory buffer
  388. * @src: source buffer (unescaped)
  389. * @isz: source buffer size
  390. * @dst: destination buffer (escaped)
  391. * @osz: destination buffer size
  392. * @flags: combination of the flags
  393. * @only: NULL-terminated string containing characters used to limit
  394. * the selected escape class. If characters are included in @only
  395. * that would not normally be escaped by the classes selected
  396. * in @flags, they will be copied to @dst unescaped.
  397. *
  398. * Description:
  399. * The process of escaping byte buffer includes several parts. They are applied
  400. * in the following sequence.
  401. *
  402. * 1. The character is matched to the printable class, if asked, and in
  403. * case of match it passes through to the output.
  404. * 2. The character is not matched to the one from @only string and thus
  405. * must go as-is to the output.
  406. * 3. The character is checked if it falls into the class given by @flags.
  407. * %ESCAPE_OCTAL and %ESCAPE_HEX are going last since they cover any
  408. * character. Note that they actually can't go together, otherwise
  409. * %ESCAPE_HEX will be ignored.
  410. *
  411. * Caller must provide valid source and destination pointers. Be aware that
  412. * destination buffer will not be NULL-terminated, thus caller have to append
  413. * it if needs. The supported flags are::
  414. *
  415. * %ESCAPE_SPACE: (special white space, not space itself)
  416. * '\f' - form feed
  417. * '\n' - new line
  418. * '\r' - carriage return
  419. * '\t' - horizontal tab
  420. * '\v' - vertical tab
  421. * %ESCAPE_SPECIAL:
  422. * '\\' - backslash
  423. * '\a' - alert (BEL)
  424. * '\e' - escape
  425. * %ESCAPE_NULL:
  426. * '\0' - null
  427. * %ESCAPE_OCTAL:
  428. * '\NNN' - byte with octal value NNN (3 digits)
  429. * %ESCAPE_ANY:
  430. * all previous together
  431. * %ESCAPE_NP:
  432. * escape only non-printable characters (checked by isprint)
  433. * %ESCAPE_ANY_NP:
  434. * all previous together
  435. * %ESCAPE_HEX:
  436. * '\xHH' - byte with hexadecimal value HH (2 digits)
  437. *
  438. * Return:
  439. * The total size of the escaped output that would be generated for
  440. * the given input and flags. To check whether the output was
  441. * truncated, compare the return value to osz. There is room left in
  442. * dst for a '\0' terminator if and only if ret < osz.
  443. */
  444. int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
  445. unsigned int flags, const char *only)
  446. {
  447. char *p = dst;
  448. char *end = p + osz;
  449. bool is_dict = only && *only;
  450. while (isz--) {
  451. unsigned char c = *src++;
  452. /*
  453. * Apply rules in the following sequence:
  454. * - the character is printable, when @flags has
  455. * %ESCAPE_NP bit set
  456. * - the @only string is supplied and does not contain a
  457. * character under question
  458. * - the character doesn't fall into a class of symbols
  459. * defined by given @flags
  460. * In these cases we just pass through a character to the
  461. * output buffer.
  462. */
  463. if ((flags & ESCAPE_NP && isprint(c)) ||
  464. (is_dict && !strchr(only, c))) {
  465. /* do nothing */
  466. } else {
  467. if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
  468. continue;
  469. if (flags & ESCAPE_SPECIAL && escape_special(c, &p, end))
  470. continue;
  471. if (flags & ESCAPE_NULL && escape_null(c, &p, end))
  472. continue;
  473. /* ESCAPE_OCTAL and ESCAPE_HEX always go last */
  474. if (flags & ESCAPE_OCTAL && escape_octal(c, &p, end))
  475. continue;
  476. if (flags & ESCAPE_HEX && escape_hex(c, &p, end))
  477. continue;
  478. }
  479. escape_passthrough(c, &p, end);
  480. }
  481. return p - dst;
  482. }
  483. EXPORT_SYMBOL(string_escape_mem);
  484. int string_escape_mem_ascii(const char *src, size_t isz, char *dst,
  485. size_t osz)
  486. {
  487. char *p = dst;
  488. char *end = p + osz;
  489. while (isz--) {
  490. unsigned char c = *src++;
  491. if (!isprint(c) || !isascii(c) || c == '"' || c == '\\')
  492. escape_hex(c, &p, end);
  493. else
  494. escape_passthrough(c, &p, end);
  495. }
  496. return p - dst;
  497. }
  498. EXPORT_SYMBOL(string_escape_mem_ascii);
  499. /*
  500. * Return an allocated string that has been escaped of special characters
  501. * and double quotes, making it safe to log in quotes.
  502. */
  503. char *kstrdup_quotable(const char *src, gfp_t gfp)
  504. {
  505. size_t slen, dlen;
  506. char *dst;
  507. const int flags = ESCAPE_HEX;
  508. const char esc[] = "\f\n\r\t\v\a\e\\\"";
  509. if (!src)
  510. return NULL;
  511. slen = strlen(src);
  512. dlen = string_escape_mem(src, slen, NULL, 0, flags, esc);
  513. dst = kmalloc(dlen + 1, gfp);
  514. if (!dst)
  515. return NULL;
  516. WARN_ON(string_escape_mem(src, slen, dst, dlen, flags, esc) != dlen);
  517. dst[dlen] = '\0';
  518. return dst;
  519. }
  520. EXPORT_SYMBOL_GPL(kstrdup_quotable);
  521. /*
  522. * Returns allocated NULL-terminated string containing process
  523. * command line, with inter-argument NULLs replaced with spaces,
  524. * and other special characters escaped.
  525. */
  526. char *kstrdup_quotable_cmdline(struct task_struct *task, gfp_t gfp)
  527. {
  528. char *buffer, *quoted;
  529. int i, res;
  530. buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
  531. if (!buffer)
  532. return NULL;
  533. res = get_cmdline(task, buffer, PAGE_SIZE - 1);
  534. buffer[res] = '\0';
  535. /* Collapse trailing NULLs, leave res pointing to last non-NULL. */
  536. while (--res >= 0 && buffer[res] == '\0')
  537. ;
  538. /* Replace inter-argument NULLs. */
  539. for (i = 0; i <= res; i++)
  540. if (buffer[i] == '\0')
  541. buffer[i] = ' ';
  542. /* Make sure result is printable. */
  543. quoted = kstrdup_quotable(buffer, gfp);
  544. kfree(buffer);
  545. return quoted;
  546. }
  547. EXPORT_SYMBOL_GPL(kstrdup_quotable_cmdline);
  548. /*
  549. * Returns allocated NULL-terminated string containing pathname,
  550. * with special characters escaped, able to be safely logged. If
  551. * there is an error, the leading character will be "<".
  552. */
  553. char *kstrdup_quotable_file(struct file *file, gfp_t gfp)
  554. {
  555. char *temp, *pathname;
  556. if (!file)
  557. return kstrdup("<unknown>", gfp);
  558. /* We add 11 spaces for ' (deleted)' to be appended */
  559. temp = kmalloc(PATH_MAX + 11, GFP_KERNEL);
  560. if (!temp)
  561. return kstrdup("<no_memory>", gfp);
  562. pathname = file_path(file, temp, PATH_MAX + 11);
  563. if (IS_ERR(pathname))
  564. pathname = kstrdup("<too_long>", gfp);
  565. else
  566. pathname = kstrdup_quotable(pathname, gfp);
  567. kfree(temp);
  568. return pathname;
  569. }
  570. EXPORT_SYMBOL_GPL(kstrdup_quotable_file);
  571. /**
  572. * kfree_strarray - free a number of dynamically allocated strings contained
  573. * in an array and the array itself
  574. *
  575. * @array: Dynamically allocated array of strings to free.
  576. * @n: Number of strings (starting from the beginning of the array) to free.
  577. *
  578. * Passing a non-NULL @array and @n == 0 as well as NULL @array are valid
  579. * use-cases. If @array is NULL, the function does nothing.
  580. */
  581. void kfree_strarray(char **array, size_t n)
  582. {
  583. unsigned int i;
  584. if (!array)
  585. return;
  586. for (i = 0; i < n; i++)
  587. kfree(array[i]);
  588. kfree(array);
  589. }
  590. EXPORT_SYMBOL_GPL(kfree_strarray);