util.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. /*
  2. *
  3. * Embedded Linux library
  4. *
  5. * Copyright (C) 2011-2014 Intel Corporation. All rights reserved.
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. */
  22. #ifdef HAVE_CONFIG_H
  23. #include <config.h>
  24. #endif
  25. #define _GNU_SOURCE
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <limits.h>
  29. #include "utf8.h"
  30. #include "util.h"
  31. #include "useful.h"
  32. #include "private.h"
  33. /**
  34. * SECTION:util
  35. * @short_description: Utility functions
  36. *
  37. * Utility functions
  38. */
  39. #define STRLOC __FILE__ ":" L_STRINGIFY(__LINE__)
  40. /**
  41. * l_malloc:
  42. * @size: memory size to allocate
  43. *
  44. * If for any reason the memory allocation fails, then execution will be
  45. * halted via abort().
  46. *
  47. * In case @size is 0 then #NULL will be returned.
  48. *
  49. * Returns: pointer to allocated memory
  50. **/
  51. LIB_EXPORT void *l_malloc(size_t size)
  52. {
  53. if (likely(size)) {
  54. void *ptr;
  55. ptr = malloc(size);
  56. if (ptr)
  57. return ptr;
  58. fprintf(stderr, "%s:%s(): failed to allocate %zd bytes\n",
  59. STRLOC, __func__, size);
  60. abort();
  61. }
  62. return NULL;
  63. }
  64. /**
  65. * l_realloc:
  66. * @mem: previously allocated memory, or NULL
  67. * @size: memory size to allocate
  68. *
  69. * If for any reason the memory allocation fails, then execution will be
  70. * halted via abort().
  71. *
  72. * In case @mem is NULL, this function acts like l_malloc.
  73. * In case @size is 0 then #NULL will be returned.
  74. *
  75. * Returns: pointer to allocated memory
  76. **/
  77. LIB_EXPORT void *l_realloc(void *mem, size_t size)
  78. {
  79. if (likely(size)) {
  80. void *ptr;
  81. ptr = realloc(mem, size);
  82. if (ptr)
  83. return ptr;
  84. fprintf(stderr, "%s:%s(): failed to re-allocate %zd bytes\n",
  85. STRLOC, __func__, size);
  86. abort();
  87. } else
  88. l_free(mem);
  89. return NULL;
  90. }
  91. /**
  92. * l_memdup:
  93. * @mem: pointer to memory you want to duplicate
  94. * @size: memory size
  95. *
  96. * If for any reason the memory allocation fails, then execution will be
  97. * halted via abort().
  98. *
  99. * In case @size is 0 then #NULL will be returned.
  100. *
  101. * Returns: pointer to duplicated memory buffer
  102. **/
  103. LIB_EXPORT void *l_memdup(const void *mem, size_t size)
  104. {
  105. void *ptr;
  106. ptr = l_malloc(size);
  107. memcpy(ptr, mem, size);
  108. return ptr;
  109. }
  110. /**
  111. * l_free:
  112. * @ptr: memory pointer
  113. *
  114. * Free the allocated memory area.
  115. **/
  116. LIB_EXPORT void l_free(void *ptr)
  117. {
  118. free(ptr);
  119. }
  120. /**
  121. * l_strdup:
  122. * @str: string pointer
  123. *
  124. * Allocates and duplicates sring
  125. *
  126. * Returns: a newly allocated string
  127. **/
  128. LIB_EXPORT char *l_strdup(const char *str)
  129. {
  130. if (likely(str)) {
  131. char *tmp;
  132. tmp = strdup(str);
  133. if (tmp)
  134. return tmp;
  135. fprintf(stderr, "%s:%s(): failed to allocate string\n",
  136. STRLOC, __func__);
  137. abort();
  138. }
  139. return NULL;
  140. }
  141. /**
  142. * l_strndup:
  143. * @str: string pointer
  144. * @max: Maximum number of characters to copy
  145. *
  146. * Allocates and duplicates sring. If the string is longer than @max
  147. * characters, only @max are copied and a null terminating character
  148. * is added.
  149. *
  150. * Returns: a newly allocated string
  151. **/
  152. LIB_EXPORT char *l_strndup(const char *str, size_t max)
  153. {
  154. if (likely(str)) {
  155. char *tmp;
  156. tmp = strndup(str, max);
  157. if (tmp)
  158. return tmp;
  159. fprintf(stderr, "%s:%s(): failed to allocate string\n",
  160. STRLOC, __func__);
  161. abort();
  162. }
  163. return NULL;
  164. }
  165. /**
  166. * l_strdup_printf:
  167. * @format: string format
  168. * @...: parameters to insert into format string
  169. *
  170. * Returns: a newly allocated string
  171. **/
  172. LIB_EXPORT char *l_strdup_printf(const char *format, ...)
  173. {
  174. va_list args;
  175. char *str;
  176. int len;
  177. va_start(args, format);
  178. len = vasprintf(&str, format, args);
  179. va_end(args);
  180. if (len < 0) {
  181. fprintf(stderr, "%s:%s(): failed to allocate string\n",
  182. STRLOC, __func__);
  183. abort();
  184. return NULL;
  185. }
  186. return str;
  187. }
  188. /**
  189. * l_strdup_vprintf:
  190. * @format: string format
  191. * @args: parameters to insert into format string
  192. *
  193. * Returns: a newly allocated string
  194. **/
  195. LIB_EXPORT char *l_strdup_vprintf(const char *format, va_list args)
  196. {
  197. char *str;
  198. int len;
  199. len = vasprintf(&str, format, args);
  200. if (len < 0) {
  201. fprintf(stderr, "%s:%s(): failed to allocate string\n",
  202. STRLOC, __func__);
  203. abort();
  204. return NULL;
  205. }
  206. return str;
  207. }
  208. /**
  209. * l_strlcpy:
  210. * @dst: Destination buffer for string
  211. * @src: Source buffer containing null-terminated string to copy
  212. * @len: Maximum destination buffer space to use
  213. *
  214. * Copies a string from the @src buffer to the @dst buffer, using no
  215. * more than @len bytes in @dst. @dst is guaranteed to be
  216. * null-terminated. The caller can determine if the copy was truncated by
  217. * checking if the return value is greater than or equal to @len.
  218. *
  219. * NOTE: Passing in a NULL string results in a no-op
  220. *
  221. * Returns: The length of the @src string, not including the null
  222. * terminator.
  223. */
  224. LIB_EXPORT size_t l_strlcpy(char *dst, const char *src, size_t len)
  225. {
  226. size_t src_len = src ? strlen(src) : 0;
  227. if (!src)
  228. goto done;
  229. if (len) {
  230. if (src_len < len) {
  231. len = src_len + 1;
  232. } else {
  233. len -= 1;
  234. dst[len] = '\0';
  235. }
  236. memcpy(dst, src, len);
  237. }
  238. done:
  239. return src_len;
  240. }
  241. /**
  242. * l_str_has_prefix:
  243. * @str: A string to be examined
  244. * @delim: Prefix string
  245. *
  246. * Determines if the string given by @str is prefixed by string given by
  247. * @prefix.
  248. *
  249. * Returns: True if @str was prefixed by @prefix. False otherwise.
  250. */
  251. LIB_EXPORT bool l_str_has_prefix(const char *str, const char *prefix)
  252. {
  253. size_t str_len;
  254. size_t prefix_len;
  255. if (unlikely(!str))
  256. return false;
  257. if (unlikely(!prefix))
  258. return false;
  259. str_len = strlen(str);
  260. prefix_len = strlen(prefix);
  261. if (str_len < prefix_len)
  262. return false;
  263. return !strncmp(str, prefix, prefix_len);
  264. }
  265. /**
  266. * l_str_has_suffix:
  267. * @str: A string to be examined
  268. * @suffix: Suffix string
  269. *
  270. * Determines if the string given by @str ends with the specified @suffix.
  271. *
  272. * Returns: True if @str ends with the specified @suffix. False otherwise.
  273. */
  274. LIB_EXPORT bool l_str_has_suffix(const char *str, const char *suffix)
  275. {
  276. size_t str_len;
  277. size_t suffix_len;
  278. size_t len_diff;
  279. if (unlikely(!str))
  280. return false;
  281. if (unlikely(!suffix))
  282. return false;
  283. str_len = strlen(str);
  284. suffix_len = strlen(suffix);
  285. if (str_len < suffix_len)
  286. return false;
  287. len_diff = str_len - suffix_len;
  288. return !strcmp(&str[len_diff], suffix);
  289. }
  290. /**
  291. * l_streq0:
  292. * @a: First operand
  293. * @b: Second operand
  294. *
  295. * Returns: True if @a and @b are both NULL or both non-NULL and identical
  296. * according to strcmp. False otherwise.
  297. */
  298. LIB_EXPORT bool l_streq0(const char *a, const char *b)
  299. {
  300. return a == b || (a && b && !strcmp(a, b));
  301. }
  302. static char *hexstring_common(const unsigned char *buf, size_t len,
  303. const char hexdigits[static 16])
  304. {
  305. char *str;
  306. size_t i;
  307. if (unlikely(!buf) || unlikely(!len))
  308. return NULL;
  309. str = l_malloc(len * 2 + 1);
  310. for (i = 0; i < len; i++) {
  311. str[(i * 2) + 0] = hexdigits[buf[i] >> 4];
  312. str[(i * 2) + 1] = hexdigits[buf[i] & 0xf];
  313. }
  314. str[len * 2] = '\0';
  315. return str;
  316. }
  317. /**
  318. * l_util_hexstring:
  319. * @buf: buffer pointer
  320. * @len: length of buffer
  321. *
  322. * Returns: a newly allocated hex string. Note that the string will contain
  323. * lower case hex digits a-f. If you require upper case hex digits, use
  324. * @l_util_hexstring_upper
  325. **/
  326. LIB_EXPORT char *l_util_hexstring(const void *buf, size_t len)
  327. {
  328. static const char hexdigits[] = "0123456789abcdef";
  329. return hexstring_common(buf, len, hexdigits);
  330. }
  331. /**
  332. * l_util_hexstring_upper:
  333. * @buf: buffer pointer
  334. * @len: length of buffer
  335. *
  336. * Returns: a newly allocated hex string. Note that the string will contain
  337. * upper case hex digits a-f. If you require lower case hex digits, use
  338. * @l_util_hexstring
  339. **/
  340. LIB_EXPORT char *l_util_hexstring_upper(const void *buf, size_t len)
  341. {
  342. static const char hexdigits[] = "0123456789ABCDEF";
  343. return hexstring_common(buf, len, hexdigits);
  344. }
  345. /**
  346. * l_util_from_hexstring:
  347. * @str: Null-terminated string containing the hex-encoded bytes
  348. * @out_len: Number of bytes decoded
  349. *
  350. * Returns: a newly allocated byte array. Empty strings are treated as
  351. * an error condition.
  352. **/
  353. LIB_EXPORT unsigned char *l_util_from_hexstring(const char *str,
  354. size_t *out_len)
  355. {
  356. size_t i, j;
  357. size_t len;
  358. char c;
  359. unsigned char *buf;
  360. if (unlikely(!str))
  361. return NULL;
  362. for (i = 0; str[i]; i++) {
  363. c = str[i];
  364. if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  365. (c >= 'a' && c <= 'f'))
  366. continue;
  367. return NULL;
  368. }
  369. if (!i)
  370. return NULL;
  371. if ((i % 2) != 0)
  372. return NULL;
  373. len = i;
  374. buf = l_malloc(i >> 1);
  375. for (i = 0, j = 0; i < len; i++, j++) {
  376. c = str[i];
  377. if (c >= '0' && c <= '9')
  378. buf[j] = c - '0';
  379. else if (c >= 'A' && c <= 'F')
  380. buf[j] = 10 + c - 'A';
  381. else if (c >= 'a' && c <= 'f')
  382. buf[j] = 10 + c - 'a';
  383. i += 1;
  384. c = str[i];
  385. if (c >= '0' && c <= '9')
  386. buf[j] = buf[j] * 16 + c - '0';
  387. else if (c >= 'A' && c <= 'F')
  388. buf[j] = buf[j] * 16 + 10 + c - 'A';
  389. else if (c >= 'a' && c <= 'f')
  390. buf[j] = buf[j] * 16 + 10 + c - 'a';
  391. }
  392. if (out_len)
  393. *out_len = j;
  394. return buf;
  395. }
  396. static void hexdump(const char dir, const unsigned char *buf, size_t len,
  397. l_util_hexdump_func_t function, void *user_data)
  398. {
  399. static const char hexdigits[] = "0123456789abcdef";
  400. char str[68];
  401. size_t i;
  402. if (unlikely(!len))
  403. return;
  404. str[0] = dir;
  405. for (i = 0; i < len; i++) {
  406. str[((i % 16) * 3) + 1] = ' ';
  407. str[((i % 16) * 3) + 2] = hexdigits[buf[i] >> 4];
  408. str[((i % 16) * 3) + 3] = hexdigits[buf[i] & 0xf];
  409. str[(i % 16) + 51] = l_ascii_isprint(buf[i]) ? buf[i] : '.';
  410. if ((i + 1) % 16 == 0) {
  411. str[49] = ' ';
  412. str[50] = ' ';
  413. str[67] = '\0';
  414. function(str, user_data);
  415. str[0] = ' ';
  416. }
  417. }
  418. if (i % 16 > 0) {
  419. size_t j;
  420. for (j = (i % 16); j < 16; j++) {
  421. str[(j * 3) + 1] = ' ';
  422. str[(j * 3) + 2] = ' ';
  423. str[(j * 3) + 3] = ' ';
  424. str[j + 51] = ' ';
  425. }
  426. str[49] = ' ';
  427. str[50] = ' ';
  428. str[67] = '\0';
  429. function(str, user_data);
  430. }
  431. }
  432. LIB_EXPORT void l_util_hexdump(bool in, const void *buf, size_t len,
  433. l_util_hexdump_func_t function, void *user_data)
  434. {
  435. if (likely(!function))
  436. return;
  437. hexdump(in ? '<' : '>', buf, len, function, user_data);
  438. }
  439. LIB_EXPORT void l_util_hexdump_two(bool in, const void *buf1, size_t len1,
  440. const void *buf2, size_t len2,
  441. l_util_hexdump_func_t function, void *user_data)
  442. {
  443. if (likely(!function))
  444. return;
  445. hexdump(in ? '<' : '>', buf1, len1, function, user_data);
  446. hexdump(' ', buf2, len2, function, user_data);
  447. }
  448. LIB_EXPORT void l_util_hexdumpv(bool in, const struct iovec *iov,
  449. size_t n_iov,
  450. l_util_hexdump_func_t function,
  451. void *user_data)
  452. {
  453. static const char hexdigits[] = "0123456789abcdef";
  454. char str[68];
  455. size_t i;
  456. size_t len;
  457. size_t c;
  458. const uint8_t *buf;
  459. if (likely(!function))
  460. return;
  461. if (unlikely(!iov || !n_iov))
  462. return;
  463. str[0] = in ? '<' : '>';
  464. for (i = 0, len = 0; i < n_iov; i++)
  465. len += iov[i].iov_len;
  466. c = 0;
  467. buf = iov[0].iov_base;
  468. for (i = 0; i < len; i++, c++) {
  469. if (c == iov[0].iov_len) {
  470. c = 0;
  471. iov += 1;
  472. buf = iov[0].iov_base;
  473. }
  474. str[((i % 16) * 3) + 1] = ' ';
  475. str[((i % 16) * 3) + 2] = hexdigits[buf[c] >> 4];
  476. str[((i % 16) * 3) + 3] = hexdigits[buf[c] & 0xf];
  477. str[(i % 16) + 51] = l_ascii_isprint(buf[c]) ? buf[c] : '.';
  478. if ((i + 1) % 16 == 0) {
  479. str[49] = ' ';
  480. str[50] = ' ';
  481. str[67] = '\0';
  482. function(str, user_data);
  483. str[0] = ' ';
  484. }
  485. }
  486. if (i % 16 > 0) {
  487. size_t j;
  488. for (j = (i % 16); j < 16; j++) {
  489. str[(j * 3) + 1] = ' ';
  490. str[(j * 3) + 2] = ' ';
  491. str[(j * 3) + 3] = ' ';
  492. str[j + 51] = ' ';
  493. }
  494. str[49] = ' ';
  495. str[50] = ' ';
  496. str[67] = '\0';
  497. function(str, user_data);
  498. }
  499. }
  500. LIB_EXPORT void l_util_debug(l_util_hexdump_func_t function, void *user_data,
  501. const char *format, ...)
  502. {
  503. va_list args;
  504. char *str;
  505. int len;
  506. if (likely(!function))
  507. return;
  508. if (unlikely(!format))
  509. return;
  510. va_start(args, format);
  511. len = vasprintf(&str, format, args);
  512. va_end(args);
  513. if (unlikely(len < 0))
  514. return;
  515. function(str, user_data);
  516. free(str);
  517. }
  518. /**
  519. * l_util_get_debugfs_path:
  520. *
  521. * Returns: a pointer to mount point of debugfs
  522. **/
  523. LIB_EXPORT const char *l_util_get_debugfs_path(void)
  524. {
  525. static char path[PATH_MAX + 1];
  526. static bool found = false;
  527. char type[100];
  528. FILE *fp;
  529. if (found)
  530. return path;
  531. fp = fopen("/proc/mounts", "r");
  532. if (!fp)
  533. return NULL;
  534. while (fscanf(fp, "%*s %" L_STRINGIFY(PATH_MAX) "s %99s %*s %*d %*d\n",
  535. path, type) == 2) {
  536. if (!strcmp(type, "debugfs")) {
  537. found = true;
  538. break;
  539. }
  540. }
  541. fclose(fp);
  542. if (!found)
  543. return NULL;
  544. return path;
  545. }
  546. LIB_EXPORT bool l_memeq(const void *field, size_t size, uint8_t byte)
  547. {
  548. const uint8_t *mem = field;
  549. size_t i;
  550. for (i = 0; i < size; i++)
  551. if (mem[i] != byte)
  552. return false;
  553. return true;
  554. }
  555. __attribute__((noinline)) static int __secure_memeq(const void *field,
  556. size_t size, uint8_t byte)
  557. {
  558. unsigned int diff = 0;
  559. size_t i;
  560. for (i = 0; i < size; i++) {
  561. diff |= ((uint8_t *) field)[i] ^ byte;
  562. DO_NOT_OPTIMIZE(diff);
  563. }
  564. return diff;
  565. }
  566. LIB_EXPORT bool l_secure_memeq(const void *field, size_t size, uint8_t byte)
  567. {
  568. return __secure_memeq(field, size, byte) == 0 ? true : false;
  569. }